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