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