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