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