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