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