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