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