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