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