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