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