CIndex.cpp revision d47afb96a3f988e6d21a92fe4dfe875ab227c7c0
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 "CXComment.h" 19#include "CXCursor.h" 20#include "CXSourceLocation.h" 21#include "CXString.h" 22#include "CXTranslationUnit.h" 23#include "CXType.h" 24#include "CursorVisitor.h" 25#include "SimpleFormatContext.h" 26#include "clang/AST/StmtVisitor.h" 27#include "clang/Basic/Diagnostic.h" 28#include "clang/Basic/Version.h" 29#include "clang/Frontend/ASTUnit.h" 30#include "clang/Frontend/CompilerInstance.h" 31#include "clang/Frontend/FrontendDiagnostic.h" 32#include "clang/Lex/HeaderSearch.h" 33#include "clang/Lex/Lexer.h" 34#include "clang/Lex/PreprocessingRecord.h" 35#include "clang/Lex/Preprocessor.h" 36#include "llvm/ADT/Optional.h" 37#include "llvm/ADT/STLExtras.h" 38#include "llvm/ADT/StringSwitch.h" 39#include "llvm/Config/config.h" 40#include "llvm/Support/Compiler.h" 41#include "llvm/Support/CrashRecoveryContext.h" 42#include "llvm/Support/Format.h" 43#include "llvm/Support/MemoryBuffer.h" 44#include "llvm/Support/Mutex.h" 45#include "llvm/Support/PrettyStackTrace.h" 46#include "llvm/Support/Program.h" 47#include "llvm/Support/SaveAndRestore.h" 48#include "llvm/Support/Signals.h" 49#include "llvm/Support/Threading.h" 50#include "llvm/Support/Timer.h" 51#include "llvm/Support/raw_ostream.h" 52 53#if HAVE_PTHREAD_H 54#include <pthread.h> 55#endif 56 57using namespace clang; 58using namespace clang::cxcursor; 59using namespace clang::cxstring; 60using namespace clang::cxtu; 61using namespace clang::cxindex; 62 63CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx, ASTUnit *TU) { 64 if (!TU) 65 return 0; 66 CXTranslationUnit D = new CXTranslationUnitImpl(); 67 D->CIdx = CIdx; 68 D->TUData = TU; 69 D->StringPool = createCXStringPool(); 70 D->Diagnostics = 0; 71 D->OverridenCursorsPool = createOverridenCXCursorsPool(); 72 D->FormatContext = 0; 73 D->FormatInMemoryUniqueId = 0; 74 return D; 75} 76 77cxtu::CXTUOwner::~CXTUOwner() { 78 if (TU) 79 clang_disposeTranslationUnit(TU); 80} 81 82/// \brief Compare two source ranges to determine their relative position in 83/// the translation unit. 84static RangeComparisonResult RangeCompare(SourceManager &SM, 85 SourceRange R1, 86 SourceRange R2) { 87 assert(R1.isValid() && "First range is invalid?"); 88 assert(R2.isValid() && "Second range is invalid?"); 89 if (R1.getEnd() != R2.getBegin() && 90 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin())) 91 return RangeBefore; 92 if (R2.getEnd() != R1.getBegin() && 93 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin())) 94 return RangeAfter; 95 return RangeOverlap; 96} 97 98/// \brief Determine if a source location falls within, before, or after a 99/// a given source range. 100static RangeComparisonResult LocationCompare(SourceManager &SM, 101 SourceLocation L, SourceRange R) { 102 assert(R.isValid() && "First range is invalid?"); 103 assert(L.isValid() && "Second range is invalid?"); 104 if (L == R.getBegin() || L == R.getEnd()) 105 return RangeOverlap; 106 if (SM.isBeforeInTranslationUnit(L, R.getBegin())) 107 return RangeBefore; 108 if (SM.isBeforeInTranslationUnit(R.getEnd(), L)) 109 return RangeAfter; 110 return RangeOverlap; 111} 112 113/// \brief Translate a Clang source range into a CIndex source range. 114/// 115/// Clang internally represents ranges where the end location points to the 116/// start of the token at the end. However, for external clients it is more 117/// useful to have a CXSourceRange be a proper half-open interval. This routine 118/// does the appropriate translation. 119CXSourceRange cxloc::translateSourceRange(const SourceManager &SM, 120 const LangOptions &LangOpts, 121 const CharSourceRange &R) { 122 // We want the last character in this location, so we will adjust the 123 // location accordingly. 124 SourceLocation EndLoc = R.getEnd(); 125 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc)) 126 EndLoc = SM.getExpansionRange(EndLoc).second; 127 if (R.isTokenRange() && !EndLoc.isInvalid()) { 128 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc), 129 SM, LangOpts); 130 EndLoc = EndLoc.getLocWithOffset(Length); 131 } 132 133 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts }, 134 R.getBegin().getRawEncoding(), 135 EndLoc.getRawEncoding() }; 136 return Result; 137} 138 139//===----------------------------------------------------------------------===// 140// Cursor visitor. 141//===----------------------------------------------------------------------===// 142 143static SourceRange getRawCursorExtent(CXCursor C); 144static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr); 145 146 147RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) { 148 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest); 149} 150 151/// \brief Visit the given cursor and, if requested by the visitor, 152/// its children. 153/// 154/// \param Cursor the cursor to visit. 155/// 156/// \param CheckedRegionOfInterest if true, then the caller already checked 157/// that this cursor is within the region of interest. 158/// 159/// \returns true if the visitation should be aborted, false if it 160/// should continue. 161bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) { 162 if (clang_isInvalid(Cursor.kind)) 163 return false; 164 165 if (clang_isDeclaration(Cursor.kind)) { 166 Decl *D = getCursorDecl(Cursor); 167 if (!D) { 168 assert(0 && "Invalid declaration cursor"); 169 return true; // abort. 170 } 171 172 // Ignore implicit declarations, unless it's an objc method because 173 // currently we should report implicit methods for properties when indexing. 174 if (D->isImplicit() && !isa<ObjCMethodDecl>(D)) 175 return false; 176 } 177 178 // If we have a range of interest, and this cursor doesn't intersect with it, 179 // we're done. 180 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) { 181 SourceRange Range = getRawCursorExtent(Cursor); 182 if (Range.isInvalid() || CompareRegionOfInterest(Range)) 183 return false; 184 } 185 186 switch (Visitor(Cursor, Parent, ClientData)) { 187 case CXChildVisit_Break: 188 return true; 189 190 case CXChildVisit_Continue: 191 return false; 192 193 case CXChildVisit_Recurse: { 194 bool ret = VisitChildren(Cursor); 195 if (PostChildrenVisitor) 196 if (PostChildrenVisitor(Cursor, ClientData)) 197 return true; 198 return ret; 199 } 200 } 201 202 llvm_unreachable("Invalid CXChildVisitResult!"); 203} 204 205static bool visitPreprocessedEntitiesInRange(SourceRange R, 206 PreprocessingRecord &PPRec, 207 CursorVisitor &Visitor) { 208 SourceManager &SM = Visitor.getASTUnit()->getSourceManager(); 209 FileID FID; 210 211 if (!Visitor.shouldVisitIncludedEntities()) { 212 // If the begin/end of the range lie in the same FileID, do the optimization 213 // where we skip preprocessed entities that do not come from the same FileID. 214 FID = SM.getFileID(SM.getFileLoc(R.getBegin())); 215 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd()))) 216 FID = FileID(); 217 } 218 219 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator> 220 Entities = PPRec.getPreprocessedEntitiesInRange(R); 221 return Visitor.visitPreprocessedEntities(Entities.first, Entities.second, 222 PPRec, FID); 223} 224 225void CursorVisitor::visitFileRegion() { 226 if (RegionOfInterest.isInvalid()) 227 return; 228 229 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData); 230 SourceManager &SM = Unit->getSourceManager(); 231 232 std::pair<FileID, unsigned> 233 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())), 234 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd())); 235 236 if (End.first != Begin.first) { 237 // If the end does not reside in the same file, try to recover by 238 // picking the end of the file of begin location. 239 End.first = Begin.first; 240 End.second = SM.getFileIDSize(Begin.first); 241 } 242 243 assert(Begin.first == End.first); 244 if (Begin.second > End.second) 245 return; 246 247 FileID File = Begin.first; 248 unsigned Offset = Begin.second; 249 unsigned Length = End.second - Begin.second; 250 251 if (!VisitDeclsOnly && !VisitPreprocessorLast) 252 if (visitPreprocessedEntitiesInRegion()) 253 return; // visitation break. 254 255 visitDeclsFromFileRegion(File, Offset, Length); 256 257 if (!VisitDeclsOnly && VisitPreprocessorLast) 258 visitPreprocessedEntitiesInRegion(); 259} 260 261static bool isInLexicalContext(Decl *D, DeclContext *DC) { 262 if (!DC) 263 return false; 264 265 for (DeclContext *DeclDC = D->getLexicalDeclContext(); 266 DeclDC; DeclDC = DeclDC->getLexicalParent()) { 267 if (DeclDC == DC) 268 return true; 269 } 270 return false; 271} 272 273void CursorVisitor::visitDeclsFromFileRegion(FileID File, 274 unsigned Offset, unsigned Length) { 275 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData); 276 SourceManager &SM = Unit->getSourceManager(); 277 SourceRange Range = RegionOfInterest; 278 279 SmallVector<Decl *, 16> Decls; 280 Unit->findFileRegionDecls(File, Offset, Length, Decls); 281 282 // If we didn't find any file level decls for the file, try looking at the 283 // file that it was included from. 284 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) { 285 bool Invalid = false; 286 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid); 287 if (Invalid) 288 return; 289 290 SourceLocation Outer; 291 if (SLEntry.isFile()) 292 Outer = SLEntry.getFile().getIncludeLoc(); 293 else 294 Outer = SLEntry.getExpansion().getExpansionLocStart(); 295 if (Outer.isInvalid()) 296 return; 297 298 llvm::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer); 299 Length = 0; 300 Unit->findFileRegionDecls(File, Offset, Length, Decls); 301 } 302 303 assert(!Decls.empty()); 304 305 bool VisitedAtLeastOnce = false; 306 DeclContext *CurDC = 0; 307 SmallVector<Decl *, 16>::iterator DIt = Decls.begin(); 308 for (SmallVector<Decl *, 16>::iterator DE = Decls.end(); DIt != DE; ++DIt) { 309 Decl *D = *DIt; 310 if (D->getSourceRange().isInvalid()) 311 continue; 312 313 if (isInLexicalContext(D, CurDC)) 314 continue; 315 316 CurDC = dyn_cast<DeclContext>(D); 317 318 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 319 if (!TD->isFreeStanding()) 320 continue; 321 322 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range); 323 if (CompRes == RangeBefore) 324 continue; 325 if (CompRes == RangeAfter) 326 break; 327 328 assert(CompRes == RangeOverlap); 329 VisitedAtLeastOnce = true; 330 331 if (isa<ObjCContainerDecl>(D)) { 332 FileDI_current = &DIt; 333 FileDE_current = DE; 334 } else { 335 FileDI_current = 0; 336 } 337 338 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true)) 339 break; 340 } 341 342 if (VisitedAtLeastOnce) 343 return; 344 345 // No Decls overlapped with the range. Move up the lexical context until there 346 // is a context that contains the range or we reach the translation unit 347 // level. 348 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext() 349 : (*(DIt-1))->getLexicalDeclContext(); 350 351 while (DC && !DC->isTranslationUnit()) { 352 Decl *D = cast<Decl>(DC); 353 SourceRange CurDeclRange = D->getSourceRange(); 354 if (CurDeclRange.isInvalid()) 355 break; 356 357 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) { 358 Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true); 359 break; 360 } 361 362 DC = D->getLexicalDeclContext(); 363 } 364} 365 366bool CursorVisitor::visitPreprocessedEntitiesInRegion() { 367 if (!AU->getPreprocessor().getPreprocessingRecord()) 368 return false; 369 370 PreprocessingRecord &PPRec 371 = *AU->getPreprocessor().getPreprocessingRecord(); 372 SourceManager &SM = AU->getSourceManager(); 373 374 if (RegionOfInterest.isValid()) { 375 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest); 376 SourceLocation B = MappedRange.getBegin(); 377 SourceLocation E = MappedRange.getEnd(); 378 379 if (AU->isInPreambleFileID(B)) { 380 if (SM.isLoadedSourceLocation(E)) 381 return visitPreprocessedEntitiesInRange(SourceRange(B, E), 382 PPRec, *this); 383 384 // Beginning of range lies in the preamble but it also extends beyond 385 // it into the main file. Split the range into 2 parts, one covering 386 // the preamble and another covering the main file. This allows subsequent 387 // calls to visitPreprocessedEntitiesInRange to accept a source range that 388 // lies in the same FileID, allowing it to skip preprocessed entities that 389 // do not come from the same FileID. 390 bool breaked = 391 visitPreprocessedEntitiesInRange( 392 SourceRange(B, AU->getEndOfPreambleFileID()), 393 PPRec, *this); 394 if (breaked) return true; 395 return visitPreprocessedEntitiesInRange( 396 SourceRange(AU->getStartOfMainFileID(), E), 397 PPRec, *this); 398 } 399 400 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this); 401 } 402 403 bool OnlyLocalDecls 404 = !AU->isMainFileAST() && AU->getOnlyLocalDecls(); 405 406 if (OnlyLocalDecls) 407 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(), 408 PPRec); 409 410 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec); 411} 412 413template<typename InputIterator> 414bool CursorVisitor::visitPreprocessedEntities(InputIterator First, 415 InputIterator Last, 416 PreprocessingRecord &PPRec, 417 FileID FID) { 418 for (; First != Last; ++First) { 419 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID)) 420 continue; 421 422 PreprocessedEntity *PPE = *First; 423 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) { 424 if (Visit(MakeMacroExpansionCursor(ME, TU))) 425 return true; 426 427 continue; 428 } 429 430 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(PPE)) { 431 if (Visit(MakeMacroDefinitionCursor(MD, TU))) 432 return true; 433 434 continue; 435 } 436 437 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) { 438 if (Visit(MakeInclusionDirectiveCursor(ID, TU))) 439 return true; 440 441 continue; 442 } 443 } 444 445 return false; 446} 447 448/// \brief Visit the children of the given cursor. 449/// 450/// \returns true if the visitation should be aborted, false if it 451/// should continue. 452bool CursorVisitor::VisitChildren(CXCursor Cursor) { 453 if (clang_isReference(Cursor.kind) && 454 Cursor.kind != CXCursor_CXXBaseSpecifier) { 455 // By definition, references have no children. 456 return false; 457 } 458 459 // Set the Parent field to Cursor, then back to its old value once we're 460 // done. 461 SetParentRAII SetParent(Parent, StmtParent, Cursor); 462 463 if (clang_isDeclaration(Cursor.kind)) { 464 Decl *D = getCursorDecl(Cursor); 465 if (!D) 466 return false; 467 468 return VisitAttributes(D) || Visit(D); 469 } 470 471 if (clang_isStatement(Cursor.kind)) { 472 if (Stmt *S = getCursorStmt(Cursor)) 473 return Visit(S); 474 475 return false; 476 } 477 478 if (clang_isExpression(Cursor.kind)) { 479 if (Expr *E = getCursorExpr(Cursor)) 480 return Visit(E); 481 482 return false; 483 } 484 485 if (clang_isTranslationUnit(Cursor.kind)) { 486 CXTranslationUnit tu = getCursorTU(Cursor); 487 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData); 488 489 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast }; 490 for (unsigned I = 0; I != 2; ++I) { 491 if (VisitOrder[I]) { 492 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() && 493 RegionOfInterest.isInvalid()) { 494 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(), 495 TLEnd = CXXUnit->top_level_end(); 496 TL != TLEnd; ++TL) { 497 if (Visit(MakeCXCursor(*TL, tu, RegionOfInterest), true)) 498 return true; 499 } 500 } else if (VisitDeclContext( 501 CXXUnit->getASTContext().getTranslationUnitDecl())) 502 return true; 503 continue; 504 } 505 506 // Walk the preprocessing record. 507 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) 508 visitPreprocessedEntitiesInRegion(); 509 } 510 511 return false; 512 } 513 514 if (Cursor.kind == CXCursor_CXXBaseSpecifier) { 515 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) { 516 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) { 517 return Visit(BaseTSInfo->getTypeLoc()); 518 } 519 } 520 } 521 522 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) { 523 IBOutletCollectionAttr *A = 524 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor)); 525 if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>()) 526 return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(), 527 A->getInterfaceLoc(), TU)); 528 } 529 530 // If pointing inside a macro definition, check if the token is an identifier 531 // that was ever defined as a macro. In such a case, create a "pseudo" macro 532 // expansion cursor for that token. 533 SourceLocation BeginLoc = RegionOfInterest.getBegin(); 534 if (Cursor.kind == CXCursor_MacroDefinition && 535 BeginLoc == RegionOfInterest.getEnd()) { 536 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc); 537 const MacroInfo *MI = 538 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU); 539 if (MacroDefinition *MacroDef = 540 checkForMacroInMacroDefinition(MI, Loc, TU)) 541 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU)); 542 } 543 544 // Nothing to visit at the moment. 545 return false; 546} 547 548bool CursorVisitor::VisitBlockDecl(BlockDecl *B) { 549 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten()) 550 if (Visit(TSInfo->getTypeLoc())) 551 return true; 552 553 if (Stmt *Body = B->getBody()) 554 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest)); 555 556 return false; 557} 558 559llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) { 560 if (RegionOfInterest.isValid()) { 561 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager()); 562 if (Range.isInvalid()) 563 return llvm::Optional<bool>(); 564 565 switch (CompareRegionOfInterest(Range)) { 566 case RangeBefore: 567 // This declaration comes before the region of interest; skip it. 568 return llvm::Optional<bool>(); 569 570 case RangeAfter: 571 // This declaration comes after the region of interest; we're done. 572 return false; 573 574 case RangeOverlap: 575 // This declaration overlaps the region of interest; visit it. 576 break; 577 } 578 } 579 return true; 580} 581 582bool CursorVisitor::VisitDeclContext(DeclContext *DC) { 583 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end(); 584 585 // FIXME: Eventually remove. This part of a hack to support proper 586 // iteration over all Decls contained lexically within an ObjC container. 587 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I); 588 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E); 589 590 for ( ; I != E; ++I) { 591 Decl *D = *I; 592 if (D->getLexicalDeclContext() != DC) 593 continue; 594 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest); 595 596 // Ignore synthesized ivars here, otherwise if we have something like: 597 // @synthesize prop = _prop; 598 // and '_prop' is not declared, we will encounter a '_prop' ivar before 599 // encountering the 'prop' synthesize declaration and we will think that 600 // we passed the region-of-interest. 601 if (ObjCIvarDecl *ivarD = dyn_cast<ObjCIvarDecl>(D)) { 602 if (ivarD->getSynthesize()) 603 continue; 604 } 605 606 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol 607 // declarations is a mismatch with the compiler semantics. 608 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) { 609 ObjCInterfaceDecl *ID = cast<ObjCInterfaceDecl>(D); 610 if (!ID->isThisDeclarationADefinition()) 611 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU); 612 613 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) { 614 ObjCProtocolDecl *PD = cast<ObjCProtocolDecl>(D); 615 if (!PD->isThisDeclarationADefinition()) 616 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU); 617 } 618 619 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor); 620 if (!V.hasValue()) 621 continue; 622 if (!V.getValue()) 623 return false; 624 if (Visit(Cursor, true)) 625 return true; 626 } 627 return false; 628} 629 630bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) { 631 llvm_unreachable("Translation units are visited directly by Visit()"); 632} 633 634bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) { 635 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo()) 636 return Visit(TSInfo->getTypeLoc()); 637 638 return false; 639} 640 641bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) { 642 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo()) 643 return Visit(TSInfo->getTypeLoc()); 644 645 return false; 646} 647 648bool CursorVisitor::VisitTagDecl(TagDecl *D) { 649 return VisitDeclContext(D); 650} 651 652bool CursorVisitor::VisitClassTemplateSpecializationDecl( 653 ClassTemplateSpecializationDecl *D) { 654 bool ShouldVisitBody = false; 655 switch (D->getSpecializationKind()) { 656 case TSK_Undeclared: 657 case TSK_ImplicitInstantiation: 658 // Nothing to visit 659 return false; 660 661 case TSK_ExplicitInstantiationDeclaration: 662 case TSK_ExplicitInstantiationDefinition: 663 break; 664 665 case TSK_ExplicitSpecialization: 666 ShouldVisitBody = true; 667 break; 668 } 669 670 // Visit the template arguments used in the specialization. 671 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) { 672 TypeLoc TL = SpecType->getTypeLoc(); 673 if (TemplateSpecializationTypeLoc *TSTLoc 674 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) { 675 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I) 676 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I))) 677 return true; 678 } 679 } 680 681 if (ShouldVisitBody && VisitCXXRecordDecl(D)) 682 return true; 683 684 return false; 685} 686 687bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl( 688 ClassTemplatePartialSpecializationDecl *D) { 689 // FIXME: Visit the "outer" template parameter lists on the TagDecl 690 // before visiting these template parameters. 691 if (VisitTemplateParameters(D->getTemplateParameters())) 692 return true; 693 694 // Visit the partial specialization arguments. 695 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten(); 696 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I) 697 if (VisitTemplateArgumentLoc(TemplateArgs[I])) 698 return true; 699 700 return VisitCXXRecordDecl(D); 701} 702 703bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) { 704 // Visit the default argument. 705 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) 706 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo()) 707 if (Visit(DefArg->getTypeLoc())) 708 return true; 709 710 return false; 711} 712 713bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) { 714 if (Expr *Init = D->getInitExpr()) 715 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest)); 716 return false; 717} 718 719bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) { 720 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo()) 721 if (Visit(TSInfo->getTypeLoc())) 722 return true; 723 724 // Visit the nested-name-specifier, if present. 725 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc()) 726 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 727 return true; 728 729 return false; 730} 731 732/// \brief Compare two base or member initializers based on their source order. 733static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) { 734 CXXCtorInitializer const * const *X 735 = static_cast<CXXCtorInitializer const * const *>(Xp); 736 CXXCtorInitializer const * const *Y 737 = static_cast<CXXCtorInitializer const * const *>(Yp); 738 739 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder()) 740 return -1; 741 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder()) 742 return 1; 743 else 744 return 0; 745} 746 747bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) { 748 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) { 749 // Visit the function declaration's syntactic components in the order 750 // written. This requires a bit of work. 751 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens(); 752 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL); 753 754 // If we have a function declared directly (without the use of a typedef), 755 // visit just the return type. Otherwise, just visit the function's type 756 // now. 757 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) || 758 (!FTL && Visit(TL))) 759 return true; 760 761 // Visit the nested-name-specifier, if present. 762 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc()) 763 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 764 return true; 765 766 // Visit the declaration name. 767 if (VisitDeclarationNameInfo(ND->getNameInfo())) 768 return true; 769 770 // FIXME: Visit explicitly-specified template arguments! 771 772 // Visit the function parameters, if we have a function type. 773 if (FTL && VisitFunctionTypeLoc(*FTL, true)) 774 return true; 775 776 // FIXME: Attributes? 777 } 778 779 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) { 780 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) { 781 // Find the initializers that were written in the source. 782 SmallVector<CXXCtorInitializer *, 4> WrittenInits; 783 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(), 784 IEnd = Constructor->init_end(); 785 I != IEnd; ++I) { 786 if (!(*I)->isWritten()) 787 continue; 788 789 WrittenInits.push_back(*I); 790 } 791 792 // Sort the initializers in source order 793 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(), 794 &CompareCXXCtorInitializers); 795 796 // Visit the initializers in source order 797 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) { 798 CXXCtorInitializer *Init = WrittenInits[I]; 799 if (Init->isAnyMemberInitializer()) { 800 if (Visit(MakeCursorMemberRef(Init->getAnyMember(), 801 Init->getMemberLocation(), TU))) 802 return true; 803 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) { 804 if (Visit(TInfo->getTypeLoc())) 805 return true; 806 } 807 808 // Visit the initializer value. 809 if (Expr *Initializer = Init->getInit()) 810 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest))) 811 return true; 812 } 813 } 814 815 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest))) 816 return true; 817 } 818 819 return false; 820} 821 822bool CursorVisitor::VisitFieldDecl(FieldDecl *D) { 823 if (VisitDeclaratorDecl(D)) 824 return true; 825 826 if (Expr *BitWidth = D->getBitWidth()) 827 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest)); 828 829 return false; 830} 831 832bool CursorVisitor::VisitVarDecl(VarDecl *D) { 833 if (VisitDeclaratorDecl(D)) 834 return true; 835 836 if (Expr *Init = D->getInit()) 837 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest)); 838 839 return false; 840} 841 842bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) { 843 if (VisitDeclaratorDecl(D)) 844 return true; 845 846 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) 847 if (Expr *DefArg = D->getDefaultArgument()) 848 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest)); 849 850 return false; 851} 852 853bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { 854 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl 855 // before visiting these template parameters. 856 if (VisitTemplateParameters(D->getTemplateParameters())) 857 return true; 858 859 return VisitFunctionDecl(D->getTemplatedDecl()); 860} 861 862bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) { 863 // FIXME: Visit the "outer" template parameter lists on the TagDecl 864 // before visiting these template parameters. 865 if (VisitTemplateParameters(D->getTemplateParameters())) 866 return true; 867 868 return VisitCXXRecordDecl(D->getTemplatedDecl()); 869} 870 871bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) { 872 if (VisitTemplateParameters(D->getTemplateParameters())) 873 return true; 874 875 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() && 876 VisitTemplateArgumentLoc(D->getDefaultArgument())) 877 return true; 878 879 return false; 880} 881 882bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) { 883 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo()) 884 if (Visit(TSInfo->getTypeLoc())) 885 return true; 886 887 for (ObjCMethodDecl::param_iterator P = ND->param_begin(), 888 PEnd = ND->param_end(); 889 P != PEnd; ++P) { 890 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest))) 891 return true; 892 } 893 894 if (ND->isThisDeclarationADefinition() && 895 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest))) 896 return true; 897 898 return false; 899} 900 901template <typename DeclIt> 902static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current, 903 SourceManager &SM, SourceLocation EndLoc, 904 SmallVectorImpl<Decl *> &Decls) { 905 DeclIt next = *DI_current; 906 while (++next != DE_current) { 907 Decl *D_next = *next; 908 if (!D_next) 909 break; 910 SourceLocation L = D_next->getLocStart(); 911 if (!L.isValid()) 912 break; 913 if (SM.isBeforeInTranslationUnit(L, EndLoc)) { 914 *DI_current = next; 915 Decls.push_back(D_next); 916 continue; 917 } 918 break; 919 } 920} 921 922namespace { 923 struct ContainerDeclsSort { 924 SourceManager &SM; 925 ContainerDeclsSort(SourceManager &sm) : SM(sm) {} 926 bool operator()(Decl *A, Decl *B) { 927 SourceLocation L_A = A->getLocStart(); 928 SourceLocation L_B = B->getLocStart(); 929 assert(L_A.isValid() && L_B.isValid()); 930 return SM.isBeforeInTranslationUnit(L_A, L_B); 931 } 932 }; 933} 934 935bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) { 936 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially 937 // an @implementation can lexically contain Decls that are not properly 938 // nested in the AST. When we identify such cases, we need to retrofit 939 // this nesting here. 940 if (!DI_current && !FileDI_current) 941 return VisitDeclContext(D); 942 943 // Scan the Decls that immediately come after the container 944 // in the current DeclContext. If any fall within the 945 // container's lexical region, stash them into a vector 946 // for later processing. 947 SmallVector<Decl *, 24> DeclsInContainer; 948 SourceLocation EndLoc = D->getSourceRange().getEnd(); 949 SourceManager &SM = AU->getSourceManager(); 950 if (EndLoc.isValid()) { 951 if (DI_current) { 952 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc, 953 DeclsInContainer); 954 } else { 955 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc, 956 DeclsInContainer); 957 } 958 } 959 960 // The common case. 961 if (DeclsInContainer.empty()) 962 return VisitDeclContext(D); 963 964 // Get all the Decls in the DeclContext, and sort them with the 965 // additional ones we've collected. Then visit them. 966 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end(); 967 I!=E; ++I) { 968 Decl *subDecl = *I; 969 if (!subDecl || subDecl->getLexicalDeclContext() != D || 970 subDecl->getLocStart().isInvalid()) 971 continue; 972 DeclsInContainer.push_back(subDecl); 973 } 974 975 // Now sort the Decls so that they appear in lexical order. 976 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(), 977 ContainerDeclsSort(SM)); 978 979 // Now visit the decls. 980 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(), 981 E = DeclsInContainer.end(); I != E; ++I) { 982 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest); 983 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor); 984 if (!V.hasValue()) 985 continue; 986 if (!V.getValue()) 987 return false; 988 if (Visit(Cursor, true)) 989 return true; 990 } 991 return false; 992} 993 994bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) { 995 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(), 996 TU))) 997 return true; 998 999 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin(); 1000 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(), 1001 E = ND->protocol_end(); I != E; ++I, ++PL) 1002 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) 1003 return true; 1004 1005 return VisitObjCContainerDecl(ND); 1006} 1007 1008bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) { 1009 if (!PID->isThisDeclarationADefinition()) 1010 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU)); 1011 1012 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin(); 1013 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(), 1014 E = PID->protocol_end(); I != E; ++I, ++PL) 1015 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) 1016 return true; 1017 1018 return VisitObjCContainerDecl(PID); 1019} 1020 1021bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) { 1022 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc())) 1023 return true; 1024 1025 // FIXME: This implements a workaround with @property declarations also being 1026 // installed in the DeclContext for the @interface. Eventually this code 1027 // should be removed. 1028 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext()); 1029 if (!CDecl || !CDecl->IsClassExtension()) 1030 return false; 1031 1032 ObjCInterfaceDecl *ID = CDecl->getClassInterface(); 1033 if (!ID) 1034 return false; 1035 1036 IdentifierInfo *PropertyId = PD->getIdentifier(); 1037 ObjCPropertyDecl *prevDecl = 1038 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId); 1039 1040 if (!prevDecl) 1041 return false; 1042 1043 // Visit synthesized methods since they will be skipped when visiting 1044 // the @interface. 1045 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl()) 1046 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl) 1047 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest))) 1048 return true; 1049 1050 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl()) 1051 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl) 1052 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest))) 1053 return true; 1054 1055 return false; 1056} 1057 1058bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) { 1059 if (!D->isThisDeclarationADefinition()) { 1060 // Forward declaration is treated like a reference. 1061 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU)); 1062 } 1063 1064 // Issue callbacks for super class. 1065 if (D->getSuperClass() && 1066 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(), 1067 D->getSuperClassLoc(), 1068 TU))) 1069 return true; 1070 1071 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin(); 1072 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(), 1073 E = D->protocol_end(); I != E; ++I, ++PL) 1074 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) 1075 return true; 1076 1077 return VisitObjCContainerDecl(D); 1078} 1079 1080bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) { 1081 return VisitObjCContainerDecl(D); 1082} 1083 1084bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) { 1085 // 'ID' could be null when dealing with invalid code. 1086 if (ObjCInterfaceDecl *ID = D->getClassInterface()) 1087 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU))) 1088 return true; 1089 1090 return VisitObjCImplDecl(D); 1091} 1092 1093bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) { 1094#if 0 1095 // Issue callbacks for super class. 1096 // FIXME: No source location information! 1097 if (D->getSuperClass() && 1098 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(), 1099 D->getSuperClassLoc(), 1100 TU))) 1101 return true; 1102#endif 1103 1104 return VisitObjCImplDecl(D); 1105} 1106 1107bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) { 1108 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl()) 1109 if (PD->isIvarNameSpecified()) 1110 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU)); 1111 1112 return false; 1113} 1114 1115bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) { 1116 return VisitDeclContext(D); 1117} 1118 1119bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { 1120 // Visit nested-name-specifier. 1121 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) 1122 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1123 return true; 1124 1125 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(), 1126 D->getTargetNameLoc(), TU)); 1127} 1128 1129bool CursorVisitor::VisitUsingDecl(UsingDecl *D) { 1130 // Visit nested-name-specifier. 1131 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) { 1132 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1133 return true; 1134 } 1135 1136 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU))) 1137 return true; 1138 1139 return VisitDeclarationNameInfo(D->getNameInfo()); 1140} 1141 1142bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { 1143 // Visit nested-name-specifier. 1144 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) 1145 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1146 return true; 1147 1148 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(), 1149 D->getIdentLocation(), TU)); 1150} 1151 1152bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) { 1153 // Visit nested-name-specifier. 1154 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) { 1155 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1156 return true; 1157 } 1158 1159 return VisitDeclarationNameInfo(D->getNameInfo()); 1160} 1161 1162bool CursorVisitor::VisitUnresolvedUsingTypenameDecl( 1163 UnresolvedUsingTypenameDecl *D) { 1164 // Visit nested-name-specifier. 1165 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) 1166 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1167 return true; 1168 1169 return false; 1170} 1171 1172bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) { 1173 switch (Name.getName().getNameKind()) { 1174 case clang::DeclarationName::Identifier: 1175 case clang::DeclarationName::CXXLiteralOperatorName: 1176 case clang::DeclarationName::CXXOperatorName: 1177 case clang::DeclarationName::CXXUsingDirective: 1178 return false; 1179 1180 case clang::DeclarationName::CXXConstructorName: 1181 case clang::DeclarationName::CXXDestructorName: 1182 case clang::DeclarationName::CXXConversionFunctionName: 1183 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo()) 1184 return Visit(TSInfo->getTypeLoc()); 1185 return false; 1186 1187 case clang::DeclarationName::ObjCZeroArgSelector: 1188 case clang::DeclarationName::ObjCOneArgSelector: 1189 case clang::DeclarationName::ObjCMultiArgSelector: 1190 // FIXME: Per-identifier location info? 1191 return false; 1192 } 1193 1194 llvm_unreachable("Invalid DeclarationName::Kind!"); 1195} 1196 1197bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS, 1198 SourceRange Range) { 1199 // FIXME: This whole routine is a hack to work around the lack of proper 1200 // source information in nested-name-specifiers (PR5791). Since we do have 1201 // a beginning source location, we can visit the first component of the 1202 // nested-name-specifier, if it's a single-token component. 1203 if (!NNS) 1204 return false; 1205 1206 // Get the first component in the nested-name-specifier. 1207 while (NestedNameSpecifier *Prefix = NNS->getPrefix()) 1208 NNS = Prefix; 1209 1210 switch (NNS->getKind()) { 1211 case NestedNameSpecifier::Namespace: 1212 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(), 1213 TU)); 1214 1215 case NestedNameSpecifier::NamespaceAlias: 1216 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(), 1217 Range.getBegin(), TU)); 1218 1219 case NestedNameSpecifier::TypeSpec: { 1220 // If the type has a form where we know that the beginning of the source 1221 // range matches up with a reference cursor. Visit the appropriate reference 1222 // cursor. 1223 const Type *T = NNS->getAsType(); 1224 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T)) 1225 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU)); 1226 if (const TagType *Tag = dyn_cast<TagType>(T)) 1227 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU)); 1228 if (const TemplateSpecializationType *TST 1229 = dyn_cast<TemplateSpecializationType>(T)) 1230 return VisitTemplateName(TST->getTemplateName(), Range.getBegin()); 1231 break; 1232 } 1233 1234 case NestedNameSpecifier::TypeSpecWithTemplate: 1235 case NestedNameSpecifier::Global: 1236 case NestedNameSpecifier::Identifier: 1237 break; 1238 } 1239 1240 return false; 1241} 1242 1243bool 1244CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) { 1245 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers; 1246 for (; Qualifier; Qualifier = Qualifier.getPrefix()) 1247 Qualifiers.push_back(Qualifier); 1248 1249 while (!Qualifiers.empty()) { 1250 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val(); 1251 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier(); 1252 switch (NNS->getKind()) { 1253 case NestedNameSpecifier::Namespace: 1254 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), 1255 Q.getLocalBeginLoc(), 1256 TU))) 1257 return true; 1258 1259 break; 1260 1261 case NestedNameSpecifier::NamespaceAlias: 1262 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(), 1263 Q.getLocalBeginLoc(), 1264 TU))) 1265 return true; 1266 1267 break; 1268 1269 case NestedNameSpecifier::TypeSpec: 1270 case NestedNameSpecifier::TypeSpecWithTemplate: 1271 if (Visit(Q.getTypeLoc())) 1272 return true; 1273 1274 break; 1275 1276 case NestedNameSpecifier::Global: 1277 case NestedNameSpecifier::Identifier: 1278 break; 1279 } 1280 } 1281 1282 return false; 1283} 1284 1285bool CursorVisitor::VisitTemplateParameters( 1286 const TemplateParameterList *Params) { 1287 if (!Params) 1288 return false; 1289 1290 for (TemplateParameterList::const_iterator P = Params->begin(), 1291 PEnd = Params->end(); 1292 P != PEnd; ++P) { 1293 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest))) 1294 return true; 1295 } 1296 1297 return false; 1298} 1299 1300bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) { 1301 switch (Name.getKind()) { 1302 case TemplateName::Template: 1303 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU)); 1304 1305 case TemplateName::OverloadedTemplate: 1306 // Visit the overloaded template set. 1307 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU))) 1308 return true; 1309 1310 return false; 1311 1312 case TemplateName::DependentTemplate: 1313 // FIXME: Visit nested-name-specifier. 1314 return false; 1315 1316 case TemplateName::QualifiedTemplate: 1317 // FIXME: Visit nested-name-specifier. 1318 return Visit(MakeCursorTemplateRef( 1319 Name.getAsQualifiedTemplateName()->getDecl(), 1320 Loc, TU)); 1321 1322 case TemplateName::SubstTemplateTemplateParm: 1323 return Visit(MakeCursorTemplateRef( 1324 Name.getAsSubstTemplateTemplateParm()->getParameter(), 1325 Loc, TU)); 1326 1327 case TemplateName::SubstTemplateTemplateParmPack: 1328 return Visit(MakeCursorTemplateRef( 1329 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(), 1330 Loc, TU)); 1331 } 1332 1333 llvm_unreachable("Invalid TemplateName::Kind!"); 1334} 1335 1336bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) { 1337 switch (TAL.getArgument().getKind()) { 1338 case TemplateArgument::Null: 1339 case TemplateArgument::Integral: 1340 case TemplateArgument::Pack: 1341 return false; 1342 1343 case TemplateArgument::Type: 1344 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo()) 1345 return Visit(TSInfo->getTypeLoc()); 1346 return false; 1347 1348 case TemplateArgument::Declaration: 1349 if (Expr *E = TAL.getSourceDeclExpression()) 1350 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest)); 1351 return false; 1352 1353 case TemplateArgument::NullPtr: 1354 if (Expr *E = TAL.getSourceNullPtrExpression()) 1355 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest)); 1356 return false; 1357 1358 case TemplateArgument::Expression: 1359 if (Expr *E = TAL.getSourceExpression()) 1360 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest)); 1361 return false; 1362 1363 case TemplateArgument::Template: 1364 case TemplateArgument::TemplateExpansion: 1365 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc())) 1366 return true; 1367 1368 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(), 1369 TAL.getTemplateNameLoc()); 1370 } 1371 1372 llvm_unreachable("Invalid TemplateArgument::Kind!"); 1373} 1374 1375bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) { 1376 return VisitDeclContext(D); 1377} 1378 1379bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 1380 return Visit(TL.getUnqualifiedLoc()); 1381} 1382 1383bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 1384 ASTContext &Context = AU->getASTContext(); 1385 1386 // Some builtin types (such as Objective-C's "id", "sel", and 1387 // "Class") have associated declarations. Create cursors for those. 1388 QualType VisitType; 1389 switch (TL.getTypePtr()->getKind()) { 1390 1391 case BuiltinType::Void: 1392 case BuiltinType::NullPtr: 1393 case BuiltinType::Dependent: 1394 case BuiltinType::OCLImage1d: 1395 case BuiltinType::OCLImage1dArray: 1396 case BuiltinType::OCLImage1dBuffer: 1397 case BuiltinType::OCLImage2d: 1398 case BuiltinType::OCLImage2dArray: 1399 case BuiltinType::OCLImage3d: 1400#define BUILTIN_TYPE(Id, SingletonId) 1401#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id: 1402#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id: 1403#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id: 1404#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id: 1405#include "clang/AST/BuiltinTypes.def" 1406 break; 1407 1408 case BuiltinType::ObjCId: 1409 VisitType = Context.getObjCIdType(); 1410 break; 1411 1412 case BuiltinType::ObjCClass: 1413 VisitType = Context.getObjCClassType(); 1414 break; 1415 1416 case BuiltinType::ObjCSel: 1417 VisitType = Context.getObjCSelType(); 1418 break; 1419 } 1420 1421 if (!VisitType.isNull()) { 1422 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>()) 1423 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(), 1424 TU)); 1425 } 1426 1427 return false; 1428} 1429 1430bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) { 1431 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU)); 1432} 1433 1434bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) { 1435 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); 1436} 1437 1438bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) { 1439 if (TL.isDefinition()) 1440 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest)); 1441 1442 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); 1443} 1444 1445bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) { 1446 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); 1447} 1448 1449bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 1450 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU))) 1451 return true; 1452 1453 return false; 1454} 1455 1456bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 1457 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc())) 1458 return true; 1459 1460 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) { 1461 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I), 1462 TU))) 1463 return true; 1464 } 1465 1466 return false; 1467} 1468 1469bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 1470 return Visit(TL.getPointeeLoc()); 1471} 1472 1473bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) { 1474 return Visit(TL.getInnerLoc()); 1475} 1476 1477bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) { 1478 return Visit(TL.getPointeeLoc()); 1479} 1480 1481bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 1482 return Visit(TL.getPointeeLoc()); 1483} 1484 1485bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 1486 return Visit(TL.getPointeeLoc()); 1487} 1488 1489bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 1490 return Visit(TL.getPointeeLoc()); 1491} 1492 1493bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 1494 return Visit(TL.getPointeeLoc()); 1495} 1496 1497bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) { 1498 return Visit(TL.getModifiedLoc()); 1499} 1500 1501bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL, 1502 bool SkipResultType) { 1503 if (!SkipResultType && Visit(TL.getResultLoc())) 1504 return true; 1505 1506 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I) 1507 if (Decl *D = TL.getArg(I)) 1508 if (Visit(MakeCXCursor(D, TU, RegionOfInterest))) 1509 return true; 1510 1511 return false; 1512} 1513 1514bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) { 1515 if (Visit(TL.getElementLoc())) 1516 return true; 1517 1518 if (Expr *Size = TL.getSizeExpr()) 1519 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest)); 1520 1521 return false; 1522} 1523 1524bool CursorVisitor::VisitTemplateSpecializationTypeLoc( 1525 TemplateSpecializationTypeLoc TL) { 1526 // Visit the template name. 1527 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(), 1528 TL.getTemplateNameLoc())) 1529 return true; 1530 1531 // Visit the template arguments. 1532 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I) 1533 if (VisitTemplateArgumentLoc(TL.getArgLoc(I))) 1534 return true; 1535 1536 return false; 1537} 1538 1539bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 1540 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU)); 1541} 1542 1543bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 1544 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo()) 1545 return Visit(TSInfo->getTypeLoc()); 1546 1547 return false; 1548} 1549 1550bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { 1551 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo()) 1552 return Visit(TSInfo->getTypeLoc()); 1553 1554 return false; 1555} 1556 1557bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 1558 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc())) 1559 return true; 1560 1561 return false; 1562} 1563 1564bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc( 1565 DependentTemplateSpecializationTypeLoc TL) { 1566 // Visit the nested-name-specifier, if there is one. 1567 if (TL.getQualifierLoc() && 1568 VisitNestedNameSpecifierLoc(TL.getQualifierLoc())) 1569 return true; 1570 1571 // Visit the template arguments. 1572 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I) 1573 if (VisitTemplateArgumentLoc(TL.getArgLoc(I))) 1574 return true; 1575 1576 return false; 1577} 1578 1579bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 1580 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc())) 1581 return true; 1582 1583 return Visit(TL.getNamedTypeLoc()); 1584} 1585 1586bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) { 1587 return Visit(TL.getPatternLoc()); 1588} 1589 1590bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) { 1591 if (Expr *E = TL.getUnderlyingExpr()) 1592 return Visit(MakeCXCursor(E, StmtParent, TU)); 1593 1594 return false; 1595} 1596 1597bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) { 1598 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); 1599} 1600 1601bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) { 1602 return Visit(TL.getValueLoc()); 1603} 1604 1605#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \ 1606bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \ 1607 return Visit##PARENT##Loc(TL); \ 1608} 1609 1610DEFAULT_TYPELOC_IMPL(Complex, Type) 1611DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType) 1612DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType) 1613DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType) 1614DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType) 1615DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type) 1616DEFAULT_TYPELOC_IMPL(Vector, Type) 1617DEFAULT_TYPELOC_IMPL(ExtVector, VectorType) 1618DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType) 1619DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType) 1620DEFAULT_TYPELOC_IMPL(Record, TagType) 1621DEFAULT_TYPELOC_IMPL(Enum, TagType) 1622DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type) 1623DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type) 1624DEFAULT_TYPELOC_IMPL(Auto, Type) 1625 1626bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) { 1627 // Visit the nested-name-specifier, if present. 1628 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) 1629 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1630 return true; 1631 1632 if (D->isCompleteDefinition()) { 1633 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(), 1634 E = D->bases_end(); I != E; ++I) { 1635 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU))) 1636 return true; 1637 } 1638 } 1639 1640 return VisitTagDecl(D); 1641} 1642 1643bool CursorVisitor::VisitAttributes(Decl *D) { 1644 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end(); 1645 i != e; ++i) 1646 if (Visit(MakeCXCursor(*i, D, TU))) 1647 return true; 1648 1649 return false; 1650} 1651 1652//===----------------------------------------------------------------------===// 1653// Data-recursive visitor methods. 1654//===----------------------------------------------------------------------===// 1655 1656namespace { 1657#define DEF_JOB(NAME, DATA, KIND)\ 1658class NAME : public VisitorJob {\ 1659public:\ 1660 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \ 1661 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\ 1662 DATA *get() const { return static_cast<DATA*>(data[0]); }\ 1663}; 1664 1665DEF_JOB(StmtVisit, Stmt, StmtVisitKind) 1666DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind) 1667DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind) 1668DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind) 1669DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo, 1670 ExplicitTemplateArgsVisitKind) 1671DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind) 1672DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind) 1673DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind) 1674#undef DEF_JOB 1675 1676class DeclVisit : public VisitorJob { 1677public: 1678 DeclVisit(Decl *d, CXCursor parent, bool isFirst) : 1679 VisitorJob(parent, VisitorJob::DeclVisitKind, 1680 d, isFirst ? (void*) 1 : (void*) 0) {} 1681 static bool classof(const VisitorJob *VJ) { 1682 return VJ->getKind() == DeclVisitKind; 1683 } 1684 Decl *get() const { return static_cast<Decl*>(data[0]); } 1685 bool isFirst() const { return data[1] ? true : false; } 1686}; 1687class TypeLocVisit : public VisitorJob { 1688public: 1689 TypeLocVisit(TypeLoc tl, CXCursor parent) : 1690 VisitorJob(parent, VisitorJob::TypeLocVisitKind, 1691 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {} 1692 1693 static bool classof(const VisitorJob *VJ) { 1694 return VJ->getKind() == TypeLocVisitKind; 1695 } 1696 1697 TypeLoc get() const { 1698 QualType T = QualType::getFromOpaquePtr(data[0]); 1699 return TypeLoc(T, data[1]); 1700 } 1701}; 1702 1703class LabelRefVisit : public VisitorJob { 1704public: 1705 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent) 1706 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD, 1707 labelLoc.getPtrEncoding()) {} 1708 1709 static bool classof(const VisitorJob *VJ) { 1710 return VJ->getKind() == VisitorJob::LabelRefVisitKind; 1711 } 1712 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); } 1713 SourceLocation getLoc() const { 1714 return SourceLocation::getFromPtrEncoding(data[1]); } 1715}; 1716 1717class NestedNameSpecifierLocVisit : public VisitorJob { 1718public: 1719 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent) 1720 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind, 1721 Qualifier.getNestedNameSpecifier(), 1722 Qualifier.getOpaqueData()) { } 1723 1724 static bool classof(const VisitorJob *VJ) { 1725 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind; 1726 } 1727 1728 NestedNameSpecifierLoc get() const { 1729 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]), 1730 data[1]); 1731 } 1732}; 1733 1734class DeclarationNameInfoVisit : public VisitorJob { 1735public: 1736 DeclarationNameInfoVisit(Stmt *S, CXCursor parent) 1737 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {} 1738 static bool classof(const VisitorJob *VJ) { 1739 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind; 1740 } 1741 DeclarationNameInfo get() const { 1742 Stmt *S = static_cast<Stmt*>(data[0]); 1743 switch (S->getStmtClass()) { 1744 default: 1745 llvm_unreachable("Unhandled Stmt"); 1746 case clang::Stmt::MSDependentExistsStmtClass: 1747 return cast<MSDependentExistsStmt>(S)->getNameInfo(); 1748 case Stmt::CXXDependentScopeMemberExprClass: 1749 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo(); 1750 case Stmt::DependentScopeDeclRefExprClass: 1751 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo(); 1752 } 1753 } 1754}; 1755class MemberRefVisit : public VisitorJob { 1756public: 1757 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent) 1758 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D, 1759 L.getPtrEncoding()) {} 1760 static bool classof(const VisitorJob *VJ) { 1761 return VJ->getKind() == VisitorJob::MemberRefVisitKind; 1762 } 1763 FieldDecl *get() const { 1764 return static_cast<FieldDecl*>(data[0]); 1765 } 1766 SourceLocation getLoc() const { 1767 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]); 1768 } 1769}; 1770class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> { 1771 VisitorWorkList &WL; 1772 CXCursor Parent; 1773public: 1774 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent) 1775 : WL(wl), Parent(parent) {} 1776 1777 void VisitAddrLabelExpr(AddrLabelExpr *E); 1778 void VisitBlockExpr(BlockExpr *B); 1779 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E); 1780 void VisitCompoundStmt(CompoundStmt *S); 1781 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ } 1782 void VisitMSDependentExistsStmt(MSDependentExistsStmt *S); 1783 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E); 1784 void VisitCXXNewExpr(CXXNewExpr *E); 1785 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E); 1786 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E); 1787 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E); 1788 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E); 1789 void VisitCXXTypeidExpr(CXXTypeidExpr *E); 1790 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E); 1791 void VisitCXXUuidofExpr(CXXUuidofExpr *E); 1792 void VisitCXXCatchStmt(CXXCatchStmt *S); 1793 void VisitDeclRefExpr(DeclRefExpr *D); 1794 void VisitDeclStmt(DeclStmt *S); 1795 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E); 1796 void VisitDesignatedInitExpr(DesignatedInitExpr *E); 1797 void VisitExplicitCastExpr(ExplicitCastExpr *E); 1798 void VisitForStmt(ForStmt *FS); 1799 void VisitGotoStmt(GotoStmt *GS); 1800 void VisitIfStmt(IfStmt *If); 1801 void VisitInitListExpr(InitListExpr *IE); 1802 void VisitMemberExpr(MemberExpr *M); 1803 void VisitOffsetOfExpr(OffsetOfExpr *E); 1804 void VisitObjCEncodeExpr(ObjCEncodeExpr *E); 1805 void VisitObjCMessageExpr(ObjCMessageExpr *M); 1806 void VisitOverloadExpr(OverloadExpr *E); 1807 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E); 1808 void VisitStmt(Stmt *S); 1809 void VisitSwitchStmt(SwitchStmt *S); 1810 void VisitWhileStmt(WhileStmt *W); 1811 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E); 1812 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E); 1813 void VisitTypeTraitExpr(TypeTraitExpr *E); 1814 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E); 1815 void VisitExpressionTraitExpr(ExpressionTraitExpr *E); 1816 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U); 1817 void VisitVAArgExpr(VAArgExpr *E); 1818 void VisitSizeOfPackExpr(SizeOfPackExpr *E); 1819 void VisitPseudoObjectExpr(PseudoObjectExpr *E); 1820 void VisitOpaqueValueExpr(OpaqueValueExpr *E); 1821 void VisitLambdaExpr(LambdaExpr *E); 1822 1823private: 1824 void AddDeclarationNameInfo(Stmt *S); 1825 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier); 1826 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A); 1827 void AddMemberRef(FieldDecl *D, SourceLocation L); 1828 void AddStmt(Stmt *S); 1829 void AddDecl(Decl *D, bool isFirst = true); 1830 void AddTypeLoc(TypeSourceInfo *TI); 1831 void EnqueueChildren(Stmt *S); 1832}; 1833} // end anonyous namespace 1834 1835void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) { 1836 // 'S' should always be non-null, since it comes from the 1837 // statement we are visiting. 1838 WL.push_back(DeclarationNameInfoVisit(S, Parent)); 1839} 1840 1841void 1842EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) { 1843 if (Qualifier) 1844 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent)); 1845} 1846 1847void EnqueueVisitor::AddStmt(Stmt *S) { 1848 if (S) 1849 WL.push_back(StmtVisit(S, Parent)); 1850} 1851void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) { 1852 if (D) 1853 WL.push_back(DeclVisit(D, Parent, isFirst)); 1854} 1855void EnqueueVisitor:: 1856 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) { 1857 if (A) 1858 WL.push_back(ExplicitTemplateArgsVisit( 1859 const_cast<ASTTemplateArgumentListInfo*>(A), Parent)); 1860} 1861void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) { 1862 if (D) 1863 WL.push_back(MemberRefVisit(D, L, Parent)); 1864} 1865void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) { 1866 if (TI) 1867 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent)); 1868 } 1869void EnqueueVisitor::EnqueueChildren(Stmt *S) { 1870 unsigned size = WL.size(); 1871 for (Stmt::child_range Child = S->children(); Child; ++Child) { 1872 AddStmt(*Child); 1873 } 1874 if (size == WL.size()) 1875 return; 1876 // Now reverse the entries we just added. This will match the DFS 1877 // ordering performed by the worklist. 1878 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end(); 1879 std::reverse(I, E); 1880} 1881void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) { 1882 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent)); 1883} 1884void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) { 1885 AddDecl(B->getBlockDecl()); 1886} 1887void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 1888 EnqueueChildren(E); 1889 AddTypeLoc(E->getTypeSourceInfo()); 1890} 1891void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) { 1892 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(), 1893 E = S->body_rend(); I != E; ++I) { 1894 AddStmt(*I); 1895 } 1896} 1897void EnqueueVisitor:: 1898VisitMSDependentExistsStmt(MSDependentExistsStmt *S) { 1899 AddStmt(S->getSubStmt()); 1900 AddDeclarationNameInfo(S); 1901 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc()) 1902 AddNestedNameSpecifierLoc(QualifierLoc); 1903} 1904 1905void EnqueueVisitor:: 1906VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) { 1907 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs()); 1908 AddDeclarationNameInfo(E); 1909 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc()) 1910 AddNestedNameSpecifierLoc(QualifierLoc); 1911 if (!E->isImplicitAccess()) 1912 AddStmt(E->getBase()); 1913} 1914void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) { 1915 // Enqueue the initializer , if any. 1916 AddStmt(E->getInitializer()); 1917 // Enqueue the array size, if any. 1918 AddStmt(E->getArraySize()); 1919 // Enqueue the allocated type. 1920 AddTypeLoc(E->getAllocatedTypeSourceInfo()); 1921 // Enqueue the placement arguments. 1922 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I) 1923 AddStmt(E->getPlacementArg(I-1)); 1924} 1925void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) { 1926 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I) 1927 AddStmt(CE->getArg(I-1)); 1928 AddStmt(CE->getCallee()); 1929 AddStmt(CE->getArg(0)); 1930} 1931void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) { 1932 // Visit the name of the type being destroyed. 1933 AddTypeLoc(E->getDestroyedTypeInfo()); 1934 // Visit the scope type that looks disturbingly like the nested-name-specifier 1935 // but isn't. 1936 AddTypeLoc(E->getScopeTypeInfo()); 1937 // Visit the nested-name-specifier. 1938 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc()) 1939 AddNestedNameSpecifierLoc(QualifierLoc); 1940 // Visit base expression. 1941 AddStmt(E->getBase()); 1942} 1943void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) { 1944 AddTypeLoc(E->getTypeSourceInfo()); 1945} 1946void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) { 1947 EnqueueChildren(E); 1948 AddTypeLoc(E->getTypeSourceInfo()); 1949} 1950void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) { 1951 EnqueueChildren(E); 1952 if (E->isTypeOperand()) 1953 AddTypeLoc(E->getTypeOperandSourceInfo()); 1954} 1955 1956void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr 1957 *E) { 1958 EnqueueChildren(E); 1959 AddTypeLoc(E->getTypeSourceInfo()); 1960} 1961void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) { 1962 EnqueueChildren(E); 1963 if (E->isTypeOperand()) 1964 AddTypeLoc(E->getTypeOperandSourceInfo()); 1965} 1966 1967void EnqueueVisitor::VisitCXXCatchStmt(CXXCatchStmt *S) { 1968 EnqueueChildren(S); 1969 AddDecl(S->getExceptionDecl()); 1970} 1971 1972void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) { 1973 if (DR->hasExplicitTemplateArgs()) { 1974 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs()); 1975 } 1976 WL.push_back(DeclRefExprParts(DR, Parent)); 1977} 1978void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) { 1979 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs()); 1980 AddDeclarationNameInfo(E); 1981 AddNestedNameSpecifierLoc(E->getQualifierLoc()); 1982} 1983void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) { 1984 unsigned size = WL.size(); 1985 bool isFirst = true; 1986 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end(); 1987 D != DEnd; ++D) { 1988 AddDecl(*D, isFirst); 1989 isFirst = false; 1990 } 1991 if (size == WL.size()) 1992 return; 1993 // Now reverse the entries we just added. This will match the DFS 1994 // ordering performed by the worklist. 1995 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end(); 1996 std::reverse(I, E); 1997} 1998void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) { 1999 AddStmt(E->getInit()); 2000 typedef DesignatedInitExpr::Designator Designator; 2001 for (DesignatedInitExpr::reverse_designators_iterator 2002 D = E->designators_rbegin(), DEnd = E->designators_rend(); 2003 D != DEnd; ++D) { 2004 if (D->isFieldDesignator()) { 2005 if (FieldDecl *Field = D->getField()) 2006 AddMemberRef(Field, D->getFieldLoc()); 2007 continue; 2008 } 2009 if (D->isArrayDesignator()) { 2010 AddStmt(E->getArrayIndex(*D)); 2011 continue; 2012 } 2013 assert(D->isArrayRangeDesignator() && "Unknown designator kind"); 2014 AddStmt(E->getArrayRangeEnd(*D)); 2015 AddStmt(E->getArrayRangeStart(*D)); 2016 } 2017} 2018void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) { 2019 EnqueueChildren(E); 2020 AddTypeLoc(E->getTypeInfoAsWritten()); 2021} 2022void EnqueueVisitor::VisitForStmt(ForStmt *FS) { 2023 AddStmt(FS->getBody()); 2024 AddStmt(FS->getInc()); 2025 AddStmt(FS->getCond()); 2026 AddDecl(FS->getConditionVariable()); 2027 AddStmt(FS->getInit()); 2028} 2029void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) { 2030 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent)); 2031} 2032void EnqueueVisitor::VisitIfStmt(IfStmt *If) { 2033 AddStmt(If->getElse()); 2034 AddStmt(If->getThen()); 2035 AddStmt(If->getCond()); 2036 AddDecl(If->getConditionVariable()); 2037} 2038void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) { 2039 // We care about the syntactic form of the initializer list, only. 2040 if (InitListExpr *Syntactic = IE->getSyntacticForm()) 2041 IE = Syntactic; 2042 EnqueueChildren(IE); 2043} 2044void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) { 2045 WL.push_back(MemberExprParts(M, Parent)); 2046 2047 // If the base of the member access expression is an implicit 'this', don't 2048 // visit it. 2049 // FIXME: If we ever want to show these implicit accesses, this will be 2050 // unfortunate. However, clang_getCursor() relies on this behavior. 2051 if (!M->isImplicitAccess()) 2052 AddStmt(M->getBase()); 2053} 2054void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) { 2055 AddTypeLoc(E->getEncodedTypeSourceInfo()); 2056} 2057void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) { 2058 EnqueueChildren(M); 2059 AddTypeLoc(M->getClassReceiverTypeInfo()); 2060} 2061void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) { 2062 // Visit the components of the offsetof expression. 2063 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) { 2064 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 2065 const OffsetOfNode &Node = E->getComponent(I-1); 2066 switch (Node.getKind()) { 2067 case OffsetOfNode::Array: 2068 AddStmt(E->getIndexExpr(Node.getArrayExprIndex())); 2069 break; 2070 case OffsetOfNode::Field: 2071 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd()); 2072 break; 2073 case OffsetOfNode::Identifier: 2074 case OffsetOfNode::Base: 2075 continue; 2076 } 2077 } 2078 // Visit the type into which we're computing the offset. 2079 AddTypeLoc(E->getTypeSourceInfo()); 2080} 2081void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) { 2082 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs()); 2083 WL.push_back(OverloadExprParts(E, Parent)); 2084} 2085void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr( 2086 UnaryExprOrTypeTraitExpr *E) { 2087 EnqueueChildren(E); 2088 if (E->isArgumentType()) 2089 AddTypeLoc(E->getArgumentTypeInfo()); 2090} 2091void EnqueueVisitor::VisitStmt(Stmt *S) { 2092 EnqueueChildren(S); 2093} 2094void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) { 2095 AddStmt(S->getBody()); 2096 AddStmt(S->getCond()); 2097 AddDecl(S->getConditionVariable()); 2098} 2099 2100void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) { 2101 AddStmt(W->getBody()); 2102 AddStmt(W->getCond()); 2103 AddDecl(W->getConditionVariable()); 2104} 2105 2106void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) { 2107 AddTypeLoc(E->getQueriedTypeSourceInfo()); 2108} 2109 2110void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) { 2111 AddTypeLoc(E->getRhsTypeSourceInfo()); 2112 AddTypeLoc(E->getLhsTypeSourceInfo()); 2113} 2114 2115void EnqueueVisitor::VisitTypeTraitExpr(TypeTraitExpr *E) { 2116 for (unsigned I = E->getNumArgs(); I > 0; --I) 2117 AddTypeLoc(E->getArg(I-1)); 2118} 2119 2120void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) { 2121 AddTypeLoc(E->getQueriedTypeSourceInfo()); 2122} 2123 2124void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) { 2125 EnqueueChildren(E); 2126} 2127 2128void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) { 2129 VisitOverloadExpr(U); 2130 if (!U->isImplicitAccess()) 2131 AddStmt(U->getBase()); 2132} 2133void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) { 2134 AddStmt(E->getSubExpr()); 2135 AddTypeLoc(E->getWrittenTypeInfo()); 2136} 2137void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) { 2138 WL.push_back(SizeOfPackExprParts(E, Parent)); 2139} 2140void EnqueueVisitor::VisitOpaqueValueExpr(OpaqueValueExpr *E) { 2141 // If the opaque value has a source expression, just transparently 2142 // visit that. This is useful for (e.g.) pseudo-object expressions. 2143 if (Expr *SourceExpr = E->getSourceExpr()) 2144 return Visit(SourceExpr); 2145} 2146void EnqueueVisitor::VisitLambdaExpr(LambdaExpr *E) { 2147 AddStmt(E->getBody()); 2148 WL.push_back(LambdaExprParts(E, Parent)); 2149} 2150void EnqueueVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *E) { 2151 // Treat the expression like its syntactic form. 2152 Visit(E->getSyntacticForm()); 2153} 2154 2155void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) { 2156 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S); 2157} 2158 2159bool CursorVisitor::IsInRegionOfInterest(CXCursor C) { 2160 if (RegionOfInterest.isValid()) { 2161 SourceRange Range = getRawCursorExtent(C); 2162 if (Range.isInvalid() || CompareRegionOfInterest(Range)) 2163 return false; 2164 } 2165 return true; 2166} 2167 2168bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) { 2169 while (!WL.empty()) { 2170 // Dequeue the worklist item. 2171 VisitorJob LI = WL.back(); 2172 WL.pop_back(); 2173 2174 // Set the Parent field, then back to its old value once we're done. 2175 SetParentRAII SetParent(Parent, StmtParent, LI.getParent()); 2176 2177 switch (LI.getKind()) { 2178 case VisitorJob::DeclVisitKind: { 2179 Decl *D = cast<DeclVisit>(&LI)->get(); 2180 if (!D) 2181 continue; 2182 2183 // For now, perform default visitation for Decls. 2184 if (Visit(MakeCXCursor(D, TU, RegionOfInterest, 2185 cast<DeclVisit>(&LI)->isFirst()))) 2186 return true; 2187 2188 continue; 2189 } 2190 case VisitorJob::ExplicitTemplateArgsVisitKind: { 2191 const ASTTemplateArgumentListInfo *ArgList = 2192 cast<ExplicitTemplateArgsVisit>(&LI)->get(); 2193 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(), 2194 *ArgEnd = Arg + ArgList->NumTemplateArgs; 2195 Arg != ArgEnd; ++Arg) { 2196 if (VisitTemplateArgumentLoc(*Arg)) 2197 return true; 2198 } 2199 continue; 2200 } 2201 case VisitorJob::TypeLocVisitKind: { 2202 // Perform default visitation for TypeLocs. 2203 if (Visit(cast<TypeLocVisit>(&LI)->get())) 2204 return true; 2205 continue; 2206 } 2207 case VisitorJob::LabelRefVisitKind: { 2208 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get(); 2209 if (LabelStmt *stmt = LS->getStmt()) { 2210 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(), 2211 TU))) { 2212 return true; 2213 } 2214 } 2215 continue; 2216 } 2217 2218 case VisitorJob::NestedNameSpecifierLocVisitKind: { 2219 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI); 2220 if (VisitNestedNameSpecifierLoc(V->get())) 2221 return true; 2222 continue; 2223 } 2224 2225 case VisitorJob::DeclarationNameInfoVisitKind: { 2226 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI) 2227 ->get())) 2228 return true; 2229 continue; 2230 } 2231 case VisitorJob::MemberRefVisitKind: { 2232 MemberRefVisit *V = cast<MemberRefVisit>(&LI); 2233 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU))) 2234 return true; 2235 continue; 2236 } 2237 case VisitorJob::StmtVisitKind: { 2238 Stmt *S = cast<StmtVisit>(&LI)->get(); 2239 if (!S) 2240 continue; 2241 2242 // Update the current cursor. 2243 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest); 2244 if (!IsInRegionOfInterest(Cursor)) 2245 continue; 2246 switch (Visitor(Cursor, Parent, ClientData)) { 2247 case CXChildVisit_Break: return true; 2248 case CXChildVisit_Continue: break; 2249 case CXChildVisit_Recurse: 2250 if (PostChildrenVisitor) 2251 WL.push_back(PostChildrenVisit(0, Cursor)); 2252 EnqueueWorkList(WL, S); 2253 break; 2254 } 2255 continue; 2256 } 2257 case VisitorJob::MemberExprPartsKind: { 2258 // Handle the other pieces in the MemberExpr besides the base. 2259 MemberExpr *M = cast<MemberExprParts>(&LI)->get(); 2260 2261 // Visit the nested-name-specifier 2262 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc()) 2263 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 2264 return true; 2265 2266 // Visit the declaration name. 2267 if (VisitDeclarationNameInfo(M->getMemberNameInfo())) 2268 return true; 2269 2270 // Visit the explicitly-specified template arguments, if any. 2271 if (M->hasExplicitTemplateArgs()) { 2272 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(), 2273 *ArgEnd = Arg + M->getNumTemplateArgs(); 2274 Arg != ArgEnd; ++Arg) { 2275 if (VisitTemplateArgumentLoc(*Arg)) 2276 return true; 2277 } 2278 } 2279 continue; 2280 } 2281 case VisitorJob::DeclRefExprPartsKind: { 2282 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get(); 2283 // Visit nested-name-specifier, if present. 2284 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc()) 2285 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 2286 return true; 2287 // Visit declaration name. 2288 if (VisitDeclarationNameInfo(DR->getNameInfo())) 2289 return true; 2290 continue; 2291 } 2292 case VisitorJob::OverloadExprPartsKind: { 2293 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get(); 2294 // Visit the nested-name-specifier. 2295 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc()) 2296 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 2297 return true; 2298 // Visit the declaration name. 2299 if (VisitDeclarationNameInfo(O->getNameInfo())) 2300 return true; 2301 // Visit the overloaded declaration reference. 2302 if (Visit(MakeCursorOverloadedDeclRef(O, TU))) 2303 return true; 2304 continue; 2305 } 2306 case VisitorJob::SizeOfPackExprPartsKind: { 2307 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get(); 2308 NamedDecl *Pack = E->getPack(); 2309 if (isa<TemplateTypeParmDecl>(Pack)) { 2310 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack), 2311 E->getPackLoc(), TU))) 2312 return true; 2313 2314 continue; 2315 } 2316 2317 if (isa<TemplateTemplateParmDecl>(Pack)) { 2318 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack), 2319 E->getPackLoc(), TU))) 2320 return true; 2321 2322 continue; 2323 } 2324 2325 // Non-type template parameter packs and function parameter packs are 2326 // treated like DeclRefExpr cursors. 2327 continue; 2328 } 2329 2330 case VisitorJob::LambdaExprPartsKind: { 2331 // Visit captures. 2332 LambdaExpr *E = cast<LambdaExprParts>(&LI)->get(); 2333 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(), 2334 CEnd = E->explicit_capture_end(); 2335 C != CEnd; ++C) { 2336 if (C->capturesThis()) 2337 continue; 2338 2339 if (Visit(MakeCursorVariableRef(C->getCapturedVar(), 2340 C->getLocation(), 2341 TU))) 2342 return true; 2343 } 2344 2345 // Visit parameters and return type, if present. 2346 if (E->hasExplicitParameters() || E->hasExplicitResultType()) { 2347 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc(); 2348 if (E->hasExplicitParameters() && E->hasExplicitResultType()) { 2349 // Visit the whole type. 2350 if (Visit(TL)) 2351 return true; 2352 } else if (isa<FunctionProtoTypeLoc>(TL)) { 2353 FunctionProtoTypeLoc Proto = cast<FunctionProtoTypeLoc>(TL); 2354 if (E->hasExplicitParameters()) { 2355 // Visit parameters. 2356 for (unsigned I = 0, N = Proto.getNumArgs(); I != N; ++I) 2357 if (Visit(MakeCXCursor(Proto.getArg(I), TU))) 2358 return true; 2359 } else { 2360 // Visit result type. 2361 if (Visit(Proto.getResultLoc())) 2362 return true; 2363 } 2364 } 2365 } 2366 break; 2367 } 2368 2369 case VisitorJob::PostChildrenVisitKind: 2370 if (PostChildrenVisitor(Parent, ClientData)) 2371 return true; 2372 break; 2373 } 2374 } 2375 return false; 2376} 2377 2378bool CursorVisitor::Visit(Stmt *S) { 2379 VisitorWorkList *WL = 0; 2380 if (!WorkListFreeList.empty()) { 2381 WL = WorkListFreeList.back(); 2382 WL->clear(); 2383 WorkListFreeList.pop_back(); 2384 } 2385 else { 2386 WL = new VisitorWorkList(); 2387 WorkListCache.push_back(WL); 2388 } 2389 EnqueueWorkList(*WL, S); 2390 bool result = RunVisitorWorkList(*WL); 2391 WorkListFreeList.push_back(WL); 2392 return result; 2393} 2394 2395namespace { 2396typedef SmallVector<SourceRange, 4> RefNamePieces; 2397RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr, 2398 const DeclarationNameInfo &NI, 2399 const SourceRange &QLoc, 2400 const ASTTemplateArgumentListInfo *TemplateArgs = 0){ 2401 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier; 2402 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs; 2403 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece; 2404 2405 const DeclarationName::NameKind Kind = NI.getName().getNameKind(); 2406 2407 RefNamePieces Pieces; 2408 2409 if (WantQualifier && QLoc.isValid()) 2410 Pieces.push_back(QLoc); 2411 2412 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr) 2413 Pieces.push_back(NI.getLoc()); 2414 2415 if (WantTemplateArgs && TemplateArgs) 2416 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc, 2417 TemplateArgs->RAngleLoc)); 2418 2419 if (Kind == DeclarationName::CXXOperatorName) { 2420 Pieces.push_back(SourceLocation::getFromRawEncoding( 2421 NI.getInfo().CXXOperatorName.BeginOpNameLoc)); 2422 Pieces.push_back(SourceLocation::getFromRawEncoding( 2423 NI.getInfo().CXXOperatorName.EndOpNameLoc)); 2424 } 2425 2426 if (WantSinglePiece) { 2427 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd()); 2428 Pieces.clear(); 2429 Pieces.push_back(R); 2430 } 2431 2432 return Pieces; 2433} 2434} 2435 2436//===----------------------------------------------------------------------===// 2437// Misc. API hooks. 2438//===----------------------------------------------------------------------===// 2439 2440static llvm::sys::Mutex EnableMultithreadingMutex; 2441static bool EnabledMultithreading; 2442 2443static void fatal_error_handler(void *user_data, const std::string& reason) { 2444 // Write the result out to stderr avoiding errs() because raw_ostreams can 2445 // call report_fatal_error. 2446 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str()); 2447 ::abort(); 2448} 2449 2450extern "C" { 2451CXIndex clang_createIndex(int excludeDeclarationsFromPCH, 2452 int displayDiagnostics) { 2453 // Disable pretty stack trace functionality, which will otherwise be a very 2454 // poor citizen of the world and set up all sorts of signal handlers. 2455 llvm::DisablePrettyStackTrace = true; 2456 2457 // We use crash recovery to make some of our APIs more reliable, implicitly 2458 // enable it. 2459 llvm::CrashRecoveryContext::Enable(); 2460 2461 // Enable support for multithreading in LLVM. 2462 { 2463 llvm::sys::ScopedLock L(EnableMultithreadingMutex); 2464 if (!EnabledMultithreading) { 2465 llvm::install_fatal_error_handler(fatal_error_handler, 0); 2466 llvm::llvm_start_multithreaded(); 2467 EnabledMultithreading = true; 2468 } 2469 } 2470 2471 CIndexer *CIdxr = new CIndexer(); 2472 if (excludeDeclarationsFromPCH) 2473 CIdxr->setOnlyLocalDecls(); 2474 if (displayDiagnostics) 2475 CIdxr->setDisplayDiagnostics(); 2476 2477 if (getenv("LIBCLANG_BGPRIO_INDEX")) 2478 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() | 2479 CXGlobalOpt_ThreadBackgroundPriorityForIndexing); 2480 if (getenv("LIBCLANG_BGPRIO_EDIT")) 2481 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() | 2482 CXGlobalOpt_ThreadBackgroundPriorityForEditing); 2483 2484 return CIdxr; 2485} 2486 2487void clang_disposeIndex(CXIndex CIdx) { 2488 if (CIdx) 2489 delete static_cast<CIndexer *>(CIdx); 2490} 2491 2492void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) { 2493 if (CIdx) 2494 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options); 2495} 2496 2497unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) { 2498 if (CIdx) 2499 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags(); 2500 return 0; 2501} 2502 2503void clang_toggleCrashRecovery(unsigned isEnabled) { 2504 if (isEnabled) 2505 llvm::CrashRecoveryContext::Enable(); 2506 else 2507 llvm::CrashRecoveryContext::Disable(); 2508} 2509 2510CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx, 2511 const char *ast_filename) { 2512 if (!CIdx) 2513 return 0; 2514 2515 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx); 2516 FileSystemOptions FileSystemOpts; 2517 2518 IntrusiveRefCntPtr<DiagnosticsEngine> Diags; 2519 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts, 2520 CXXIdx->getOnlyLocalDecls(), 2521 0, 0, 2522 /*CaptureDiagnostics=*/true, 2523 /*AllowPCHWithCompilerErrors=*/true, 2524 /*UserFilesAreVolatile=*/true); 2525 return MakeCXTranslationUnit(CXXIdx, TU); 2526} 2527 2528unsigned clang_defaultEditingTranslationUnitOptions() { 2529 return CXTranslationUnit_PrecompiledPreamble | 2530 CXTranslationUnit_CacheCompletionResults; 2531} 2532 2533CXTranslationUnit 2534clang_createTranslationUnitFromSourceFile(CXIndex CIdx, 2535 const char *source_filename, 2536 int num_command_line_args, 2537 const char * const *command_line_args, 2538 unsigned num_unsaved_files, 2539 struct CXUnsavedFile *unsaved_files) { 2540 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord; 2541 return clang_parseTranslationUnit(CIdx, source_filename, 2542 command_line_args, num_command_line_args, 2543 unsaved_files, num_unsaved_files, 2544 Options); 2545} 2546 2547struct ParseTranslationUnitInfo { 2548 CXIndex CIdx; 2549 const char *source_filename; 2550 const char *const *command_line_args; 2551 int num_command_line_args; 2552 struct CXUnsavedFile *unsaved_files; 2553 unsigned num_unsaved_files; 2554 unsigned options; 2555 CXTranslationUnit result; 2556}; 2557static void clang_parseTranslationUnit_Impl(void *UserData) { 2558 ParseTranslationUnitInfo *PTUI = 2559 static_cast<ParseTranslationUnitInfo*>(UserData); 2560 CXIndex CIdx = PTUI->CIdx; 2561 const char *source_filename = PTUI->source_filename; 2562 const char * const *command_line_args = PTUI->command_line_args; 2563 int num_command_line_args = PTUI->num_command_line_args; 2564 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files; 2565 unsigned num_unsaved_files = PTUI->num_unsaved_files; 2566 unsigned options = PTUI->options; 2567 PTUI->result = 0; 2568 2569 if (!CIdx) 2570 return; 2571 2572 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx); 2573 2574 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing)) 2575 setThreadBackgroundPriority(); 2576 2577 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble; 2578 // FIXME: Add a flag for modules. 2579 TranslationUnitKind TUKind 2580 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete; 2581 bool CacheCodeCompetionResults 2582 = options & CXTranslationUnit_CacheCompletionResults; 2583 bool IncludeBriefCommentsInCodeCompletion 2584 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion; 2585 bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies; 2586 bool ForSerialization = options & CXTranslationUnit_ForSerialization; 2587 2588 // Configure the diagnostics. 2589 IntrusiveRefCntPtr<DiagnosticsEngine> 2590 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions)); 2591 2592 // Recover resources if we crash before exiting this function. 2593 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine, 2594 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> > 2595 DiagCleanup(Diags.getPtr()); 2596 2597 OwningPtr<std::vector<ASTUnit::RemappedFile> > 2598 RemappedFiles(new std::vector<ASTUnit::RemappedFile>()); 2599 2600 // Recover resources if we crash before exiting this function. 2601 llvm::CrashRecoveryContextCleanupRegistrar< 2602 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get()); 2603 2604 for (unsigned I = 0; I != num_unsaved_files; ++I) { 2605 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length); 2606 const llvm::MemoryBuffer *Buffer 2607 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename); 2608 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename, 2609 Buffer)); 2610 } 2611 2612 OwningPtr<std::vector<const char *> > 2613 Args(new std::vector<const char*>()); 2614 2615 // Recover resources if we crash before exiting this method. 2616 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> > 2617 ArgsCleanup(Args.get()); 2618 2619 // Since the Clang C library is primarily used by batch tools dealing with 2620 // (often very broken) source code, where spell-checking can have a 2621 // significant negative impact on performance (particularly when 2622 // precompiled headers are involved), we disable it by default. 2623 // Only do this if we haven't found a spell-checking-related argument. 2624 bool FoundSpellCheckingArgument = false; 2625 for (int I = 0; I != num_command_line_args; ++I) { 2626 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 || 2627 strcmp(command_line_args[I], "-fspell-checking") == 0) { 2628 FoundSpellCheckingArgument = true; 2629 break; 2630 } 2631 } 2632 if (!FoundSpellCheckingArgument) 2633 Args->push_back("-fno-spell-checking"); 2634 2635 Args->insert(Args->end(), command_line_args, 2636 command_line_args + num_command_line_args); 2637 2638 // The 'source_filename' argument is optional. If the caller does not 2639 // specify it then it is assumed that the source file is specified 2640 // in the actual argument list. 2641 // Put the source file after command_line_args otherwise if '-x' flag is 2642 // present it will be unused. 2643 if (source_filename) 2644 Args->push_back(source_filename); 2645 2646 // Do we need the detailed preprocessing record? 2647 if (options & CXTranslationUnit_DetailedPreprocessingRecord) { 2648 Args->push_back("-Xclang"); 2649 Args->push_back("-detailed-preprocessing-record"); 2650 } 2651 2652 unsigned NumErrors = Diags->getClient()->getNumErrors(); 2653 OwningPtr<ASTUnit> ErrUnit; 2654 OwningPtr<ASTUnit> Unit( 2655 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0 2656 /* vector::data() not portable */, 2657 Args->size() ? (&(*Args)[0] + Args->size()) :0, 2658 Diags, 2659 CXXIdx->getClangResourcesPath(), 2660 CXXIdx->getOnlyLocalDecls(), 2661 /*CaptureDiagnostics=*/true, 2662 RemappedFiles->size() ? &(*RemappedFiles)[0]:0, 2663 RemappedFiles->size(), 2664 /*RemappedFilesKeepOriginalName=*/true, 2665 PrecompilePreamble, 2666 TUKind, 2667 CacheCodeCompetionResults, 2668 IncludeBriefCommentsInCodeCompletion, 2669 /*AllowPCHWithCompilerErrors=*/true, 2670 SkipFunctionBodies, 2671 /*UserFilesAreVolatile=*/true, 2672 ForSerialization, 2673 &ErrUnit)); 2674 2675 if (NumErrors != Diags->getClient()->getNumErrors()) { 2676 // Make sure to check that 'Unit' is non-NULL. 2677 if (CXXIdx->getDisplayDiagnostics()) 2678 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get()); 2679 } 2680 2681 PTUI->result = MakeCXTranslationUnit(CXXIdx, Unit.take()); 2682} 2683CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx, 2684 const char *source_filename, 2685 const char * const *command_line_args, 2686 int num_command_line_args, 2687 struct CXUnsavedFile *unsaved_files, 2688 unsigned num_unsaved_files, 2689 unsigned options) { 2690 LOG_FUNC_SECTION { 2691 *Log << source_filename << ": "; 2692 for (int i = 0; i != num_command_line_args; ++i) 2693 *Log << command_line_args[i] << " "; 2694 } 2695 2696 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args, 2697 num_command_line_args, unsaved_files, 2698 num_unsaved_files, options, 0 }; 2699 llvm::CrashRecoveryContext CRC; 2700 2701 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) { 2702 fprintf(stderr, "libclang: crash detected during parsing: {\n"); 2703 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename); 2704 fprintf(stderr, " 'command_line_args' : ["); 2705 for (int i = 0; i != num_command_line_args; ++i) { 2706 if (i) 2707 fprintf(stderr, ", "); 2708 fprintf(stderr, "'%s'", command_line_args[i]); 2709 } 2710 fprintf(stderr, "],\n"); 2711 fprintf(stderr, " 'unsaved_files' : ["); 2712 for (unsigned i = 0; i != num_unsaved_files; ++i) { 2713 if (i) 2714 fprintf(stderr, ", "); 2715 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename, 2716 unsaved_files[i].Length); 2717 } 2718 fprintf(stderr, "],\n"); 2719 fprintf(stderr, " 'options' : %d,\n", options); 2720 fprintf(stderr, "}\n"); 2721 2722 return 0; 2723 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) { 2724 PrintLibclangResourceUsage(PTUI.result); 2725 } 2726 2727 return PTUI.result; 2728} 2729 2730unsigned clang_defaultSaveOptions(CXTranslationUnit TU) { 2731 return CXSaveTranslationUnit_None; 2732} 2733 2734namespace { 2735 2736struct SaveTranslationUnitInfo { 2737 CXTranslationUnit TU; 2738 const char *FileName; 2739 unsigned options; 2740 CXSaveError result; 2741}; 2742 2743} 2744 2745static void clang_saveTranslationUnit_Impl(void *UserData) { 2746 SaveTranslationUnitInfo *STUI = 2747 static_cast<SaveTranslationUnitInfo*>(UserData); 2748 2749 CIndexer *CXXIdx = (CIndexer*)STUI->TU->CIdx; 2750 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing)) 2751 setThreadBackgroundPriority(); 2752 2753 bool hadError = static_cast<ASTUnit *>(STUI->TU->TUData)->Save(STUI->FileName); 2754 STUI->result = hadError ? CXSaveError_Unknown : CXSaveError_None; 2755} 2756 2757int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName, 2758 unsigned options) { 2759 LOG_FUNC_SECTION { 2760 *Log << TU << ' ' << FileName; 2761 } 2762 2763 if (!TU) 2764 return CXSaveError_InvalidTU; 2765 2766 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 2767 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 2768 if (!CXXUnit->hasSema()) 2769 return CXSaveError_InvalidTU; 2770 2771 SaveTranslationUnitInfo STUI = { TU, FileName, options, CXSaveError_None }; 2772 2773 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() || 2774 getenv("LIBCLANG_NOTHREADS")) { 2775 clang_saveTranslationUnit_Impl(&STUI); 2776 2777 if (getenv("LIBCLANG_RESOURCE_USAGE")) 2778 PrintLibclangResourceUsage(TU); 2779 2780 return STUI.result; 2781 } 2782 2783 // We have an AST that has invalid nodes due to compiler errors. 2784 // Use a crash recovery thread for protection. 2785 2786 llvm::CrashRecoveryContext CRC; 2787 2788 if (!RunSafely(CRC, clang_saveTranslationUnit_Impl, &STUI)) { 2789 fprintf(stderr, "libclang: crash detected during AST saving: {\n"); 2790 fprintf(stderr, " 'filename' : '%s'\n", FileName); 2791 fprintf(stderr, " 'options' : %d,\n", options); 2792 fprintf(stderr, "}\n"); 2793 2794 return CXSaveError_Unknown; 2795 2796 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) { 2797 PrintLibclangResourceUsage(TU); 2798 } 2799 2800 return STUI.result; 2801} 2802 2803void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) { 2804 if (CTUnit) { 2805 // If the translation unit has been marked as unsafe to free, just discard 2806 // it. 2807 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree()) 2808 return; 2809 2810 delete static_cast<ASTUnit *>(CTUnit->TUData); 2811 disposeCXStringPool(CTUnit->StringPool); 2812 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics); 2813 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool); 2814 delete static_cast<SimpleFormatContext*>(CTUnit->FormatContext); 2815 delete CTUnit; 2816 } 2817} 2818 2819unsigned clang_defaultReparseOptions(CXTranslationUnit TU) { 2820 return CXReparse_None; 2821} 2822 2823struct ReparseTranslationUnitInfo { 2824 CXTranslationUnit TU; 2825 unsigned num_unsaved_files; 2826 struct CXUnsavedFile *unsaved_files; 2827 unsigned options; 2828 int result; 2829}; 2830 2831static void clang_reparseTranslationUnit_Impl(void *UserData) { 2832 ReparseTranslationUnitInfo *RTUI = 2833 static_cast<ReparseTranslationUnitInfo*>(UserData); 2834 CXTranslationUnit TU = RTUI->TU; 2835 if (!TU) 2836 return; 2837 2838 // Reset the associated diagnostics. 2839 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics); 2840 TU->Diagnostics = 0; 2841 2842 unsigned num_unsaved_files = RTUI->num_unsaved_files; 2843 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files; 2844 unsigned options = RTUI->options; 2845 (void) options; 2846 RTUI->result = 1; 2847 2848 CIndexer *CXXIdx = (CIndexer*)TU->CIdx; 2849 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing)) 2850 setThreadBackgroundPriority(); 2851 2852 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 2853 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 2854 2855 OwningPtr<std::vector<ASTUnit::RemappedFile> > 2856 RemappedFiles(new std::vector<ASTUnit::RemappedFile>()); 2857 2858 // Recover resources if we crash before exiting this function. 2859 llvm::CrashRecoveryContextCleanupRegistrar< 2860 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get()); 2861 2862 for (unsigned I = 0; I != num_unsaved_files; ++I) { 2863 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length); 2864 const llvm::MemoryBuffer *Buffer 2865 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename); 2866 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename, 2867 Buffer)); 2868 } 2869 2870 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0, 2871 RemappedFiles->size())) 2872 RTUI->result = 0; 2873} 2874 2875int clang_reparseTranslationUnit(CXTranslationUnit TU, 2876 unsigned num_unsaved_files, 2877 struct CXUnsavedFile *unsaved_files, 2878 unsigned options) { 2879 LOG_FUNC_SECTION { 2880 *Log << TU; 2881 } 2882 2883 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files, 2884 options, 0 }; 2885 2886 if (getenv("LIBCLANG_NOTHREADS")) { 2887 clang_reparseTranslationUnit_Impl(&RTUI); 2888 return RTUI.result; 2889 } 2890 2891 llvm::CrashRecoveryContext CRC; 2892 2893 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) { 2894 fprintf(stderr, "libclang: crash detected during reparsing\n"); 2895 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true); 2896 return 1; 2897 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) 2898 PrintLibclangResourceUsage(TU); 2899 2900 return RTUI.result; 2901} 2902 2903 2904CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) { 2905 if (!CTUnit) 2906 return createCXString(""); 2907 2908 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData); 2909 return createCXString(CXXUnit->getOriginalSourceFileName(), true); 2910} 2911 2912CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) { 2913 ASTUnit *CXXUnit = static_cast<ASTUnit*>(TU->TUData); 2914 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU); 2915} 2916 2917} // end: extern "C" 2918 2919//===----------------------------------------------------------------------===// 2920// CXFile Operations. 2921//===----------------------------------------------------------------------===// 2922 2923extern "C" { 2924CXString clang_getFileName(CXFile SFile) { 2925 if (!SFile) 2926 return createCXString((const char*)NULL); 2927 2928 FileEntry *FEnt = static_cast<FileEntry *>(SFile); 2929 return createCXString(FEnt->getName()); 2930} 2931 2932time_t clang_getFileTime(CXFile SFile) { 2933 if (!SFile) 2934 return 0; 2935 2936 FileEntry *FEnt = static_cast<FileEntry *>(SFile); 2937 return FEnt->getModificationTime(); 2938} 2939 2940CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) { 2941 if (!tu) 2942 return 0; 2943 2944 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData); 2945 2946 FileManager &FMgr = CXXUnit->getFileManager(); 2947 return const_cast<FileEntry *>(FMgr.getFile(file_name)); 2948} 2949 2950unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) { 2951 if (!tu || !file) 2952 return 0; 2953 2954 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData); 2955 FileEntry *FEnt = static_cast<FileEntry *>(file); 2956 return CXXUnit->getPreprocessor().getHeaderSearchInfo() 2957 .isFileMultipleIncludeGuarded(FEnt); 2958} 2959 2960} // end: extern "C" 2961 2962//===----------------------------------------------------------------------===// 2963// CXCursor Operations. 2964//===----------------------------------------------------------------------===// 2965 2966static Decl *getDeclFromExpr(Stmt *E) { 2967 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) 2968 return getDeclFromExpr(CE->getSubExpr()); 2969 2970 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E)) 2971 return RefExpr->getDecl(); 2972 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) 2973 return ME->getMemberDecl(); 2974 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E)) 2975 return RE->getDecl(); 2976 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) { 2977 if (PRE->isExplicitProperty()) 2978 return PRE->getExplicitProperty(); 2979 // It could be messaging both getter and setter as in: 2980 // ++myobj.myprop; 2981 // in which case prefer to associate the setter since it is less obvious 2982 // from inspecting the source that the setter is going to get called. 2983 if (PRE->isMessagingSetter()) 2984 return PRE->getImplicitPropertySetter(); 2985 return PRE->getImplicitPropertyGetter(); 2986 } 2987 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 2988 return getDeclFromExpr(POE->getSyntacticForm()); 2989 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) 2990 if (Expr *Src = OVE->getSourceExpr()) 2991 return getDeclFromExpr(Src); 2992 2993 if (CallExpr *CE = dyn_cast<CallExpr>(E)) 2994 return getDeclFromExpr(CE->getCallee()); 2995 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E)) 2996 if (!CE->isElidable()) 2997 return CE->getConstructor(); 2998 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E)) 2999 return OME->getMethodDecl(); 3000 3001 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E)) 3002 return PE->getProtocol(); 3003 if (SubstNonTypeTemplateParmPackExpr *NTTP 3004 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E)) 3005 return NTTP->getParameterPack(); 3006 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E)) 3007 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) || 3008 isa<ParmVarDecl>(SizeOfPack->getPack())) 3009 return SizeOfPack->getPack(); 3010 3011 return 0; 3012} 3013 3014static SourceLocation getLocationFromExpr(Expr *E) { 3015 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) 3016 return getLocationFromExpr(CE->getSubExpr()); 3017 3018 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) 3019 return /*FIXME:*/Msg->getLeftLoc(); 3020 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 3021 return DRE->getLocation(); 3022 if (MemberExpr *Member = dyn_cast<MemberExpr>(E)) 3023 return Member->getMemberLoc(); 3024 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) 3025 return Ivar->getLocation(); 3026 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E)) 3027 return SizeOfPack->getPackLoc(); 3028 if (ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E)) 3029 return PropRef->getLocation(); 3030 3031 return E->getLocStart(); 3032} 3033 3034extern "C" { 3035 3036unsigned clang_visitChildren(CXCursor parent, 3037 CXCursorVisitor visitor, 3038 CXClientData client_data) { 3039 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data, 3040 /*VisitPreprocessorLast=*/false); 3041 return CursorVis.VisitChildren(parent); 3042} 3043 3044#ifndef __has_feature 3045#define __has_feature(x) 0 3046#endif 3047#if __has_feature(blocks) 3048typedef enum CXChildVisitResult 3049 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent); 3050 3051static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent, 3052 CXClientData client_data) { 3053 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data; 3054 return block(cursor, parent); 3055} 3056#else 3057// If we are compiled with a compiler that doesn't have native blocks support, 3058// define and call the block manually, so the 3059typedef struct _CXChildVisitResult 3060{ 3061 void *isa; 3062 int flags; 3063 int reserved; 3064 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor, 3065 CXCursor); 3066} *CXCursorVisitorBlock; 3067 3068static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent, 3069 CXClientData client_data) { 3070 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data; 3071 return block->invoke(block, cursor, parent); 3072} 3073#endif 3074 3075 3076unsigned clang_visitChildrenWithBlock(CXCursor parent, 3077 CXCursorVisitorBlock block) { 3078 return clang_visitChildren(parent, visitWithBlock, block); 3079} 3080 3081static CXString getDeclSpelling(Decl *D) { 3082 if (!D) 3083 return createCXString(""); 3084 3085 NamedDecl *ND = dyn_cast<NamedDecl>(D); 3086 if (!ND) { 3087 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D)) 3088 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl()) 3089 return createCXString(Property->getIdentifier()->getName()); 3090 3091 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) 3092 if (Module *Mod = ImportD->getImportedModule()) 3093 return createCXString(Mod->getFullModuleName()); 3094 3095 return createCXString(""); 3096 } 3097 3098 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND)) 3099 return createCXString(OMD->getSelector().getAsString()); 3100 3101 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND)) 3102 // No, this isn't the same as the code below. getIdentifier() is non-virtual 3103 // and returns different names. NamedDecl returns the class name and 3104 // ObjCCategoryImplDecl returns the category name. 3105 return createCXString(CIMP->getIdentifier()->getNameStart()); 3106 3107 if (isa<UsingDirectiveDecl>(D)) 3108 return createCXString(""); 3109 3110 SmallString<1024> S; 3111 llvm::raw_svector_ostream os(S); 3112 ND->printName(os); 3113 3114 return createCXString(os.str()); 3115} 3116 3117CXString clang_getCursorSpelling(CXCursor C) { 3118 if (clang_isTranslationUnit(C.kind)) 3119 return clang_getTranslationUnitSpelling(getCursorTU(C)); 3120 3121 if (clang_isReference(C.kind)) { 3122 switch (C.kind) { 3123 case CXCursor_ObjCSuperClassRef: { 3124 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first; 3125 return createCXString(Super->getIdentifier()->getNameStart()); 3126 } 3127 case CXCursor_ObjCClassRef: { 3128 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first; 3129 return createCXString(Class->getIdentifier()->getNameStart()); 3130 } 3131 case CXCursor_ObjCProtocolRef: { 3132 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first; 3133 assert(OID && "getCursorSpelling(): Missing protocol decl"); 3134 return createCXString(OID->getIdentifier()->getNameStart()); 3135 } 3136 case CXCursor_CXXBaseSpecifier: { 3137 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C); 3138 return createCXString(B->getType().getAsString()); 3139 } 3140 case CXCursor_TypeRef: { 3141 const TypeDecl *Type = getCursorTypeRef(C).first; 3142 assert(Type && "Missing type decl"); 3143 3144 return createCXString(getCursorContext(C).getTypeDeclType(Type). 3145 getAsString()); 3146 } 3147 case CXCursor_TemplateRef: { 3148 const TemplateDecl *Template = getCursorTemplateRef(C).first; 3149 assert(Template && "Missing template decl"); 3150 3151 return createCXString(Template->getNameAsString()); 3152 } 3153 3154 case CXCursor_NamespaceRef: { 3155 const NamedDecl *NS = getCursorNamespaceRef(C).first; 3156 assert(NS && "Missing namespace decl"); 3157 3158 return createCXString(NS->getNameAsString()); 3159 } 3160 3161 case CXCursor_MemberRef: { 3162 const FieldDecl *Field = getCursorMemberRef(C).first; 3163 assert(Field && "Missing member decl"); 3164 3165 return createCXString(Field->getNameAsString()); 3166 } 3167 3168 case CXCursor_LabelRef: { 3169 const LabelStmt *Label = getCursorLabelRef(C).first; 3170 assert(Label && "Missing label"); 3171 3172 return createCXString(Label->getName()); 3173 } 3174 3175 case CXCursor_OverloadedDeclRef: { 3176 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first; 3177 if (Decl *D = Storage.dyn_cast<Decl *>()) { 3178 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) 3179 return createCXString(ND->getNameAsString()); 3180 return createCXString(""); 3181 } 3182 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>()) 3183 return createCXString(E->getName().getAsString()); 3184 OverloadedTemplateStorage *Ovl 3185 = Storage.get<OverloadedTemplateStorage*>(); 3186 if (Ovl->size() == 0) 3187 return createCXString(""); 3188 return createCXString((*Ovl->begin())->getNameAsString()); 3189 } 3190 3191 case CXCursor_VariableRef: { 3192 const VarDecl *Var = getCursorVariableRef(C).first; 3193 assert(Var && "Missing variable decl"); 3194 3195 return createCXString(Var->getNameAsString()); 3196 } 3197 3198 default: 3199 return createCXString("<not implemented>"); 3200 } 3201 } 3202 3203 if (clang_isExpression(C.kind)) { 3204 Decl *D = getDeclFromExpr(getCursorExpr(C)); 3205 if (D) 3206 return getDeclSpelling(D); 3207 return createCXString(""); 3208 } 3209 3210 if (clang_isStatement(C.kind)) { 3211 Stmt *S = getCursorStmt(C); 3212 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) 3213 return createCXString(Label->getName()); 3214 3215 return createCXString(""); 3216 } 3217 3218 if (C.kind == CXCursor_MacroExpansion) 3219 return createCXString(getCursorMacroExpansion(C).getName() 3220 ->getNameStart()); 3221 3222 if (C.kind == CXCursor_MacroDefinition) 3223 return createCXString(getCursorMacroDefinition(C)->getName() 3224 ->getNameStart()); 3225 3226 if (C.kind == CXCursor_InclusionDirective) 3227 return createCXString(getCursorInclusionDirective(C)->getFileName()); 3228 3229 if (clang_isDeclaration(C.kind)) 3230 return getDeclSpelling(getCursorDecl(C)); 3231 3232 if (C.kind == CXCursor_AnnotateAttr) { 3233 AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C)); 3234 return createCXString(AA->getAnnotation()); 3235 } 3236 3237 if (C.kind == CXCursor_AsmLabelAttr) { 3238 AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C)); 3239 return createCXString(AA->getLabel()); 3240 } 3241 3242 return createCXString(""); 3243} 3244 3245CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C, 3246 unsigned pieceIndex, 3247 unsigned options) { 3248 if (clang_Cursor_isNull(C)) 3249 return clang_getNullRange(); 3250 3251 ASTContext &Ctx = getCursorContext(C); 3252 3253 if (clang_isStatement(C.kind)) { 3254 Stmt *S = getCursorStmt(C); 3255 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) { 3256 if (pieceIndex > 0) 3257 return clang_getNullRange(); 3258 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc()); 3259 } 3260 3261 return clang_getNullRange(); 3262 } 3263 3264 if (C.kind == CXCursor_ObjCMessageExpr) { 3265 if (ObjCMessageExpr * 3266 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) { 3267 if (pieceIndex >= ME->getNumSelectorLocs()) 3268 return clang_getNullRange(); 3269 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex)); 3270 } 3271 } 3272 3273 if (C.kind == CXCursor_ObjCInstanceMethodDecl || 3274 C.kind == CXCursor_ObjCClassMethodDecl) { 3275 if (ObjCMethodDecl * 3276 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) { 3277 if (pieceIndex >= MD->getNumSelectorLocs()) 3278 return clang_getNullRange(); 3279 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex)); 3280 } 3281 } 3282 3283 if (C.kind == CXCursor_ObjCCategoryDecl || 3284 C.kind == CXCursor_ObjCCategoryImplDecl) { 3285 if (pieceIndex > 0) 3286 return clang_getNullRange(); 3287 if (ObjCCategoryDecl * 3288 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C))) 3289 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc()); 3290 if (ObjCCategoryImplDecl * 3291 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C))) 3292 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc()); 3293 } 3294 3295 if (C.kind == CXCursor_ModuleImportDecl) { 3296 if (pieceIndex > 0) 3297 return clang_getNullRange(); 3298 if (ImportDecl *ImportD = dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) { 3299 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs(); 3300 if (!Locs.empty()) 3301 return cxloc::translateSourceRange(Ctx, 3302 SourceRange(Locs.front(), Locs.back())); 3303 } 3304 return clang_getNullRange(); 3305 } 3306 3307 // FIXME: A CXCursor_InclusionDirective should give the location of the 3308 // filename, but we don't keep track of this. 3309 3310 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation 3311 // but we don't keep track of this. 3312 3313 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label 3314 // but we don't keep track of this. 3315 3316 // Default handling, give the location of the cursor. 3317 3318 if (pieceIndex > 0) 3319 return clang_getNullRange(); 3320 3321 CXSourceLocation CXLoc = clang_getCursorLocation(C); 3322 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc); 3323 return cxloc::translateSourceRange(Ctx, Loc); 3324} 3325 3326CXString clang_getCursorDisplayName(CXCursor C) { 3327 if (!clang_isDeclaration(C.kind)) 3328 return clang_getCursorSpelling(C); 3329 3330 Decl *D = getCursorDecl(C); 3331 if (!D) 3332 return createCXString(""); 3333 3334 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy(); 3335 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 3336 D = FunTmpl->getTemplatedDecl(); 3337 3338 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 3339 SmallString<64> Str; 3340 llvm::raw_svector_ostream OS(Str); 3341 OS << *Function; 3342 if (Function->getPrimaryTemplate()) 3343 OS << "<>"; 3344 OS << "("; 3345 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) { 3346 if (I) 3347 OS << ", "; 3348 OS << Function->getParamDecl(I)->getType().getAsString(Policy); 3349 } 3350 3351 if (Function->isVariadic()) { 3352 if (Function->getNumParams()) 3353 OS << ", "; 3354 OS << "..."; 3355 } 3356 OS << ")"; 3357 return createCXString(OS.str()); 3358 } 3359 3360 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) { 3361 SmallString<64> Str; 3362 llvm::raw_svector_ostream OS(Str); 3363 OS << *ClassTemplate; 3364 OS << "<"; 3365 TemplateParameterList *Params = ClassTemplate->getTemplateParameters(); 3366 for (unsigned I = 0, N = Params->size(); I != N; ++I) { 3367 if (I) 3368 OS << ", "; 3369 3370 NamedDecl *Param = Params->getParam(I); 3371 if (Param->getIdentifier()) { 3372 OS << Param->getIdentifier()->getName(); 3373 continue; 3374 } 3375 3376 // There is no parameter name, which makes this tricky. Try to come up 3377 // with something useful that isn't too long. 3378 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) 3379 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class"); 3380 else if (NonTypeTemplateParmDecl *NTTP 3381 = dyn_cast<NonTypeTemplateParmDecl>(Param)) 3382 OS << NTTP->getType().getAsString(Policy); 3383 else 3384 OS << "template<...> class"; 3385 } 3386 3387 OS << ">"; 3388 return createCXString(OS.str()); 3389 } 3390 3391 if (ClassTemplateSpecializationDecl *ClassSpec 3392 = dyn_cast<ClassTemplateSpecializationDecl>(D)) { 3393 // If the type was explicitly written, use that. 3394 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten()) 3395 return createCXString(TSInfo->getType().getAsString(Policy)); 3396 3397 SmallString<64> Str; 3398 llvm::raw_svector_ostream OS(Str); 3399 OS << *ClassSpec; 3400 OS << TemplateSpecializationType::PrintTemplateArgumentList( 3401 ClassSpec->getTemplateArgs().data(), 3402 ClassSpec->getTemplateArgs().size(), 3403 Policy); 3404 return createCXString(OS.str()); 3405 } 3406 3407 return clang_getCursorSpelling(C); 3408} 3409 3410CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) { 3411 switch (Kind) { 3412 case CXCursor_FunctionDecl: 3413 return createCXString("FunctionDecl"); 3414 case CXCursor_TypedefDecl: 3415 return createCXString("TypedefDecl"); 3416 case CXCursor_EnumDecl: 3417 return createCXString("EnumDecl"); 3418 case CXCursor_EnumConstantDecl: 3419 return createCXString("EnumConstantDecl"); 3420 case CXCursor_StructDecl: 3421 return createCXString("StructDecl"); 3422 case CXCursor_UnionDecl: 3423 return createCXString("UnionDecl"); 3424 case CXCursor_ClassDecl: 3425 return createCXString("ClassDecl"); 3426 case CXCursor_FieldDecl: 3427 return createCXString("FieldDecl"); 3428 case CXCursor_VarDecl: 3429 return createCXString("VarDecl"); 3430 case CXCursor_ParmDecl: 3431 return createCXString("ParmDecl"); 3432 case CXCursor_ObjCInterfaceDecl: 3433 return createCXString("ObjCInterfaceDecl"); 3434 case CXCursor_ObjCCategoryDecl: 3435 return createCXString("ObjCCategoryDecl"); 3436 case CXCursor_ObjCProtocolDecl: 3437 return createCXString("ObjCProtocolDecl"); 3438 case CXCursor_ObjCPropertyDecl: 3439 return createCXString("ObjCPropertyDecl"); 3440 case CXCursor_ObjCIvarDecl: 3441 return createCXString("ObjCIvarDecl"); 3442 case CXCursor_ObjCInstanceMethodDecl: 3443 return createCXString("ObjCInstanceMethodDecl"); 3444 case CXCursor_ObjCClassMethodDecl: 3445 return createCXString("ObjCClassMethodDecl"); 3446 case CXCursor_ObjCImplementationDecl: 3447 return createCXString("ObjCImplementationDecl"); 3448 case CXCursor_ObjCCategoryImplDecl: 3449 return createCXString("ObjCCategoryImplDecl"); 3450 case CXCursor_CXXMethod: 3451 return createCXString("CXXMethod"); 3452 case CXCursor_UnexposedDecl: 3453 return createCXString("UnexposedDecl"); 3454 case CXCursor_ObjCSuperClassRef: 3455 return createCXString("ObjCSuperClassRef"); 3456 case CXCursor_ObjCProtocolRef: 3457 return createCXString("ObjCProtocolRef"); 3458 case CXCursor_ObjCClassRef: 3459 return createCXString("ObjCClassRef"); 3460 case CXCursor_TypeRef: 3461 return createCXString("TypeRef"); 3462 case CXCursor_TemplateRef: 3463 return createCXString("TemplateRef"); 3464 case CXCursor_NamespaceRef: 3465 return createCXString("NamespaceRef"); 3466 case CXCursor_MemberRef: 3467 return createCXString("MemberRef"); 3468 case CXCursor_LabelRef: 3469 return createCXString("LabelRef"); 3470 case CXCursor_OverloadedDeclRef: 3471 return createCXString("OverloadedDeclRef"); 3472 case CXCursor_VariableRef: 3473 return createCXString("VariableRef"); 3474 case CXCursor_IntegerLiteral: 3475 return createCXString("IntegerLiteral"); 3476 case CXCursor_FloatingLiteral: 3477 return createCXString("FloatingLiteral"); 3478 case CXCursor_ImaginaryLiteral: 3479 return createCXString("ImaginaryLiteral"); 3480 case CXCursor_StringLiteral: 3481 return createCXString("StringLiteral"); 3482 case CXCursor_CharacterLiteral: 3483 return createCXString("CharacterLiteral"); 3484 case CXCursor_ParenExpr: 3485 return createCXString("ParenExpr"); 3486 case CXCursor_UnaryOperator: 3487 return createCXString("UnaryOperator"); 3488 case CXCursor_ArraySubscriptExpr: 3489 return createCXString("ArraySubscriptExpr"); 3490 case CXCursor_BinaryOperator: 3491 return createCXString("BinaryOperator"); 3492 case CXCursor_CompoundAssignOperator: 3493 return createCXString("CompoundAssignOperator"); 3494 case CXCursor_ConditionalOperator: 3495 return createCXString("ConditionalOperator"); 3496 case CXCursor_CStyleCastExpr: 3497 return createCXString("CStyleCastExpr"); 3498 case CXCursor_CompoundLiteralExpr: 3499 return createCXString("CompoundLiteralExpr"); 3500 case CXCursor_InitListExpr: 3501 return createCXString("InitListExpr"); 3502 case CXCursor_AddrLabelExpr: 3503 return createCXString("AddrLabelExpr"); 3504 case CXCursor_StmtExpr: 3505 return createCXString("StmtExpr"); 3506 case CXCursor_GenericSelectionExpr: 3507 return createCXString("GenericSelectionExpr"); 3508 case CXCursor_GNUNullExpr: 3509 return createCXString("GNUNullExpr"); 3510 case CXCursor_CXXStaticCastExpr: 3511 return createCXString("CXXStaticCastExpr"); 3512 case CXCursor_CXXDynamicCastExpr: 3513 return createCXString("CXXDynamicCastExpr"); 3514 case CXCursor_CXXReinterpretCastExpr: 3515 return createCXString("CXXReinterpretCastExpr"); 3516 case CXCursor_CXXConstCastExpr: 3517 return createCXString("CXXConstCastExpr"); 3518 case CXCursor_CXXFunctionalCastExpr: 3519 return createCXString("CXXFunctionalCastExpr"); 3520 case CXCursor_CXXTypeidExpr: 3521 return createCXString("CXXTypeidExpr"); 3522 case CXCursor_CXXBoolLiteralExpr: 3523 return createCXString("CXXBoolLiteralExpr"); 3524 case CXCursor_CXXNullPtrLiteralExpr: 3525 return createCXString("CXXNullPtrLiteralExpr"); 3526 case CXCursor_CXXThisExpr: 3527 return createCXString("CXXThisExpr"); 3528 case CXCursor_CXXThrowExpr: 3529 return createCXString("CXXThrowExpr"); 3530 case CXCursor_CXXNewExpr: 3531 return createCXString("CXXNewExpr"); 3532 case CXCursor_CXXDeleteExpr: 3533 return createCXString("CXXDeleteExpr"); 3534 case CXCursor_UnaryExpr: 3535 return createCXString("UnaryExpr"); 3536 case CXCursor_ObjCStringLiteral: 3537 return createCXString("ObjCStringLiteral"); 3538 case CXCursor_ObjCBoolLiteralExpr: 3539 return createCXString("ObjCBoolLiteralExpr"); 3540 case CXCursor_ObjCEncodeExpr: 3541 return createCXString("ObjCEncodeExpr"); 3542 case CXCursor_ObjCSelectorExpr: 3543 return createCXString("ObjCSelectorExpr"); 3544 case CXCursor_ObjCProtocolExpr: 3545 return createCXString("ObjCProtocolExpr"); 3546 case CXCursor_ObjCBridgedCastExpr: 3547 return createCXString("ObjCBridgedCastExpr"); 3548 case CXCursor_BlockExpr: 3549 return createCXString("BlockExpr"); 3550 case CXCursor_PackExpansionExpr: 3551 return createCXString("PackExpansionExpr"); 3552 case CXCursor_SizeOfPackExpr: 3553 return createCXString("SizeOfPackExpr"); 3554 case CXCursor_LambdaExpr: 3555 return createCXString("LambdaExpr"); 3556 case CXCursor_UnexposedExpr: 3557 return createCXString("UnexposedExpr"); 3558 case CXCursor_DeclRefExpr: 3559 return createCXString("DeclRefExpr"); 3560 case CXCursor_MemberRefExpr: 3561 return createCXString("MemberRefExpr"); 3562 case CXCursor_CallExpr: 3563 return createCXString("CallExpr"); 3564 case CXCursor_ObjCMessageExpr: 3565 return createCXString("ObjCMessageExpr"); 3566 case CXCursor_UnexposedStmt: 3567 return createCXString("UnexposedStmt"); 3568 case CXCursor_DeclStmt: 3569 return createCXString("DeclStmt"); 3570 case CXCursor_LabelStmt: 3571 return createCXString("LabelStmt"); 3572 case CXCursor_CompoundStmt: 3573 return createCXString("CompoundStmt"); 3574 case CXCursor_CaseStmt: 3575 return createCXString("CaseStmt"); 3576 case CXCursor_DefaultStmt: 3577 return createCXString("DefaultStmt"); 3578 case CXCursor_IfStmt: 3579 return createCXString("IfStmt"); 3580 case CXCursor_SwitchStmt: 3581 return createCXString("SwitchStmt"); 3582 case CXCursor_WhileStmt: 3583 return createCXString("WhileStmt"); 3584 case CXCursor_DoStmt: 3585 return createCXString("DoStmt"); 3586 case CXCursor_ForStmt: 3587 return createCXString("ForStmt"); 3588 case CXCursor_GotoStmt: 3589 return createCXString("GotoStmt"); 3590 case CXCursor_IndirectGotoStmt: 3591 return createCXString("IndirectGotoStmt"); 3592 case CXCursor_ContinueStmt: 3593 return createCXString("ContinueStmt"); 3594 case CXCursor_BreakStmt: 3595 return createCXString("BreakStmt"); 3596 case CXCursor_ReturnStmt: 3597 return createCXString("ReturnStmt"); 3598 case CXCursor_GCCAsmStmt: 3599 return createCXString("GCCAsmStmt"); 3600 case CXCursor_MSAsmStmt: 3601 return createCXString("MSAsmStmt"); 3602 case CXCursor_ObjCAtTryStmt: 3603 return createCXString("ObjCAtTryStmt"); 3604 case CXCursor_ObjCAtCatchStmt: 3605 return createCXString("ObjCAtCatchStmt"); 3606 case CXCursor_ObjCAtFinallyStmt: 3607 return createCXString("ObjCAtFinallyStmt"); 3608 case CXCursor_ObjCAtThrowStmt: 3609 return createCXString("ObjCAtThrowStmt"); 3610 case CXCursor_ObjCAtSynchronizedStmt: 3611 return createCXString("ObjCAtSynchronizedStmt"); 3612 case CXCursor_ObjCAutoreleasePoolStmt: 3613 return createCXString("ObjCAutoreleasePoolStmt"); 3614 case CXCursor_ObjCForCollectionStmt: 3615 return createCXString("ObjCForCollectionStmt"); 3616 case CXCursor_CXXCatchStmt: 3617 return createCXString("CXXCatchStmt"); 3618 case CXCursor_CXXTryStmt: 3619 return createCXString("CXXTryStmt"); 3620 case CXCursor_CXXForRangeStmt: 3621 return createCXString("CXXForRangeStmt"); 3622 case CXCursor_SEHTryStmt: 3623 return createCXString("SEHTryStmt"); 3624 case CXCursor_SEHExceptStmt: 3625 return createCXString("SEHExceptStmt"); 3626 case CXCursor_SEHFinallyStmt: 3627 return createCXString("SEHFinallyStmt"); 3628 case CXCursor_NullStmt: 3629 return createCXString("NullStmt"); 3630 case CXCursor_InvalidFile: 3631 return createCXString("InvalidFile"); 3632 case CXCursor_InvalidCode: 3633 return createCXString("InvalidCode"); 3634 case CXCursor_NoDeclFound: 3635 return createCXString("NoDeclFound"); 3636 case CXCursor_NotImplemented: 3637 return createCXString("NotImplemented"); 3638 case CXCursor_TranslationUnit: 3639 return createCXString("TranslationUnit"); 3640 case CXCursor_UnexposedAttr: 3641 return createCXString("UnexposedAttr"); 3642 case CXCursor_IBActionAttr: 3643 return createCXString("attribute(ibaction)"); 3644 case CXCursor_IBOutletAttr: 3645 return createCXString("attribute(iboutlet)"); 3646 case CXCursor_IBOutletCollectionAttr: 3647 return createCXString("attribute(iboutletcollection)"); 3648 case CXCursor_CXXFinalAttr: 3649 return createCXString("attribute(final)"); 3650 case CXCursor_CXXOverrideAttr: 3651 return createCXString("attribute(override)"); 3652 case CXCursor_AnnotateAttr: 3653 return createCXString("attribute(annotate)"); 3654 case CXCursor_AsmLabelAttr: 3655 return createCXString("asm label"); 3656 case CXCursor_PreprocessingDirective: 3657 return createCXString("preprocessing directive"); 3658 case CXCursor_MacroDefinition: 3659 return createCXString("macro definition"); 3660 case CXCursor_MacroExpansion: 3661 return createCXString("macro expansion"); 3662 case CXCursor_InclusionDirective: 3663 return createCXString("inclusion directive"); 3664 case CXCursor_Namespace: 3665 return createCXString("Namespace"); 3666 case CXCursor_LinkageSpec: 3667 return createCXString("LinkageSpec"); 3668 case CXCursor_CXXBaseSpecifier: 3669 return createCXString("C++ base class specifier"); 3670 case CXCursor_Constructor: 3671 return createCXString("CXXConstructor"); 3672 case CXCursor_Destructor: 3673 return createCXString("CXXDestructor"); 3674 case CXCursor_ConversionFunction: 3675 return createCXString("CXXConversion"); 3676 case CXCursor_TemplateTypeParameter: 3677 return createCXString("TemplateTypeParameter"); 3678 case CXCursor_NonTypeTemplateParameter: 3679 return createCXString("NonTypeTemplateParameter"); 3680 case CXCursor_TemplateTemplateParameter: 3681 return createCXString("TemplateTemplateParameter"); 3682 case CXCursor_FunctionTemplate: 3683 return createCXString("FunctionTemplate"); 3684 case CXCursor_ClassTemplate: 3685 return createCXString("ClassTemplate"); 3686 case CXCursor_ClassTemplatePartialSpecialization: 3687 return createCXString("ClassTemplatePartialSpecialization"); 3688 case CXCursor_NamespaceAlias: 3689 return createCXString("NamespaceAlias"); 3690 case CXCursor_UsingDirective: 3691 return createCXString("UsingDirective"); 3692 case CXCursor_UsingDeclaration: 3693 return createCXString("UsingDeclaration"); 3694 case CXCursor_TypeAliasDecl: 3695 return createCXString("TypeAliasDecl"); 3696 case CXCursor_ObjCSynthesizeDecl: 3697 return createCXString("ObjCSynthesizeDecl"); 3698 case CXCursor_ObjCDynamicDecl: 3699 return createCXString("ObjCDynamicDecl"); 3700 case CXCursor_CXXAccessSpecifier: 3701 return createCXString("CXXAccessSpecifier"); 3702 case CXCursor_ModuleImportDecl: 3703 return createCXString("ModuleImport"); 3704 } 3705 3706 llvm_unreachable("Unhandled CXCursorKind"); 3707} 3708 3709struct GetCursorData { 3710 SourceLocation TokenBeginLoc; 3711 bool PointsAtMacroArgExpansion; 3712 bool VisitedObjCPropertyImplDecl; 3713 SourceLocation VisitedDeclaratorDeclStartLoc; 3714 CXCursor &BestCursor; 3715 3716 GetCursorData(SourceManager &SM, 3717 SourceLocation tokenBegin, CXCursor &outputCursor) 3718 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) { 3719 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin); 3720 VisitedObjCPropertyImplDecl = false; 3721 } 3722}; 3723 3724static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor, 3725 CXCursor parent, 3726 CXClientData client_data) { 3727 GetCursorData *Data = static_cast<GetCursorData *>(client_data); 3728 CXCursor *BestCursor = &Data->BestCursor; 3729 3730 // If we point inside a macro argument we should provide info of what the 3731 // token is so use the actual cursor, don't replace it with a macro expansion 3732 // cursor. 3733 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion) 3734 return CXChildVisit_Recurse; 3735 3736 if (clang_isDeclaration(cursor.kind)) { 3737 // Avoid having the implicit methods override the property decls. 3738 if (ObjCMethodDecl *MD 3739 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) { 3740 if (MD->isImplicit()) 3741 return CXChildVisit_Break; 3742 3743 } else if (ObjCInterfaceDecl *ID 3744 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) { 3745 // Check that when we have multiple @class references in the same line, 3746 // that later ones do not override the previous ones. 3747 // If we have: 3748 // @class Foo, Bar; 3749 // source ranges for both start at '@', so 'Bar' will end up overriding 3750 // 'Foo' even though the cursor location was at 'Foo'. 3751 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl || 3752 BestCursor->kind == CXCursor_ObjCClassRef) 3753 if (ObjCInterfaceDecl *PrevID 3754 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){ 3755 if (PrevID != ID && 3756 !PrevID->isThisDeclarationADefinition() && 3757 !ID->isThisDeclarationADefinition()) 3758 return CXChildVisit_Break; 3759 } 3760 3761 } else if (DeclaratorDecl *DD 3762 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) { 3763 SourceLocation StartLoc = DD->getSourceRange().getBegin(); 3764 // Check that when we have multiple declarators in the same line, 3765 // that later ones do not override the previous ones. 3766 // If we have: 3767 // int Foo, Bar; 3768 // source ranges for both start at 'int', so 'Bar' will end up overriding 3769 // 'Foo' even though the cursor location was at 'Foo'. 3770 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc) 3771 return CXChildVisit_Break; 3772 Data->VisitedDeclaratorDeclStartLoc = StartLoc; 3773 3774 } else if (ObjCPropertyImplDecl *PropImp 3775 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) { 3776 (void)PropImp; 3777 // Check that when we have multiple @synthesize in the same line, 3778 // that later ones do not override the previous ones. 3779 // If we have: 3780 // @synthesize Foo, Bar; 3781 // source ranges for both start at '@', so 'Bar' will end up overriding 3782 // 'Foo' even though the cursor location was at 'Foo'. 3783 if (Data->VisitedObjCPropertyImplDecl) 3784 return CXChildVisit_Break; 3785 Data->VisitedObjCPropertyImplDecl = true; 3786 } 3787 } 3788 3789 if (clang_isExpression(cursor.kind) && 3790 clang_isDeclaration(BestCursor->kind)) { 3791 if (Decl *D = getCursorDecl(*BestCursor)) { 3792 // Avoid having the cursor of an expression replace the declaration cursor 3793 // when the expression source range overlaps the declaration range. 3794 // This can happen for C++ constructor expressions whose range generally 3795 // include the variable declaration, e.g.: 3796 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor. 3797 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() && 3798 D->getLocation() == Data->TokenBeginLoc) 3799 return CXChildVisit_Break; 3800 } 3801 } 3802 3803 // If our current best cursor is the construction of a temporary object, 3804 // don't replace that cursor with a type reference, because we want 3805 // clang_getCursor() to point at the constructor. 3806 if (clang_isExpression(BestCursor->kind) && 3807 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) && 3808 cursor.kind == CXCursor_TypeRef) { 3809 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it 3810 // as having the actual point on the type reference. 3811 *BestCursor = getTypeRefedCallExprCursor(*BestCursor); 3812 return CXChildVisit_Recurse; 3813 } 3814 3815 *BestCursor = cursor; 3816 return CXChildVisit_Recurse; 3817} 3818 3819CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) { 3820 if (!TU) 3821 return clang_getNullCursor(); 3822 3823 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 3824 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 3825 3826 SourceLocation SLoc = cxloc::translateSourceLocation(Loc); 3827 CXCursor Result = cxcursor::getCursor(TU, SLoc); 3828 3829 LOG_FUNC_SECTION { 3830 CXFile SearchFile; 3831 unsigned SearchLine, SearchColumn; 3832 CXFile ResultFile; 3833 unsigned ResultLine, ResultColumn; 3834 CXString SearchFileName, ResultFileName, KindSpelling, USR; 3835 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : ""; 3836 CXSourceLocation ResultLoc = clang_getCursorLocation(Result); 3837 3838 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0); 3839 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine, 3840 &ResultColumn, 0); 3841 SearchFileName = clang_getFileName(SearchFile); 3842 ResultFileName = clang_getFileName(ResultFile); 3843 KindSpelling = clang_getCursorKindSpelling(Result.kind); 3844 USR = clang_getCursorUSR(Result); 3845 *Log << llvm::format("(%s:%d:%d) = %s", 3846 clang_getCString(SearchFileName), SearchLine, SearchColumn, 3847 clang_getCString(KindSpelling)) 3848 << llvm::format("(%s:%d:%d):%s%s", 3849 clang_getCString(ResultFileName), ResultLine, ResultColumn, 3850 clang_getCString(USR), IsDef); 3851 clang_disposeString(SearchFileName); 3852 clang_disposeString(ResultFileName); 3853 clang_disposeString(KindSpelling); 3854 clang_disposeString(USR); 3855 3856 CXCursor Definition = clang_getCursorDefinition(Result); 3857 if (!clang_equalCursors(Definition, clang_getNullCursor())) { 3858 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition); 3859 CXString DefinitionKindSpelling 3860 = clang_getCursorKindSpelling(Definition.kind); 3861 CXFile DefinitionFile; 3862 unsigned DefinitionLine, DefinitionColumn; 3863 clang_getFileLocation(DefinitionLoc, &DefinitionFile, 3864 &DefinitionLine, &DefinitionColumn, 0); 3865 CXString DefinitionFileName = clang_getFileName(DefinitionFile); 3866 *Log << llvm::format(" -> %s(%s:%d:%d)", 3867 clang_getCString(DefinitionKindSpelling), 3868 clang_getCString(DefinitionFileName), 3869 DefinitionLine, DefinitionColumn); 3870 clang_disposeString(DefinitionFileName); 3871 clang_disposeString(DefinitionKindSpelling); 3872 } 3873 } 3874 3875 return Result; 3876} 3877 3878CXCursor clang_getNullCursor(void) { 3879 return MakeCXCursorInvalid(CXCursor_InvalidFile); 3880} 3881 3882unsigned clang_equalCursors(CXCursor X, CXCursor Y) { 3883 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we 3884 // can't set consistently. For example, when visiting a DeclStmt we will set 3885 // it but we don't set it on the result of clang_getCursorDefinition for 3886 // a reference of the same declaration. 3887 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works 3888 // when visiting a DeclStmt currently, the AST should be enhanced to be able 3889 // to provide that kind of info. 3890 if (clang_isDeclaration(X.kind)) 3891 X.data[1] = 0; 3892 if (clang_isDeclaration(Y.kind)) 3893 Y.data[1] = 0; 3894 3895 return X == Y; 3896} 3897 3898unsigned clang_hashCursor(CXCursor C) { 3899 unsigned Index = 0; 3900 if (clang_isExpression(C.kind) || clang_isStatement(C.kind)) 3901 Index = 1; 3902 3903 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue( 3904 std::make_pair(C.kind, C.data[Index])); 3905} 3906 3907unsigned clang_isInvalid(enum CXCursorKind K) { 3908 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid; 3909} 3910 3911unsigned clang_isDeclaration(enum CXCursorKind K) { 3912 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) || 3913 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl); 3914} 3915 3916unsigned clang_isReference(enum CXCursorKind K) { 3917 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef; 3918} 3919 3920unsigned clang_isExpression(enum CXCursorKind K) { 3921 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr; 3922} 3923 3924unsigned clang_isStatement(enum CXCursorKind K) { 3925 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt; 3926} 3927 3928unsigned clang_isAttribute(enum CXCursorKind K) { 3929 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr; 3930} 3931 3932unsigned clang_isTranslationUnit(enum CXCursorKind K) { 3933 return K == CXCursor_TranslationUnit; 3934} 3935 3936unsigned clang_isPreprocessing(enum CXCursorKind K) { 3937 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing; 3938} 3939 3940unsigned clang_isUnexposed(enum CXCursorKind K) { 3941 switch (K) { 3942 case CXCursor_UnexposedDecl: 3943 case CXCursor_UnexposedExpr: 3944 case CXCursor_UnexposedStmt: 3945 case CXCursor_UnexposedAttr: 3946 return true; 3947 default: 3948 return false; 3949 } 3950} 3951 3952CXCursorKind clang_getCursorKind(CXCursor C) { 3953 return C.kind; 3954} 3955 3956CXSourceLocation clang_getCursorLocation(CXCursor C) { 3957 if (clang_isReference(C.kind)) { 3958 switch (C.kind) { 3959 case CXCursor_ObjCSuperClassRef: { 3960 std::pair<const ObjCInterfaceDecl *, SourceLocation> P 3961 = getCursorObjCSuperClassRef(C); 3962 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3963 } 3964 3965 case CXCursor_ObjCProtocolRef: { 3966 std::pair<const ObjCProtocolDecl *, SourceLocation> P 3967 = getCursorObjCProtocolRef(C); 3968 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3969 } 3970 3971 case CXCursor_ObjCClassRef: { 3972 std::pair<const ObjCInterfaceDecl *, SourceLocation> P 3973 = getCursorObjCClassRef(C); 3974 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3975 } 3976 3977 case CXCursor_TypeRef: { 3978 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C); 3979 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3980 } 3981 3982 case CXCursor_TemplateRef: { 3983 std::pair<const TemplateDecl *, SourceLocation> P = 3984 getCursorTemplateRef(C); 3985 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3986 } 3987 3988 case CXCursor_NamespaceRef: { 3989 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C); 3990 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3991 } 3992 3993 case CXCursor_MemberRef: { 3994 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C); 3995 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3996 } 3997 3998 case CXCursor_VariableRef: { 3999 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C); 4000 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 4001 } 4002 4003 case CXCursor_CXXBaseSpecifier: { 4004 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C); 4005 if (!BaseSpec) 4006 return clang_getNullLocation(); 4007 4008 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo()) 4009 return cxloc::translateSourceLocation(getCursorContext(C), 4010 TSInfo->getTypeLoc().getBeginLoc()); 4011 4012 return cxloc::translateSourceLocation(getCursorContext(C), 4013 BaseSpec->getLocStart()); 4014 } 4015 4016 case CXCursor_LabelRef: { 4017 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C); 4018 return cxloc::translateSourceLocation(getCursorContext(C), P.second); 4019 } 4020 4021 case CXCursor_OverloadedDeclRef: 4022 return cxloc::translateSourceLocation(getCursorContext(C), 4023 getCursorOverloadedDeclRef(C).second); 4024 4025 default: 4026 // FIXME: Need a way to enumerate all non-reference cases. 4027 llvm_unreachable("Missed a reference kind"); 4028 } 4029 } 4030 4031 if (clang_isExpression(C.kind)) 4032 return cxloc::translateSourceLocation(getCursorContext(C), 4033 getLocationFromExpr(getCursorExpr(C))); 4034 4035 if (clang_isStatement(C.kind)) 4036 return cxloc::translateSourceLocation(getCursorContext(C), 4037 getCursorStmt(C)->getLocStart()); 4038 4039 if (C.kind == CXCursor_PreprocessingDirective) { 4040 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin(); 4041 return cxloc::translateSourceLocation(getCursorContext(C), L); 4042 } 4043 4044 if (C.kind == CXCursor_MacroExpansion) { 4045 SourceLocation L 4046 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin(); 4047 return cxloc::translateSourceLocation(getCursorContext(C), L); 4048 } 4049 4050 if (C.kind == CXCursor_MacroDefinition) { 4051 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation(); 4052 return cxloc::translateSourceLocation(getCursorContext(C), L); 4053 } 4054 4055 if (C.kind == CXCursor_InclusionDirective) { 4056 SourceLocation L 4057 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin(); 4058 return cxloc::translateSourceLocation(getCursorContext(C), L); 4059 } 4060 4061 if (!clang_isDeclaration(C.kind)) 4062 return clang_getNullLocation(); 4063 4064 Decl *D = getCursorDecl(C); 4065 if (!D) 4066 return clang_getNullLocation(); 4067 4068 SourceLocation Loc = D->getLocation(); 4069 // FIXME: Multiple variables declared in a single declaration 4070 // currently lack the information needed to correctly determine their 4071 // ranges when accounting for the type-specifier. We use context 4072 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, 4073 // and if so, whether it is the first decl. 4074 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 4075 if (!cxcursor::isFirstInDeclGroup(C)) 4076 Loc = VD->getLocation(); 4077 } 4078 4079 // For ObjC methods, give the start location of the method name. 4080 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) 4081 Loc = MD->getSelectorStartLoc(); 4082 4083 return cxloc::translateSourceLocation(getCursorContext(C), Loc); 4084} 4085 4086} // end extern "C" 4087 4088CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) { 4089 assert(TU); 4090 4091 // Guard against an invalid SourceLocation, or we may assert in one 4092 // of the following calls. 4093 if (SLoc.isInvalid()) 4094 return clang_getNullCursor(); 4095 4096 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 4097 4098 // Translate the given source location to make it point at the beginning of 4099 // the token under the cursor. 4100 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(), 4101 CXXUnit->getASTContext().getLangOpts()); 4102 4103 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound); 4104 if (SLoc.isValid()) { 4105 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result); 4106 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData, 4107 /*VisitPreprocessorLast=*/true, 4108 /*VisitIncludedEntities=*/false, 4109 SourceLocation(SLoc)); 4110 CursorVis.visitFileRegion(); 4111 } 4112 4113 return Result; 4114} 4115 4116static SourceRange getRawCursorExtent(CXCursor C) { 4117 if (clang_isReference(C.kind)) { 4118 switch (C.kind) { 4119 case CXCursor_ObjCSuperClassRef: 4120 return getCursorObjCSuperClassRef(C).second; 4121 4122 case CXCursor_ObjCProtocolRef: 4123 return getCursorObjCProtocolRef(C).second; 4124 4125 case CXCursor_ObjCClassRef: 4126 return getCursorObjCClassRef(C).second; 4127 4128 case CXCursor_TypeRef: 4129 return getCursorTypeRef(C).second; 4130 4131 case CXCursor_TemplateRef: 4132 return getCursorTemplateRef(C).second; 4133 4134 case CXCursor_NamespaceRef: 4135 return getCursorNamespaceRef(C).second; 4136 4137 case CXCursor_MemberRef: 4138 return getCursorMemberRef(C).second; 4139 4140 case CXCursor_CXXBaseSpecifier: 4141 return getCursorCXXBaseSpecifier(C)->getSourceRange(); 4142 4143 case CXCursor_LabelRef: 4144 return getCursorLabelRef(C).second; 4145 4146 case CXCursor_OverloadedDeclRef: 4147 return getCursorOverloadedDeclRef(C).second; 4148 4149 case CXCursor_VariableRef: 4150 return getCursorVariableRef(C).second; 4151 4152 default: 4153 // FIXME: Need a way to enumerate all non-reference cases. 4154 llvm_unreachable("Missed a reference kind"); 4155 } 4156 } 4157 4158 if (clang_isExpression(C.kind)) 4159 return getCursorExpr(C)->getSourceRange(); 4160 4161 if (clang_isStatement(C.kind)) 4162 return getCursorStmt(C)->getSourceRange(); 4163 4164 if (clang_isAttribute(C.kind)) 4165 return getCursorAttr(C)->getRange(); 4166 4167 if (C.kind == CXCursor_PreprocessingDirective) 4168 return cxcursor::getCursorPreprocessingDirective(C); 4169 4170 if (C.kind == CXCursor_MacroExpansion) { 4171 ASTUnit *TU = getCursorASTUnit(C); 4172 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange(); 4173 return TU->mapRangeFromPreamble(Range); 4174 } 4175 4176 if (C.kind == CXCursor_MacroDefinition) { 4177 ASTUnit *TU = getCursorASTUnit(C); 4178 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange(); 4179 return TU->mapRangeFromPreamble(Range); 4180 } 4181 4182 if (C.kind == CXCursor_InclusionDirective) { 4183 ASTUnit *TU = getCursorASTUnit(C); 4184 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange(); 4185 return TU->mapRangeFromPreamble(Range); 4186 } 4187 4188 if (C.kind == CXCursor_TranslationUnit) { 4189 ASTUnit *TU = getCursorASTUnit(C); 4190 FileID MainID = TU->getSourceManager().getMainFileID(); 4191 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID); 4192 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID); 4193 return SourceRange(Start, End); 4194 } 4195 4196 if (clang_isDeclaration(C.kind)) { 4197 Decl *D = cxcursor::getCursorDecl(C); 4198 if (!D) 4199 return SourceRange(); 4200 4201 SourceRange R = D->getSourceRange(); 4202 // FIXME: Multiple variables declared in a single declaration 4203 // currently lack the information needed to correctly determine their 4204 // ranges when accounting for the type-specifier. We use context 4205 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, 4206 // and if so, whether it is the first decl. 4207 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 4208 if (!cxcursor::isFirstInDeclGroup(C)) 4209 R.setBegin(VD->getLocation()); 4210 } 4211 return R; 4212 } 4213 return SourceRange(); 4214} 4215 4216/// \brief Retrieves the "raw" cursor extent, which is then extended to include 4217/// the decl-specifier-seq for declarations. 4218static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) { 4219 if (clang_isDeclaration(C.kind)) { 4220 Decl *D = cxcursor::getCursorDecl(C); 4221 if (!D) 4222 return SourceRange(); 4223 4224 SourceRange R = D->getSourceRange(); 4225 4226 // Adjust the start of the location for declarations preceded by 4227 // declaration specifiers. 4228 SourceLocation StartLoc; 4229 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 4230 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) 4231 StartLoc = TI->getTypeLoc().getLocStart(); 4232 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) { 4233 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo()) 4234 StartLoc = TI->getTypeLoc().getLocStart(); 4235 } 4236 4237 if (StartLoc.isValid() && R.getBegin().isValid() && 4238 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin())) 4239 R.setBegin(StartLoc); 4240 4241 // FIXME: Multiple variables declared in a single declaration 4242 // currently lack the information needed to correctly determine their 4243 // ranges when accounting for the type-specifier. We use context 4244 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, 4245 // and if so, whether it is the first decl. 4246 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 4247 if (!cxcursor::isFirstInDeclGroup(C)) 4248 R.setBegin(VD->getLocation()); 4249 } 4250 4251 return R; 4252 } 4253 4254 return getRawCursorExtent(C); 4255} 4256 4257extern "C" { 4258 4259CXSourceRange clang_getCursorExtent(CXCursor C) { 4260 SourceRange R = getRawCursorExtent(C); 4261 if (R.isInvalid()) 4262 return clang_getNullRange(); 4263 4264 return cxloc::translateSourceRange(getCursorContext(C), R); 4265} 4266 4267CXCursor clang_getCursorReferenced(CXCursor C) { 4268 if (clang_isInvalid(C.kind)) 4269 return clang_getNullCursor(); 4270 4271 CXTranslationUnit tu = getCursorTU(C); 4272 if (clang_isDeclaration(C.kind)) { 4273 Decl *D = getCursorDecl(C); 4274 if (!D) 4275 return clang_getNullCursor(); 4276 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) 4277 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu); 4278 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D)) 4279 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl()) 4280 return MakeCXCursor(Property, tu); 4281 4282 return C; 4283 } 4284 4285 if (clang_isExpression(C.kind)) { 4286 Expr *E = getCursorExpr(C); 4287 Decl *D = getDeclFromExpr(E); 4288 if (D) { 4289 CXCursor declCursor = MakeCXCursor(D, tu); 4290 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C), 4291 declCursor); 4292 return declCursor; 4293 } 4294 4295 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E)) 4296 return MakeCursorOverloadedDeclRef(Ovl, tu); 4297 4298 return clang_getNullCursor(); 4299 } 4300 4301 if (clang_isStatement(C.kind)) { 4302 Stmt *S = getCursorStmt(C); 4303 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S)) 4304 if (LabelDecl *label = Goto->getLabel()) 4305 if (LabelStmt *labelS = label->getStmt()) 4306 return MakeCXCursor(labelS, getCursorDecl(C), tu); 4307 4308 return clang_getNullCursor(); 4309 } 4310 4311 if (C.kind == CXCursor_MacroExpansion) { 4312 if (const MacroDefinition *Def = getCursorMacroExpansion(C).getDefinition()) 4313 return MakeMacroDefinitionCursor(Def, tu); 4314 } 4315 4316 if (!clang_isReference(C.kind)) 4317 return clang_getNullCursor(); 4318 4319 switch (C.kind) { 4320 case CXCursor_ObjCSuperClassRef: 4321 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu); 4322 4323 case CXCursor_ObjCProtocolRef: { 4324 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first; 4325 if (const ObjCProtocolDecl *Def = Prot->getDefinition()) 4326 return MakeCXCursor(Def, tu); 4327 4328 return MakeCXCursor(Prot, tu); 4329 } 4330 4331 case CXCursor_ObjCClassRef: { 4332 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first; 4333 if (const ObjCInterfaceDecl *Def = Class->getDefinition()) 4334 return MakeCXCursor(Def, tu); 4335 4336 return MakeCXCursor(Class, tu); 4337 } 4338 4339 case CXCursor_TypeRef: 4340 return MakeCXCursor(getCursorTypeRef(C).first, tu ); 4341 4342 case CXCursor_TemplateRef: 4343 return MakeCXCursor(getCursorTemplateRef(C).first, tu ); 4344 4345 case CXCursor_NamespaceRef: 4346 return MakeCXCursor(getCursorNamespaceRef(C).first, tu ); 4347 4348 case CXCursor_MemberRef: 4349 return MakeCXCursor(getCursorMemberRef(C).first, tu ); 4350 4351 case CXCursor_CXXBaseSpecifier: { 4352 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C); 4353 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(), 4354 tu )); 4355 } 4356 4357 case CXCursor_LabelRef: 4358 // FIXME: We end up faking the "parent" declaration here because we 4359 // don't want to make CXCursor larger. 4360 return MakeCXCursor(getCursorLabelRef(C).first, 4361 static_cast<ASTUnit*>(tu->TUData)->getASTContext() 4362 .getTranslationUnitDecl(), 4363 tu); 4364 4365 case CXCursor_OverloadedDeclRef: 4366 return C; 4367 4368 case CXCursor_VariableRef: 4369 return MakeCXCursor(getCursorVariableRef(C).first, tu); 4370 4371 default: 4372 // We would prefer to enumerate all non-reference cursor kinds here. 4373 llvm_unreachable("Unhandled reference cursor kind"); 4374 } 4375} 4376 4377CXCursor clang_getCursorDefinition(CXCursor C) { 4378 if (clang_isInvalid(C.kind)) 4379 return clang_getNullCursor(); 4380 4381 CXTranslationUnit TU = getCursorTU(C); 4382 4383 bool WasReference = false; 4384 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) { 4385 C = clang_getCursorReferenced(C); 4386 WasReference = true; 4387 } 4388 4389 if (C.kind == CXCursor_MacroExpansion) 4390 return clang_getCursorReferenced(C); 4391 4392 if (!clang_isDeclaration(C.kind)) 4393 return clang_getNullCursor(); 4394 4395 Decl *D = getCursorDecl(C); 4396 if (!D) 4397 return clang_getNullCursor(); 4398 4399 switch (D->getKind()) { 4400 // Declaration kinds that don't really separate the notions of 4401 // declaration and definition. 4402 case Decl::Namespace: 4403 case Decl::Typedef: 4404 case Decl::TypeAlias: 4405 case Decl::TypeAliasTemplate: 4406 case Decl::TemplateTypeParm: 4407 case Decl::EnumConstant: 4408 case Decl::Field: 4409 case Decl::IndirectField: 4410 case Decl::ObjCIvar: 4411 case Decl::ObjCAtDefsField: 4412 case Decl::ImplicitParam: 4413 case Decl::ParmVar: 4414 case Decl::NonTypeTemplateParm: 4415 case Decl::TemplateTemplateParm: 4416 case Decl::ObjCCategoryImpl: 4417 case Decl::ObjCImplementation: 4418 case Decl::AccessSpec: 4419 case Decl::LinkageSpec: 4420 case Decl::ObjCPropertyImpl: 4421 case Decl::FileScopeAsm: 4422 case Decl::StaticAssert: 4423 case Decl::Block: 4424 case Decl::Label: // FIXME: Is this right?? 4425 case Decl::ClassScopeFunctionSpecialization: 4426 case Decl::Import: 4427 return C; 4428 4429 // Declaration kinds that don't make any sense here, but are 4430 // nonetheless harmless. 4431 case Decl::TranslationUnit: 4432 break; 4433 4434 // Declaration kinds for which the definition is not resolvable. 4435 case Decl::UnresolvedUsingTypename: 4436 case Decl::UnresolvedUsingValue: 4437 break; 4438 4439 case Decl::UsingDirective: 4440 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(), 4441 TU); 4442 4443 case Decl::NamespaceAlias: 4444 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU); 4445 4446 case Decl::Enum: 4447 case Decl::Record: 4448 case Decl::CXXRecord: 4449 case Decl::ClassTemplateSpecialization: 4450 case Decl::ClassTemplatePartialSpecialization: 4451 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition()) 4452 return MakeCXCursor(Def, TU); 4453 return clang_getNullCursor(); 4454 4455 case Decl::Function: 4456 case Decl::CXXMethod: 4457 case Decl::CXXConstructor: 4458 case Decl::CXXDestructor: 4459 case Decl::CXXConversion: { 4460 const FunctionDecl *Def = 0; 4461 if (cast<FunctionDecl>(D)->getBody(Def)) 4462 return MakeCXCursor(Def, TU); 4463 return clang_getNullCursor(); 4464 } 4465 4466 case Decl::Var: { 4467 // Ask the variable if it has a definition. 4468 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition()) 4469 return MakeCXCursor(Def, TU); 4470 return clang_getNullCursor(); 4471 } 4472 4473 case Decl::FunctionTemplate: { 4474 const FunctionDecl *Def = 0; 4475 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def)) 4476 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU); 4477 return clang_getNullCursor(); 4478 } 4479 4480 case Decl::ClassTemplate: { 4481 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl() 4482 ->getDefinition()) 4483 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(), 4484 TU); 4485 return clang_getNullCursor(); 4486 } 4487 4488 case Decl::Using: 4489 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D), 4490 D->getLocation(), TU); 4491 4492 case Decl::UsingShadow: 4493 return clang_getCursorDefinition( 4494 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(), 4495 TU)); 4496 4497 case Decl::ObjCMethod: { 4498 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D); 4499 if (Method->isThisDeclarationADefinition()) 4500 return C; 4501 4502 // Dig out the method definition in the associated 4503 // @implementation, if we have it. 4504 // FIXME: The ASTs should make finding the definition easier. 4505 if (ObjCInterfaceDecl *Class 4506 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) 4507 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation()) 4508 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(), 4509 Method->isInstanceMethod())) 4510 if (Def->isThisDeclarationADefinition()) 4511 return MakeCXCursor(Def, TU); 4512 4513 return clang_getNullCursor(); 4514 } 4515 4516 case Decl::ObjCCategory: 4517 if (ObjCCategoryImplDecl *Impl 4518 = cast<ObjCCategoryDecl>(D)->getImplementation()) 4519 return MakeCXCursor(Impl, TU); 4520 return clang_getNullCursor(); 4521 4522 case Decl::ObjCProtocol: 4523 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition()) 4524 return MakeCXCursor(Def, TU); 4525 return clang_getNullCursor(); 4526 4527 case Decl::ObjCInterface: { 4528 // There are two notions of a "definition" for an Objective-C 4529 // class: the interface and its implementation. When we resolved a 4530 // reference to an Objective-C class, produce the @interface as 4531 // the definition; when we were provided with the interface, 4532 // produce the @implementation as the definition. 4533 ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D); 4534 if (WasReference) { 4535 if (ObjCInterfaceDecl *Def = IFace->getDefinition()) 4536 return MakeCXCursor(Def, TU); 4537 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation()) 4538 return MakeCXCursor(Impl, TU); 4539 return clang_getNullCursor(); 4540 } 4541 4542 case Decl::ObjCProperty: 4543 // FIXME: We don't really know where to find the 4544 // ObjCPropertyImplDecls that implement this property. 4545 return clang_getNullCursor(); 4546 4547 case Decl::ObjCCompatibleAlias: 4548 if (ObjCInterfaceDecl *Class 4549 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface()) 4550 if (ObjCInterfaceDecl *Def = Class->getDefinition()) 4551 return MakeCXCursor(Def, TU); 4552 4553 return clang_getNullCursor(); 4554 4555 case Decl::Friend: 4556 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl()) 4557 return clang_getCursorDefinition(MakeCXCursor(Friend, TU)); 4558 return clang_getNullCursor(); 4559 4560 case Decl::FriendTemplate: 4561 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl()) 4562 return clang_getCursorDefinition(MakeCXCursor(Friend, TU)); 4563 return clang_getNullCursor(); 4564 } 4565 4566 return clang_getNullCursor(); 4567} 4568 4569unsigned clang_isCursorDefinition(CXCursor C) { 4570 if (!clang_isDeclaration(C.kind)) 4571 return 0; 4572 4573 return clang_getCursorDefinition(C) == C; 4574} 4575 4576CXCursor clang_getCanonicalCursor(CXCursor C) { 4577 if (!clang_isDeclaration(C.kind)) 4578 return C; 4579 4580 if (Decl *D = getCursorDecl(C)) { 4581 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D)) 4582 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl()) 4583 return MakeCXCursor(CatD, getCursorTU(C)); 4584 4585 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D)) 4586 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface()) 4587 return MakeCXCursor(IFD, getCursorTU(C)); 4588 4589 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C)); 4590 } 4591 4592 return C; 4593} 4594 4595int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) { 4596 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first; 4597} 4598 4599unsigned clang_getNumOverloadedDecls(CXCursor C) { 4600 if (C.kind != CXCursor_OverloadedDeclRef) 4601 return 0; 4602 4603 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first; 4604 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>()) 4605 return E->getNumDecls(); 4606 4607 if (OverloadedTemplateStorage *S 4608 = Storage.dyn_cast<OverloadedTemplateStorage*>()) 4609 return S->size(); 4610 4611 Decl *D = Storage.get<Decl*>(); 4612 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) 4613 return Using->shadow_size(); 4614 4615 return 0; 4616} 4617 4618CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) { 4619 if (cursor.kind != CXCursor_OverloadedDeclRef) 4620 return clang_getNullCursor(); 4621 4622 if (index >= clang_getNumOverloadedDecls(cursor)) 4623 return clang_getNullCursor(); 4624 4625 CXTranslationUnit TU = getCursorTU(cursor); 4626 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first; 4627 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>()) 4628 return MakeCXCursor(E->decls_begin()[index], TU); 4629 4630 if (OverloadedTemplateStorage *S 4631 = Storage.dyn_cast<OverloadedTemplateStorage*>()) 4632 return MakeCXCursor(S->begin()[index], TU); 4633 4634 Decl *D = Storage.get<Decl*>(); 4635 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) { 4636 // FIXME: This is, unfortunately, linear time. 4637 UsingDecl::shadow_iterator Pos = Using->shadow_begin(); 4638 std::advance(Pos, index); 4639 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU); 4640 } 4641 4642 return clang_getNullCursor(); 4643} 4644 4645void clang_getDefinitionSpellingAndExtent(CXCursor C, 4646 const char **startBuf, 4647 const char **endBuf, 4648 unsigned *startLine, 4649 unsigned *startColumn, 4650 unsigned *endLine, 4651 unsigned *endColumn) { 4652 assert(getCursorDecl(C) && "CXCursor has null decl"); 4653 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C)); 4654 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND); 4655 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody()); 4656 4657 SourceManager &SM = FD->getASTContext().getSourceManager(); 4658 *startBuf = SM.getCharacterData(Body->getLBracLoc()); 4659 *endBuf = SM.getCharacterData(Body->getRBracLoc()); 4660 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc()); 4661 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc()); 4662 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc()); 4663 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc()); 4664} 4665 4666 4667CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags, 4668 unsigned PieceIndex) { 4669 RefNamePieces Pieces; 4670 4671 switch (C.kind) { 4672 case CXCursor_MemberRefExpr: 4673 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C))) 4674 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(), 4675 E->getQualifierLoc().getSourceRange()); 4676 break; 4677 4678 case CXCursor_DeclRefExpr: 4679 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) 4680 Pieces = buildPieces(NameFlags, false, E->getNameInfo(), 4681 E->getQualifierLoc().getSourceRange(), 4682 E->getOptionalExplicitTemplateArgs()); 4683 break; 4684 4685 case CXCursor_CallExpr: 4686 if (CXXOperatorCallExpr *OCE = 4687 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) { 4688 Expr *Callee = OCE->getCallee(); 4689 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) 4690 Callee = ICE->getSubExpr(); 4691 4692 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) 4693 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(), 4694 DRE->getQualifierLoc().getSourceRange()); 4695 } 4696 break; 4697 4698 default: 4699 break; 4700 } 4701 4702 if (Pieces.empty()) { 4703 if (PieceIndex == 0) 4704 return clang_getCursorExtent(C); 4705 } else if (PieceIndex < Pieces.size()) { 4706 SourceRange R = Pieces[PieceIndex]; 4707 if (R.isValid()) 4708 return cxloc::translateSourceRange(getCursorContext(C), R); 4709 } 4710 4711 return clang_getNullRange(); 4712} 4713 4714void clang_enableStackTraces(void) { 4715 llvm::sys::PrintStackTraceOnErrorSignal(); 4716} 4717 4718void clang_executeOnThread(void (*fn)(void*), void *user_data, 4719 unsigned stack_size) { 4720 llvm::llvm_execute_on_thread(fn, user_data, stack_size); 4721} 4722 4723} // end: extern "C" 4724 4725//===----------------------------------------------------------------------===// 4726// Token-based Operations. 4727//===----------------------------------------------------------------------===// 4728 4729/* CXToken layout: 4730 * int_data[0]: a CXTokenKind 4731 * int_data[1]: starting token location 4732 * int_data[2]: token length 4733 * int_data[3]: reserved 4734 * ptr_data: for identifiers and keywords, an IdentifierInfo*. 4735 * otherwise unused. 4736 */ 4737extern "C" { 4738 4739CXTokenKind clang_getTokenKind(CXToken CXTok) { 4740 return static_cast<CXTokenKind>(CXTok.int_data[0]); 4741} 4742 4743CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) { 4744 switch (clang_getTokenKind(CXTok)) { 4745 case CXToken_Identifier: 4746 case CXToken_Keyword: 4747 // We know we have an IdentifierInfo*, so use that. 4748 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data) 4749 ->getNameStart()); 4750 4751 case CXToken_Literal: { 4752 // We have stashed the starting pointer in the ptr_data field. Use it. 4753 const char *Text = static_cast<const char *>(CXTok.ptr_data); 4754 return createCXString(StringRef(Text, CXTok.int_data[2])); 4755 } 4756 4757 case CXToken_Punctuation: 4758 case CXToken_Comment: 4759 break; 4760 } 4761 4762 // We have to find the starting buffer pointer the hard way, by 4763 // deconstructing the source location. 4764 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 4765 if (!CXXUnit) 4766 return createCXString(""); 4767 4768 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]); 4769 std::pair<FileID, unsigned> LocInfo 4770 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc); 4771 bool Invalid = false; 4772 StringRef Buffer 4773 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid); 4774 if (Invalid) 4775 return createCXString(""); 4776 4777 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2])); 4778} 4779 4780CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) { 4781 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 4782 if (!CXXUnit) 4783 return clang_getNullLocation(); 4784 4785 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), 4786 SourceLocation::getFromRawEncoding(CXTok.int_data[1])); 4787} 4788 4789CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) { 4790 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 4791 if (!CXXUnit) 4792 return clang_getNullRange(); 4793 4794 return cxloc::translateSourceRange(CXXUnit->getASTContext(), 4795 SourceLocation::getFromRawEncoding(CXTok.int_data[1])); 4796} 4797 4798static void getTokens(ASTUnit *CXXUnit, SourceRange Range, 4799 SmallVectorImpl<CXToken> &CXTokens) { 4800 SourceManager &SourceMgr = CXXUnit->getSourceManager(); 4801 std::pair<FileID, unsigned> BeginLocInfo 4802 = SourceMgr.getDecomposedLoc(Range.getBegin()); 4803 std::pair<FileID, unsigned> EndLocInfo 4804 = SourceMgr.getDecomposedLoc(Range.getEnd()); 4805 4806 // Cannot tokenize across files. 4807 if (BeginLocInfo.first != EndLocInfo.first) 4808 return; 4809 4810 // Create a lexer 4811 bool Invalid = false; 4812 StringRef Buffer 4813 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid); 4814 if (Invalid) 4815 return; 4816 4817 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first), 4818 CXXUnit->getASTContext().getLangOpts(), 4819 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end()); 4820 Lex.SetCommentRetentionState(true); 4821 4822 // Lex tokens until we hit the end of the range. 4823 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second; 4824 Token Tok; 4825 bool previousWasAt = false; 4826 do { 4827 // Lex the next token 4828 Lex.LexFromRawLexer(Tok); 4829 if (Tok.is(tok::eof)) 4830 break; 4831 4832 // Initialize the CXToken. 4833 CXToken CXTok; 4834 4835 // - Common fields 4836 CXTok.int_data[1] = Tok.getLocation().getRawEncoding(); 4837 CXTok.int_data[2] = Tok.getLength(); 4838 CXTok.int_data[3] = 0; 4839 4840 // - Kind-specific fields 4841 if (Tok.isLiteral()) { 4842 CXTok.int_data[0] = CXToken_Literal; 4843 CXTok.ptr_data = (void *)Tok.getLiteralData(); 4844 } else if (Tok.is(tok::raw_identifier)) { 4845 // Lookup the identifier to determine whether we have a keyword. 4846 IdentifierInfo *II 4847 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok); 4848 4849 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) { 4850 CXTok.int_data[0] = CXToken_Keyword; 4851 } 4852 else { 4853 CXTok.int_data[0] = Tok.is(tok::identifier) 4854 ? CXToken_Identifier 4855 : CXToken_Keyword; 4856 } 4857 CXTok.ptr_data = II; 4858 } else if (Tok.is(tok::comment)) { 4859 CXTok.int_data[0] = CXToken_Comment; 4860 CXTok.ptr_data = 0; 4861 } else { 4862 CXTok.int_data[0] = CXToken_Punctuation; 4863 CXTok.ptr_data = 0; 4864 } 4865 CXTokens.push_back(CXTok); 4866 previousWasAt = Tok.is(tok::at); 4867 } while (Lex.getBufferLocation() <= EffectiveBufferEnd); 4868} 4869 4870void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range, 4871 CXToken **Tokens, unsigned *NumTokens) { 4872 LOG_FUNC_SECTION { 4873 *Log << TU << ' ' << Range; 4874 } 4875 4876 if (Tokens) 4877 *Tokens = 0; 4878 if (NumTokens) 4879 *NumTokens = 0; 4880 4881 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 4882 if (!CXXUnit || !Tokens || !NumTokens) 4883 return; 4884 4885 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 4886 4887 SourceRange R = cxloc::translateCXSourceRange(Range); 4888 if (R.isInvalid()) 4889 return; 4890 4891 SmallVector<CXToken, 32> CXTokens; 4892 getTokens(CXXUnit, R, CXTokens); 4893 4894 if (CXTokens.empty()) 4895 return; 4896 4897 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size()); 4898 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size()); 4899 *NumTokens = CXTokens.size(); 4900} 4901 4902void clang_disposeTokens(CXTranslationUnit TU, 4903 CXToken *Tokens, unsigned NumTokens) { 4904 free(Tokens); 4905} 4906 4907} // end: extern "C" 4908 4909//===----------------------------------------------------------------------===// 4910// Token annotation APIs. 4911//===----------------------------------------------------------------------===// 4912 4913static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor, 4914 CXCursor parent, 4915 CXClientData client_data); 4916static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor, 4917 CXClientData client_data); 4918 4919namespace { 4920class AnnotateTokensWorker { 4921 CXToken *Tokens; 4922 CXCursor *Cursors; 4923 unsigned NumTokens; 4924 unsigned TokIdx; 4925 unsigned PreprocessingTokIdx; 4926 CursorVisitor AnnotateVis; 4927 SourceManager &SrcMgr; 4928 bool HasContextSensitiveKeywords; 4929 4930 struct PostChildrenInfo { 4931 CXCursor Cursor; 4932 SourceRange CursorRange; 4933 unsigned BeforeChildrenTokenIdx; 4934 }; 4935 SmallVector<PostChildrenInfo, 8> PostChildrenInfos; 4936 4937 bool MoreTokens() const { return TokIdx < NumTokens; } 4938 unsigned NextToken() const { return TokIdx; } 4939 void AdvanceToken() { ++TokIdx; } 4940 SourceLocation GetTokenLoc(unsigned tokI) { 4941 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]); 4942 } 4943 bool isFunctionMacroToken(unsigned tokI) const { 4944 return Tokens[tokI].int_data[3] != 0; 4945 } 4946 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const { 4947 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]); 4948 } 4949 4950 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange); 4951 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult, 4952 SourceRange); 4953 4954public: 4955 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens, 4956 CXTranslationUnit tu, SourceRange RegionOfInterest) 4957 : Tokens(tokens), Cursors(cursors), 4958 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0), 4959 AnnotateVis(tu, 4960 AnnotateTokensVisitor, this, 4961 /*VisitPreprocessorLast=*/true, 4962 /*VisitIncludedEntities=*/false, 4963 RegionOfInterest, 4964 /*VisitDeclsOnly=*/false, 4965 AnnotateTokensPostChildrenVisitor), 4966 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()), 4967 HasContextSensitiveKeywords(false) { } 4968 4969 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); } 4970 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent); 4971 bool postVisitChildren(CXCursor cursor); 4972 void AnnotateTokens(); 4973 4974 /// \brief Determine whether the annotator saw any cursors that have 4975 /// context-sensitive keywords. 4976 bool hasContextSensitiveKeywords() const { 4977 return HasContextSensitiveKeywords; 4978 } 4979 4980 ~AnnotateTokensWorker() { 4981 assert(PostChildrenInfos.empty()); 4982 } 4983}; 4984} 4985 4986void AnnotateTokensWorker::AnnotateTokens() { 4987 // Walk the AST within the region of interest, annotating tokens 4988 // along the way. 4989 AnnotateVis.visitFileRegion(); 4990} 4991 4992static inline void updateCursorAnnotation(CXCursor &Cursor, 4993 const CXCursor &updateC) { 4994 if (clang_isInvalid(updateC.kind) || clang_isPreprocessing(Cursor.kind)) 4995 return; 4996 Cursor = updateC; 4997} 4998 4999/// \brief It annotates and advances tokens with a cursor until the comparison 5000//// between the cursor location and the source range is the same as 5001/// \arg compResult. 5002/// 5003/// Pass RangeBefore to annotate tokens with a cursor until a range is reached. 5004/// Pass RangeOverlap to annotate tokens inside a range. 5005void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC, 5006 RangeComparisonResult compResult, 5007 SourceRange range) { 5008 while (MoreTokens()) { 5009 const unsigned I = NextToken(); 5010 if (isFunctionMacroToken(I)) 5011 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range); 5012 5013 SourceLocation TokLoc = GetTokenLoc(I); 5014 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) { 5015 updateCursorAnnotation(Cursors[I], updateC); 5016 AdvanceToken(); 5017 continue; 5018 } 5019 break; 5020 } 5021} 5022 5023/// \brief Special annotation handling for macro argument tokens. 5024void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens( 5025 CXCursor updateC, 5026 RangeComparisonResult compResult, 5027 SourceRange range) { 5028 assert(MoreTokens()); 5029 assert(isFunctionMacroToken(NextToken()) && 5030 "Should be called only for macro arg tokens"); 5031 5032 // This works differently than annotateAndAdvanceTokens; because expanded 5033 // macro arguments can have arbitrary translation-unit source order, we do not 5034 // advance the token index one by one until a token fails the range test. 5035 // We only advance once past all of the macro arg tokens if all of them 5036 // pass the range test. If one of them fails we keep the token index pointing 5037 // at the start of the macro arg tokens so that the failing token will be 5038 // annotated by a subsequent annotation try. 5039 5040 bool atLeastOneCompFail = false; 5041 5042 unsigned I = NextToken(); 5043 for (; I < NumTokens && isFunctionMacroToken(I); ++I) { 5044 SourceLocation TokLoc = getFunctionMacroTokenLoc(I); 5045 if (TokLoc.isFileID()) 5046 continue; // not macro arg token, it's parens or comma. 5047 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) { 5048 if (clang_isInvalid(clang_getCursorKind(Cursors[I]))) 5049 Cursors[I] = updateC; 5050 } else 5051 atLeastOneCompFail = true; 5052 } 5053 5054 if (!atLeastOneCompFail) 5055 TokIdx = I; // All of the tokens were handled, advance beyond all of them. 5056} 5057 5058enum CXChildVisitResult 5059AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) { 5060 SourceRange cursorRange = getRawCursorExtent(cursor); 5061 if (cursorRange.isInvalid()) 5062 return CXChildVisit_Recurse; 5063 5064 if (!HasContextSensitiveKeywords) { 5065 // Objective-C properties can have context-sensitive keywords. 5066 if (cursor.kind == CXCursor_ObjCPropertyDecl) { 5067 if (ObjCPropertyDecl *Property 5068 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor))) 5069 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0; 5070 } 5071 // Objective-C methods can have context-sensitive keywords. 5072 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl || 5073 cursor.kind == CXCursor_ObjCClassMethodDecl) { 5074 if (ObjCMethodDecl *Method 5075 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) { 5076 if (Method->getObjCDeclQualifier()) 5077 HasContextSensitiveKeywords = true; 5078 else { 5079 for (ObjCMethodDecl::param_iterator P = Method->param_begin(), 5080 PEnd = Method->param_end(); 5081 P != PEnd; ++P) { 5082 if ((*P)->getObjCDeclQualifier()) { 5083 HasContextSensitiveKeywords = true; 5084 break; 5085 } 5086 } 5087 } 5088 } 5089 } 5090 // C++ methods can have context-sensitive keywords. 5091 else if (cursor.kind == CXCursor_CXXMethod) { 5092 if (CXXMethodDecl *Method 5093 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) { 5094 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>()) 5095 HasContextSensitiveKeywords = true; 5096 } 5097 } 5098 // C++ classes can have context-sensitive keywords. 5099 else if (cursor.kind == CXCursor_StructDecl || 5100 cursor.kind == CXCursor_ClassDecl || 5101 cursor.kind == CXCursor_ClassTemplate || 5102 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) { 5103 if (Decl *D = getCursorDecl(cursor)) 5104 if (D->hasAttr<FinalAttr>()) 5105 HasContextSensitiveKeywords = true; 5106 } 5107 } 5108 5109 if (clang_isPreprocessing(cursor.kind)) { 5110 // Items in the preprocessing record are kept separate from items in 5111 // declarations, so we keep a separate token index. 5112 unsigned SavedTokIdx = TokIdx; 5113 TokIdx = PreprocessingTokIdx; 5114 5115 // Skip tokens up until we catch up to the beginning of the preprocessing 5116 // entry. 5117 while (MoreTokens()) { 5118 const unsigned I = NextToken(); 5119 SourceLocation TokLoc = GetTokenLoc(I); 5120 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 5121 case RangeBefore: 5122 AdvanceToken(); 5123 continue; 5124 case RangeAfter: 5125 case RangeOverlap: 5126 break; 5127 } 5128 break; 5129 } 5130 5131 // Look at all of the tokens within this range. 5132 while (MoreTokens()) { 5133 const unsigned I = NextToken(); 5134 SourceLocation TokLoc = GetTokenLoc(I); 5135 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 5136 case RangeBefore: 5137 llvm_unreachable("Infeasible"); 5138 case RangeAfter: 5139 break; 5140 case RangeOverlap: 5141 // We may have already annotated macro names inside macro definitions. 5142 if (Cursors[I].kind != CXCursor_MacroExpansion) 5143 Cursors[I] = cursor; 5144 AdvanceToken(); 5145 // For macro expansions, just note where the beginning of the macro 5146 // expansion occurs. 5147 if (cursor.kind == CXCursor_MacroExpansion) 5148 break; 5149 continue; 5150 } 5151 break; 5152 } 5153 5154 // Save the preprocessing token index; restore the non-preprocessing 5155 // token index. 5156 PreprocessingTokIdx = TokIdx; 5157 TokIdx = SavedTokIdx; 5158 return CXChildVisit_Recurse; 5159 } 5160 5161 if (cursorRange.isInvalid()) 5162 return CXChildVisit_Continue; 5163 5164 const enum CXCursorKind cursorK = clang_getCursorKind(cursor); 5165 const enum CXCursorKind K = clang_getCursorKind(parent); 5166 const CXCursor updateC = 5167 (clang_isInvalid(K) || K == CXCursor_TranslationUnit) 5168 ? clang_getNullCursor() : parent; 5169 5170 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange); 5171 5172 // Avoid having the cursor of an expression "overwrite" the annotation of the 5173 // variable declaration that it belongs to. 5174 // This can happen for C++ constructor expressions whose range generally 5175 // include the variable declaration, e.g.: 5176 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor. 5177 if (clang_isExpression(cursorK)) { 5178 Expr *E = getCursorExpr(cursor); 5179 if (Decl *D = getCursorParentDecl(cursor)) { 5180 const unsigned I = NextToken(); 5181 if (E->getLocStart().isValid() && D->getLocation().isValid() && 5182 E->getLocStart() == D->getLocation() && 5183 E->getLocStart() == GetTokenLoc(I)) { 5184 updateCursorAnnotation(Cursors[I], updateC); 5185 AdvanceToken(); 5186 } 5187 } 5188 } 5189 5190 // Before recursing into the children keep some state that we are going 5191 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some 5192 // extra work after the child nodes are visited. 5193 // Note that we don't call VisitChildren here to avoid traversing statements 5194 // code-recursively which can blow the stack. 5195 5196 PostChildrenInfo Info; 5197 Info.Cursor = cursor; 5198 Info.CursorRange = cursorRange; 5199 Info.BeforeChildrenTokenIdx = NextToken(); 5200 PostChildrenInfos.push_back(Info); 5201 5202 return CXChildVisit_Recurse; 5203} 5204 5205bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) { 5206 if (PostChildrenInfos.empty()) 5207 return false; 5208 const PostChildrenInfo &Info = PostChildrenInfos.back(); 5209 if (!clang_equalCursors(Info.Cursor, cursor)) 5210 return false; 5211 5212 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx; 5213 const unsigned AfterChildren = NextToken(); 5214 SourceRange cursorRange = Info.CursorRange; 5215 5216 // Scan the tokens that are at the end of the cursor, but are not captured 5217 // but the child cursors. 5218 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange); 5219 5220 // Scan the tokens that are at the beginning of the cursor, but are not 5221 // capture by the child cursors. 5222 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) { 5223 if (!clang_isInvalid(clang_getCursorKind(Cursors[I]))) 5224 break; 5225 5226 Cursors[I] = cursor; 5227 } 5228 5229 PostChildrenInfos.pop_back(); 5230 return false; 5231} 5232 5233static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor, 5234 CXCursor parent, 5235 CXClientData client_data) { 5236 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent); 5237} 5238 5239static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor, 5240 CXClientData client_data) { 5241 return static_cast<AnnotateTokensWorker*>(client_data)-> 5242 postVisitChildren(cursor); 5243} 5244 5245namespace { 5246 5247/// \brief Uses the macro expansions in the preprocessing record to find 5248/// and mark tokens that are macro arguments. This info is used by the 5249/// AnnotateTokensWorker. 5250class MarkMacroArgTokensVisitor { 5251 SourceManager &SM; 5252 CXToken *Tokens; 5253 unsigned NumTokens; 5254 unsigned CurIdx; 5255 5256public: 5257 MarkMacroArgTokensVisitor(SourceManager &SM, 5258 CXToken *tokens, unsigned numTokens) 5259 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { } 5260 5261 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) { 5262 if (cursor.kind != CXCursor_MacroExpansion) 5263 return CXChildVisit_Continue; 5264 5265 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange(); 5266 if (macroRange.getBegin() == macroRange.getEnd()) 5267 return CXChildVisit_Continue; // it's not a function macro. 5268 5269 for (; CurIdx < NumTokens; ++CurIdx) { 5270 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx), 5271 macroRange.getBegin())) 5272 break; 5273 } 5274 5275 if (CurIdx == NumTokens) 5276 return CXChildVisit_Break; 5277 5278 for (; CurIdx < NumTokens; ++CurIdx) { 5279 SourceLocation tokLoc = getTokenLoc(CurIdx); 5280 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd())) 5281 break; 5282 5283 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc)); 5284 } 5285 5286 if (CurIdx == NumTokens) 5287 return CXChildVisit_Break; 5288 5289 return CXChildVisit_Continue; 5290 } 5291 5292private: 5293 SourceLocation getTokenLoc(unsigned tokI) { 5294 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]); 5295 } 5296 5297 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) { 5298 // The third field is reserved and currently not used. Use it here 5299 // to mark macro arg expanded tokens with their expanded locations. 5300 Tokens[tokI].int_data[3] = loc.getRawEncoding(); 5301 } 5302}; 5303 5304} // end anonymous namespace 5305 5306static CXChildVisitResult 5307MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent, 5308 CXClientData client_data) { 5309 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor, 5310 parent); 5311} 5312 5313namespace { 5314 struct clang_annotateTokens_Data { 5315 CXTranslationUnit TU; 5316 ASTUnit *CXXUnit; 5317 CXToken *Tokens; 5318 unsigned NumTokens; 5319 CXCursor *Cursors; 5320 }; 5321} 5322 5323/// \brief Used by \c annotatePreprocessorTokens. 5324/// \returns true if lexing was finished, false otherwise. 5325static bool lexNext(Lexer &Lex, Token &Tok, 5326 unsigned &NextIdx, unsigned NumTokens) { 5327 if (NextIdx >= NumTokens) 5328 return true; 5329 5330 ++NextIdx; 5331 Lex.LexFromRawLexer(Tok); 5332 if (Tok.is(tok::eof)) 5333 return true; 5334 5335 return false; 5336} 5337 5338static void annotatePreprocessorTokens(CXTranslationUnit TU, 5339 SourceRange RegionOfInterest, 5340 CXCursor *Cursors, 5341 CXToken *Tokens, 5342 unsigned NumTokens) { 5343 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 5344 5345 Preprocessor &PP = CXXUnit->getPreprocessor(); 5346 SourceManager &SourceMgr = CXXUnit->getSourceManager(); 5347 std::pair<FileID, unsigned> BeginLocInfo 5348 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin()); 5349 std::pair<FileID, unsigned> EndLocInfo 5350 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd()); 5351 5352 if (BeginLocInfo.first != EndLocInfo.first) 5353 return; 5354 5355 StringRef Buffer; 5356 bool Invalid = false; 5357 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid); 5358 if (Buffer.empty() || Invalid) 5359 return; 5360 5361 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first), 5362 CXXUnit->getASTContext().getLangOpts(), 5363 Buffer.begin(), Buffer.data() + BeginLocInfo.second, 5364 Buffer.end()); 5365 Lex.SetCommentRetentionState(true); 5366 5367 unsigned NextIdx = 0; 5368 // Lex tokens in raw mode until we hit the end of the range, to avoid 5369 // entering #includes or expanding macros. 5370 while (true) { 5371 Token Tok; 5372 if (lexNext(Lex, Tok, NextIdx, NumTokens)) 5373 break; 5374 unsigned TokIdx = NextIdx-1; 5375 assert(Tok.getLocation() == 5376 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1])); 5377 5378 reprocess: 5379 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) { 5380 // We have found a preprocessing directive. Annotate the tokens 5381 // appropriately. 5382 // 5383 // FIXME: Some simple tests here could identify macro definitions and 5384 // #undefs, to provide specific cursor kinds for those. 5385 5386 SourceLocation BeginLoc = Tok.getLocation(); 5387 if (lexNext(Lex, Tok, NextIdx, NumTokens)) 5388 break; 5389 5390 MacroInfo *MI = 0; 5391 if (Tok.is(tok::raw_identifier) && 5392 StringRef(Tok.getRawIdentifierData(), Tok.getLength()) == "define") { 5393 if (lexNext(Lex, Tok, NextIdx, NumTokens)) 5394 break; 5395 5396 if (Tok.is(tok::raw_identifier)) { 5397 StringRef Name(Tok.getRawIdentifierData(), Tok.getLength()); 5398 IdentifierInfo &II = PP.getIdentifierTable().get(Name); 5399 SourceLocation MappedTokLoc = 5400 CXXUnit->mapLocationToPreamble(Tok.getLocation()); 5401 MI = getMacroInfo(II, MappedTokLoc, TU); 5402 } 5403 } 5404 5405 bool finished = false; 5406 do { 5407 if (lexNext(Lex, Tok, NextIdx, NumTokens)) { 5408 finished = true; 5409 break; 5410 } 5411 // If we are in a macro definition, check if the token was ever a 5412 // macro name and annotate it if that's the case. 5413 if (MI) { 5414 SourceLocation SaveLoc = Tok.getLocation(); 5415 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc)); 5416 MacroDefinition *MacroDef = checkForMacroInMacroDefinition(MI,Tok,TU); 5417 Tok.setLocation(SaveLoc); 5418 if (MacroDef) 5419 Cursors[NextIdx-1] = MakeMacroExpansionCursor(MacroDef, 5420 Tok.getLocation(), TU); 5421 } 5422 } while (!Tok.isAtStartOfLine()); 5423 5424 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2; 5425 assert(TokIdx <= LastIdx); 5426 SourceLocation EndLoc = 5427 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]); 5428 CXCursor Cursor = 5429 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU); 5430 5431 for (; TokIdx <= LastIdx; ++TokIdx) 5432 updateCursorAnnotation(Cursors[TokIdx], Cursor); 5433 5434 if (finished) 5435 break; 5436 goto reprocess; 5437 } 5438 } 5439} 5440 5441// This gets run a separate thread to avoid stack blowout. 5442static void clang_annotateTokensImpl(void *UserData) { 5443 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU; 5444 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit; 5445 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens; 5446 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens; 5447 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors; 5448 5449 CIndexer *CXXIdx = (CIndexer*)TU->CIdx; 5450 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing)) 5451 setThreadBackgroundPriority(); 5452 5453 // Determine the region of interest, which contains all of the tokens. 5454 SourceRange RegionOfInterest; 5455 RegionOfInterest.setBegin( 5456 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0]))); 5457 RegionOfInterest.setEnd( 5458 cxloc::translateSourceLocation(clang_getTokenLocation(TU, 5459 Tokens[NumTokens-1]))); 5460 5461 // Relex the tokens within the source range to look for preprocessing 5462 // directives. 5463 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens); 5464 5465 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) { 5466 // Search and mark tokens that are macro argument expansions. 5467 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(), 5468 Tokens, NumTokens); 5469 CursorVisitor MacroArgMarker(TU, 5470 MarkMacroArgTokensVisitorDelegate, &Visitor, 5471 /*VisitPreprocessorLast=*/true, 5472 /*VisitIncludedEntities=*/false, 5473 RegionOfInterest); 5474 MacroArgMarker.visitPreprocessedEntitiesInRegion(); 5475 } 5476 5477 // Annotate all of the source locations in the region of interest that map to 5478 // a specific cursor. 5479 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest); 5480 5481 // FIXME: We use a ridiculous stack size here because the data-recursion 5482 // algorithm uses a large stack frame than the non-data recursive version, 5483 // and AnnotationTokensWorker currently transforms the data-recursion 5484 // algorithm back into a traditional recursion by explicitly calling 5485 // VisitChildren(). We will need to remove this explicit recursive call. 5486 W.AnnotateTokens(); 5487 5488 // If we ran into any entities that involve context-sensitive keywords, 5489 // take another pass through the tokens to mark them as such. 5490 if (W.hasContextSensitiveKeywords()) { 5491 for (unsigned I = 0; I != NumTokens; ++I) { 5492 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier) 5493 continue; 5494 5495 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) { 5496 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data); 5497 if (ObjCPropertyDecl *Property 5498 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) { 5499 if (Property->getPropertyAttributesAsWritten() != 0 && 5500 llvm::StringSwitch<bool>(II->getName()) 5501 .Case("readonly", true) 5502 .Case("assign", true) 5503 .Case("unsafe_unretained", true) 5504 .Case("readwrite", true) 5505 .Case("retain", true) 5506 .Case("copy", true) 5507 .Case("nonatomic", true) 5508 .Case("atomic", true) 5509 .Case("getter", true) 5510 .Case("setter", true) 5511 .Case("strong", true) 5512 .Case("weak", true) 5513 .Default(false)) 5514 Tokens[I].int_data[0] = CXToken_Keyword; 5515 } 5516 continue; 5517 } 5518 5519 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl || 5520 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) { 5521 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data); 5522 if (llvm::StringSwitch<bool>(II->getName()) 5523 .Case("in", true) 5524 .Case("out", true) 5525 .Case("inout", true) 5526 .Case("oneway", true) 5527 .Case("bycopy", true) 5528 .Case("byref", true) 5529 .Default(false)) 5530 Tokens[I].int_data[0] = CXToken_Keyword; 5531 continue; 5532 } 5533 5534 if (Cursors[I].kind == CXCursor_CXXFinalAttr || 5535 Cursors[I].kind == CXCursor_CXXOverrideAttr) { 5536 Tokens[I].int_data[0] = CXToken_Keyword; 5537 continue; 5538 } 5539 } 5540 } 5541} 5542 5543extern "C" { 5544 5545void clang_annotateTokens(CXTranslationUnit TU, 5546 CXToken *Tokens, unsigned NumTokens, 5547 CXCursor *Cursors) { 5548 if (NumTokens == 0 || !Tokens || !Cursors) { 5549 LOG_FUNC_SECTION { *Log << "<null input>"; } 5550 return; 5551 } 5552 5553 LOG_FUNC_SECTION { 5554 *Log << TU << ' '; 5555 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]); 5556 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]); 5557 *Log << clang_getRange(bloc, eloc); 5558 } 5559 5560 // Any token we don't specifically annotate will have a NULL cursor. 5561 CXCursor C = clang_getNullCursor(); 5562 for (unsigned I = 0; I != NumTokens; ++I) 5563 Cursors[I] = C; 5564 5565 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 5566 if (!CXXUnit) 5567 return; 5568 5569 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 5570 5571 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors }; 5572 llvm::CrashRecoveryContext CRC; 5573 if (!RunSafely(CRC, clang_annotateTokensImpl, &data, 5574 GetSafetyThreadStackSize() * 2)) { 5575 fprintf(stderr, "libclang: crash detected while annotating tokens\n"); 5576 } 5577} 5578 5579} // end: extern "C" 5580 5581//===----------------------------------------------------------------------===// 5582// Operations for querying linkage of a cursor. 5583//===----------------------------------------------------------------------===// 5584 5585extern "C" { 5586CXLinkageKind clang_getCursorLinkage(CXCursor cursor) { 5587 if (!clang_isDeclaration(cursor.kind)) 5588 return CXLinkage_Invalid; 5589 5590 Decl *D = cxcursor::getCursorDecl(cursor); 5591 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D)) 5592 switch (ND->getLinkage()) { 5593 case NoLinkage: return CXLinkage_NoLinkage; 5594 case InternalLinkage: return CXLinkage_Internal; 5595 case UniqueExternalLinkage: return CXLinkage_UniqueExternal; 5596 case ExternalLinkage: return CXLinkage_External; 5597 }; 5598 5599 return CXLinkage_Invalid; 5600} 5601} // end: extern "C" 5602 5603//===----------------------------------------------------------------------===// 5604// Operations for querying language of a cursor. 5605//===----------------------------------------------------------------------===// 5606 5607static CXLanguageKind getDeclLanguage(const Decl *D) { 5608 if (!D) 5609 return CXLanguage_C; 5610 5611 switch (D->getKind()) { 5612 default: 5613 break; 5614 case Decl::ImplicitParam: 5615 case Decl::ObjCAtDefsField: 5616 case Decl::ObjCCategory: 5617 case Decl::ObjCCategoryImpl: 5618 case Decl::ObjCCompatibleAlias: 5619 case Decl::ObjCImplementation: 5620 case Decl::ObjCInterface: 5621 case Decl::ObjCIvar: 5622 case Decl::ObjCMethod: 5623 case Decl::ObjCProperty: 5624 case Decl::ObjCPropertyImpl: 5625 case Decl::ObjCProtocol: 5626 return CXLanguage_ObjC; 5627 case Decl::CXXConstructor: 5628 case Decl::CXXConversion: 5629 case Decl::CXXDestructor: 5630 case Decl::CXXMethod: 5631 case Decl::CXXRecord: 5632 case Decl::ClassTemplate: 5633 case Decl::ClassTemplatePartialSpecialization: 5634 case Decl::ClassTemplateSpecialization: 5635 case Decl::Friend: 5636 case Decl::FriendTemplate: 5637 case Decl::FunctionTemplate: 5638 case Decl::LinkageSpec: 5639 case Decl::Namespace: 5640 case Decl::NamespaceAlias: 5641 case Decl::NonTypeTemplateParm: 5642 case Decl::StaticAssert: 5643 case Decl::TemplateTemplateParm: 5644 case Decl::TemplateTypeParm: 5645 case Decl::UnresolvedUsingTypename: 5646 case Decl::UnresolvedUsingValue: 5647 case Decl::Using: 5648 case Decl::UsingDirective: 5649 case Decl::UsingShadow: 5650 return CXLanguage_CPlusPlus; 5651 } 5652 5653 return CXLanguage_C; 5654} 5655 5656extern "C" { 5657 5658enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) { 5659 if (clang_isDeclaration(cursor.kind)) 5660 if (Decl *D = cxcursor::getCursorDecl(cursor)) { 5661 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()) 5662 return CXAvailability_Available; 5663 5664 switch (D->getAvailability()) { 5665 case AR_Available: 5666 case AR_NotYetIntroduced: 5667 return CXAvailability_Available; 5668 5669 case AR_Deprecated: 5670 return CXAvailability_Deprecated; 5671 5672 case AR_Unavailable: 5673 return CXAvailability_NotAvailable; 5674 } 5675 } 5676 5677 return CXAvailability_Available; 5678} 5679 5680static CXVersion convertVersion(VersionTuple In) { 5681 CXVersion Out = { -1, -1, -1 }; 5682 if (In.empty()) 5683 return Out; 5684 5685 Out.Major = In.getMajor(); 5686 5687 if (llvm::Optional<unsigned> Minor = In.getMinor()) 5688 Out.Minor = *Minor; 5689 else 5690 return Out; 5691 5692 if (llvm::Optional<unsigned> Subminor = In.getSubminor()) 5693 Out.Subminor = *Subminor; 5694 5695 return Out; 5696} 5697 5698int clang_getCursorPlatformAvailability(CXCursor cursor, 5699 int *always_deprecated, 5700 CXString *deprecated_message, 5701 int *always_unavailable, 5702 CXString *unavailable_message, 5703 CXPlatformAvailability *availability, 5704 int availability_size) { 5705 if (always_deprecated) 5706 *always_deprecated = 0; 5707 if (deprecated_message) 5708 *deprecated_message = cxstring::createCXString("", /*DupString=*/false); 5709 if (always_unavailable) 5710 *always_unavailable = 0; 5711 if (unavailable_message) 5712 *unavailable_message = cxstring::createCXString("", /*DupString=*/false); 5713 5714 if (!clang_isDeclaration(cursor.kind)) 5715 return 0; 5716 5717 Decl *D = cxcursor::getCursorDecl(cursor); 5718 if (!D) 5719 return 0; 5720 5721 int N = 0; 5722 for (Decl::attr_iterator A = D->attr_begin(), AEnd = D->attr_end(); A != AEnd; 5723 ++A) { 5724 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(*A)) { 5725 if (always_deprecated) 5726 *always_deprecated = 1; 5727 if (deprecated_message) 5728 *deprecated_message = cxstring::createCXString(Deprecated->getMessage()); 5729 continue; 5730 } 5731 5732 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(*A)) { 5733 if (always_unavailable) 5734 *always_unavailable = 1; 5735 if (unavailable_message) { 5736 *unavailable_message 5737 = cxstring::createCXString(Unavailable->getMessage()); 5738 } 5739 continue; 5740 } 5741 5742 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(*A)) { 5743 if (N < availability_size) { 5744 availability[N].Platform 5745 = cxstring::createCXString(Avail->getPlatform()->getName()); 5746 availability[N].Introduced = convertVersion(Avail->getIntroduced()); 5747 availability[N].Deprecated = convertVersion(Avail->getDeprecated()); 5748 availability[N].Obsoleted = convertVersion(Avail->getObsoleted()); 5749 availability[N].Unavailable = Avail->getUnavailable(); 5750 availability[N].Message = cxstring::createCXString(Avail->getMessage()); 5751 } 5752 ++N; 5753 } 5754 } 5755 5756 return N; 5757} 5758 5759void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) { 5760 clang_disposeString(availability->Platform); 5761 clang_disposeString(availability->Message); 5762} 5763 5764CXLanguageKind clang_getCursorLanguage(CXCursor cursor) { 5765 if (clang_isDeclaration(cursor.kind)) 5766 return getDeclLanguage(cxcursor::getCursorDecl(cursor)); 5767 5768 return CXLanguage_Invalid; 5769} 5770 5771 /// \brief If the given cursor is the "templated" declaration 5772 /// descibing a class or function template, return the class or 5773 /// function template. 5774static Decl *maybeGetTemplateCursor(Decl *D) { 5775 if (!D) 5776 return 0; 5777 5778 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 5779 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate()) 5780 return FunTmpl; 5781 5782 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) 5783 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate()) 5784 return ClassTmpl; 5785 5786 return D; 5787} 5788 5789CXCursor clang_getCursorSemanticParent(CXCursor cursor) { 5790 if (clang_isDeclaration(cursor.kind)) { 5791 if (Decl *D = getCursorDecl(cursor)) { 5792 DeclContext *DC = D->getDeclContext(); 5793 if (!DC) 5794 return clang_getNullCursor(); 5795 5796 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)), 5797 getCursorTU(cursor)); 5798 } 5799 } 5800 5801 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) { 5802 if (Decl *D = getCursorDecl(cursor)) 5803 return MakeCXCursor(D, getCursorTU(cursor)); 5804 } 5805 5806 return clang_getNullCursor(); 5807} 5808 5809CXCursor clang_getCursorLexicalParent(CXCursor cursor) { 5810 if (clang_isDeclaration(cursor.kind)) { 5811 if (Decl *D = getCursorDecl(cursor)) { 5812 DeclContext *DC = D->getLexicalDeclContext(); 5813 if (!DC) 5814 return clang_getNullCursor(); 5815 5816 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)), 5817 getCursorTU(cursor)); 5818 } 5819 } 5820 5821 // FIXME: Note that we can't easily compute the lexical context of a 5822 // statement or expression, so we return nothing. 5823 return clang_getNullCursor(); 5824} 5825 5826CXFile clang_getIncludedFile(CXCursor cursor) { 5827 if (cursor.kind != CXCursor_InclusionDirective) 5828 return 0; 5829 5830 const InclusionDirective *ID = getCursorInclusionDirective(cursor); 5831 return (void *)ID->getFile(); 5832} 5833 5834CXSourceRange clang_Cursor_getCommentRange(CXCursor C) { 5835 if (!clang_isDeclaration(C.kind)) 5836 return clang_getNullRange(); 5837 5838 const Decl *D = getCursorDecl(C); 5839 ASTContext &Context = getCursorContext(C); 5840 const RawComment *RC = Context.getRawCommentForAnyRedecl(D); 5841 if (!RC) 5842 return clang_getNullRange(); 5843 5844 return cxloc::translateSourceRange(Context, RC->getSourceRange()); 5845} 5846 5847CXString clang_Cursor_getRawCommentText(CXCursor C) { 5848 if (!clang_isDeclaration(C.kind)) 5849 return createCXString((const char *) NULL); 5850 5851 const Decl *D = getCursorDecl(C); 5852 ASTContext &Context = getCursorContext(C); 5853 const RawComment *RC = Context.getRawCommentForAnyRedecl(D); 5854 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) : 5855 StringRef(); 5856 5857 // Don't duplicate the string because RawText points directly into source 5858 // code. 5859 return createCXString(RawText, false); 5860} 5861 5862CXString clang_Cursor_getBriefCommentText(CXCursor C) { 5863 if (!clang_isDeclaration(C.kind)) 5864 return createCXString((const char *) NULL); 5865 5866 const Decl *D = getCursorDecl(C); 5867 const ASTContext &Context = getCursorContext(C); 5868 const RawComment *RC = Context.getRawCommentForAnyRedecl(D); 5869 5870 if (RC) { 5871 StringRef BriefText = RC->getBriefText(Context); 5872 5873 // Don't duplicate the string because RawComment ensures that this memory 5874 // will not go away. 5875 return createCXString(BriefText, false); 5876 } 5877 5878 return createCXString((const char *) NULL); 5879} 5880 5881CXComment clang_Cursor_getParsedComment(CXCursor C) { 5882 if (!clang_isDeclaration(C.kind)) 5883 return cxcomment::createCXComment(NULL, NULL); 5884 5885 const Decl *D = getCursorDecl(C); 5886 const ASTContext &Context = getCursorContext(C); 5887 const comments::FullComment *FC = Context.getCommentForDecl(D, /*PP=*/ NULL); 5888 5889 return cxcomment::createCXComment(FC, getCursorTU(C)); 5890} 5891 5892CXModule clang_Cursor_getModule(CXCursor C) { 5893 if (C.kind == CXCursor_ModuleImportDecl) { 5894 if (ImportDecl *ImportD = dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) 5895 return ImportD->getImportedModule(); 5896 } 5897 5898 return 0; 5899} 5900 5901CXModule clang_Module_getParent(CXModule CXMod) { 5902 if (!CXMod) 5903 return 0; 5904 Module *Mod = static_cast<Module*>(CXMod); 5905 return Mod->Parent; 5906} 5907 5908CXString clang_Module_getName(CXModule CXMod) { 5909 if (!CXMod) 5910 return createCXString(""); 5911 Module *Mod = static_cast<Module*>(CXMod); 5912 return createCXString(Mod->Name); 5913} 5914 5915CXString clang_Module_getFullName(CXModule CXMod) { 5916 if (!CXMod) 5917 return createCXString(""); 5918 Module *Mod = static_cast<Module*>(CXMod); 5919 return createCXString(Mod->getFullModuleName()); 5920} 5921 5922unsigned clang_Module_getNumTopLevelHeaders(CXModule CXMod) { 5923 if (!CXMod) 5924 return 0; 5925 Module *Mod = static_cast<Module*>(CXMod); 5926 return Mod->TopHeaders.size(); 5927} 5928 5929CXFile clang_Module_getTopLevelHeader(CXModule CXMod, unsigned Index) { 5930 if (!CXMod) 5931 return 0; 5932 Module *Mod = static_cast<Module*>(CXMod); 5933 5934 if (Index < Mod->TopHeaders.size()) 5935 return const_cast<FileEntry *>(Mod->TopHeaders[Index]); 5936 5937 return 0; 5938} 5939 5940} // end: extern "C" 5941 5942//===----------------------------------------------------------------------===// 5943// C++ AST instrospection. 5944//===----------------------------------------------------------------------===// 5945 5946extern "C" { 5947unsigned clang_CXXMethod_isStatic(CXCursor C) { 5948 if (!clang_isDeclaration(C.kind)) 5949 return 0; 5950 5951 CXXMethodDecl *Method = 0; 5952 Decl *D = cxcursor::getCursorDecl(C); 5953 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D)) 5954 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl()); 5955 else 5956 Method = dyn_cast_or_null<CXXMethodDecl>(D); 5957 return (Method && Method->isStatic()) ? 1 : 0; 5958} 5959 5960unsigned clang_CXXMethod_isVirtual(CXCursor C) { 5961 if (!clang_isDeclaration(C.kind)) 5962 return 0; 5963 5964 CXXMethodDecl *Method = 0; 5965 Decl *D = cxcursor::getCursorDecl(C); 5966 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D)) 5967 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl()); 5968 else 5969 Method = dyn_cast_or_null<CXXMethodDecl>(D); 5970 return (Method && Method->isVirtual()) ? 1 : 0; 5971} 5972} // end: extern "C" 5973 5974//===----------------------------------------------------------------------===// 5975// Attribute introspection. 5976//===----------------------------------------------------------------------===// 5977 5978extern "C" { 5979CXType clang_getIBOutletCollectionType(CXCursor C) { 5980 if (C.kind != CXCursor_IBOutletCollectionAttr) 5981 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C)); 5982 5983 IBOutletCollectionAttr *A = 5984 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C)); 5985 5986 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C)); 5987} 5988} // end: extern "C" 5989 5990//===----------------------------------------------------------------------===// 5991// Inspecting memory usage. 5992//===----------------------------------------------------------------------===// 5993 5994typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries; 5995 5996static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries, 5997 enum CXTUResourceUsageKind k, 5998 unsigned long amount) { 5999 CXTUResourceUsageEntry entry = { k, amount }; 6000 entries.push_back(entry); 6001} 6002 6003extern "C" { 6004 6005const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) { 6006 const char *str = ""; 6007 switch (kind) { 6008 case CXTUResourceUsage_AST: 6009 str = "ASTContext: expressions, declarations, and types"; 6010 break; 6011 case CXTUResourceUsage_Identifiers: 6012 str = "ASTContext: identifiers"; 6013 break; 6014 case CXTUResourceUsage_Selectors: 6015 str = "ASTContext: selectors"; 6016 break; 6017 case CXTUResourceUsage_GlobalCompletionResults: 6018 str = "Code completion: cached global results"; 6019 break; 6020 case CXTUResourceUsage_SourceManagerContentCache: 6021 str = "SourceManager: content cache allocator"; 6022 break; 6023 case CXTUResourceUsage_AST_SideTables: 6024 str = "ASTContext: side tables"; 6025 break; 6026 case CXTUResourceUsage_SourceManager_Membuffer_Malloc: 6027 str = "SourceManager: malloc'ed memory buffers"; 6028 break; 6029 case CXTUResourceUsage_SourceManager_Membuffer_MMap: 6030 str = "SourceManager: mmap'ed memory buffers"; 6031 break; 6032 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc: 6033 str = "ExternalASTSource: malloc'ed memory buffers"; 6034 break; 6035 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap: 6036 str = "ExternalASTSource: mmap'ed memory buffers"; 6037 break; 6038 case CXTUResourceUsage_Preprocessor: 6039 str = "Preprocessor: malloc'ed memory"; 6040 break; 6041 case CXTUResourceUsage_PreprocessingRecord: 6042 str = "Preprocessor: PreprocessingRecord"; 6043 break; 6044 case CXTUResourceUsage_SourceManager_DataStructures: 6045 str = "SourceManager: data structures and tables"; 6046 break; 6047 case CXTUResourceUsage_Preprocessor_HeaderSearch: 6048 str = "Preprocessor: header search tables"; 6049 break; 6050 } 6051 return str; 6052} 6053 6054CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) { 6055 if (!TU) { 6056 CXTUResourceUsage usage = { (void*) 0, 0, 0 }; 6057 return usage; 6058 } 6059 6060 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData); 6061 OwningPtr<MemUsageEntries> entries(new MemUsageEntries()); 6062 ASTContext &astContext = astUnit->getASTContext(); 6063 6064 // How much memory is used by AST nodes and types? 6065 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST, 6066 (unsigned long) astContext.getASTAllocatedMemory()); 6067 6068 // How much memory is used by identifiers? 6069 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers, 6070 (unsigned long) astContext.Idents.getAllocator().getTotalMemory()); 6071 6072 // How much memory is used for selectors? 6073 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors, 6074 (unsigned long) astContext.Selectors.getTotalMemory()); 6075 6076 // How much memory is used by ASTContext's side tables? 6077 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables, 6078 (unsigned long) astContext.getSideTableAllocatedMemory()); 6079 6080 // How much memory is used for caching global code completion results? 6081 unsigned long completionBytes = 0; 6082 if (GlobalCodeCompletionAllocator *completionAllocator = 6083 astUnit->getCachedCompletionAllocator().getPtr()) { 6084 completionBytes = completionAllocator->getTotalMemory(); 6085 } 6086 createCXTUResourceUsageEntry(*entries, 6087 CXTUResourceUsage_GlobalCompletionResults, 6088 completionBytes); 6089 6090 // How much memory is being used by SourceManager's content cache? 6091 createCXTUResourceUsageEntry(*entries, 6092 CXTUResourceUsage_SourceManagerContentCache, 6093 (unsigned long) astContext.getSourceManager().getContentCacheSize()); 6094 6095 // How much memory is being used by the MemoryBuffer's in SourceManager? 6096 const SourceManager::MemoryBufferSizes &srcBufs = 6097 astUnit->getSourceManager().getMemoryBufferSizes(); 6098 6099 createCXTUResourceUsageEntry(*entries, 6100 CXTUResourceUsage_SourceManager_Membuffer_Malloc, 6101 (unsigned long) srcBufs.malloc_bytes); 6102 createCXTUResourceUsageEntry(*entries, 6103 CXTUResourceUsage_SourceManager_Membuffer_MMap, 6104 (unsigned long) srcBufs.mmap_bytes); 6105 createCXTUResourceUsageEntry(*entries, 6106 CXTUResourceUsage_SourceManager_DataStructures, 6107 (unsigned long) astContext.getSourceManager() 6108 .getDataStructureSizes()); 6109 6110 // How much memory is being used by the ExternalASTSource? 6111 if (ExternalASTSource *esrc = astContext.getExternalSource()) { 6112 const ExternalASTSource::MemoryBufferSizes &sizes = 6113 esrc->getMemoryBufferSizes(); 6114 6115 createCXTUResourceUsageEntry(*entries, 6116 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc, 6117 (unsigned long) sizes.malloc_bytes); 6118 createCXTUResourceUsageEntry(*entries, 6119 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap, 6120 (unsigned long) sizes.mmap_bytes); 6121 } 6122 6123 // How much memory is being used by the Preprocessor? 6124 Preprocessor &pp = astUnit->getPreprocessor(); 6125 createCXTUResourceUsageEntry(*entries, 6126 CXTUResourceUsage_Preprocessor, 6127 pp.getTotalMemory()); 6128 6129 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) { 6130 createCXTUResourceUsageEntry(*entries, 6131 CXTUResourceUsage_PreprocessingRecord, 6132 pRec->getTotalMemory()); 6133 } 6134 6135 createCXTUResourceUsageEntry(*entries, 6136 CXTUResourceUsage_Preprocessor_HeaderSearch, 6137 pp.getHeaderSearchInfo().getTotalMemory()); 6138 6139 CXTUResourceUsage usage = { (void*) entries.get(), 6140 (unsigned) entries->size(), 6141 entries->size() ? &(*entries)[0] : 0 }; 6142 entries.take(); 6143 return usage; 6144} 6145 6146void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) { 6147 if (usage.data) 6148 delete (MemUsageEntries*) usage.data; 6149} 6150 6151} // end extern "C" 6152 6153void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) { 6154 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU); 6155 for (unsigned I = 0; I != Usage.numEntries; ++I) 6156 fprintf(stderr, " %s: %lu\n", 6157 clang_getTUResourceUsageName(Usage.entries[I].kind), 6158 Usage.entries[I].amount); 6159 6160 clang_disposeCXTUResourceUsage(Usage); 6161} 6162 6163//===----------------------------------------------------------------------===// 6164// Misc. utility functions. 6165//===----------------------------------------------------------------------===// 6166 6167/// Default to using an 8 MB stack size on "safety" threads. 6168static unsigned SafetyStackThreadSize = 8 << 20; 6169 6170namespace clang { 6171 6172bool RunSafely(llvm::CrashRecoveryContext &CRC, 6173 void (*Fn)(void*), void *UserData, 6174 unsigned Size) { 6175 if (!Size) 6176 Size = GetSafetyThreadStackSize(); 6177 if (Size) 6178 return CRC.RunSafelyOnThread(Fn, UserData, Size); 6179 return CRC.RunSafely(Fn, UserData); 6180} 6181 6182unsigned GetSafetyThreadStackSize() { 6183 return SafetyStackThreadSize; 6184} 6185 6186void SetSafetyThreadStackSize(unsigned Value) { 6187 SafetyStackThreadSize = Value; 6188} 6189 6190} 6191 6192void clang::setThreadBackgroundPriority() { 6193 if (getenv("LIBCLANG_BGPRIO_DISABLE")) 6194 return; 6195 6196 // FIXME: Move to llvm/Support and make it cross-platform. 6197#ifdef __APPLE__ 6198 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG); 6199#endif 6200} 6201 6202void cxindex::printDiagsToStderr(ASTUnit *Unit) { 6203 if (!Unit) 6204 return; 6205 6206 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(), 6207 DEnd = Unit->stored_diag_end(); 6208 D != DEnd; ++D) { 6209 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOpts()); 6210 CXString Msg = clang_formatDiagnostic(&Diag, 6211 clang_defaultDiagnosticDisplayOptions()); 6212 fprintf(stderr, "%s\n", clang_getCString(Msg)); 6213 clang_disposeString(Msg); 6214 } 6215#ifdef LLVM_ON_WIN32 6216 // On Windows, force a flush, since there may be multiple copies of 6217 // stderr and stdout in the file system, all with different buffers 6218 // but writing to the same device. 6219 fflush(stderr); 6220#endif 6221} 6222 6223MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II, 6224 SourceLocation MacroDefLoc, 6225 CXTranslationUnit TU){ 6226 if (MacroDefLoc.isInvalid() || !TU) 6227 return 0; 6228 if (!II.hadMacroDefinition()) 6229 return 0; 6230 6231 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData); 6232 Preprocessor &PP = Unit->getPreprocessor(); 6233 MacroInfo *MI = PP.getMacroInfoHistory(&II); 6234 while (MI) { 6235 if (MacroDefLoc == MI->getDefinitionLoc()) 6236 return MI; 6237 MI = MI->getPreviousDefinition(); 6238 } 6239 6240 return 0; 6241} 6242 6243const MacroInfo *cxindex::getMacroInfo(const MacroDefinition *MacroDef, 6244 CXTranslationUnit TU) { 6245 if (!MacroDef || !TU) 6246 return 0; 6247 const IdentifierInfo *II = MacroDef->getName(); 6248 if (!II) 6249 return 0; 6250 6251 return getMacroInfo(*II, MacroDef->getLocation(), TU); 6252} 6253 6254MacroDefinition *cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, 6255 const Token &Tok, 6256 CXTranslationUnit TU) { 6257 if (!MI || !TU) 6258 return 0; 6259 if (Tok.isNot(tok::raw_identifier)) 6260 return 0; 6261 6262 if (MI->getNumTokens() == 0) 6263 return 0; 6264 SourceRange DefRange(MI->getReplacementToken(0).getLocation(), 6265 MI->getDefinitionEndLoc()); 6266 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData); 6267 6268 // Check that the token is inside the definition and not its argument list. 6269 SourceManager &SM = Unit->getSourceManager(); 6270 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin())) 6271 return 0; 6272 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation())) 6273 return 0; 6274 6275 Preprocessor &PP = Unit->getPreprocessor(); 6276 PreprocessingRecord *PPRec = PP.getPreprocessingRecord(); 6277 if (!PPRec) 6278 return 0; 6279 6280 StringRef Name(Tok.getRawIdentifierData(), Tok.getLength()); 6281 IdentifierInfo &II = PP.getIdentifierTable().get(Name); 6282 if (!II.hadMacroDefinition()) 6283 return 0; 6284 6285 // Check that the identifier is not one of the macro arguments. 6286 if (std::find(MI->arg_begin(), MI->arg_end(), &II) != MI->arg_end()) 6287 return 0; 6288 6289 MacroInfo *InnerMI = PP.getMacroInfoHistory(&II); 6290 if (!InnerMI) 6291 return 0; 6292 6293 return PPRec->findMacroDefinition(InnerMI); 6294} 6295 6296MacroDefinition *cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, 6297 SourceLocation Loc, 6298 CXTranslationUnit TU) { 6299 if (Loc.isInvalid() || !MI || !TU) 6300 return 0; 6301 6302 if (MI->getNumTokens() == 0) 6303 return 0; 6304 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData); 6305 Preprocessor &PP = Unit->getPreprocessor(); 6306 if (!PP.getPreprocessingRecord()) 6307 return 0; 6308 Loc = Unit->getSourceManager().getSpellingLoc(Loc); 6309 Token Tok; 6310 if (PP.getRawToken(Loc, Tok)) 6311 return 0; 6312 6313 return checkForMacroInMacroDefinition(MI, Tok, TU); 6314} 6315 6316extern "C" { 6317 6318CXString clang_getClangVersion() { 6319 return createCXString(getClangFullVersion()); 6320} 6321 6322} // end: extern "C" 6323 6324Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) { 6325 if (TU) { 6326 if (ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData)) { 6327 LogOS << '<' << Unit->getMainFileName() << '>'; 6328 return *this; 6329 } 6330 } 6331 6332 LogOS << "<NULL TU>"; 6333 return *this; 6334} 6335 6336Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) { 6337 CXFile File; 6338 unsigned Line, Column; 6339 clang_getFileLocation(Loc, &File, &Line, &Column, 0); 6340 CXString FileName = clang_getFileName(File); 6341 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column); 6342 clang_disposeString(FileName); 6343 return *this; 6344} 6345 6346Logger &cxindex::Logger::operator<<(CXSourceRange range) { 6347 CXSourceLocation BLoc = clang_getRangeStart(range); 6348 CXSourceLocation ELoc = clang_getRangeEnd(range); 6349 6350 CXFile BFile; 6351 unsigned BLine, BColumn; 6352 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, 0); 6353 6354 CXFile EFile; 6355 unsigned ELine, EColumn; 6356 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, 0); 6357 6358 CXString BFileName = clang_getFileName(BFile); 6359 if (BFile == EFile) { 6360 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName), 6361 BLine, BColumn, ELine, EColumn); 6362 } else { 6363 CXString EFileName = clang_getFileName(EFile); 6364 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName), 6365 BLine, BColumn) 6366 << llvm::format("%s:%d:%d]", clang_getCString(EFileName), 6367 ELine, EColumn); 6368 clang_disposeString(EFileName); 6369 } 6370 clang_disposeString(BFileName); 6371 return *this; 6372} 6373 6374Logger &cxindex::Logger::operator<<(CXString Str) { 6375 *this << clang_getCString(Str); 6376 return *this; 6377} 6378 6379Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) { 6380 LogOS << Fmt; 6381 return *this; 6382} 6383 6384cxindex::Logger::~Logger() { 6385 LogOS.flush(); 6386 6387 llvm::sys::ScopedLock L(EnableMultithreadingMutex); 6388 6389 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime(); 6390 6391 raw_ostream &OS = llvm::errs(); 6392 OS << "[libclang:" << Name << ':'; 6393 6394 // FIXME: Portability. 6395#if HAVE_PTHREAD_H && __APPLE__ 6396 mach_port_t tid = pthread_mach_thread_np(pthread_self()); 6397 OS << tid << ':'; 6398#endif 6399 6400 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime(); 6401 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime()); 6402 OS << Msg.str() << '\n'; 6403 6404 if (Trace) { 6405 llvm::sys::PrintStackTrace(stderr); 6406 OS << "--------------------------------------------------\n"; 6407 } 6408} 6409