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