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