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