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