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