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