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