1 //===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the main API hooks in the Clang-C Source Indexing 10 // library. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CIndexDiagnostic.h" 15 #include "CIndexer.h" 16 #include "CLog.h" 17 #include "CXCursor.h" 18 #include "CXSourceLocation.h" 19 #include "CXString.h" 20 #include "CXTranslationUnit.h" 21 #include "CXType.h" 22 #include "CursorVisitor.h" 23 #include "clang-c/FatalErrorHandler.h" 24 #include "clang/AST/Attr.h" 25 #include "clang/AST/DeclObjCCommon.h" 26 #include "clang/AST/Mangle.h" 27 #include "clang/AST/OpenMPClause.h" 28 #include "clang/AST/StmtVisitor.h" 29 #include "clang/Basic/Diagnostic.h" 30 #include "clang/Basic/DiagnosticCategories.h" 31 #include "clang/Basic/DiagnosticIDs.h" 32 #include "clang/Basic/Stack.h" 33 #include "clang/Basic/TargetInfo.h" 34 #include "clang/Basic/Version.h" 35 #include "clang/Frontend/ASTUnit.h" 36 #include "clang/Frontend/CompilerInstance.h" 37 #include "clang/Index/CommentToXML.h" 38 #include "clang/Lex/HeaderSearch.h" 39 #include "clang/Lex/Lexer.h" 40 #include "clang/Lex/PreprocessingRecord.h" 41 #include "clang/Lex/Preprocessor.h" 42 #include "llvm/ADT/Optional.h" 43 #include "llvm/ADT/STLExtras.h" 44 #include "llvm/ADT/StringSwitch.h" 45 #include "llvm/Config/llvm-config.h" 46 #include "llvm/Support/Compiler.h" 47 #include "llvm/Support/CrashRecoveryContext.h" 48 #include "llvm/Support/Format.h" 49 #include "llvm/Support/ManagedStatic.h" 50 #include "llvm/Support/MemoryBuffer.h" 51 #include "llvm/Support/Program.h" 52 #include "llvm/Support/SaveAndRestore.h" 53 #include "llvm/Support/Signals.h" 54 #include "llvm/Support/TargetSelect.h" 55 #include "llvm/Support/Threading.h" 56 #include "llvm/Support/Timer.h" 57 #include "llvm/Support/raw_ostream.h" 58 #include "llvm/Support/thread.h" 59 #include <mutex> 60 61 #if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__) 62 #define USE_DARWIN_THREADS 63 #endif 64 65 #ifdef USE_DARWIN_THREADS 66 #include <pthread.h> 67 #endif 68 69 using namespace clang; 70 using namespace clang::cxcursor; 71 using namespace clang::cxtu; 72 using namespace clang::cxindex; 73 74 CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx, 75 std::unique_ptr<ASTUnit> AU) { 76 if (!AU) 77 return nullptr; 78 assert(CIdx); 79 CXTranslationUnit D = new CXTranslationUnitImpl(); 80 D->CIdx = CIdx; 81 D->TheASTUnit = AU.release(); 82 D->StringPool = new cxstring::CXStringPool(); 83 D->Diagnostics = nullptr; 84 D->OverridenCursorsPool = createOverridenCXCursorsPool(); 85 D->CommentToXML = nullptr; 86 D->ParsingOptions = 0; 87 D->Arguments = {}; 88 return D; 89 } 90 91 bool cxtu::isASTReadError(ASTUnit *AU) { 92 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(), 93 DEnd = AU->stored_diag_end(); 94 D != DEnd; ++D) { 95 if (D->getLevel() >= DiagnosticsEngine::Error && 96 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) == 97 diag::DiagCat_AST_Deserialization_Issue) 98 return true; 99 } 100 return false; 101 } 102 103 cxtu::CXTUOwner::~CXTUOwner() { 104 if (TU) 105 clang_disposeTranslationUnit(TU); 106 } 107 108 /// Compare two source ranges to determine their relative position in 109 /// the translation unit. 110 static RangeComparisonResult RangeCompare(SourceManager &SM, SourceRange R1, 111 SourceRange R2) { 112 assert(R1.isValid() && "First range is invalid?"); 113 assert(R2.isValid() && "Second range is invalid?"); 114 if (R1.getEnd() != R2.getBegin() && 115 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin())) 116 return RangeBefore; 117 if (R2.getEnd() != R1.getBegin() && 118 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin())) 119 return RangeAfter; 120 return RangeOverlap; 121 } 122 123 /// Determine if a source location falls within, before, or after a 124 /// a given source range. 125 static RangeComparisonResult LocationCompare(SourceManager &SM, 126 SourceLocation L, SourceRange R) { 127 assert(R.isValid() && "First range is invalid?"); 128 assert(L.isValid() && "Second range is invalid?"); 129 if (L == R.getBegin() || L == R.getEnd()) 130 return RangeOverlap; 131 if (SM.isBeforeInTranslationUnit(L, R.getBegin())) 132 return RangeBefore; 133 if (SM.isBeforeInTranslationUnit(R.getEnd(), L)) 134 return RangeAfter; 135 return RangeOverlap; 136 } 137 138 /// Translate a Clang source range into a CIndex source range. 139 /// 140 /// Clang internally represents ranges where the end location points to the 141 /// start of the token at the end. However, for external clients it is more 142 /// useful to have a CXSourceRange be a proper half-open interval. This routine 143 /// does the appropriate translation. 144 CXSourceRange cxloc::translateSourceRange(const SourceManager &SM, 145 const LangOptions &LangOpts, 146 const CharSourceRange &R) { 147 // We want the last character in this location, so we will adjust the 148 // location accordingly. 149 SourceLocation EndLoc = R.getEnd(); 150 bool IsTokenRange = R.isTokenRange(); 151 if (EndLoc.isValid() && EndLoc.isMacroID() && 152 !SM.isMacroArgExpansion(EndLoc)) { 153 CharSourceRange Expansion = SM.getExpansionRange(EndLoc); 154 EndLoc = Expansion.getEnd(); 155 IsTokenRange = Expansion.isTokenRange(); 156 } 157 if (IsTokenRange && EndLoc.isValid()) { 158 unsigned Length = 159 Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc), SM, LangOpts); 160 EndLoc = EndLoc.getLocWithOffset(Length); 161 } 162 163 CXSourceRange Result = { 164 {&SM, &LangOpts}, R.getBegin().getRawEncoding(), EndLoc.getRawEncoding()}; 165 return Result; 166 } 167 168 CharSourceRange cxloc::translateCXRangeToCharRange(CXSourceRange R) { 169 return CharSourceRange::getCharRange( 170 SourceLocation::getFromRawEncoding(R.begin_int_data), 171 SourceLocation::getFromRawEncoding(R.end_int_data)); 172 } 173 174 //===----------------------------------------------------------------------===// 175 // Cursor visitor. 176 //===----------------------------------------------------------------------===// 177 178 static SourceRange getRawCursorExtent(CXCursor C); 179 static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr); 180 181 RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) { 182 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest); 183 } 184 185 /// Visit the given cursor and, if requested by the visitor, 186 /// its children. 187 /// 188 /// \param Cursor the cursor to visit. 189 /// 190 /// \param CheckedRegionOfInterest if true, then the caller already checked 191 /// that this cursor is within the region of interest. 192 /// 193 /// \returns true if the visitation should be aborted, false if it 194 /// should continue. 195 bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) { 196 if (clang_isInvalid(Cursor.kind)) 197 return false; 198 199 if (clang_isDeclaration(Cursor.kind)) { 200 const Decl *D = getCursorDecl(Cursor); 201 if (!D) { 202 assert(0 && "Invalid declaration cursor"); 203 return true; // abort. 204 } 205 206 // Ignore implicit declarations, unless it's an objc method because 207 // currently we should report implicit methods for properties when indexing. 208 if (D->isImplicit() && !isa<ObjCMethodDecl>(D)) 209 return false; 210 } 211 212 // If we have a range of interest, and this cursor doesn't intersect with it, 213 // we're done. 214 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) { 215 SourceRange Range = getRawCursorExtent(Cursor); 216 if (Range.isInvalid() || CompareRegionOfInterest(Range)) 217 return false; 218 } 219 220 switch (Visitor(Cursor, Parent, ClientData)) { 221 case CXChildVisit_Break: 222 return true; 223 224 case CXChildVisit_Continue: 225 return false; 226 227 case CXChildVisit_Recurse: { 228 bool ret = VisitChildren(Cursor); 229 if (PostChildrenVisitor) 230 if (PostChildrenVisitor(Cursor, ClientData)) 231 return true; 232 return ret; 233 } 234 } 235 236 llvm_unreachable("Invalid CXChildVisitResult!"); 237 } 238 239 static bool visitPreprocessedEntitiesInRange(SourceRange R, 240 PreprocessingRecord &PPRec, 241 CursorVisitor &Visitor) { 242 SourceManager &SM = Visitor.getASTUnit()->getSourceManager(); 243 FileID FID; 244 245 if (!Visitor.shouldVisitIncludedEntities()) { 246 // If the begin/end of the range lie in the same FileID, do the optimization 247 // where we skip preprocessed entities that do not come from the same 248 // FileID. 249 FID = SM.getFileID(SM.getFileLoc(R.getBegin())); 250 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd()))) 251 FID = FileID(); 252 } 253 254 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R); 255 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(), 256 PPRec, FID); 257 } 258 259 bool CursorVisitor::visitFileRegion() { 260 if (RegionOfInterest.isInvalid()) 261 return false; 262 263 ASTUnit *Unit = cxtu::getASTUnit(TU); 264 SourceManager &SM = Unit->getSourceManager(); 265 266 std::pair<FileID, unsigned> Begin = SM.getDecomposedLoc( 267 SM.getFileLoc(RegionOfInterest.getBegin())), 268 End = SM.getDecomposedLoc( 269 SM.getFileLoc(RegionOfInterest.getEnd())); 270 271 if (End.first != Begin.first) { 272 // If the end does not reside in the same file, try to recover by 273 // picking the end of the file of begin location. 274 End.first = Begin.first; 275 End.second = SM.getFileIDSize(Begin.first); 276 } 277 278 assert(Begin.first == End.first); 279 if (Begin.second > End.second) 280 return false; 281 282 FileID File = Begin.first; 283 unsigned Offset = Begin.second; 284 unsigned Length = End.second - Begin.second; 285 286 if (!VisitDeclsOnly && !VisitPreprocessorLast) 287 if (visitPreprocessedEntitiesInRegion()) 288 return true; // visitation break. 289 290 if (visitDeclsFromFileRegion(File, Offset, Length)) 291 return true; // visitation break. 292 293 if (!VisitDeclsOnly && VisitPreprocessorLast) 294 return visitPreprocessedEntitiesInRegion(); 295 296 return false; 297 } 298 299 static bool isInLexicalContext(Decl *D, DeclContext *DC) { 300 if (!DC) 301 return false; 302 303 for (DeclContext *DeclDC = D->getLexicalDeclContext(); DeclDC; 304 DeclDC = DeclDC->getLexicalParent()) { 305 if (DeclDC == DC) 306 return true; 307 } 308 return false; 309 } 310 311 bool CursorVisitor::visitDeclsFromFileRegion(FileID File, unsigned Offset, 312 unsigned Length) { 313 ASTUnit *Unit = cxtu::getASTUnit(TU); 314 SourceManager &SM = Unit->getSourceManager(); 315 SourceRange Range = RegionOfInterest; 316 317 SmallVector<Decl *, 16> Decls; 318 Unit->findFileRegionDecls(File, Offset, Length, Decls); 319 320 // If we didn't find any file level decls for the file, try looking at the 321 // file that it was included from. 322 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) { 323 bool Invalid = false; 324 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid); 325 if (Invalid) 326 return false; 327 328 SourceLocation Outer; 329 if (SLEntry.isFile()) 330 Outer = SLEntry.getFile().getIncludeLoc(); 331 else 332 Outer = SLEntry.getExpansion().getExpansionLocStart(); 333 if (Outer.isInvalid()) 334 return false; 335 336 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer); 337 Length = 0; 338 Unit->findFileRegionDecls(File, Offset, Length, Decls); 339 } 340 341 assert(!Decls.empty()); 342 343 bool VisitedAtLeastOnce = false; 344 DeclContext *CurDC = nullptr; 345 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin(); 346 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) { 347 Decl *D = *DIt; 348 if (D->getSourceRange().isInvalid()) 349 continue; 350 351 if (isInLexicalContext(D, CurDC)) 352 continue; 353 354 CurDC = dyn_cast<DeclContext>(D); 355 356 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 357 if (!TD->isFreeStanding()) 358 continue; 359 360 RangeComparisonResult CompRes = 361 RangeCompare(SM, D->getSourceRange(), Range); 362 if (CompRes == RangeBefore) 363 continue; 364 if (CompRes == RangeAfter) 365 break; 366 367 assert(CompRes == RangeOverlap); 368 VisitedAtLeastOnce = true; 369 370 if (isa<ObjCContainerDecl>(D)) { 371 FileDI_current = &DIt; 372 FileDE_current = DE; 373 } else { 374 FileDI_current = nullptr; 375 } 376 377 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true)) 378 return true; // visitation break. 379 } 380 381 if (VisitedAtLeastOnce) 382 return false; 383 384 // No Decls overlapped with the range. Move up the lexical context until there 385 // is a context that contains the range or we reach the translation unit 386 // level. 387 DeclContext *DC = DIt == Decls.begin() 388 ? (*DIt)->getLexicalDeclContext() 389 : (*(DIt - 1))->getLexicalDeclContext(); 390 391 while (DC && !DC->isTranslationUnit()) { 392 Decl *D = cast<Decl>(DC); 393 SourceRange CurDeclRange = D->getSourceRange(); 394 if (CurDeclRange.isInvalid()) 395 break; 396 397 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) { 398 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true)) 399 return true; // visitation break. 400 } 401 402 DC = D->getLexicalDeclContext(); 403 } 404 405 return false; 406 } 407 408 bool CursorVisitor::visitPreprocessedEntitiesInRegion() { 409 if (!AU->getPreprocessor().getPreprocessingRecord()) 410 return false; 411 412 PreprocessingRecord &PPRec = *AU->getPreprocessor().getPreprocessingRecord(); 413 SourceManager &SM = AU->getSourceManager(); 414 415 if (RegionOfInterest.isValid()) { 416 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest); 417 SourceLocation B = MappedRange.getBegin(); 418 SourceLocation E = MappedRange.getEnd(); 419 420 if (AU->isInPreambleFileID(B)) { 421 if (SM.isLoadedSourceLocation(E)) 422 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, 423 *this); 424 425 // Beginning of range lies in the preamble but it also extends beyond 426 // it into the main file. Split the range into 2 parts, one covering 427 // the preamble and another covering the main file. This allows subsequent 428 // calls to visitPreprocessedEntitiesInRange to accept a source range that 429 // lies in the same FileID, allowing it to skip preprocessed entities that 430 // do not come from the same FileID. 431 bool breaked = visitPreprocessedEntitiesInRange( 432 SourceRange(B, AU->getEndOfPreambleFileID()), PPRec, *this); 433 if (breaked) 434 return true; 435 return visitPreprocessedEntitiesInRange( 436 SourceRange(AU->getStartOfMainFileID(), E), PPRec, *this); 437 } 438 439 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this); 440 } 441 442 bool OnlyLocalDecls = !AU->isMainFileAST() && AU->getOnlyLocalDecls(); 443 444 if (OnlyLocalDecls) 445 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(), 446 PPRec); 447 448 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec); 449 } 450 451 template <typename InputIterator> 452 bool CursorVisitor::visitPreprocessedEntities(InputIterator First, 453 InputIterator Last, 454 PreprocessingRecord &PPRec, 455 FileID FID) { 456 for (; First != Last; ++First) { 457 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID)) 458 continue; 459 460 PreprocessedEntity *PPE = *First; 461 if (!PPE) 462 continue; 463 464 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) { 465 if (Visit(MakeMacroExpansionCursor(ME, TU))) 466 return true; 467 468 continue; 469 } 470 471 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) { 472 if (Visit(MakeMacroDefinitionCursor(MD, TU))) 473 return true; 474 475 continue; 476 } 477 478 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) { 479 if (Visit(MakeInclusionDirectiveCursor(ID, TU))) 480 return true; 481 482 continue; 483 } 484 } 485 486 return false; 487 } 488 489 /// Visit the children of the given cursor. 490 /// 491 /// \returns true if the visitation should be aborted, false if it 492 /// should continue. 493 bool CursorVisitor::VisitChildren(CXCursor Cursor) { 494 if (clang_isReference(Cursor.kind) && 495 Cursor.kind != CXCursor_CXXBaseSpecifier) { 496 // By definition, references have no children. 497 return false; 498 } 499 500 // Set the Parent field to Cursor, then back to its old value once we're 501 // done. 502 SetParentRAII SetParent(Parent, StmtParent, Cursor); 503 504 if (clang_isDeclaration(Cursor.kind)) { 505 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor)); 506 if (!D) 507 return false; 508 509 return VisitAttributes(D) || Visit(D); 510 } 511 512 if (clang_isStatement(Cursor.kind)) { 513 if (const Stmt *S = getCursorStmt(Cursor)) 514 return Visit(S); 515 516 return false; 517 } 518 519 if (clang_isExpression(Cursor.kind)) { 520 if (const Expr *E = getCursorExpr(Cursor)) 521 return Visit(E); 522 523 return false; 524 } 525 526 if (clang_isTranslationUnit(Cursor.kind)) { 527 CXTranslationUnit TU = getCursorTU(Cursor); 528 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 529 530 int VisitOrder[2] = {VisitPreprocessorLast, !VisitPreprocessorLast}; 531 for (unsigned I = 0; I != 2; ++I) { 532 if (VisitOrder[I]) { 533 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() && 534 RegionOfInterest.isInvalid()) { 535 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(), 536 TLEnd = CXXUnit->top_level_end(); 537 TL != TLEnd; ++TL) { 538 const Optional<bool> V = handleDeclForVisitation(*TL); 539 if (!V.hasValue()) 540 continue; 541 return V.getValue(); 542 } 543 } else if (VisitDeclContext( 544 CXXUnit->getASTContext().getTranslationUnitDecl())) 545 return true; 546 continue; 547 } 548 549 // Walk the preprocessing record. 550 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) 551 visitPreprocessedEntitiesInRegion(); 552 } 553 554 return false; 555 } 556 557 if (Cursor.kind == CXCursor_CXXBaseSpecifier) { 558 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) { 559 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) { 560 return Visit(BaseTSInfo->getTypeLoc()); 561 } 562 } 563 } 564 565 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) { 566 const IBOutletCollectionAttr *A = 567 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor)); 568 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>()) 569 return Visit(cxcursor::MakeCursorObjCClassRef( 570 ObjT->getInterface(), 571 A->getInterfaceLoc()->getTypeLoc().getBeginLoc(), TU)); 572 } 573 574 // If pointing inside a macro definition, check if the token is an identifier 575 // that was ever defined as a macro. In such a case, create a "pseudo" macro 576 // expansion cursor for that token. 577 SourceLocation BeginLoc = RegionOfInterest.getBegin(); 578 if (Cursor.kind == CXCursor_MacroDefinition && 579 BeginLoc == RegionOfInterest.getEnd()) { 580 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc); 581 const MacroInfo *MI = 582 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU); 583 if (MacroDefinitionRecord *MacroDef = 584 checkForMacroInMacroDefinition(MI, Loc, TU)) 585 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU)); 586 } 587 588 // Nothing to visit at the moment. 589 return false; 590 } 591 592 bool CursorVisitor::VisitBlockDecl(BlockDecl *B) { 593 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten()) 594 if (Visit(TSInfo->getTypeLoc())) 595 return true; 596 597 if (Stmt *Body = B->getBody()) 598 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest)); 599 600 return false; 601 } 602 603 Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) { 604 if (RegionOfInterest.isValid()) { 605 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager()); 606 if (Range.isInvalid()) 607 return None; 608 609 switch (CompareRegionOfInterest(Range)) { 610 case RangeBefore: 611 // This declaration comes before the region of interest; skip it. 612 return None; 613 614 case RangeAfter: 615 // This declaration comes after the region of interest; we're done. 616 return false; 617 618 case RangeOverlap: 619 // This declaration overlaps the region of interest; visit it. 620 break; 621 } 622 } 623 return true; 624 } 625 626 bool CursorVisitor::VisitDeclContext(DeclContext *DC) { 627 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end(); 628 629 // FIXME: Eventually remove. This part of a hack to support proper 630 // iteration over all Decls contained lexically within an ObjC container. 631 SaveAndRestore<DeclContext::decl_iterator *> DI_saved(DI_current, &I); 632 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E); 633 634 for (; I != E; ++I) { 635 Decl *D = *I; 636 if (D->getLexicalDeclContext() != DC) 637 continue; 638 // Filter out synthesized property accessor redeclarations. 639 if (isa<ObjCImplDecl>(DC)) 640 if (auto *OMD = dyn_cast<ObjCMethodDecl>(D)) 641 if (OMD->isSynthesizedAccessorStub()) 642 continue; 643 const Optional<bool> V = handleDeclForVisitation(D); 644 if (!V.hasValue()) 645 continue; 646 return V.getValue(); 647 } 648 return false; 649 } 650 651 Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) { 652 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest); 653 654 // Ignore synthesized ivars here, otherwise if we have something like: 655 // @synthesize prop = _prop; 656 // and '_prop' is not declared, we will encounter a '_prop' ivar before 657 // encountering the 'prop' synthesize declaration and we will think that 658 // we passed the region-of-interest. 659 if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) { 660 if (ivarD->getSynthesize()) 661 return None; 662 } 663 664 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol 665 // declarations is a mismatch with the compiler semantics. 666 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) { 667 auto *ID = cast<ObjCInterfaceDecl>(D); 668 if (!ID->isThisDeclarationADefinition()) 669 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU); 670 671 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) { 672 auto *PD = cast<ObjCProtocolDecl>(D); 673 if (!PD->isThisDeclarationADefinition()) 674 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU); 675 } 676 677 const Optional<bool> V = shouldVisitCursor(Cursor); 678 if (!V.hasValue()) 679 return None; 680 if (!V.getValue()) 681 return false; 682 if (Visit(Cursor, true)) 683 return true; 684 return None; 685 } 686 687 bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) { 688 llvm_unreachable("Translation units are visited directly by Visit()"); 689 } 690 691 bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) { 692 if (VisitTemplateParameters(D->getTemplateParameters())) 693 return true; 694 695 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest)); 696 } 697 698 bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) { 699 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo()) 700 return Visit(TSInfo->getTypeLoc()); 701 702 return false; 703 } 704 705 bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) { 706 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo()) 707 return Visit(TSInfo->getTypeLoc()); 708 709 return false; 710 } 711 712 bool CursorVisitor::VisitTagDecl(TagDecl *D) { return VisitDeclContext(D); } 713 714 bool CursorVisitor::VisitClassTemplateSpecializationDecl( 715 ClassTemplateSpecializationDecl *D) { 716 bool ShouldVisitBody = false; 717 switch (D->getSpecializationKind()) { 718 case TSK_Undeclared: 719 case TSK_ImplicitInstantiation: 720 // Nothing to visit 721 return false; 722 723 case TSK_ExplicitInstantiationDeclaration: 724 case TSK_ExplicitInstantiationDefinition: 725 break; 726 727 case TSK_ExplicitSpecialization: 728 ShouldVisitBody = true; 729 break; 730 } 731 732 // Visit the template arguments used in the specialization. 733 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) { 734 TypeLoc TL = SpecType->getTypeLoc(); 735 if (TemplateSpecializationTypeLoc TSTLoc = 736 TL.getAs<TemplateSpecializationTypeLoc>()) { 737 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I) 738 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I))) 739 return true; 740 } 741 } 742 743 return ShouldVisitBody && VisitCXXRecordDecl(D); 744 } 745 746 bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl( 747 ClassTemplatePartialSpecializationDecl *D) { 748 // FIXME: Visit the "outer" template parameter lists on the TagDecl 749 // before visiting these template parameters. 750 if (VisitTemplateParameters(D->getTemplateParameters())) 751 return true; 752 753 // Visit the partial specialization arguments. 754 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten(); 755 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs(); 756 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I) 757 if (VisitTemplateArgumentLoc(TemplateArgs[I])) 758 return true; 759 760 return VisitCXXRecordDecl(D); 761 } 762 763 bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) { 764 if (const auto *TC = D->getTypeConstraint()) 765 if (Visit(MakeCXCursor(TC->getImmediatelyDeclaredConstraint(), StmtParent, 766 TU, RegionOfInterest))) 767 return true; 768 769 // Visit the default argument. 770 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) 771 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo()) 772 if (Visit(DefArg->getTypeLoc())) 773 return true; 774 775 return false; 776 } 777 778 bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) { 779 if (Expr *Init = D->getInitExpr()) 780 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest)); 781 return false; 782 } 783 784 bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) { 785 unsigned NumParamList = DD->getNumTemplateParameterLists(); 786 for (unsigned i = 0; i < NumParamList; i++) { 787 TemplateParameterList *Params = DD->getTemplateParameterList(i); 788 if (VisitTemplateParameters(Params)) 789 return true; 790 } 791 792 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo()) 793 if (Visit(TSInfo->getTypeLoc())) 794 return true; 795 796 // Visit the nested-name-specifier, if present. 797 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc()) 798 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 799 return true; 800 801 return false; 802 } 803 804 static bool HasTrailingReturnType(FunctionDecl *ND) { 805 const QualType Ty = ND->getType(); 806 if (const FunctionType *AFT = Ty->getAs<FunctionType>()) { 807 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(AFT)) 808 return FT->hasTrailingReturn(); 809 } 810 811 return false; 812 } 813 814 /// Compare two base or member initializers based on their source order. 815 static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X, 816 CXXCtorInitializer *const *Y) { 817 return (*X)->getSourceOrder() - (*Y)->getSourceOrder(); 818 } 819 820 bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) { 821 unsigned NumParamList = ND->getNumTemplateParameterLists(); 822 for (unsigned i = 0; i < NumParamList; i++) { 823 TemplateParameterList *Params = ND->getTemplateParameterList(i); 824 if (VisitTemplateParameters(Params)) 825 return true; 826 } 827 828 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) { 829 // Visit the function declaration's syntactic components in the order 830 // written. This requires a bit of work. 831 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens(); 832 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>(); 833 const bool HasTrailingRT = HasTrailingReturnType(ND); 834 835 // If we have a function declared directly (without the use of a typedef), 836 // visit just the return type. Otherwise, just visit the function's type 837 // now. 838 if ((FTL && !isa<CXXConversionDecl>(ND) && !HasTrailingRT && 839 Visit(FTL.getReturnLoc())) || 840 (!FTL && Visit(TL))) 841 return true; 842 843 // Visit the nested-name-specifier, if present. 844 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc()) 845 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 846 return true; 847 848 // Visit the declaration name. 849 if (!isa<CXXDestructorDecl>(ND)) 850 if (VisitDeclarationNameInfo(ND->getNameInfo())) 851 return true; 852 853 // FIXME: Visit explicitly-specified template arguments! 854 855 // Visit the function parameters, if we have a function type. 856 if (FTL && VisitFunctionTypeLoc(FTL, true)) 857 return true; 858 859 // Visit the function's trailing return type. 860 if (FTL && HasTrailingRT && Visit(FTL.getReturnLoc())) 861 return true; 862 863 // FIXME: Attributes? 864 } 865 866 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) { 867 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) { 868 // Find the initializers that were written in the source. 869 SmallVector<CXXCtorInitializer *, 4> WrittenInits; 870 for (auto *I : Constructor->inits()) { 871 if (!I->isWritten()) 872 continue; 873 874 WrittenInits.push_back(I); 875 } 876 877 // Sort the initializers in source order 878 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(), 879 &CompareCXXCtorInitializers); 880 881 // Visit the initializers in source order 882 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) { 883 CXXCtorInitializer *Init = WrittenInits[I]; 884 if (Init->isAnyMemberInitializer()) { 885 if (Visit(MakeCursorMemberRef(Init->getAnyMember(), 886 Init->getMemberLocation(), TU))) 887 return true; 888 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) { 889 if (Visit(TInfo->getTypeLoc())) 890 return true; 891 } 892 893 // Visit the initializer value. 894 if (Expr *Initializer = Init->getInit()) 895 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest))) 896 return true; 897 } 898 } 899 900 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest))) 901 return true; 902 } 903 904 return false; 905 } 906 907 bool CursorVisitor::VisitFieldDecl(FieldDecl *D) { 908 if (VisitDeclaratorDecl(D)) 909 return true; 910 911 if (Expr *BitWidth = D->getBitWidth()) 912 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest)); 913 914 if (Expr *Init = D->getInClassInitializer()) 915 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest)); 916 917 return false; 918 } 919 920 bool CursorVisitor::VisitVarDecl(VarDecl *D) { 921 if (VisitDeclaratorDecl(D)) 922 return true; 923 924 if (Expr *Init = D->getInit()) 925 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest)); 926 927 return false; 928 } 929 930 bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) { 931 if (VisitDeclaratorDecl(D)) 932 return true; 933 934 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) 935 if (Expr *DefArg = D->getDefaultArgument()) 936 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest)); 937 938 return false; 939 } 940 941 bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { 942 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl 943 // before visiting these template parameters. 944 if (VisitTemplateParameters(D->getTemplateParameters())) 945 return true; 946 947 auto *FD = D->getTemplatedDecl(); 948 return VisitAttributes(FD) || VisitFunctionDecl(FD); 949 } 950 951 bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) { 952 // FIXME: Visit the "outer" template parameter lists on the TagDecl 953 // before visiting these template parameters. 954 if (VisitTemplateParameters(D->getTemplateParameters())) 955 return true; 956 957 auto *CD = D->getTemplatedDecl(); 958 return VisitAttributes(CD) || VisitCXXRecordDecl(CD); 959 } 960 961 bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) { 962 if (VisitTemplateParameters(D->getTemplateParameters())) 963 return true; 964 965 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() && 966 VisitTemplateArgumentLoc(D->getDefaultArgument())) 967 return true; 968 969 return false; 970 } 971 972 bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) { 973 // Visit the bound, if it's explicit. 974 if (D->hasExplicitBound()) { 975 if (auto TInfo = D->getTypeSourceInfo()) { 976 if (Visit(TInfo->getTypeLoc())) 977 return true; 978 } 979 } 980 981 return false; 982 } 983 984 bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) { 985 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo()) 986 if (Visit(TSInfo->getTypeLoc())) 987 return true; 988 989 for (const auto *P : ND->parameters()) { 990 if (Visit(MakeCXCursor(P, TU, RegionOfInterest))) 991 return true; 992 } 993 994 return ND->isThisDeclarationADefinition() && 995 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)); 996 } 997 998 template <typename DeclIt> 999 static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current, 1000 SourceManager &SM, SourceLocation EndLoc, 1001 SmallVectorImpl<Decl *> &Decls) { 1002 DeclIt next = *DI_current; 1003 while (++next != DE_current) { 1004 Decl *D_next = *next; 1005 if (!D_next) 1006 break; 1007 SourceLocation L = D_next->getBeginLoc(); 1008 if (!L.isValid()) 1009 break; 1010 if (SM.isBeforeInTranslationUnit(L, EndLoc)) { 1011 *DI_current = next; 1012 Decls.push_back(D_next); 1013 continue; 1014 } 1015 break; 1016 } 1017 } 1018 1019 bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) { 1020 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially 1021 // an @implementation can lexically contain Decls that are not properly 1022 // nested in the AST. When we identify such cases, we need to retrofit 1023 // this nesting here. 1024 if (!DI_current && !FileDI_current) 1025 return VisitDeclContext(D); 1026 1027 // Scan the Decls that immediately come after the container 1028 // in the current DeclContext. If any fall within the 1029 // container's lexical region, stash them into a vector 1030 // for later processing. 1031 SmallVector<Decl *, 24> DeclsInContainer; 1032 SourceLocation EndLoc = D->getSourceRange().getEnd(); 1033 SourceManager &SM = AU->getSourceManager(); 1034 if (EndLoc.isValid()) { 1035 if (DI_current) { 1036 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc, 1037 DeclsInContainer); 1038 } else { 1039 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc, 1040 DeclsInContainer); 1041 } 1042 } 1043 1044 // The common case. 1045 if (DeclsInContainer.empty()) 1046 return VisitDeclContext(D); 1047 1048 // Get all the Decls in the DeclContext, and sort them with the 1049 // additional ones we've collected. Then visit them. 1050 for (auto *SubDecl : D->decls()) { 1051 if (!SubDecl || SubDecl->getLexicalDeclContext() != D || 1052 SubDecl->getBeginLoc().isInvalid()) 1053 continue; 1054 DeclsInContainer.push_back(SubDecl); 1055 } 1056 1057 // Now sort the Decls so that they appear in lexical order. 1058 llvm::sort(DeclsInContainer, [&SM](Decl *A, Decl *B) { 1059 SourceLocation L_A = A->getBeginLoc(); 1060 SourceLocation L_B = B->getBeginLoc(); 1061 return L_A != L_B 1062 ? SM.isBeforeInTranslationUnit(L_A, L_B) 1063 : SM.isBeforeInTranslationUnit(A->getEndLoc(), B->getEndLoc()); 1064 }); 1065 1066 // Now visit the decls. 1067 for (SmallVectorImpl<Decl *>::iterator I = DeclsInContainer.begin(), 1068 E = DeclsInContainer.end(); 1069 I != E; ++I) { 1070 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest); 1071 const Optional<bool> &V = shouldVisitCursor(Cursor); 1072 if (!V.hasValue()) 1073 continue; 1074 if (!V.getValue()) 1075 return false; 1076 if (Visit(Cursor, true)) 1077 return true; 1078 } 1079 return false; 1080 } 1081 1082 bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) { 1083 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(), 1084 TU))) 1085 return true; 1086 1087 if (VisitObjCTypeParamList(ND->getTypeParamList())) 1088 return true; 1089 1090 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin(); 1091 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(), 1092 E = ND->protocol_end(); 1093 I != E; ++I, ++PL) 1094 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) 1095 return true; 1096 1097 return VisitObjCContainerDecl(ND); 1098 } 1099 1100 bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) { 1101 if (!PID->isThisDeclarationADefinition()) 1102 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU)); 1103 1104 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin(); 1105 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(), 1106 E = PID->protocol_end(); 1107 I != E; ++I, ++PL) 1108 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) 1109 return true; 1110 1111 return VisitObjCContainerDecl(PID); 1112 } 1113 1114 bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) { 1115 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc())) 1116 return true; 1117 1118 // FIXME: This implements a workaround with @property declarations also being 1119 // installed in the DeclContext for the @interface. Eventually this code 1120 // should be removed. 1121 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext()); 1122 if (!CDecl || !CDecl->IsClassExtension()) 1123 return false; 1124 1125 ObjCInterfaceDecl *ID = CDecl->getClassInterface(); 1126 if (!ID) 1127 return false; 1128 1129 IdentifierInfo *PropertyId = PD->getIdentifier(); 1130 ObjCPropertyDecl *prevDecl = ObjCPropertyDecl::findPropertyDecl( 1131 cast<DeclContext>(ID), PropertyId, PD->getQueryKind()); 1132 1133 if (!prevDecl) 1134 return false; 1135 1136 // Visit synthesized methods since they will be skipped when visiting 1137 // the @interface. 1138 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl()) 1139 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl) 1140 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest))) 1141 return true; 1142 1143 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl()) 1144 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl) 1145 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest))) 1146 return true; 1147 1148 return false; 1149 } 1150 1151 bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) { 1152 if (!typeParamList) 1153 return false; 1154 1155 for (auto *typeParam : *typeParamList) { 1156 // Visit the type parameter. 1157 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest))) 1158 return true; 1159 } 1160 1161 return false; 1162 } 1163 1164 bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) { 1165 if (!D->isThisDeclarationADefinition()) { 1166 // Forward declaration is treated like a reference. 1167 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU)); 1168 } 1169 1170 // Objective-C type parameters. 1171 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten())) 1172 return true; 1173 1174 // Issue callbacks for super class. 1175 if (D->getSuperClass() && Visit(MakeCursorObjCSuperClassRef( 1176 D->getSuperClass(), D->getSuperClassLoc(), TU))) 1177 return true; 1178 1179 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo()) 1180 if (Visit(SuperClassTInfo->getTypeLoc())) 1181 return true; 1182 1183 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin(); 1184 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(), 1185 E = D->protocol_end(); 1186 I != E; ++I, ++PL) 1187 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) 1188 return true; 1189 1190 return VisitObjCContainerDecl(D); 1191 } 1192 1193 bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) { 1194 return VisitObjCContainerDecl(D); 1195 } 1196 1197 bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) { 1198 // 'ID' could be null when dealing with invalid code. 1199 if (ObjCInterfaceDecl *ID = D->getClassInterface()) 1200 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU))) 1201 return true; 1202 1203 return VisitObjCImplDecl(D); 1204 } 1205 1206 bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) { 1207 #if 0 1208 // Issue callbacks for super class. 1209 // FIXME: No source location information! 1210 if (D->getSuperClass() && 1211 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(), 1212 D->getSuperClassLoc(), 1213 TU))) 1214 return true; 1215 #endif 1216 1217 return VisitObjCImplDecl(D); 1218 } 1219 1220 bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) { 1221 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl()) 1222 if (PD->isIvarNameSpecified()) 1223 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU)); 1224 1225 return false; 1226 } 1227 1228 bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) { 1229 return VisitDeclContext(D); 1230 } 1231 1232 bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { 1233 // Visit nested-name-specifier. 1234 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) 1235 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1236 return true; 1237 1238 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(), 1239 D->getTargetNameLoc(), TU)); 1240 } 1241 1242 bool CursorVisitor::VisitUsingDecl(UsingDecl *D) { 1243 // Visit nested-name-specifier. 1244 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) { 1245 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1246 return true; 1247 } 1248 1249 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU))) 1250 return true; 1251 1252 return VisitDeclarationNameInfo(D->getNameInfo()); 1253 } 1254 1255 bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { 1256 // Visit nested-name-specifier. 1257 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) 1258 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1259 return true; 1260 1261 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(), 1262 D->getIdentLocation(), TU)); 1263 } 1264 1265 bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) { 1266 // Visit nested-name-specifier. 1267 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) { 1268 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1269 return true; 1270 } 1271 1272 return VisitDeclarationNameInfo(D->getNameInfo()); 1273 } 1274 1275 bool CursorVisitor::VisitUnresolvedUsingTypenameDecl( 1276 UnresolvedUsingTypenameDecl *D) { 1277 // Visit nested-name-specifier. 1278 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) 1279 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1280 return true; 1281 1282 return false; 1283 } 1284 1285 bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) { 1286 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest))) 1287 return true; 1288 if (StringLiteral *Message = D->getMessage()) 1289 if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest))) 1290 return true; 1291 return false; 1292 } 1293 1294 bool CursorVisitor::VisitFriendDecl(FriendDecl *D) { 1295 if (NamedDecl *FriendD = D->getFriendDecl()) { 1296 if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest))) 1297 return true; 1298 } else if (TypeSourceInfo *TI = D->getFriendType()) { 1299 if (Visit(TI->getTypeLoc())) 1300 return true; 1301 } 1302 return false; 1303 } 1304 1305 bool CursorVisitor::VisitDecompositionDecl(DecompositionDecl *D) { 1306 for (auto *B : D->bindings()) { 1307 if (Visit(MakeCXCursor(B, TU, RegionOfInterest))) 1308 return true; 1309 } 1310 return VisitVarDecl(D); 1311 } 1312 1313 bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) { 1314 switch (Name.getName().getNameKind()) { 1315 case clang::DeclarationName::Identifier: 1316 case clang::DeclarationName::CXXLiteralOperatorName: 1317 case clang::DeclarationName::CXXDeductionGuideName: 1318 case clang::DeclarationName::CXXOperatorName: 1319 case clang::DeclarationName::CXXUsingDirective: 1320 return false; 1321 1322 case clang::DeclarationName::CXXConstructorName: 1323 case clang::DeclarationName::CXXDestructorName: 1324 case clang::DeclarationName::CXXConversionFunctionName: 1325 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo()) 1326 return Visit(TSInfo->getTypeLoc()); 1327 return false; 1328 1329 case clang::DeclarationName::ObjCZeroArgSelector: 1330 case clang::DeclarationName::ObjCOneArgSelector: 1331 case clang::DeclarationName::ObjCMultiArgSelector: 1332 // FIXME: Per-identifier location info? 1333 return false; 1334 } 1335 1336 llvm_unreachable("Invalid DeclarationName::Kind!"); 1337 } 1338 1339 bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS, 1340 SourceRange Range) { 1341 // FIXME: This whole routine is a hack to work around the lack of proper 1342 // source information in nested-name-specifiers (PR5791). Since we do have 1343 // a beginning source location, we can visit the first component of the 1344 // nested-name-specifier, if it's a single-token component. 1345 if (!NNS) 1346 return false; 1347 1348 // Get the first component in the nested-name-specifier. 1349 while (NestedNameSpecifier *Prefix = NNS->getPrefix()) 1350 NNS = Prefix; 1351 1352 switch (NNS->getKind()) { 1353 case NestedNameSpecifier::Namespace: 1354 return Visit( 1355 MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(), TU)); 1356 1357 case NestedNameSpecifier::NamespaceAlias: 1358 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(), 1359 Range.getBegin(), TU)); 1360 1361 case NestedNameSpecifier::TypeSpec: { 1362 // If the type has a form where we know that the beginning of the source 1363 // range matches up with a reference cursor. Visit the appropriate reference 1364 // cursor. 1365 const Type *T = NNS->getAsType(); 1366 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T)) 1367 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU)); 1368 if (const TagType *Tag = dyn_cast<TagType>(T)) 1369 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU)); 1370 if (const TemplateSpecializationType *TST = 1371 dyn_cast<TemplateSpecializationType>(T)) 1372 return VisitTemplateName(TST->getTemplateName(), Range.getBegin()); 1373 break; 1374 } 1375 1376 case NestedNameSpecifier::TypeSpecWithTemplate: 1377 case NestedNameSpecifier::Global: 1378 case NestedNameSpecifier::Identifier: 1379 case NestedNameSpecifier::Super: 1380 break; 1381 } 1382 1383 return false; 1384 } 1385 1386 bool CursorVisitor::VisitNestedNameSpecifierLoc( 1387 NestedNameSpecifierLoc Qualifier) { 1388 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers; 1389 for (; Qualifier; Qualifier = Qualifier.getPrefix()) 1390 Qualifiers.push_back(Qualifier); 1391 1392 while (!Qualifiers.empty()) { 1393 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val(); 1394 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier(); 1395 switch (NNS->getKind()) { 1396 case NestedNameSpecifier::Namespace: 1397 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), 1398 Q.getLocalBeginLoc(), TU))) 1399 return true; 1400 1401 break; 1402 1403 case NestedNameSpecifier::NamespaceAlias: 1404 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(), 1405 Q.getLocalBeginLoc(), TU))) 1406 return true; 1407 1408 break; 1409 1410 case NestedNameSpecifier::TypeSpec: 1411 case NestedNameSpecifier::TypeSpecWithTemplate: 1412 if (Visit(Q.getTypeLoc())) 1413 return true; 1414 1415 break; 1416 1417 case NestedNameSpecifier::Global: 1418 case NestedNameSpecifier::Identifier: 1419 case NestedNameSpecifier::Super: 1420 break; 1421 } 1422 } 1423 1424 return false; 1425 } 1426 1427 bool CursorVisitor::VisitTemplateParameters( 1428 const TemplateParameterList *Params) { 1429 if (!Params) 1430 return false; 1431 1432 for (TemplateParameterList::const_iterator P = Params->begin(), 1433 PEnd = Params->end(); 1434 P != PEnd; ++P) { 1435 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest))) 1436 return true; 1437 } 1438 1439 return false; 1440 } 1441 1442 bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) { 1443 switch (Name.getKind()) { 1444 case TemplateName::Template: 1445 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU)); 1446 1447 case TemplateName::OverloadedTemplate: 1448 // Visit the overloaded template set. 1449 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU))) 1450 return true; 1451 1452 return false; 1453 1454 case TemplateName::AssumedTemplate: 1455 // FIXME: Visit DeclarationName? 1456 return false; 1457 1458 case TemplateName::DependentTemplate: 1459 // FIXME: Visit nested-name-specifier. 1460 return false; 1461 1462 case TemplateName::QualifiedTemplate: 1463 // FIXME: Visit nested-name-specifier. 1464 return Visit(MakeCursorTemplateRef( 1465 Name.getAsQualifiedTemplateName()->getDecl(), Loc, TU)); 1466 1467 case TemplateName::SubstTemplateTemplateParm: 1468 return Visit(MakeCursorTemplateRef( 1469 Name.getAsSubstTemplateTemplateParm()->getParameter(), Loc, TU)); 1470 1471 case TemplateName::SubstTemplateTemplateParmPack: 1472 return Visit(MakeCursorTemplateRef( 1473 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(), Loc, 1474 TU)); 1475 } 1476 1477 llvm_unreachable("Invalid TemplateName::Kind!"); 1478 } 1479 1480 bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) { 1481 switch (TAL.getArgument().getKind()) { 1482 case TemplateArgument::Null: 1483 case TemplateArgument::Integral: 1484 case TemplateArgument::Pack: 1485 return false; 1486 1487 case TemplateArgument::Type: 1488 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo()) 1489 return Visit(TSInfo->getTypeLoc()); 1490 return false; 1491 1492 case TemplateArgument::Declaration: 1493 if (Expr *E = TAL.getSourceDeclExpression()) 1494 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest)); 1495 return false; 1496 1497 case TemplateArgument::NullPtr: 1498 if (Expr *E = TAL.getSourceNullPtrExpression()) 1499 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest)); 1500 return false; 1501 1502 case TemplateArgument::Expression: 1503 if (Expr *E = TAL.getSourceExpression()) 1504 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest)); 1505 return false; 1506 1507 case TemplateArgument::Template: 1508 case TemplateArgument::TemplateExpansion: 1509 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc())) 1510 return true; 1511 1512 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(), 1513 TAL.getTemplateNameLoc()); 1514 } 1515 1516 llvm_unreachable("Invalid TemplateArgument::Kind!"); 1517 } 1518 1519 bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) { 1520 return VisitDeclContext(D); 1521 } 1522 1523 bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 1524 return Visit(TL.getUnqualifiedLoc()); 1525 } 1526 1527 bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 1528 ASTContext &Context = AU->getASTContext(); 1529 1530 // Some builtin types (such as Objective-C's "id", "sel", and 1531 // "Class") have associated declarations. Create cursors for those. 1532 QualType VisitType; 1533 switch (TL.getTypePtr()->getKind()) { 1534 1535 case BuiltinType::Void: 1536 case BuiltinType::NullPtr: 1537 case BuiltinType::Dependent: 1538 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 1539 case BuiltinType::Id: 1540 #include "clang/Basic/OpenCLImageTypes.def" 1541 #define EXT_OPAQUE_TYPE(ExtTYpe, Id, Ext) case BuiltinType::Id: 1542 #include "clang/Basic/OpenCLExtensionTypes.def" 1543 case BuiltinType::OCLSampler: 1544 case BuiltinType::OCLEvent: 1545 case BuiltinType::OCLClkEvent: 1546 case BuiltinType::OCLQueue: 1547 case BuiltinType::OCLReserveID: 1548 #define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 1549 #include "clang/Basic/AArch64SVEACLETypes.def" 1550 #define PPC_VECTOR_TYPE(Name, Id, Size) case BuiltinType::Id: 1551 #include "clang/Basic/PPCTypes.def" 1552 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 1553 #include "clang/Basic/RISCVVTypes.def" 1554 #define BUILTIN_TYPE(Id, SingletonId) 1555 #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id: 1556 #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id: 1557 #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id: 1558 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id: 1559 #include "clang/AST/BuiltinTypes.def" 1560 break; 1561 1562 case BuiltinType::ObjCId: 1563 VisitType = Context.getObjCIdType(); 1564 break; 1565 1566 case BuiltinType::ObjCClass: 1567 VisitType = Context.getObjCClassType(); 1568 break; 1569 1570 case BuiltinType::ObjCSel: 1571 VisitType = Context.getObjCSelType(); 1572 break; 1573 } 1574 1575 if (!VisitType.isNull()) { 1576 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>()) 1577 return Visit( 1578 MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(), TU)); 1579 } 1580 1581 return false; 1582 } 1583 1584 bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) { 1585 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU)); 1586 } 1587 1588 bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) { 1589 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); 1590 } 1591 1592 bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) { 1593 if (TL.isDefinition()) 1594 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest)); 1595 1596 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); 1597 } 1598 1599 bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) { 1600 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); 1601 } 1602 1603 bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 1604 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)); 1605 } 1606 1607 bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) { 1608 if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getBeginLoc(), TU))) 1609 return true; 1610 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) { 1611 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I), 1612 TU))) 1613 return true; 1614 } 1615 1616 return false; 1617 } 1618 1619 bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 1620 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc())) 1621 return true; 1622 1623 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) { 1624 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc())) 1625 return true; 1626 } 1627 1628 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) { 1629 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I), 1630 TU))) 1631 return true; 1632 } 1633 1634 return false; 1635 } 1636 1637 bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 1638 return Visit(TL.getPointeeLoc()); 1639 } 1640 1641 bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) { 1642 return Visit(TL.getInnerLoc()); 1643 } 1644 1645 bool CursorVisitor::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) { 1646 return Visit(TL.getInnerLoc()); 1647 } 1648 1649 bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) { 1650 return Visit(TL.getPointeeLoc()); 1651 } 1652 1653 bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 1654 return Visit(TL.getPointeeLoc()); 1655 } 1656 1657 bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 1658 return Visit(TL.getPointeeLoc()); 1659 } 1660 1661 bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 1662 return Visit(TL.getPointeeLoc()); 1663 } 1664 1665 bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 1666 return Visit(TL.getPointeeLoc()); 1667 } 1668 1669 bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) { 1670 return Visit(TL.getModifiedLoc()); 1671 } 1672 1673 bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL, 1674 bool SkipResultType) { 1675 if (!SkipResultType && Visit(TL.getReturnLoc())) 1676 return true; 1677 1678 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I) 1679 if (Decl *D = TL.getParam(I)) 1680 if (Visit(MakeCXCursor(D, TU, RegionOfInterest))) 1681 return true; 1682 1683 return false; 1684 } 1685 1686 bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) { 1687 if (Visit(TL.getElementLoc())) 1688 return true; 1689 1690 if (Expr *Size = TL.getSizeExpr()) 1691 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest)); 1692 1693 return false; 1694 } 1695 1696 bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) { 1697 return Visit(TL.getOriginalLoc()); 1698 } 1699 1700 bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { 1701 return Visit(TL.getOriginalLoc()); 1702 } 1703 1704 bool CursorVisitor::VisitDeducedTemplateSpecializationTypeLoc( 1705 DeducedTemplateSpecializationTypeLoc TL) { 1706 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(), 1707 TL.getTemplateNameLoc())) 1708 return true; 1709 1710 return false; 1711 } 1712 1713 bool CursorVisitor::VisitTemplateSpecializationTypeLoc( 1714 TemplateSpecializationTypeLoc TL) { 1715 // Visit the template name. 1716 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(), 1717 TL.getTemplateNameLoc())) 1718 return true; 1719 1720 // Visit the template arguments. 1721 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I) 1722 if (VisitTemplateArgumentLoc(TL.getArgLoc(I))) 1723 return true; 1724 1725 return false; 1726 } 1727 1728 bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 1729 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU)); 1730 } 1731 1732 bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 1733 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo()) 1734 return Visit(TSInfo->getTypeLoc()); 1735 1736 return false; 1737 } 1738 1739 bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { 1740 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo()) 1741 return Visit(TSInfo->getTypeLoc()); 1742 1743 return false; 1744 } 1745 1746 bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 1747 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc()); 1748 } 1749 1750 bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc( 1751 DependentTemplateSpecializationTypeLoc TL) { 1752 // Visit the nested-name-specifier, if there is one. 1753 if (TL.getQualifierLoc() && VisitNestedNameSpecifierLoc(TL.getQualifierLoc())) 1754 return true; 1755 1756 // Visit the template arguments. 1757 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I) 1758 if (VisitTemplateArgumentLoc(TL.getArgLoc(I))) 1759 return true; 1760 1761 return false; 1762 } 1763 1764 bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 1765 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc())) 1766 return true; 1767 1768 return Visit(TL.getNamedTypeLoc()); 1769 } 1770 1771 bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) { 1772 return Visit(TL.getPatternLoc()); 1773 } 1774 1775 bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) { 1776 if (Expr *E = TL.getUnderlyingExpr()) 1777 return Visit(MakeCXCursor(E, StmtParent, TU)); 1778 1779 return false; 1780 } 1781 1782 bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) { 1783 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); 1784 } 1785 1786 bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) { 1787 return Visit(TL.getValueLoc()); 1788 } 1789 1790 bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) { 1791 return Visit(TL.getValueLoc()); 1792 } 1793 1794 #define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \ 1795 bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \ 1796 return Visit##PARENT##Loc(TL); \ 1797 } 1798 1799 DEFAULT_TYPELOC_IMPL(Complex, Type) 1800 DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType) 1801 DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType) 1802 DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType) 1803 DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType) 1804 DEFAULT_TYPELOC_IMPL(DependentAddressSpace, Type) 1805 DEFAULT_TYPELOC_IMPL(DependentVector, Type) 1806 DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type) 1807 DEFAULT_TYPELOC_IMPL(Vector, Type) 1808 DEFAULT_TYPELOC_IMPL(ExtVector, VectorType) 1809 DEFAULT_TYPELOC_IMPL(ConstantMatrix, MatrixType) 1810 DEFAULT_TYPELOC_IMPL(DependentSizedMatrix, MatrixType) 1811 DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType) 1812 DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType) 1813 DEFAULT_TYPELOC_IMPL(Record, TagType) 1814 DEFAULT_TYPELOC_IMPL(Enum, TagType) 1815 DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type) 1816 DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type) 1817 DEFAULT_TYPELOC_IMPL(Auto, Type) 1818 DEFAULT_TYPELOC_IMPL(ExtInt, Type) 1819 DEFAULT_TYPELOC_IMPL(DependentExtInt, Type) 1820 1821 bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) { 1822 // Visit the nested-name-specifier, if present. 1823 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) 1824 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1825 return true; 1826 1827 if (D->isCompleteDefinition()) { 1828 for (const auto &I : D->bases()) { 1829 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU))) 1830 return true; 1831 } 1832 } 1833 1834 return VisitTagDecl(D); 1835 } 1836 1837 bool CursorVisitor::VisitAttributes(Decl *D) { 1838 for (const auto *I : D->attrs()) 1839 if ((TU->ParsingOptions & CXTranslationUnit_VisitImplicitAttributes || 1840 !I->isImplicit()) && 1841 Visit(MakeCXCursor(I, D, TU))) 1842 return true; 1843 1844 return false; 1845 } 1846 1847 //===----------------------------------------------------------------------===// 1848 // Data-recursive visitor methods. 1849 //===----------------------------------------------------------------------===// 1850 1851 namespace { 1852 #define DEF_JOB(NAME, DATA, KIND) \ 1853 class NAME : public VisitorJob { \ 1854 public: \ 1855 NAME(const DATA *d, CXCursor parent) \ 1856 : VisitorJob(parent, VisitorJob::KIND, d) {} \ 1857 static bool classof(const VisitorJob *VJ) { \ 1858 return VJ->getKind() == KIND; \ 1859 } \ 1860 const DATA *get() const { return static_cast<const DATA *>(data[0]); } \ 1861 }; 1862 1863 DEF_JOB(StmtVisit, Stmt, StmtVisitKind) 1864 DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind) 1865 DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind) 1866 DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind) 1867 DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind) 1868 DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind) 1869 DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind) 1870 #undef DEF_JOB 1871 1872 class ExplicitTemplateArgsVisit : public VisitorJob { 1873 public: 1874 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin, 1875 const TemplateArgumentLoc *End, CXCursor parent) 1876 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin, 1877 End) {} 1878 static bool classof(const VisitorJob *VJ) { 1879 return VJ->getKind() == ExplicitTemplateArgsVisitKind; 1880 } 1881 const TemplateArgumentLoc *begin() const { 1882 return static_cast<const TemplateArgumentLoc *>(data[0]); 1883 } 1884 const TemplateArgumentLoc *end() { 1885 return static_cast<const TemplateArgumentLoc *>(data[1]); 1886 } 1887 }; 1888 class DeclVisit : public VisitorJob { 1889 public: 1890 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) 1891 : VisitorJob(parent, VisitorJob::DeclVisitKind, D, 1892 isFirst ? (void *)1 : (void *)nullptr) {} 1893 static bool classof(const VisitorJob *VJ) { 1894 return VJ->getKind() == DeclVisitKind; 1895 } 1896 const Decl *get() const { return static_cast<const Decl *>(data[0]); } 1897 bool isFirst() const { return data[1] != nullptr; } 1898 }; 1899 class TypeLocVisit : public VisitorJob { 1900 public: 1901 TypeLocVisit(TypeLoc tl, CXCursor parent) 1902 : VisitorJob(parent, VisitorJob::TypeLocVisitKind, 1903 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {} 1904 1905 static bool classof(const VisitorJob *VJ) { 1906 return VJ->getKind() == TypeLocVisitKind; 1907 } 1908 1909 TypeLoc get() const { 1910 QualType T = QualType::getFromOpaquePtr(data[0]); 1911 return TypeLoc(T, const_cast<void *>(data[1])); 1912 } 1913 }; 1914 1915 class LabelRefVisit : public VisitorJob { 1916 public: 1917 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent) 1918 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD, 1919 labelLoc.getPtrEncoding()) {} 1920 1921 static bool classof(const VisitorJob *VJ) { 1922 return VJ->getKind() == VisitorJob::LabelRefVisitKind; 1923 } 1924 const LabelDecl *get() const { 1925 return static_cast<const LabelDecl *>(data[0]); 1926 } 1927 SourceLocation getLoc() const { 1928 return SourceLocation::getFromPtrEncoding(data[1]); 1929 } 1930 }; 1931 1932 class NestedNameSpecifierLocVisit : public VisitorJob { 1933 public: 1934 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent) 1935 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind, 1936 Qualifier.getNestedNameSpecifier(), 1937 Qualifier.getOpaqueData()) {} 1938 1939 static bool classof(const VisitorJob *VJ) { 1940 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind; 1941 } 1942 1943 NestedNameSpecifierLoc get() const { 1944 return NestedNameSpecifierLoc( 1945 const_cast<NestedNameSpecifier *>( 1946 static_cast<const NestedNameSpecifier *>(data[0])), 1947 const_cast<void *>(data[1])); 1948 } 1949 }; 1950 1951 class DeclarationNameInfoVisit : public VisitorJob { 1952 public: 1953 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent) 1954 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {} 1955 static bool classof(const VisitorJob *VJ) { 1956 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind; 1957 } 1958 DeclarationNameInfo get() const { 1959 const Stmt *S = static_cast<const Stmt *>(data[0]); 1960 switch (S->getStmtClass()) { 1961 default: 1962 llvm_unreachable("Unhandled Stmt"); 1963 case clang::Stmt::MSDependentExistsStmtClass: 1964 return cast<MSDependentExistsStmt>(S)->getNameInfo(); 1965 case Stmt::CXXDependentScopeMemberExprClass: 1966 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo(); 1967 case Stmt::DependentScopeDeclRefExprClass: 1968 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo(); 1969 case Stmt::OMPCriticalDirectiveClass: 1970 return cast<OMPCriticalDirective>(S)->getDirectiveName(); 1971 } 1972 } 1973 }; 1974 class MemberRefVisit : public VisitorJob { 1975 public: 1976 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent) 1977 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D, 1978 L.getPtrEncoding()) {} 1979 static bool classof(const VisitorJob *VJ) { 1980 return VJ->getKind() == VisitorJob::MemberRefVisitKind; 1981 } 1982 const FieldDecl *get() const { 1983 return static_cast<const FieldDecl *>(data[0]); 1984 } 1985 SourceLocation getLoc() const { 1986 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t)data[1]); 1987 } 1988 }; 1989 class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> { 1990 friend class OMPClauseEnqueue; 1991 VisitorWorkList &WL; 1992 CXCursor Parent; 1993 1994 public: 1995 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent) 1996 : WL(wl), Parent(parent) {} 1997 1998 void VisitAddrLabelExpr(const AddrLabelExpr *E); 1999 void VisitBlockExpr(const BlockExpr *B); 2000 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 2001 void VisitCompoundStmt(const CompoundStmt *S); 2002 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ 2003 } 2004 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S); 2005 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E); 2006 void VisitCXXNewExpr(const CXXNewExpr *E); 2007 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E); 2008 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E); 2009 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E); 2010 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E); 2011 void VisitCXXTypeidExpr(const CXXTypeidExpr *E); 2012 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E); 2013 void VisitCXXUuidofExpr(const CXXUuidofExpr *E); 2014 void VisitCXXCatchStmt(const CXXCatchStmt *S); 2015 void VisitCXXForRangeStmt(const CXXForRangeStmt *S); 2016 void VisitDeclRefExpr(const DeclRefExpr *D); 2017 void VisitDeclStmt(const DeclStmt *S); 2018 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E); 2019 void VisitDesignatedInitExpr(const DesignatedInitExpr *E); 2020 void VisitExplicitCastExpr(const ExplicitCastExpr *E); 2021 void VisitForStmt(const ForStmt *FS); 2022 void VisitGotoStmt(const GotoStmt *GS); 2023 void VisitIfStmt(const IfStmt *If); 2024 void VisitInitListExpr(const InitListExpr *IE); 2025 void VisitMemberExpr(const MemberExpr *M); 2026 void VisitOffsetOfExpr(const OffsetOfExpr *E); 2027 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E); 2028 void VisitObjCMessageExpr(const ObjCMessageExpr *M); 2029 void VisitOverloadExpr(const OverloadExpr *E); 2030 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 2031 void VisitStmt(const Stmt *S); 2032 void VisitSwitchStmt(const SwitchStmt *S); 2033 void VisitWhileStmt(const WhileStmt *W); 2034 void VisitTypeTraitExpr(const TypeTraitExpr *E); 2035 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E); 2036 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E); 2037 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U); 2038 void VisitVAArgExpr(const VAArgExpr *E); 2039 void VisitSizeOfPackExpr(const SizeOfPackExpr *E); 2040 void VisitPseudoObjectExpr(const PseudoObjectExpr *E); 2041 void VisitOpaqueValueExpr(const OpaqueValueExpr *E); 2042 void VisitLambdaExpr(const LambdaExpr *E); 2043 void VisitOMPExecutableDirective(const OMPExecutableDirective *D); 2044 void VisitOMPLoopBasedDirective(const OMPLoopBasedDirective *D); 2045 void VisitOMPLoopDirective(const OMPLoopDirective *D); 2046 void VisitOMPParallelDirective(const OMPParallelDirective *D); 2047 void VisitOMPSimdDirective(const OMPSimdDirective *D); 2048 void VisitOMPTileDirective(const OMPTileDirective *D); 2049 void VisitOMPUnrollDirective(const OMPUnrollDirective *D); 2050 void VisitOMPForDirective(const OMPForDirective *D); 2051 void VisitOMPForSimdDirective(const OMPForSimdDirective *D); 2052 void VisitOMPSectionsDirective(const OMPSectionsDirective *D); 2053 void VisitOMPSectionDirective(const OMPSectionDirective *D); 2054 void VisitOMPSingleDirective(const OMPSingleDirective *D); 2055 void VisitOMPMasterDirective(const OMPMasterDirective *D); 2056 void VisitOMPCriticalDirective(const OMPCriticalDirective *D); 2057 void VisitOMPParallelForDirective(const OMPParallelForDirective *D); 2058 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D); 2059 void VisitOMPParallelMasterDirective(const OMPParallelMasterDirective *D); 2060 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D); 2061 void VisitOMPTaskDirective(const OMPTaskDirective *D); 2062 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D); 2063 void VisitOMPBarrierDirective(const OMPBarrierDirective *D); 2064 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D); 2065 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D); 2066 void 2067 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D); 2068 void VisitOMPCancelDirective(const OMPCancelDirective *D); 2069 void VisitOMPFlushDirective(const OMPFlushDirective *D); 2070 void VisitOMPDepobjDirective(const OMPDepobjDirective *D); 2071 void VisitOMPScanDirective(const OMPScanDirective *D); 2072 void VisitOMPOrderedDirective(const OMPOrderedDirective *D); 2073 void VisitOMPAtomicDirective(const OMPAtomicDirective *D); 2074 void VisitOMPTargetDirective(const OMPTargetDirective *D); 2075 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D); 2076 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D); 2077 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D); 2078 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D); 2079 void 2080 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D); 2081 void VisitOMPTeamsDirective(const OMPTeamsDirective *D); 2082 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D); 2083 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D); 2084 void VisitOMPMasterTaskLoopDirective(const OMPMasterTaskLoopDirective *D); 2085 void 2086 VisitOMPMasterTaskLoopSimdDirective(const OMPMasterTaskLoopSimdDirective *D); 2087 void VisitOMPParallelMasterTaskLoopDirective( 2088 const OMPParallelMasterTaskLoopDirective *D); 2089 void VisitOMPParallelMasterTaskLoopSimdDirective( 2090 const OMPParallelMasterTaskLoopSimdDirective *D); 2091 void VisitOMPDistributeDirective(const OMPDistributeDirective *D); 2092 void VisitOMPDistributeParallelForDirective( 2093 const OMPDistributeParallelForDirective *D); 2094 void VisitOMPDistributeParallelForSimdDirective( 2095 const OMPDistributeParallelForSimdDirective *D); 2096 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D); 2097 void VisitOMPTargetParallelForSimdDirective( 2098 const OMPTargetParallelForSimdDirective *D); 2099 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D); 2100 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D); 2101 void VisitOMPTeamsDistributeSimdDirective( 2102 const OMPTeamsDistributeSimdDirective *D); 2103 void VisitOMPTeamsDistributeParallelForSimdDirective( 2104 const OMPTeamsDistributeParallelForSimdDirective *D); 2105 void VisitOMPTeamsDistributeParallelForDirective( 2106 const OMPTeamsDistributeParallelForDirective *D); 2107 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D); 2108 void VisitOMPTargetTeamsDistributeDirective( 2109 const OMPTargetTeamsDistributeDirective *D); 2110 void VisitOMPTargetTeamsDistributeParallelForDirective( 2111 const OMPTargetTeamsDistributeParallelForDirective *D); 2112 void VisitOMPTargetTeamsDistributeParallelForSimdDirective( 2113 const OMPTargetTeamsDistributeParallelForSimdDirective *D); 2114 void VisitOMPTargetTeamsDistributeSimdDirective( 2115 const OMPTargetTeamsDistributeSimdDirective *D); 2116 2117 private: 2118 void AddDeclarationNameInfo(const Stmt *S); 2119 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier); 2120 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A, 2121 unsigned NumTemplateArgs); 2122 void AddMemberRef(const FieldDecl *D, SourceLocation L); 2123 void AddStmt(const Stmt *S); 2124 void AddDecl(const Decl *D, bool isFirst = true); 2125 void AddTypeLoc(TypeSourceInfo *TI); 2126 void EnqueueChildren(const Stmt *S); 2127 void EnqueueChildren(const OMPClause *S); 2128 }; 2129 } // namespace 2130 2131 void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) { 2132 // 'S' should always be non-null, since it comes from the 2133 // statement we are visiting. 2134 WL.push_back(DeclarationNameInfoVisit(S, Parent)); 2135 } 2136 2137 void EnqueueVisitor::AddNestedNameSpecifierLoc( 2138 NestedNameSpecifierLoc Qualifier) { 2139 if (Qualifier) 2140 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent)); 2141 } 2142 2143 void EnqueueVisitor::AddStmt(const Stmt *S) { 2144 if (S) 2145 WL.push_back(StmtVisit(S, Parent)); 2146 } 2147 void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) { 2148 if (D) 2149 WL.push_back(DeclVisit(D, Parent, isFirst)); 2150 } 2151 void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A, 2152 unsigned NumTemplateArgs) { 2153 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent)); 2154 } 2155 void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) { 2156 if (D) 2157 WL.push_back(MemberRefVisit(D, L, Parent)); 2158 } 2159 void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) { 2160 if (TI) 2161 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent)); 2162 } 2163 void EnqueueVisitor::EnqueueChildren(const Stmt *S) { 2164 unsigned size = WL.size(); 2165 for (const Stmt *SubStmt : S->children()) { 2166 AddStmt(SubStmt); 2167 } 2168 if (size == WL.size()) 2169 return; 2170 // Now reverse the entries we just added. This will match the DFS 2171 // ordering performed by the worklist. 2172 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end(); 2173 std::reverse(I, E); 2174 } 2175 namespace { 2176 class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> { 2177 EnqueueVisitor *Visitor; 2178 /// Process clauses with list of variables. 2179 template <typename T> void VisitOMPClauseList(T *Node); 2180 2181 public: 2182 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) {} 2183 #define GEN_CLANG_CLAUSE_CLASS 2184 #define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(const Class *C); 2185 #include "llvm/Frontend/OpenMP/OMP.inc" 2186 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C); 2187 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C); 2188 }; 2189 2190 void OMPClauseEnqueue::VisitOMPClauseWithPreInit( 2191 const OMPClauseWithPreInit *C) { 2192 Visitor->AddStmt(C->getPreInitStmt()); 2193 } 2194 2195 void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate( 2196 const OMPClauseWithPostUpdate *C) { 2197 VisitOMPClauseWithPreInit(C); 2198 Visitor->AddStmt(C->getPostUpdateExpr()); 2199 } 2200 2201 void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) { 2202 VisitOMPClauseWithPreInit(C); 2203 Visitor->AddStmt(C->getCondition()); 2204 } 2205 2206 void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) { 2207 Visitor->AddStmt(C->getCondition()); 2208 } 2209 2210 void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) { 2211 VisitOMPClauseWithPreInit(C); 2212 Visitor->AddStmt(C->getNumThreads()); 2213 } 2214 2215 void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) { 2216 Visitor->AddStmt(C->getSafelen()); 2217 } 2218 2219 void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) { 2220 Visitor->AddStmt(C->getSimdlen()); 2221 } 2222 2223 void OMPClauseEnqueue::VisitOMPSizesClause(const OMPSizesClause *C) { 2224 for (auto E : C->getSizesRefs()) 2225 Visitor->AddStmt(E); 2226 } 2227 2228 void OMPClauseEnqueue::VisitOMPFullClause(const OMPFullClause *C) {} 2229 2230 void OMPClauseEnqueue::VisitOMPPartialClause(const OMPPartialClause *C) { 2231 Visitor->AddStmt(C->getFactor()); 2232 } 2233 2234 void OMPClauseEnqueue::VisitOMPAllocatorClause(const OMPAllocatorClause *C) { 2235 Visitor->AddStmt(C->getAllocator()); 2236 } 2237 2238 void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) { 2239 Visitor->AddStmt(C->getNumForLoops()); 2240 } 2241 2242 void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) {} 2243 2244 void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) {} 2245 2246 void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) { 2247 VisitOMPClauseWithPreInit(C); 2248 Visitor->AddStmt(C->getChunkSize()); 2249 } 2250 2251 void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) { 2252 Visitor->AddStmt(C->getNumForLoops()); 2253 } 2254 2255 void OMPClauseEnqueue::VisitOMPDetachClause(const OMPDetachClause *C) { 2256 Visitor->AddStmt(C->getEventHandler()); 2257 } 2258 2259 void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {} 2260 2261 void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {} 2262 2263 void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {} 2264 2265 void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {} 2266 2267 void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {} 2268 2269 void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {} 2270 2271 void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {} 2272 2273 void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {} 2274 2275 void OMPClauseEnqueue::VisitOMPAcqRelClause(const OMPAcqRelClause *) {} 2276 2277 void OMPClauseEnqueue::VisitOMPAcquireClause(const OMPAcquireClause *) {} 2278 2279 void OMPClauseEnqueue::VisitOMPReleaseClause(const OMPReleaseClause *) {} 2280 2281 void OMPClauseEnqueue::VisitOMPRelaxedClause(const OMPRelaxedClause *) {} 2282 2283 void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {} 2284 2285 void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {} 2286 2287 void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {} 2288 2289 void OMPClauseEnqueue::VisitOMPInitClause(const OMPInitClause *C) { 2290 VisitOMPClauseList(C); 2291 } 2292 2293 void OMPClauseEnqueue::VisitOMPUseClause(const OMPUseClause *C) { 2294 Visitor->AddStmt(C->getInteropVar()); 2295 } 2296 2297 void OMPClauseEnqueue::VisitOMPDestroyClause(const OMPDestroyClause *C) { 2298 if (C->getInteropVar()) 2299 Visitor->AddStmt(C->getInteropVar()); 2300 } 2301 2302 void OMPClauseEnqueue::VisitOMPNovariantsClause(const OMPNovariantsClause *C) { 2303 Visitor->AddStmt(C->getCondition()); 2304 } 2305 2306 void OMPClauseEnqueue::VisitOMPNocontextClause(const OMPNocontextClause *C) { 2307 Visitor->AddStmt(C->getCondition()); 2308 } 2309 2310 void OMPClauseEnqueue::VisitOMPFilterClause(const OMPFilterClause *C) { 2311 VisitOMPClauseWithPreInit(C); 2312 Visitor->AddStmt(C->getThreadID()); 2313 } 2314 2315 void OMPClauseEnqueue::VisitOMPUnifiedAddressClause( 2316 const OMPUnifiedAddressClause *) {} 2317 2318 void OMPClauseEnqueue::VisitOMPUnifiedSharedMemoryClause( 2319 const OMPUnifiedSharedMemoryClause *) {} 2320 2321 void OMPClauseEnqueue::VisitOMPReverseOffloadClause( 2322 const OMPReverseOffloadClause *) {} 2323 2324 void OMPClauseEnqueue::VisitOMPDynamicAllocatorsClause( 2325 const OMPDynamicAllocatorsClause *) {} 2326 2327 void OMPClauseEnqueue::VisitOMPAtomicDefaultMemOrderClause( 2328 const OMPAtomicDefaultMemOrderClause *) {} 2329 2330 void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) { 2331 Visitor->AddStmt(C->getDevice()); 2332 } 2333 2334 void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) { 2335 VisitOMPClauseWithPreInit(C); 2336 Visitor->AddStmt(C->getNumTeams()); 2337 } 2338 2339 void OMPClauseEnqueue::VisitOMPThreadLimitClause( 2340 const OMPThreadLimitClause *C) { 2341 VisitOMPClauseWithPreInit(C); 2342 Visitor->AddStmt(C->getThreadLimit()); 2343 } 2344 2345 void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) { 2346 Visitor->AddStmt(C->getPriority()); 2347 } 2348 2349 void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) { 2350 Visitor->AddStmt(C->getGrainsize()); 2351 } 2352 2353 void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) { 2354 Visitor->AddStmt(C->getNumTasks()); 2355 } 2356 2357 void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) { 2358 Visitor->AddStmt(C->getHint()); 2359 } 2360 2361 template <typename T> void OMPClauseEnqueue::VisitOMPClauseList(T *Node) { 2362 for (const auto *I : Node->varlists()) { 2363 Visitor->AddStmt(I); 2364 } 2365 } 2366 2367 void OMPClauseEnqueue::VisitOMPInclusiveClause(const OMPInclusiveClause *C) { 2368 VisitOMPClauseList(C); 2369 } 2370 void OMPClauseEnqueue::VisitOMPExclusiveClause(const OMPExclusiveClause *C) { 2371 VisitOMPClauseList(C); 2372 } 2373 void OMPClauseEnqueue::VisitOMPAllocateClause(const OMPAllocateClause *C) { 2374 VisitOMPClauseList(C); 2375 Visitor->AddStmt(C->getAllocator()); 2376 } 2377 void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) { 2378 VisitOMPClauseList(C); 2379 for (const auto *E : C->private_copies()) { 2380 Visitor->AddStmt(E); 2381 } 2382 } 2383 void OMPClauseEnqueue::VisitOMPFirstprivateClause( 2384 const OMPFirstprivateClause *C) { 2385 VisitOMPClauseList(C); 2386 VisitOMPClauseWithPreInit(C); 2387 for (const auto *E : C->private_copies()) { 2388 Visitor->AddStmt(E); 2389 } 2390 for (const auto *E : C->inits()) { 2391 Visitor->AddStmt(E); 2392 } 2393 } 2394 void OMPClauseEnqueue::VisitOMPLastprivateClause( 2395 const OMPLastprivateClause *C) { 2396 VisitOMPClauseList(C); 2397 VisitOMPClauseWithPostUpdate(C); 2398 for (auto *E : C->private_copies()) { 2399 Visitor->AddStmt(E); 2400 } 2401 for (auto *E : C->source_exprs()) { 2402 Visitor->AddStmt(E); 2403 } 2404 for (auto *E : C->destination_exprs()) { 2405 Visitor->AddStmt(E); 2406 } 2407 for (auto *E : C->assignment_ops()) { 2408 Visitor->AddStmt(E); 2409 } 2410 } 2411 void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) { 2412 VisitOMPClauseList(C); 2413 } 2414 void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) { 2415 VisitOMPClauseList(C); 2416 VisitOMPClauseWithPostUpdate(C); 2417 for (auto *E : C->privates()) { 2418 Visitor->AddStmt(E); 2419 } 2420 for (auto *E : C->lhs_exprs()) { 2421 Visitor->AddStmt(E); 2422 } 2423 for (auto *E : C->rhs_exprs()) { 2424 Visitor->AddStmt(E); 2425 } 2426 for (auto *E : C->reduction_ops()) { 2427 Visitor->AddStmt(E); 2428 } 2429 if (C->getModifier() == clang::OMPC_REDUCTION_inscan) { 2430 for (auto *E : C->copy_ops()) { 2431 Visitor->AddStmt(E); 2432 } 2433 for (auto *E : C->copy_array_temps()) { 2434 Visitor->AddStmt(E); 2435 } 2436 for (auto *E : C->copy_array_elems()) { 2437 Visitor->AddStmt(E); 2438 } 2439 } 2440 } 2441 void OMPClauseEnqueue::VisitOMPTaskReductionClause( 2442 const OMPTaskReductionClause *C) { 2443 VisitOMPClauseList(C); 2444 VisitOMPClauseWithPostUpdate(C); 2445 for (auto *E : C->privates()) { 2446 Visitor->AddStmt(E); 2447 } 2448 for (auto *E : C->lhs_exprs()) { 2449 Visitor->AddStmt(E); 2450 } 2451 for (auto *E : C->rhs_exprs()) { 2452 Visitor->AddStmt(E); 2453 } 2454 for (auto *E : C->reduction_ops()) { 2455 Visitor->AddStmt(E); 2456 } 2457 } 2458 void OMPClauseEnqueue::VisitOMPInReductionClause( 2459 const OMPInReductionClause *C) { 2460 VisitOMPClauseList(C); 2461 VisitOMPClauseWithPostUpdate(C); 2462 for (auto *E : C->privates()) { 2463 Visitor->AddStmt(E); 2464 } 2465 for (auto *E : C->lhs_exprs()) { 2466 Visitor->AddStmt(E); 2467 } 2468 for (auto *E : C->rhs_exprs()) { 2469 Visitor->AddStmt(E); 2470 } 2471 for (auto *E : C->reduction_ops()) { 2472 Visitor->AddStmt(E); 2473 } 2474 for (auto *E : C->taskgroup_descriptors()) 2475 Visitor->AddStmt(E); 2476 } 2477 void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) { 2478 VisitOMPClauseList(C); 2479 VisitOMPClauseWithPostUpdate(C); 2480 for (const auto *E : C->privates()) { 2481 Visitor->AddStmt(E); 2482 } 2483 for (const auto *E : C->inits()) { 2484 Visitor->AddStmt(E); 2485 } 2486 for (const auto *E : C->updates()) { 2487 Visitor->AddStmt(E); 2488 } 2489 for (const auto *E : C->finals()) { 2490 Visitor->AddStmt(E); 2491 } 2492 Visitor->AddStmt(C->getStep()); 2493 Visitor->AddStmt(C->getCalcStep()); 2494 } 2495 void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) { 2496 VisitOMPClauseList(C); 2497 Visitor->AddStmt(C->getAlignment()); 2498 } 2499 void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) { 2500 VisitOMPClauseList(C); 2501 for (auto *E : C->source_exprs()) { 2502 Visitor->AddStmt(E); 2503 } 2504 for (auto *E : C->destination_exprs()) { 2505 Visitor->AddStmt(E); 2506 } 2507 for (auto *E : C->assignment_ops()) { 2508 Visitor->AddStmt(E); 2509 } 2510 } 2511 void OMPClauseEnqueue::VisitOMPCopyprivateClause( 2512 const OMPCopyprivateClause *C) { 2513 VisitOMPClauseList(C); 2514 for (auto *E : C->source_exprs()) { 2515 Visitor->AddStmt(E); 2516 } 2517 for (auto *E : C->destination_exprs()) { 2518 Visitor->AddStmt(E); 2519 } 2520 for (auto *E : C->assignment_ops()) { 2521 Visitor->AddStmt(E); 2522 } 2523 } 2524 void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) { 2525 VisitOMPClauseList(C); 2526 } 2527 void OMPClauseEnqueue::VisitOMPDepobjClause(const OMPDepobjClause *C) { 2528 Visitor->AddStmt(C->getDepobj()); 2529 } 2530 void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) { 2531 VisitOMPClauseList(C); 2532 } 2533 void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) { 2534 VisitOMPClauseList(C); 2535 } 2536 void OMPClauseEnqueue::VisitOMPDistScheduleClause( 2537 const OMPDistScheduleClause *C) { 2538 VisitOMPClauseWithPreInit(C); 2539 Visitor->AddStmt(C->getChunkSize()); 2540 } 2541 void OMPClauseEnqueue::VisitOMPDefaultmapClause( 2542 const OMPDefaultmapClause * /*C*/) {} 2543 void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) { 2544 VisitOMPClauseList(C); 2545 } 2546 void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) { 2547 VisitOMPClauseList(C); 2548 } 2549 void OMPClauseEnqueue::VisitOMPUseDevicePtrClause( 2550 const OMPUseDevicePtrClause *C) { 2551 VisitOMPClauseList(C); 2552 } 2553 void OMPClauseEnqueue::VisitOMPUseDeviceAddrClause( 2554 const OMPUseDeviceAddrClause *C) { 2555 VisitOMPClauseList(C); 2556 } 2557 void OMPClauseEnqueue::VisitOMPIsDevicePtrClause( 2558 const OMPIsDevicePtrClause *C) { 2559 VisitOMPClauseList(C); 2560 } 2561 void OMPClauseEnqueue::VisitOMPNontemporalClause( 2562 const OMPNontemporalClause *C) { 2563 VisitOMPClauseList(C); 2564 for (const auto *E : C->private_refs()) 2565 Visitor->AddStmt(E); 2566 } 2567 void OMPClauseEnqueue::VisitOMPOrderClause(const OMPOrderClause *C) {} 2568 void OMPClauseEnqueue::VisitOMPUsesAllocatorsClause( 2569 const OMPUsesAllocatorsClause *C) { 2570 for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) { 2571 const OMPUsesAllocatorsClause::Data &D = C->getAllocatorData(I); 2572 Visitor->AddStmt(D.Allocator); 2573 Visitor->AddStmt(D.AllocatorTraits); 2574 } 2575 } 2576 void OMPClauseEnqueue::VisitOMPAffinityClause(const OMPAffinityClause *C) { 2577 Visitor->AddStmt(C->getModifier()); 2578 for (const Expr *E : C->varlists()) 2579 Visitor->AddStmt(E); 2580 } 2581 } // namespace 2582 2583 void EnqueueVisitor::EnqueueChildren(const OMPClause *S) { 2584 unsigned size = WL.size(); 2585 OMPClauseEnqueue Visitor(this); 2586 Visitor.Visit(S); 2587 if (size == WL.size()) 2588 return; 2589 // Now reverse the entries we just added. This will match the DFS 2590 // ordering performed by the worklist. 2591 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end(); 2592 std::reverse(I, E); 2593 } 2594 void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) { 2595 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent)); 2596 } 2597 void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) { 2598 AddDecl(B->getBlockDecl()); 2599 } 2600 void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 2601 EnqueueChildren(E); 2602 AddTypeLoc(E->getTypeSourceInfo()); 2603 } 2604 void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) { 2605 for (auto &I : llvm::reverse(S->body())) 2606 AddStmt(I); 2607 } 2608 void EnqueueVisitor::VisitMSDependentExistsStmt( 2609 const MSDependentExistsStmt *S) { 2610 AddStmt(S->getSubStmt()); 2611 AddDeclarationNameInfo(S); 2612 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc()) 2613 AddNestedNameSpecifierLoc(QualifierLoc); 2614 } 2615 2616 void EnqueueVisitor::VisitCXXDependentScopeMemberExpr( 2617 const CXXDependentScopeMemberExpr *E) { 2618 if (E->hasExplicitTemplateArgs()) 2619 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs()); 2620 AddDeclarationNameInfo(E); 2621 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc()) 2622 AddNestedNameSpecifierLoc(QualifierLoc); 2623 if (!E->isImplicitAccess()) 2624 AddStmt(E->getBase()); 2625 } 2626 void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) { 2627 // Enqueue the initializer , if any. 2628 AddStmt(E->getInitializer()); 2629 // Enqueue the array size, if any. 2630 AddStmt(E->getArraySize().getValueOr(nullptr)); 2631 // Enqueue the allocated type. 2632 AddTypeLoc(E->getAllocatedTypeSourceInfo()); 2633 // Enqueue the placement arguments. 2634 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I) 2635 AddStmt(E->getPlacementArg(I - 1)); 2636 } 2637 void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) { 2638 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I) 2639 AddStmt(CE->getArg(I - 1)); 2640 AddStmt(CE->getCallee()); 2641 AddStmt(CE->getArg(0)); 2642 } 2643 void EnqueueVisitor::VisitCXXPseudoDestructorExpr( 2644 const CXXPseudoDestructorExpr *E) { 2645 // Visit the name of the type being destroyed. 2646 AddTypeLoc(E->getDestroyedTypeInfo()); 2647 // Visit the scope type that looks disturbingly like the nested-name-specifier 2648 // but isn't. 2649 AddTypeLoc(E->getScopeTypeInfo()); 2650 // Visit the nested-name-specifier. 2651 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc()) 2652 AddNestedNameSpecifierLoc(QualifierLoc); 2653 // Visit base expression. 2654 AddStmt(E->getBase()); 2655 } 2656 void EnqueueVisitor::VisitCXXScalarValueInitExpr( 2657 const CXXScalarValueInitExpr *E) { 2658 AddTypeLoc(E->getTypeSourceInfo()); 2659 } 2660 void EnqueueVisitor::VisitCXXTemporaryObjectExpr( 2661 const CXXTemporaryObjectExpr *E) { 2662 EnqueueChildren(E); 2663 AddTypeLoc(E->getTypeSourceInfo()); 2664 } 2665 void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 2666 EnqueueChildren(E); 2667 if (E->isTypeOperand()) 2668 AddTypeLoc(E->getTypeOperandSourceInfo()); 2669 } 2670 2671 void EnqueueVisitor::VisitCXXUnresolvedConstructExpr( 2672 const CXXUnresolvedConstructExpr *E) { 2673 EnqueueChildren(E); 2674 AddTypeLoc(E->getTypeSourceInfo()); 2675 } 2676 void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 2677 EnqueueChildren(E); 2678 if (E->isTypeOperand()) 2679 AddTypeLoc(E->getTypeOperandSourceInfo()); 2680 } 2681 2682 void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) { 2683 EnqueueChildren(S); 2684 AddDecl(S->getExceptionDecl()); 2685 } 2686 2687 void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) { 2688 AddStmt(S->getBody()); 2689 AddStmt(S->getRangeInit()); 2690 AddDecl(S->getLoopVariable()); 2691 } 2692 2693 void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) { 2694 if (DR->hasExplicitTemplateArgs()) 2695 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs()); 2696 WL.push_back(DeclRefExprParts(DR, Parent)); 2697 } 2698 void EnqueueVisitor::VisitDependentScopeDeclRefExpr( 2699 const DependentScopeDeclRefExpr *E) { 2700 if (E->hasExplicitTemplateArgs()) 2701 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs()); 2702 AddDeclarationNameInfo(E); 2703 AddNestedNameSpecifierLoc(E->getQualifierLoc()); 2704 } 2705 void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) { 2706 unsigned size = WL.size(); 2707 bool isFirst = true; 2708 for (const auto *D : S->decls()) { 2709 AddDecl(D, isFirst); 2710 isFirst = false; 2711 } 2712 if (size == WL.size()) 2713 return; 2714 // Now reverse the entries we just added. This will match the DFS 2715 // ordering performed by the worklist. 2716 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end(); 2717 std::reverse(I, E); 2718 } 2719 void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) { 2720 AddStmt(E->getInit()); 2721 for (const DesignatedInitExpr::Designator &D : 2722 llvm::reverse(E->designators())) { 2723 if (D.isFieldDesignator()) { 2724 if (FieldDecl *Field = D.getField()) 2725 AddMemberRef(Field, D.getFieldLoc()); 2726 continue; 2727 } 2728 if (D.isArrayDesignator()) { 2729 AddStmt(E->getArrayIndex(D)); 2730 continue; 2731 } 2732 assert(D.isArrayRangeDesignator() && "Unknown designator kind"); 2733 AddStmt(E->getArrayRangeEnd(D)); 2734 AddStmt(E->getArrayRangeStart(D)); 2735 } 2736 } 2737 void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) { 2738 EnqueueChildren(E); 2739 AddTypeLoc(E->getTypeInfoAsWritten()); 2740 } 2741 void EnqueueVisitor::VisitForStmt(const ForStmt *FS) { 2742 AddStmt(FS->getBody()); 2743 AddStmt(FS->getInc()); 2744 AddStmt(FS->getCond()); 2745 AddDecl(FS->getConditionVariable()); 2746 AddStmt(FS->getInit()); 2747 } 2748 void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) { 2749 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent)); 2750 } 2751 void EnqueueVisitor::VisitIfStmt(const IfStmt *If) { 2752 AddStmt(If->getElse()); 2753 AddStmt(If->getThen()); 2754 AddStmt(If->getCond()); 2755 AddStmt(If->getInit()); 2756 AddDecl(If->getConditionVariable()); 2757 } 2758 void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) { 2759 // We care about the syntactic form of the initializer list, only. 2760 if (InitListExpr *Syntactic = IE->getSyntacticForm()) 2761 IE = Syntactic; 2762 EnqueueChildren(IE); 2763 } 2764 void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) { 2765 WL.push_back(MemberExprParts(M, Parent)); 2766 2767 // If the base of the member access expression is an implicit 'this', don't 2768 // visit it. 2769 // FIXME: If we ever want to show these implicit accesses, this will be 2770 // unfortunate. However, clang_getCursor() relies on this behavior. 2771 if (M->isImplicitAccess()) 2772 return; 2773 2774 // Ignore base anonymous struct/union fields, otherwise they will shadow the 2775 // real field that we are interested in. 2776 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) { 2777 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) { 2778 if (FD->isAnonymousStructOrUnion()) { 2779 AddStmt(SubME->getBase()); 2780 return; 2781 } 2782 } 2783 } 2784 2785 AddStmt(M->getBase()); 2786 } 2787 void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { 2788 AddTypeLoc(E->getEncodedTypeSourceInfo()); 2789 } 2790 void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) { 2791 EnqueueChildren(M); 2792 AddTypeLoc(M->getClassReceiverTypeInfo()); 2793 } 2794 void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) { 2795 // Visit the components of the offsetof expression. 2796 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) { 2797 const OffsetOfNode &Node = E->getComponent(I - 1); 2798 switch (Node.getKind()) { 2799 case OffsetOfNode::Array: 2800 AddStmt(E->getIndexExpr(Node.getArrayExprIndex())); 2801 break; 2802 case OffsetOfNode::Field: 2803 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd()); 2804 break; 2805 case OffsetOfNode::Identifier: 2806 case OffsetOfNode::Base: 2807 continue; 2808 } 2809 } 2810 // Visit the type into which we're computing the offset. 2811 AddTypeLoc(E->getTypeSourceInfo()); 2812 } 2813 void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) { 2814 if (E->hasExplicitTemplateArgs()) 2815 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs()); 2816 WL.push_back(OverloadExprParts(E, Parent)); 2817 } 2818 void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr( 2819 const UnaryExprOrTypeTraitExpr *E) { 2820 EnqueueChildren(E); 2821 if (E->isArgumentType()) 2822 AddTypeLoc(E->getArgumentTypeInfo()); 2823 } 2824 void EnqueueVisitor::VisitStmt(const Stmt *S) { EnqueueChildren(S); } 2825 void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) { 2826 AddStmt(S->getBody()); 2827 AddStmt(S->getCond()); 2828 AddDecl(S->getConditionVariable()); 2829 } 2830 2831 void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) { 2832 AddStmt(W->getBody()); 2833 AddStmt(W->getCond()); 2834 AddDecl(W->getConditionVariable()); 2835 } 2836 2837 void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) { 2838 for (unsigned I = E->getNumArgs(); I > 0; --I) 2839 AddTypeLoc(E->getArg(I - 1)); 2840 } 2841 2842 void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 2843 AddTypeLoc(E->getQueriedTypeSourceInfo()); 2844 } 2845 2846 void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 2847 EnqueueChildren(E); 2848 } 2849 2850 void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) { 2851 VisitOverloadExpr(U); 2852 if (!U->isImplicitAccess()) 2853 AddStmt(U->getBase()); 2854 } 2855 void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) { 2856 AddStmt(E->getSubExpr()); 2857 AddTypeLoc(E->getWrittenTypeInfo()); 2858 } 2859 void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 2860 WL.push_back(SizeOfPackExprParts(E, Parent)); 2861 } 2862 void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 2863 // If the opaque value has a source expression, just transparently 2864 // visit that. This is useful for (e.g.) pseudo-object expressions. 2865 if (Expr *SourceExpr = E->getSourceExpr()) 2866 return Visit(SourceExpr); 2867 } 2868 void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) { 2869 AddStmt(E->getBody()); 2870 WL.push_back(LambdaExprParts(E, Parent)); 2871 } 2872 void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) { 2873 // Treat the expression like its syntactic form. 2874 Visit(E->getSyntacticForm()); 2875 } 2876 2877 void EnqueueVisitor::VisitOMPExecutableDirective( 2878 const OMPExecutableDirective *D) { 2879 EnqueueChildren(D); 2880 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(), 2881 E = D->clauses().end(); 2882 I != E; ++I) 2883 EnqueueChildren(*I); 2884 } 2885 2886 void EnqueueVisitor::VisitOMPLoopBasedDirective( 2887 const OMPLoopBasedDirective *D) { 2888 VisitOMPExecutableDirective(D); 2889 } 2890 2891 void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) { 2892 VisitOMPLoopBasedDirective(D); 2893 } 2894 2895 void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) { 2896 VisitOMPExecutableDirective(D); 2897 } 2898 2899 void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) { 2900 VisitOMPLoopDirective(D); 2901 } 2902 2903 void EnqueueVisitor::VisitOMPTileDirective(const OMPTileDirective *D) { 2904 VisitOMPLoopBasedDirective(D); 2905 } 2906 2907 void EnqueueVisitor::VisitOMPUnrollDirective(const OMPUnrollDirective *D) { 2908 VisitOMPLoopBasedDirective(D); 2909 } 2910 2911 void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) { 2912 VisitOMPLoopDirective(D); 2913 } 2914 2915 void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) { 2916 VisitOMPLoopDirective(D); 2917 } 2918 2919 void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) { 2920 VisitOMPExecutableDirective(D); 2921 } 2922 2923 void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) { 2924 VisitOMPExecutableDirective(D); 2925 } 2926 2927 void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) { 2928 VisitOMPExecutableDirective(D); 2929 } 2930 2931 void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) { 2932 VisitOMPExecutableDirective(D); 2933 } 2934 2935 void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) { 2936 VisitOMPExecutableDirective(D); 2937 AddDeclarationNameInfo(D); 2938 } 2939 2940 void EnqueueVisitor::VisitOMPParallelForDirective( 2941 const OMPParallelForDirective *D) { 2942 VisitOMPLoopDirective(D); 2943 } 2944 2945 void EnqueueVisitor::VisitOMPParallelForSimdDirective( 2946 const OMPParallelForSimdDirective *D) { 2947 VisitOMPLoopDirective(D); 2948 } 2949 2950 void EnqueueVisitor::VisitOMPParallelMasterDirective( 2951 const OMPParallelMasterDirective *D) { 2952 VisitOMPExecutableDirective(D); 2953 } 2954 2955 void EnqueueVisitor::VisitOMPParallelSectionsDirective( 2956 const OMPParallelSectionsDirective *D) { 2957 VisitOMPExecutableDirective(D); 2958 } 2959 2960 void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) { 2961 VisitOMPExecutableDirective(D); 2962 } 2963 2964 void EnqueueVisitor::VisitOMPTaskyieldDirective( 2965 const OMPTaskyieldDirective *D) { 2966 VisitOMPExecutableDirective(D); 2967 } 2968 2969 void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) { 2970 VisitOMPExecutableDirective(D); 2971 } 2972 2973 void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) { 2974 VisitOMPExecutableDirective(D); 2975 } 2976 2977 void EnqueueVisitor::VisitOMPTaskgroupDirective( 2978 const OMPTaskgroupDirective *D) { 2979 VisitOMPExecutableDirective(D); 2980 if (const Expr *E = D->getReductionRef()) 2981 VisitStmt(E); 2982 } 2983 2984 void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) { 2985 VisitOMPExecutableDirective(D); 2986 } 2987 2988 void EnqueueVisitor::VisitOMPDepobjDirective(const OMPDepobjDirective *D) { 2989 VisitOMPExecutableDirective(D); 2990 } 2991 2992 void EnqueueVisitor::VisitOMPScanDirective(const OMPScanDirective *D) { 2993 VisitOMPExecutableDirective(D); 2994 } 2995 2996 void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) { 2997 VisitOMPExecutableDirective(D); 2998 } 2999 3000 void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) { 3001 VisitOMPExecutableDirective(D); 3002 } 3003 3004 void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) { 3005 VisitOMPExecutableDirective(D); 3006 } 3007 3008 void EnqueueVisitor::VisitOMPTargetDataDirective( 3009 const OMPTargetDataDirective *D) { 3010 VisitOMPExecutableDirective(D); 3011 } 3012 3013 void EnqueueVisitor::VisitOMPTargetEnterDataDirective( 3014 const OMPTargetEnterDataDirective *D) { 3015 VisitOMPExecutableDirective(D); 3016 } 3017 3018 void EnqueueVisitor::VisitOMPTargetExitDataDirective( 3019 const OMPTargetExitDataDirective *D) { 3020 VisitOMPExecutableDirective(D); 3021 } 3022 3023 void EnqueueVisitor::VisitOMPTargetParallelDirective( 3024 const OMPTargetParallelDirective *D) { 3025 VisitOMPExecutableDirective(D); 3026 } 3027 3028 void EnqueueVisitor::VisitOMPTargetParallelForDirective( 3029 const OMPTargetParallelForDirective *D) { 3030 VisitOMPLoopDirective(D); 3031 } 3032 3033 void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) { 3034 VisitOMPExecutableDirective(D); 3035 } 3036 3037 void EnqueueVisitor::VisitOMPCancellationPointDirective( 3038 const OMPCancellationPointDirective *D) { 3039 VisitOMPExecutableDirective(D); 3040 } 3041 3042 void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) { 3043 VisitOMPExecutableDirective(D); 3044 } 3045 3046 void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) { 3047 VisitOMPLoopDirective(D); 3048 } 3049 3050 void EnqueueVisitor::VisitOMPTaskLoopSimdDirective( 3051 const OMPTaskLoopSimdDirective *D) { 3052 VisitOMPLoopDirective(D); 3053 } 3054 3055 void EnqueueVisitor::VisitOMPMasterTaskLoopDirective( 3056 const OMPMasterTaskLoopDirective *D) { 3057 VisitOMPLoopDirective(D); 3058 } 3059 3060 void EnqueueVisitor::VisitOMPMasterTaskLoopSimdDirective( 3061 const OMPMasterTaskLoopSimdDirective *D) { 3062 VisitOMPLoopDirective(D); 3063 } 3064 3065 void EnqueueVisitor::VisitOMPParallelMasterTaskLoopDirective( 3066 const OMPParallelMasterTaskLoopDirective *D) { 3067 VisitOMPLoopDirective(D); 3068 } 3069 3070 void EnqueueVisitor::VisitOMPParallelMasterTaskLoopSimdDirective( 3071 const OMPParallelMasterTaskLoopSimdDirective *D) { 3072 VisitOMPLoopDirective(D); 3073 } 3074 3075 void EnqueueVisitor::VisitOMPDistributeDirective( 3076 const OMPDistributeDirective *D) { 3077 VisitOMPLoopDirective(D); 3078 } 3079 3080 void EnqueueVisitor::VisitOMPDistributeParallelForDirective( 3081 const OMPDistributeParallelForDirective *D) { 3082 VisitOMPLoopDirective(D); 3083 } 3084 3085 void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective( 3086 const OMPDistributeParallelForSimdDirective *D) { 3087 VisitOMPLoopDirective(D); 3088 } 3089 3090 void EnqueueVisitor::VisitOMPDistributeSimdDirective( 3091 const OMPDistributeSimdDirective *D) { 3092 VisitOMPLoopDirective(D); 3093 } 3094 3095 void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective( 3096 const OMPTargetParallelForSimdDirective *D) { 3097 VisitOMPLoopDirective(D); 3098 } 3099 3100 void EnqueueVisitor::VisitOMPTargetSimdDirective( 3101 const OMPTargetSimdDirective *D) { 3102 VisitOMPLoopDirective(D); 3103 } 3104 3105 void EnqueueVisitor::VisitOMPTeamsDistributeDirective( 3106 const OMPTeamsDistributeDirective *D) { 3107 VisitOMPLoopDirective(D); 3108 } 3109 3110 void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective( 3111 const OMPTeamsDistributeSimdDirective *D) { 3112 VisitOMPLoopDirective(D); 3113 } 3114 3115 void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective( 3116 const OMPTeamsDistributeParallelForSimdDirective *D) { 3117 VisitOMPLoopDirective(D); 3118 } 3119 3120 void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective( 3121 const OMPTeamsDistributeParallelForDirective *D) { 3122 VisitOMPLoopDirective(D); 3123 } 3124 3125 void EnqueueVisitor::VisitOMPTargetTeamsDirective( 3126 const OMPTargetTeamsDirective *D) { 3127 VisitOMPExecutableDirective(D); 3128 } 3129 3130 void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective( 3131 const OMPTargetTeamsDistributeDirective *D) { 3132 VisitOMPLoopDirective(D); 3133 } 3134 3135 void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective( 3136 const OMPTargetTeamsDistributeParallelForDirective *D) { 3137 VisitOMPLoopDirective(D); 3138 } 3139 3140 void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective( 3141 const OMPTargetTeamsDistributeParallelForSimdDirective *D) { 3142 VisitOMPLoopDirective(D); 3143 } 3144 3145 void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective( 3146 const OMPTargetTeamsDistributeSimdDirective *D) { 3147 VisitOMPLoopDirective(D); 3148 } 3149 3150 void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) { 3151 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU, RegionOfInterest)) 3152 .Visit(S); 3153 } 3154 3155 bool CursorVisitor::IsInRegionOfInterest(CXCursor C) { 3156 if (RegionOfInterest.isValid()) { 3157 SourceRange Range = getRawCursorExtent(C); 3158 if (Range.isInvalid() || CompareRegionOfInterest(Range)) 3159 return false; 3160 } 3161 return true; 3162 } 3163 3164 bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) { 3165 while (!WL.empty()) { 3166 // Dequeue the worklist item. 3167 VisitorJob LI = WL.pop_back_val(); 3168 3169 // Set the Parent field, then back to its old value once we're done. 3170 SetParentRAII SetParent(Parent, StmtParent, LI.getParent()); 3171 3172 switch (LI.getKind()) { 3173 case VisitorJob::DeclVisitKind: { 3174 const Decl *D = cast<DeclVisit>(&LI)->get(); 3175 if (!D) 3176 continue; 3177 3178 // For now, perform default visitation for Decls. 3179 if (Visit(MakeCXCursor(D, TU, RegionOfInterest, 3180 cast<DeclVisit>(&LI)->isFirst()))) 3181 return true; 3182 3183 continue; 3184 } 3185 case VisitorJob::ExplicitTemplateArgsVisitKind: { 3186 for (const TemplateArgumentLoc &Arg : 3187 *cast<ExplicitTemplateArgsVisit>(&LI)) { 3188 if (VisitTemplateArgumentLoc(Arg)) 3189 return true; 3190 } 3191 continue; 3192 } 3193 case VisitorJob::TypeLocVisitKind: { 3194 // Perform default visitation for TypeLocs. 3195 if (Visit(cast<TypeLocVisit>(&LI)->get())) 3196 return true; 3197 continue; 3198 } 3199 case VisitorJob::LabelRefVisitKind: { 3200 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get(); 3201 if (LabelStmt *stmt = LS->getStmt()) { 3202 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(), 3203 TU))) { 3204 return true; 3205 } 3206 } 3207 continue; 3208 } 3209 3210 case VisitorJob::NestedNameSpecifierLocVisitKind: { 3211 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI); 3212 if (VisitNestedNameSpecifierLoc(V->get())) 3213 return true; 3214 continue; 3215 } 3216 3217 case VisitorJob::DeclarationNameInfoVisitKind: { 3218 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)->get())) 3219 return true; 3220 continue; 3221 } 3222 case VisitorJob::MemberRefVisitKind: { 3223 MemberRefVisit *V = cast<MemberRefVisit>(&LI); 3224 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU))) 3225 return true; 3226 continue; 3227 } 3228 case VisitorJob::StmtVisitKind: { 3229 const Stmt *S = cast<StmtVisit>(&LI)->get(); 3230 if (!S) 3231 continue; 3232 3233 // Update the current cursor. 3234 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest); 3235 if (!IsInRegionOfInterest(Cursor)) 3236 continue; 3237 switch (Visitor(Cursor, Parent, ClientData)) { 3238 case CXChildVisit_Break: 3239 return true; 3240 case CXChildVisit_Continue: 3241 break; 3242 case CXChildVisit_Recurse: 3243 if (PostChildrenVisitor) 3244 WL.push_back(PostChildrenVisit(nullptr, Cursor)); 3245 EnqueueWorkList(WL, S); 3246 break; 3247 } 3248 continue; 3249 } 3250 case VisitorJob::MemberExprPartsKind: { 3251 // Handle the other pieces in the MemberExpr besides the base. 3252 const MemberExpr *M = cast<MemberExprParts>(&LI)->get(); 3253 3254 // Visit the nested-name-specifier 3255 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc()) 3256 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 3257 return true; 3258 3259 // Visit the declaration name. 3260 if (VisitDeclarationNameInfo(M->getMemberNameInfo())) 3261 return true; 3262 3263 // Visit the explicitly-specified template arguments, if any. 3264 if (M->hasExplicitTemplateArgs()) { 3265 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(), 3266 *ArgEnd = Arg + M->getNumTemplateArgs(); 3267 Arg != ArgEnd; ++Arg) { 3268 if (VisitTemplateArgumentLoc(*Arg)) 3269 return true; 3270 } 3271 } 3272 continue; 3273 } 3274 case VisitorJob::DeclRefExprPartsKind: { 3275 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get(); 3276 // Visit nested-name-specifier, if present. 3277 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc()) 3278 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 3279 return true; 3280 // Visit declaration name. 3281 if (VisitDeclarationNameInfo(DR->getNameInfo())) 3282 return true; 3283 continue; 3284 } 3285 case VisitorJob::OverloadExprPartsKind: { 3286 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get(); 3287 // Visit the nested-name-specifier. 3288 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc()) 3289 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 3290 return true; 3291 // Visit the declaration name. 3292 if (VisitDeclarationNameInfo(O->getNameInfo())) 3293 return true; 3294 // Visit the overloaded declaration reference. 3295 if (Visit(MakeCursorOverloadedDeclRef(O, TU))) 3296 return true; 3297 continue; 3298 } 3299 case VisitorJob::SizeOfPackExprPartsKind: { 3300 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get(); 3301 NamedDecl *Pack = E->getPack(); 3302 if (isa<TemplateTypeParmDecl>(Pack)) { 3303 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack), 3304 E->getPackLoc(), TU))) 3305 return true; 3306 3307 continue; 3308 } 3309 3310 if (isa<TemplateTemplateParmDecl>(Pack)) { 3311 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack), 3312 E->getPackLoc(), TU))) 3313 return true; 3314 3315 continue; 3316 } 3317 3318 // Non-type template parameter packs and function parameter packs are 3319 // treated like DeclRefExpr cursors. 3320 continue; 3321 } 3322 3323 case VisitorJob::LambdaExprPartsKind: { 3324 // Visit non-init captures. 3325 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get(); 3326 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(), 3327 CEnd = E->explicit_capture_end(); 3328 C != CEnd; ++C) { 3329 if (!C->capturesVariable()) 3330 continue; 3331 3332 if (Visit(MakeCursorVariableRef(C->getCapturedVar(), C->getLocation(), 3333 TU))) 3334 return true; 3335 } 3336 // Visit init captures 3337 for (auto InitExpr : E->capture_inits()) { 3338 if (InitExpr && Visit(InitExpr)) 3339 return true; 3340 } 3341 3342 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc(); 3343 // Visit parameters and return type, if present. 3344 if (FunctionTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) { 3345 if (E->hasExplicitParameters()) { 3346 // Visit parameters. 3347 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I) 3348 if (Visit(MakeCXCursor(Proto.getParam(I), TU))) 3349 return true; 3350 } 3351 if (E->hasExplicitResultType()) { 3352 // Visit result type. 3353 if (Visit(Proto.getReturnLoc())) 3354 return true; 3355 } 3356 } 3357 break; 3358 } 3359 3360 case VisitorJob::PostChildrenVisitKind: 3361 if (PostChildrenVisitor(Parent, ClientData)) 3362 return true; 3363 break; 3364 } 3365 } 3366 return false; 3367 } 3368 3369 bool CursorVisitor::Visit(const Stmt *S) { 3370 VisitorWorkList *WL = nullptr; 3371 if (!WorkListFreeList.empty()) { 3372 WL = WorkListFreeList.back(); 3373 WL->clear(); 3374 WorkListFreeList.pop_back(); 3375 } else { 3376 WL = new VisitorWorkList(); 3377 WorkListCache.push_back(WL); 3378 } 3379 EnqueueWorkList(*WL, S); 3380 bool result = RunVisitorWorkList(*WL); 3381 WorkListFreeList.push_back(WL); 3382 return result; 3383 } 3384 3385 namespace { 3386 typedef SmallVector<SourceRange, 4> RefNamePieces; 3387 RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr, 3388 const DeclarationNameInfo &NI, SourceRange QLoc, 3389 const SourceRange *TemplateArgsLoc = nullptr) { 3390 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier; 3391 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs; 3392 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece; 3393 3394 const DeclarationName::NameKind Kind = NI.getName().getNameKind(); 3395 3396 RefNamePieces Pieces; 3397 3398 if (WantQualifier && QLoc.isValid()) 3399 Pieces.push_back(QLoc); 3400 3401 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr) 3402 Pieces.push_back(NI.getLoc()); 3403 3404 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid()) 3405 Pieces.push_back(*TemplateArgsLoc); 3406 3407 if (Kind == DeclarationName::CXXOperatorName) { 3408 Pieces.push_back(NI.getInfo().getCXXOperatorNameBeginLoc()); 3409 Pieces.push_back(NI.getInfo().getCXXOperatorNameEndLoc()); 3410 } 3411 3412 if (WantSinglePiece) { 3413 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd()); 3414 Pieces.clear(); 3415 Pieces.push_back(R); 3416 } 3417 3418 return Pieces; 3419 } 3420 } // namespace 3421 3422 //===----------------------------------------------------------------------===// 3423 // Misc. API hooks. 3424 //===----------------------------------------------------------------------===// 3425 3426 namespace { 3427 struct RegisterFatalErrorHandler { 3428 RegisterFatalErrorHandler() { 3429 clang_install_aborting_llvm_fatal_error_handler(); 3430 } 3431 }; 3432 } // namespace 3433 3434 static llvm::ManagedStatic<RegisterFatalErrorHandler> 3435 RegisterFatalErrorHandlerOnce; 3436 3437 CXIndex clang_createIndex(int excludeDeclarationsFromPCH, 3438 int displayDiagnostics) { 3439 // We use crash recovery to make some of our APIs more reliable, implicitly 3440 // enable it. 3441 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY")) 3442 llvm::CrashRecoveryContext::Enable(); 3443 3444 // Look through the managed static to trigger construction of the managed 3445 // static which registers our fatal error handler. This ensures it is only 3446 // registered once. 3447 (void)*RegisterFatalErrorHandlerOnce; 3448 3449 // Initialize targets for clang module support. 3450 llvm::InitializeAllTargets(); 3451 llvm::InitializeAllTargetMCs(); 3452 llvm::InitializeAllAsmPrinters(); 3453 llvm::InitializeAllAsmParsers(); 3454 3455 CIndexer *CIdxr = new CIndexer(); 3456 3457 if (excludeDeclarationsFromPCH) 3458 CIdxr->setOnlyLocalDecls(); 3459 if (displayDiagnostics) 3460 CIdxr->setDisplayDiagnostics(); 3461 3462 if (getenv("LIBCLANG_BGPRIO_INDEX")) 3463 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() | 3464 CXGlobalOpt_ThreadBackgroundPriorityForIndexing); 3465 if (getenv("LIBCLANG_BGPRIO_EDIT")) 3466 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() | 3467 CXGlobalOpt_ThreadBackgroundPriorityForEditing); 3468 3469 return CIdxr; 3470 } 3471 3472 void clang_disposeIndex(CXIndex CIdx) { 3473 if (CIdx) 3474 delete static_cast<CIndexer *>(CIdx); 3475 } 3476 3477 void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) { 3478 if (CIdx) 3479 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options); 3480 } 3481 3482 unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) { 3483 if (CIdx) 3484 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags(); 3485 return 0; 3486 } 3487 3488 void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx, 3489 const char *Path) { 3490 if (CIdx) 3491 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : ""); 3492 } 3493 3494 void clang_toggleCrashRecovery(unsigned isEnabled) { 3495 if (isEnabled) 3496 llvm::CrashRecoveryContext::Enable(); 3497 else 3498 llvm::CrashRecoveryContext::Disable(); 3499 } 3500 3501 CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx, 3502 const char *ast_filename) { 3503 CXTranslationUnit TU; 3504 enum CXErrorCode Result = 3505 clang_createTranslationUnit2(CIdx, ast_filename, &TU); 3506 (void)Result; 3507 assert((TU && Result == CXError_Success) || 3508 (!TU && Result != CXError_Success)); 3509 return TU; 3510 } 3511 3512 enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx, 3513 const char *ast_filename, 3514 CXTranslationUnit *out_TU) { 3515 if (out_TU) 3516 *out_TU = nullptr; 3517 3518 if (!CIdx || !ast_filename || !out_TU) 3519 return CXError_InvalidArguments; 3520 3521 LOG_FUNC_SECTION { *Log << ast_filename; } 3522 3523 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx); 3524 FileSystemOptions FileSystemOpts; 3525 3526 IntrusiveRefCntPtr<DiagnosticsEngine> Diags = 3527 CompilerInstance::createDiagnostics(new DiagnosticOptions()); 3528 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile( 3529 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(), 3530 ASTUnit::LoadEverything, Diags, FileSystemOpts, /*UseDebugInfo=*/false, 3531 CXXIdx->getOnlyLocalDecls(), CaptureDiagsKind::All, 3532 /*AllowASTWithCompilerErrors=*/true, 3533 /*UserFilesAreVolatile=*/true); 3534 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU)); 3535 return *out_TU ? CXError_Success : CXError_Failure; 3536 } 3537 3538 unsigned clang_defaultEditingTranslationUnitOptions() { 3539 return CXTranslationUnit_PrecompiledPreamble | 3540 CXTranslationUnit_CacheCompletionResults; 3541 } 3542 3543 CXTranslationUnit clang_createTranslationUnitFromSourceFile( 3544 CXIndex CIdx, const char *source_filename, int num_command_line_args, 3545 const char *const *command_line_args, unsigned num_unsaved_files, 3546 struct CXUnsavedFile *unsaved_files) { 3547 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord; 3548 return clang_parseTranslationUnit(CIdx, source_filename, command_line_args, 3549 num_command_line_args, unsaved_files, 3550 num_unsaved_files, Options); 3551 } 3552 3553 static CXErrorCode 3554 clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename, 3555 const char *const *command_line_args, 3556 int num_command_line_args, 3557 ArrayRef<CXUnsavedFile> unsaved_files, 3558 unsigned options, CXTranslationUnit *out_TU) { 3559 // Set up the initial return values. 3560 if (out_TU) 3561 *out_TU = nullptr; 3562 3563 // Check arguments. 3564 if (!CIdx || !out_TU) 3565 return CXError_InvalidArguments; 3566 3567 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx); 3568 3569 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing)) 3570 setThreadBackgroundPriority(); 3571 3572 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble; 3573 bool CreatePreambleOnFirstParse = 3574 options & CXTranslationUnit_CreatePreambleOnFirstParse; 3575 // FIXME: Add a flag for modules. 3576 TranslationUnitKind TUKind = (options & (CXTranslationUnit_Incomplete | 3577 CXTranslationUnit_SingleFileParse)) 3578 ? TU_Prefix 3579 : TU_Complete; 3580 bool CacheCodeCompletionResults = 3581 options & CXTranslationUnit_CacheCompletionResults; 3582 bool IncludeBriefCommentsInCodeCompletion = 3583 options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion; 3584 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse; 3585 bool ForSerialization = options & CXTranslationUnit_ForSerialization; 3586 bool RetainExcludedCB = 3587 options & CXTranslationUnit_RetainExcludedConditionalBlocks; 3588 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None; 3589 if (options & CXTranslationUnit_SkipFunctionBodies) { 3590 SkipFunctionBodies = 3591 (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble) 3592 ? SkipFunctionBodiesScope::Preamble 3593 : SkipFunctionBodiesScope::PreambleAndMainFile; 3594 } 3595 3596 // Configure the diagnostics. 3597 IntrusiveRefCntPtr<DiagnosticsEngine> Diags( 3598 CompilerInstance::createDiagnostics(new DiagnosticOptions)); 3599 3600 if (options & CXTranslationUnit_KeepGoing) 3601 Diags->setFatalsAsError(true); 3602 3603 CaptureDiagsKind CaptureDiagnostics = CaptureDiagsKind::All; 3604 if (options & CXTranslationUnit_IgnoreNonErrorsFromIncludedFiles) 3605 CaptureDiagnostics = CaptureDiagsKind::AllWithoutNonErrorsFromIncludes; 3606 3607 // Recover resources if we crash before exiting this function. 3608 llvm::CrashRecoveryContextCleanupRegistrar< 3609 DiagnosticsEngine, 3610 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>> 3611 DiagCleanup(Diags.get()); 3612 3613 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles( 3614 new std::vector<ASTUnit::RemappedFile>()); 3615 3616 // Recover resources if we crash before exiting this function. 3617 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<ASTUnit::RemappedFile>> 3618 RemappedCleanup(RemappedFiles.get()); 3619 3620 for (auto &UF : unsaved_files) { 3621 std::unique_ptr<llvm::MemoryBuffer> MB = 3622 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename); 3623 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release())); 3624 } 3625 3626 std::unique_ptr<std::vector<const char *>> Args( 3627 new std::vector<const char *>()); 3628 3629 // Recover resources if we crash before exiting this method. 3630 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char *>> 3631 ArgsCleanup(Args.get()); 3632 3633 // Since the Clang C library is primarily used by batch tools dealing with 3634 // (often very broken) source code, where spell-checking can have a 3635 // significant negative impact on performance (particularly when 3636 // precompiled headers are involved), we disable it by default. 3637 // Only do this if we haven't found a spell-checking-related argument. 3638 bool FoundSpellCheckingArgument = false; 3639 for (int I = 0; I != num_command_line_args; ++I) { 3640 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 || 3641 strcmp(command_line_args[I], "-fspell-checking") == 0) { 3642 FoundSpellCheckingArgument = true; 3643 break; 3644 } 3645 } 3646 Args->insert(Args->end(), command_line_args, 3647 command_line_args + num_command_line_args); 3648 3649 if (!FoundSpellCheckingArgument) 3650 Args->insert(Args->begin() + 1, "-fno-spell-checking"); 3651 3652 // The 'source_filename' argument is optional. If the caller does not 3653 // specify it then it is assumed that the source file is specified 3654 // in the actual argument list. 3655 // Put the source file after command_line_args otherwise if '-x' flag is 3656 // present it will be unused. 3657 if (source_filename) 3658 Args->push_back(source_filename); 3659 3660 // Do we need the detailed preprocessing record? 3661 if (options & CXTranslationUnit_DetailedPreprocessingRecord) { 3662 Args->push_back("-Xclang"); 3663 Args->push_back("-detailed-preprocessing-record"); 3664 } 3665 3666 // Suppress any editor placeholder diagnostics. 3667 Args->push_back("-fallow-editor-placeholders"); 3668 3669 unsigned NumErrors = Diags->getClient()->getNumErrors(); 3670 std::unique_ptr<ASTUnit> ErrUnit; 3671 // Unless the user specified that they want the preamble on the first parse 3672 // set it up to be created on the first reparse. This makes the first parse 3673 // faster, trading for a slower (first) reparse. 3674 unsigned PrecompilePreambleAfterNParses = 3675 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse; 3676 3677 LibclangInvocationReporter InvocationReporter( 3678 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation, 3679 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None, 3680 unsaved_files); 3681 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine( 3682 Args->data(), Args->data() + Args->size(), 3683 CXXIdx->getPCHContainerOperations(), Diags, 3684 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(), 3685 CaptureDiagnostics, *RemappedFiles.get(), 3686 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses, 3687 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion, 3688 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse, 3689 /*UserFilesAreVolatile=*/true, ForSerialization, RetainExcludedCB, 3690 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(), 3691 &ErrUnit)); 3692 3693 // Early failures in LoadFromCommandLine may return with ErrUnit unset. 3694 if (!Unit && !ErrUnit) 3695 return CXError_ASTReadError; 3696 3697 if (NumErrors != Diags->getClient()->getNumErrors()) { 3698 // Make sure to check that 'Unit' is non-NULL. 3699 if (CXXIdx->getDisplayDiagnostics()) 3700 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get()); 3701 } 3702 3703 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get())) 3704 return CXError_ASTReadError; 3705 3706 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit)); 3707 if (CXTranslationUnitImpl *TU = *out_TU) { 3708 TU->ParsingOptions = options; 3709 TU->Arguments.reserve(Args->size()); 3710 for (const char *Arg : *Args) 3711 TU->Arguments.push_back(Arg); 3712 return CXError_Success; 3713 } 3714 return CXError_Failure; 3715 } 3716 3717 CXTranslationUnit 3718 clang_parseTranslationUnit(CXIndex CIdx, const char *source_filename, 3719 const char *const *command_line_args, 3720 int num_command_line_args, 3721 struct CXUnsavedFile *unsaved_files, 3722 unsigned num_unsaved_files, unsigned options) { 3723 CXTranslationUnit TU; 3724 enum CXErrorCode Result = clang_parseTranslationUnit2( 3725 CIdx, source_filename, command_line_args, num_command_line_args, 3726 unsaved_files, num_unsaved_files, options, &TU); 3727 (void)Result; 3728 assert((TU && Result == CXError_Success) || 3729 (!TU && Result != CXError_Success)); 3730 return TU; 3731 } 3732 3733 enum CXErrorCode clang_parseTranslationUnit2( 3734 CXIndex CIdx, const char *source_filename, 3735 const char *const *command_line_args, int num_command_line_args, 3736 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files, 3737 unsigned options, CXTranslationUnit *out_TU) { 3738 noteBottomOfStack(); 3739 SmallVector<const char *, 4> Args; 3740 Args.push_back("clang"); 3741 Args.append(command_line_args, command_line_args + num_command_line_args); 3742 return clang_parseTranslationUnit2FullArgv( 3743 CIdx, source_filename, Args.data(), Args.size(), unsaved_files, 3744 num_unsaved_files, options, out_TU); 3745 } 3746 3747 enum CXErrorCode clang_parseTranslationUnit2FullArgv( 3748 CXIndex CIdx, const char *source_filename, 3749 const char *const *command_line_args, int num_command_line_args, 3750 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files, 3751 unsigned options, CXTranslationUnit *out_TU) { 3752 LOG_FUNC_SECTION { 3753 *Log << source_filename << ": "; 3754 for (int i = 0; i != num_command_line_args; ++i) 3755 *Log << command_line_args[i] << " "; 3756 } 3757 3758 if (num_unsaved_files && !unsaved_files) 3759 return CXError_InvalidArguments; 3760 3761 CXErrorCode result = CXError_Failure; 3762 auto ParseTranslationUnitImpl = [=, &result] { 3763 noteBottomOfStack(); 3764 result = clang_parseTranslationUnit_Impl( 3765 CIdx, source_filename, command_line_args, num_command_line_args, 3766 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU); 3767 }; 3768 3769 llvm::CrashRecoveryContext CRC; 3770 3771 if (!RunSafely(CRC, ParseTranslationUnitImpl)) { 3772 fprintf(stderr, "libclang: crash detected during parsing: {\n"); 3773 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename); 3774 fprintf(stderr, " 'command_line_args' : ["); 3775 for (int i = 0; i != num_command_line_args; ++i) { 3776 if (i) 3777 fprintf(stderr, ", "); 3778 fprintf(stderr, "'%s'", command_line_args[i]); 3779 } 3780 fprintf(stderr, "],\n"); 3781 fprintf(stderr, " 'unsaved_files' : ["); 3782 for (unsigned i = 0; i != num_unsaved_files; ++i) { 3783 if (i) 3784 fprintf(stderr, ", "); 3785 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename, 3786 unsaved_files[i].Length); 3787 } 3788 fprintf(stderr, "],\n"); 3789 fprintf(stderr, " 'options' : %d,\n", options); 3790 fprintf(stderr, "}\n"); 3791 3792 return CXError_Crashed; 3793 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) { 3794 if (CXTranslationUnit *TU = out_TU) 3795 PrintLibclangResourceUsage(*TU); 3796 } 3797 3798 return result; 3799 } 3800 3801 CXString clang_Type_getObjCEncoding(CXType CT) { 3802 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]); 3803 ASTContext &Ctx = getASTUnit(tu)->getASTContext(); 3804 std::string encoding; 3805 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]), encoding); 3806 3807 return cxstring::createDup(encoding); 3808 } 3809 3810 static const IdentifierInfo *getMacroIdentifier(CXCursor C) { 3811 if (C.kind == CXCursor_MacroDefinition) { 3812 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C)) 3813 return MDR->getName(); 3814 } else if (C.kind == CXCursor_MacroExpansion) { 3815 MacroExpansionCursor ME = getCursorMacroExpansion(C); 3816 return ME.getName(); 3817 } 3818 return nullptr; 3819 } 3820 3821 unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) { 3822 const IdentifierInfo *II = getMacroIdentifier(C); 3823 if (!II) { 3824 return false; 3825 } 3826 ASTUnit *ASTU = getCursorASTUnit(C); 3827 Preprocessor &PP = ASTU->getPreprocessor(); 3828 if (const MacroInfo *MI = PP.getMacroInfo(II)) 3829 return MI->isFunctionLike(); 3830 return false; 3831 } 3832 3833 unsigned clang_Cursor_isMacroBuiltin(CXCursor C) { 3834 const IdentifierInfo *II = getMacroIdentifier(C); 3835 if (!II) { 3836 return false; 3837 } 3838 ASTUnit *ASTU = getCursorASTUnit(C); 3839 Preprocessor &PP = ASTU->getPreprocessor(); 3840 if (const MacroInfo *MI = PP.getMacroInfo(II)) 3841 return MI->isBuiltinMacro(); 3842 return false; 3843 } 3844 3845 unsigned clang_Cursor_isFunctionInlined(CXCursor C) { 3846 const Decl *D = getCursorDecl(C); 3847 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 3848 if (!FD) { 3849 return false; 3850 } 3851 return FD->isInlined(); 3852 } 3853 3854 static StringLiteral *getCFSTR_value(CallExpr *callExpr) { 3855 if (callExpr->getNumArgs() != 1) { 3856 return nullptr; 3857 } 3858 3859 StringLiteral *S = nullptr; 3860 auto *arg = callExpr->getArg(0); 3861 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) { 3862 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg); 3863 auto *subExpr = I->getSubExprAsWritten(); 3864 3865 if (subExpr->getStmtClass() != Stmt::StringLiteralClass) { 3866 return nullptr; 3867 } 3868 3869 S = static_cast<StringLiteral *>(I->getSubExprAsWritten()); 3870 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) { 3871 S = static_cast<StringLiteral *>(callExpr->getArg(0)); 3872 } else { 3873 return nullptr; 3874 } 3875 return S; 3876 } 3877 3878 struct ExprEvalResult { 3879 CXEvalResultKind EvalType; 3880 union { 3881 unsigned long long unsignedVal; 3882 long long intVal; 3883 double floatVal; 3884 char *stringVal; 3885 } EvalData; 3886 bool IsUnsignedInt; 3887 ~ExprEvalResult() { 3888 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float && 3889 EvalType != CXEval_Int) { 3890 delete[] EvalData.stringVal; 3891 } 3892 } 3893 }; 3894 3895 void clang_EvalResult_dispose(CXEvalResult E) { 3896 delete static_cast<ExprEvalResult *>(E); 3897 } 3898 3899 CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) { 3900 if (!E) { 3901 return CXEval_UnExposed; 3902 } 3903 return ((ExprEvalResult *)E)->EvalType; 3904 } 3905 3906 int clang_EvalResult_getAsInt(CXEvalResult E) { 3907 return clang_EvalResult_getAsLongLong(E); 3908 } 3909 3910 long long clang_EvalResult_getAsLongLong(CXEvalResult E) { 3911 if (!E) { 3912 return 0; 3913 } 3914 ExprEvalResult *Result = (ExprEvalResult *)E; 3915 if (Result->IsUnsignedInt) 3916 return Result->EvalData.unsignedVal; 3917 return Result->EvalData.intVal; 3918 } 3919 3920 unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) { 3921 return ((ExprEvalResult *)E)->IsUnsignedInt; 3922 } 3923 3924 unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) { 3925 if (!E) { 3926 return 0; 3927 } 3928 3929 ExprEvalResult *Result = (ExprEvalResult *)E; 3930 if (Result->IsUnsignedInt) 3931 return Result->EvalData.unsignedVal; 3932 return Result->EvalData.intVal; 3933 } 3934 3935 double clang_EvalResult_getAsDouble(CXEvalResult E) { 3936 if (!E) { 3937 return 0; 3938 } 3939 return ((ExprEvalResult *)E)->EvalData.floatVal; 3940 } 3941 3942 const char *clang_EvalResult_getAsStr(CXEvalResult E) { 3943 if (!E) { 3944 return nullptr; 3945 } 3946 return ((ExprEvalResult *)E)->EvalData.stringVal; 3947 } 3948 3949 static const ExprEvalResult *evaluateExpr(Expr *expr, CXCursor C) { 3950 Expr::EvalResult ER; 3951 ASTContext &ctx = getCursorContext(C); 3952 if (!expr) 3953 return nullptr; 3954 3955 expr = expr->IgnoreParens(); 3956 if (expr->isValueDependent()) 3957 return nullptr; 3958 if (!expr->EvaluateAsRValue(ER, ctx)) 3959 return nullptr; 3960 3961 QualType rettype; 3962 CallExpr *callExpr; 3963 auto result = std::make_unique<ExprEvalResult>(); 3964 result->EvalType = CXEval_UnExposed; 3965 result->IsUnsignedInt = false; 3966 3967 if (ER.Val.isInt()) { 3968 result->EvalType = CXEval_Int; 3969 3970 auto &val = ER.Val.getInt(); 3971 if (val.isUnsigned()) { 3972 result->IsUnsignedInt = true; 3973 result->EvalData.unsignedVal = val.getZExtValue(); 3974 } else { 3975 result->EvalData.intVal = val.getExtValue(); 3976 } 3977 3978 return result.release(); 3979 } 3980 3981 if (ER.Val.isFloat()) { 3982 llvm::SmallVector<char, 100> Buffer; 3983 ER.Val.getFloat().toString(Buffer); 3984 std::string floatStr(Buffer.data(), Buffer.size()); 3985 result->EvalType = CXEval_Float; 3986 bool ignored; 3987 llvm::APFloat apFloat = ER.Val.getFloat(); 3988 apFloat.convert(llvm::APFloat::IEEEdouble(), 3989 llvm::APFloat::rmNearestTiesToEven, &ignored); 3990 result->EvalData.floatVal = apFloat.convertToDouble(); 3991 return result.release(); 3992 } 3993 3994 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) { 3995 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr); 3996 auto *subExpr = I->getSubExprAsWritten(); 3997 if (subExpr->getStmtClass() == Stmt::StringLiteralClass || 3998 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) { 3999 const StringLiteral *StrE = nullptr; 4000 const ObjCStringLiteral *ObjCExpr; 4001 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr); 4002 4003 if (ObjCExpr) { 4004 StrE = ObjCExpr->getString(); 4005 result->EvalType = CXEval_ObjCStrLiteral; 4006 } else { 4007 StrE = cast<StringLiteral>(I->getSubExprAsWritten()); 4008 result->EvalType = CXEval_StrLiteral; 4009 } 4010 4011 std::string strRef(StrE->getString().str()); 4012 result->EvalData.stringVal = new char[strRef.size() + 1]; 4013 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), 4014 strRef.size()); 4015 result->EvalData.stringVal[strRef.size()] = '\0'; 4016 return result.release(); 4017 } 4018 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass || 4019 expr->getStmtClass() == Stmt::StringLiteralClass) { 4020 const StringLiteral *StrE = nullptr; 4021 const ObjCStringLiteral *ObjCExpr; 4022 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr); 4023 4024 if (ObjCExpr) { 4025 StrE = ObjCExpr->getString(); 4026 result->EvalType = CXEval_ObjCStrLiteral; 4027 } else { 4028 StrE = cast<StringLiteral>(expr); 4029 result->EvalType = CXEval_StrLiteral; 4030 } 4031 4032 std::string strRef(StrE->getString().str()); 4033 result->EvalData.stringVal = new char[strRef.size() + 1]; 4034 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size()); 4035 result->EvalData.stringVal[strRef.size()] = '\0'; 4036 return result.release(); 4037 } 4038 4039 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) { 4040 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr); 4041 4042 rettype = CC->getType(); 4043 if (rettype.getAsString() == "CFStringRef" && 4044 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) { 4045 4046 callExpr = static_cast<CallExpr *>(CC->getSubExpr()); 4047 StringLiteral *S = getCFSTR_value(callExpr); 4048 if (S) { 4049 std::string strLiteral(S->getString().str()); 4050 result->EvalType = CXEval_CFStr; 4051 4052 result->EvalData.stringVal = new char[strLiteral.size() + 1]; 4053 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(), 4054 strLiteral.size()); 4055 result->EvalData.stringVal[strLiteral.size()] = '\0'; 4056 return result.release(); 4057 } 4058 } 4059 4060 } else if (expr->getStmtClass() == Stmt::CallExprClass) { 4061 callExpr = static_cast<CallExpr *>(expr); 4062 rettype = callExpr->getCallReturnType(ctx); 4063 4064 if (rettype->isVectorType() || callExpr->getNumArgs() > 1) 4065 return nullptr; 4066 4067 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) { 4068 if (callExpr->getNumArgs() == 1 && 4069 !callExpr->getArg(0)->getType()->isIntegralType(ctx)) 4070 return nullptr; 4071 } else if (rettype.getAsString() == "CFStringRef") { 4072 4073 StringLiteral *S = getCFSTR_value(callExpr); 4074 if (S) { 4075 std::string strLiteral(S->getString().str()); 4076 result->EvalType = CXEval_CFStr; 4077 result->EvalData.stringVal = new char[strLiteral.size() + 1]; 4078 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(), 4079 strLiteral.size()); 4080 result->EvalData.stringVal[strLiteral.size()] = '\0'; 4081 return result.release(); 4082 } 4083 } 4084 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) { 4085 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr); 4086 ValueDecl *V = D->getDecl(); 4087 if (V->getKind() == Decl::Function) { 4088 std::string strName = V->getNameAsString(); 4089 result->EvalType = CXEval_Other; 4090 result->EvalData.stringVal = new char[strName.size() + 1]; 4091 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size()); 4092 result->EvalData.stringVal[strName.size()] = '\0'; 4093 return result.release(); 4094 } 4095 } 4096 4097 return nullptr; 4098 } 4099 4100 static const Expr *evaluateDeclExpr(const Decl *D) { 4101 if (!D) 4102 return nullptr; 4103 if (auto *Var = dyn_cast<VarDecl>(D)) 4104 return Var->getInit(); 4105 else if (auto *Field = dyn_cast<FieldDecl>(D)) 4106 return Field->getInClassInitializer(); 4107 return nullptr; 4108 } 4109 4110 static const Expr *evaluateCompoundStmtExpr(const CompoundStmt *CS) { 4111 assert(CS && "invalid compound statement"); 4112 for (auto *bodyIterator : CS->body()) { 4113 if (const auto *E = dyn_cast<Expr>(bodyIterator)) 4114 return E; 4115 } 4116 return nullptr; 4117 } 4118 4119 CXEvalResult clang_Cursor_Evaluate(CXCursor C) { 4120 const Expr *E = nullptr; 4121 if (clang_getCursorKind(C) == CXCursor_CompoundStmt) 4122 E = evaluateCompoundStmtExpr(cast<CompoundStmt>(getCursorStmt(C))); 4123 else if (clang_isDeclaration(C.kind)) 4124 E = evaluateDeclExpr(getCursorDecl(C)); 4125 else if (clang_isExpression(C.kind)) 4126 E = getCursorExpr(C); 4127 if (E) 4128 return const_cast<CXEvalResult>( 4129 reinterpret_cast<const void *>(evaluateExpr(const_cast<Expr *>(E), C))); 4130 return nullptr; 4131 } 4132 4133 unsigned clang_Cursor_hasAttrs(CXCursor C) { 4134 const Decl *D = getCursorDecl(C); 4135 if (!D) { 4136 return 0; 4137 } 4138 4139 if (D->hasAttrs()) { 4140 return 1; 4141 } 4142 4143 return 0; 4144 } 4145 unsigned clang_defaultSaveOptions(CXTranslationUnit TU) { 4146 return CXSaveTranslationUnit_None; 4147 } 4148 4149 static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU, 4150 const char *FileName, 4151 unsigned options) { 4152 CIndexer *CXXIdx = TU->CIdx; 4153 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing)) 4154 setThreadBackgroundPriority(); 4155 4156 bool hadError = cxtu::getASTUnit(TU)->Save(FileName); 4157 return hadError ? CXSaveError_Unknown : CXSaveError_None; 4158 } 4159 4160 int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName, 4161 unsigned options) { 4162 LOG_FUNC_SECTION { *Log << TU << ' ' << FileName; } 4163 4164 if (isNotUsableTU(TU)) { 4165 LOG_BAD_TU(TU); 4166 return CXSaveError_InvalidTU; 4167 } 4168 4169 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 4170 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 4171 if (!CXXUnit->hasSema()) 4172 return CXSaveError_InvalidTU; 4173 4174 CXSaveError result; 4175 auto SaveTranslationUnitImpl = [=, &result]() { 4176 result = clang_saveTranslationUnit_Impl(TU, FileName, options); 4177 }; 4178 4179 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) { 4180 SaveTranslationUnitImpl(); 4181 4182 if (getenv("LIBCLANG_RESOURCE_USAGE")) 4183 PrintLibclangResourceUsage(TU); 4184 4185 return result; 4186 } 4187 4188 // We have an AST that has invalid nodes due to compiler errors. 4189 // Use a crash recovery thread for protection. 4190 4191 llvm::CrashRecoveryContext CRC; 4192 4193 if (!RunSafely(CRC, SaveTranslationUnitImpl)) { 4194 fprintf(stderr, "libclang: crash detected during AST saving: {\n"); 4195 fprintf(stderr, " 'filename' : '%s'\n", FileName); 4196 fprintf(stderr, " 'options' : %d,\n", options); 4197 fprintf(stderr, "}\n"); 4198 4199 return CXSaveError_Unknown; 4200 4201 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) { 4202 PrintLibclangResourceUsage(TU); 4203 } 4204 4205 return result; 4206 } 4207 4208 void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) { 4209 if (CTUnit) { 4210 // If the translation unit has been marked as unsafe to free, just discard 4211 // it. 4212 ASTUnit *Unit = cxtu::getASTUnit(CTUnit); 4213 if (Unit && Unit->isUnsafeToFree()) 4214 return; 4215 4216 delete cxtu::getASTUnit(CTUnit); 4217 delete CTUnit->StringPool; 4218 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics); 4219 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool); 4220 delete CTUnit->CommentToXML; 4221 delete CTUnit; 4222 } 4223 } 4224 4225 unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) { 4226 if (CTUnit) { 4227 ASTUnit *Unit = cxtu::getASTUnit(CTUnit); 4228 4229 if (Unit && Unit->isUnsafeToFree()) 4230 return false; 4231 4232 Unit->ResetForParse(); 4233 return true; 4234 } 4235 4236 return false; 4237 } 4238 4239 unsigned clang_defaultReparseOptions(CXTranslationUnit TU) { 4240 return CXReparse_None; 4241 } 4242 4243 static CXErrorCode 4244 clang_reparseTranslationUnit_Impl(CXTranslationUnit TU, 4245 ArrayRef<CXUnsavedFile> unsaved_files, 4246 unsigned options) { 4247 // Check arguments. 4248 if (isNotUsableTU(TU)) { 4249 LOG_BAD_TU(TU); 4250 return CXError_InvalidArguments; 4251 } 4252 4253 // Reset the associated diagnostics. 4254 delete static_cast<CXDiagnosticSetImpl *>(TU->Diagnostics); 4255 TU->Diagnostics = nullptr; 4256 4257 CIndexer *CXXIdx = TU->CIdx; 4258 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing)) 4259 setThreadBackgroundPriority(); 4260 4261 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 4262 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 4263 4264 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles( 4265 new std::vector<ASTUnit::RemappedFile>()); 4266 4267 // Recover resources if we crash before exiting this function. 4268 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<ASTUnit::RemappedFile>> 4269 RemappedCleanup(RemappedFiles.get()); 4270 4271 for (auto &UF : unsaved_files) { 4272 std::unique_ptr<llvm::MemoryBuffer> MB = 4273 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename); 4274 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release())); 4275 } 4276 4277 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(), 4278 *RemappedFiles.get())) 4279 return CXError_Success; 4280 if (isASTReadError(CXXUnit)) 4281 return CXError_ASTReadError; 4282 return CXError_Failure; 4283 } 4284 4285 int clang_reparseTranslationUnit(CXTranslationUnit TU, 4286 unsigned num_unsaved_files, 4287 struct CXUnsavedFile *unsaved_files, 4288 unsigned options) { 4289 LOG_FUNC_SECTION { *Log << TU; } 4290 4291 if (num_unsaved_files && !unsaved_files) 4292 return CXError_InvalidArguments; 4293 4294 CXErrorCode result; 4295 auto ReparseTranslationUnitImpl = [=, &result]() { 4296 result = clang_reparseTranslationUnit_Impl( 4297 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options); 4298 }; 4299 4300 llvm::CrashRecoveryContext CRC; 4301 4302 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) { 4303 fprintf(stderr, "libclang: crash detected during reparsing\n"); 4304 cxtu::getASTUnit(TU)->setUnsafeToFree(true); 4305 return CXError_Crashed; 4306 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) 4307 PrintLibclangResourceUsage(TU); 4308 4309 return result; 4310 } 4311 4312 CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) { 4313 if (isNotUsableTU(CTUnit)) { 4314 LOG_BAD_TU(CTUnit); 4315 return cxstring::createEmpty(); 4316 } 4317 4318 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit); 4319 return cxstring::createDup(CXXUnit->getOriginalSourceFileName()); 4320 } 4321 4322 CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) { 4323 if (isNotUsableTU(TU)) { 4324 LOG_BAD_TU(TU); 4325 return clang_getNullCursor(); 4326 } 4327 4328 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 4329 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU); 4330 } 4331 4332 CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) { 4333 if (isNotUsableTU(CTUnit)) { 4334 LOG_BAD_TU(CTUnit); 4335 return nullptr; 4336 } 4337 4338 CXTargetInfoImpl *impl = new CXTargetInfoImpl(); 4339 impl->TranslationUnit = CTUnit; 4340 return impl; 4341 } 4342 4343 CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) { 4344 if (!TargetInfo) 4345 return cxstring::createEmpty(); 4346 4347 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit; 4348 assert(!isNotUsableTU(CTUnit) && 4349 "Unexpected unusable translation unit in TargetInfo"); 4350 4351 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit); 4352 std::string Triple = 4353 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize(); 4354 return cxstring::createDup(Triple); 4355 } 4356 4357 int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) { 4358 if (!TargetInfo) 4359 return -1; 4360 4361 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit; 4362 assert(!isNotUsableTU(CTUnit) && 4363 "Unexpected unusable translation unit in TargetInfo"); 4364 4365 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit); 4366 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth(); 4367 } 4368 4369 void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) { 4370 if (!TargetInfo) 4371 return; 4372 4373 delete TargetInfo; 4374 } 4375 4376 //===----------------------------------------------------------------------===// 4377 // CXFile Operations. 4378 //===----------------------------------------------------------------------===// 4379 4380 CXString clang_getFileName(CXFile SFile) { 4381 if (!SFile) 4382 return cxstring::createNull(); 4383 4384 FileEntry *FEnt = static_cast<FileEntry *>(SFile); 4385 return cxstring::createRef(FEnt->getName()); 4386 } 4387 4388 time_t clang_getFileTime(CXFile SFile) { 4389 if (!SFile) 4390 return 0; 4391 4392 FileEntry *FEnt = static_cast<FileEntry *>(SFile); 4393 return FEnt->getModificationTime(); 4394 } 4395 4396 CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) { 4397 if (isNotUsableTU(TU)) { 4398 LOG_BAD_TU(TU); 4399 return nullptr; 4400 } 4401 4402 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 4403 4404 FileManager &FMgr = CXXUnit->getFileManager(); 4405 auto File = FMgr.getFile(file_name); 4406 if (!File) 4407 return nullptr; 4408 return const_cast<FileEntry *>(*File); 4409 } 4410 4411 const char *clang_getFileContents(CXTranslationUnit TU, CXFile file, 4412 size_t *size) { 4413 if (isNotUsableTU(TU)) { 4414 LOG_BAD_TU(TU); 4415 return nullptr; 4416 } 4417 4418 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager(); 4419 FileID fid = SM.translateFile(static_cast<FileEntry *>(file)); 4420 llvm::Optional<llvm::MemoryBufferRef> buf = SM.getBufferOrNone(fid); 4421 if (!buf) { 4422 if (size) 4423 *size = 0; 4424 return nullptr; 4425 } 4426 if (size) 4427 *size = buf->getBufferSize(); 4428 return buf->getBufferStart(); 4429 } 4430 4431 unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU, CXFile file) { 4432 if (isNotUsableTU(TU)) { 4433 LOG_BAD_TU(TU); 4434 return 0; 4435 } 4436 4437 if (!file) 4438 return 0; 4439 4440 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 4441 FileEntry *FEnt = static_cast<FileEntry *>(file); 4442 return CXXUnit->getPreprocessor() 4443 .getHeaderSearchInfo() 4444 .isFileMultipleIncludeGuarded(FEnt); 4445 } 4446 4447 int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) { 4448 if (!file || !outID) 4449 return 1; 4450 4451 FileEntry *FEnt = static_cast<FileEntry *>(file); 4452 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID(); 4453 outID->data[0] = ID.getDevice(); 4454 outID->data[1] = ID.getFile(); 4455 outID->data[2] = FEnt->getModificationTime(); 4456 return 0; 4457 } 4458 4459 int clang_File_isEqual(CXFile file1, CXFile file2) { 4460 if (file1 == file2) 4461 return true; 4462 4463 if (!file1 || !file2) 4464 return false; 4465 4466 FileEntry *FEnt1 = static_cast<FileEntry *>(file1); 4467 FileEntry *FEnt2 = static_cast<FileEntry *>(file2); 4468 return FEnt1->getUniqueID() == FEnt2->getUniqueID(); 4469 } 4470 4471 CXString clang_File_tryGetRealPathName(CXFile SFile) { 4472 if (!SFile) 4473 return cxstring::createNull(); 4474 4475 FileEntry *FEnt = static_cast<FileEntry *>(SFile); 4476 return cxstring::createRef(FEnt->tryGetRealPathName()); 4477 } 4478 4479 //===----------------------------------------------------------------------===// 4480 // CXCursor Operations. 4481 //===----------------------------------------------------------------------===// 4482 4483 static const Decl *getDeclFromExpr(const Stmt *E) { 4484 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) 4485 return getDeclFromExpr(CE->getSubExpr()); 4486 4487 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E)) 4488 return RefExpr->getDecl(); 4489 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 4490 return ME->getMemberDecl(); 4491 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E)) 4492 return RE->getDecl(); 4493 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) { 4494 if (PRE->isExplicitProperty()) 4495 return PRE->getExplicitProperty(); 4496 // It could be messaging both getter and setter as in: 4497 // ++myobj.myprop; 4498 // in which case prefer to associate the setter since it is less obvious 4499 // from inspecting the source that the setter is going to get called. 4500 if (PRE->isMessagingSetter()) 4501 return PRE->getImplicitPropertySetter(); 4502 return PRE->getImplicitPropertyGetter(); 4503 } 4504 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 4505 return getDeclFromExpr(POE->getSyntacticForm()); 4506 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) 4507 if (Expr *Src = OVE->getSourceExpr()) 4508 return getDeclFromExpr(Src); 4509 4510 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) 4511 return getDeclFromExpr(CE->getCallee()); 4512 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E)) 4513 if (!CE->isElidable()) 4514 return CE->getConstructor(); 4515 if (const CXXInheritedCtorInitExpr *CE = 4516 dyn_cast<CXXInheritedCtorInitExpr>(E)) 4517 return CE->getConstructor(); 4518 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E)) 4519 return OME->getMethodDecl(); 4520 4521 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E)) 4522 return PE->getProtocol(); 4523 if (const SubstNonTypeTemplateParmPackExpr *NTTP = 4524 dyn_cast<SubstNonTypeTemplateParmPackExpr>(E)) 4525 return NTTP->getParameterPack(); 4526 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E)) 4527 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) || 4528 isa<ParmVarDecl>(SizeOfPack->getPack())) 4529 return SizeOfPack->getPack(); 4530 4531 return nullptr; 4532 } 4533 4534 static SourceLocation getLocationFromExpr(const Expr *E) { 4535 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) 4536 return getLocationFromExpr(CE->getSubExpr()); 4537 4538 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) 4539 return /*FIXME:*/ Msg->getLeftLoc(); 4540 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 4541 return DRE->getLocation(); 4542 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E)) 4543 return Member->getMemberLoc(); 4544 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) 4545 return Ivar->getLocation(); 4546 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E)) 4547 return SizeOfPack->getPackLoc(); 4548 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E)) 4549 return PropRef->getLocation(); 4550 4551 return E->getBeginLoc(); 4552 } 4553 4554 extern "C" { 4555 4556 unsigned clang_visitChildren(CXCursor parent, CXCursorVisitor visitor, 4557 CXClientData client_data) { 4558 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data, 4559 /*VisitPreprocessorLast=*/false); 4560 return CursorVis.VisitChildren(parent); 4561 } 4562 4563 #ifndef __has_feature 4564 #define __has_feature(x) 0 4565 #endif 4566 #if __has_feature(blocks) 4567 typedef enum CXChildVisitResult (^CXCursorVisitorBlock)(CXCursor cursor, 4568 CXCursor parent); 4569 4570 static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent, 4571 CXClientData client_data) { 4572 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data; 4573 return block(cursor, parent); 4574 } 4575 #else 4576 // If we are compiled with a compiler that doesn't have native blocks support, 4577 // define and call the block manually, so the 4578 typedef struct _CXChildVisitResult { 4579 void *isa; 4580 int flags; 4581 int reserved; 4582 enum CXChildVisitResult (*invoke)(struct _CXChildVisitResult *, CXCursor, 4583 CXCursor); 4584 } * CXCursorVisitorBlock; 4585 4586 static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent, 4587 CXClientData client_data) { 4588 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data; 4589 return block->invoke(block, cursor, parent); 4590 } 4591 #endif 4592 4593 unsigned clang_visitChildrenWithBlock(CXCursor parent, 4594 CXCursorVisitorBlock block) { 4595 return clang_visitChildren(parent, visitWithBlock, block); 4596 } 4597 4598 static CXString getDeclSpelling(const Decl *D) { 4599 if (!D) 4600 return cxstring::createEmpty(); 4601 4602 const NamedDecl *ND = dyn_cast<NamedDecl>(D); 4603 if (!ND) { 4604 if (const ObjCPropertyImplDecl *PropImpl = 4605 dyn_cast<ObjCPropertyImplDecl>(D)) 4606 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl()) 4607 return cxstring::createDup(Property->getIdentifier()->getName()); 4608 4609 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) 4610 if (Module *Mod = ImportD->getImportedModule()) 4611 return cxstring::createDup(Mod->getFullModuleName()); 4612 4613 return cxstring::createEmpty(); 4614 } 4615 4616 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND)) 4617 return cxstring::createDup(OMD->getSelector().getAsString()); 4618 4619 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND)) 4620 // No, this isn't the same as the code below. getIdentifier() is non-virtual 4621 // and returns different names. NamedDecl returns the class name and 4622 // ObjCCategoryImplDecl returns the category name. 4623 return cxstring::createRef(CIMP->getIdentifier()->getNameStart()); 4624 4625 if (isa<UsingDirectiveDecl>(D)) 4626 return cxstring::createEmpty(); 4627 4628 SmallString<1024> S; 4629 llvm::raw_svector_ostream os(S); 4630 ND->printName(os); 4631 4632 return cxstring::createDup(os.str()); 4633 } 4634 4635 CXString clang_getCursorSpelling(CXCursor C) { 4636 if (clang_isTranslationUnit(C.kind)) 4637 return clang_getTranslationUnitSpelling(getCursorTU(C)); 4638 4639 if (clang_isReference(C.kind)) { 4640 switch (C.kind) { 4641 case CXCursor_ObjCSuperClassRef: { 4642 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first; 4643 return cxstring::createRef(Super->getIdentifier()->getNameStart()); 4644 } 4645 case CXCursor_ObjCClassRef: { 4646 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first; 4647 return cxstring::createRef(Class->getIdentifier()->getNameStart()); 4648 } 4649 case CXCursor_ObjCProtocolRef: { 4650 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first; 4651 assert(OID && "getCursorSpelling(): Missing protocol decl"); 4652 return cxstring::createRef(OID->getIdentifier()->getNameStart()); 4653 } 4654 case CXCursor_CXXBaseSpecifier: { 4655 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C); 4656 return cxstring::createDup(B->getType().getAsString()); 4657 } 4658 case CXCursor_TypeRef: { 4659 const TypeDecl *Type = getCursorTypeRef(C).first; 4660 assert(Type && "Missing type decl"); 4661 4662 return cxstring::createDup( 4663 getCursorContext(C).getTypeDeclType(Type).getAsString()); 4664 } 4665 case CXCursor_TemplateRef: { 4666 const TemplateDecl *Template = getCursorTemplateRef(C).first; 4667 assert(Template && "Missing template decl"); 4668 4669 return cxstring::createDup(Template->getNameAsString()); 4670 } 4671 4672 case CXCursor_NamespaceRef: { 4673 const NamedDecl *NS = getCursorNamespaceRef(C).first; 4674 assert(NS && "Missing namespace decl"); 4675 4676 return cxstring::createDup(NS->getNameAsString()); 4677 } 4678 4679 case CXCursor_MemberRef: { 4680 const FieldDecl *Field = getCursorMemberRef(C).first; 4681 assert(Field && "Missing member decl"); 4682 4683 return cxstring::createDup(Field->getNameAsString()); 4684 } 4685 4686 case CXCursor_LabelRef: { 4687 const LabelStmt *Label = getCursorLabelRef(C).first; 4688 assert(Label && "Missing label"); 4689 4690 return cxstring::createRef(Label->getName()); 4691 } 4692 4693 case CXCursor_OverloadedDeclRef: { 4694 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first; 4695 if (const Decl *D = Storage.dyn_cast<const Decl *>()) { 4696 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) 4697 return cxstring::createDup(ND->getNameAsString()); 4698 return cxstring::createEmpty(); 4699 } 4700 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>()) 4701 return cxstring::createDup(E->getName().getAsString()); 4702 OverloadedTemplateStorage *Ovl = 4703 Storage.get<OverloadedTemplateStorage *>(); 4704 if (Ovl->size() == 0) 4705 return cxstring::createEmpty(); 4706 return cxstring::createDup((*Ovl->begin())->getNameAsString()); 4707 } 4708 4709 case CXCursor_VariableRef: { 4710 const VarDecl *Var = getCursorVariableRef(C).first; 4711 assert(Var && "Missing variable decl"); 4712 4713 return cxstring::createDup(Var->getNameAsString()); 4714 } 4715 4716 default: 4717 return cxstring::createRef("<not implemented>"); 4718 } 4719 } 4720 4721 if (clang_isExpression(C.kind)) { 4722 const Expr *E = getCursorExpr(C); 4723 4724 if (C.kind == CXCursor_ObjCStringLiteral || 4725 C.kind == CXCursor_StringLiteral) { 4726 const StringLiteral *SLit; 4727 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) { 4728 SLit = OSL->getString(); 4729 } else { 4730 SLit = cast<StringLiteral>(E); 4731 } 4732 SmallString<256> Buf; 4733 llvm::raw_svector_ostream OS(Buf); 4734 SLit->outputString(OS); 4735 return cxstring::createDup(OS.str()); 4736 } 4737 4738 const Decl *D = getDeclFromExpr(getCursorExpr(C)); 4739 if (D) 4740 return getDeclSpelling(D); 4741 return cxstring::createEmpty(); 4742 } 4743 4744 if (clang_isStatement(C.kind)) { 4745 const Stmt *S = getCursorStmt(C); 4746 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) 4747 return cxstring::createRef(Label->getName()); 4748 4749 return cxstring::createEmpty(); 4750 } 4751 4752 if (C.kind == CXCursor_MacroExpansion) 4753 return cxstring::createRef( 4754 getCursorMacroExpansion(C).getName()->getNameStart()); 4755 4756 if (C.kind == CXCursor_MacroDefinition) 4757 return cxstring::createRef( 4758 getCursorMacroDefinition(C)->getName()->getNameStart()); 4759 4760 if (C.kind == CXCursor_InclusionDirective) 4761 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName()); 4762 4763 if (clang_isDeclaration(C.kind)) 4764 return getDeclSpelling(getCursorDecl(C)); 4765 4766 if (C.kind == CXCursor_AnnotateAttr) { 4767 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C)); 4768 return cxstring::createDup(AA->getAnnotation()); 4769 } 4770 4771 if (C.kind == CXCursor_AsmLabelAttr) { 4772 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C)); 4773 return cxstring::createDup(AA->getLabel()); 4774 } 4775 4776 if (C.kind == CXCursor_PackedAttr) { 4777 return cxstring::createRef("packed"); 4778 } 4779 4780 if (C.kind == CXCursor_VisibilityAttr) { 4781 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C)); 4782 switch (AA->getVisibility()) { 4783 case VisibilityAttr::VisibilityType::Default: 4784 return cxstring::createRef("default"); 4785 case VisibilityAttr::VisibilityType::Hidden: 4786 return cxstring::createRef("hidden"); 4787 case VisibilityAttr::VisibilityType::Protected: 4788 return cxstring::createRef("protected"); 4789 } 4790 llvm_unreachable("unknown visibility type"); 4791 } 4792 4793 return cxstring::createEmpty(); 4794 } 4795 4796 CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C, unsigned pieceIndex, 4797 unsigned options) { 4798 if (clang_Cursor_isNull(C)) 4799 return clang_getNullRange(); 4800 4801 ASTContext &Ctx = getCursorContext(C); 4802 4803 if (clang_isStatement(C.kind)) { 4804 const Stmt *S = getCursorStmt(C); 4805 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) { 4806 if (pieceIndex > 0) 4807 return clang_getNullRange(); 4808 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc()); 4809 } 4810 4811 return clang_getNullRange(); 4812 } 4813 4814 if (C.kind == CXCursor_ObjCMessageExpr) { 4815 if (const ObjCMessageExpr *ME = 4816 dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) { 4817 if (pieceIndex >= ME->getNumSelectorLocs()) 4818 return clang_getNullRange(); 4819 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex)); 4820 } 4821 } 4822 4823 if (C.kind == CXCursor_ObjCInstanceMethodDecl || 4824 C.kind == CXCursor_ObjCClassMethodDecl) { 4825 if (const ObjCMethodDecl *MD = 4826 dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) { 4827 if (pieceIndex >= MD->getNumSelectorLocs()) 4828 return clang_getNullRange(); 4829 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex)); 4830 } 4831 } 4832 4833 if (C.kind == CXCursor_ObjCCategoryDecl || 4834 C.kind == CXCursor_ObjCCategoryImplDecl) { 4835 if (pieceIndex > 0) 4836 return clang_getNullRange(); 4837 if (const ObjCCategoryDecl *CD = 4838 dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C))) 4839 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc()); 4840 if (const ObjCCategoryImplDecl *CID = 4841 dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C))) 4842 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc()); 4843 } 4844 4845 if (C.kind == CXCursor_ModuleImportDecl) { 4846 if (pieceIndex > 0) 4847 return clang_getNullRange(); 4848 if (const ImportDecl *ImportD = 4849 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) { 4850 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs(); 4851 if (!Locs.empty()) 4852 return cxloc::translateSourceRange( 4853 Ctx, SourceRange(Locs.front(), Locs.back())); 4854 } 4855 return clang_getNullRange(); 4856 } 4857 4858 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor || 4859 C.kind == CXCursor_ConversionFunction || 4860 C.kind == CXCursor_FunctionDecl) { 4861 if (pieceIndex > 0) 4862 return clang_getNullRange(); 4863 if (const FunctionDecl *FD = 4864 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) { 4865 DeclarationNameInfo FunctionName = FD->getNameInfo(); 4866 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange()); 4867 } 4868 return clang_getNullRange(); 4869 } 4870 4871 // FIXME: A CXCursor_InclusionDirective should give the location of the 4872 // filename, but we don't keep track of this. 4873 4874 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation 4875 // but we don't keep track of this. 4876 4877 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label 4878 // but we don't keep track of this. 4879 4880 // Default handling, give the location of the cursor. 4881 4882 if (pieceIndex > 0) 4883 return clang_getNullRange(); 4884 4885 CXSourceLocation CXLoc = clang_getCursorLocation(C); 4886 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc); 4887 return cxloc::translateSourceRange(Ctx, Loc); 4888 } 4889 4890 CXString clang_Cursor_getMangling(CXCursor C) { 4891 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind)) 4892 return cxstring::createEmpty(); 4893 4894 // Mangling only works for functions and variables. 4895 const Decl *D = getCursorDecl(C); 4896 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D))) 4897 return cxstring::createEmpty(); 4898 4899 ASTContext &Ctx = D->getASTContext(); 4900 ASTNameGenerator ASTNameGen(Ctx); 4901 return cxstring::createDup(ASTNameGen.getName(D)); 4902 } 4903 4904 CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) { 4905 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind)) 4906 return nullptr; 4907 4908 const Decl *D = getCursorDecl(C); 4909 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D))) 4910 return nullptr; 4911 4912 ASTContext &Ctx = D->getASTContext(); 4913 ASTNameGenerator ASTNameGen(Ctx); 4914 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D); 4915 return cxstring::createSet(Manglings); 4916 } 4917 4918 CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) { 4919 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind)) 4920 return nullptr; 4921 4922 const Decl *D = getCursorDecl(C); 4923 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D))) 4924 return nullptr; 4925 4926 ASTContext &Ctx = D->getASTContext(); 4927 ASTNameGenerator ASTNameGen(Ctx); 4928 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D); 4929 return cxstring::createSet(Manglings); 4930 } 4931 4932 CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) { 4933 if (clang_Cursor_isNull(C)) 4934 return 0; 4935 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy()); 4936 } 4937 4938 void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) { 4939 if (Policy) 4940 delete static_cast<PrintingPolicy *>(Policy); 4941 } 4942 4943 unsigned 4944 clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy, 4945 enum CXPrintingPolicyProperty Property) { 4946 if (!Policy) 4947 return 0; 4948 4949 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy); 4950 switch (Property) { 4951 case CXPrintingPolicy_Indentation: 4952 return P->Indentation; 4953 case CXPrintingPolicy_SuppressSpecifiers: 4954 return P->SuppressSpecifiers; 4955 case CXPrintingPolicy_SuppressTagKeyword: 4956 return P->SuppressTagKeyword; 4957 case CXPrintingPolicy_IncludeTagDefinition: 4958 return P->IncludeTagDefinition; 4959 case CXPrintingPolicy_SuppressScope: 4960 return P->SuppressScope; 4961 case CXPrintingPolicy_SuppressUnwrittenScope: 4962 return P->SuppressUnwrittenScope; 4963 case CXPrintingPolicy_SuppressInitializers: 4964 return P->SuppressInitializers; 4965 case CXPrintingPolicy_ConstantArraySizeAsWritten: 4966 return P->ConstantArraySizeAsWritten; 4967 case CXPrintingPolicy_AnonymousTagLocations: 4968 return P->AnonymousTagLocations; 4969 case CXPrintingPolicy_SuppressStrongLifetime: 4970 return P->SuppressStrongLifetime; 4971 case CXPrintingPolicy_SuppressLifetimeQualifiers: 4972 return P->SuppressLifetimeQualifiers; 4973 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors: 4974 return P->SuppressTemplateArgsInCXXConstructors; 4975 case CXPrintingPolicy_Bool: 4976 return P->Bool; 4977 case CXPrintingPolicy_Restrict: 4978 return P->Restrict; 4979 case CXPrintingPolicy_Alignof: 4980 return P->Alignof; 4981 case CXPrintingPolicy_UnderscoreAlignof: 4982 return P->UnderscoreAlignof; 4983 case CXPrintingPolicy_UseVoidForZeroParams: 4984 return P->UseVoidForZeroParams; 4985 case CXPrintingPolicy_TerseOutput: 4986 return P->TerseOutput; 4987 case CXPrintingPolicy_PolishForDeclaration: 4988 return P->PolishForDeclaration; 4989 case CXPrintingPolicy_Half: 4990 return P->Half; 4991 case CXPrintingPolicy_MSWChar: 4992 return P->MSWChar; 4993 case CXPrintingPolicy_IncludeNewlines: 4994 return P->IncludeNewlines; 4995 case CXPrintingPolicy_MSVCFormatting: 4996 return P->MSVCFormatting; 4997 case CXPrintingPolicy_ConstantsAsWritten: 4998 return P->ConstantsAsWritten; 4999 case CXPrintingPolicy_SuppressImplicitBase: 5000 return P->SuppressImplicitBase; 5001 case CXPrintingPolicy_FullyQualifiedName: 5002 return P->FullyQualifiedName; 5003 } 5004 5005 assert(false && "Invalid CXPrintingPolicyProperty"); 5006 return 0; 5007 } 5008 5009 void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy, 5010 enum CXPrintingPolicyProperty Property, 5011 unsigned Value) { 5012 if (!Policy) 5013 return; 5014 5015 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy); 5016 switch (Property) { 5017 case CXPrintingPolicy_Indentation: 5018 P->Indentation = Value; 5019 return; 5020 case CXPrintingPolicy_SuppressSpecifiers: 5021 P->SuppressSpecifiers = Value; 5022 return; 5023 case CXPrintingPolicy_SuppressTagKeyword: 5024 P->SuppressTagKeyword = Value; 5025 return; 5026 case CXPrintingPolicy_IncludeTagDefinition: 5027 P->IncludeTagDefinition = Value; 5028 return; 5029 case CXPrintingPolicy_SuppressScope: 5030 P->SuppressScope = Value; 5031 return; 5032 case CXPrintingPolicy_SuppressUnwrittenScope: 5033 P->SuppressUnwrittenScope = Value; 5034 return; 5035 case CXPrintingPolicy_SuppressInitializers: 5036 P->SuppressInitializers = Value; 5037 return; 5038 case CXPrintingPolicy_ConstantArraySizeAsWritten: 5039 P->ConstantArraySizeAsWritten = Value; 5040 return; 5041 case CXPrintingPolicy_AnonymousTagLocations: 5042 P->AnonymousTagLocations = Value; 5043 return; 5044 case CXPrintingPolicy_SuppressStrongLifetime: 5045 P->SuppressStrongLifetime = Value; 5046 return; 5047 case CXPrintingPolicy_SuppressLifetimeQualifiers: 5048 P->SuppressLifetimeQualifiers = Value; 5049 return; 5050 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors: 5051 P->SuppressTemplateArgsInCXXConstructors = Value; 5052 return; 5053 case CXPrintingPolicy_Bool: 5054 P->Bool = Value; 5055 return; 5056 case CXPrintingPolicy_Restrict: 5057 P->Restrict = Value; 5058 return; 5059 case CXPrintingPolicy_Alignof: 5060 P->Alignof = Value; 5061 return; 5062 case CXPrintingPolicy_UnderscoreAlignof: 5063 P->UnderscoreAlignof = Value; 5064 return; 5065 case CXPrintingPolicy_UseVoidForZeroParams: 5066 P->UseVoidForZeroParams = Value; 5067 return; 5068 case CXPrintingPolicy_TerseOutput: 5069 P->TerseOutput = Value; 5070 return; 5071 case CXPrintingPolicy_PolishForDeclaration: 5072 P->PolishForDeclaration = Value; 5073 return; 5074 case CXPrintingPolicy_Half: 5075 P->Half = Value; 5076 return; 5077 case CXPrintingPolicy_MSWChar: 5078 P->MSWChar = Value; 5079 return; 5080 case CXPrintingPolicy_IncludeNewlines: 5081 P->IncludeNewlines = Value; 5082 return; 5083 case CXPrintingPolicy_MSVCFormatting: 5084 P->MSVCFormatting = Value; 5085 return; 5086 case CXPrintingPolicy_ConstantsAsWritten: 5087 P->ConstantsAsWritten = Value; 5088 return; 5089 case CXPrintingPolicy_SuppressImplicitBase: 5090 P->SuppressImplicitBase = Value; 5091 return; 5092 case CXPrintingPolicy_FullyQualifiedName: 5093 P->FullyQualifiedName = Value; 5094 return; 5095 } 5096 5097 assert(false && "Invalid CXPrintingPolicyProperty"); 5098 } 5099 5100 CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) { 5101 if (clang_Cursor_isNull(C)) 5102 return cxstring::createEmpty(); 5103 5104 if (clang_isDeclaration(C.kind)) { 5105 const Decl *D = getCursorDecl(C); 5106 if (!D) 5107 return cxstring::createEmpty(); 5108 5109 SmallString<128> Str; 5110 llvm::raw_svector_ostream OS(Str); 5111 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy); 5112 D->print(OS, UserPolicy ? *UserPolicy 5113 : getCursorContext(C).getPrintingPolicy()); 5114 5115 return cxstring::createDup(OS.str()); 5116 } 5117 5118 return cxstring::createEmpty(); 5119 } 5120 5121 CXString clang_getCursorDisplayName(CXCursor C) { 5122 if (!clang_isDeclaration(C.kind)) 5123 return clang_getCursorSpelling(C); 5124 5125 const Decl *D = getCursorDecl(C); 5126 if (!D) 5127 return cxstring::createEmpty(); 5128 5129 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy(); 5130 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 5131 D = FunTmpl->getTemplatedDecl(); 5132 5133 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 5134 SmallString<64> Str; 5135 llvm::raw_svector_ostream OS(Str); 5136 OS << *Function; 5137 if (Function->getPrimaryTemplate()) 5138 OS << "<>"; 5139 OS << "("; 5140 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) { 5141 if (I) 5142 OS << ", "; 5143 OS << Function->getParamDecl(I)->getType().getAsString(Policy); 5144 } 5145 5146 if (Function->isVariadic()) { 5147 if (Function->getNumParams()) 5148 OS << ", "; 5149 OS << "..."; 5150 } 5151 OS << ")"; 5152 return cxstring::createDup(OS.str()); 5153 } 5154 5155 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) { 5156 SmallString<64> Str; 5157 llvm::raw_svector_ostream OS(Str); 5158 OS << *ClassTemplate; 5159 OS << "<"; 5160 TemplateParameterList *Params = ClassTemplate->getTemplateParameters(); 5161 for (unsigned I = 0, N = Params->size(); I != N; ++I) { 5162 if (I) 5163 OS << ", "; 5164 5165 NamedDecl *Param = Params->getParam(I); 5166 if (Param->getIdentifier()) { 5167 OS << Param->getIdentifier()->getName(); 5168 continue; 5169 } 5170 5171 // There is no parameter name, which makes this tricky. Try to come up 5172 // with something useful that isn't too long. 5173 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) 5174 if (const auto *TC = TTP->getTypeConstraint()) { 5175 TC->getConceptNameInfo().printName(OS, Policy); 5176 if (TC->hasExplicitTemplateArgs()) 5177 OS << "<...>"; 5178 } else 5179 OS << (TTP->wasDeclaredWithTypename() ? "typename" : "class"); 5180 else if (NonTypeTemplateParmDecl *NTTP = 5181 dyn_cast<NonTypeTemplateParmDecl>(Param)) 5182 OS << NTTP->getType().getAsString(Policy); 5183 else 5184 OS << "template<...> class"; 5185 } 5186 5187 OS << ">"; 5188 return cxstring::createDup(OS.str()); 5189 } 5190 5191 if (const ClassTemplateSpecializationDecl *ClassSpec = 5192 dyn_cast<ClassTemplateSpecializationDecl>(D)) { 5193 // If the type was explicitly written, use that. 5194 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten()) 5195 return cxstring::createDup(TSInfo->getType().getAsString(Policy)); 5196 5197 SmallString<128> Str; 5198 llvm::raw_svector_ostream OS(Str); 5199 OS << *ClassSpec; 5200 printTemplateArgumentList( 5201 OS, ClassSpec->getTemplateArgs().asArray(), Policy, 5202 ClassSpec->getSpecializedTemplate()->getTemplateParameters()); 5203 return cxstring::createDup(OS.str()); 5204 } 5205 5206 return clang_getCursorSpelling(C); 5207 } 5208 5209 CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) { 5210 switch (Kind) { 5211 case CXCursor_FunctionDecl: 5212 return cxstring::createRef("FunctionDecl"); 5213 case CXCursor_TypedefDecl: 5214 return cxstring::createRef("TypedefDecl"); 5215 case CXCursor_EnumDecl: 5216 return cxstring::createRef("EnumDecl"); 5217 case CXCursor_EnumConstantDecl: 5218 return cxstring::createRef("EnumConstantDecl"); 5219 case CXCursor_StructDecl: 5220 return cxstring::createRef("StructDecl"); 5221 case CXCursor_UnionDecl: 5222 return cxstring::createRef("UnionDecl"); 5223 case CXCursor_ClassDecl: 5224 return cxstring::createRef("ClassDecl"); 5225 case CXCursor_FieldDecl: 5226 return cxstring::createRef("FieldDecl"); 5227 case CXCursor_VarDecl: 5228 return cxstring::createRef("VarDecl"); 5229 case CXCursor_ParmDecl: 5230 return cxstring::createRef("ParmDecl"); 5231 case CXCursor_ObjCInterfaceDecl: 5232 return cxstring::createRef("ObjCInterfaceDecl"); 5233 case CXCursor_ObjCCategoryDecl: 5234 return cxstring::createRef("ObjCCategoryDecl"); 5235 case CXCursor_ObjCProtocolDecl: 5236 return cxstring::createRef("ObjCProtocolDecl"); 5237 case CXCursor_ObjCPropertyDecl: 5238 return cxstring::createRef("ObjCPropertyDecl"); 5239 case CXCursor_ObjCIvarDecl: 5240 return cxstring::createRef("ObjCIvarDecl"); 5241 case CXCursor_ObjCInstanceMethodDecl: 5242 return cxstring::createRef("ObjCInstanceMethodDecl"); 5243 case CXCursor_ObjCClassMethodDecl: 5244 return cxstring::createRef("ObjCClassMethodDecl"); 5245 case CXCursor_ObjCImplementationDecl: 5246 return cxstring::createRef("ObjCImplementationDecl"); 5247 case CXCursor_ObjCCategoryImplDecl: 5248 return cxstring::createRef("ObjCCategoryImplDecl"); 5249 case CXCursor_CXXMethod: 5250 return cxstring::createRef("CXXMethod"); 5251 case CXCursor_UnexposedDecl: 5252 return cxstring::createRef("UnexposedDecl"); 5253 case CXCursor_ObjCSuperClassRef: 5254 return cxstring::createRef("ObjCSuperClassRef"); 5255 case CXCursor_ObjCProtocolRef: 5256 return cxstring::createRef("ObjCProtocolRef"); 5257 case CXCursor_ObjCClassRef: 5258 return cxstring::createRef("ObjCClassRef"); 5259 case CXCursor_TypeRef: 5260 return cxstring::createRef("TypeRef"); 5261 case CXCursor_TemplateRef: 5262 return cxstring::createRef("TemplateRef"); 5263 case CXCursor_NamespaceRef: 5264 return cxstring::createRef("NamespaceRef"); 5265 case CXCursor_MemberRef: 5266 return cxstring::createRef("MemberRef"); 5267 case CXCursor_LabelRef: 5268 return cxstring::createRef("LabelRef"); 5269 case CXCursor_OverloadedDeclRef: 5270 return cxstring::createRef("OverloadedDeclRef"); 5271 case CXCursor_VariableRef: 5272 return cxstring::createRef("VariableRef"); 5273 case CXCursor_IntegerLiteral: 5274 return cxstring::createRef("IntegerLiteral"); 5275 case CXCursor_FixedPointLiteral: 5276 return cxstring::createRef("FixedPointLiteral"); 5277 case CXCursor_FloatingLiteral: 5278 return cxstring::createRef("FloatingLiteral"); 5279 case CXCursor_ImaginaryLiteral: 5280 return cxstring::createRef("ImaginaryLiteral"); 5281 case CXCursor_StringLiteral: 5282 return cxstring::createRef("StringLiteral"); 5283 case CXCursor_CharacterLiteral: 5284 return cxstring::createRef("CharacterLiteral"); 5285 case CXCursor_ParenExpr: 5286 return cxstring::createRef("ParenExpr"); 5287 case CXCursor_UnaryOperator: 5288 return cxstring::createRef("UnaryOperator"); 5289 case CXCursor_ArraySubscriptExpr: 5290 return cxstring::createRef("ArraySubscriptExpr"); 5291 case CXCursor_OMPArraySectionExpr: 5292 return cxstring::createRef("OMPArraySectionExpr"); 5293 case CXCursor_OMPArrayShapingExpr: 5294 return cxstring::createRef("OMPArrayShapingExpr"); 5295 case CXCursor_OMPIteratorExpr: 5296 return cxstring::createRef("OMPIteratorExpr"); 5297 case CXCursor_BinaryOperator: 5298 return cxstring::createRef("BinaryOperator"); 5299 case CXCursor_CompoundAssignOperator: 5300 return cxstring::createRef("CompoundAssignOperator"); 5301 case CXCursor_ConditionalOperator: 5302 return cxstring::createRef("ConditionalOperator"); 5303 case CXCursor_CStyleCastExpr: 5304 return cxstring::createRef("CStyleCastExpr"); 5305 case CXCursor_CompoundLiteralExpr: 5306 return cxstring::createRef("CompoundLiteralExpr"); 5307 case CXCursor_InitListExpr: 5308 return cxstring::createRef("InitListExpr"); 5309 case CXCursor_AddrLabelExpr: 5310 return cxstring::createRef("AddrLabelExpr"); 5311 case CXCursor_StmtExpr: 5312 return cxstring::createRef("StmtExpr"); 5313 case CXCursor_GenericSelectionExpr: 5314 return cxstring::createRef("GenericSelectionExpr"); 5315 case CXCursor_GNUNullExpr: 5316 return cxstring::createRef("GNUNullExpr"); 5317 case CXCursor_CXXStaticCastExpr: 5318 return cxstring::createRef("CXXStaticCastExpr"); 5319 case CXCursor_CXXDynamicCastExpr: 5320 return cxstring::createRef("CXXDynamicCastExpr"); 5321 case CXCursor_CXXReinterpretCastExpr: 5322 return cxstring::createRef("CXXReinterpretCastExpr"); 5323 case CXCursor_CXXConstCastExpr: 5324 return cxstring::createRef("CXXConstCastExpr"); 5325 case CXCursor_CXXFunctionalCastExpr: 5326 return cxstring::createRef("CXXFunctionalCastExpr"); 5327 case CXCursor_CXXAddrspaceCastExpr: 5328 return cxstring::createRef("CXXAddrspaceCastExpr"); 5329 case CXCursor_CXXTypeidExpr: 5330 return cxstring::createRef("CXXTypeidExpr"); 5331 case CXCursor_CXXBoolLiteralExpr: 5332 return cxstring::createRef("CXXBoolLiteralExpr"); 5333 case CXCursor_CXXNullPtrLiteralExpr: 5334 return cxstring::createRef("CXXNullPtrLiteralExpr"); 5335 case CXCursor_CXXThisExpr: 5336 return cxstring::createRef("CXXThisExpr"); 5337 case CXCursor_CXXThrowExpr: 5338 return cxstring::createRef("CXXThrowExpr"); 5339 case CXCursor_CXXNewExpr: 5340 return cxstring::createRef("CXXNewExpr"); 5341 case CXCursor_CXXDeleteExpr: 5342 return cxstring::createRef("CXXDeleteExpr"); 5343 case CXCursor_UnaryExpr: 5344 return cxstring::createRef("UnaryExpr"); 5345 case CXCursor_ObjCStringLiteral: 5346 return cxstring::createRef("ObjCStringLiteral"); 5347 case CXCursor_ObjCBoolLiteralExpr: 5348 return cxstring::createRef("ObjCBoolLiteralExpr"); 5349 case CXCursor_ObjCAvailabilityCheckExpr: 5350 return cxstring::createRef("ObjCAvailabilityCheckExpr"); 5351 case CXCursor_ObjCSelfExpr: 5352 return cxstring::createRef("ObjCSelfExpr"); 5353 case CXCursor_ObjCEncodeExpr: 5354 return cxstring::createRef("ObjCEncodeExpr"); 5355 case CXCursor_ObjCSelectorExpr: 5356 return cxstring::createRef("ObjCSelectorExpr"); 5357 case CXCursor_ObjCProtocolExpr: 5358 return cxstring::createRef("ObjCProtocolExpr"); 5359 case CXCursor_ObjCBridgedCastExpr: 5360 return cxstring::createRef("ObjCBridgedCastExpr"); 5361 case CXCursor_BlockExpr: 5362 return cxstring::createRef("BlockExpr"); 5363 case CXCursor_PackExpansionExpr: 5364 return cxstring::createRef("PackExpansionExpr"); 5365 case CXCursor_SizeOfPackExpr: 5366 return cxstring::createRef("SizeOfPackExpr"); 5367 case CXCursor_LambdaExpr: 5368 return cxstring::createRef("LambdaExpr"); 5369 case CXCursor_UnexposedExpr: 5370 return cxstring::createRef("UnexposedExpr"); 5371 case CXCursor_DeclRefExpr: 5372 return cxstring::createRef("DeclRefExpr"); 5373 case CXCursor_MemberRefExpr: 5374 return cxstring::createRef("MemberRefExpr"); 5375 case CXCursor_CallExpr: 5376 return cxstring::createRef("CallExpr"); 5377 case CXCursor_ObjCMessageExpr: 5378 return cxstring::createRef("ObjCMessageExpr"); 5379 case CXCursor_BuiltinBitCastExpr: 5380 return cxstring::createRef("BuiltinBitCastExpr"); 5381 case CXCursor_UnexposedStmt: 5382 return cxstring::createRef("UnexposedStmt"); 5383 case CXCursor_DeclStmt: 5384 return cxstring::createRef("DeclStmt"); 5385 case CXCursor_LabelStmt: 5386 return cxstring::createRef("LabelStmt"); 5387 case CXCursor_CompoundStmt: 5388 return cxstring::createRef("CompoundStmt"); 5389 case CXCursor_CaseStmt: 5390 return cxstring::createRef("CaseStmt"); 5391 case CXCursor_DefaultStmt: 5392 return cxstring::createRef("DefaultStmt"); 5393 case CXCursor_IfStmt: 5394 return cxstring::createRef("IfStmt"); 5395 case CXCursor_SwitchStmt: 5396 return cxstring::createRef("SwitchStmt"); 5397 case CXCursor_WhileStmt: 5398 return cxstring::createRef("WhileStmt"); 5399 case CXCursor_DoStmt: 5400 return cxstring::createRef("DoStmt"); 5401 case CXCursor_ForStmt: 5402 return cxstring::createRef("ForStmt"); 5403 case CXCursor_GotoStmt: 5404 return cxstring::createRef("GotoStmt"); 5405 case CXCursor_IndirectGotoStmt: 5406 return cxstring::createRef("IndirectGotoStmt"); 5407 case CXCursor_ContinueStmt: 5408 return cxstring::createRef("ContinueStmt"); 5409 case CXCursor_BreakStmt: 5410 return cxstring::createRef("BreakStmt"); 5411 case CXCursor_ReturnStmt: 5412 return cxstring::createRef("ReturnStmt"); 5413 case CXCursor_GCCAsmStmt: 5414 return cxstring::createRef("GCCAsmStmt"); 5415 case CXCursor_MSAsmStmt: 5416 return cxstring::createRef("MSAsmStmt"); 5417 case CXCursor_ObjCAtTryStmt: 5418 return cxstring::createRef("ObjCAtTryStmt"); 5419 case CXCursor_ObjCAtCatchStmt: 5420 return cxstring::createRef("ObjCAtCatchStmt"); 5421 case CXCursor_ObjCAtFinallyStmt: 5422 return cxstring::createRef("ObjCAtFinallyStmt"); 5423 case CXCursor_ObjCAtThrowStmt: 5424 return cxstring::createRef("ObjCAtThrowStmt"); 5425 case CXCursor_ObjCAtSynchronizedStmt: 5426 return cxstring::createRef("ObjCAtSynchronizedStmt"); 5427 case CXCursor_ObjCAutoreleasePoolStmt: 5428 return cxstring::createRef("ObjCAutoreleasePoolStmt"); 5429 case CXCursor_ObjCForCollectionStmt: 5430 return cxstring::createRef("ObjCForCollectionStmt"); 5431 case CXCursor_CXXCatchStmt: 5432 return cxstring::createRef("CXXCatchStmt"); 5433 case CXCursor_CXXTryStmt: 5434 return cxstring::createRef("CXXTryStmt"); 5435 case CXCursor_CXXForRangeStmt: 5436 return cxstring::createRef("CXXForRangeStmt"); 5437 case CXCursor_SEHTryStmt: 5438 return cxstring::createRef("SEHTryStmt"); 5439 case CXCursor_SEHExceptStmt: 5440 return cxstring::createRef("SEHExceptStmt"); 5441 case CXCursor_SEHFinallyStmt: 5442 return cxstring::createRef("SEHFinallyStmt"); 5443 case CXCursor_SEHLeaveStmt: 5444 return cxstring::createRef("SEHLeaveStmt"); 5445 case CXCursor_NullStmt: 5446 return cxstring::createRef("NullStmt"); 5447 case CXCursor_InvalidFile: 5448 return cxstring::createRef("InvalidFile"); 5449 case CXCursor_InvalidCode: 5450 return cxstring::createRef("InvalidCode"); 5451 case CXCursor_NoDeclFound: 5452 return cxstring::createRef("NoDeclFound"); 5453 case CXCursor_NotImplemented: 5454 return cxstring::createRef("NotImplemented"); 5455 case CXCursor_TranslationUnit: 5456 return cxstring::createRef("TranslationUnit"); 5457 case CXCursor_UnexposedAttr: 5458 return cxstring::createRef("UnexposedAttr"); 5459 case CXCursor_IBActionAttr: 5460 return cxstring::createRef("attribute(ibaction)"); 5461 case CXCursor_IBOutletAttr: 5462 return cxstring::createRef("attribute(iboutlet)"); 5463 case CXCursor_IBOutletCollectionAttr: 5464 return cxstring::createRef("attribute(iboutletcollection)"); 5465 case CXCursor_CXXFinalAttr: 5466 return cxstring::createRef("attribute(final)"); 5467 case CXCursor_CXXOverrideAttr: 5468 return cxstring::createRef("attribute(override)"); 5469 case CXCursor_AnnotateAttr: 5470 return cxstring::createRef("attribute(annotate)"); 5471 case CXCursor_AsmLabelAttr: 5472 return cxstring::createRef("asm label"); 5473 case CXCursor_PackedAttr: 5474 return cxstring::createRef("attribute(packed)"); 5475 case CXCursor_PureAttr: 5476 return cxstring::createRef("attribute(pure)"); 5477 case CXCursor_ConstAttr: 5478 return cxstring::createRef("attribute(const)"); 5479 case CXCursor_NoDuplicateAttr: 5480 return cxstring::createRef("attribute(noduplicate)"); 5481 case CXCursor_CUDAConstantAttr: 5482 return cxstring::createRef("attribute(constant)"); 5483 case CXCursor_CUDADeviceAttr: 5484 return cxstring::createRef("attribute(device)"); 5485 case CXCursor_CUDAGlobalAttr: 5486 return cxstring::createRef("attribute(global)"); 5487 case CXCursor_CUDAHostAttr: 5488 return cxstring::createRef("attribute(host)"); 5489 case CXCursor_CUDASharedAttr: 5490 return cxstring::createRef("attribute(shared)"); 5491 case CXCursor_VisibilityAttr: 5492 return cxstring::createRef("attribute(visibility)"); 5493 case CXCursor_DLLExport: 5494 return cxstring::createRef("attribute(dllexport)"); 5495 case CXCursor_DLLImport: 5496 return cxstring::createRef("attribute(dllimport)"); 5497 case CXCursor_NSReturnsRetained: 5498 return cxstring::createRef("attribute(ns_returns_retained)"); 5499 case CXCursor_NSReturnsNotRetained: 5500 return cxstring::createRef("attribute(ns_returns_not_retained)"); 5501 case CXCursor_NSReturnsAutoreleased: 5502 return cxstring::createRef("attribute(ns_returns_autoreleased)"); 5503 case CXCursor_NSConsumesSelf: 5504 return cxstring::createRef("attribute(ns_consumes_self)"); 5505 case CXCursor_NSConsumed: 5506 return cxstring::createRef("attribute(ns_consumed)"); 5507 case CXCursor_ObjCException: 5508 return cxstring::createRef("attribute(objc_exception)"); 5509 case CXCursor_ObjCNSObject: 5510 return cxstring::createRef("attribute(NSObject)"); 5511 case CXCursor_ObjCIndependentClass: 5512 return cxstring::createRef("attribute(objc_independent_class)"); 5513 case CXCursor_ObjCPreciseLifetime: 5514 return cxstring::createRef("attribute(objc_precise_lifetime)"); 5515 case CXCursor_ObjCReturnsInnerPointer: 5516 return cxstring::createRef("attribute(objc_returns_inner_pointer)"); 5517 case CXCursor_ObjCRequiresSuper: 5518 return cxstring::createRef("attribute(objc_requires_super)"); 5519 case CXCursor_ObjCRootClass: 5520 return cxstring::createRef("attribute(objc_root_class)"); 5521 case CXCursor_ObjCSubclassingRestricted: 5522 return cxstring::createRef("attribute(objc_subclassing_restricted)"); 5523 case CXCursor_ObjCExplicitProtocolImpl: 5524 return cxstring::createRef( 5525 "attribute(objc_protocol_requires_explicit_implementation)"); 5526 case CXCursor_ObjCDesignatedInitializer: 5527 return cxstring::createRef("attribute(objc_designated_initializer)"); 5528 case CXCursor_ObjCRuntimeVisible: 5529 return cxstring::createRef("attribute(objc_runtime_visible)"); 5530 case CXCursor_ObjCBoxable: 5531 return cxstring::createRef("attribute(objc_boxable)"); 5532 case CXCursor_FlagEnum: 5533 return cxstring::createRef("attribute(flag_enum)"); 5534 case CXCursor_PreprocessingDirective: 5535 return cxstring::createRef("preprocessing directive"); 5536 case CXCursor_MacroDefinition: 5537 return cxstring::createRef("macro definition"); 5538 case CXCursor_MacroExpansion: 5539 return cxstring::createRef("macro expansion"); 5540 case CXCursor_InclusionDirective: 5541 return cxstring::createRef("inclusion directive"); 5542 case CXCursor_Namespace: 5543 return cxstring::createRef("Namespace"); 5544 case CXCursor_LinkageSpec: 5545 return cxstring::createRef("LinkageSpec"); 5546 case CXCursor_CXXBaseSpecifier: 5547 return cxstring::createRef("C++ base class specifier"); 5548 case CXCursor_Constructor: 5549 return cxstring::createRef("CXXConstructor"); 5550 case CXCursor_Destructor: 5551 return cxstring::createRef("CXXDestructor"); 5552 case CXCursor_ConversionFunction: 5553 return cxstring::createRef("CXXConversion"); 5554 case CXCursor_TemplateTypeParameter: 5555 return cxstring::createRef("TemplateTypeParameter"); 5556 case CXCursor_NonTypeTemplateParameter: 5557 return cxstring::createRef("NonTypeTemplateParameter"); 5558 case CXCursor_TemplateTemplateParameter: 5559 return cxstring::createRef("TemplateTemplateParameter"); 5560 case CXCursor_FunctionTemplate: 5561 return cxstring::createRef("FunctionTemplate"); 5562 case CXCursor_ClassTemplate: 5563 return cxstring::createRef("ClassTemplate"); 5564 case CXCursor_ClassTemplatePartialSpecialization: 5565 return cxstring::createRef("ClassTemplatePartialSpecialization"); 5566 case CXCursor_NamespaceAlias: 5567 return cxstring::createRef("NamespaceAlias"); 5568 case CXCursor_UsingDirective: 5569 return cxstring::createRef("UsingDirective"); 5570 case CXCursor_UsingDeclaration: 5571 return cxstring::createRef("UsingDeclaration"); 5572 case CXCursor_TypeAliasDecl: 5573 return cxstring::createRef("TypeAliasDecl"); 5574 case CXCursor_ObjCSynthesizeDecl: 5575 return cxstring::createRef("ObjCSynthesizeDecl"); 5576 case CXCursor_ObjCDynamicDecl: 5577 return cxstring::createRef("ObjCDynamicDecl"); 5578 case CXCursor_CXXAccessSpecifier: 5579 return cxstring::createRef("CXXAccessSpecifier"); 5580 case CXCursor_ModuleImportDecl: 5581 return cxstring::createRef("ModuleImport"); 5582 case CXCursor_OMPCanonicalLoop: 5583 return cxstring::createRef("OMPCanonicalLoop"); 5584 case CXCursor_OMPParallelDirective: 5585 return cxstring::createRef("OMPParallelDirective"); 5586 case CXCursor_OMPSimdDirective: 5587 return cxstring::createRef("OMPSimdDirective"); 5588 case CXCursor_OMPTileDirective: 5589 return cxstring::createRef("OMPTileDirective"); 5590 case CXCursor_OMPUnrollDirective: 5591 return cxstring::createRef("OMPUnrollDirective"); 5592 case CXCursor_OMPForDirective: 5593 return cxstring::createRef("OMPForDirective"); 5594 case CXCursor_OMPForSimdDirective: 5595 return cxstring::createRef("OMPForSimdDirective"); 5596 case CXCursor_OMPSectionsDirective: 5597 return cxstring::createRef("OMPSectionsDirective"); 5598 case CXCursor_OMPSectionDirective: 5599 return cxstring::createRef("OMPSectionDirective"); 5600 case CXCursor_OMPSingleDirective: 5601 return cxstring::createRef("OMPSingleDirective"); 5602 case CXCursor_OMPMasterDirective: 5603 return cxstring::createRef("OMPMasterDirective"); 5604 case CXCursor_OMPCriticalDirective: 5605 return cxstring::createRef("OMPCriticalDirective"); 5606 case CXCursor_OMPParallelForDirective: 5607 return cxstring::createRef("OMPParallelForDirective"); 5608 case CXCursor_OMPParallelForSimdDirective: 5609 return cxstring::createRef("OMPParallelForSimdDirective"); 5610 case CXCursor_OMPParallelMasterDirective: 5611 return cxstring::createRef("OMPParallelMasterDirective"); 5612 case CXCursor_OMPParallelSectionsDirective: 5613 return cxstring::createRef("OMPParallelSectionsDirective"); 5614 case CXCursor_OMPTaskDirective: 5615 return cxstring::createRef("OMPTaskDirective"); 5616 case CXCursor_OMPTaskyieldDirective: 5617 return cxstring::createRef("OMPTaskyieldDirective"); 5618 case CXCursor_OMPBarrierDirective: 5619 return cxstring::createRef("OMPBarrierDirective"); 5620 case CXCursor_OMPTaskwaitDirective: 5621 return cxstring::createRef("OMPTaskwaitDirective"); 5622 case CXCursor_OMPTaskgroupDirective: 5623 return cxstring::createRef("OMPTaskgroupDirective"); 5624 case CXCursor_OMPFlushDirective: 5625 return cxstring::createRef("OMPFlushDirective"); 5626 case CXCursor_OMPDepobjDirective: 5627 return cxstring::createRef("OMPDepobjDirective"); 5628 case CXCursor_OMPScanDirective: 5629 return cxstring::createRef("OMPScanDirective"); 5630 case CXCursor_OMPOrderedDirective: 5631 return cxstring::createRef("OMPOrderedDirective"); 5632 case CXCursor_OMPAtomicDirective: 5633 return cxstring::createRef("OMPAtomicDirective"); 5634 case CXCursor_OMPTargetDirective: 5635 return cxstring::createRef("OMPTargetDirective"); 5636 case CXCursor_OMPTargetDataDirective: 5637 return cxstring::createRef("OMPTargetDataDirective"); 5638 case CXCursor_OMPTargetEnterDataDirective: 5639 return cxstring::createRef("OMPTargetEnterDataDirective"); 5640 case CXCursor_OMPTargetExitDataDirective: 5641 return cxstring::createRef("OMPTargetExitDataDirective"); 5642 case CXCursor_OMPTargetParallelDirective: 5643 return cxstring::createRef("OMPTargetParallelDirective"); 5644 case CXCursor_OMPTargetParallelForDirective: 5645 return cxstring::createRef("OMPTargetParallelForDirective"); 5646 case CXCursor_OMPTargetUpdateDirective: 5647 return cxstring::createRef("OMPTargetUpdateDirective"); 5648 case CXCursor_OMPTeamsDirective: 5649 return cxstring::createRef("OMPTeamsDirective"); 5650 case CXCursor_OMPCancellationPointDirective: 5651 return cxstring::createRef("OMPCancellationPointDirective"); 5652 case CXCursor_OMPCancelDirective: 5653 return cxstring::createRef("OMPCancelDirective"); 5654 case CXCursor_OMPTaskLoopDirective: 5655 return cxstring::createRef("OMPTaskLoopDirective"); 5656 case CXCursor_OMPTaskLoopSimdDirective: 5657 return cxstring::createRef("OMPTaskLoopSimdDirective"); 5658 case CXCursor_OMPMasterTaskLoopDirective: 5659 return cxstring::createRef("OMPMasterTaskLoopDirective"); 5660 case CXCursor_OMPMasterTaskLoopSimdDirective: 5661 return cxstring::createRef("OMPMasterTaskLoopSimdDirective"); 5662 case CXCursor_OMPParallelMasterTaskLoopDirective: 5663 return cxstring::createRef("OMPParallelMasterTaskLoopDirective"); 5664 case CXCursor_OMPParallelMasterTaskLoopSimdDirective: 5665 return cxstring::createRef("OMPParallelMasterTaskLoopSimdDirective"); 5666 case CXCursor_OMPDistributeDirective: 5667 return cxstring::createRef("OMPDistributeDirective"); 5668 case CXCursor_OMPDistributeParallelForDirective: 5669 return cxstring::createRef("OMPDistributeParallelForDirective"); 5670 case CXCursor_OMPDistributeParallelForSimdDirective: 5671 return cxstring::createRef("OMPDistributeParallelForSimdDirective"); 5672 case CXCursor_OMPDistributeSimdDirective: 5673 return cxstring::createRef("OMPDistributeSimdDirective"); 5674 case CXCursor_OMPTargetParallelForSimdDirective: 5675 return cxstring::createRef("OMPTargetParallelForSimdDirective"); 5676 case CXCursor_OMPTargetSimdDirective: 5677 return cxstring::createRef("OMPTargetSimdDirective"); 5678 case CXCursor_OMPTeamsDistributeDirective: 5679 return cxstring::createRef("OMPTeamsDistributeDirective"); 5680 case CXCursor_OMPTeamsDistributeSimdDirective: 5681 return cxstring::createRef("OMPTeamsDistributeSimdDirective"); 5682 case CXCursor_OMPTeamsDistributeParallelForSimdDirective: 5683 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective"); 5684 case CXCursor_OMPTeamsDistributeParallelForDirective: 5685 return cxstring::createRef("OMPTeamsDistributeParallelForDirective"); 5686 case CXCursor_OMPTargetTeamsDirective: 5687 return cxstring::createRef("OMPTargetTeamsDirective"); 5688 case CXCursor_OMPTargetTeamsDistributeDirective: 5689 return cxstring::createRef("OMPTargetTeamsDistributeDirective"); 5690 case CXCursor_OMPTargetTeamsDistributeParallelForDirective: 5691 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective"); 5692 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective: 5693 return cxstring::createRef( 5694 "OMPTargetTeamsDistributeParallelForSimdDirective"); 5695 case CXCursor_OMPTargetTeamsDistributeSimdDirective: 5696 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective"); 5697 case CXCursor_OMPInteropDirective: 5698 return cxstring::createRef("OMPInteropDirective"); 5699 case CXCursor_OMPDispatchDirective: 5700 return cxstring::createRef("OMPDispatchDirective"); 5701 case CXCursor_OMPMaskedDirective: 5702 return cxstring::createRef("OMPMaskedDirective"); 5703 case CXCursor_OverloadCandidate: 5704 return cxstring::createRef("OverloadCandidate"); 5705 case CXCursor_TypeAliasTemplateDecl: 5706 return cxstring::createRef("TypeAliasTemplateDecl"); 5707 case CXCursor_StaticAssert: 5708 return cxstring::createRef("StaticAssert"); 5709 case CXCursor_FriendDecl: 5710 return cxstring::createRef("FriendDecl"); 5711 case CXCursor_ConvergentAttr: 5712 return cxstring::createRef("attribute(convergent)"); 5713 case CXCursor_WarnUnusedAttr: 5714 return cxstring::createRef("attribute(warn_unused)"); 5715 case CXCursor_WarnUnusedResultAttr: 5716 return cxstring::createRef("attribute(warn_unused_result)"); 5717 case CXCursor_AlignedAttr: 5718 return cxstring::createRef("attribute(aligned)"); 5719 } 5720 5721 llvm_unreachable("Unhandled CXCursorKind"); 5722 } 5723 5724 struct GetCursorData { 5725 SourceLocation TokenBeginLoc; 5726 bool PointsAtMacroArgExpansion; 5727 bool VisitedObjCPropertyImplDecl; 5728 SourceLocation VisitedDeclaratorDeclStartLoc; 5729 CXCursor &BestCursor; 5730 5731 GetCursorData(SourceManager &SM, SourceLocation tokenBegin, 5732 CXCursor &outputCursor) 5733 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) { 5734 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin); 5735 VisitedObjCPropertyImplDecl = false; 5736 } 5737 }; 5738 5739 static enum CXChildVisitResult 5740 GetCursorVisitor(CXCursor cursor, CXCursor parent, CXClientData client_data) { 5741 GetCursorData *Data = static_cast<GetCursorData *>(client_data); 5742 CXCursor *BestCursor = &Data->BestCursor; 5743 5744 // If we point inside a macro argument we should provide info of what the 5745 // token is so use the actual cursor, don't replace it with a macro expansion 5746 // cursor. 5747 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion) 5748 return CXChildVisit_Recurse; 5749 5750 if (clang_isDeclaration(cursor.kind)) { 5751 // Avoid having the implicit methods override the property decls. 5752 if (const ObjCMethodDecl *MD = 5753 dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) { 5754 if (MD->isImplicit()) 5755 return CXChildVisit_Break; 5756 5757 } else if (const ObjCInterfaceDecl *ID = 5758 dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) { 5759 // Check that when we have multiple @class references in the same line, 5760 // that later ones do not override the previous ones. 5761 // If we have: 5762 // @class Foo, Bar; 5763 // source ranges for both start at '@', so 'Bar' will end up overriding 5764 // 'Foo' even though the cursor location was at 'Foo'. 5765 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl || 5766 BestCursor->kind == CXCursor_ObjCClassRef) 5767 if (const ObjCInterfaceDecl *PrevID = 5768 dyn_cast_or_null<ObjCInterfaceDecl>( 5769 getCursorDecl(*BestCursor))) { 5770 if (PrevID != ID && !PrevID->isThisDeclarationADefinition() && 5771 !ID->isThisDeclarationADefinition()) 5772 return CXChildVisit_Break; 5773 } 5774 5775 } else if (const DeclaratorDecl *DD = 5776 dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) { 5777 SourceLocation StartLoc = DD->getSourceRange().getBegin(); 5778 // Check that when we have multiple declarators in the same line, 5779 // that later ones do not override the previous ones. 5780 // If we have: 5781 // int Foo, Bar; 5782 // source ranges for both start at 'int', so 'Bar' will end up overriding 5783 // 'Foo' even though the cursor location was at 'Foo'. 5784 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc) 5785 return CXChildVisit_Break; 5786 Data->VisitedDeclaratorDeclStartLoc = StartLoc; 5787 5788 } else if (const ObjCPropertyImplDecl *PropImp = 5789 dyn_cast_or_null<ObjCPropertyImplDecl>( 5790 getCursorDecl(cursor))) { 5791 (void)PropImp; 5792 // Check that when we have multiple @synthesize in the same line, 5793 // that later ones do not override the previous ones. 5794 // If we have: 5795 // @synthesize Foo, Bar; 5796 // source ranges for both start at '@', so 'Bar' will end up overriding 5797 // 'Foo' even though the cursor location was at 'Foo'. 5798 if (Data->VisitedObjCPropertyImplDecl) 5799 return CXChildVisit_Break; 5800 Data->VisitedObjCPropertyImplDecl = true; 5801 } 5802 } 5803 5804 if (clang_isExpression(cursor.kind) && 5805 clang_isDeclaration(BestCursor->kind)) { 5806 if (const Decl *D = getCursorDecl(*BestCursor)) { 5807 // Avoid having the cursor of an expression replace the declaration cursor 5808 // when the expression source range overlaps the declaration range. 5809 // This can happen for C++ constructor expressions whose range generally 5810 // include the variable declaration, e.g.: 5811 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl 5812 // cursor. 5813 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() && 5814 D->getLocation() == Data->TokenBeginLoc) 5815 return CXChildVisit_Break; 5816 } 5817 } 5818 5819 // If our current best cursor is the construction of a temporary object, 5820 // don't replace that cursor with a type reference, because we want 5821 // clang_getCursor() to point at the constructor. 5822 if (clang_isExpression(BestCursor->kind) && 5823 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) && 5824 cursor.kind == CXCursor_TypeRef) { 5825 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it 5826 // as having the actual point on the type reference. 5827 *BestCursor = getTypeRefedCallExprCursor(*BestCursor); 5828 return CXChildVisit_Recurse; 5829 } 5830 5831 // If we already have an Objective-C superclass reference, don't 5832 // update it further. 5833 if (BestCursor->kind == CXCursor_ObjCSuperClassRef) 5834 return CXChildVisit_Break; 5835 5836 *BestCursor = cursor; 5837 return CXChildVisit_Recurse; 5838 } 5839 5840 CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) { 5841 if (isNotUsableTU(TU)) { 5842 LOG_BAD_TU(TU); 5843 return clang_getNullCursor(); 5844 } 5845 5846 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 5847 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 5848 5849 SourceLocation SLoc = cxloc::translateSourceLocation(Loc); 5850 CXCursor Result = cxcursor::getCursor(TU, SLoc); 5851 5852 LOG_FUNC_SECTION { 5853 CXFile SearchFile; 5854 unsigned SearchLine, SearchColumn; 5855 CXFile ResultFile; 5856 unsigned ResultLine, ResultColumn; 5857 CXString SearchFileName, ResultFileName, KindSpelling, USR; 5858 const char *IsDef = clang_isCursorDefinition(Result) ? " (Definition)" : ""; 5859 CXSourceLocation ResultLoc = clang_getCursorLocation(Result); 5860 5861 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 5862 nullptr); 5863 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine, &ResultColumn, 5864 nullptr); 5865 SearchFileName = clang_getFileName(SearchFile); 5866 ResultFileName = clang_getFileName(ResultFile); 5867 KindSpelling = clang_getCursorKindSpelling(Result.kind); 5868 USR = clang_getCursorUSR(Result); 5869 *Log << llvm::format("(%s:%d:%d) = %s", clang_getCString(SearchFileName), 5870 SearchLine, SearchColumn, 5871 clang_getCString(KindSpelling)) 5872 << llvm::format("(%s:%d:%d):%s%s", clang_getCString(ResultFileName), 5873 ResultLine, ResultColumn, clang_getCString(USR), 5874 IsDef); 5875 clang_disposeString(SearchFileName); 5876 clang_disposeString(ResultFileName); 5877 clang_disposeString(KindSpelling); 5878 clang_disposeString(USR); 5879 5880 CXCursor Definition = clang_getCursorDefinition(Result); 5881 if (!clang_equalCursors(Definition, clang_getNullCursor())) { 5882 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition); 5883 CXString DefinitionKindSpelling = 5884 clang_getCursorKindSpelling(Definition.kind); 5885 CXFile DefinitionFile; 5886 unsigned DefinitionLine, DefinitionColumn; 5887 clang_getFileLocation(DefinitionLoc, &DefinitionFile, &DefinitionLine, 5888 &DefinitionColumn, nullptr); 5889 CXString DefinitionFileName = clang_getFileName(DefinitionFile); 5890 *Log << llvm::format(" -> %s(%s:%d:%d)", 5891 clang_getCString(DefinitionKindSpelling), 5892 clang_getCString(DefinitionFileName), DefinitionLine, 5893 DefinitionColumn); 5894 clang_disposeString(DefinitionFileName); 5895 clang_disposeString(DefinitionKindSpelling); 5896 } 5897 } 5898 5899 return Result; 5900 } 5901 5902 CXCursor clang_getNullCursor(void) { 5903 return MakeCXCursorInvalid(CXCursor_InvalidFile); 5904 } 5905 5906 unsigned clang_equalCursors(CXCursor X, CXCursor Y) { 5907 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we 5908 // can't set consistently. For example, when visiting a DeclStmt we will set 5909 // it but we don't set it on the result of clang_getCursorDefinition for 5910 // a reference of the same declaration. 5911 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works 5912 // when visiting a DeclStmt currently, the AST should be enhanced to be able 5913 // to provide that kind of info. 5914 if (clang_isDeclaration(X.kind)) 5915 X.data[1] = nullptr; 5916 if (clang_isDeclaration(Y.kind)) 5917 Y.data[1] = nullptr; 5918 5919 return X == Y; 5920 } 5921 5922 unsigned clang_hashCursor(CXCursor C) { 5923 unsigned Index = 0; 5924 if (clang_isExpression(C.kind) || clang_isStatement(C.kind)) 5925 Index = 1; 5926 5927 return llvm::DenseMapInfo<std::pair<unsigned, const void *>>::getHashValue( 5928 std::make_pair(C.kind, C.data[Index])); 5929 } 5930 5931 unsigned clang_isInvalid(enum CXCursorKind K) { 5932 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid; 5933 } 5934 5935 unsigned clang_isDeclaration(enum CXCursorKind K) { 5936 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) || 5937 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl); 5938 } 5939 5940 unsigned clang_isInvalidDeclaration(CXCursor C) { 5941 if (clang_isDeclaration(C.kind)) { 5942 if (const Decl *D = getCursorDecl(C)) 5943 return D->isInvalidDecl(); 5944 } 5945 5946 return 0; 5947 } 5948 5949 unsigned clang_isReference(enum CXCursorKind K) { 5950 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef; 5951 } 5952 5953 unsigned clang_isExpression(enum CXCursorKind K) { 5954 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr; 5955 } 5956 5957 unsigned clang_isStatement(enum CXCursorKind K) { 5958 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt; 5959 } 5960 5961 unsigned clang_isAttribute(enum CXCursorKind K) { 5962 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr; 5963 } 5964 5965 unsigned clang_isTranslationUnit(enum CXCursorKind K) { 5966 return K == CXCursor_TranslationUnit; 5967 } 5968 5969 unsigned clang_isPreprocessing(enum CXCursorKind K) { 5970 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing; 5971 } 5972 5973 unsigned clang_isUnexposed(enum CXCursorKind K) { 5974 switch (K) { 5975 case CXCursor_UnexposedDecl: 5976 case CXCursor_UnexposedExpr: 5977 case CXCursor_UnexposedStmt: 5978 case CXCursor_UnexposedAttr: 5979 return true; 5980 default: 5981 return false; 5982 } 5983 } 5984 5985 CXCursorKind clang_getCursorKind(CXCursor C) { return C.kind; } 5986 5987 CXSourceLocation clang_getCursorLocation(CXCursor C) { 5988 if (clang_isReference(C.kind)) { 5989 switch (C.kind) { 5990 case CXCursor_ObjCSuperClassRef: { 5991 std::pair<const ObjCInterfaceDecl *, SourceLocation> P = 5992 getCursorObjCSuperClassRef(C); 5993 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 5994 } 5995 5996 case CXCursor_ObjCProtocolRef: { 5997 std::pair<const ObjCProtocolDecl *, SourceLocation> P = 5998 getCursorObjCProtocolRef(C); 5999 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 6000 } 6001 6002 case CXCursor_ObjCClassRef: { 6003 std::pair<const ObjCInterfaceDecl *, SourceLocation> P = 6004 getCursorObjCClassRef(C); 6005 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 6006 } 6007 6008 case CXCursor_TypeRef: { 6009 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C); 6010 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 6011 } 6012 6013 case CXCursor_TemplateRef: { 6014 std::pair<const TemplateDecl *, SourceLocation> P = 6015 getCursorTemplateRef(C); 6016 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 6017 } 6018 6019 case CXCursor_NamespaceRef: { 6020 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C); 6021 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 6022 } 6023 6024 case CXCursor_MemberRef: { 6025 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C); 6026 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 6027 } 6028 6029 case CXCursor_VariableRef: { 6030 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C); 6031 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 6032 } 6033 6034 case CXCursor_CXXBaseSpecifier: { 6035 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C); 6036 if (!BaseSpec) 6037 return clang_getNullLocation(); 6038 6039 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo()) 6040 return cxloc::translateSourceLocation( 6041 getCursorContext(C), TSInfo->getTypeLoc().getBeginLoc()); 6042 6043 return cxloc::translateSourceLocation(getCursorContext(C), 6044 BaseSpec->getBeginLoc()); 6045 } 6046 6047 case CXCursor_LabelRef: { 6048 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C); 6049 return cxloc::translateSourceLocation(getCursorContext(C), P.second); 6050 } 6051 6052 case CXCursor_OverloadedDeclRef: 6053 return cxloc::translateSourceLocation( 6054 getCursorContext(C), getCursorOverloadedDeclRef(C).second); 6055 6056 default: 6057 // FIXME: Need a way to enumerate all non-reference cases. 6058 llvm_unreachable("Missed a reference kind"); 6059 } 6060 } 6061 6062 if (clang_isExpression(C.kind)) 6063 return cxloc::translateSourceLocation( 6064 getCursorContext(C), getLocationFromExpr(getCursorExpr(C))); 6065 6066 if (clang_isStatement(C.kind)) 6067 return cxloc::translateSourceLocation(getCursorContext(C), 6068 getCursorStmt(C)->getBeginLoc()); 6069 6070 if (C.kind == CXCursor_PreprocessingDirective) { 6071 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin(); 6072 return cxloc::translateSourceLocation(getCursorContext(C), L); 6073 } 6074 6075 if (C.kind == CXCursor_MacroExpansion) { 6076 SourceLocation L = 6077 cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin(); 6078 return cxloc::translateSourceLocation(getCursorContext(C), L); 6079 } 6080 6081 if (C.kind == CXCursor_MacroDefinition) { 6082 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation(); 6083 return cxloc::translateSourceLocation(getCursorContext(C), L); 6084 } 6085 6086 if (C.kind == CXCursor_InclusionDirective) { 6087 SourceLocation L = 6088 cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin(); 6089 return cxloc::translateSourceLocation(getCursorContext(C), L); 6090 } 6091 6092 if (clang_isAttribute(C.kind)) { 6093 SourceLocation L = cxcursor::getCursorAttr(C)->getLocation(); 6094 return cxloc::translateSourceLocation(getCursorContext(C), L); 6095 } 6096 6097 if (!clang_isDeclaration(C.kind)) 6098 return clang_getNullLocation(); 6099 6100 const Decl *D = getCursorDecl(C); 6101 if (!D) 6102 return clang_getNullLocation(); 6103 6104 SourceLocation Loc = D->getLocation(); 6105 // FIXME: Multiple variables declared in a single declaration 6106 // currently lack the information needed to correctly determine their 6107 // ranges when accounting for the type-specifier. We use context 6108 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, 6109 // and if so, whether it is the first decl. 6110 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 6111 if (!cxcursor::isFirstInDeclGroup(C)) 6112 Loc = VD->getLocation(); 6113 } 6114 6115 // For ObjC methods, give the start location of the method name. 6116 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) 6117 Loc = MD->getSelectorStartLoc(); 6118 6119 return cxloc::translateSourceLocation(getCursorContext(C), Loc); 6120 } 6121 6122 } // end extern "C" 6123 6124 CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) { 6125 assert(TU); 6126 6127 // Guard against an invalid SourceLocation, or we may assert in one 6128 // of the following calls. 6129 if (SLoc.isInvalid()) 6130 return clang_getNullCursor(); 6131 6132 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 6133 6134 // Translate the given source location to make it point at the beginning of 6135 // the token under the cursor. 6136 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(), 6137 CXXUnit->getASTContext().getLangOpts()); 6138 6139 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound); 6140 if (SLoc.isValid()) { 6141 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result); 6142 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData, 6143 /*VisitPreprocessorLast=*/true, 6144 /*VisitIncludedEntities=*/false, 6145 SourceLocation(SLoc)); 6146 CursorVis.visitFileRegion(); 6147 } 6148 6149 return Result; 6150 } 6151 6152 static SourceRange getRawCursorExtent(CXCursor C) { 6153 if (clang_isReference(C.kind)) { 6154 switch (C.kind) { 6155 case CXCursor_ObjCSuperClassRef: 6156 return getCursorObjCSuperClassRef(C).second; 6157 6158 case CXCursor_ObjCProtocolRef: 6159 return getCursorObjCProtocolRef(C).second; 6160 6161 case CXCursor_ObjCClassRef: 6162 return getCursorObjCClassRef(C).second; 6163 6164 case CXCursor_TypeRef: 6165 return getCursorTypeRef(C).second; 6166 6167 case CXCursor_TemplateRef: 6168 return getCursorTemplateRef(C).second; 6169 6170 case CXCursor_NamespaceRef: 6171 return getCursorNamespaceRef(C).second; 6172 6173 case CXCursor_MemberRef: 6174 return getCursorMemberRef(C).second; 6175 6176 case CXCursor_CXXBaseSpecifier: 6177 return getCursorCXXBaseSpecifier(C)->getSourceRange(); 6178 6179 case CXCursor_LabelRef: 6180 return getCursorLabelRef(C).second; 6181 6182 case CXCursor_OverloadedDeclRef: 6183 return getCursorOverloadedDeclRef(C).second; 6184 6185 case CXCursor_VariableRef: 6186 return getCursorVariableRef(C).second; 6187 6188 default: 6189 // FIXME: Need a way to enumerate all non-reference cases. 6190 llvm_unreachable("Missed a reference kind"); 6191 } 6192 } 6193 6194 if (clang_isExpression(C.kind)) 6195 return getCursorExpr(C)->getSourceRange(); 6196 6197 if (clang_isStatement(C.kind)) 6198 return getCursorStmt(C)->getSourceRange(); 6199 6200 if (clang_isAttribute(C.kind)) 6201 return getCursorAttr(C)->getRange(); 6202 6203 if (C.kind == CXCursor_PreprocessingDirective) 6204 return cxcursor::getCursorPreprocessingDirective(C); 6205 6206 if (C.kind == CXCursor_MacroExpansion) { 6207 ASTUnit *TU = getCursorASTUnit(C); 6208 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange(); 6209 return TU->mapRangeFromPreamble(Range); 6210 } 6211 6212 if (C.kind == CXCursor_MacroDefinition) { 6213 ASTUnit *TU = getCursorASTUnit(C); 6214 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange(); 6215 return TU->mapRangeFromPreamble(Range); 6216 } 6217 6218 if (C.kind == CXCursor_InclusionDirective) { 6219 ASTUnit *TU = getCursorASTUnit(C); 6220 SourceRange Range = 6221 cxcursor::getCursorInclusionDirective(C)->getSourceRange(); 6222 return TU->mapRangeFromPreamble(Range); 6223 } 6224 6225 if (C.kind == CXCursor_TranslationUnit) { 6226 ASTUnit *TU = getCursorASTUnit(C); 6227 FileID MainID = TU->getSourceManager().getMainFileID(); 6228 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID); 6229 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID); 6230 return SourceRange(Start, End); 6231 } 6232 6233 if (clang_isDeclaration(C.kind)) { 6234 const Decl *D = cxcursor::getCursorDecl(C); 6235 if (!D) 6236 return SourceRange(); 6237 6238 SourceRange R = D->getSourceRange(); 6239 // FIXME: Multiple variables declared in a single declaration 6240 // currently lack the information needed to correctly determine their 6241 // ranges when accounting for the type-specifier. We use context 6242 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, 6243 // and if so, whether it is the first decl. 6244 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 6245 if (!cxcursor::isFirstInDeclGroup(C)) 6246 R.setBegin(VD->getLocation()); 6247 } 6248 return R; 6249 } 6250 return SourceRange(); 6251 } 6252 6253 /// Retrieves the "raw" cursor extent, which is then extended to include 6254 /// the decl-specifier-seq for declarations. 6255 static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) { 6256 if (clang_isDeclaration(C.kind)) { 6257 const Decl *D = cxcursor::getCursorDecl(C); 6258 if (!D) 6259 return SourceRange(); 6260 6261 SourceRange R = D->getSourceRange(); 6262 6263 // Adjust the start of the location for declarations preceded by 6264 // declaration specifiers. 6265 SourceLocation StartLoc; 6266 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 6267 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) 6268 StartLoc = TI->getTypeLoc().getBeginLoc(); 6269 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) { 6270 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo()) 6271 StartLoc = TI->getTypeLoc().getBeginLoc(); 6272 } 6273 6274 if (StartLoc.isValid() && R.getBegin().isValid() && 6275 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin())) 6276 R.setBegin(StartLoc); 6277 6278 // FIXME: Multiple variables declared in a single declaration 6279 // currently lack the information needed to correctly determine their 6280 // ranges when accounting for the type-specifier. We use context 6281 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, 6282 // and if so, whether it is the first decl. 6283 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 6284 if (!cxcursor::isFirstInDeclGroup(C)) 6285 R.setBegin(VD->getLocation()); 6286 } 6287 6288 return R; 6289 } 6290 6291 return getRawCursorExtent(C); 6292 } 6293 6294 CXSourceRange clang_getCursorExtent(CXCursor C) { 6295 SourceRange R = getRawCursorExtent(C); 6296 if (R.isInvalid()) 6297 return clang_getNullRange(); 6298 6299 return cxloc::translateSourceRange(getCursorContext(C), R); 6300 } 6301 6302 CXCursor clang_getCursorReferenced(CXCursor C) { 6303 if (clang_isInvalid(C.kind)) 6304 return clang_getNullCursor(); 6305 6306 CXTranslationUnit tu = getCursorTU(C); 6307 if (clang_isDeclaration(C.kind)) { 6308 const Decl *D = getCursorDecl(C); 6309 if (!D) 6310 return clang_getNullCursor(); 6311 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) 6312 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu); 6313 if (const ObjCPropertyImplDecl *PropImpl = 6314 dyn_cast<ObjCPropertyImplDecl>(D)) 6315 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl()) 6316 return MakeCXCursor(Property, tu); 6317 6318 return C; 6319 } 6320 6321 if (clang_isExpression(C.kind)) { 6322 const Expr *E = getCursorExpr(C); 6323 const Decl *D = getDeclFromExpr(E); 6324 if (D) { 6325 CXCursor declCursor = MakeCXCursor(D, tu); 6326 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C), 6327 declCursor); 6328 return declCursor; 6329 } 6330 6331 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E)) 6332 return MakeCursorOverloadedDeclRef(Ovl, tu); 6333 6334 return clang_getNullCursor(); 6335 } 6336 6337 if (clang_isStatement(C.kind)) { 6338 const Stmt *S = getCursorStmt(C); 6339 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S)) 6340 if (LabelDecl *label = Goto->getLabel()) 6341 if (LabelStmt *labelS = label->getStmt()) 6342 return MakeCXCursor(labelS, getCursorDecl(C), tu); 6343 6344 return clang_getNullCursor(); 6345 } 6346 6347 if (C.kind == CXCursor_MacroExpansion) { 6348 if (const MacroDefinitionRecord *Def = 6349 getCursorMacroExpansion(C).getDefinition()) 6350 return MakeMacroDefinitionCursor(Def, tu); 6351 } 6352 6353 if (!clang_isReference(C.kind)) 6354 return clang_getNullCursor(); 6355 6356 switch (C.kind) { 6357 case CXCursor_ObjCSuperClassRef: 6358 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu); 6359 6360 case CXCursor_ObjCProtocolRef: { 6361 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first; 6362 if (const ObjCProtocolDecl *Def = Prot->getDefinition()) 6363 return MakeCXCursor(Def, tu); 6364 6365 return MakeCXCursor(Prot, tu); 6366 } 6367 6368 case CXCursor_ObjCClassRef: { 6369 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first; 6370 if (const ObjCInterfaceDecl *Def = Class->getDefinition()) 6371 return MakeCXCursor(Def, tu); 6372 6373 return MakeCXCursor(Class, tu); 6374 } 6375 6376 case CXCursor_TypeRef: 6377 return MakeCXCursor(getCursorTypeRef(C).first, tu); 6378 6379 case CXCursor_TemplateRef: 6380 return MakeCXCursor(getCursorTemplateRef(C).first, tu); 6381 6382 case CXCursor_NamespaceRef: 6383 return MakeCXCursor(getCursorNamespaceRef(C).first, tu); 6384 6385 case CXCursor_MemberRef: 6386 return MakeCXCursor(getCursorMemberRef(C).first, tu); 6387 6388 case CXCursor_CXXBaseSpecifier: { 6389 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C); 6390 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(), tu)); 6391 } 6392 6393 case CXCursor_LabelRef: 6394 // FIXME: We end up faking the "parent" declaration here because we 6395 // don't want to make CXCursor larger. 6396 return MakeCXCursor( 6397 getCursorLabelRef(C).first, 6398 cxtu::getASTUnit(tu)->getASTContext().getTranslationUnitDecl(), tu); 6399 6400 case CXCursor_OverloadedDeclRef: 6401 return C; 6402 6403 case CXCursor_VariableRef: 6404 return MakeCXCursor(getCursorVariableRef(C).first, tu); 6405 6406 default: 6407 // We would prefer to enumerate all non-reference cursor kinds here. 6408 llvm_unreachable("Unhandled reference cursor kind"); 6409 } 6410 } 6411 6412 CXCursor clang_getCursorDefinition(CXCursor C) { 6413 if (clang_isInvalid(C.kind)) 6414 return clang_getNullCursor(); 6415 6416 CXTranslationUnit TU = getCursorTU(C); 6417 6418 bool WasReference = false; 6419 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) { 6420 C = clang_getCursorReferenced(C); 6421 WasReference = true; 6422 } 6423 6424 if (C.kind == CXCursor_MacroExpansion) 6425 return clang_getCursorReferenced(C); 6426 6427 if (!clang_isDeclaration(C.kind)) 6428 return clang_getNullCursor(); 6429 6430 const Decl *D = getCursorDecl(C); 6431 if (!D) 6432 return clang_getNullCursor(); 6433 6434 switch (D->getKind()) { 6435 // Declaration kinds that don't really separate the notions of 6436 // declaration and definition. 6437 case Decl::Namespace: 6438 case Decl::Typedef: 6439 case Decl::TypeAlias: 6440 case Decl::TypeAliasTemplate: 6441 case Decl::TemplateTypeParm: 6442 case Decl::EnumConstant: 6443 case Decl::Field: 6444 case Decl::Binding: 6445 case Decl::MSProperty: 6446 case Decl::MSGuid: 6447 case Decl::TemplateParamObject: 6448 case Decl::IndirectField: 6449 case Decl::ObjCIvar: 6450 case Decl::ObjCAtDefsField: 6451 case Decl::ImplicitParam: 6452 case Decl::ParmVar: 6453 case Decl::NonTypeTemplateParm: 6454 case Decl::TemplateTemplateParm: 6455 case Decl::ObjCCategoryImpl: 6456 case Decl::ObjCImplementation: 6457 case Decl::AccessSpec: 6458 case Decl::LinkageSpec: 6459 case Decl::Export: 6460 case Decl::ObjCPropertyImpl: 6461 case Decl::FileScopeAsm: 6462 case Decl::StaticAssert: 6463 case Decl::Block: 6464 case Decl::Captured: 6465 case Decl::OMPCapturedExpr: 6466 case Decl::Label: // FIXME: Is this right?? 6467 case Decl::ClassScopeFunctionSpecialization: 6468 case Decl::CXXDeductionGuide: 6469 case Decl::Import: 6470 case Decl::OMPThreadPrivate: 6471 case Decl::OMPAllocate: 6472 case Decl::OMPDeclareReduction: 6473 case Decl::OMPDeclareMapper: 6474 case Decl::OMPRequires: 6475 case Decl::ObjCTypeParam: 6476 case Decl::BuiltinTemplate: 6477 case Decl::PragmaComment: 6478 case Decl::PragmaDetectMismatch: 6479 case Decl::UsingPack: 6480 case Decl::Concept: 6481 case Decl::LifetimeExtendedTemporary: 6482 case Decl::RequiresExprBody: 6483 case Decl::UnresolvedUsingIfExists: 6484 return C; 6485 6486 // Declaration kinds that don't make any sense here, but are 6487 // nonetheless harmless. 6488 case Decl::Empty: 6489 case Decl::TranslationUnit: 6490 case Decl::ExternCContext: 6491 break; 6492 6493 // Declaration kinds for which the definition is not resolvable. 6494 case Decl::UnresolvedUsingTypename: 6495 case Decl::UnresolvedUsingValue: 6496 break; 6497 6498 case Decl::UsingDirective: 6499 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(), 6500 TU); 6501 6502 case Decl::NamespaceAlias: 6503 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU); 6504 6505 case Decl::Enum: 6506 case Decl::Record: 6507 case Decl::CXXRecord: 6508 case Decl::ClassTemplateSpecialization: 6509 case Decl::ClassTemplatePartialSpecialization: 6510 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition()) 6511 return MakeCXCursor(Def, TU); 6512 return clang_getNullCursor(); 6513 6514 case Decl::Function: 6515 case Decl::CXXMethod: 6516 case Decl::CXXConstructor: 6517 case Decl::CXXDestructor: 6518 case Decl::CXXConversion: { 6519 const FunctionDecl *Def = nullptr; 6520 if (cast<FunctionDecl>(D)->getBody(Def)) 6521 return MakeCXCursor(Def, TU); 6522 return clang_getNullCursor(); 6523 } 6524 6525 case Decl::Var: 6526 case Decl::VarTemplateSpecialization: 6527 case Decl::VarTemplatePartialSpecialization: 6528 case Decl::Decomposition: { 6529 // Ask the variable if it has a definition. 6530 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition()) 6531 return MakeCXCursor(Def, TU); 6532 return clang_getNullCursor(); 6533 } 6534 6535 case Decl::FunctionTemplate: { 6536 const FunctionDecl *Def = nullptr; 6537 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def)) 6538 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU); 6539 return clang_getNullCursor(); 6540 } 6541 6542 case Decl::ClassTemplate: { 6543 if (RecordDecl *Def = 6544 cast<ClassTemplateDecl>(D)->getTemplatedDecl()->getDefinition()) 6545 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(), 6546 TU); 6547 return clang_getNullCursor(); 6548 } 6549 6550 case Decl::VarTemplate: { 6551 if (VarDecl *Def = 6552 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition()) 6553 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU); 6554 return clang_getNullCursor(); 6555 } 6556 6557 case Decl::Using: 6558 case Decl::UsingEnum: 6559 return MakeCursorOverloadedDeclRef(cast<BaseUsingDecl>(D), D->getLocation(), 6560 TU); 6561 6562 case Decl::UsingShadow: 6563 case Decl::ConstructorUsingShadow: 6564 return clang_getCursorDefinition( 6565 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(), TU)); 6566 6567 case Decl::ObjCMethod: { 6568 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D); 6569 if (Method->isThisDeclarationADefinition()) 6570 return C; 6571 6572 // Dig out the method definition in the associated 6573 // @implementation, if we have it. 6574 // FIXME: The ASTs should make finding the definition easier. 6575 if (const ObjCInterfaceDecl *Class = 6576 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) 6577 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation()) 6578 if (ObjCMethodDecl *Def = ClassImpl->getMethod( 6579 Method->getSelector(), Method->isInstanceMethod())) 6580 if (Def->isThisDeclarationADefinition()) 6581 return MakeCXCursor(Def, TU); 6582 6583 return clang_getNullCursor(); 6584 } 6585 6586 case Decl::ObjCCategory: 6587 if (ObjCCategoryImplDecl *Impl = 6588 cast<ObjCCategoryDecl>(D)->getImplementation()) 6589 return MakeCXCursor(Impl, TU); 6590 return clang_getNullCursor(); 6591 6592 case Decl::ObjCProtocol: 6593 if (const ObjCProtocolDecl *Def = 6594 cast<ObjCProtocolDecl>(D)->getDefinition()) 6595 return MakeCXCursor(Def, TU); 6596 return clang_getNullCursor(); 6597 6598 case Decl::ObjCInterface: { 6599 // There are two notions of a "definition" for an Objective-C 6600 // class: the interface and its implementation. When we resolved a 6601 // reference to an Objective-C class, produce the @interface as 6602 // the definition; when we were provided with the interface, 6603 // produce the @implementation as the definition. 6604 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D); 6605 if (WasReference) { 6606 if (const ObjCInterfaceDecl *Def = IFace->getDefinition()) 6607 return MakeCXCursor(Def, TU); 6608 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation()) 6609 return MakeCXCursor(Impl, TU); 6610 return clang_getNullCursor(); 6611 } 6612 6613 case Decl::ObjCProperty: 6614 // FIXME: We don't really know where to find the 6615 // ObjCPropertyImplDecls that implement this property. 6616 return clang_getNullCursor(); 6617 6618 case Decl::ObjCCompatibleAlias: 6619 if (const ObjCInterfaceDecl *Class = 6620 cast<ObjCCompatibleAliasDecl>(D)->getClassInterface()) 6621 if (const ObjCInterfaceDecl *Def = Class->getDefinition()) 6622 return MakeCXCursor(Def, TU); 6623 6624 return clang_getNullCursor(); 6625 6626 case Decl::Friend: 6627 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl()) 6628 return clang_getCursorDefinition(MakeCXCursor(Friend, TU)); 6629 return clang_getNullCursor(); 6630 6631 case Decl::FriendTemplate: 6632 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl()) 6633 return clang_getCursorDefinition(MakeCXCursor(Friend, TU)); 6634 return clang_getNullCursor(); 6635 } 6636 6637 return clang_getNullCursor(); 6638 } 6639 6640 unsigned clang_isCursorDefinition(CXCursor C) { 6641 if (!clang_isDeclaration(C.kind)) 6642 return 0; 6643 6644 return clang_getCursorDefinition(C) == C; 6645 } 6646 6647 CXCursor clang_getCanonicalCursor(CXCursor C) { 6648 if (!clang_isDeclaration(C.kind)) 6649 return C; 6650 6651 if (const Decl *D = getCursorDecl(C)) { 6652 if (const ObjCCategoryImplDecl *CatImplD = 6653 dyn_cast<ObjCCategoryImplDecl>(D)) 6654 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl()) 6655 return MakeCXCursor(CatD, getCursorTU(C)); 6656 6657 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D)) 6658 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface()) 6659 return MakeCXCursor(IFD, getCursorTU(C)); 6660 6661 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C)); 6662 } 6663 6664 return C; 6665 } 6666 6667 int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) { 6668 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first; 6669 } 6670 6671 unsigned clang_getNumOverloadedDecls(CXCursor C) { 6672 if (C.kind != CXCursor_OverloadedDeclRef) 6673 return 0; 6674 6675 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first; 6676 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>()) 6677 return E->getNumDecls(); 6678 6679 if (OverloadedTemplateStorage *S = 6680 Storage.dyn_cast<OverloadedTemplateStorage *>()) 6681 return S->size(); 6682 6683 const Decl *D = Storage.get<const Decl *>(); 6684 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) 6685 return Using->shadow_size(); 6686 6687 return 0; 6688 } 6689 6690 CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) { 6691 if (cursor.kind != CXCursor_OverloadedDeclRef) 6692 return clang_getNullCursor(); 6693 6694 if (index >= clang_getNumOverloadedDecls(cursor)) 6695 return clang_getNullCursor(); 6696 6697 CXTranslationUnit TU = getCursorTU(cursor); 6698 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first; 6699 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>()) 6700 return MakeCXCursor(E->decls_begin()[index], TU); 6701 6702 if (OverloadedTemplateStorage *S = 6703 Storage.dyn_cast<OverloadedTemplateStorage *>()) 6704 return MakeCXCursor(S->begin()[index], TU); 6705 6706 const Decl *D = Storage.get<const Decl *>(); 6707 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) { 6708 // FIXME: This is, unfortunately, linear time. 6709 UsingDecl::shadow_iterator Pos = Using->shadow_begin(); 6710 std::advance(Pos, index); 6711 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU); 6712 } 6713 6714 return clang_getNullCursor(); 6715 } 6716 6717 void clang_getDefinitionSpellingAndExtent( 6718 CXCursor C, const char **startBuf, const char **endBuf, unsigned *startLine, 6719 unsigned *startColumn, unsigned *endLine, unsigned *endColumn) { 6720 assert(getCursorDecl(C) && "CXCursor has null decl"); 6721 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C)); 6722 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody()); 6723 6724 SourceManager &SM = FD->getASTContext().getSourceManager(); 6725 *startBuf = SM.getCharacterData(Body->getLBracLoc()); 6726 *endBuf = SM.getCharacterData(Body->getRBracLoc()); 6727 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc()); 6728 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc()); 6729 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc()); 6730 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc()); 6731 } 6732 6733 CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags, 6734 unsigned PieceIndex) { 6735 RefNamePieces Pieces; 6736 6737 switch (C.kind) { 6738 case CXCursor_MemberRefExpr: 6739 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C))) 6740 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(), 6741 E->getQualifierLoc().getSourceRange()); 6742 break; 6743 6744 case CXCursor_DeclRefExpr: 6745 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) { 6746 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc()); 6747 Pieces = 6748 buildPieces(NameFlags, false, E->getNameInfo(), 6749 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc); 6750 } 6751 break; 6752 6753 case CXCursor_CallExpr: 6754 if (const CXXOperatorCallExpr *OCE = 6755 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) { 6756 const Expr *Callee = OCE->getCallee(); 6757 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) 6758 Callee = ICE->getSubExpr(); 6759 6760 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) 6761 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(), 6762 DRE->getQualifierLoc().getSourceRange()); 6763 } 6764 break; 6765 6766 default: 6767 break; 6768 } 6769 6770 if (Pieces.empty()) { 6771 if (PieceIndex == 0) 6772 return clang_getCursorExtent(C); 6773 } else if (PieceIndex < Pieces.size()) { 6774 SourceRange R = Pieces[PieceIndex]; 6775 if (R.isValid()) 6776 return cxloc::translateSourceRange(getCursorContext(C), R); 6777 } 6778 6779 return clang_getNullRange(); 6780 } 6781 6782 void clang_enableStackTraces(void) { 6783 // FIXME: Provide an argv0 here so we can find llvm-symbolizer. 6784 llvm::sys::PrintStackTraceOnErrorSignal(StringRef()); 6785 } 6786 6787 void clang_executeOnThread(void (*fn)(void *), void *user_data, 6788 unsigned stack_size) { 6789 llvm::thread Thread(stack_size == 0 ? clang::DesiredStackSize 6790 : llvm::Optional<unsigned>(stack_size), 6791 fn, user_data); 6792 Thread.join(); 6793 } 6794 6795 //===----------------------------------------------------------------------===// 6796 // Token-based Operations. 6797 //===----------------------------------------------------------------------===// 6798 6799 /* CXToken layout: 6800 * int_data[0]: a CXTokenKind 6801 * int_data[1]: starting token location 6802 * int_data[2]: token length 6803 * int_data[3]: reserved 6804 * ptr_data: for identifiers and keywords, an IdentifierInfo*. 6805 * otherwise unused. 6806 */ 6807 CXTokenKind clang_getTokenKind(CXToken CXTok) { 6808 return static_cast<CXTokenKind>(CXTok.int_data[0]); 6809 } 6810 6811 CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) { 6812 switch (clang_getTokenKind(CXTok)) { 6813 case CXToken_Identifier: 6814 case CXToken_Keyword: 6815 // We know we have an IdentifierInfo*, so use that. 6816 return cxstring::createRef( 6817 static_cast<IdentifierInfo *>(CXTok.ptr_data)->getNameStart()); 6818 6819 case CXToken_Literal: { 6820 // We have stashed the starting pointer in the ptr_data field. Use it. 6821 const char *Text = static_cast<const char *>(CXTok.ptr_data); 6822 return cxstring::createDup(StringRef(Text, CXTok.int_data[2])); 6823 } 6824 6825 case CXToken_Punctuation: 6826 case CXToken_Comment: 6827 break; 6828 } 6829 6830 if (isNotUsableTU(TU)) { 6831 LOG_BAD_TU(TU); 6832 return cxstring::createEmpty(); 6833 } 6834 6835 // We have to find the starting buffer pointer the hard way, by 6836 // deconstructing the source location. 6837 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 6838 if (!CXXUnit) 6839 return cxstring::createEmpty(); 6840 6841 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]); 6842 std::pair<FileID, unsigned> LocInfo = 6843 CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc); 6844 bool Invalid = false; 6845 StringRef Buffer = 6846 CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid); 6847 if (Invalid) 6848 return cxstring::createEmpty(); 6849 6850 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2])); 6851 } 6852 6853 CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) { 6854 if (isNotUsableTU(TU)) { 6855 LOG_BAD_TU(TU); 6856 return clang_getNullLocation(); 6857 } 6858 6859 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 6860 if (!CXXUnit) 6861 return clang_getNullLocation(); 6862 6863 return cxloc::translateSourceLocation( 6864 CXXUnit->getASTContext(), 6865 SourceLocation::getFromRawEncoding(CXTok.int_data[1])); 6866 } 6867 6868 CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) { 6869 if (isNotUsableTU(TU)) { 6870 LOG_BAD_TU(TU); 6871 return clang_getNullRange(); 6872 } 6873 6874 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 6875 if (!CXXUnit) 6876 return clang_getNullRange(); 6877 6878 return cxloc::translateSourceRange( 6879 CXXUnit->getASTContext(), 6880 SourceLocation::getFromRawEncoding(CXTok.int_data[1])); 6881 } 6882 6883 static void getTokens(ASTUnit *CXXUnit, SourceRange Range, 6884 SmallVectorImpl<CXToken> &CXTokens) { 6885 SourceManager &SourceMgr = CXXUnit->getSourceManager(); 6886 std::pair<FileID, unsigned> BeginLocInfo = 6887 SourceMgr.getDecomposedSpellingLoc(Range.getBegin()); 6888 std::pair<FileID, unsigned> EndLocInfo = 6889 SourceMgr.getDecomposedSpellingLoc(Range.getEnd()); 6890 6891 // Cannot tokenize across files. 6892 if (BeginLocInfo.first != EndLocInfo.first) 6893 return; 6894 6895 // Create a lexer 6896 bool Invalid = false; 6897 StringRef Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid); 6898 if (Invalid) 6899 return; 6900 6901 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first), 6902 CXXUnit->getASTContext().getLangOpts(), Buffer.begin(), 6903 Buffer.data() + BeginLocInfo.second, Buffer.end()); 6904 Lex.SetCommentRetentionState(true); 6905 6906 // Lex tokens until we hit the end of the range. 6907 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second; 6908 Token Tok; 6909 bool previousWasAt = false; 6910 do { 6911 // Lex the next token 6912 Lex.LexFromRawLexer(Tok); 6913 if (Tok.is(tok::eof)) 6914 break; 6915 6916 // Initialize the CXToken. 6917 CXToken CXTok; 6918 6919 // - Common fields 6920 CXTok.int_data[1] = Tok.getLocation().getRawEncoding(); 6921 CXTok.int_data[2] = Tok.getLength(); 6922 CXTok.int_data[3] = 0; 6923 6924 // - Kind-specific fields 6925 if (Tok.isLiteral()) { 6926 CXTok.int_data[0] = CXToken_Literal; 6927 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData()); 6928 } else if (Tok.is(tok::raw_identifier)) { 6929 // Lookup the identifier to determine whether we have a keyword. 6930 IdentifierInfo *II = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok); 6931 6932 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) { 6933 CXTok.int_data[0] = CXToken_Keyword; 6934 } else { 6935 CXTok.int_data[0] = 6936 Tok.is(tok::identifier) ? CXToken_Identifier : CXToken_Keyword; 6937 } 6938 CXTok.ptr_data = II; 6939 } else if (Tok.is(tok::comment)) { 6940 CXTok.int_data[0] = CXToken_Comment; 6941 CXTok.ptr_data = nullptr; 6942 } else { 6943 CXTok.int_data[0] = CXToken_Punctuation; 6944 CXTok.ptr_data = nullptr; 6945 } 6946 CXTokens.push_back(CXTok); 6947 previousWasAt = Tok.is(tok::at); 6948 } while (Lex.getBufferLocation() < EffectiveBufferEnd); 6949 } 6950 6951 CXToken *clang_getToken(CXTranslationUnit TU, CXSourceLocation Location) { 6952 LOG_FUNC_SECTION { *Log << TU << ' ' << Location; } 6953 6954 if (isNotUsableTU(TU)) { 6955 LOG_BAD_TU(TU); 6956 return NULL; 6957 } 6958 6959 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 6960 if (!CXXUnit) 6961 return NULL; 6962 6963 SourceLocation Begin = cxloc::translateSourceLocation(Location); 6964 if (Begin.isInvalid()) 6965 return NULL; 6966 SourceManager &SM = CXXUnit->getSourceManager(); 6967 std::pair<FileID, unsigned> DecomposedEnd = SM.getDecomposedLoc(Begin); 6968 DecomposedEnd.second += 6969 Lexer::MeasureTokenLength(Begin, SM, CXXUnit->getLangOpts()); 6970 6971 SourceLocation End = 6972 SM.getComposedLoc(DecomposedEnd.first, DecomposedEnd.second); 6973 6974 SmallVector<CXToken, 32> CXTokens; 6975 getTokens(CXXUnit, SourceRange(Begin, End), CXTokens); 6976 6977 if (CXTokens.empty()) 6978 return NULL; 6979 6980 CXTokens.resize(1); 6981 CXToken *Token = static_cast<CXToken *>(llvm::safe_malloc(sizeof(CXToken))); 6982 6983 memmove(Token, CXTokens.data(), sizeof(CXToken)); 6984 return Token; 6985 } 6986 6987 void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range, CXToken **Tokens, 6988 unsigned *NumTokens) { 6989 LOG_FUNC_SECTION { *Log << TU << ' ' << Range; } 6990 6991 if (Tokens) 6992 *Tokens = nullptr; 6993 if (NumTokens) 6994 *NumTokens = 0; 6995 6996 if (isNotUsableTU(TU)) { 6997 LOG_BAD_TU(TU); 6998 return; 6999 } 7000 7001 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 7002 if (!CXXUnit || !Tokens || !NumTokens) 7003 return; 7004 7005 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 7006 7007 SourceRange R = cxloc::translateCXSourceRange(Range); 7008 if (R.isInvalid()) 7009 return; 7010 7011 SmallVector<CXToken, 32> CXTokens; 7012 getTokens(CXXUnit, R, CXTokens); 7013 7014 if (CXTokens.empty()) 7015 return; 7016 7017 *Tokens = static_cast<CXToken *>( 7018 llvm::safe_malloc(sizeof(CXToken) * CXTokens.size())); 7019 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size()); 7020 *NumTokens = CXTokens.size(); 7021 } 7022 7023 void clang_disposeTokens(CXTranslationUnit TU, CXToken *Tokens, 7024 unsigned NumTokens) { 7025 free(Tokens); 7026 } 7027 7028 //===----------------------------------------------------------------------===// 7029 // Token annotation APIs. 7030 //===----------------------------------------------------------------------===// 7031 7032 static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor, 7033 CXCursor parent, 7034 CXClientData client_data); 7035 static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor, 7036 CXClientData client_data); 7037 7038 namespace { 7039 class AnnotateTokensWorker { 7040 CXToken *Tokens; 7041 CXCursor *Cursors; 7042 unsigned NumTokens; 7043 unsigned TokIdx; 7044 unsigned PreprocessingTokIdx; 7045 CursorVisitor AnnotateVis; 7046 SourceManager &SrcMgr; 7047 bool HasContextSensitiveKeywords; 7048 7049 struct PostChildrenAction { 7050 CXCursor cursor; 7051 enum Action { Invalid, Ignore, Postpone } action; 7052 }; 7053 using PostChildrenActions = SmallVector<PostChildrenAction, 0>; 7054 7055 struct PostChildrenInfo { 7056 CXCursor Cursor; 7057 SourceRange CursorRange; 7058 unsigned BeforeReachingCursorIdx; 7059 unsigned BeforeChildrenTokenIdx; 7060 PostChildrenActions ChildActions; 7061 }; 7062 SmallVector<PostChildrenInfo, 8> PostChildrenInfos; 7063 7064 CXToken &getTok(unsigned Idx) { 7065 assert(Idx < NumTokens); 7066 return Tokens[Idx]; 7067 } 7068 const CXToken &getTok(unsigned Idx) const { 7069 assert(Idx < NumTokens); 7070 return Tokens[Idx]; 7071 } 7072 bool MoreTokens() const { return TokIdx < NumTokens; } 7073 unsigned NextToken() const { return TokIdx; } 7074 void AdvanceToken() { ++TokIdx; } 7075 SourceLocation GetTokenLoc(unsigned tokI) { 7076 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]); 7077 } 7078 bool isFunctionMacroToken(unsigned tokI) const { 7079 return getTok(tokI).int_data[3] != 0; 7080 } 7081 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const { 7082 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]); 7083 } 7084 7085 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange); 7086 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult, 7087 SourceRange); 7088 7089 public: 7090 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens, 7091 CXTranslationUnit TU, SourceRange RegionOfInterest) 7092 : Tokens(tokens), Cursors(cursors), NumTokens(numTokens), TokIdx(0), 7093 PreprocessingTokIdx(0), 7094 AnnotateVis(TU, AnnotateTokensVisitor, this, 7095 /*VisitPreprocessorLast=*/true, 7096 /*VisitIncludedEntities=*/false, RegionOfInterest, 7097 /*VisitDeclsOnly=*/false, 7098 AnnotateTokensPostChildrenVisitor), 7099 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()), 7100 HasContextSensitiveKeywords(false) {} 7101 7102 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); } 7103 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent); 7104 bool IsIgnoredChildCursor(CXCursor cursor) const; 7105 PostChildrenActions DetermineChildActions(CXCursor Cursor) const; 7106 7107 bool postVisitChildren(CXCursor cursor); 7108 void HandlePostPonedChildCursors(const PostChildrenInfo &Info); 7109 void HandlePostPonedChildCursor(CXCursor Cursor, unsigned StartTokenIndex); 7110 7111 void AnnotateTokens(); 7112 7113 /// Determine whether the annotator saw any cursors that have 7114 /// context-sensitive keywords. 7115 bool hasContextSensitiveKeywords() const { 7116 return HasContextSensitiveKeywords; 7117 } 7118 7119 ~AnnotateTokensWorker() { assert(PostChildrenInfos.empty()); } 7120 }; 7121 } // namespace 7122 7123 void AnnotateTokensWorker::AnnotateTokens() { 7124 // Walk the AST within the region of interest, annotating tokens 7125 // along the way. 7126 AnnotateVis.visitFileRegion(); 7127 } 7128 7129 bool AnnotateTokensWorker::IsIgnoredChildCursor(CXCursor cursor) const { 7130 if (PostChildrenInfos.empty()) 7131 return false; 7132 7133 for (const auto &ChildAction : PostChildrenInfos.back().ChildActions) { 7134 if (ChildAction.cursor == cursor && 7135 ChildAction.action == PostChildrenAction::Ignore) { 7136 return true; 7137 } 7138 } 7139 7140 return false; 7141 } 7142 7143 const CXXOperatorCallExpr *GetSubscriptOrCallOperator(CXCursor Cursor) { 7144 if (!clang_isExpression(Cursor.kind)) 7145 return nullptr; 7146 7147 const Expr *E = getCursorExpr(Cursor); 7148 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) { 7149 const OverloadedOperatorKind Kind = OCE->getOperator(); 7150 if (Kind == OO_Call || Kind == OO_Subscript) 7151 return OCE; 7152 } 7153 7154 return nullptr; 7155 } 7156 7157 AnnotateTokensWorker::PostChildrenActions 7158 AnnotateTokensWorker::DetermineChildActions(CXCursor Cursor) const { 7159 PostChildrenActions actions; 7160 7161 // The DeclRefExpr of CXXOperatorCallExpr refering to the custom operator is 7162 // visited before the arguments to the operator call. For the Call and 7163 // Subscript operator the range of this DeclRefExpr includes the whole call 7164 // expression, so that all tokens in that range would be mapped to the 7165 // operator function, including the tokens of the arguments. To avoid that, 7166 // ensure to visit this DeclRefExpr as last node. 7167 if (const auto *OCE = GetSubscriptOrCallOperator(Cursor)) { 7168 const Expr *Callee = OCE->getCallee(); 7169 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) { 7170 const Expr *SubExpr = ICE->getSubExpr(); 7171 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) { 7172 const Decl *parentDecl = getCursorDecl(Cursor); 7173 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor); 7174 7175 // Visit the DeclRefExpr as last. 7176 CXCursor cxChild = MakeCXCursor(DRE, parentDecl, TU); 7177 actions.push_back({cxChild, PostChildrenAction::Postpone}); 7178 7179 // The parent of the DeclRefExpr, an ImplicitCastExpr, has an equally 7180 // wide range as the DeclRefExpr. We can skip visiting this entirely. 7181 cxChild = MakeCXCursor(ICE, parentDecl, TU); 7182 actions.push_back({cxChild, PostChildrenAction::Ignore}); 7183 } 7184 } 7185 } 7186 7187 return actions; 7188 } 7189 7190 static inline void updateCursorAnnotation(CXCursor &Cursor, 7191 const CXCursor &updateC) { 7192 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind)) 7193 return; 7194 Cursor = updateC; 7195 } 7196 7197 /// It annotates and advances tokens with a cursor until the comparison 7198 //// between the cursor location and the source range is the same as 7199 /// \arg compResult. 7200 /// 7201 /// Pass RangeBefore to annotate tokens with a cursor until a range is reached. 7202 /// Pass RangeOverlap to annotate tokens inside a range. 7203 void AnnotateTokensWorker::annotateAndAdvanceTokens( 7204 CXCursor updateC, RangeComparisonResult compResult, SourceRange range) { 7205 while (MoreTokens()) { 7206 const unsigned I = NextToken(); 7207 if (isFunctionMacroToken(I)) 7208 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range)) 7209 return; 7210 7211 SourceLocation TokLoc = GetTokenLoc(I); 7212 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) { 7213 updateCursorAnnotation(Cursors[I], updateC); 7214 AdvanceToken(); 7215 continue; 7216 } 7217 break; 7218 } 7219 } 7220 7221 /// Special annotation handling for macro argument tokens. 7222 /// \returns true if it advanced beyond all macro tokens, false otherwise. 7223 bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens( 7224 CXCursor updateC, RangeComparisonResult compResult, SourceRange range) { 7225 assert(MoreTokens()); 7226 assert(isFunctionMacroToken(NextToken()) && 7227 "Should be called only for macro arg tokens"); 7228 7229 // This works differently than annotateAndAdvanceTokens; because expanded 7230 // macro arguments can have arbitrary translation-unit source order, we do not 7231 // advance the token index one by one until a token fails the range test. 7232 // We only advance once past all of the macro arg tokens if all of them 7233 // pass the range test. If one of them fails we keep the token index pointing 7234 // at the start of the macro arg tokens so that the failing token will be 7235 // annotated by a subsequent annotation try. 7236 7237 bool atLeastOneCompFail = false; 7238 7239 unsigned I = NextToken(); 7240 for (; I < NumTokens && isFunctionMacroToken(I); ++I) { 7241 SourceLocation TokLoc = getFunctionMacroTokenLoc(I); 7242 if (TokLoc.isFileID()) 7243 continue; // not macro arg token, it's parens or comma. 7244 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) { 7245 if (clang_isInvalid(clang_getCursorKind(Cursors[I]))) 7246 Cursors[I] = updateC; 7247 } else 7248 atLeastOneCompFail = true; 7249 } 7250 7251 if (atLeastOneCompFail) 7252 return false; 7253 7254 TokIdx = I; // All of the tokens were handled, advance beyond all of them. 7255 return true; 7256 } 7257 7258 enum CXChildVisitResult AnnotateTokensWorker::Visit(CXCursor cursor, 7259 CXCursor parent) { 7260 SourceRange cursorRange = getRawCursorExtent(cursor); 7261 if (cursorRange.isInvalid()) 7262 return CXChildVisit_Recurse; 7263 7264 if (IsIgnoredChildCursor(cursor)) 7265 return CXChildVisit_Continue; 7266 7267 if (!HasContextSensitiveKeywords) { 7268 // Objective-C properties can have context-sensitive keywords. 7269 if (cursor.kind == CXCursor_ObjCPropertyDecl) { 7270 if (const ObjCPropertyDecl *Property = 7271 dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor))) 7272 HasContextSensitiveKeywords = 7273 Property->getPropertyAttributesAsWritten() != 0; 7274 } 7275 // Objective-C methods can have context-sensitive keywords. 7276 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl || 7277 cursor.kind == CXCursor_ObjCClassMethodDecl) { 7278 if (const ObjCMethodDecl *Method = 7279 dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) { 7280 if (Method->getObjCDeclQualifier()) 7281 HasContextSensitiveKeywords = true; 7282 else { 7283 for (const auto *P : Method->parameters()) { 7284 if (P->getObjCDeclQualifier()) { 7285 HasContextSensitiveKeywords = true; 7286 break; 7287 } 7288 } 7289 } 7290 } 7291 } 7292 // C++ methods can have context-sensitive keywords. 7293 else if (cursor.kind == CXCursor_CXXMethod) { 7294 if (const CXXMethodDecl *Method = 7295 dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) { 7296 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>()) 7297 HasContextSensitiveKeywords = true; 7298 } 7299 } 7300 // C++ classes can have context-sensitive keywords. 7301 else if (cursor.kind == CXCursor_StructDecl || 7302 cursor.kind == CXCursor_ClassDecl || 7303 cursor.kind == CXCursor_ClassTemplate || 7304 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) { 7305 if (const Decl *D = getCursorDecl(cursor)) 7306 if (D->hasAttr<FinalAttr>()) 7307 HasContextSensitiveKeywords = true; 7308 } 7309 } 7310 7311 // Don't override a property annotation with its getter/setter method. 7312 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl && 7313 parent.kind == CXCursor_ObjCPropertyDecl) 7314 return CXChildVisit_Continue; 7315 7316 if (clang_isPreprocessing(cursor.kind)) { 7317 // Items in the preprocessing record are kept separate from items in 7318 // declarations, so we keep a separate token index. 7319 unsigned SavedTokIdx = TokIdx; 7320 TokIdx = PreprocessingTokIdx; 7321 7322 // Skip tokens up until we catch up to the beginning of the preprocessing 7323 // entry. 7324 while (MoreTokens()) { 7325 const unsigned I = NextToken(); 7326 SourceLocation TokLoc = GetTokenLoc(I); 7327 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 7328 case RangeBefore: 7329 AdvanceToken(); 7330 continue; 7331 case RangeAfter: 7332 case RangeOverlap: 7333 break; 7334 } 7335 break; 7336 } 7337 7338 // Look at all of the tokens within this range. 7339 while (MoreTokens()) { 7340 const unsigned I = NextToken(); 7341 SourceLocation TokLoc = GetTokenLoc(I); 7342 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 7343 case RangeBefore: 7344 llvm_unreachable("Infeasible"); 7345 case RangeAfter: 7346 break; 7347 case RangeOverlap: 7348 // For macro expansions, just note where the beginning of the macro 7349 // expansion occurs. 7350 if (cursor.kind == CXCursor_MacroExpansion) { 7351 if (TokLoc == cursorRange.getBegin()) 7352 Cursors[I] = cursor; 7353 AdvanceToken(); 7354 break; 7355 } 7356 // We may have already annotated macro names inside macro definitions. 7357 if (Cursors[I].kind != CXCursor_MacroExpansion) 7358 Cursors[I] = cursor; 7359 AdvanceToken(); 7360 continue; 7361 } 7362 break; 7363 } 7364 7365 // Save the preprocessing token index; restore the non-preprocessing 7366 // token index. 7367 PreprocessingTokIdx = TokIdx; 7368 TokIdx = SavedTokIdx; 7369 return CXChildVisit_Recurse; 7370 } 7371 7372 if (cursorRange.isInvalid()) 7373 return CXChildVisit_Continue; 7374 7375 unsigned BeforeReachingCursorIdx = NextToken(); 7376 const enum CXCursorKind cursorK = clang_getCursorKind(cursor); 7377 const enum CXCursorKind K = clang_getCursorKind(parent); 7378 const CXCursor updateC = 7379 (clang_isInvalid(K) || K == CXCursor_TranslationUnit || 7380 // Attributes are annotated out-of-order, skip tokens until we reach it. 7381 clang_isAttribute(cursor.kind)) 7382 ? clang_getNullCursor() 7383 : parent; 7384 7385 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange); 7386 7387 // Avoid having the cursor of an expression "overwrite" the annotation of the 7388 // variable declaration that it belongs to. 7389 // This can happen for C++ constructor expressions whose range generally 7390 // include the variable declaration, e.g.: 7391 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor. 7392 if (clang_isExpression(cursorK) && MoreTokens()) { 7393 const Expr *E = getCursorExpr(cursor); 7394 if (const Decl *D = getCursorDecl(cursor)) { 7395 const unsigned I = NextToken(); 7396 if (E->getBeginLoc().isValid() && D->getLocation().isValid() && 7397 E->getBeginLoc() == D->getLocation() && 7398 E->getBeginLoc() == GetTokenLoc(I)) { 7399 updateCursorAnnotation(Cursors[I], updateC); 7400 AdvanceToken(); 7401 } 7402 } 7403 } 7404 7405 // Before recursing into the children keep some state that we are going 7406 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some 7407 // extra work after the child nodes are visited. 7408 // Note that we don't call VisitChildren here to avoid traversing statements 7409 // code-recursively which can blow the stack. 7410 7411 PostChildrenInfo Info; 7412 Info.Cursor = cursor; 7413 Info.CursorRange = cursorRange; 7414 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx; 7415 Info.BeforeChildrenTokenIdx = NextToken(); 7416 Info.ChildActions = DetermineChildActions(cursor); 7417 PostChildrenInfos.push_back(Info); 7418 7419 return CXChildVisit_Recurse; 7420 } 7421 7422 bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) { 7423 if (PostChildrenInfos.empty()) 7424 return false; 7425 const PostChildrenInfo &Info = PostChildrenInfos.back(); 7426 if (!clang_equalCursors(Info.Cursor, cursor)) 7427 return false; 7428 7429 HandlePostPonedChildCursors(Info); 7430 7431 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx; 7432 const unsigned AfterChildren = NextToken(); 7433 SourceRange cursorRange = Info.CursorRange; 7434 7435 // Scan the tokens that are at the end of the cursor, but are not captured 7436 // but the child cursors. 7437 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange); 7438 7439 // Scan the tokens that are at the beginning of the cursor, but are not 7440 // capture by the child cursors. 7441 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) { 7442 if (!clang_isInvalid(clang_getCursorKind(Cursors[I]))) 7443 break; 7444 7445 Cursors[I] = cursor; 7446 } 7447 7448 // Attributes are annotated out-of-order, rewind TokIdx to when we first 7449 // encountered the attribute cursor. 7450 if (clang_isAttribute(cursor.kind)) 7451 TokIdx = Info.BeforeReachingCursorIdx; 7452 7453 PostChildrenInfos.pop_back(); 7454 return false; 7455 } 7456 7457 void AnnotateTokensWorker::HandlePostPonedChildCursors( 7458 const PostChildrenInfo &Info) { 7459 for (const auto &ChildAction : Info.ChildActions) { 7460 if (ChildAction.action == PostChildrenAction::Postpone) { 7461 HandlePostPonedChildCursor(ChildAction.cursor, 7462 Info.BeforeChildrenTokenIdx); 7463 } 7464 } 7465 } 7466 7467 void AnnotateTokensWorker::HandlePostPonedChildCursor( 7468 CXCursor Cursor, unsigned StartTokenIndex) { 7469 unsigned I = StartTokenIndex; 7470 7471 // The bracket tokens of a Call or Subscript operator are mapped to 7472 // CallExpr/CXXOperatorCallExpr because we skipped visiting the corresponding 7473 // DeclRefExpr. Remap these tokens to the DeclRefExpr cursors. 7474 for (unsigned RefNameRangeNr = 0; I < NumTokens; RefNameRangeNr++) { 7475 const CXSourceRange CXRefNameRange = clang_getCursorReferenceNameRange( 7476 Cursor, CXNameRange_WantQualifier, RefNameRangeNr); 7477 if (clang_Range_isNull(CXRefNameRange)) 7478 break; // All ranges handled. 7479 7480 SourceRange RefNameRange = cxloc::translateCXSourceRange(CXRefNameRange); 7481 while (I < NumTokens) { 7482 const SourceLocation TokenLocation = GetTokenLoc(I); 7483 if (!TokenLocation.isValid()) 7484 break; 7485 7486 // Adapt the end range, because LocationCompare() reports 7487 // RangeOverlap even for the not-inclusive end location. 7488 const SourceLocation fixedEnd = 7489 RefNameRange.getEnd().getLocWithOffset(-1); 7490 RefNameRange = SourceRange(RefNameRange.getBegin(), fixedEnd); 7491 7492 const RangeComparisonResult ComparisonResult = 7493 LocationCompare(SrcMgr, TokenLocation, RefNameRange); 7494 7495 if (ComparisonResult == RangeOverlap) { 7496 Cursors[I++] = Cursor; 7497 } else if (ComparisonResult == RangeBefore) { 7498 ++I; // Not relevant token, check next one. 7499 } else if (ComparisonResult == RangeAfter) { 7500 break; // All tokens updated for current range, check next. 7501 } 7502 } 7503 } 7504 } 7505 7506 static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor, 7507 CXCursor parent, 7508 CXClientData client_data) { 7509 return static_cast<AnnotateTokensWorker *>(client_data) 7510 ->Visit(cursor, parent); 7511 } 7512 7513 static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor, 7514 CXClientData client_data) { 7515 return static_cast<AnnotateTokensWorker *>(client_data) 7516 ->postVisitChildren(cursor); 7517 } 7518 7519 namespace { 7520 7521 /// Uses the macro expansions in the preprocessing record to find 7522 /// and mark tokens that are macro arguments. This info is used by the 7523 /// AnnotateTokensWorker. 7524 class MarkMacroArgTokensVisitor { 7525 SourceManager &SM; 7526 CXToken *Tokens; 7527 unsigned NumTokens; 7528 unsigned CurIdx; 7529 7530 public: 7531 MarkMacroArgTokensVisitor(SourceManager &SM, CXToken *tokens, 7532 unsigned numTokens) 7533 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) {} 7534 7535 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) { 7536 if (cursor.kind != CXCursor_MacroExpansion) 7537 return CXChildVisit_Continue; 7538 7539 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange(); 7540 if (macroRange.getBegin() == macroRange.getEnd()) 7541 return CXChildVisit_Continue; // it's not a function macro. 7542 7543 for (; CurIdx < NumTokens; ++CurIdx) { 7544 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx), 7545 macroRange.getBegin())) 7546 break; 7547 } 7548 7549 if (CurIdx == NumTokens) 7550 return CXChildVisit_Break; 7551 7552 for (; CurIdx < NumTokens; ++CurIdx) { 7553 SourceLocation tokLoc = getTokenLoc(CurIdx); 7554 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd())) 7555 break; 7556 7557 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc)); 7558 } 7559 7560 if (CurIdx == NumTokens) 7561 return CXChildVisit_Break; 7562 7563 return CXChildVisit_Continue; 7564 } 7565 7566 private: 7567 CXToken &getTok(unsigned Idx) { 7568 assert(Idx < NumTokens); 7569 return Tokens[Idx]; 7570 } 7571 const CXToken &getTok(unsigned Idx) const { 7572 assert(Idx < NumTokens); 7573 return Tokens[Idx]; 7574 } 7575 7576 SourceLocation getTokenLoc(unsigned tokI) { 7577 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]); 7578 } 7579 7580 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) { 7581 // The third field is reserved and currently not used. Use it here 7582 // to mark macro arg expanded tokens with their expanded locations. 7583 getTok(tokI).int_data[3] = loc.getRawEncoding(); 7584 } 7585 }; 7586 7587 } // end anonymous namespace 7588 7589 static CXChildVisitResult 7590 MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent, 7591 CXClientData client_data) { 7592 return static_cast<MarkMacroArgTokensVisitor *>(client_data) 7593 ->visit(cursor, parent); 7594 } 7595 7596 /// Used by \c annotatePreprocessorTokens. 7597 /// \returns true if lexing was finished, false otherwise. 7598 static bool lexNext(Lexer &Lex, Token &Tok, unsigned &NextIdx, 7599 unsigned NumTokens) { 7600 if (NextIdx >= NumTokens) 7601 return true; 7602 7603 ++NextIdx; 7604 Lex.LexFromRawLexer(Tok); 7605 return Tok.is(tok::eof); 7606 } 7607 7608 static void annotatePreprocessorTokens(CXTranslationUnit TU, 7609 SourceRange RegionOfInterest, 7610 CXCursor *Cursors, CXToken *Tokens, 7611 unsigned NumTokens) { 7612 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 7613 7614 Preprocessor &PP = CXXUnit->getPreprocessor(); 7615 SourceManager &SourceMgr = CXXUnit->getSourceManager(); 7616 std::pair<FileID, unsigned> BeginLocInfo = 7617 SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin()); 7618 std::pair<FileID, unsigned> EndLocInfo = 7619 SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd()); 7620 7621 if (BeginLocInfo.first != EndLocInfo.first) 7622 return; 7623 7624 StringRef Buffer; 7625 bool Invalid = false; 7626 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid); 7627 if (Buffer.empty() || Invalid) 7628 return; 7629 7630 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first), 7631 CXXUnit->getASTContext().getLangOpts(), Buffer.begin(), 7632 Buffer.data() + BeginLocInfo.second, Buffer.end()); 7633 Lex.SetCommentRetentionState(true); 7634 7635 unsigned NextIdx = 0; 7636 // Lex tokens in raw mode until we hit the end of the range, to avoid 7637 // entering #includes or expanding macros. 7638 while (true) { 7639 Token Tok; 7640 if (lexNext(Lex, Tok, NextIdx, NumTokens)) 7641 break; 7642 unsigned TokIdx = NextIdx - 1; 7643 assert(Tok.getLocation() == 7644 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1])); 7645 7646 reprocess: 7647 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) { 7648 // We have found a preprocessing directive. Annotate the tokens 7649 // appropriately. 7650 // 7651 // FIXME: Some simple tests here could identify macro definitions and 7652 // #undefs, to provide specific cursor kinds for those. 7653 7654 SourceLocation BeginLoc = Tok.getLocation(); 7655 if (lexNext(Lex, Tok, NextIdx, NumTokens)) 7656 break; 7657 7658 MacroInfo *MI = nullptr; 7659 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") { 7660 if (lexNext(Lex, Tok, NextIdx, NumTokens)) 7661 break; 7662 7663 if (Tok.is(tok::raw_identifier)) { 7664 IdentifierInfo &II = 7665 PP.getIdentifierTable().get(Tok.getRawIdentifier()); 7666 SourceLocation MappedTokLoc = 7667 CXXUnit->mapLocationToPreamble(Tok.getLocation()); 7668 MI = getMacroInfo(II, MappedTokLoc, TU); 7669 } 7670 } 7671 7672 bool finished = false; 7673 do { 7674 if (lexNext(Lex, Tok, NextIdx, NumTokens)) { 7675 finished = true; 7676 break; 7677 } 7678 // If we are in a macro definition, check if the token was ever a 7679 // macro name and annotate it if that's the case. 7680 if (MI) { 7681 SourceLocation SaveLoc = Tok.getLocation(); 7682 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc)); 7683 MacroDefinitionRecord *MacroDef = 7684 checkForMacroInMacroDefinition(MI, Tok, TU); 7685 Tok.setLocation(SaveLoc); 7686 if (MacroDef) 7687 Cursors[NextIdx - 1] = 7688 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU); 7689 } 7690 } while (!Tok.isAtStartOfLine()); 7691 7692 unsigned LastIdx = finished ? NextIdx - 1 : NextIdx - 2; 7693 assert(TokIdx <= LastIdx); 7694 SourceLocation EndLoc = 7695 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]); 7696 CXCursor Cursor = 7697 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU); 7698 7699 for (; TokIdx <= LastIdx; ++TokIdx) 7700 updateCursorAnnotation(Cursors[TokIdx], Cursor); 7701 7702 if (finished) 7703 break; 7704 goto reprocess; 7705 } 7706 } 7707 } 7708 7709 // This gets run a separate thread to avoid stack blowout. 7710 static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit, 7711 CXToken *Tokens, unsigned NumTokens, 7712 CXCursor *Cursors) { 7713 CIndexer *CXXIdx = TU->CIdx; 7714 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing)) 7715 setThreadBackgroundPriority(); 7716 7717 // Determine the region of interest, which contains all of the tokens. 7718 SourceRange RegionOfInterest; 7719 RegionOfInterest.setBegin( 7720 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0]))); 7721 RegionOfInterest.setEnd(cxloc::translateSourceLocation( 7722 clang_getTokenLocation(TU, Tokens[NumTokens - 1]))); 7723 7724 // Relex the tokens within the source range to look for preprocessing 7725 // directives. 7726 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens); 7727 7728 // If begin location points inside a macro argument, set it to the expansion 7729 // location so we can have the full context when annotating semantically. 7730 { 7731 SourceManager &SM = CXXUnit->getSourceManager(); 7732 SourceLocation Loc = 7733 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin()); 7734 if (Loc.isMacroID()) 7735 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc)); 7736 } 7737 7738 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) { 7739 // Search and mark tokens that are macro argument expansions. 7740 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(), Tokens, 7741 NumTokens); 7742 CursorVisitor MacroArgMarker( 7743 TU, MarkMacroArgTokensVisitorDelegate, &Visitor, 7744 /*VisitPreprocessorLast=*/true, 7745 /*VisitIncludedEntities=*/false, RegionOfInterest); 7746 MacroArgMarker.visitPreprocessedEntitiesInRegion(); 7747 } 7748 7749 // Annotate all of the source locations in the region of interest that map to 7750 // a specific cursor. 7751 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest); 7752 7753 // FIXME: We use a ridiculous stack size here because the data-recursion 7754 // algorithm uses a large stack frame than the non-data recursive version, 7755 // and AnnotationTokensWorker currently transforms the data-recursion 7756 // algorithm back into a traditional recursion by explicitly calling 7757 // VisitChildren(). We will need to remove this explicit recursive call. 7758 W.AnnotateTokens(); 7759 7760 // If we ran into any entities that involve context-sensitive keywords, 7761 // take another pass through the tokens to mark them as such. 7762 if (W.hasContextSensitiveKeywords()) { 7763 for (unsigned I = 0; I != NumTokens; ++I) { 7764 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier) 7765 continue; 7766 7767 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) { 7768 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data); 7769 if (const ObjCPropertyDecl *Property = 7770 dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) { 7771 if (Property->getPropertyAttributesAsWritten() != 0 && 7772 llvm::StringSwitch<bool>(II->getName()) 7773 .Case("readonly", true) 7774 .Case("assign", true) 7775 .Case("unsafe_unretained", true) 7776 .Case("readwrite", true) 7777 .Case("retain", true) 7778 .Case("copy", true) 7779 .Case("nonatomic", true) 7780 .Case("atomic", true) 7781 .Case("getter", true) 7782 .Case("setter", true) 7783 .Case("strong", true) 7784 .Case("weak", true) 7785 .Case("class", true) 7786 .Default(false)) 7787 Tokens[I].int_data[0] = CXToken_Keyword; 7788 } 7789 continue; 7790 } 7791 7792 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl || 7793 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) { 7794 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data); 7795 if (llvm::StringSwitch<bool>(II->getName()) 7796 .Case("in", true) 7797 .Case("out", true) 7798 .Case("inout", true) 7799 .Case("oneway", true) 7800 .Case("bycopy", true) 7801 .Case("byref", true) 7802 .Default(false)) 7803 Tokens[I].int_data[0] = CXToken_Keyword; 7804 continue; 7805 } 7806 7807 if (Cursors[I].kind == CXCursor_CXXFinalAttr || 7808 Cursors[I].kind == CXCursor_CXXOverrideAttr) { 7809 Tokens[I].int_data[0] = CXToken_Keyword; 7810 continue; 7811 } 7812 } 7813 } 7814 } 7815 7816 void clang_annotateTokens(CXTranslationUnit TU, CXToken *Tokens, 7817 unsigned NumTokens, CXCursor *Cursors) { 7818 if (isNotUsableTU(TU)) { 7819 LOG_BAD_TU(TU); 7820 return; 7821 } 7822 if (NumTokens == 0 || !Tokens || !Cursors) { 7823 LOG_FUNC_SECTION { *Log << "<null input>"; } 7824 return; 7825 } 7826 7827 LOG_FUNC_SECTION { 7828 *Log << TU << ' '; 7829 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]); 7830 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens - 1]); 7831 *Log << clang_getRange(bloc, eloc); 7832 } 7833 7834 // Any token we don't specifically annotate will have a NULL cursor. 7835 CXCursor C = clang_getNullCursor(); 7836 for (unsigned I = 0; I != NumTokens; ++I) 7837 Cursors[I] = C; 7838 7839 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 7840 if (!CXXUnit) 7841 return; 7842 7843 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 7844 7845 auto AnnotateTokensImpl = [=]() { 7846 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors); 7847 }; 7848 llvm::CrashRecoveryContext CRC; 7849 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) { 7850 fprintf(stderr, "libclang: crash detected while annotating tokens\n"); 7851 } 7852 } 7853 7854 //===----------------------------------------------------------------------===// 7855 // Operations for querying linkage of a cursor. 7856 //===----------------------------------------------------------------------===// 7857 7858 CXLinkageKind clang_getCursorLinkage(CXCursor cursor) { 7859 if (!clang_isDeclaration(cursor.kind)) 7860 return CXLinkage_Invalid; 7861 7862 const Decl *D = cxcursor::getCursorDecl(cursor); 7863 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D)) 7864 switch (ND->getLinkageInternal()) { 7865 case NoLinkage: 7866 case VisibleNoLinkage: 7867 return CXLinkage_NoLinkage; 7868 case ModuleInternalLinkage: 7869 case InternalLinkage: 7870 return CXLinkage_Internal; 7871 case UniqueExternalLinkage: 7872 return CXLinkage_UniqueExternal; 7873 case ModuleLinkage: 7874 case ExternalLinkage: 7875 return CXLinkage_External; 7876 }; 7877 7878 return CXLinkage_Invalid; 7879 } 7880 7881 //===----------------------------------------------------------------------===// 7882 // Operations for querying visibility of a cursor. 7883 //===----------------------------------------------------------------------===// 7884 7885 CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) { 7886 if (!clang_isDeclaration(cursor.kind)) 7887 return CXVisibility_Invalid; 7888 7889 const Decl *D = cxcursor::getCursorDecl(cursor); 7890 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D)) 7891 switch (ND->getVisibility()) { 7892 case HiddenVisibility: 7893 return CXVisibility_Hidden; 7894 case ProtectedVisibility: 7895 return CXVisibility_Protected; 7896 case DefaultVisibility: 7897 return CXVisibility_Default; 7898 }; 7899 7900 return CXVisibility_Invalid; 7901 } 7902 7903 //===----------------------------------------------------------------------===// 7904 // Operations for querying language of a cursor. 7905 //===----------------------------------------------------------------------===// 7906 7907 static CXLanguageKind getDeclLanguage(const Decl *D) { 7908 if (!D) 7909 return CXLanguage_C; 7910 7911 switch (D->getKind()) { 7912 default: 7913 break; 7914 case Decl::ImplicitParam: 7915 case Decl::ObjCAtDefsField: 7916 case Decl::ObjCCategory: 7917 case Decl::ObjCCategoryImpl: 7918 case Decl::ObjCCompatibleAlias: 7919 case Decl::ObjCImplementation: 7920 case Decl::ObjCInterface: 7921 case Decl::ObjCIvar: 7922 case Decl::ObjCMethod: 7923 case Decl::ObjCProperty: 7924 case Decl::ObjCPropertyImpl: 7925 case Decl::ObjCProtocol: 7926 case Decl::ObjCTypeParam: 7927 return CXLanguage_ObjC; 7928 case Decl::CXXConstructor: 7929 case Decl::CXXConversion: 7930 case Decl::CXXDestructor: 7931 case Decl::CXXMethod: 7932 case Decl::CXXRecord: 7933 case Decl::ClassTemplate: 7934 case Decl::ClassTemplatePartialSpecialization: 7935 case Decl::ClassTemplateSpecialization: 7936 case Decl::Friend: 7937 case Decl::FriendTemplate: 7938 case Decl::FunctionTemplate: 7939 case Decl::LinkageSpec: 7940 case Decl::Namespace: 7941 case Decl::NamespaceAlias: 7942 case Decl::NonTypeTemplateParm: 7943 case Decl::StaticAssert: 7944 case Decl::TemplateTemplateParm: 7945 case Decl::TemplateTypeParm: 7946 case Decl::UnresolvedUsingTypename: 7947 case Decl::UnresolvedUsingValue: 7948 case Decl::Using: 7949 case Decl::UsingDirective: 7950 case Decl::UsingShadow: 7951 return CXLanguage_CPlusPlus; 7952 } 7953 7954 return CXLanguage_C; 7955 } 7956 7957 static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) { 7958 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()) 7959 return CXAvailability_NotAvailable; 7960 7961 switch (D->getAvailability()) { 7962 case AR_Available: 7963 case AR_NotYetIntroduced: 7964 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D)) 7965 return getCursorAvailabilityForDecl( 7966 cast<Decl>(EnumConst->getDeclContext())); 7967 return CXAvailability_Available; 7968 7969 case AR_Deprecated: 7970 return CXAvailability_Deprecated; 7971 7972 case AR_Unavailable: 7973 return CXAvailability_NotAvailable; 7974 } 7975 7976 llvm_unreachable("Unknown availability kind!"); 7977 } 7978 7979 enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) { 7980 if (clang_isDeclaration(cursor.kind)) 7981 if (const Decl *D = cxcursor::getCursorDecl(cursor)) 7982 return getCursorAvailabilityForDecl(D); 7983 7984 return CXAvailability_Available; 7985 } 7986 7987 static CXVersion convertVersion(VersionTuple In) { 7988 CXVersion Out = {-1, -1, -1}; 7989 if (In.empty()) 7990 return Out; 7991 7992 Out.Major = In.getMajor(); 7993 7994 Optional<unsigned> Minor = In.getMinor(); 7995 if (Minor.hasValue()) 7996 Out.Minor = *Minor; 7997 else 7998 return Out; 7999 8000 Optional<unsigned> Subminor = In.getSubminor(); 8001 if (Subminor.hasValue()) 8002 Out.Subminor = *Subminor; 8003 8004 return Out; 8005 } 8006 8007 static void getCursorPlatformAvailabilityForDecl( 8008 const Decl *D, int *always_deprecated, CXString *deprecated_message, 8009 int *always_unavailable, CXString *unavailable_message, 8010 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) { 8011 bool HadAvailAttr = false; 8012 for (auto A : D->attrs()) { 8013 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) { 8014 HadAvailAttr = true; 8015 if (always_deprecated) 8016 *always_deprecated = 1; 8017 if (deprecated_message) { 8018 clang_disposeString(*deprecated_message); 8019 *deprecated_message = cxstring::createDup(Deprecated->getMessage()); 8020 } 8021 continue; 8022 } 8023 8024 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) { 8025 HadAvailAttr = true; 8026 if (always_unavailable) 8027 *always_unavailable = 1; 8028 if (unavailable_message) { 8029 clang_disposeString(*unavailable_message); 8030 *unavailable_message = cxstring::createDup(Unavailable->getMessage()); 8031 } 8032 continue; 8033 } 8034 8035 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) { 8036 AvailabilityAttrs.push_back(Avail); 8037 HadAvailAttr = true; 8038 } 8039 } 8040 8041 if (!HadAvailAttr) 8042 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D)) 8043 return getCursorPlatformAvailabilityForDecl( 8044 cast<Decl>(EnumConst->getDeclContext()), always_deprecated, 8045 deprecated_message, always_unavailable, unavailable_message, 8046 AvailabilityAttrs); 8047 8048 if (AvailabilityAttrs.empty()) 8049 return; 8050 8051 llvm::sort( 8052 AvailabilityAttrs, [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) { 8053 return LHS->getPlatform()->getName() < RHS->getPlatform()->getName(); 8054 }); 8055 ASTContext &Ctx = D->getASTContext(); 8056 auto It = std::unique( 8057 AvailabilityAttrs.begin(), AvailabilityAttrs.end(), 8058 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) { 8059 if (LHS->getPlatform() != RHS->getPlatform()) 8060 return false; 8061 8062 if (LHS->getIntroduced() == RHS->getIntroduced() && 8063 LHS->getDeprecated() == RHS->getDeprecated() && 8064 LHS->getObsoleted() == RHS->getObsoleted() && 8065 LHS->getMessage() == RHS->getMessage() && 8066 LHS->getReplacement() == RHS->getReplacement()) 8067 return true; 8068 8069 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) || 8070 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) || 8071 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty())) 8072 return false; 8073 8074 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) 8075 LHS->setIntroduced(Ctx, RHS->getIntroduced()); 8076 8077 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) { 8078 LHS->setDeprecated(Ctx, RHS->getDeprecated()); 8079 if (LHS->getMessage().empty()) 8080 LHS->setMessage(Ctx, RHS->getMessage()); 8081 if (LHS->getReplacement().empty()) 8082 LHS->setReplacement(Ctx, RHS->getReplacement()); 8083 } 8084 8085 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) { 8086 LHS->setObsoleted(Ctx, RHS->getObsoleted()); 8087 if (LHS->getMessage().empty()) 8088 LHS->setMessage(Ctx, RHS->getMessage()); 8089 if (LHS->getReplacement().empty()) 8090 LHS->setReplacement(Ctx, RHS->getReplacement()); 8091 } 8092 8093 return true; 8094 }); 8095 AvailabilityAttrs.erase(It, AvailabilityAttrs.end()); 8096 } 8097 8098 int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated, 8099 CXString *deprecated_message, 8100 int *always_unavailable, 8101 CXString *unavailable_message, 8102 CXPlatformAvailability *availability, 8103 int availability_size) { 8104 if (always_deprecated) 8105 *always_deprecated = 0; 8106 if (deprecated_message) 8107 *deprecated_message = cxstring::createEmpty(); 8108 if (always_unavailable) 8109 *always_unavailable = 0; 8110 if (unavailable_message) 8111 *unavailable_message = cxstring::createEmpty(); 8112 8113 if (!clang_isDeclaration(cursor.kind)) 8114 return 0; 8115 8116 const Decl *D = cxcursor::getCursorDecl(cursor); 8117 if (!D) 8118 return 0; 8119 8120 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs; 8121 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message, 8122 always_unavailable, unavailable_message, 8123 AvailabilityAttrs); 8124 for (const auto &Avail : 8125 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs) 8126 .take_front(availability_size))) { 8127 availability[Avail.index()].Platform = 8128 cxstring::createDup(Avail.value()->getPlatform()->getName()); 8129 availability[Avail.index()].Introduced = 8130 convertVersion(Avail.value()->getIntroduced()); 8131 availability[Avail.index()].Deprecated = 8132 convertVersion(Avail.value()->getDeprecated()); 8133 availability[Avail.index()].Obsoleted = 8134 convertVersion(Avail.value()->getObsoleted()); 8135 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable(); 8136 availability[Avail.index()].Message = 8137 cxstring::createDup(Avail.value()->getMessage()); 8138 } 8139 8140 return AvailabilityAttrs.size(); 8141 } 8142 8143 void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) { 8144 clang_disposeString(availability->Platform); 8145 clang_disposeString(availability->Message); 8146 } 8147 8148 CXLanguageKind clang_getCursorLanguage(CXCursor cursor) { 8149 if (clang_isDeclaration(cursor.kind)) 8150 return getDeclLanguage(cxcursor::getCursorDecl(cursor)); 8151 8152 return CXLanguage_Invalid; 8153 } 8154 8155 CXTLSKind clang_getCursorTLSKind(CXCursor cursor) { 8156 const Decl *D = cxcursor::getCursorDecl(cursor); 8157 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 8158 switch (VD->getTLSKind()) { 8159 case VarDecl::TLS_None: 8160 return CXTLS_None; 8161 case VarDecl::TLS_Dynamic: 8162 return CXTLS_Dynamic; 8163 case VarDecl::TLS_Static: 8164 return CXTLS_Static; 8165 } 8166 } 8167 8168 return CXTLS_None; 8169 } 8170 8171 /// If the given cursor is the "templated" declaration 8172 /// describing a class or function template, return the class or 8173 /// function template. 8174 static const Decl *maybeGetTemplateCursor(const Decl *D) { 8175 if (!D) 8176 return nullptr; 8177 8178 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 8179 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate()) 8180 return FunTmpl; 8181 8182 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) 8183 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate()) 8184 return ClassTmpl; 8185 8186 return D; 8187 } 8188 8189 enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) { 8190 StorageClass sc = SC_None; 8191 const Decl *D = getCursorDecl(C); 8192 if (D) { 8193 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 8194 sc = FD->getStorageClass(); 8195 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 8196 sc = VD->getStorageClass(); 8197 } else { 8198 return CX_SC_Invalid; 8199 } 8200 } else { 8201 return CX_SC_Invalid; 8202 } 8203 switch (sc) { 8204 case SC_None: 8205 return CX_SC_None; 8206 case SC_Extern: 8207 return CX_SC_Extern; 8208 case SC_Static: 8209 return CX_SC_Static; 8210 case SC_PrivateExtern: 8211 return CX_SC_PrivateExtern; 8212 case SC_Auto: 8213 return CX_SC_Auto; 8214 case SC_Register: 8215 return CX_SC_Register; 8216 } 8217 llvm_unreachable("Unhandled storage class!"); 8218 } 8219 8220 CXCursor clang_getCursorSemanticParent(CXCursor cursor) { 8221 if (clang_isDeclaration(cursor.kind)) { 8222 if (const Decl *D = getCursorDecl(cursor)) { 8223 const DeclContext *DC = D->getDeclContext(); 8224 if (!DC) 8225 return clang_getNullCursor(); 8226 8227 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)), 8228 getCursorTU(cursor)); 8229 } 8230 } 8231 8232 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) { 8233 if (const Decl *D = getCursorDecl(cursor)) 8234 return MakeCXCursor(D, getCursorTU(cursor)); 8235 } 8236 8237 return clang_getNullCursor(); 8238 } 8239 8240 CXCursor clang_getCursorLexicalParent(CXCursor cursor) { 8241 if (clang_isDeclaration(cursor.kind)) { 8242 if (const Decl *D = getCursorDecl(cursor)) { 8243 const DeclContext *DC = D->getLexicalDeclContext(); 8244 if (!DC) 8245 return clang_getNullCursor(); 8246 8247 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)), 8248 getCursorTU(cursor)); 8249 } 8250 } 8251 8252 // FIXME: Note that we can't easily compute the lexical context of a 8253 // statement or expression, so we return nothing. 8254 return clang_getNullCursor(); 8255 } 8256 8257 CXFile clang_getIncludedFile(CXCursor cursor) { 8258 if (cursor.kind != CXCursor_InclusionDirective) 8259 return nullptr; 8260 8261 const InclusionDirective *ID = getCursorInclusionDirective(cursor); 8262 return const_cast<FileEntry *>(ID->getFile()); 8263 } 8264 8265 unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) { 8266 if (C.kind != CXCursor_ObjCPropertyDecl) 8267 return CXObjCPropertyAttr_noattr; 8268 8269 unsigned Result = CXObjCPropertyAttr_noattr; 8270 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C)); 8271 ObjCPropertyAttribute::Kind Attr = PD->getPropertyAttributesAsWritten(); 8272 8273 #define SET_CXOBJCPROP_ATTR(A) \ 8274 if (Attr & ObjCPropertyAttribute::kind_##A) \ 8275 Result |= CXObjCPropertyAttr_##A 8276 SET_CXOBJCPROP_ATTR(readonly); 8277 SET_CXOBJCPROP_ATTR(getter); 8278 SET_CXOBJCPROP_ATTR(assign); 8279 SET_CXOBJCPROP_ATTR(readwrite); 8280 SET_CXOBJCPROP_ATTR(retain); 8281 SET_CXOBJCPROP_ATTR(copy); 8282 SET_CXOBJCPROP_ATTR(nonatomic); 8283 SET_CXOBJCPROP_ATTR(setter); 8284 SET_CXOBJCPROP_ATTR(atomic); 8285 SET_CXOBJCPROP_ATTR(weak); 8286 SET_CXOBJCPROP_ATTR(strong); 8287 SET_CXOBJCPROP_ATTR(unsafe_unretained); 8288 SET_CXOBJCPROP_ATTR(class); 8289 #undef SET_CXOBJCPROP_ATTR 8290 8291 return Result; 8292 } 8293 8294 CXString clang_Cursor_getObjCPropertyGetterName(CXCursor C) { 8295 if (C.kind != CXCursor_ObjCPropertyDecl) 8296 return cxstring::createNull(); 8297 8298 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C)); 8299 Selector sel = PD->getGetterName(); 8300 if (sel.isNull()) 8301 return cxstring::createNull(); 8302 8303 return cxstring::createDup(sel.getAsString()); 8304 } 8305 8306 CXString clang_Cursor_getObjCPropertySetterName(CXCursor C) { 8307 if (C.kind != CXCursor_ObjCPropertyDecl) 8308 return cxstring::createNull(); 8309 8310 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C)); 8311 Selector sel = PD->getSetterName(); 8312 if (sel.isNull()) 8313 return cxstring::createNull(); 8314 8315 return cxstring::createDup(sel.getAsString()); 8316 } 8317 8318 unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) { 8319 if (!clang_isDeclaration(C.kind)) 8320 return CXObjCDeclQualifier_None; 8321 8322 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None; 8323 const Decl *D = getCursorDecl(C); 8324 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) 8325 QT = MD->getObjCDeclQualifier(); 8326 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D)) 8327 QT = PD->getObjCDeclQualifier(); 8328 if (QT == Decl::OBJC_TQ_None) 8329 return CXObjCDeclQualifier_None; 8330 8331 unsigned Result = CXObjCDeclQualifier_None; 8332 if (QT & Decl::OBJC_TQ_In) 8333 Result |= CXObjCDeclQualifier_In; 8334 if (QT & Decl::OBJC_TQ_Inout) 8335 Result |= CXObjCDeclQualifier_Inout; 8336 if (QT & Decl::OBJC_TQ_Out) 8337 Result |= CXObjCDeclQualifier_Out; 8338 if (QT & Decl::OBJC_TQ_Bycopy) 8339 Result |= CXObjCDeclQualifier_Bycopy; 8340 if (QT & Decl::OBJC_TQ_Byref) 8341 Result |= CXObjCDeclQualifier_Byref; 8342 if (QT & Decl::OBJC_TQ_Oneway) 8343 Result |= CXObjCDeclQualifier_Oneway; 8344 8345 return Result; 8346 } 8347 8348 unsigned clang_Cursor_isObjCOptional(CXCursor C) { 8349 if (!clang_isDeclaration(C.kind)) 8350 return 0; 8351 8352 const Decl *D = getCursorDecl(C); 8353 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) 8354 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional; 8355 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) 8356 return MD->getImplementationControl() == ObjCMethodDecl::Optional; 8357 8358 return 0; 8359 } 8360 8361 unsigned clang_Cursor_isVariadic(CXCursor C) { 8362 if (!clang_isDeclaration(C.kind)) 8363 return 0; 8364 8365 const Decl *D = getCursorDecl(C); 8366 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 8367 return FD->isVariadic(); 8368 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) 8369 return MD->isVariadic(); 8370 8371 return 0; 8372 } 8373 8374 unsigned clang_Cursor_isExternalSymbol(CXCursor C, CXString *language, 8375 CXString *definedIn, 8376 unsigned *isGenerated) { 8377 if (!clang_isDeclaration(C.kind)) 8378 return 0; 8379 8380 const Decl *D = getCursorDecl(C); 8381 8382 if (auto *attr = D->getExternalSourceSymbolAttr()) { 8383 if (language) 8384 *language = cxstring::createDup(attr->getLanguage()); 8385 if (definedIn) 8386 *definedIn = cxstring::createDup(attr->getDefinedIn()); 8387 if (isGenerated) 8388 *isGenerated = attr->getGeneratedDeclaration(); 8389 return 1; 8390 } 8391 return 0; 8392 } 8393 8394 CXSourceRange clang_Cursor_getCommentRange(CXCursor C) { 8395 if (!clang_isDeclaration(C.kind)) 8396 return clang_getNullRange(); 8397 8398 const Decl *D = getCursorDecl(C); 8399 ASTContext &Context = getCursorContext(C); 8400 const RawComment *RC = Context.getRawCommentForAnyRedecl(D); 8401 if (!RC) 8402 return clang_getNullRange(); 8403 8404 return cxloc::translateSourceRange(Context, RC->getSourceRange()); 8405 } 8406 8407 CXString clang_Cursor_getRawCommentText(CXCursor C) { 8408 if (!clang_isDeclaration(C.kind)) 8409 return cxstring::createNull(); 8410 8411 const Decl *D = getCursorDecl(C); 8412 ASTContext &Context = getCursorContext(C); 8413 const RawComment *RC = Context.getRawCommentForAnyRedecl(D); 8414 StringRef RawText = 8415 RC ? RC->getRawText(Context.getSourceManager()) : StringRef(); 8416 8417 // Don't duplicate the string because RawText points directly into source 8418 // code. 8419 return cxstring::createRef(RawText); 8420 } 8421 8422 CXString clang_Cursor_getBriefCommentText(CXCursor C) { 8423 if (!clang_isDeclaration(C.kind)) 8424 return cxstring::createNull(); 8425 8426 const Decl *D = getCursorDecl(C); 8427 const ASTContext &Context = getCursorContext(C); 8428 const RawComment *RC = Context.getRawCommentForAnyRedecl(D); 8429 8430 if (RC) { 8431 StringRef BriefText = RC->getBriefText(Context); 8432 8433 // Don't duplicate the string because RawComment ensures that this memory 8434 // will not go away. 8435 return cxstring::createRef(BriefText); 8436 } 8437 8438 return cxstring::createNull(); 8439 } 8440 8441 CXModule clang_Cursor_getModule(CXCursor C) { 8442 if (C.kind == CXCursor_ModuleImportDecl) { 8443 if (const ImportDecl *ImportD = 8444 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) 8445 return ImportD->getImportedModule(); 8446 } 8447 8448 return nullptr; 8449 } 8450 8451 CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) { 8452 if (isNotUsableTU(TU)) { 8453 LOG_BAD_TU(TU); 8454 return nullptr; 8455 } 8456 if (!File) 8457 return nullptr; 8458 FileEntry *FE = static_cast<FileEntry *>(File); 8459 8460 ASTUnit &Unit = *cxtu::getASTUnit(TU); 8461 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo(); 8462 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE); 8463 8464 return Header.getModule(); 8465 } 8466 8467 CXFile clang_Module_getASTFile(CXModule CXMod) { 8468 if (!CXMod) 8469 return nullptr; 8470 Module *Mod = static_cast<Module *>(CXMod); 8471 if (auto File = Mod->getASTFile()) 8472 return const_cast<FileEntry *>(&File->getFileEntry()); 8473 return nullptr; 8474 } 8475 8476 CXModule clang_Module_getParent(CXModule CXMod) { 8477 if (!CXMod) 8478 return nullptr; 8479 Module *Mod = static_cast<Module *>(CXMod); 8480 return Mod->Parent; 8481 } 8482 8483 CXString clang_Module_getName(CXModule CXMod) { 8484 if (!CXMod) 8485 return cxstring::createEmpty(); 8486 Module *Mod = static_cast<Module *>(CXMod); 8487 return cxstring::createDup(Mod->Name); 8488 } 8489 8490 CXString clang_Module_getFullName(CXModule CXMod) { 8491 if (!CXMod) 8492 return cxstring::createEmpty(); 8493 Module *Mod = static_cast<Module *>(CXMod); 8494 return cxstring::createDup(Mod->getFullModuleName()); 8495 } 8496 8497 int clang_Module_isSystem(CXModule CXMod) { 8498 if (!CXMod) 8499 return 0; 8500 Module *Mod = static_cast<Module *>(CXMod); 8501 return Mod->IsSystem; 8502 } 8503 8504 unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU, 8505 CXModule CXMod) { 8506 if (isNotUsableTU(TU)) { 8507 LOG_BAD_TU(TU); 8508 return 0; 8509 } 8510 if (!CXMod) 8511 return 0; 8512 Module *Mod = static_cast<Module *>(CXMod); 8513 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager(); 8514 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr); 8515 return TopHeaders.size(); 8516 } 8517 8518 CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU, CXModule CXMod, 8519 unsigned Index) { 8520 if (isNotUsableTU(TU)) { 8521 LOG_BAD_TU(TU); 8522 return nullptr; 8523 } 8524 if (!CXMod) 8525 return nullptr; 8526 Module *Mod = static_cast<Module *>(CXMod); 8527 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager(); 8528 8529 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr); 8530 if (Index < TopHeaders.size()) 8531 return const_cast<FileEntry *>(TopHeaders[Index]); 8532 8533 return nullptr; 8534 } 8535 8536 //===----------------------------------------------------------------------===// 8537 // C++ AST instrospection. 8538 //===----------------------------------------------------------------------===// 8539 8540 unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) { 8541 if (!clang_isDeclaration(C.kind)) 8542 return 0; 8543 8544 const Decl *D = cxcursor::getCursorDecl(C); 8545 const CXXConstructorDecl *Constructor = 8546 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr; 8547 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0; 8548 } 8549 8550 unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) { 8551 if (!clang_isDeclaration(C.kind)) 8552 return 0; 8553 8554 const Decl *D = cxcursor::getCursorDecl(C); 8555 const CXXConstructorDecl *Constructor = 8556 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr; 8557 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0; 8558 } 8559 8560 unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) { 8561 if (!clang_isDeclaration(C.kind)) 8562 return 0; 8563 8564 const Decl *D = cxcursor::getCursorDecl(C); 8565 const CXXConstructorDecl *Constructor = 8566 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr; 8567 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0; 8568 } 8569 8570 unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) { 8571 if (!clang_isDeclaration(C.kind)) 8572 return 0; 8573 8574 const Decl *D = cxcursor::getCursorDecl(C); 8575 const CXXConstructorDecl *Constructor = 8576 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr; 8577 // Passing 'false' excludes constructors marked 'explicit'. 8578 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0; 8579 } 8580 8581 unsigned clang_CXXField_isMutable(CXCursor C) { 8582 if (!clang_isDeclaration(C.kind)) 8583 return 0; 8584 8585 if (const auto D = cxcursor::getCursorDecl(C)) 8586 if (const auto FD = dyn_cast_or_null<FieldDecl>(D)) 8587 return FD->isMutable() ? 1 : 0; 8588 return 0; 8589 } 8590 8591 unsigned clang_CXXMethod_isPureVirtual(CXCursor C) { 8592 if (!clang_isDeclaration(C.kind)) 8593 return 0; 8594 8595 const Decl *D = cxcursor::getCursorDecl(C); 8596 const CXXMethodDecl *Method = 8597 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr; 8598 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0; 8599 } 8600 8601 unsigned clang_CXXMethod_isConst(CXCursor C) { 8602 if (!clang_isDeclaration(C.kind)) 8603 return 0; 8604 8605 const Decl *D = cxcursor::getCursorDecl(C); 8606 const CXXMethodDecl *Method = 8607 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr; 8608 return (Method && Method->getMethodQualifiers().hasConst()) ? 1 : 0; 8609 } 8610 8611 unsigned clang_CXXMethod_isDefaulted(CXCursor C) { 8612 if (!clang_isDeclaration(C.kind)) 8613 return 0; 8614 8615 const Decl *D = cxcursor::getCursorDecl(C); 8616 const CXXMethodDecl *Method = 8617 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr; 8618 return (Method && Method->isDefaulted()) ? 1 : 0; 8619 } 8620 8621 unsigned clang_CXXMethod_isStatic(CXCursor C) { 8622 if (!clang_isDeclaration(C.kind)) 8623 return 0; 8624 8625 const Decl *D = cxcursor::getCursorDecl(C); 8626 const CXXMethodDecl *Method = 8627 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr; 8628 return (Method && Method->isStatic()) ? 1 : 0; 8629 } 8630 8631 unsigned clang_CXXMethod_isVirtual(CXCursor C) { 8632 if (!clang_isDeclaration(C.kind)) 8633 return 0; 8634 8635 const Decl *D = cxcursor::getCursorDecl(C); 8636 const CXXMethodDecl *Method = 8637 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr; 8638 return (Method && Method->isVirtual()) ? 1 : 0; 8639 } 8640 8641 unsigned clang_CXXRecord_isAbstract(CXCursor C) { 8642 if (!clang_isDeclaration(C.kind)) 8643 return 0; 8644 8645 const auto *D = cxcursor::getCursorDecl(C); 8646 const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D); 8647 if (RD) 8648 RD = RD->getDefinition(); 8649 return (RD && RD->isAbstract()) ? 1 : 0; 8650 } 8651 8652 unsigned clang_EnumDecl_isScoped(CXCursor C) { 8653 if (!clang_isDeclaration(C.kind)) 8654 return 0; 8655 8656 const Decl *D = cxcursor::getCursorDecl(C); 8657 auto *Enum = dyn_cast_or_null<EnumDecl>(D); 8658 return (Enum && Enum->isScoped()) ? 1 : 0; 8659 } 8660 8661 //===----------------------------------------------------------------------===// 8662 // Attribute introspection. 8663 //===----------------------------------------------------------------------===// 8664 8665 CXType clang_getIBOutletCollectionType(CXCursor C) { 8666 if (C.kind != CXCursor_IBOutletCollectionAttr) 8667 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C)); 8668 8669 const IBOutletCollectionAttr *A = 8670 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C)); 8671 8672 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C)); 8673 } 8674 8675 //===----------------------------------------------------------------------===// 8676 // Inspecting memory usage. 8677 //===----------------------------------------------------------------------===// 8678 8679 typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries; 8680 8681 static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries, 8682 enum CXTUResourceUsageKind k, 8683 unsigned long amount) { 8684 CXTUResourceUsageEntry entry = {k, amount}; 8685 entries.push_back(entry); 8686 } 8687 8688 const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) { 8689 const char *str = ""; 8690 switch (kind) { 8691 case CXTUResourceUsage_AST: 8692 str = "ASTContext: expressions, declarations, and types"; 8693 break; 8694 case CXTUResourceUsage_Identifiers: 8695 str = "ASTContext: identifiers"; 8696 break; 8697 case CXTUResourceUsage_Selectors: 8698 str = "ASTContext: selectors"; 8699 break; 8700 case CXTUResourceUsage_GlobalCompletionResults: 8701 str = "Code completion: cached global results"; 8702 break; 8703 case CXTUResourceUsage_SourceManagerContentCache: 8704 str = "SourceManager: content cache allocator"; 8705 break; 8706 case CXTUResourceUsage_AST_SideTables: 8707 str = "ASTContext: side tables"; 8708 break; 8709 case CXTUResourceUsage_SourceManager_Membuffer_Malloc: 8710 str = "SourceManager: malloc'ed memory buffers"; 8711 break; 8712 case CXTUResourceUsage_SourceManager_Membuffer_MMap: 8713 str = "SourceManager: mmap'ed memory buffers"; 8714 break; 8715 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc: 8716 str = "ExternalASTSource: malloc'ed memory buffers"; 8717 break; 8718 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap: 8719 str = "ExternalASTSource: mmap'ed memory buffers"; 8720 break; 8721 case CXTUResourceUsage_Preprocessor: 8722 str = "Preprocessor: malloc'ed memory"; 8723 break; 8724 case CXTUResourceUsage_PreprocessingRecord: 8725 str = "Preprocessor: PreprocessingRecord"; 8726 break; 8727 case CXTUResourceUsage_SourceManager_DataStructures: 8728 str = "SourceManager: data structures and tables"; 8729 break; 8730 case CXTUResourceUsage_Preprocessor_HeaderSearch: 8731 str = "Preprocessor: header search tables"; 8732 break; 8733 } 8734 return str; 8735 } 8736 8737 CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) { 8738 if (isNotUsableTU(TU)) { 8739 LOG_BAD_TU(TU); 8740 CXTUResourceUsage usage = {(void *)nullptr, 0, nullptr}; 8741 return usage; 8742 } 8743 8744 ASTUnit *astUnit = cxtu::getASTUnit(TU); 8745 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries()); 8746 ASTContext &astContext = astUnit->getASTContext(); 8747 8748 // How much memory is used by AST nodes and types? 8749 createCXTUResourceUsageEntry( 8750 *entries, CXTUResourceUsage_AST, 8751 (unsigned long)astContext.getASTAllocatedMemory()); 8752 8753 // How much memory is used by identifiers? 8754 createCXTUResourceUsageEntry( 8755 *entries, CXTUResourceUsage_Identifiers, 8756 (unsigned long)astContext.Idents.getAllocator().getTotalMemory()); 8757 8758 // How much memory is used for selectors? 8759 createCXTUResourceUsageEntry( 8760 *entries, CXTUResourceUsage_Selectors, 8761 (unsigned long)astContext.Selectors.getTotalMemory()); 8762 8763 // How much memory is used by ASTContext's side tables? 8764 createCXTUResourceUsageEntry( 8765 *entries, CXTUResourceUsage_AST_SideTables, 8766 (unsigned long)astContext.getSideTableAllocatedMemory()); 8767 8768 // How much memory is used for caching global code completion results? 8769 unsigned long completionBytes = 0; 8770 if (GlobalCodeCompletionAllocator *completionAllocator = 8771 astUnit->getCachedCompletionAllocator().get()) { 8772 completionBytes = completionAllocator->getTotalMemory(); 8773 } 8774 createCXTUResourceUsageEntry( 8775 *entries, CXTUResourceUsage_GlobalCompletionResults, completionBytes); 8776 8777 // How much memory is being used by SourceManager's content cache? 8778 createCXTUResourceUsageEntry( 8779 *entries, CXTUResourceUsage_SourceManagerContentCache, 8780 (unsigned long)astContext.getSourceManager().getContentCacheSize()); 8781 8782 // How much memory is being used by the MemoryBuffer's in SourceManager? 8783 const SourceManager::MemoryBufferSizes &srcBufs = 8784 astUnit->getSourceManager().getMemoryBufferSizes(); 8785 8786 createCXTUResourceUsageEntry(*entries, 8787 CXTUResourceUsage_SourceManager_Membuffer_Malloc, 8788 (unsigned long)srcBufs.malloc_bytes); 8789 createCXTUResourceUsageEntry(*entries, 8790 CXTUResourceUsage_SourceManager_Membuffer_MMap, 8791 (unsigned long)srcBufs.mmap_bytes); 8792 createCXTUResourceUsageEntry( 8793 *entries, CXTUResourceUsage_SourceManager_DataStructures, 8794 (unsigned long)astContext.getSourceManager().getDataStructureSizes()); 8795 8796 // How much memory is being used by the ExternalASTSource? 8797 if (ExternalASTSource *esrc = astContext.getExternalSource()) { 8798 const ExternalASTSource::MemoryBufferSizes &sizes = 8799 esrc->getMemoryBufferSizes(); 8800 8801 createCXTUResourceUsageEntry( 8802 *entries, CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc, 8803 (unsigned long)sizes.malloc_bytes); 8804 createCXTUResourceUsageEntry( 8805 *entries, CXTUResourceUsage_ExternalASTSource_Membuffer_MMap, 8806 (unsigned long)sizes.mmap_bytes); 8807 } 8808 8809 // How much memory is being used by the Preprocessor? 8810 Preprocessor &pp = astUnit->getPreprocessor(); 8811 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Preprocessor, 8812 pp.getTotalMemory()); 8813 8814 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) { 8815 createCXTUResourceUsageEntry(*entries, 8816 CXTUResourceUsage_PreprocessingRecord, 8817 pRec->getTotalMemory()); 8818 } 8819 8820 createCXTUResourceUsageEntry(*entries, 8821 CXTUResourceUsage_Preprocessor_HeaderSearch, 8822 pp.getHeaderSearchInfo().getTotalMemory()); 8823 8824 CXTUResourceUsage usage = {(void *)entries.get(), (unsigned)entries->size(), 8825 !entries->empty() ? &(*entries)[0] : nullptr}; 8826 (void)entries.release(); 8827 return usage; 8828 } 8829 8830 void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) { 8831 if (usage.data) 8832 delete (MemUsageEntries *)usage.data; 8833 } 8834 8835 CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) { 8836 CXSourceRangeList *skipped = new CXSourceRangeList; 8837 skipped->count = 0; 8838 skipped->ranges = nullptr; 8839 8840 if (isNotUsableTU(TU)) { 8841 LOG_BAD_TU(TU); 8842 return skipped; 8843 } 8844 8845 if (!file) 8846 return skipped; 8847 8848 ASTUnit *astUnit = cxtu::getASTUnit(TU); 8849 PreprocessingRecord *ppRec = 8850 astUnit->getPreprocessor().getPreprocessingRecord(); 8851 if (!ppRec) 8852 return skipped; 8853 8854 ASTContext &Ctx = astUnit->getASTContext(); 8855 SourceManager &sm = Ctx.getSourceManager(); 8856 FileEntry *fileEntry = static_cast<FileEntry *>(file); 8857 FileID wantedFileID = sm.translateFile(fileEntry); 8858 bool isMainFile = wantedFileID == sm.getMainFileID(); 8859 8860 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges(); 8861 std::vector<SourceRange> wantedRanges; 8862 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), 8863 ei = SkippedRanges.end(); 8864 i != ei; ++i) { 8865 if (sm.getFileID(i->getBegin()) == wantedFileID || 8866 sm.getFileID(i->getEnd()) == wantedFileID) 8867 wantedRanges.push_back(*i); 8868 else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) || 8869 astUnit->isInPreambleFileID(i->getEnd()))) 8870 wantedRanges.push_back(*i); 8871 } 8872 8873 skipped->count = wantedRanges.size(); 8874 skipped->ranges = new CXSourceRange[skipped->count]; 8875 for (unsigned i = 0, ei = skipped->count; i != ei; ++i) 8876 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]); 8877 8878 return skipped; 8879 } 8880 8881 CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) { 8882 CXSourceRangeList *skipped = new CXSourceRangeList; 8883 skipped->count = 0; 8884 skipped->ranges = nullptr; 8885 8886 if (isNotUsableTU(TU)) { 8887 LOG_BAD_TU(TU); 8888 return skipped; 8889 } 8890 8891 ASTUnit *astUnit = cxtu::getASTUnit(TU); 8892 PreprocessingRecord *ppRec = 8893 astUnit->getPreprocessor().getPreprocessingRecord(); 8894 if (!ppRec) 8895 return skipped; 8896 8897 ASTContext &Ctx = astUnit->getASTContext(); 8898 8899 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges(); 8900 8901 skipped->count = SkippedRanges.size(); 8902 skipped->ranges = new CXSourceRange[skipped->count]; 8903 for (unsigned i = 0, ei = skipped->count; i != ei; ++i) 8904 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]); 8905 8906 return skipped; 8907 } 8908 8909 void clang_disposeSourceRangeList(CXSourceRangeList *ranges) { 8910 if (ranges) { 8911 delete[] ranges->ranges; 8912 delete ranges; 8913 } 8914 } 8915 8916 void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) { 8917 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU); 8918 for (unsigned I = 0; I != Usage.numEntries; ++I) 8919 fprintf(stderr, " %s: %lu\n", 8920 clang_getTUResourceUsageName(Usage.entries[I].kind), 8921 Usage.entries[I].amount); 8922 8923 clang_disposeCXTUResourceUsage(Usage); 8924 } 8925 8926 CXCursor clang_Cursor_getVarDeclInitializer(CXCursor cursor) { 8927 const Decl *const D = getCursorDecl(cursor); 8928 if (!D) 8929 return clang_getNullCursor(); 8930 const auto *const VD = dyn_cast<VarDecl>(D); 8931 if (!VD) 8932 return clang_getNullCursor(); 8933 const Expr *const Init = VD->getInit(); 8934 if (!Init) 8935 return clang_getNullCursor(); 8936 8937 return cxcursor::MakeCXCursor(Init, VD, cxcursor::getCursorTU(cursor)); 8938 } 8939 8940 int clang_Cursor_hasVarDeclGlobalStorage(CXCursor cursor) { 8941 const Decl *const D = getCursorDecl(cursor); 8942 if (!D) 8943 return -1; 8944 const auto *const VD = dyn_cast<VarDecl>(D); 8945 if (!VD) 8946 return -1; 8947 8948 return VD->hasGlobalStorage(); 8949 } 8950 8951 int clang_Cursor_hasVarDeclExternalStorage(CXCursor cursor) { 8952 const Decl *const D = getCursorDecl(cursor); 8953 if (!D) 8954 return -1; 8955 const auto *const VD = dyn_cast<VarDecl>(D); 8956 if (!VD) 8957 return -1; 8958 8959 return VD->hasExternalStorage(); 8960 } 8961 8962 //===----------------------------------------------------------------------===// 8963 // Misc. utility functions. 8964 //===----------------------------------------------------------------------===// 8965 8966 /// Default to using our desired 8 MB stack size on "safety" threads. 8967 static unsigned SafetyStackThreadSize = DesiredStackSize; 8968 8969 namespace clang { 8970 8971 bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn, 8972 unsigned Size) { 8973 if (!Size) 8974 Size = GetSafetyThreadStackSize(); 8975 if (Size && !getenv("LIBCLANG_NOTHREADS")) 8976 return CRC.RunSafelyOnThread(Fn, Size); 8977 return CRC.RunSafely(Fn); 8978 } 8979 8980 unsigned GetSafetyThreadStackSize() { return SafetyStackThreadSize; } 8981 8982 void SetSafetyThreadStackSize(unsigned Value) { SafetyStackThreadSize = Value; } 8983 8984 } // namespace clang 8985 8986 void clang::setThreadBackgroundPriority() { 8987 if (getenv("LIBCLANG_BGPRIO_DISABLE")) 8988 return; 8989 8990 #if LLVM_ENABLE_THREADS 8991 llvm::set_thread_priority(llvm::ThreadPriority::Background); 8992 #endif 8993 } 8994 8995 void cxindex::printDiagsToStderr(ASTUnit *Unit) { 8996 if (!Unit) 8997 return; 8998 8999 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(), 9000 DEnd = Unit->stored_diag_end(); 9001 D != DEnd; ++D) { 9002 CXStoredDiagnostic Diag(*D, Unit->getLangOpts()); 9003 CXString Msg = 9004 clang_formatDiagnostic(&Diag, clang_defaultDiagnosticDisplayOptions()); 9005 fprintf(stderr, "%s\n", clang_getCString(Msg)); 9006 clang_disposeString(Msg); 9007 } 9008 #ifdef _WIN32 9009 // On Windows, force a flush, since there may be multiple copies of 9010 // stderr and stdout in the file system, all with different buffers 9011 // but writing to the same device. 9012 fflush(stderr); 9013 #endif 9014 } 9015 9016 MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II, 9017 SourceLocation MacroDefLoc, 9018 CXTranslationUnit TU) { 9019 if (MacroDefLoc.isInvalid() || !TU) 9020 return nullptr; 9021 if (!II.hadMacroDefinition()) 9022 return nullptr; 9023 9024 ASTUnit *Unit = cxtu::getASTUnit(TU); 9025 Preprocessor &PP = Unit->getPreprocessor(); 9026 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II); 9027 if (MD) { 9028 for (MacroDirective::DefInfo Def = MD->getDefinition(); Def; 9029 Def = Def.getPreviousDefinition()) { 9030 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc()) 9031 return Def.getMacroInfo(); 9032 } 9033 } 9034 9035 return nullptr; 9036 } 9037 9038 const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef, 9039 CXTranslationUnit TU) { 9040 if (!MacroDef || !TU) 9041 return nullptr; 9042 const IdentifierInfo *II = MacroDef->getName(); 9043 if (!II) 9044 return nullptr; 9045 9046 return getMacroInfo(*II, MacroDef->getLocation(), TU); 9047 } 9048 9049 MacroDefinitionRecord * 9050 cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok, 9051 CXTranslationUnit TU) { 9052 if (!MI || !TU) 9053 return nullptr; 9054 if (Tok.isNot(tok::raw_identifier)) 9055 return nullptr; 9056 9057 if (MI->getNumTokens() == 0) 9058 return nullptr; 9059 SourceRange DefRange(MI->getReplacementToken(0).getLocation(), 9060 MI->getDefinitionEndLoc()); 9061 ASTUnit *Unit = cxtu::getASTUnit(TU); 9062 9063 // Check that the token is inside the definition and not its argument list. 9064 SourceManager &SM = Unit->getSourceManager(); 9065 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin())) 9066 return nullptr; 9067 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation())) 9068 return nullptr; 9069 9070 Preprocessor &PP = Unit->getPreprocessor(); 9071 PreprocessingRecord *PPRec = PP.getPreprocessingRecord(); 9072 if (!PPRec) 9073 return nullptr; 9074 9075 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier()); 9076 if (!II.hadMacroDefinition()) 9077 return nullptr; 9078 9079 // Check that the identifier is not one of the macro arguments. 9080 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end()) 9081 return nullptr; 9082 9083 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II); 9084 if (!InnerMD) 9085 return nullptr; 9086 9087 return PPRec->findMacroDefinition(InnerMD->getMacroInfo()); 9088 } 9089 9090 MacroDefinitionRecord * 9091 cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc, 9092 CXTranslationUnit TU) { 9093 if (Loc.isInvalid() || !MI || !TU) 9094 return nullptr; 9095 9096 if (MI->getNumTokens() == 0) 9097 return nullptr; 9098 ASTUnit *Unit = cxtu::getASTUnit(TU); 9099 Preprocessor &PP = Unit->getPreprocessor(); 9100 if (!PP.getPreprocessingRecord()) 9101 return nullptr; 9102 Loc = Unit->getSourceManager().getSpellingLoc(Loc); 9103 Token Tok; 9104 if (PP.getRawToken(Loc, Tok)) 9105 return nullptr; 9106 9107 return checkForMacroInMacroDefinition(MI, Tok, TU); 9108 } 9109 9110 CXString clang_getClangVersion() { 9111 return cxstring::createDup(getClangFullVersion()); 9112 } 9113 9114 Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) { 9115 if (TU) { 9116 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) { 9117 LogOS << '<' << Unit->getMainFileName() << '>'; 9118 if (Unit->isMainFileAST()) 9119 LogOS << " (" << Unit->getASTFileName() << ')'; 9120 return *this; 9121 } 9122 } else { 9123 LogOS << "<NULL TU>"; 9124 } 9125 return *this; 9126 } 9127 9128 Logger &cxindex::Logger::operator<<(const FileEntry *FE) { 9129 *this << FE->getName(); 9130 return *this; 9131 } 9132 9133 Logger &cxindex::Logger::operator<<(CXCursor cursor) { 9134 CXString cursorName = clang_getCursorDisplayName(cursor); 9135 *this << cursorName << "@" << clang_getCursorLocation(cursor); 9136 clang_disposeString(cursorName); 9137 return *this; 9138 } 9139 9140 Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) { 9141 CXFile File; 9142 unsigned Line, Column; 9143 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr); 9144 CXString FileName = clang_getFileName(File); 9145 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column); 9146 clang_disposeString(FileName); 9147 return *this; 9148 } 9149 9150 Logger &cxindex::Logger::operator<<(CXSourceRange range) { 9151 CXSourceLocation BLoc = clang_getRangeStart(range); 9152 CXSourceLocation ELoc = clang_getRangeEnd(range); 9153 9154 CXFile BFile; 9155 unsigned BLine, BColumn; 9156 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr); 9157 9158 CXFile EFile; 9159 unsigned ELine, EColumn; 9160 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr); 9161 9162 CXString BFileName = clang_getFileName(BFile); 9163 if (BFile == EFile) { 9164 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName), 9165 BLine, BColumn, ELine, EColumn); 9166 } else { 9167 CXString EFileName = clang_getFileName(EFile); 9168 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName), BLine, 9169 BColumn) 9170 << llvm::format("%s:%d:%d]", clang_getCString(EFileName), ELine, 9171 EColumn); 9172 clang_disposeString(EFileName); 9173 } 9174 clang_disposeString(BFileName); 9175 return *this; 9176 } 9177 9178 Logger &cxindex::Logger::operator<<(CXString Str) { 9179 *this << clang_getCString(Str); 9180 return *this; 9181 } 9182 9183 Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) { 9184 LogOS << Fmt; 9185 return *this; 9186 } 9187 9188 static llvm::ManagedStatic<std::mutex> LoggingMutex; 9189 9190 cxindex::Logger::~Logger() { 9191 std::lock_guard<std::mutex> L(*LoggingMutex); 9192 9193 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime(); 9194 9195 raw_ostream &OS = llvm::errs(); 9196 OS << "[libclang:" << Name << ':'; 9197 9198 #ifdef USE_DARWIN_THREADS 9199 // TODO: Portability. 9200 mach_port_t tid = pthread_mach_thread_np(pthread_self()); 9201 OS << tid << ':'; 9202 #endif 9203 9204 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime(); 9205 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime()); 9206 OS << Msg << '\n'; 9207 9208 if (Trace) { 9209 llvm::sys::PrintStackTrace(OS); 9210 OS << "--------------------------------------------------\n"; 9211 } 9212 } 9213