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