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