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