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