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