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