CIndex.cpp revision 94fdffa4a572fc14ac296f5f1aae9db3734c72f1
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 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(), 1323 TAL.getTemplateNameLoc()); 1324 } 1325 1326 return false; 1327} 1328 1329bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) { 1330 return VisitDeclContext(D); 1331} 1332 1333bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 1334 return Visit(TL.getUnqualifiedLoc()); 1335} 1336 1337bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 1338 ASTContext &Context = AU->getASTContext(); 1339 1340 // Some builtin types (such as Objective-C's "id", "sel", and 1341 // "Class") have associated declarations. Create cursors for those. 1342 QualType VisitType; 1343 switch (TL.getType()->getAs<BuiltinType>()->getKind()) { 1344 case BuiltinType::Void: 1345 case BuiltinType::Bool: 1346 case BuiltinType::Char_U: 1347 case BuiltinType::UChar: 1348 case BuiltinType::Char16: 1349 case BuiltinType::Char32: 1350 case BuiltinType::UShort: 1351 case BuiltinType::UInt: 1352 case BuiltinType::ULong: 1353 case BuiltinType::ULongLong: 1354 case BuiltinType::UInt128: 1355 case BuiltinType::Char_S: 1356 case BuiltinType::SChar: 1357 case BuiltinType::WChar_U: 1358 case BuiltinType::WChar_S: 1359 case BuiltinType::Short: 1360 case BuiltinType::Int: 1361 case BuiltinType::Long: 1362 case BuiltinType::LongLong: 1363 case BuiltinType::Int128: 1364 case BuiltinType::Float: 1365 case BuiltinType::Double: 1366 case BuiltinType::LongDouble: 1367 case BuiltinType::NullPtr: 1368 case BuiltinType::Overload: 1369 case BuiltinType::Dependent: 1370 break; 1371 1372 case BuiltinType::ObjCId: 1373 VisitType = Context.getObjCIdType(); 1374 break; 1375 1376 case BuiltinType::ObjCClass: 1377 VisitType = Context.getObjCClassType(); 1378 break; 1379 1380 case BuiltinType::ObjCSel: 1381 VisitType = Context.getObjCSelType(); 1382 break; 1383 } 1384 1385 if (!VisitType.isNull()) { 1386 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>()) 1387 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(), 1388 TU)); 1389 } 1390 1391 return false; 1392} 1393 1394bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) { 1395 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU)); 1396} 1397 1398bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) { 1399 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); 1400} 1401 1402bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) { 1403 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); 1404} 1405 1406bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) { 1407 // FIXME: We can't visit the template type parameter, because there's 1408 // no context information with which we can match up the depth/index in the 1409 // type to the appropriate 1410 return false; 1411} 1412 1413bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 1414 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU))) 1415 return true; 1416 1417 return false; 1418} 1419 1420bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 1421 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc())) 1422 return true; 1423 1424 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) { 1425 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I), 1426 TU))) 1427 return true; 1428 } 1429 1430 return false; 1431} 1432 1433bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 1434 return Visit(TL.getPointeeLoc()); 1435} 1436 1437bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) { 1438 return Visit(TL.getInnerLoc()); 1439} 1440 1441bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) { 1442 return Visit(TL.getPointeeLoc()); 1443} 1444 1445bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 1446 return Visit(TL.getPointeeLoc()); 1447} 1448 1449bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 1450 return Visit(TL.getPointeeLoc()); 1451} 1452 1453bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 1454 return Visit(TL.getPointeeLoc()); 1455} 1456 1457bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 1458 return Visit(TL.getPointeeLoc()); 1459} 1460 1461bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL, 1462 bool SkipResultType) { 1463 if (!SkipResultType && Visit(TL.getResultLoc())) 1464 return true; 1465 1466 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I) 1467 if (Decl *D = TL.getArg(I)) 1468 if (Visit(MakeCXCursor(D, TU))) 1469 return true; 1470 1471 return false; 1472} 1473 1474bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) { 1475 if (Visit(TL.getElementLoc())) 1476 return true; 1477 1478 if (Expr *Size = TL.getSizeExpr()) 1479 return Visit(MakeCXCursor(Size, StmtParent, TU)); 1480 1481 return false; 1482} 1483 1484bool CursorVisitor::VisitTemplateSpecializationTypeLoc( 1485 TemplateSpecializationTypeLoc TL) { 1486 // Visit the template name. 1487 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(), 1488 TL.getTemplateNameLoc())) 1489 return true; 1490 1491 // Visit the template arguments. 1492 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I) 1493 if (VisitTemplateArgumentLoc(TL.getArgLoc(I))) 1494 return true; 1495 1496 return false; 1497} 1498 1499bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 1500 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU)); 1501} 1502 1503bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 1504 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo()) 1505 return Visit(TSInfo->getTypeLoc()); 1506 1507 return false; 1508} 1509 1510bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 1511 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc())) 1512 return true; 1513 1514 return false; 1515} 1516 1517bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc( 1518 DependentTemplateSpecializationTypeLoc TL) { 1519 // Visit the nested-name-specifier, if there is one. 1520 if (TL.getQualifierLoc() && 1521 VisitNestedNameSpecifierLoc(TL.getQualifierLoc())) 1522 return true; 1523 1524 // Visit the template arguments. 1525 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I) 1526 if (VisitTemplateArgumentLoc(TL.getArgLoc(I))) 1527 return true; 1528 1529 return false; 1530} 1531 1532bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 1533 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc())) 1534 return true; 1535 1536 return Visit(TL.getNamedTypeLoc()); 1537} 1538 1539bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) { 1540 return Visit(TL.getPatternLoc()); 1541} 1542 1543bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) { 1544 // Visit the nested-name-specifier, if present. 1545 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) 1546 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1547 return true; 1548 1549 if (D->isDefinition()) { 1550 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(), 1551 E = D->bases_end(); I != E; ++I) { 1552 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU))) 1553 return true; 1554 } 1555 } 1556 1557 return VisitTagDecl(D); 1558} 1559 1560bool CursorVisitor::VisitAttributes(Decl *D) { 1561 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end(); 1562 i != e; ++i) 1563 if (Visit(MakeCXCursor(*i, D, TU))) 1564 return true; 1565 1566 return false; 1567} 1568 1569//===----------------------------------------------------------------------===// 1570// Data-recursive visitor methods. 1571//===----------------------------------------------------------------------===// 1572 1573namespace { 1574#define DEF_JOB(NAME, DATA, KIND)\ 1575class NAME : public VisitorJob {\ 1576public:\ 1577 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \ 1578 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\ 1579 DATA *get() const { return static_cast<DATA*>(data[0]); }\ 1580}; 1581 1582DEF_JOB(StmtVisit, Stmt, StmtVisitKind) 1583DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind) 1584DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind) 1585DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind) 1586DEF_JOB(ExplicitTemplateArgsVisit, ExplicitTemplateArgumentList, 1587 ExplicitTemplateArgsVisitKind) 1588DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind) 1589#undef DEF_JOB 1590 1591class DeclVisit : public VisitorJob { 1592public: 1593 DeclVisit(Decl *d, CXCursor parent, bool isFirst) : 1594 VisitorJob(parent, VisitorJob::DeclVisitKind, 1595 d, isFirst ? (void*) 1 : (void*) 0) {} 1596 static bool classof(const VisitorJob *VJ) { 1597 return VJ->getKind() == DeclVisitKind; 1598 } 1599 Decl *get() const { return static_cast<Decl*>(data[0]); } 1600 bool isFirst() const { return data[1] ? true : false; } 1601}; 1602class TypeLocVisit : public VisitorJob { 1603public: 1604 TypeLocVisit(TypeLoc tl, CXCursor parent) : 1605 VisitorJob(parent, VisitorJob::TypeLocVisitKind, 1606 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {} 1607 1608 static bool classof(const VisitorJob *VJ) { 1609 return VJ->getKind() == TypeLocVisitKind; 1610 } 1611 1612 TypeLoc get() const { 1613 QualType T = QualType::getFromOpaquePtr(data[0]); 1614 return TypeLoc(T, data[1]); 1615 } 1616}; 1617 1618class LabelRefVisit : public VisitorJob { 1619public: 1620 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent) 1621 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD, 1622 labelLoc.getPtrEncoding()) {} 1623 1624 static bool classof(const VisitorJob *VJ) { 1625 return VJ->getKind() == VisitorJob::LabelRefVisitKind; 1626 } 1627 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); } 1628 SourceLocation getLoc() const { 1629 return SourceLocation::getFromPtrEncoding(data[1]); } 1630}; 1631class NestedNameSpecifierVisit : public VisitorJob { 1632public: 1633 NestedNameSpecifierVisit(NestedNameSpecifier *NS, SourceRange R, 1634 CXCursor parent) 1635 : VisitorJob(parent, VisitorJob::NestedNameSpecifierVisitKind, 1636 NS, R.getBegin().getPtrEncoding(), 1637 R.getEnd().getPtrEncoding()) {} 1638 static bool classof(const VisitorJob *VJ) { 1639 return VJ->getKind() == VisitorJob::NestedNameSpecifierVisitKind; 1640 } 1641 NestedNameSpecifier *get() const { 1642 return static_cast<NestedNameSpecifier*>(data[0]); 1643 } 1644 SourceRange getSourceRange() const { 1645 SourceLocation A = 1646 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]); 1647 SourceLocation B = 1648 SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[2]); 1649 return SourceRange(A, B); 1650 } 1651}; 1652 1653class NestedNameSpecifierLocVisit : public VisitorJob { 1654public: 1655 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent) 1656 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind, 1657 Qualifier.getNestedNameSpecifier(), 1658 Qualifier.getOpaqueData()) { } 1659 1660 static bool classof(const VisitorJob *VJ) { 1661 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind; 1662 } 1663 1664 NestedNameSpecifierLoc get() const { 1665 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]), 1666 data[1]); 1667 } 1668}; 1669 1670class DeclarationNameInfoVisit : public VisitorJob { 1671public: 1672 DeclarationNameInfoVisit(Stmt *S, CXCursor parent) 1673 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {} 1674 static bool classof(const VisitorJob *VJ) { 1675 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind; 1676 } 1677 DeclarationNameInfo get() const { 1678 Stmt *S = static_cast<Stmt*>(data[0]); 1679 switch (S->getStmtClass()) { 1680 default: 1681 llvm_unreachable("Unhandled Stmt"); 1682 case Stmt::CXXDependentScopeMemberExprClass: 1683 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo(); 1684 case Stmt::DependentScopeDeclRefExprClass: 1685 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo(); 1686 } 1687 } 1688}; 1689class MemberRefVisit : public VisitorJob { 1690public: 1691 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent) 1692 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D, 1693 L.getPtrEncoding()) {} 1694 static bool classof(const VisitorJob *VJ) { 1695 return VJ->getKind() == VisitorJob::MemberRefVisitKind; 1696 } 1697 FieldDecl *get() const { 1698 return static_cast<FieldDecl*>(data[0]); 1699 } 1700 SourceLocation getLoc() const { 1701 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]); 1702 } 1703}; 1704class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> { 1705 VisitorWorkList &WL; 1706 CXCursor Parent; 1707public: 1708 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent) 1709 : WL(wl), Parent(parent) {} 1710 1711 void VisitAddrLabelExpr(AddrLabelExpr *E); 1712 void VisitBlockExpr(BlockExpr *B); 1713 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E); 1714 void VisitCompoundStmt(CompoundStmt *S); 1715 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ } 1716 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E); 1717 void VisitCXXNewExpr(CXXNewExpr *E); 1718 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E); 1719 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E); 1720 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E); 1721 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E); 1722 void VisitCXXTypeidExpr(CXXTypeidExpr *E); 1723 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E); 1724 void VisitCXXUuidofExpr(CXXUuidofExpr *E); 1725 void VisitDeclRefExpr(DeclRefExpr *D); 1726 void VisitDeclStmt(DeclStmt *S); 1727 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E); 1728 void VisitDesignatedInitExpr(DesignatedInitExpr *E); 1729 void VisitExplicitCastExpr(ExplicitCastExpr *E); 1730 void VisitForStmt(ForStmt *FS); 1731 void VisitGotoStmt(GotoStmt *GS); 1732 void VisitIfStmt(IfStmt *If); 1733 void VisitInitListExpr(InitListExpr *IE); 1734 void VisitMemberExpr(MemberExpr *M); 1735 void VisitOffsetOfExpr(OffsetOfExpr *E); 1736 void VisitObjCEncodeExpr(ObjCEncodeExpr *E); 1737 void VisitObjCMessageExpr(ObjCMessageExpr *M); 1738 void VisitOverloadExpr(OverloadExpr *E); 1739 void VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E); 1740 void VisitStmt(Stmt *S); 1741 void VisitSwitchStmt(SwitchStmt *S); 1742 void VisitWhileStmt(WhileStmt *W); 1743 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E); 1744 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E); 1745 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U); 1746 void VisitVAArgExpr(VAArgExpr *E); 1747 void VisitSizeOfPackExpr(SizeOfPackExpr *E); 1748 1749private: 1750 void AddDeclarationNameInfo(Stmt *S); 1751 void AddNestedNameSpecifier(NestedNameSpecifier *NS, SourceRange R); 1752 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier); 1753 void AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A); 1754 void AddMemberRef(FieldDecl *D, SourceLocation L); 1755 void AddStmt(Stmt *S); 1756 void AddDecl(Decl *D, bool isFirst = true); 1757 void AddTypeLoc(TypeSourceInfo *TI); 1758 void EnqueueChildren(Stmt *S); 1759}; 1760} // end anonyous namespace 1761 1762void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) { 1763 // 'S' should always be non-null, since it comes from the 1764 // statement we are visiting. 1765 WL.push_back(DeclarationNameInfoVisit(S, Parent)); 1766} 1767void EnqueueVisitor::AddNestedNameSpecifier(NestedNameSpecifier *N, 1768 SourceRange R) { 1769 if (N) 1770 WL.push_back(NestedNameSpecifierVisit(N, R, Parent)); 1771} 1772 1773void 1774EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) { 1775 if (Qualifier) 1776 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent)); 1777} 1778 1779void EnqueueVisitor::AddStmt(Stmt *S) { 1780 if (S) 1781 WL.push_back(StmtVisit(S, Parent)); 1782} 1783void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) { 1784 if (D) 1785 WL.push_back(DeclVisit(D, Parent, isFirst)); 1786} 1787void EnqueueVisitor:: 1788 AddExplicitTemplateArgs(const ExplicitTemplateArgumentList *A) { 1789 if (A) 1790 WL.push_back(ExplicitTemplateArgsVisit( 1791 const_cast<ExplicitTemplateArgumentList*>(A), Parent)); 1792} 1793void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) { 1794 if (D) 1795 WL.push_back(MemberRefVisit(D, L, Parent)); 1796} 1797void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) { 1798 if (TI) 1799 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent)); 1800 } 1801void EnqueueVisitor::EnqueueChildren(Stmt *S) { 1802 unsigned size = WL.size(); 1803 for (Stmt::child_range Child = S->children(); Child; ++Child) { 1804 AddStmt(*Child); 1805 } 1806 if (size == WL.size()) 1807 return; 1808 // Now reverse the entries we just added. This will match the DFS 1809 // ordering performed by the worklist. 1810 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end(); 1811 std::reverse(I, E); 1812} 1813void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) { 1814 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent)); 1815} 1816void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) { 1817 AddDecl(B->getBlockDecl()); 1818} 1819void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 1820 EnqueueChildren(E); 1821 AddTypeLoc(E->getTypeSourceInfo()); 1822} 1823void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) { 1824 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(), 1825 E = S->body_rend(); I != E; ++I) { 1826 AddStmt(*I); 1827 } 1828} 1829void EnqueueVisitor:: 1830VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) { 1831 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs()); 1832 AddDeclarationNameInfo(E); 1833 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc()) 1834 AddNestedNameSpecifierLoc(QualifierLoc); 1835 if (!E->isImplicitAccess()) 1836 AddStmt(E->getBase()); 1837} 1838void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) { 1839 // Enqueue the initializer or constructor arguments. 1840 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I) 1841 AddStmt(E->getConstructorArg(I-1)); 1842 // Enqueue the array size, if any. 1843 AddStmt(E->getArraySize()); 1844 // Enqueue the allocated type. 1845 AddTypeLoc(E->getAllocatedTypeSourceInfo()); 1846 // Enqueue the placement arguments. 1847 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I) 1848 AddStmt(E->getPlacementArg(I-1)); 1849} 1850void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) { 1851 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I) 1852 AddStmt(CE->getArg(I-1)); 1853 AddStmt(CE->getCallee()); 1854 AddStmt(CE->getArg(0)); 1855} 1856void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) { 1857 // Visit the name of the type being destroyed. 1858 AddTypeLoc(E->getDestroyedTypeInfo()); 1859 // Visit the scope type that looks disturbingly like the nested-name-specifier 1860 // but isn't. 1861 AddTypeLoc(E->getScopeTypeInfo()); 1862 // Visit the nested-name-specifier. 1863 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc()) 1864 AddNestedNameSpecifierLoc(QualifierLoc); 1865 // Visit base expression. 1866 AddStmt(E->getBase()); 1867} 1868void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) { 1869 AddTypeLoc(E->getTypeSourceInfo()); 1870} 1871void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) { 1872 EnqueueChildren(E); 1873 AddTypeLoc(E->getTypeSourceInfo()); 1874} 1875void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) { 1876 EnqueueChildren(E); 1877 if (E->isTypeOperand()) 1878 AddTypeLoc(E->getTypeOperandSourceInfo()); 1879} 1880 1881void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr 1882 *E) { 1883 EnqueueChildren(E); 1884 AddTypeLoc(E->getTypeSourceInfo()); 1885} 1886void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) { 1887 EnqueueChildren(E); 1888 if (E->isTypeOperand()) 1889 AddTypeLoc(E->getTypeOperandSourceInfo()); 1890} 1891void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) { 1892 if (DR->hasExplicitTemplateArgs()) { 1893 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs()); 1894 } 1895 WL.push_back(DeclRefExprParts(DR, Parent)); 1896} 1897void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) { 1898 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs()); 1899 AddDeclarationNameInfo(E); 1900 AddNestedNameSpecifierLoc(E->getQualifierLoc()); 1901} 1902void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) { 1903 unsigned size = WL.size(); 1904 bool isFirst = true; 1905 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end(); 1906 D != DEnd; ++D) { 1907 AddDecl(*D, isFirst); 1908 isFirst = false; 1909 } 1910 if (size == WL.size()) 1911 return; 1912 // Now reverse the entries we just added. This will match the DFS 1913 // ordering performed by the worklist. 1914 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end(); 1915 std::reverse(I, E); 1916} 1917void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) { 1918 AddStmt(E->getInit()); 1919 typedef DesignatedInitExpr::Designator Designator; 1920 for (DesignatedInitExpr::reverse_designators_iterator 1921 D = E->designators_rbegin(), DEnd = E->designators_rend(); 1922 D != DEnd; ++D) { 1923 if (D->isFieldDesignator()) { 1924 if (FieldDecl *Field = D->getField()) 1925 AddMemberRef(Field, D->getFieldLoc()); 1926 continue; 1927 } 1928 if (D->isArrayDesignator()) { 1929 AddStmt(E->getArrayIndex(*D)); 1930 continue; 1931 } 1932 assert(D->isArrayRangeDesignator() && "Unknown designator kind"); 1933 AddStmt(E->getArrayRangeEnd(*D)); 1934 AddStmt(E->getArrayRangeStart(*D)); 1935 } 1936} 1937void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) { 1938 EnqueueChildren(E); 1939 AddTypeLoc(E->getTypeInfoAsWritten()); 1940} 1941void EnqueueVisitor::VisitForStmt(ForStmt *FS) { 1942 AddStmt(FS->getBody()); 1943 AddStmt(FS->getInc()); 1944 AddStmt(FS->getCond()); 1945 AddDecl(FS->getConditionVariable()); 1946 AddStmt(FS->getInit()); 1947} 1948void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) { 1949 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent)); 1950} 1951void EnqueueVisitor::VisitIfStmt(IfStmt *If) { 1952 AddStmt(If->getElse()); 1953 AddStmt(If->getThen()); 1954 AddStmt(If->getCond()); 1955 AddDecl(If->getConditionVariable()); 1956} 1957void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) { 1958 // We care about the syntactic form of the initializer list, only. 1959 if (InitListExpr *Syntactic = IE->getSyntacticForm()) 1960 IE = Syntactic; 1961 EnqueueChildren(IE); 1962} 1963void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) { 1964 WL.push_back(MemberExprParts(M, Parent)); 1965 1966 // If the base of the member access expression is an implicit 'this', don't 1967 // visit it. 1968 // FIXME: If we ever want to show these implicit accesses, this will be 1969 // unfortunate. However, clang_getCursor() relies on this behavior. 1970 if (CXXThisExpr *This 1971 = llvm::dyn_cast<CXXThisExpr>(M->getBase()->IgnoreParenImpCasts())) 1972 if (This->isImplicit()) 1973 return; 1974 1975 AddStmt(M->getBase()); 1976} 1977void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) { 1978 AddTypeLoc(E->getEncodedTypeSourceInfo()); 1979} 1980void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) { 1981 EnqueueChildren(M); 1982 AddTypeLoc(M->getClassReceiverTypeInfo()); 1983} 1984void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) { 1985 // Visit the components of the offsetof expression. 1986 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) { 1987 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 1988 const OffsetOfNode &Node = E->getComponent(I-1); 1989 switch (Node.getKind()) { 1990 case OffsetOfNode::Array: 1991 AddStmt(E->getIndexExpr(Node.getArrayExprIndex())); 1992 break; 1993 case OffsetOfNode::Field: 1994 AddMemberRef(Node.getField(), Node.getRange().getEnd()); 1995 break; 1996 case OffsetOfNode::Identifier: 1997 case OffsetOfNode::Base: 1998 continue; 1999 } 2000 } 2001 // Visit the type into which we're computing the offset. 2002 AddTypeLoc(E->getTypeSourceInfo()); 2003} 2004void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) { 2005 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs()); 2006 WL.push_back(OverloadExprParts(E, Parent)); 2007} 2008void EnqueueVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) { 2009 EnqueueChildren(E); 2010 if (E->isArgumentType()) 2011 AddTypeLoc(E->getArgumentTypeInfo()); 2012} 2013void EnqueueVisitor::VisitStmt(Stmt *S) { 2014 EnqueueChildren(S); 2015} 2016void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) { 2017 AddStmt(S->getBody()); 2018 AddStmt(S->getCond()); 2019 AddDecl(S->getConditionVariable()); 2020} 2021 2022void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) { 2023 AddStmt(W->getBody()); 2024 AddStmt(W->getCond()); 2025 AddDecl(W->getConditionVariable()); 2026} 2027void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) { 2028 AddTypeLoc(E->getQueriedTypeSourceInfo()); 2029} 2030 2031void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) { 2032 AddTypeLoc(E->getRhsTypeSourceInfo()); 2033 AddTypeLoc(E->getLhsTypeSourceInfo()); 2034} 2035 2036void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) { 2037 VisitOverloadExpr(U); 2038 if (!U->isImplicitAccess()) 2039 AddStmt(U->getBase()); 2040} 2041void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) { 2042 AddStmt(E->getSubExpr()); 2043 AddTypeLoc(E->getWrittenTypeInfo()); 2044} 2045void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) { 2046 WL.push_back(SizeOfPackExprParts(E, Parent)); 2047} 2048 2049void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) { 2050 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S); 2051} 2052 2053bool CursorVisitor::IsInRegionOfInterest(CXCursor C) { 2054 if (RegionOfInterest.isValid()) { 2055 SourceRange Range = getRawCursorExtent(C); 2056 if (Range.isInvalid() || CompareRegionOfInterest(Range)) 2057 return false; 2058 } 2059 return true; 2060} 2061 2062bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) { 2063 while (!WL.empty()) { 2064 // Dequeue the worklist item. 2065 VisitorJob LI = WL.back(); 2066 WL.pop_back(); 2067 2068 // Set the Parent field, then back to its old value once we're done. 2069 SetParentRAII SetParent(Parent, StmtParent, LI.getParent()); 2070 2071 switch (LI.getKind()) { 2072 case VisitorJob::DeclVisitKind: { 2073 Decl *D = cast<DeclVisit>(&LI)->get(); 2074 if (!D) 2075 continue; 2076 2077 // For now, perform default visitation for Decls. 2078 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst()))) 2079 return true; 2080 2081 continue; 2082 } 2083 case VisitorJob::ExplicitTemplateArgsVisitKind: { 2084 const ExplicitTemplateArgumentList *ArgList = 2085 cast<ExplicitTemplateArgsVisit>(&LI)->get(); 2086 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(), 2087 *ArgEnd = Arg + ArgList->NumTemplateArgs; 2088 Arg != ArgEnd; ++Arg) { 2089 if (VisitTemplateArgumentLoc(*Arg)) 2090 return true; 2091 } 2092 continue; 2093 } 2094 case VisitorJob::TypeLocVisitKind: { 2095 // Perform default visitation for TypeLocs. 2096 if (Visit(cast<TypeLocVisit>(&LI)->get())) 2097 return true; 2098 continue; 2099 } 2100 case VisitorJob::LabelRefVisitKind: { 2101 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get(); 2102 if (LabelStmt *stmt = LS->getStmt()) { 2103 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(), 2104 TU))) { 2105 return true; 2106 } 2107 } 2108 continue; 2109 } 2110 2111 case VisitorJob::NestedNameSpecifierVisitKind: { 2112 NestedNameSpecifierVisit *V = cast<NestedNameSpecifierVisit>(&LI); 2113 if (VisitNestedNameSpecifier(V->get(), V->getSourceRange())) 2114 return true; 2115 continue; 2116 } 2117 2118 case VisitorJob::NestedNameSpecifierLocVisitKind: { 2119 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI); 2120 if (VisitNestedNameSpecifierLoc(V->get())) 2121 return true; 2122 continue; 2123 } 2124 2125 case VisitorJob::DeclarationNameInfoVisitKind: { 2126 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI) 2127 ->get())) 2128 return true; 2129 continue; 2130 } 2131 case VisitorJob::MemberRefVisitKind: { 2132 MemberRefVisit *V = cast<MemberRefVisit>(&LI); 2133 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU))) 2134 return true; 2135 continue; 2136 } 2137 case VisitorJob::StmtVisitKind: { 2138 Stmt *S = cast<StmtVisit>(&LI)->get(); 2139 if (!S) 2140 continue; 2141 2142 // Update the current cursor. 2143 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU); 2144 if (!IsInRegionOfInterest(Cursor)) 2145 continue; 2146 switch (Visitor(Cursor, Parent, ClientData)) { 2147 case CXChildVisit_Break: return true; 2148 case CXChildVisit_Continue: break; 2149 case CXChildVisit_Recurse: 2150 EnqueueWorkList(WL, S); 2151 break; 2152 } 2153 continue; 2154 } 2155 case VisitorJob::MemberExprPartsKind: { 2156 // Handle the other pieces in the MemberExpr besides the base. 2157 MemberExpr *M = cast<MemberExprParts>(&LI)->get(); 2158 2159 // Visit the nested-name-specifier 2160 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc()) 2161 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 2162 return true; 2163 2164 // Visit the declaration name. 2165 if (VisitDeclarationNameInfo(M->getMemberNameInfo())) 2166 return true; 2167 2168 // Visit the explicitly-specified template arguments, if any. 2169 if (M->hasExplicitTemplateArgs()) { 2170 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(), 2171 *ArgEnd = Arg + M->getNumTemplateArgs(); 2172 Arg != ArgEnd; ++Arg) { 2173 if (VisitTemplateArgumentLoc(*Arg)) 2174 return true; 2175 } 2176 } 2177 continue; 2178 } 2179 case VisitorJob::DeclRefExprPartsKind: { 2180 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get(); 2181 // Visit nested-name-specifier, if present. 2182 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc()) 2183 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 2184 return true; 2185 // Visit declaration name. 2186 if (VisitDeclarationNameInfo(DR->getNameInfo())) 2187 return true; 2188 continue; 2189 } 2190 case VisitorJob::OverloadExprPartsKind: { 2191 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get(); 2192 // Visit the nested-name-specifier. 2193 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc()) 2194 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 2195 return true; 2196 // Visit the declaration name. 2197 if (VisitDeclarationNameInfo(O->getNameInfo())) 2198 return true; 2199 // Visit the overloaded declaration reference. 2200 if (Visit(MakeCursorOverloadedDeclRef(O, TU))) 2201 return true; 2202 continue; 2203 } 2204 case VisitorJob::SizeOfPackExprPartsKind: { 2205 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get(); 2206 NamedDecl *Pack = E->getPack(); 2207 if (isa<TemplateTypeParmDecl>(Pack)) { 2208 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack), 2209 E->getPackLoc(), TU))) 2210 return true; 2211 2212 continue; 2213 } 2214 2215 if (isa<TemplateTemplateParmDecl>(Pack)) { 2216 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack), 2217 E->getPackLoc(), TU))) 2218 return true; 2219 2220 continue; 2221 } 2222 2223 // Non-type template parameter packs and function parameter packs are 2224 // treated like DeclRefExpr cursors. 2225 continue; 2226 } 2227 } 2228 } 2229 return false; 2230} 2231 2232bool CursorVisitor::Visit(Stmt *S) { 2233 VisitorWorkList *WL = 0; 2234 if (!WorkListFreeList.empty()) { 2235 WL = WorkListFreeList.back(); 2236 WL->clear(); 2237 WorkListFreeList.pop_back(); 2238 } 2239 else { 2240 WL = new VisitorWorkList(); 2241 WorkListCache.push_back(WL); 2242 } 2243 EnqueueWorkList(*WL, S); 2244 bool result = RunVisitorWorkList(*WL); 2245 WorkListFreeList.push_back(WL); 2246 return result; 2247} 2248 2249//===----------------------------------------------------------------------===// 2250// Misc. API hooks. 2251//===----------------------------------------------------------------------===// 2252 2253static llvm::sys::Mutex EnableMultithreadingMutex; 2254static bool EnabledMultithreading; 2255 2256extern "C" { 2257CXIndex clang_createIndex(int excludeDeclarationsFromPCH, 2258 int displayDiagnostics) { 2259 // Disable pretty stack trace functionality, which will otherwise be a very 2260 // poor citizen of the world and set up all sorts of signal handlers. 2261 llvm::DisablePrettyStackTrace = true; 2262 2263 // We use crash recovery to make some of our APIs more reliable, implicitly 2264 // enable it. 2265 llvm::CrashRecoveryContext::Enable(); 2266 2267 // Enable support for multithreading in LLVM. 2268 { 2269 llvm::sys::ScopedLock L(EnableMultithreadingMutex); 2270 if (!EnabledMultithreading) { 2271 llvm::llvm_start_multithreaded(); 2272 EnabledMultithreading = true; 2273 } 2274 } 2275 2276 CIndexer *CIdxr = new CIndexer(); 2277 if (excludeDeclarationsFromPCH) 2278 CIdxr->setOnlyLocalDecls(); 2279 if (displayDiagnostics) 2280 CIdxr->setDisplayDiagnostics(); 2281 return CIdxr; 2282} 2283 2284void clang_disposeIndex(CXIndex CIdx) { 2285 if (CIdx) 2286 delete static_cast<CIndexer *>(CIdx); 2287} 2288 2289CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx, 2290 const char *ast_filename) { 2291 if (!CIdx) 2292 return 0; 2293 2294 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx); 2295 FileSystemOptions FileSystemOpts; 2296 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory(); 2297 2298 llvm::IntrusiveRefCntPtr<Diagnostic> Diags; 2299 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts, 2300 CXXIdx->getOnlyLocalDecls(), 2301 0, 0, true); 2302 return MakeCXTranslationUnit(TU); 2303} 2304 2305unsigned clang_defaultEditingTranslationUnitOptions() { 2306 return CXTranslationUnit_PrecompiledPreamble | 2307 CXTranslationUnit_CacheCompletionResults | 2308 CXTranslationUnit_CXXPrecompiledPreamble; 2309} 2310 2311CXTranslationUnit 2312clang_createTranslationUnitFromSourceFile(CXIndex CIdx, 2313 const char *source_filename, 2314 int num_command_line_args, 2315 const char * const *command_line_args, 2316 unsigned num_unsaved_files, 2317 struct CXUnsavedFile *unsaved_files) { 2318 return clang_parseTranslationUnit(CIdx, source_filename, 2319 command_line_args, num_command_line_args, 2320 unsaved_files, num_unsaved_files, 2321 CXTranslationUnit_DetailedPreprocessingRecord); 2322} 2323 2324struct ParseTranslationUnitInfo { 2325 CXIndex CIdx; 2326 const char *source_filename; 2327 const char *const *command_line_args; 2328 int num_command_line_args; 2329 struct CXUnsavedFile *unsaved_files; 2330 unsigned num_unsaved_files; 2331 unsigned options; 2332 CXTranslationUnit result; 2333}; 2334static void clang_parseTranslationUnit_Impl(void *UserData) { 2335 ParseTranslationUnitInfo *PTUI = 2336 static_cast<ParseTranslationUnitInfo*>(UserData); 2337 CXIndex CIdx = PTUI->CIdx; 2338 const char *source_filename = PTUI->source_filename; 2339 const char * const *command_line_args = PTUI->command_line_args; 2340 int num_command_line_args = PTUI->num_command_line_args; 2341 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files; 2342 unsigned num_unsaved_files = PTUI->num_unsaved_files; 2343 unsigned options = PTUI->options; 2344 PTUI->result = 0; 2345 2346 if (!CIdx) 2347 return; 2348 2349 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx); 2350 2351 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble; 2352 bool CompleteTranslationUnit 2353 = ((options & CXTranslationUnit_Incomplete) == 0); 2354 bool CacheCodeCompetionResults 2355 = options & CXTranslationUnit_CacheCompletionResults; 2356 bool CXXPrecompilePreamble 2357 = options & CXTranslationUnit_CXXPrecompiledPreamble; 2358 bool CXXChainedPCH 2359 = options & CXTranslationUnit_CXXChainedPCH; 2360 2361 // Configure the diagnostics. 2362 DiagnosticOptions DiagOpts; 2363 llvm::IntrusiveRefCntPtr<Diagnostic> Diags; 2364 Diags = CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args, 2365 command_line_args); 2366 2367 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles; 2368 for (unsigned I = 0; I != num_unsaved_files; ++I) { 2369 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length); 2370 const llvm::MemoryBuffer *Buffer 2371 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename); 2372 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename, 2373 Buffer)); 2374 } 2375 2376 llvm::SmallVector<const char *, 16> Args; 2377 2378 // The 'source_filename' argument is optional. If the caller does not 2379 // specify it then it is assumed that the source file is specified 2380 // in the actual argument list. 2381 if (source_filename) 2382 Args.push_back(source_filename); 2383 2384 // Since the Clang C library is primarily used by batch tools dealing with 2385 // (often very broken) source code, where spell-checking can have a 2386 // significant negative impact on performance (particularly when 2387 // precompiled headers are involved), we disable it by default. 2388 // Only do this if we haven't found a spell-checking-related argument. 2389 bool FoundSpellCheckingArgument = false; 2390 for (int I = 0; I != num_command_line_args; ++I) { 2391 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 || 2392 strcmp(command_line_args[I], "-fspell-checking") == 0) { 2393 FoundSpellCheckingArgument = true; 2394 break; 2395 } 2396 } 2397 if (!FoundSpellCheckingArgument) 2398 Args.push_back("-fno-spell-checking"); 2399 2400 Args.insert(Args.end(), command_line_args, 2401 command_line_args + num_command_line_args); 2402 2403 // Do we need the detailed preprocessing record? 2404 if (options & CXTranslationUnit_DetailedPreprocessingRecord) { 2405 Args.push_back("-Xclang"); 2406 Args.push_back("-detailed-preprocessing-record"); 2407 } 2408 2409 unsigned NumErrors = Diags->getClient()->getNumErrors(); 2410 llvm::OwningPtr<ASTUnit> Unit( 2411 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(), 2412 Diags, 2413 CXXIdx->getClangResourcesPath(), 2414 CXXIdx->getOnlyLocalDecls(), 2415 /*CaptureDiagnostics=*/true, 2416 RemappedFiles.data(), 2417 RemappedFiles.size(), 2418 PrecompilePreamble, 2419 CompleteTranslationUnit, 2420 CacheCodeCompetionResults, 2421 CXXPrecompilePreamble, 2422 CXXChainedPCH)); 2423 2424 if (NumErrors != Diags->getClient()->getNumErrors()) { 2425 // Make sure to check that 'Unit' is non-NULL. 2426 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) { 2427 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(), 2428 DEnd = Unit->stored_diag_end(); 2429 D != DEnd; ++D) { 2430 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions()); 2431 CXString Msg = clang_formatDiagnostic(&Diag, 2432 clang_defaultDiagnosticDisplayOptions()); 2433 fprintf(stderr, "%s\n", clang_getCString(Msg)); 2434 clang_disposeString(Msg); 2435 } 2436#ifdef LLVM_ON_WIN32 2437 // On Windows, force a flush, since there may be multiple copies of 2438 // stderr and stdout in the file system, all with different buffers 2439 // but writing to the same device. 2440 fflush(stderr); 2441#endif 2442 } 2443 } 2444 2445 PTUI->result = MakeCXTranslationUnit(Unit.take()); 2446} 2447CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx, 2448 const char *source_filename, 2449 const char * const *command_line_args, 2450 int num_command_line_args, 2451 struct CXUnsavedFile *unsaved_files, 2452 unsigned num_unsaved_files, 2453 unsigned options) { 2454 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args, 2455 num_command_line_args, unsaved_files, 2456 num_unsaved_files, options, 0 }; 2457 llvm::CrashRecoveryContext CRC; 2458 2459 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) { 2460 fprintf(stderr, "libclang: crash detected during parsing: {\n"); 2461 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename); 2462 fprintf(stderr, " 'command_line_args' : ["); 2463 for (int i = 0; i != num_command_line_args; ++i) { 2464 if (i) 2465 fprintf(stderr, ", "); 2466 fprintf(stderr, "'%s'", command_line_args[i]); 2467 } 2468 fprintf(stderr, "],\n"); 2469 fprintf(stderr, " 'unsaved_files' : ["); 2470 for (unsigned i = 0; i != num_unsaved_files; ++i) { 2471 if (i) 2472 fprintf(stderr, ", "); 2473 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename, 2474 unsaved_files[i].Length); 2475 } 2476 fprintf(stderr, "],\n"); 2477 fprintf(stderr, " 'options' : %d,\n", options); 2478 fprintf(stderr, "}\n"); 2479 2480 return 0; 2481 } 2482 2483 return PTUI.result; 2484} 2485 2486unsigned clang_defaultSaveOptions(CXTranslationUnit TU) { 2487 return CXSaveTranslationUnit_None; 2488} 2489 2490int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName, 2491 unsigned options) { 2492 if (!TU) 2493 return 1; 2494 2495 return static_cast<ASTUnit *>(TU->TUData)->Save(FileName); 2496} 2497 2498void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) { 2499 if (CTUnit) { 2500 // If the translation unit has been marked as unsafe to free, just discard 2501 // it. 2502 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree()) 2503 return; 2504 2505 delete static_cast<ASTUnit *>(CTUnit->TUData); 2506 disposeCXStringPool(CTUnit->StringPool); 2507 delete CTUnit; 2508 } 2509} 2510 2511unsigned clang_defaultReparseOptions(CXTranslationUnit TU) { 2512 return CXReparse_None; 2513} 2514 2515struct ReparseTranslationUnitInfo { 2516 CXTranslationUnit TU; 2517 unsigned num_unsaved_files; 2518 struct CXUnsavedFile *unsaved_files; 2519 unsigned options; 2520 int result; 2521}; 2522 2523static void clang_reparseTranslationUnit_Impl(void *UserData) { 2524 ReparseTranslationUnitInfo *RTUI = 2525 static_cast<ReparseTranslationUnitInfo*>(UserData); 2526 CXTranslationUnit TU = RTUI->TU; 2527 unsigned num_unsaved_files = RTUI->num_unsaved_files; 2528 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files; 2529 unsigned options = RTUI->options; 2530 (void) options; 2531 RTUI->result = 1; 2532 2533 if (!TU) 2534 return; 2535 2536 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 2537 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 2538 2539 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles; 2540 for (unsigned I = 0; I != num_unsaved_files; ++I) { 2541 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length); 2542 const llvm::MemoryBuffer *Buffer 2543 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename); 2544 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename, 2545 Buffer)); 2546 } 2547 2548 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size())) 2549 RTUI->result = 0; 2550} 2551 2552int clang_reparseTranslationUnit(CXTranslationUnit TU, 2553 unsigned num_unsaved_files, 2554 struct CXUnsavedFile *unsaved_files, 2555 unsigned options) { 2556 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files, 2557 options, 0 }; 2558 llvm::CrashRecoveryContext CRC; 2559 2560 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) { 2561 fprintf(stderr, "libclang: crash detected during reparsing\n"); 2562 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true); 2563 return 1; 2564 } 2565 2566 2567 return RTUI.result; 2568} 2569 2570 2571CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) { 2572 if (!CTUnit) 2573 return createCXString(""); 2574 2575 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData); 2576 return createCXString(CXXUnit->getOriginalSourceFileName(), true); 2577} 2578 2579CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) { 2580 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } }; 2581 return Result; 2582} 2583 2584} // end: extern "C" 2585 2586//===----------------------------------------------------------------------===// 2587// CXSourceLocation and CXSourceRange Operations. 2588//===----------------------------------------------------------------------===// 2589 2590extern "C" { 2591CXSourceLocation clang_getNullLocation() { 2592 CXSourceLocation Result = { { 0, 0 }, 0 }; 2593 return Result; 2594} 2595 2596unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) { 2597 return (loc1.ptr_data[0] == loc2.ptr_data[0] && 2598 loc1.ptr_data[1] == loc2.ptr_data[1] && 2599 loc1.int_data == loc2.int_data); 2600} 2601 2602CXSourceLocation clang_getLocation(CXTranslationUnit tu, 2603 CXFile file, 2604 unsigned line, 2605 unsigned column) { 2606 if (!tu || !file) 2607 return clang_getNullLocation(); 2608 2609 bool Logging = ::getenv("LIBCLANG_LOGGING"); 2610 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData); 2611 const FileEntry *File = static_cast<const FileEntry *>(file); 2612 SourceLocation SLoc 2613 = CXXUnit->getSourceManager().getLocation(File, line, column); 2614 if (SLoc.isInvalid()) { 2615 if (Logging) 2616 llvm::errs() << "clang_getLocation(\"" << File->getName() 2617 << "\", " << line << ", " << column << ") = invalid\n"; 2618 return clang_getNullLocation(); 2619 } 2620 2621 if (Logging) 2622 llvm::errs() << "clang_getLocation(\"" << File->getName() 2623 << "\", " << line << ", " << column << ") = " 2624 << SLoc.getRawEncoding() << "\n"; 2625 2626 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc); 2627} 2628 2629CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu, 2630 CXFile file, 2631 unsigned offset) { 2632 if (!tu || !file) 2633 return clang_getNullLocation(); 2634 2635 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData); 2636 SourceLocation Start 2637 = CXXUnit->getSourceManager().getLocation( 2638 static_cast<const FileEntry *>(file), 2639 1, 1); 2640 if (Start.isInvalid()) return clang_getNullLocation(); 2641 2642 SourceLocation SLoc = Start.getFileLocWithOffset(offset); 2643 2644 if (SLoc.isInvalid()) return clang_getNullLocation(); 2645 2646 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc); 2647} 2648 2649CXSourceRange clang_getNullRange() { 2650 CXSourceRange Result = { { 0, 0 }, 0, 0 }; 2651 return Result; 2652} 2653 2654CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) { 2655 if (begin.ptr_data[0] != end.ptr_data[0] || 2656 begin.ptr_data[1] != end.ptr_data[1]) 2657 return clang_getNullRange(); 2658 2659 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] }, 2660 begin.int_data, end.int_data }; 2661 return Result; 2662} 2663 2664void clang_getInstantiationLocation(CXSourceLocation location, 2665 CXFile *file, 2666 unsigned *line, 2667 unsigned *column, 2668 unsigned *offset) { 2669 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data); 2670 2671 if (!location.ptr_data[0] || Loc.isInvalid()) { 2672 if (file) 2673 *file = 0; 2674 if (line) 2675 *line = 0; 2676 if (column) 2677 *column = 0; 2678 if (offset) 2679 *offset = 0; 2680 return; 2681 } 2682 2683 const SourceManager &SM = 2684 *static_cast<const SourceManager*>(location.ptr_data[0]); 2685 SourceLocation InstLoc = SM.getInstantiationLoc(Loc); 2686 2687 if (file) 2688 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc)); 2689 if (line) 2690 *line = SM.getInstantiationLineNumber(InstLoc); 2691 if (column) 2692 *column = SM.getInstantiationColumnNumber(InstLoc); 2693 if (offset) 2694 *offset = SM.getDecomposedLoc(InstLoc).second; 2695} 2696 2697void clang_getSpellingLocation(CXSourceLocation location, 2698 CXFile *file, 2699 unsigned *line, 2700 unsigned *column, 2701 unsigned *offset) { 2702 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data); 2703 2704 if (!location.ptr_data[0] || Loc.isInvalid()) { 2705 if (file) 2706 *file = 0; 2707 if (line) 2708 *line = 0; 2709 if (column) 2710 *column = 0; 2711 if (offset) 2712 *offset = 0; 2713 return; 2714 } 2715 2716 const SourceManager &SM = 2717 *static_cast<const SourceManager*>(location.ptr_data[0]); 2718 SourceLocation SpellLoc = Loc; 2719 if (SpellLoc.isMacroID()) { 2720 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc); 2721 if (SimpleSpellingLoc.isFileID() && 2722 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first)) 2723 SpellLoc = SimpleSpellingLoc; 2724 else 2725 SpellLoc = SM.getInstantiationLoc(SpellLoc); 2726 } 2727 2728 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc); 2729 FileID FID = LocInfo.first; 2730 unsigned FileOffset = LocInfo.second; 2731 2732 if (file) 2733 *file = (void *)SM.getFileEntryForID(FID); 2734 if (line) 2735 *line = SM.getLineNumber(FID, FileOffset); 2736 if (column) 2737 *column = SM.getColumnNumber(FID, FileOffset); 2738 if (offset) 2739 *offset = FileOffset; 2740} 2741 2742CXSourceLocation clang_getRangeStart(CXSourceRange range) { 2743 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] }, 2744 range.begin_int_data }; 2745 return Result; 2746} 2747 2748CXSourceLocation clang_getRangeEnd(CXSourceRange range) { 2749 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] }, 2750 range.end_int_data }; 2751 return Result; 2752} 2753 2754} // end: extern "C" 2755 2756//===----------------------------------------------------------------------===// 2757// CXFile Operations. 2758//===----------------------------------------------------------------------===// 2759 2760extern "C" { 2761CXString clang_getFileName(CXFile SFile) { 2762 if (!SFile) 2763 return createCXString((const char*)NULL); 2764 2765 FileEntry *FEnt = static_cast<FileEntry *>(SFile); 2766 return createCXString(FEnt->getName()); 2767} 2768 2769time_t clang_getFileTime(CXFile SFile) { 2770 if (!SFile) 2771 return 0; 2772 2773 FileEntry *FEnt = static_cast<FileEntry *>(SFile); 2774 return FEnt->getModificationTime(); 2775} 2776 2777CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) { 2778 if (!tu) 2779 return 0; 2780 2781 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData); 2782 2783 FileManager &FMgr = CXXUnit->getFileManager(); 2784 return const_cast<FileEntry *>(FMgr.getFile(file_name)); 2785} 2786 2787} // end: extern "C" 2788 2789//===----------------------------------------------------------------------===// 2790// CXCursor Operations. 2791//===----------------------------------------------------------------------===// 2792 2793static Decl *getDeclFromExpr(Stmt *E) { 2794 if (CastExpr *CE = dyn_cast<CastExpr>(E)) 2795 return getDeclFromExpr(CE->getSubExpr()); 2796 2797 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E)) 2798 return RefExpr->getDecl(); 2799 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E)) 2800 return RefExpr->getDecl(); 2801 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) 2802 return ME->getMemberDecl(); 2803 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E)) 2804 return RE->getDecl(); 2805 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) 2806 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0; 2807 2808 if (CallExpr *CE = dyn_cast<CallExpr>(E)) 2809 return getDeclFromExpr(CE->getCallee()); 2810 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E)) 2811 if (!CE->isElidable()) 2812 return CE->getConstructor(); 2813 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E)) 2814 return OME->getMethodDecl(); 2815 2816 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E)) 2817 return PE->getProtocol(); 2818 if (SubstNonTypeTemplateParmPackExpr *NTTP 2819 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E)) 2820 return NTTP->getParameterPack(); 2821 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E)) 2822 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) || 2823 isa<ParmVarDecl>(SizeOfPack->getPack())) 2824 return SizeOfPack->getPack(); 2825 2826 return 0; 2827} 2828 2829static SourceLocation getLocationFromExpr(Expr *E) { 2830 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) 2831 return /*FIXME:*/Msg->getLeftLoc(); 2832 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 2833 return DRE->getLocation(); 2834 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E)) 2835 return RefExpr->getLocation(); 2836 if (MemberExpr *Member = dyn_cast<MemberExpr>(E)) 2837 return Member->getMemberLoc(); 2838 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) 2839 return Ivar->getLocation(); 2840 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E)) 2841 return SizeOfPack->getPackLoc(); 2842 2843 return E->getLocStart(); 2844} 2845 2846extern "C" { 2847 2848unsigned clang_visitChildren(CXCursor parent, 2849 CXCursorVisitor visitor, 2850 CXClientData client_data) { 2851 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data, 2852 getCursorASTUnit(parent)->getMaxPCHLevel()); 2853 return CursorVis.VisitChildren(parent); 2854} 2855 2856#ifndef __has_feature 2857#define __has_feature(x) 0 2858#endif 2859#if __has_feature(blocks) 2860typedef enum CXChildVisitResult 2861 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent); 2862 2863static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent, 2864 CXClientData client_data) { 2865 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data; 2866 return block(cursor, parent); 2867} 2868#else 2869// If we are compiled with a compiler that doesn't have native blocks support, 2870// define and call the block manually, so the 2871typedef struct _CXChildVisitResult 2872{ 2873 void *isa; 2874 int flags; 2875 int reserved; 2876 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor, 2877 CXCursor); 2878} *CXCursorVisitorBlock; 2879 2880static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent, 2881 CXClientData client_data) { 2882 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data; 2883 return block->invoke(block, cursor, parent); 2884} 2885#endif 2886 2887 2888unsigned clang_visitChildrenWithBlock(CXCursor parent, 2889 CXCursorVisitorBlock block) { 2890 return clang_visitChildren(parent, visitWithBlock, block); 2891} 2892 2893static CXString getDeclSpelling(Decl *D) { 2894 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D); 2895 if (!ND) { 2896 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D)) 2897 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl()) 2898 return createCXString(Property->getIdentifier()->getName()); 2899 2900 return createCXString(""); 2901 } 2902 2903 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND)) 2904 return createCXString(OMD->getSelector().getAsString()); 2905 2906 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND)) 2907 // No, this isn't the same as the code below. getIdentifier() is non-virtual 2908 // and returns different names. NamedDecl returns the class name and 2909 // ObjCCategoryImplDecl returns the category name. 2910 return createCXString(CIMP->getIdentifier()->getNameStart()); 2911 2912 if (isa<UsingDirectiveDecl>(D)) 2913 return createCXString(""); 2914 2915 llvm::SmallString<1024> S; 2916 llvm::raw_svector_ostream os(S); 2917 ND->printName(os); 2918 2919 return createCXString(os.str()); 2920} 2921 2922CXString clang_getCursorSpelling(CXCursor C) { 2923 if (clang_isTranslationUnit(C.kind)) 2924 return clang_getTranslationUnitSpelling( 2925 static_cast<CXTranslationUnit>(C.data[2])); 2926 2927 if (clang_isReference(C.kind)) { 2928 switch (C.kind) { 2929 case CXCursor_ObjCSuperClassRef: { 2930 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first; 2931 return createCXString(Super->getIdentifier()->getNameStart()); 2932 } 2933 case CXCursor_ObjCClassRef: { 2934 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first; 2935 return createCXString(Class->getIdentifier()->getNameStart()); 2936 } 2937 case CXCursor_ObjCProtocolRef: { 2938 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first; 2939 assert(OID && "getCursorSpelling(): Missing protocol decl"); 2940 return createCXString(OID->getIdentifier()->getNameStart()); 2941 } 2942 case CXCursor_CXXBaseSpecifier: { 2943 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C); 2944 return createCXString(B->getType().getAsString()); 2945 } 2946 case CXCursor_TypeRef: { 2947 TypeDecl *Type = getCursorTypeRef(C).first; 2948 assert(Type && "Missing type decl"); 2949 2950 return createCXString(getCursorContext(C).getTypeDeclType(Type). 2951 getAsString()); 2952 } 2953 case CXCursor_TemplateRef: { 2954 TemplateDecl *Template = getCursorTemplateRef(C).first; 2955 assert(Template && "Missing template decl"); 2956 2957 return createCXString(Template->getNameAsString()); 2958 } 2959 2960 case CXCursor_NamespaceRef: { 2961 NamedDecl *NS = getCursorNamespaceRef(C).first; 2962 assert(NS && "Missing namespace decl"); 2963 2964 return createCXString(NS->getNameAsString()); 2965 } 2966 2967 case CXCursor_MemberRef: { 2968 FieldDecl *Field = getCursorMemberRef(C).first; 2969 assert(Field && "Missing member decl"); 2970 2971 return createCXString(Field->getNameAsString()); 2972 } 2973 2974 case CXCursor_LabelRef: { 2975 LabelStmt *Label = getCursorLabelRef(C).first; 2976 assert(Label && "Missing label"); 2977 2978 return createCXString(Label->getName()); 2979 } 2980 2981 case CXCursor_OverloadedDeclRef: { 2982 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first; 2983 if (Decl *D = Storage.dyn_cast<Decl *>()) { 2984 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) 2985 return createCXString(ND->getNameAsString()); 2986 return createCXString(""); 2987 } 2988 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>()) 2989 return createCXString(E->getName().getAsString()); 2990 OverloadedTemplateStorage *Ovl 2991 = Storage.get<OverloadedTemplateStorage*>(); 2992 if (Ovl->size() == 0) 2993 return createCXString(""); 2994 return createCXString((*Ovl->begin())->getNameAsString()); 2995 } 2996 2997 default: 2998 return createCXString("<not implemented>"); 2999 } 3000 } 3001 3002 if (clang_isExpression(C.kind)) { 3003 Decl *D = getDeclFromExpr(getCursorExpr(C)); 3004 if (D) 3005 return getDeclSpelling(D); 3006 return createCXString(""); 3007 } 3008 3009 if (clang_isStatement(C.kind)) { 3010 Stmt *S = getCursorStmt(C); 3011 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) 3012 return createCXString(Label->getName()); 3013 3014 return createCXString(""); 3015 } 3016 3017 if (C.kind == CXCursor_MacroInstantiation) 3018 return createCXString(getCursorMacroInstantiation(C)->getName() 3019 ->getNameStart()); 3020 3021 if (C.kind == CXCursor_MacroDefinition) 3022 return createCXString(getCursorMacroDefinition(C)->getName() 3023 ->getNameStart()); 3024 3025 if (C.kind == CXCursor_InclusionDirective) 3026 return createCXString(getCursorInclusionDirective(C)->getFileName()); 3027 3028 if (clang_isDeclaration(C.kind)) 3029 return getDeclSpelling(getCursorDecl(C)); 3030 3031 return createCXString(""); 3032} 3033 3034CXString clang_getCursorDisplayName(CXCursor C) { 3035 if (!clang_isDeclaration(C.kind)) 3036 return clang_getCursorSpelling(C); 3037 3038 Decl *D = getCursorDecl(C); 3039 if (!D) 3040 return createCXString(""); 3041 3042 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy; 3043 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 3044 D = FunTmpl->getTemplatedDecl(); 3045 3046 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 3047 llvm::SmallString<64> Str; 3048 llvm::raw_svector_ostream OS(Str); 3049 OS << Function->getNameAsString(); 3050 if (Function->getPrimaryTemplate()) 3051 OS << "<>"; 3052 OS << "("; 3053 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) { 3054 if (I) 3055 OS << ", "; 3056 OS << Function->getParamDecl(I)->getType().getAsString(Policy); 3057 } 3058 3059 if (Function->isVariadic()) { 3060 if (Function->getNumParams()) 3061 OS << ", "; 3062 OS << "..."; 3063 } 3064 OS << ")"; 3065 return createCXString(OS.str()); 3066 } 3067 3068 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) { 3069 llvm::SmallString<64> Str; 3070 llvm::raw_svector_ostream OS(Str); 3071 OS << ClassTemplate->getNameAsString(); 3072 OS << "<"; 3073 TemplateParameterList *Params = ClassTemplate->getTemplateParameters(); 3074 for (unsigned I = 0, N = Params->size(); I != N; ++I) { 3075 if (I) 3076 OS << ", "; 3077 3078 NamedDecl *Param = Params->getParam(I); 3079 if (Param->getIdentifier()) { 3080 OS << Param->getIdentifier()->getName(); 3081 continue; 3082 } 3083 3084 // There is no parameter name, which makes this tricky. Try to come up 3085 // with something useful that isn't too long. 3086 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) 3087 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class"); 3088 else if (NonTypeTemplateParmDecl *NTTP 3089 = dyn_cast<NonTypeTemplateParmDecl>(Param)) 3090 OS << NTTP->getType().getAsString(Policy); 3091 else 3092 OS << "template<...> class"; 3093 } 3094 3095 OS << ">"; 3096 return createCXString(OS.str()); 3097 } 3098 3099 if (ClassTemplateSpecializationDecl *ClassSpec 3100 = dyn_cast<ClassTemplateSpecializationDecl>(D)) { 3101 // If the type was explicitly written, use that. 3102 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten()) 3103 return createCXString(TSInfo->getType().getAsString(Policy)); 3104 3105 llvm::SmallString<64> Str; 3106 llvm::raw_svector_ostream OS(Str); 3107 OS << ClassSpec->getNameAsString(); 3108 OS << TemplateSpecializationType::PrintTemplateArgumentList( 3109 ClassSpec->getTemplateArgs().data(), 3110 ClassSpec->getTemplateArgs().size(), 3111 Policy); 3112 return createCXString(OS.str()); 3113 } 3114 3115 return clang_getCursorSpelling(C); 3116} 3117 3118CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) { 3119 switch (Kind) { 3120 case CXCursor_FunctionDecl: 3121 return createCXString("FunctionDecl"); 3122 case CXCursor_TypedefDecl: 3123 return createCXString("TypedefDecl"); 3124 case CXCursor_EnumDecl: 3125 return createCXString("EnumDecl"); 3126 case CXCursor_EnumConstantDecl: 3127 return createCXString("EnumConstantDecl"); 3128 case CXCursor_StructDecl: 3129 return createCXString("StructDecl"); 3130 case CXCursor_UnionDecl: 3131 return createCXString("UnionDecl"); 3132 case CXCursor_ClassDecl: 3133 return createCXString("ClassDecl"); 3134 case CXCursor_FieldDecl: 3135 return createCXString("FieldDecl"); 3136 case CXCursor_VarDecl: 3137 return createCXString("VarDecl"); 3138 case CXCursor_ParmDecl: 3139 return createCXString("ParmDecl"); 3140 case CXCursor_ObjCInterfaceDecl: 3141 return createCXString("ObjCInterfaceDecl"); 3142 case CXCursor_ObjCCategoryDecl: 3143 return createCXString("ObjCCategoryDecl"); 3144 case CXCursor_ObjCProtocolDecl: 3145 return createCXString("ObjCProtocolDecl"); 3146 case CXCursor_ObjCPropertyDecl: 3147 return createCXString("ObjCPropertyDecl"); 3148 case CXCursor_ObjCIvarDecl: 3149 return createCXString("ObjCIvarDecl"); 3150 case CXCursor_ObjCInstanceMethodDecl: 3151 return createCXString("ObjCInstanceMethodDecl"); 3152 case CXCursor_ObjCClassMethodDecl: 3153 return createCXString("ObjCClassMethodDecl"); 3154 case CXCursor_ObjCImplementationDecl: 3155 return createCXString("ObjCImplementationDecl"); 3156 case CXCursor_ObjCCategoryImplDecl: 3157 return createCXString("ObjCCategoryImplDecl"); 3158 case CXCursor_CXXMethod: 3159 return createCXString("CXXMethod"); 3160 case CXCursor_UnexposedDecl: 3161 return createCXString("UnexposedDecl"); 3162 case CXCursor_ObjCSuperClassRef: 3163 return createCXString("ObjCSuperClassRef"); 3164 case CXCursor_ObjCProtocolRef: 3165 return createCXString("ObjCProtocolRef"); 3166 case CXCursor_ObjCClassRef: 3167 return createCXString("ObjCClassRef"); 3168 case CXCursor_TypeRef: 3169 return createCXString("TypeRef"); 3170 case CXCursor_TemplateRef: 3171 return createCXString("TemplateRef"); 3172 case CXCursor_NamespaceRef: 3173 return createCXString("NamespaceRef"); 3174 case CXCursor_MemberRef: 3175 return createCXString("MemberRef"); 3176 case CXCursor_LabelRef: 3177 return createCXString("LabelRef"); 3178 case CXCursor_OverloadedDeclRef: 3179 return createCXString("OverloadedDeclRef"); 3180 case CXCursor_UnexposedExpr: 3181 return createCXString("UnexposedExpr"); 3182 case CXCursor_BlockExpr: 3183 return createCXString("BlockExpr"); 3184 case CXCursor_DeclRefExpr: 3185 return createCXString("DeclRefExpr"); 3186 case CXCursor_MemberRefExpr: 3187 return createCXString("MemberRefExpr"); 3188 case CXCursor_CallExpr: 3189 return createCXString("CallExpr"); 3190 case CXCursor_ObjCMessageExpr: 3191 return createCXString("ObjCMessageExpr"); 3192 case CXCursor_UnexposedStmt: 3193 return createCXString("UnexposedStmt"); 3194 case CXCursor_LabelStmt: 3195 return createCXString("LabelStmt"); 3196 case CXCursor_InvalidFile: 3197 return createCXString("InvalidFile"); 3198 case CXCursor_InvalidCode: 3199 return createCXString("InvalidCode"); 3200 case CXCursor_NoDeclFound: 3201 return createCXString("NoDeclFound"); 3202 case CXCursor_NotImplemented: 3203 return createCXString("NotImplemented"); 3204 case CXCursor_TranslationUnit: 3205 return createCXString("TranslationUnit"); 3206 case CXCursor_UnexposedAttr: 3207 return createCXString("UnexposedAttr"); 3208 case CXCursor_IBActionAttr: 3209 return createCXString("attribute(ibaction)"); 3210 case CXCursor_IBOutletAttr: 3211 return createCXString("attribute(iboutlet)"); 3212 case CXCursor_IBOutletCollectionAttr: 3213 return createCXString("attribute(iboutletcollection)"); 3214 case CXCursor_PreprocessingDirective: 3215 return createCXString("preprocessing directive"); 3216 case CXCursor_MacroDefinition: 3217 return createCXString("macro definition"); 3218 case CXCursor_MacroInstantiation: 3219 return createCXString("macro instantiation"); 3220 case CXCursor_InclusionDirective: 3221 return createCXString("inclusion directive"); 3222 case CXCursor_Namespace: 3223 return createCXString("Namespace"); 3224 case CXCursor_LinkageSpec: 3225 return createCXString("LinkageSpec"); 3226 case CXCursor_CXXBaseSpecifier: 3227 return createCXString("C++ base class specifier"); 3228 case CXCursor_Constructor: 3229 return createCXString("CXXConstructor"); 3230 case CXCursor_Destructor: 3231 return createCXString("CXXDestructor"); 3232 case CXCursor_ConversionFunction: 3233 return createCXString("CXXConversion"); 3234 case CXCursor_TemplateTypeParameter: 3235 return createCXString("TemplateTypeParameter"); 3236 case CXCursor_NonTypeTemplateParameter: 3237 return createCXString("NonTypeTemplateParameter"); 3238 case CXCursor_TemplateTemplateParameter: 3239 return createCXString("TemplateTemplateParameter"); 3240 case CXCursor_FunctionTemplate: 3241 return createCXString("FunctionTemplate"); 3242 case CXCursor_ClassTemplate: 3243 return createCXString("ClassTemplate"); 3244 case CXCursor_ClassTemplatePartialSpecialization: 3245 return createCXString("ClassTemplatePartialSpecialization"); 3246 case CXCursor_NamespaceAlias: 3247 return createCXString("NamespaceAlias"); 3248 case CXCursor_UsingDirective: 3249 return createCXString("UsingDirective"); 3250 case CXCursor_UsingDeclaration: 3251 return createCXString("UsingDeclaration"); 3252 } 3253 3254 llvm_unreachable("Unhandled CXCursorKind"); 3255 return createCXString((const char*) 0); 3256} 3257 3258enum CXChildVisitResult GetCursorVisitor(CXCursor cursor, 3259 CXCursor parent, 3260 CXClientData client_data) { 3261 CXCursor *BestCursor = static_cast<CXCursor *>(client_data); 3262 3263 // If our current best cursor is the construction of a temporary object, 3264 // don't replace that cursor with a type reference, because we want 3265 // clang_getCursor() to point at the constructor. 3266 if (clang_isExpression(BestCursor->kind) && 3267 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) && 3268 cursor.kind == CXCursor_TypeRef) 3269 return CXChildVisit_Recurse; 3270 3271 // Don't override a preprocessing cursor with another preprocessing 3272 // cursor; we want the outermost preprocessing cursor. 3273 if (clang_isPreprocessing(cursor.kind) && 3274 clang_isPreprocessing(BestCursor->kind)) 3275 return CXChildVisit_Recurse; 3276 3277 *BestCursor = cursor; 3278 return CXChildVisit_Recurse; 3279} 3280 3281CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) { 3282 if (!TU) 3283 return clang_getNullCursor(); 3284 3285 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 3286 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 3287 3288 // Translate the given source location to make it point at the beginning of 3289 // the token under the cursor. 3290 SourceLocation SLoc = cxloc::translateSourceLocation(Loc); 3291 3292 // Guard against an invalid SourceLocation, or we may assert in one 3293 // of the following calls. 3294 if (SLoc.isInvalid()) 3295 return clang_getNullCursor(); 3296 3297 bool Logging = getenv("LIBCLANG_LOGGING"); 3298 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(), 3299 CXXUnit->getASTContext().getLangOptions()); 3300 3301 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound); 3302 if (SLoc.isValid()) { 3303 // FIXME: Would be great to have a "hint" cursor, then walk from that 3304 // hint cursor upward until we find a cursor whose source range encloses 3305 // the region of interest, rather than starting from the translation unit. 3306 CXCursor Parent = clang_getTranslationUnitCursor(TU); 3307 CursorVisitor CursorVis(TU, GetCursorVisitor, &Result, 3308 Decl::MaxPCHLevel, SourceLocation(SLoc)); 3309 CursorVis.VisitChildren(Parent); 3310 } 3311 3312 if (Logging) { 3313 CXFile SearchFile; 3314 unsigned SearchLine, SearchColumn; 3315 CXFile ResultFile; 3316 unsigned ResultLine, ResultColumn; 3317 CXString SearchFileName, ResultFileName, KindSpelling, USR; 3318 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : ""; 3319 CXSourceLocation ResultLoc = clang_getCursorLocation(Result); 3320 3321 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 3322 0); 3323 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine, 3324 &ResultColumn, 0); 3325 SearchFileName = clang_getFileName(SearchFile); 3326 ResultFileName = clang_getFileName(ResultFile); 3327 KindSpelling = clang_getCursorKindSpelling(Result.kind); 3328 USR = clang_getCursorUSR(Result); 3329 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n", 3330 clang_getCString(SearchFileName), SearchLine, SearchColumn, 3331 clang_getCString(KindSpelling), 3332 clang_getCString(ResultFileName), ResultLine, ResultColumn, 3333 clang_getCString(USR), IsDef); 3334 clang_disposeString(SearchFileName); 3335 clang_disposeString(ResultFileName); 3336 clang_disposeString(KindSpelling); 3337 clang_disposeString(USR); 3338 3339 CXCursor Definition = clang_getCursorDefinition(Result); 3340 if (!clang_equalCursors(Definition, clang_getNullCursor())) { 3341 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition); 3342 CXString DefinitionKindSpelling 3343 = clang_getCursorKindSpelling(Definition.kind); 3344 CXFile DefinitionFile; 3345 unsigned DefinitionLine, DefinitionColumn; 3346 clang_getInstantiationLocation(DefinitionLoc, &DefinitionFile, 3347 &DefinitionLine, &DefinitionColumn, 0); 3348 CXString DefinitionFileName = clang_getFileName(DefinitionFile); 3349 fprintf(stderr, " -> %s(%s:%d:%d)\n", 3350 clang_getCString(DefinitionKindSpelling), 3351 clang_getCString(DefinitionFileName), 3352 DefinitionLine, DefinitionColumn); 3353 clang_disposeString(DefinitionFileName); 3354 clang_disposeString(DefinitionKindSpelling); 3355 } 3356 } 3357 3358 return Result; 3359} 3360 3361CXCursor clang_getNullCursor(void) { 3362 return MakeCXCursorInvalid(CXCursor_InvalidFile); 3363} 3364 3365unsigned clang_equalCursors(CXCursor X, CXCursor Y) { 3366 return X == Y; 3367} 3368 3369unsigned clang_hashCursor(CXCursor C) { 3370 unsigned Index = 0; 3371 if (clang_isExpression(C.kind) || clang_isStatement(C.kind)) 3372 Index = 1; 3373 3374 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue( 3375 std::make_pair(C.kind, C.data[Index])); 3376} 3377 3378unsigned clang_isInvalid(enum CXCursorKind K) { 3379 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid; 3380} 3381 3382unsigned clang_isDeclaration(enum CXCursorKind K) { 3383 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl; 3384} 3385 3386unsigned clang_isReference(enum CXCursorKind K) { 3387 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef; 3388} 3389 3390unsigned clang_isExpression(enum CXCursorKind K) { 3391 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr; 3392} 3393 3394unsigned clang_isStatement(enum CXCursorKind K) { 3395 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt; 3396} 3397 3398unsigned clang_isTranslationUnit(enum CXCursorKind K) { 3399 return K == CXCursor_TranslationUnit; 3400} 3401 3402unsigned clang_isPreprocessing(enum CXCursorKind K) { 3403 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing; 3404} 3405 3406unsigned clang_isUnexposed(enum CXCursorKind K) { 3407 switch (K) { 3408 case CXCursor_UnexposedDecl: 3409 case CXCursor_UnexposedExpr: 3410 case CXCursor_UnexposedStmt: 3411 case CXCursor_UnexposedAttr: 3412 return true; 3413 default: 3414 return false; 3415 } 3416} 3417 3418CXCursorKind clang_getCursorKind(CXCursor C) { 3419 return C.kind; 3420} 3421 3422CXSourceLocation clang_getCursorLocation(CXCursor C) { 3423 if (clang_isReference(C.kind)) { 3424 switch (C.kind) { 3425 case CXCursor_ObjCSuperClassRef: { 3426 std::pair<ObjCInterfaceDecl *, SourceLocation> P 3427 = getCursorObjCSuperClassRef(C); 3428 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3429 } 3430 3431 case CXCursor_ObjCProtocolRef: { 3432 std::pair<ObjCProtocolDecl *, SourceLocation> P 3433 = getCursorObjCProtocolRef(C); 3434 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3435 } 3436 3437 case CXCursor_ObjCClassRef: { 3438 std::pair<ObjCInterfaceDecl *, SourceLocation> P 3439 = getCursorObjCClassRef(C); 3440 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3441 } 3442 3443 case CXCursor_TypeRef: { 3444 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C); 3445 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3446 } 3447 3448 case CXCursor_TemplateRef: { 3449 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C); 3450 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3451 } 3452 3453 case CXCursor_NamespaceRef: { 3454 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C); 3455 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3456 } 3457 3458 case CXCursor_MemberRef: { 3459 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C); 3460 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3461 } 3462 3463 case CXCursor_CXXBaseSpecifier: { 3464 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C); 3465 if (!BaseSpec) 3466 return clang_getNullLocation(); 3467 3468 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo()) 3469 return cxloc::translateSourceLocation(getCursorContext(C), 3470 TSInfo->getTypeLoc().getBeginLoc()); 3471 3472 return cxloc::translateSourceLocation(getCursorContext(C), 3473 BaseSpec->getSourceRange().getBegin()); 3474 } 3475 3476 case CXCursor_LabelRef: { 3477 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C); 3478 return cxloc::translateSourceLocation(getCursorContext(C), P.second); 3479 } 3480 3481 case CXCursor_OverloadedDeclRef: 3482 return cxloc::translateSourceLocation(getCursorContext(C), 3483 getCursorOverloadedDeclRef(C).second); 3484 3485 default: 3486 // FIXME: Need a way to enumerate all non-reference cases. 3487 llvm_unreachable("Missed a reference kind"); 3488 } 3489 } 3490 3491 if (clang_isExpression(C.kind)) 3492 return cxloc::translateSourceLocation(getCursorContext(C), 3493 getLocationFromExpr(getCursorExpr(C))); 3494 3495 if (clang_isStatement(C.kind)) 3496 return cxloc::translateSourceLocation(getCursorContext(C), 3497 getCursorStmt(C)->getLocStart()); 3498 3499 if (C.kind == CXCursor_PreprocessingDirective) { 3500 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin(); 3501 return cxloc::translateSourceLocation(getCursorContext(C), L); 3502 } 3503 3504 if (C.kind == CXCursor_MacroInstantiation) { 3505 SourceLocation L 3506 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin(); 3507 return cxloc::translateSourceLocation(getCursorContext(C), L); 3508 } 3509 3510 if (C.kind == CXCursor_MacroDefinition) { 3511 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation(); 3512 return cxloc::translateSourceLocation(getCursorContext(C), L); 3513 } 3514 3515 if (C.kind == CXCursor_InclusionDirective) { 3516 SourceLocation L 3517 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin(); 3518 return cxloc::translateSourceLocation(getCursorContext(C), L); 3519 } 3520 3521 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl) 3522 return clang_getNullLocation(); 3523 3524 Decl *D = getCursorDecl(C); 3525 SourceLocation Loc = D->getLocation(); 3526 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D)) 3527 Loc = Class->getClassLoc(); 3528 // FIXME: Multiple variables declared in a single declaration 3529 // currently lack the information needed to correctly determine their 3530 // ranges when accounting for the type-specifier. We use context 3531 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, 3532 // and if so, whether it is the first decl. 3533 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 3534 if (!cxcursor::isFirstInDeclGroup(C)) 3535 Loc = VD->getLocation(); 3536 } 3537 3538 return cxloc::translateSourceLocation(getCursorContext(C), Loc); 3539} 3540 3541} // end extern "C" 3542 3543static SourceRange getRawCursorExtent(CXCursor C) { 3544 if (clang_isReference(C.kind)) { 3545 switch (C.kind) { 3546 case CXCursor_ObjCSuperClassRef: 3547 return getCursorObjCSuperClassRef(C).second; 3548 3549 case CXCursor_ObjCProtocolRef: 3550 return getCursorObjCProtocolRef(C).second; 3551 3552 case CXCursor_ObjCClassRef: 3553 return getCursorObjCClassRef(C).second; 3554 3555 case CXCursor_TypeRef: 3556 return getCursorTypeRef(C).second; 3557 3558 case CXCursor_TemplateRef: 3559 return getCursorTemplateRef(C).second; 3560 3561 case CXCursor_NamespaceRef: 3562 return getCursorNamespaceRef(C).second; 3563 3564 case CXCursor_MemberRef: 3565 return getCursorMemberRef(C).second; 3566 3567 case CXCursor_CXXBaseSpecifier: 3568 return getCursorCXXBaseSpecifier(C)->getSourceRange(); 3569 3570 case CXCursor_LabelRef: 3571 return getCursorLabelRef(C).second; 3572 3573 case CXCursor_OverloadedDeclRef: 3574 return getCursorOverloadedDeclRef(C).second; 3575 3576 default: 3577 // FIXME: Need a way to enumerate all non-reference cases. 3578 llvm_unreachable("Missed a reference kind"); 3579 } 3580 } 3581 3582 if (clang_isExpression(C.kind)) 3583 return getCursorExpr(C)->getSourceRange(); 3584 3585 if (clang_isStatement(C.kind)) 3586 return getCursorStmt(C)->getSourceRange(); 3587 3588 if (C.kind == CXCursor_PreprocessingDirective) 3589 return cxcursor::getCursorPreprocessingDirective(C); 3590 3591 if (C.kind == CXCursor_MacroInstantiation) 3592 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange(); 3593 3594 if (C.kind == CXCursor_MacroDefinition) 3595 return cxcursor::getCursorMacroDefinition(C)->getSourceRange(); 3596 3597 if (C.kind == CXCursor_InclusionDirective) 3598 return cxcursor::getCursorInclusionDirective(C)->getSourceRange(); 3599 3600 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) { 3601 Decl *D = cxcursor::getCursorDecl(C); 3602 SourceRange R = D->getSourceRange(); 3603 // FIXME: Multiple variables declared in a single declaration 3604 // currently lack the information needed to correctly determine their 3605 // ranges when accounting for the type-specifier. We use context 3606 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, 3607 // and if so, whether it is the first decl. 3608 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 3609 if (!cxcursor::isFirstInDeclGroup(C)) 3610 R.setBegin(VD->getLocation()); 3611 } 3612 return R; 3613 } 3614 return SourceRange(); 3615} 3616 3617/// \brief Retrieves the "raw" cursor extent, which is then extended to include 3618/// the decl-specifier-seq for declarations. 3619static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) { 3620 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) { 3621 Decl *D = cxcursor::getCursorDecl(C); 3622 SourceRange R = D->getSourceRange(); 3623 3624 // Adjust the start of the location for declarations preceded by 3625 // declaration specifiers. 3626 SourceLocation StartLoc; 3627 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 3628 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) 3629 StartLoc = TI->getTypeLoc().getSourceRange().getBegin(); 3630 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) { 3631 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo()) 3632 StartLoc = TI->getTypeLoc().getSourceRange().getBegin(); 3633 } 3634 3635 if (StartLoc.isValid() && R.getBegin().isValid() && 3636 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin())) 3637 R.setBegin(StartLoc); 3638 3639 // FIXME: Multiple variables declared in a single declaration 3640 // currently lack the information needed to correctly determine their 3641 // ranges when accounting for the type-specifier. We use context 3642 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, 3643 // and if so, whether it is the first decl. 3644 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 3645 if (!cxcursor::isFirstInDeclGroup(C)) 3646 R.setBegin(VD->getLocation()); 3647 } 3648 3649 return R; 3650 } 3651 3652 return getRawCursorExtent(C); 3653} 3654 3655extern "C" { 3656 3657CXSourceRange clang_getCursorExtent(CXCursor C) { 3658 SourceRange R = getRawCursorExtent(C); 3659 if (R.isInvalid()) 3660 return clang_getNullRange(); 3661 3662 return cxloc::translateSourceRange(getCursorContext(C), R); 3663} 3664 3665CXCursor clang_getCursorReferenced(CXCursor C) { 3666 if (clang_isInvalid(C.kind)) 3667 return clang_getNullCursor(); 3668 3669 CXTranslationUnit tu = getCursorTU(C); 3670 if (clang_isDeclaration(C.kind)) { 3671 Decl *D = getCursorDecl(C); 3672 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) 3673 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu); 3674 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D)) 3675 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu); 3676 if (ObjCForwardProtocolDecl *Protocols 3677 = dyn_cast<ObjCForwardProtocolDecl>(D)) 3678 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu); 3679 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D)) 3680 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl()) 3681 return MakeCXCursor(Property, tu); 3682 3683 return C; 3684 } 3685 3686 if (clang_isExpression(C.kind)) { 3687 Expr *E = getCursorExpr(C); 3688 Decl *D = getDeclFromExpr(E); 3689 if (D) 3690 return MakeCXCursor(D, tu); 3691 3692 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E)) 3693 return MakeCursorOverloadedDeclRef(Ovl, tu); 3694 3695 return clang_getNullCursor(); 3696 } 3697 3698 if (clang_isStatement(C.kind)) { 3699 Stmt *S = getCursorStmt(C); 3700 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S)) 3701 return MakeCXCursor(Goto->getLabel()->getStmt(), getCursorDecl(C), tu); 3702 3703 return clang_getNullCursor(); 3704 } 3705 3706 if (C.kind == CXCursor_MacroInstantiation) { 3707 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition()) 3708 return MakeMacroDefinitionCursor(Def, tu); 3709 } 3710 3711 if (!clang_isReference(C.kind)) 3712 return clang_getNullCursor(); 3713 3714 switch (C.kind) { 3715 case CXCursor_ObjCSuperClassRef: 3716 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu); 3717 3718 case CXCursor_ObjCProtocolRef: { 3719 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu); 3720 3721 case CXCursor_ObjCClassRef: 3722 return MakeCXCursor(getCursorObjCClassRef(C).first, tu ); 3723 3724 case CXCursor_TypeRef: 3725 return MakeCXCursor(getCursorTypeRef(C).first, tu ); 3726 3727 case CXCursor_TemplateRef: 3728 return MakeCXCursor(getCursorTemplateRef(C).first, tu ); 3729 3730 case CXCursor_NamespaceRef: 3731 return MakeCXCursor(getCursorNamespaceRef(C).first, tu ); 3732 3733 case CXCursor_MemberRef: 3734 return MakeCXCursor(getCursorMemberRef(C).first, tu ); 3735 3736 case CXCursor_CXXBaseSpecifier: { 3737 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C); 3738 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(), 3739 tu )); 3740 } 3741 3742 case CXCursor_LabelRef: 3743 // FIXME: We end up faking the "parent" declaration here because we 3744 // don't want to make CXCursor larger. 3745 return MakeCXCursor(getCursorLabelRef(C).first, 3746 static_cast<ASTUnit*>(tu->TUData)->getASTContext() 3747 .getTranslationUnitDecl(), 3748 tu); 3749 3750 case CXCursor_OverloadedDeclRef: 3751 return C; 3752 3753 default: 3754 // We would prefer to enumerate all non-reference cursor kinds here. 3755 llvm_unreachable("Unhandled reference cursor kind"); 3756 break; 3757 } 3758 } 3759 3760 return clang_getNullCursor(); 3761} 3762 3763CXCursor clang_getCursorDefinition(CXCursor C) { 3764 if (clang_isInvalid(C.kind)) 3765 return clang_getNullCursor(); 3766 3767 CXTranslationUnit TU = getCursorTU(C); 3768 3769 bool WasReference = false; 3770 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) { 3771 C = clang_getCursorReferenced(C); 3772 WasReference = true; 3773 } 3774 3775 if (C.kind == CXCursor_MacroInstantiation) 3776 return clang_getCursorReferenced(C); 3777 3778 if (!clang_isDeclaration(C.kind)) 3779 return clang_getNullCursor(); 3780 3781 Decl *D = getCursorDecl(C); 3782 if (!D) 3783 return clang_getNullCursor(); 3784 3785 switch (D->getKind()) { 3786 // Declaration kinds that don't really separate the notions of 3787 // declaration and definition. 3788 case Decl::Namespace: 3789 case Decl::Typedef: 3790 case Decl::TemplateTypeParm: 3791 case Decl::EnumConstant: 3792 case Decl::Field: 3793 case Decl::IndirectField: 3794 case Decl::ObjCIvar: 3795 case Decl::ObjCAtDefsField: 3796 case Decl::ImplicitParam: 3797 case Decl::ParmVar: 3798 case Decl::NonTypeTemplateParm: 3799 case Decl::TemplateTemplateParm: 3800 case Decl::ObjCCategoryImpl: 3801 case Decl::ObjCImplementation: 3802 case Decl::AccessSpec: 3803 case Decl::LinkageSpec: 3804 case Decl::ObjCPropertyImpl: 3805 case Decl::FileScopeAsm: 3806 case Decl::StaticAssert: 3807 case Decl::Block: 3808 case Decl::Label: // FIXME: Is this right?? 3809 return C; 3810 3811 // Declaration kinds that don't make any sense here, but are 3812 // nonetheless harmless. 3813 case Decl::TranslationUnit: 3814 break; 3815 3816 // Declaration kinds for which the definition is not resolvable. 3817 case Decl::UnresolvedUsingTypename: 3818 case Decl::UnresolvedUsingValue: 3819 break; 3820 3821 case Decl::UsingDirective: 3822 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(), 3823 TU); 3824 3825 case Decl::NamespaceAlias: 3826 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU); 3827 3828 case Decl::Enum: 3829 case Decl::Record: 3830 case Decl::CXXRecord: 3831 case Decl::ClassTemplateSpecialization: 3832 case Decl::ClassTemplatePartialSpecialization: 3833 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition()) 3834 return MakeCXCursor(Def, TU); 3835 return clang_getNullCursor(); 3836 3837 case Decl::Function: 3838 case Decl::CXXMethod: 3839 case Decl::CXXConstructor: 3840 case Decl::CXXDestructor: 3841 case Decl::CXXConversion: { 3842 const FunctionDecl *Def = 0; 3843 if (cast<FunctionDecl>(D)->getBody(Def)) 3844 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU); 3845 return clang_getNullCursor(); 3846 } 3847 3848 case Decl::Var: { 3849 // Ask the variable if it has a definition. 3850 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition()) 3851 return MakeCXCursor(Def, TU); 3852 return clang_getNullCursor(); 3853 } 3854 3855 case Decl::FunctionTemplate: { 3856 const FunctionDecl *Def = 0; 3857 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def)) 3858 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU); 3859 return clang_getNullCursor(); 3860 } 3861 3862 case Decl::ClassTemplate: { 3863 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl() 3864 ->getDefinition()) 3865 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(), 3866 TU); 3867 return clang_getNullCursor(); 3868 } 3869 3870 case Decl::Using: 3871 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D), 3872 D->getLocation(), TU); 3873 3874 case Decl::UsingShadow: 3875 return clang_getCursorDefinition( 3876 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(), 3877 TU)); 3878 3879 case Decl::ObjCMethod: { 3880 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D); 3881 if (Method->isThisDeclarationADefinition()) 3882 return C; 3883 3884 // Dig out the method definition in the associated 3885 // @implementation, if we have it. 3886 // FIXME: The ASTs should make finding the definition easier. 3887 if (ObjCInterfaceDecl *Class 3888 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) 3889 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation()) 3890 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(), 3891 Method->isInstanceMethod())) 3892 if (Def->isThisDeclarationADefinition()) 3893 return MakeCXCursor(Def, TU); 3894 3895 return clang_getNullCursor(); 3896 } 3897 3898 case Decl::ObjCCategory: 3899 if (ObjCCategoryImplDecl *Impl 3900 = cast<ObjCCategoryDecl>(D)->getImplementation()) 3901 return MakeCXCursor(Impl, TU); 3902 return clang_getNullCursor(); 3903 3904 case Decl::ObjCProtocol: 3905 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl()) 3906 return C; 3907 return clang_getNullCursor(); 3908 3909 case Decl::ObjCInterface: 3910 // There are two notions of a "definition" for an Objective-C 3911 // class: the interface and its implementation. When we resolved a 3912 // reference to an Objective-C class, produce the @interface as 3913 // the definition; when we were provided with the interface, 3914 // produce the @implementation as the definition. 3915 if (WasReference) { 3916 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl()) 3917 return C; 3918 } else if (ObjCImplementationDecl *Impl 3919 = cast<ObjCInterfaceDecl>(D)->getImplementation()) 3920 return MakeCXCursor(Impl, TU); 3921 return clang_getNullCursor(); 3922 3923 case Decl::ObjCProperty: 3924 // FIXME: We don't really know where to find the 3925 // ObjCPropertyImplDecls that implement this property. 3926 return clang_getNullCursor(); 3927 3928 case Decl::ObjCCompatibleAlias: 3929 if (ObjCInterfaceDecl *Class 3930 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface()) 3931 if (!Class->isForwardDecl()) 3932 return MakeCXCursor(Class, TU); 3933 3934 return clang_getNullCursor(); 3935 3936 case Decl::ObjCForwardProtocol: 3937 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D), 3938 D->getLocation(), TU); 3939 3940 case Decl::ObjCClass: 3941 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(), 3942 TU); 3943 3944 case Decl::Friend: 3945 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl()) 3946 return clang_getCursorDefinition(MakeCXCursor(Friend, TU)); 3947 return clang_getNullCursor(); 3948 3949 case Decl::FriendTemplate: 3950 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl()) 3951 return clang_getCursorDefinition(MakeCXCursor(Friend, TU)); 3952 return clang_getNullCursor(); 3953 } 3954 3955 return clang_getNullCursor(); 3956} 3957 3958unsigned clang_isCursorDefinition(CXCursor C) { 3959 if (!clang_isDeclaration(C.kind)) 3960 return 0; 3961 3962 return clang_getCursorDefinition(C) == C; 3963} 3964 3965CXCursor clang_getCanonicalCursor(CXCursor C) { 3966 if (!clang_isDeclaration(C.kind)) 3967 return C; 3968 3969 if (Decl *D = getCursorDecl(C)) 3970 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C)); 3971 3972 return C; 3973} 3974 3975unsigned clang_getNumOverloadedDecls(CXCursor C) { 3976 if (C.kind != CXCursor_OverloadedDeclRef) 3977 return 0; 3978 3979 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first; 3980 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>()) 3981 return E->getNumDecls(); 3982 3983 if (OverloadedTemplateStorage *S 3984 = Storage.dyn_cast<OverloadedTemplateStorage*>()) 3985 return S->size(); 3986 3987 Decl *D = Storage.get<Decl*>(); 3988 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) 3989 return Using->shadow_size(); 3990 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D)) 3991 return Classes->size(); 3992 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D)) 3993 return Protocols->protocol_size(); 3994 3995 return 0; 3996} 3997 3998CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) { 3999 if (cursor.kind != CXCursor_OverloadedDeclRef) 4000 return clang_getNullCursor(); 4001 4002 if (index >= clang_getNumOverloadedDecls(cursor)) 4003 return clang_getNullCursor(); 4004 4005 CXTranslationUnit TU = getCursorTU(cursor); 4006 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first; 4007 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>()) 4008 return MakeCXCursor(E->decls_begin()[index], TU); 4009 4010 if (OverloadedTemplateStorage *S 4011 = Storage.dyn_cast<OverloadedTemplateStorage*>()) 4012 return MakeCXCursor(S->begin()[index], TU); 4013 4014 Decl *D = Storage.get<Decl*>(); 4015 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) { 4016 // FIXME: This is, unfortunately, linear time. 4017 UsingDecl::shadow_iterator Pos = Using->shadow_begin(); 4018 std::advance(Pos, index); 4019 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU); 4020 } 4021 4022 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D)) 4023 return MakeCXCursor(Classes->begin()[index].getInterface(), TU); 4024 4025 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D)) 4026 return MakeCXCursor(Protocols->protocol_begin()[index], TU); 4027 4028 return clang_getNullCursor(); 4029} 4030 4031void clang_getDefinitionSpellingAndExtent(CXCursor C, 4032 const char **startBuf, 4033 const char **endBuf, 4034 unsigned *startLine, 4035 unsigned *startColumn, 4036 unsigned *endLine, 4037 unsigned *endColumn) { 4038 assert(getCursorDecl(C) && "CXCursor has null decl"); 4039 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C)); 4040 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND); 4041 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody()); 4042 4043 SourceManager &SM = FD->getASTContext().getSourceManager(); 4044 *startBuf = SM.getCharacterData(Body->getLBracLoc()); 4045 *endBuf = SM.getCharacterData(Body->getRBracLoc()); 4046 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc()); 4047 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc()); 4048 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc()); 4049 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc()); 4050} 4051 4052void clang_enableStackTraces(void) { 4053 llvm::sys::PrintStackTraceOnErrorSignal(); 4054} 4055 4056void clang_executeOnThread(void (*fn)(void*), void *user_data, 4057 unsigned stack_size) { 4058 llvm::llvm_execute_on_thread(fn, user_data, stack_size); 4059} 4060 4061} // end: extern "C" 4062 4063//===----------------------------------------------------------------------===// 4064// Token-based Operations. 4065//===----------------------------------------------------------------------===// 4066 4067/* CXToken layout: 4068 * int_data[0]: a CXTokenKind 4069 * int_data[1]: starting token location 4070 * int_data[2]: token length 4071 * int_data[3]: reserved 4072 * ptr_data: for identifiers and keywords, an IdentifierInfo*. 4073 * otherwise unused. 4074 */ 4075extern "C" { 4076 4077CXTokenKind clang_getTokenKind(CXToken CXTok) { 4078 return static_cast<CXTokenKind>(CXTok.int_data[0]); 4079} 4080 4081CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) { 4082 switch (clang_getTokenKind(CXTok)) { 4083 case CXToken_Identifier: 4084 case CXToken_Keyword: 4085 // We know we have an IdentifierInfo*, so use that. 4086 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data) 4087 ->getNameStart()); 4088 4089 case CXToken_Literal: { 4090 // We have stashed the starting pointer in the ptr_data field. Use it. 4091 const char *Text = static_cast<const char *>(CXTok.ptr_data); 4092 return createCXString(llvm::StringRef(Text, CXTok.int_data[2])); 4093 } 4094 4095 case CXToken_Punctuation: 4096 case CXToken_Comment: 4097 break; 4098 } 4099 4100 // We have to find the starting buffer pointer the hard way, by 4101 // deconstructing the source location. 4102 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 4103 if (!CXXUnit) 4104 return createCXString(""); 4105 4106 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]); 4107 std::pair<FileID, unsigned> LocInfo 4108 = CXXUnit->getSourceManager().getDecomposedLoc(Loc); 4109 bool Invalid = false; 4110 llvm::StringRef Buffer 4111 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid); 4112 if (Invalid) 4113 return createCXString(""); 4114 4115 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2])); 4116} 4117 4118CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) { 4119 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 4120 if (!CXXUnit) 4121 return clang_getNullLocation(); 4122 4123 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), 4124 SourceLocation::getFromRawEncoding(CXTok.int_data[1])); 4125} 4126 4127CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) { 4128 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 4129 if (!CXXUnit) 4130 return clang_getNullRange(); 4131 4132 return cxloc::translateSourceRange(CXXUnit->getASTContext(), 4133 SourceLocation::getFromRawEncoding(CXTok.int_data[1])); 4134} 4135 4136void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range, 4137 CXToken **Tokens, unsigned *NumTokens) { 4138 if (Tokens) 4139 *Tokens = 0; 4140 if (NumTokens) 4141 *NumTokens = 0; 4142 4143 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 4144 if (!CXXUnit || !Tokens || !NumTokens) 4145 return; 4146 4147 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 4148 4149 SourceRange R = cxloc::translateCXSourceRange(Range); 4150 if (R.isInvalid()) 4151 return; 4152 4153 SourceManager &SourceMgr = CXXUnit->getSourceManager(); 4154 std::pair<FileID, unsigned> BeginLocInfo 4155 = SourceMgr.getDecomposedLoc(R.getBegin()); 4156 std::pair<FileID, unsigned> EndLocInfo 4157 = SourceMgr.getDecomposedLoc(R.getEnd()); 4158 4159 // Cannot tokenize across files. 4160 if (BeginLocInfo.first != EndLocInfo.first) 4161 return; 4162 4163 // Create a lexer 4164 bool Invalid = false; 4165 llvm::StringRef Buffer 4166 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid); 4167 if (Invalid) 4168 return; 4169 4170 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first), 4171 CXXUnit->getASTContext().getLangOptions(), 4172 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end()); 4173 Lex.SetCommentRetentionState(true); 4174 4175 // Lex tokens until we hit the end of the range. 4176 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second; 4177 llvm::SmallVector<CXToken, 32> CXTokens; 4178 Token Tok; 4179 bool previousWasAt = false; 4180 do { 4181 // Lex the next token 4182 Lex.LexFromRawLexer(Tok); 4183 if (Tok.is(tok::eof)) 4184 break; 4185 4186 // Initialize the CXToken. 4187 CXToken CXTok; 4188 4189 // - Common fields 4190 CXTok.int_data[1] = Tok.getLocation().getRawEncoding(); 4191 CXTok.int_data[2] = Tok.getLength(); 4192 CXTok.int_data[3] = 0; 4193 4194 // - Kind-specific fields 4195 if (Tok.isLiteral()) { 4196 CXTok.int_data[0] = CXToken_Literal; 4197 CXTok.ptr_data = (void *)Tok.getLiteralData(); 4198 } else if (Tok.is(tok::raw_identifier)) { 4199 // Lookup the identifier to determine whether we have a keyword. 4200 IdentifierInfo *II 4201 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok); 4202 4203 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) { 4204 CXTok.int_data[0] = CXToken_Keyword; 4205 } 4206 else { 4207 CXTok.int_data[0] = Tok.is(tok::identifier) 4208 ? CXToken_Identifier 4209 : CXToken_Keyword; 4210 } 4211 CXTok.ptr_data = II; 4212 } else if (Tok.is(tok::comment)) { 4213 CXTok.int_data[0] = CXToken_Comment; 4214 CXTok.ptr_data = 0; 4215 } else { 4216 CXTok.int_data[0] = CXToken_Punctuation; 4217 CXTok.ptr_data = 0; 4218 } 4219 CXTokens.push_back(CXTok); 4220 previousWasAt = Tok.is(tok::at); 4221 } while (Lex.getBufferLocation() <= EffectiveBufferEnd); 4222 4223 if (CXTokens.empty()) 4224 return; 4225 4226 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size()); 4227 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size()); 4228 *NumTokens = CXTokens.size(); 4229} 4230 4231void clang_disposeTokens(CXTranslationUnit TU, 4232 CXToken *Tokens, unsigned NumTokens) { 4233 free(Tokens); 4234} 4235 4236} // end: extern "C" 4237 4238//===----------------------------------------------------------------------===// 4239// Token annotation APIs. 4240//===----------------------------------------------------------------------===// 4241 4242typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData; 4243static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor, 4244 CXCursor parent, 4245 CXClientData client_data); 4246namespace { 4247class AnnotateTokensWorker { 4248 AnnotateTokensData &Annotated; 4249 CXToken *Tokens; 4250 CXCursor *Cursors; 4251 unsigned NumTokens; 4252 unsigned TokIdx; 4253 unsigned PreprocessingTokIdx; 4254 CursorVisitor AnnotateVis; 4255 SourceManager &SrcMgr; 4256 4257 bool MoreTokens() const { return TokIdx < NumTokens; } 4258 unsigned NextToken() const { return TokIdx; } 4259 void AdvanceToken() { ++TokIdx; } 4260 SourceLocation GetTokenLoc(unsigned tokI) { 4261 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]); 4262 } 4263 4264public: 4265 AnnotateTokensWorker(AnnotateTokensData &annotated, 4266 CXToken *tokens, CXCursor *cursors, unsigned numTokens, 4267 CXTranslationUnit tu, SourceRange RegionOfInterest) 4268 : Annotated(annotated), Tokens(tokens), Cursors(cursors), 4269 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0), 4270 AnnotateVis(tu, 4271 AnnotateTokensVisitor, this, 4272 Decl::MaxPCHLevel, RegionOfInterest), 4273 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()) {} 4274 4275 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); } 4276 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent); 4277 void AnnotateTokens(CXCursor parent); 4278 void AnnotateTokens() { 4279 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU())); 4280 } 4281}; 4282} 4283 4284void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) { 4285 // Walk the AST within the region of interest, annotating tokens 4286 // along the way. 4287 VisitChildren(parent); 4288 4289 for (unsigned I = 0 ; I < TokIdx ; ++I) { 4290 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]); 4291 if (Pos != Annotated.end() && 4292 (clang_isInvalid(Cursors[I].kind) || 4293 Pos->second.kind != CXCursor_PreprocessingDirective)) 4294 Cursors[I] = Pos->second; 4295 } 4296 4297 // Finish up annotating any tokens left. 4298 if (!MoreTokens()) 4299 return; 4300 4301 const CXCursor &C = clang_getNullCursor(); 4302 for (unsigned I = TokIdx ; I < NumTokens ; ++I) { 4303 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]); 4304 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second; 4305 } 4306} 4307 4308enum CXChildVisitResult 4309AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) { 4310 CXSourceLocation Loc = clang_getCursorLocation(cursor); 4311 SourceRange cursorRange = getRawCursorExtent(cursor); 4312 if (cursorRange.isInvalid()) 4313 return CXChildVisit_Recurse; 4314 4315 if (clang_isPreprocessing(cursor.kind)) { 4316 // For macro instantiations, just note where the beginning of the macro 4317 // instantiation occurs. 4318 if (cursor.kind == CXCursor_MacroInstantiation) { 4319 Annotated[Loc.int_data] = cursor; 4320 return CXChildVisit_Recurse; 4321 } 4322 4323 // Items in the preprocessing record are kept separate from items in 4324 // declarations, so we keep a separate token index. 4325 unsigned SavedTokIdx = TokIdx; 4326 TokIdx = PreprocessingTokIdx; 4327 4328 // Skip tokens up until we catch up to the beginning of the preprocessing 4329 // entry. 4330 while (MoreTokens()) { 4331 const unsigned I = NextToken(); 4332 SourceLocation TokLoc = GetTokenLoc(I); 4333 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 4334 case RangeBefore: 4335 AdvanceToken(); 4336 continue; 4337 case RangeAfter: 4338 case RangeOverlap: 4339 break; 4340 } 4341 break; 4342 } 4343 4344 // Look at all of the tokens within this range. 4345 while (MoreTokens()) { 4346 const unsigned I = NextToken(); 4347 SourceLocation TokLoc = GetTokenLoc(I); 4348 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 4349 case RangeBefore: 4350 assert(0 && "Infeasible"); 4351 case RangeAfter: 4352 break; 4353 case RangeOverlap: 4354 Cursors[I] = cursor; 4355 AdvanceToken(); 4356 continue; 4357 } 4358 break; 4359 } 4360 4361 // Save the preprocessing token index; restore the non-preprocessing 4362 // token index. 4363 PreprocessingTokIdx = TokIdx; 4364 TokIdx = SavedTokIdx; 4365 return CXChildVisit_Recurse; 4366 } 4367 4368 if (cursorRange.isInvalid()) 4369 return CXChildVisit_Continue; 4370 4371 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data); 4372 4373 // Adjust the annotated range based specific declarations. 4374 const enum CXCursorKind cursorK = clang_getCursorKind(cursor); 4375 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) { 4376 Decl *D = cxcursor::getCursorDecl(cursor); 4377 // Don't visit synthesized ObjC methods, since they have no syntatic 4378 // representation in the source. 4379 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 4380 if (MD->isSynthesized()) 4381 return CXChildVisit_Continue; 4382 } 4383 4384 SourceLocation StartLoc; 4385 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 4386 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) 4387 StartLoc = TI->getTypeLoc().getSourceRange().getBegin(); 4388 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) { 4389 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo()) 4390 StartLoc = TI->getTypeLoc().getSourceRange().getBegin(); 4391 } 4392 4393 if (StartLoc.isValid() && L.isValid() && 4394 SrcMgr.isBeforeInTranslationUnit(StartLoc, L)) 4395 cursorRange.setBegin(StartLoc); 4396 } 4397 4398 // If the location of the cursor occurs within a macro instantiation, record 4399 // the spelling location of the cursor in our annotation map. We can then 4400 // paper over the token labelings during a post-processing step to try and 4401 // get cursor mappings for tokens that are the *arguments* of a macro 4402 // instantiation. 4403 if (L.isMacroID()) { 4404 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding(); 4405 // Only invalidate the old annotation if it isn't part of a preprocessing 4406 // directive. Here we assume that the default construction of CXCursor 4407 // results in CXCursor.kind being an initialized value (i.e., 0). If 4408 // this isn't the case, we can fix by doing lookup + insertion. 4409 4410 CXCursor &oldC = Annotated[rawEncoding]; 4411 if (!clang_isPreprocessing(oldC.kind)) 4412 oldC = cursor; 4413 } 4414 4415 const enum CXCursorKind K = clang_getCursorKind(parent); 4416 const CXCursor updateC = 4417 (clang_isInvalid(K) || K == CXCursor_TranslationUnit) 4418 ? clang_getNullCursor() : parent; 4419 4420 while (MoreTokens()) { 4421 const unsigned I = NextToken(); 4422 SourceLocation TokLoc = GetTokenLoc(I); 4423 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 4424 case RangeBefore: 4425 Cursors[I] = updateC; 4426 AdvanceToken(); 4427 continue; 4428 case RangeAfter: 4429 case RangeOverlap: 4430 break; 4431 } 4432 break; 4433 } 4434 4435 // Visit children to get their cursor information. 4436 const unsigned BeforeChildren = NextToken(); 4437 VisitChildren(cursor); 4438 const unsigned AfterChildren = NextToken(); 4439 4440 // Adjust 'Last' to the last token within the extent of the cursor. 4441 while (MoreTokens()) { 4442 const unsigned I = NextToken(); 4443 SourceLocation TokLoc = GetTokenLoc(I); 4444 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 4445 case RangeBefore: 4446 assert(0 && "Infeasible"); 4447 case RangeAfter: 4448 break; 4449 case RangeOverlap: 4450 Cursors[I] = updateC; 4451 AdvanceToken(); 4452 continue; 4453 } 4454 break; 4455 } 4456 const unsigned Last = NextToken(); 4457 4458 // Scan the tokens that are at the beginning of the cursor, but are not 4459 // capture by the child cursors. 4460 4461 // For AST elements within macros, rely on a post-annotate pass to 4462 // to correctly annotate the tokens with cursors. Otherwise we can 4463 // get confusing results of having tokens that map to cursors that really 4464 // are expanded by an instantiation. 4465 if (L.isMacroID()) 4466 cursor = clang_getNullCursor(); 4467 4468 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) { 4469 if (!clang_isInvalid(clang_getCursorKind(Cursors[I]))) 4470 break; 4471 4472 Cursors[I] = cursor; 4473 } 4474 // Scan the tokens that are at the end of the cursor, but are not captured 4475 // but the child cursors. 4476 for (unsigned I = AfterChildren; I != Last; ++I) 4477 Cursors[I] = cursor; 4478 4479 TokIdx = Last; 4480 return CXChildVisit_Continue; 4481} 4482 4483static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor, 4484 CXCursor parent, 4485 CXClientData client_data) { 4486 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent); 4487} 4488 4489// This gets run a separate thread to avoid stack blowout. 4490static void runAnnotateTokensWorker(void *UserData) { 4491 ((AnnotateTokensWorker*)UserData)->AnnotateTokens(); 4492} 4493 4494extern "C" { 4495 4496void clang_annotateTokens(CXTranslationUnit TU, 4497 CXToken *Tokens, unsigned NumTokens, 4498 CXCursor *Cursors) { 4499 4500 if (NumTokens == 0 || !Tokens || !Cursors) 4501 return; 4502 4503 // Any token we don't specifically annotate will have a NULL cursor. 4504 CXCursor C = clang_getNullCursor(); 4505 for (unsigned I = 0; I != NumTokens; ++I) 4506 Cursors[I] = C; 4507 4508 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 4509 if (!CXXUnit) 4510 return; 4511 4512 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 4513 4514 // Determine the region of interest, which contains all of the tokens. 4515 SourceRange RegionOfInterest; 4516 RegionOfInterest.setBegin(cxloc::translateSourceLocation( 4517 clang_getTokenLocation(TU, Tokens[0]))); 4518 RegionOfInterest.setEnd(cxloc::translateSourceLocation( 4519 clang_getTokenLocation(TU, 4520 Tokens[NumTokens - 1]))); 4521 4522 // A mapping from the source locations found when re-lexing or traversing the 4523 // region of interest to the corresponding cursors. 4524 AnnotateTokensData Annotated; 4525 4526 // Relex the tokens within the source range to look for preprocessing 4527 // directives. 4528 SourceManager &SourceMgr = CXXUnit->getSourceManager(); 4529 std::pair<FileID, unsigned> BeginLocInfo 4530 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin()); 4531 std::pair<FileID, unsigned> EndLocInfo 4532 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd()); 4533 4534 llvm::StringRef Buffer; 4535 bool Invalid = false; 4536 if (BeginLocInfo.first == EndLocInfo.first && 4537 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) && 4538 !Invalid) { 4539 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first), 4540 CXXUnit->getASTContext().getLangOptions(), 4541 Buffer.begin(), Buffer.data() + BeginLocInfo.second, 4542 Buffer.end()); 4543 Lex.SetCommentRetentionState(true); 4544 4545 // Lex tokens in raw mode until we hit the end of the range, to avoid 4546 // entering #includes or expanding macros. 4547 while (true) { 4548 Token Tok; 4549 Lex.LexFromRawLexer(Tok); 4550 4551 reprocess: 4552 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) { 4553 // We have found a preprocessing directive. Gobble it up so that we 4554 // don't see it while preprocessing these tokens later, but keep track 4555 // of all of the token locations inside this preprocessing directive so 4556 // that we can annotate them appropriately. 4557 // 4558 // FIXME: Some simple tests here could identify macro definitions and 4559 // #undefs, to provide specific cursor kinds for those. 4560 std::vector<SourceLocation> Locations; 4561 do { 4562 Locations.push_back(Tok.getLocation()); 4563 Lex.LexFromRawLexer(Tok); 4564 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof)); 4565 4566 using namespace cxcursor; 4567 CXCursor Cursor 4568 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(), 4569 Locations.back()), 4570 TU); 4571 for (unsigned I = 0, N = Locations.size(); I != N; ++I) { 4572 Annotated[Locations[I].getRawEncoding()] = Cursor; 4573 } 4574 4575 if (Tok.isAtStartOfLine()) 4576 goto reprocess; 4577 4578 continue; 4579 } 4580 4581 if (Tok.is(tok::eof)) 4582 break; 4583 } 4584 } 4585 4586 // Annotate all of the source locations in the region of interest that map to 4587 // a specific cursor. 4588 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens, 4589 TU, RegionOfInterest); 4590 4591 // Run the worker within a CrashRecoveryContext. 4592 // FIXME: We use a ridiculous stack size here because the data-recursion 4593 // algorithm uses a large stack frame than the non-data recursive version, 4594 // and AnnotationTokensWorker currently transforms the data-recursion 4595 // algorithm back into a traditional recursion by explicitly calling 4596 // VisitChildren(). We will need to remove this explicit recursive call. 4597 llvm::CrashRecoveryContext CRC; 4598 if (!RunSafely(CRC, runAnnotateTokensWorker, &W, 4599 GetSafetyThreadStackSize() * 2)) { 4600 fprintf(stderr, "libclang: crash detected while annotating tokens\n"); 4601 } 4602} 4603} // end: extern "C" 4604 4605//===----------------------------------------------------------------------===// 4606// Operations for querying linkage of a cursor. 4607//===----------------------------------------------------------------------===// 4608 4609extern "C" { 4610CXLinkageKind clang_getCursorLinkage(CXCursor cursor) { 4611 if (!clang_isDeclaration(cursor.kind)) 4612 return CXLinkage_Invalid; 4613 4614 Decl *D = cxcursor::getCursorDecl(cursor); 4615 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D)) 4616 switch (ND->getLinkage()) { 4617 case NoLinkage: return CXLinkage_NoLinkage; 4618 case InternalLinkage: return CXLinkage_Internal; 4619 case UniqueExternalLinkage: return CXLinkage_UniqueExternal; 4620 case ExternalLinkage: return CXLinkage_External; 4621 }; 4622 4623 return CXLinkage_Invalid; 4624} 4625} // end: extern "C" 4626 4627//===----------------------------------------------------------------------===// 4628// Operations for querying language of a cursor. 4629//===----------------------------------------------------------------------===// 4630 4631static CXLanguageKind getDeclLanguage(const Decl *D) { 4632 switch (D->getKind()) { 4633 default: 4634 break; 4635 case Decl::ImplicitParam: 4636 case Decl::ObjCAtDefsField: 4637 case Decl::ObjCCategory: 4638 case Decl::ObjCCategoryImpl: 4639 case Decl::ObjCClass: 4640 case Decl::ObjCCompatibleAlias: 4641 case Decl::ObjCForwardProtocol: 4642 case Decl::ObjCImplementation: 4643 case Decl::ObjCInterface: 4644 case Decl::ObjCIvar: 4645 case Decl::ObjCMethod: 4646 case Decl::ObjCProperty: 4647 case Decl::ObjCPropertyImpl: 4648 case Decl::ObjCProtocol: 4649 return CXLanguage_ObjC; 4650 case Decl::CXXConstructor: 4651 case Decl::CXXConversion: 4652 case Decl::CXXDestructor: 4653 case Decl::CXXMethod: 4654 case Decl::CXXRecord: 4655 case Decl::ClassTemplate: 4656 case Decl::ClassTemplatePartialSpecialization: 4657 case Decl::ClassTemplateSpecialization: 4658 case Decl::Friend: 4659 case Decl::FriendTemplate: 4660 case Decl::FunctionTemplate: 4661 case Decl::LinkageSpec: 4662 case Decl::Namespace: 4663 case Decl::NamespaceAlias: 4664 case Decl::NonTypeTemplateParm: 4665 case Decl::StaticAssert: 4666 case Decl::TemplateTemplateParm: 4667 case Decl::TemplateTypeParm: 4668 case Decl::UnresolvedUsingTypename: 4669 case Decl::UnresolvedUsingValue: 4670 case Decl::Using: 4671 case Decl::UsingDirective: 4672 case Decl::UsingShadow: 4673 return CXLanguage_CPlusPlus; 4674 } 4675 4676 return CXLanguage_C; 4677} 4678 4679extern "C" { 4680 4681enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) { 4682 if (clang_isDeclaration(cursor.kind)) 4683 if (Decl *D = cxcursor::getCursorDecl(cursor)) { 4684 if (D->hasAttr<UnavailableAttr>() || 4685 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())) 4686 return CXAvailability_Available; 4687 4688 if (D->hasAttr<DeprecatedAttr>()) 4689 return CXAvailability_Deprecated; 4690 } 4691 4692 return CXAvailability_Available; 4693} 4694 4695CXLanguageKind clang_getCursorLanguage(CXCursor cursor) { 4696 if (clang_isDeclaration(cursor.kind)) 4697 return getDeclLanguage(cxcursor::getCursorDecl(cursor)); 4698 4699 return CXLanguage_Invalid; 4700} 4701 4702 /// \brief If the given cursor is the "templated" declaration 4703 /// descibing a class or function template, return the class or 4704 /// function template. 4705static Decl *maybeGetTemplateCursor(Decl *D) { 4706 if (!D) 4707 return 0; 4708 4709 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 4710 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate()) 4711 return FunTmpl; 4712 4713 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) 4714 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate()) 4715 return ClassTmpl; 4716 4717 return D; 4718} 4719 4720CXCursor clang_getCursorSemanticParent(CXCursor cursor) { 4721 if (clang_isDeclaration(cursor.kind)) { 4722 if (Decl *D = getCursorDecl(cursor)) { 4723 DeclContext *DC = D->getDeclContext(); 4724 if (!DC) 4725 return clang_getNullCursor(); 4726 4727 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)), 4728 getCursorTU(cursor)); 4729 } 4730 } 4731 4732 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) { 4733 if (Decl *D = getCursorDecl(cursor)) 4734 return MakeCXCursor(D, getCursorTU(cursor)); 4735 } 4736 4737 return clang_getNullCursor(); 4738} 4739 4740CXCursor clang_getCursorLexicalParent(CXCursor cursor) { 4741 if (clang_isDeclaration(cursor.kind)) { 4742 if (Decl *D = getCursorDecl(cursor)) { 4743 DeclContext *DC = D->getLexicalDeclContext(); 4744 if (!DC) 4745 return clang_getNullCursor(); 4746 4747 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)), 4748 getCursorTU(cursor)); 4749 } 4750 } 4751 4752 // FIXME: Note that we can't easily compute the lexical context of a 4753 // statement or expression, so we return nothing. 4754 return clang_getNullCursor(); 4755} 4756 4757static void CollectOverriddenMethods(DeclContext *Ctx, 4758 ObjCMethodDecl *Method, 4759 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) { 4760 if (!Ctx) 4761 return; 4762 4763 // If we have a class or category implementation, jump straight to the 4764 // interface. 4765 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx)) 4766 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods); 4767 4768 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx); 4769 if (!Container) 4770 return; 4771 4772 // Check whether we have a matching method at this level. 4773 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(), 4774 Method->isInstanceMethod())) 4775 if (Method != Overridden) { 4776 // We found an override at this level; there is no need to look 4777 // into other protocols or categories. 4778 Methods.push_back(Overridden); 4779 return; 4780 } 4781 4782 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 4783 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(), 4784 PEnd = Protocol->protocol_end(); 4785 P != PEnd; ++P) 4786 CollectOverriddenMethods(*P, Method, Methods); 4787 } 4788 4789 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) { 4790 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(), 4791 PEnd = Category->protocol_end(); 4792 P != PEnd; ++P) 4793 CollectOverriddenMethods(*P, Method, Methods); 4794 } 4795 4796 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) { 4797 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(), 4798 PEnd = Interface->protocol_end(); 4799 P != PEnd; ++P) 4800 CollectOverriddenMethods(*P, Method, Methods); 4801 4802 for (ObjCCategoryDecl *Category = Interface->getCategoryList(); 4803 Category; Category = Category->getNextClassCategory()) 4804 CollectOverriddenMethods(Category, Method, Methods); 4805 4806 // We only look into the superclass if we haven't found anything yet. 4807 if (Methods.empty()) 4808 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) 4809 return CollectOverriddenMethods(Super, Method, Methods); 4810 } 4811} 4812 4813void clang_getOverriddenCursors(CXCursor cursor, 4814 CXCursor **overridden, 4815 unsigned *num_overridden) { 4816 if (overridden) 4817 *overridden = 0; 4818 if (num_overridden) 4819 *num_overridden = 0; 4820 if (!overridden || !num_overridden) 4821 return; 4822 4823 if (!clang_isDeclaration(cursor.kind)) 4824 return; 4825 4826 Decl *D = getCursorDecl(cursor); 4827 if (!D) 4828 return; 4829 4830 // Handle C++ member functions. 4831 CXTranslationUnit TU = getCursorTU(cursor); 4832 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) { 4833 *num_overridden = CXXMethod->size_overridden_methods(); 4834 if (!*num_overridden) 4835 return; 4836 4837 *overridden = new CXCursor [*num_overridden]; 4838 unsigned I = 0; 4839 for (CXXMethodDecl::method_iterator 4840 M = CXXMethod->begin_overridden_methods(), 4841 MEnd = CXXMethod->end_overridden_methods(); 4842 M != MEnd; (void)++M, ++I) 4843 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU); 4844 return; 4845 } 4846 4847 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D); 4848 if (!Method) 4849 return; 4850 4851 // Handle Objective-C methods. 4852 llvm::SmallVector<ObjCMethodDecl *, 4> Methods; 4853 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods); 4854 4855 if (Methods.empty()) 4856 return; 4857 4858 *num_overridden = Methods.size(); 4859 *overridden = new CXCursor [Methods.size()]; 4860 for (unsigned I = 0, N = Methods.size(); I != N; ++I) 4861 (*overridden)[I] = MakeCXCursor(Methods[I], TU); 4862} 4863 4864void clang_disposeOverriddenCursors(CXCursor *overridden) { 4865 delete [] overridden; 4866} 4867 4868CXFile clang_getIncludedFile(CXCursor cursor) { 4869 if (cursor.kind != CXCursor_InclusionDirective) 4870 return 0; 4871 4872 InclusionDirective *ID = getCursorInclusionDirective(cursor); 4873 return (void *)ID->getFile(); 4874} 4875 4876} // end: extern "C" 4877 4878 4879//===----------------------------------------------------------------------===// 4880// C++ AST instrospection. 4881//===----------------------------------------------------------------------===// 4882 4883extern "C" { 4884unsigned clang_CXXMethod_isStatic(CXCursor C) { 4885 if (!clang_isDeclaration(C.kind)) 4886 return 0; 4887 4888 CXXMethodDecl *Method = 0; 4889 Decl *D = cxcursor::getCursorDecl(C); 4890 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D)) 4891 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl()); 4892 else 4893 Method = dyn_cast_or_null<CXXMethodDecl>(D); 4894 return (Method && Method->isStatic()) ? 1 : 0; 4895} 4896 4897} // end: extern "C" 4898 4899//===----------------------------------------------------------------------===// 4900// Attribute introspection. 4901//===----------------------------------------------------------------------===// 4902 4903extern "C" { 4904CXType clang_getIBOutletCollectionType(CXCursor C) { 4905 if (C.kind != CXCursor_IBOutletCollectionAttr) 4906 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C)); 4907 4908 IBOutletCollectionAttr *A = 4909 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C)); 4910 4911 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C)); 4912} 4913} // end: extern "C" 4914 4915//===----------------------------------------------------------------------===// 4916// Misc. utility functions. 4917//===----------------------------------------------------------------------===// 4918 4919/// Default to using an 8 MB stack size on "safety" threads. 4920static unsigned SafetyStackThreadSize = 8 << 20; 4921 4922namespace clang { 4923 4924bool RunSafely(llvm::CrashRecoveryContext &CRC, 4925 void (*Fn)(void*), void *UserData, 4926 unsigned Size) { 4927 if (!Size) 4928 Size = GetSafetyThreadStackSize(); 4929 if (Size) 4930 return CRC.RunSafelyOnThread(Fn, UserData, Size); 4931 return CRC.RunSafely(Fn, UserData); 4932} 4933 4934unsigned GetSafetyThreadStackSize() { 4935 return SafetyStackThreadSize; 4936} 4937 4938void SetSafetyThreadStackSize(unsigned Value) { 4939 SafetyStackThreadSize = Value; 4940} 4941 4942} 4943 4944extern "C" { 4945 4946CXString clang_getClangVersion() { 4947 return createCXString(getClangFullVersion()); 4948} 4949 4950} // end: extern "C" 4951