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