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