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