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