CIndex.cpp revision 8387e2a41eef6fa17fb140a18c29b6eee9dd2b8a
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.getInstantiationRange(EndLoc).second; 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() && !ND->isLateTemplateParsed()) { 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 bool Invalid = false; 2777 const SrcMgr::SLocEntry &sloc = SM.getSLocEntry(fileID, &Invalid); 2778 if (!sloc.isFile() || Invalid) { 2779 createNullLocation(file, line, column, offset); 2780 return; 2781 } 2782 2783 if (file) 2784 *file = (void *)SM.getFileEntryForSLocEntry(sloc); 2785 if (line) 2786 *line = SM.getInstantiationLineNumber(InstLoc); 2787 if (column) 2788 *column = SM.getInstantiationColumnNumber(InstLoc); 2789 if (offset) 2790 *offset = SM.getDecomposedLoc(InstLoc).second; 2791} 2792 2793void clang_getSpellingLocation(CXSourceLocation location, 2794 CXFile *file, 2795 unsigned *line, 2796 unsigned *column, 2797 unsigned *offset) { 2798 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data); 2799 2800 if (!location.ptr_data[0] || Loc.isInvalid()) { 2801 if (file) 2802 *file = 0; 2803 if (line) 2804 *line = 0; 2805 if (column) 2806 *column = 0; 2807 if (offset) 2808 *offset = 0; 2809 return; 2810 } 2811 2812 const SourceManager &SM = 2813 *static_cast<const SourceManager*>(location.ptr_data[0]); 2814 SourceLocation SpellLoc = Loc; 2815 if (SpellLoc.isMacroID()) { 2816 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc); 2817 if (SimpleSpellingLoc.isFileID() && 2818 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first)) 2819 SpellLoc = SimpleSpellingLoc; 2820 else 2821 SpellLoc = SM.getInstantiationLoc(SpellLoc); 2822 } 2823 2824 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc); 2825 FileID FID = LocInfo.first; 2826 unsigned FileOffset = LocInfo.second; 2827 2828 if (file) 2829 *file = (void *)SM.getFileEntryForID(FID); 2830 if (line) 2831 *line = SM.getLineNumber(FID, FileOffset); 2832 if (column) 2833 *column = SM.getColumnNumber(FID, FileOffset); 2834 if (offset) 2835 *offset = FileOffset; 2836} 2837 2838CXSourceLocation clang_getRangeStart(CXSourceRange range) { 2839 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] }, 2840 range.begin_int_data }; 2841 return Result; 2842} 2843 2844CXSourceLocation clang_getRangeEnd(CXSourceRange range) { 2845 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] }, 2846 range.end_int_data }; 2847 return Result; 2848} 2849 2850} // end: extern "C" 2851 2852//===----------------------------------------------------------------------===// 2853// CXFile Operations. 2854//===----------------------------------------------------------------------===// 2855 2856extern "C" { 2857CXString clang_getFileName(CXFile SFile) { 2858 if (!SFile) 2859 return createCXString((const char*)NULL); 2860 2861 FileEntry *FEnt = static_cast<FileEntry *>(SFile); 2862 return createCXString(FEnt->getName()); 2863} 2864 2865time_t clang_getFileTime(CXFile SFile) { 2866 if (!SFile) 2867 return 0; 2868 2869 FileEntry *FEnt = static_cast<FileEntry *>(SFile); 2870 return FEnt->getModificationTime(); 2871} 2872 2873CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) { 2874 if (!tu) 2875 return 0; 2876 2877 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData); 2878 2879 FileManager &FMgr = CXXUnit->getFileManager(); 2880 return const_cast<FileEntry *>(FMgr.getFile(file_name)); 2881} 2882 2883} // end: extern "C" 2884 2885//===----------------------------------------------------------------------===// 2886// CXCursor Operations. 2887//===----------------------------------------------------------------------===// 2888 2889static Decl *getDeclFromExpr(Stmt *E) { 2890 if (CastExpr *CE = dyn_cast<CastExpr>(E)) 2891 return getDeclFromExpr(CE->getSubExpr()); 2892 2893 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E)) 2894 return RefExpr->getDecl(); 2895 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E)) 2896 return RefExpr->getDecl(); 2897 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) 2898 return ME->getMemberDecl(); 2899 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E)) 2900 return RE->getDecl(); 2901 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) 2902 return PRE->isExplicitProperty() ? PRE->getExplicitProperty() : 0; 2903 2904 if (CallExpr *CE = dyn_cast<CallExpr>(E)) 2905 return getDeclFromExpr(CE->getCallee()); 2906 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E)) 2907 if (!CE->isElidable()) 2908 return CE->getConstructor(); 2909 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E)) 2910 return OME->getMethodDecl(); 2911 2912 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E)) 2913 return PE->getProtocol(); 2914 if (SubstNonTypeTemplateParmPackExpr *NTTP 2915 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E)) 2916 return NTTP->getParameterPack(); 2917 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E)) 2918 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) || 2919 isa<ParmVarDecl>(SizeOfPack->getPack())) 2920 return SizeOfPack->getPack(); 2921 2922 return 0; 2923} 2924 2925static SourceLocation getLocationFromExpr(Expr *E) { 2926 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) 2927 return /*FIXME:*/Msg->getLeftLoc(); 2928 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 2929 return DRE->getLocation(); 2930 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E)) 2931 return RefExpr->getLocation(); 2932 if (MemberExpr *Member = dyn_cast<MemberExpr>(E)) 2933 return Member->getMemberLoc(); 2934 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) 2935 return Ivar->getLocation(); 2936 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E)) 2937 return SizeOfPack->getPackLoc(); 2938 2939 return E->getLocStart(); 2940} 2941 2942extern "C" { 2943 2944unsigned clang_visitChildren(CXCursor parent, 2945 CXCursorVisitor visitor, 2946 CXClientData client_data) { 2947 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data, 2948 getCursorASTUnit(parent)->getMaxPCHLevel(), 2949 false); 2950 return CursorVis.VisitChildren(parent); 2951} 2952 2953#ifndef __has_feature 2954#define __has_feature(x) 0 2955#endif 2956#if __has_feature(blocks) 2957typedef enum CXChildVisitResult 2958 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent); 2959 2960static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent, 2961 CXClientData client_data) { 2962 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data; 2963 return block(cursor, parent); 2964} 2965#else 2966// If we are compiled with a compiler that doesn't have native blocks support, 2967// define and call the block manually, so the 2968typedef struct _CXChildVisitResult 2969{ 2970 void *isa; 2971 int flags; 2972 int reserved; 2973 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor, 2974 CXCursor); 2975} *CXCursorVisitorBlock; 2976 2977static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent, 2978 CXClientData client_data) { 2979 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data; 2980 return block->invoke(block, cursor, parent); 2981} 2982#endif 2983 2984 2985unsigned clang_visitChildrenWithBlock(CXCursor parent, 2986 CXCursorVisitorBlock block) { 2987 return clang_visitChildren(parent, visitWithBlock, block); 2988} 2989 2990static CXString getDeclSpelling(Decl *D) { 2991 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D); 2992 if (!ND) { 2993 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D)) 2994 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl()) 2995 return createCXString(Property->getIdentifier()->getName()); 2996 2997 return createCXString(""); 2998 } 2999 3000 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND)) 3001 return createCXString(OMD->getSelector().getAsString()); 3002 3003 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND)) 3004 // No, this isn't the same as the code below. getIdentifier() is non-virtual 3005 // and returns different names. NamedDecl returns the class name and 3006 // ObjCCategoryImplDecl returns the category name. 3007 return createCXString(CIMP->getIdentifier()->getNameStart()); 3008 3009 if (isa<UsingDirectiveDecl>(D)) 3010 return createCXString(""); 3011 3012 llvm::SmallString<1024> S; 3013 llvm::raw_svector_ostream os(S); 3014 ND->printName(os); 3015 3016 return createCXString(os.str()); 3017} 3018 3019CXString clang_getCursorSpelling(CXCursor C) { 3020 if (clang_isTranslationUnit(C.kind)) 3021 return clang_getTranslationUnitSpelling( 3022 static_cast<CXTranslationUnit>(C.data[2])); 3023 3024 if (clang_isReference(C.kind)) { 3025 switch (C.kind) { 3026 case CXCursor_ObjCSuperClassRef: { 3027 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first; 3028 return createCXString(Super->getIdentifier()->getNameStart()); 3029 } 3030 case CXCursor_ObjCClassRef: { 3031 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first; 3032 return createCXString(Class->getIdentifier()->getNameStart()); 3033 } 3034 case CXCursor_ObjCProtocolRef: { 3035 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first; 3036 assert(OID && "getCursorSpelling(): Missing protocol decl"); 3037 return createCXString(OID->getIdentifier()->getNameStart()); 3038 } 3039 case CXCursor_CXXBaseSpecifier: { 3040 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C); 3041 return createCXString(B->getType().getAsString()); 3042 } 3043 case CXCursor_TypeRef: { 3044 TypeDecl *Type = getCursorTypeRef(C).first; 3045 assert(Type && "Missing type decl"); 3046 3047 return createCXString(getCursorContext(C).getTypeDeclType(Type). 3048 getAsString()); 3049 } 3050 case CXCursor_TemplateRef: { 3051 TemplateDecl *Template = getCursorTemplateRef(C).first; 3052 assert(Template && "Missing template decl"); 3053 3054 return createCXString(Template->getNameAsString()); 3055 } 3056 3057 case CXCursor_NamespaceRef: { 3058 NamedDecl *NS = getCursorNamespaceRef(C).first; 3059 assert(NS && "Missing namespace decl"); 3060 3061 return createCXString(NS->getNameAsString()); 3062 } 3063 3064 case CXCursor_MemberRef: { 3065 FieldDecl *Field = getCursorMemberRef(C).first; 3066 assert(Field && "Missing member decl"); 3067 3068 return createCXString(Field->getNameAsString()); 3069 } 3070 3071 case CXCursor_LabelRef: { 3072 LabelStmt *Label = getCursorLabelRef(C).first; 3073 assert(Label && "Missing label"); 3074 3075 return createCXString(Label->getName()); 3076 } 3077 3078 case CXCursor_OverloadedDeclRef: { 3079 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first; 3080 if (Decl *D = Storage.dyn_cast<Decl *>()) { 3081 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) 3082 return createCXString(ND->getNameAsString()); 3083 return createCXString(""); 3084 } 3085 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>()) 3086 return createCXString(E->getName().getAsString()); 3087 OverloadedTemplateStorage *Ovl 3088 = Storage.get<OverloadedTemplateStorage*>(); 3089 if (Ovl->size() == 0) 3090 return createCXString(""); 3091 return createCXString((*Ovl->begin())->getNameAsString()); 3092 } 3093 3094 default: 3095 return createCXString("<not implemented>"); 3096 } 3097 } 3098 3099 if (clang_isExpression(C.kind)) { 3100 Decl *D = getDeclFromExpr(getCursorExpr(C)); 3101 if (D) 3102 return getDeclSpelling(D); 3103 return createCXString(""); 3104 } 3105 3106 if (clang_isStatement(C.kind)) { 3107 Stmt *S = getCursorStmt(C); 3108 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) 3109 return createCXString(Label->getName()); 3110 3111 return createCXString(""); 3112 } 3113 3114 if (C.kind == CXCursor_MacroInstantiation) 3115 return createCXString(getCursorMacroInstantiation(C)->getName() 3116 ->getNameStart()); 3117 3118 if (C.kind == CXCursor_MacroDefinition) 3119 return createCXString(getCursorMacroDefinition(C)->getName() 3120 ->getNameStart()); 3121 3122 if (C.kind == CXCursor_InclusionDirective) 3123 return createCXString(getCursorInclusionDirective(C)->getFileName()); 3124 3125 if (clang_isDeclaration(C.kind)) 3126 return getDeclSpelling(getCursorDecl(C)); 3127 3128 return createCXString(""); 3129} 3130 3131CXString clang_getCursorDisplayName(CXCursor C) { 3132 if (!clang_isDeclaration(C.kind)) 3133 return clang_getCursorSpelling(C); 3134 3135 Decl *D = getCursorDecl(C); 3136 if (!D) 3137 return createCXString(""); 3138 3139 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy; 3140 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 3141 D = FunTmpl->getTemplatedDecl(); 3142 3143 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 3144 llvm::SmallString<64> Str; 3145 llvm::raw_svector_ostream OS(Str); 3146 OS << Function->getNameAsString(); 3147 if (Function->getPrimaryTemplate()) 3148 OS << "<>"; 3149 OS << "("; 3150 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) { 3151 if (I) 3152 OS << ", "; 3153 OS << Function->getParamDecl(I)->getType().getAsString(Policy); 3154 } 3155 3156 if (Function->isVariadic()) { 3157 if (Function->getNumParams()) 3158 OS << ", "; 3159 OS << "..."; 3160 } 3161 OS << ")"; 3162 return createCXString(OS.str()); 3163 } 3164 3165 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) { 3166 llvm::SmallString<64> Str; 3167 llvm::raw_svector_ostream OS(Str); 3168 OS << ClassTemplate->getNameAsString(); 3169 OS << "<"; 3170 TemplateParameterList *Params = ClassTemplate->getTemplateParameters(); 3171 for (unsigned I = 0, N = Params->size(); I != N; ++I) { 3172 if (I) 3173 OS << ", "; 3174 3175 NamedDecl *Param = Params->getParam(I); 3176 if (Param->getIdentifier()) { 3177 OS << Param->getIdentifier()->getName(); 3178 continue; 3179 } 3180 3181 // There is no parameter name, which makes this tricky. Try to come up 3182 // with something useful that isn't too long. 3183 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) 3184 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class"); 3185 else if (NonTypeTemplateParmDecl *NTTP 3186 = dyn_cast<NonTypeTemplateParmDecl>(Param)) 3187 OS << NTTP->getType().getAsString(Policy); 3188 else 3189 OS << "template<...> class"; 3190 } 3191 3192 OS << ">"; 3193 return createCXString(OS.str()); 3194 } 3195 3196 if (ClassTemplateSpecializationDecl *ClassSpec 3197 = dyn_cast<ClassTemplateSpecializationDecl>(D)) { 3198 // If the type was explicitly written, use that. 3199 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten()) 3200 return createCXString(TSInfo->getType().getAsString(Policy)); 3201 3202 llvm::SmallString<64> Str; 3203 llvm::raw_svector_ostream OS(Str); 3204 OS << ClassSpec->getNameAsString(); 3205 OS << TemplateSpecializationType::PrintTemplateArgumentList( 3206 ClassSpec->getTemplateArgs().data(), 3207 ClassSpec->getTemplateArgs().size(), 3208 Policy); 3209 return createCXString(OS.str()); 3210 } 3211 3212 return clang_getCursorSpelling(C); 3213} 3214 3215CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) { 3216 switch (Kind) { 3217 case CXCursor_FunctionDecl: 3218 return createCXString("FunctionDecl"); 3219 case CXCursor_TypedefDecl: 3220 return createCXString("TypedefDecl"); 3221 case CXCursor_EnumDecl: 3222 return createCXString("EnumDecl"); 3223 case CXCursor_EnumConstantDecl: 3224 return createCXString("EnumConstantDecl"); 3225 case CXCursor_StructDecl: 3226 return createCXString("StructDecl"); 3227 case CXCursor_UnionDecl: 3228 return createCXString("UnionDecl"); 3229 case CXCursor_ClassDecl: 3230 return createCXString("ClassDecl"); 3231 case CXCursor_FieldDecl: 3232 return createCXString("FieldDecl"); 3233 case CXCursor_VarDecl: 3234 return createCXString("VarDecl"); 3235 case CXCursor_ParmDecl: 3236 return createCXString("ParmDecl"); 3237 case CXCursor_ObjCInterfaceDecl: 3238 return createCXString("ObjCInterfaceDecl"); 3239 case CXCursor_ObjCCategoryDecl: 3240 return createCXString("ObjCCategoryDecl"); 3241 case CXCursor_ObjCProtocolDecl: 3242 return createCXString("ObjCProtocolDecl"); 3243 case CXCursor_ObjCPropertyDecl: 3244 return createCXString("ObjCPropertyDecl"); 3245 case CXCursor_ObjCIvarDecl: 3246 return createCXString("ObjCIvarDecl"); 3247 case CXCursor_ObjCInstanceMethodDecl: 3248 return createCXString("ObjCInstanceMethodDecl"); 3249 case CXCursor_ObjCClassMethodDecl: 3250 return createCXString("ObjCClassMethodDecl"); 3251 case CXCursor_ObjCImplementationDecl: 3252 return createCXString("ObjCImplementationDecl"); 3253 case CXCursor_ObjCCategoryImplDecl: 3254 return createCXString("ObjCCategoryImplDecl"); 3255 case CXCursor_CXXMethod: 3256 return createCXString("CXXMethod"); 3257 case CXCursor_UnexposedDecl: 3258 return createCXString("UnexposedDecl"); 3259 case CXCursor_ObjCSuperClassRef: 3260 return createCXString("ObjCSuperClassRef"); 3261 case CXCursor_ObjCProtocolRef: 3262 return createCXString("ObjCProtocolRef"); 3263 case CXCursor_ObjCClassRef: 3264 return createCXString("ObjCClassRef"); 3265 case CXCursor_TypeRef: 3266 return createCXString("TypeRef"); 3267 case CXCursor_TemplateRef: 3268 return createCXString("TemplateRef"); 3269 case CXCursor_NamespaceRef: 3270 return createCXString("NamespaceRef"); 3271 case CXCursor_MemberRef: 3272 return createCXString("MemberRef"); 3273 case CXCursor_LabelRef: 3274 return createCXString("LabelRef"); 3275 case CXCursor_OverloadedDeclRef: 3276 return createCXString("OverloadedDeclRef"); 3277 case CXCursor_UnexposedExpr: 3278 return createCXString("UnexposedExpr"); 3279 case CXCursor_BlockExpr: 3280 return createCXString("BlockExpr"); 3281 case CXCursor_DeclRefExpr: 3282 return createCXString("DeclRefExpr"); 3283 case CXCursor_MemberRefExpr: 3284 return createCXString("MemberRefExpr"); 3285 case CXCursor_CallExpr: 3286 return createCXString("CallExpr"); 3287 case CXCursor_ObjCMessageExpr: 3288 return createCXString("ObjCMessageExpr"); 3289 case CXCursor_UnexposedStmt: 3290 return createCXString("UnexposedStmt"); 3291 case CXCursor_LabelStmt: 3292 return createCXString("LabelStmt"); 3293 case CXCursor_InvalidFile: 3294 return createCXString("InvalidFile"); 3295 case CXCursor_InvalidCode: 3296 return createCXString("InvalidCode"); 3297 case CXCursor_NoDeclFound: 3298 return createCXString("NoDeclFound"); 3299 case CXCursor_NotImplemented: 3300 return createCXString("NotImplemented"); 3301 case CXCursor_TranslationUnit: 3302 return createCXString("TranslationUnit"); 3303 case CXCursor_UnexposedAttr: 3304 return createCXString("UnexposedAttr"); 3305 case CXCursor_IBActionAttr: 3306 return createCXString("attribute(ibaction)"); 3307 case CXCursor_IBOutletAttr: 3308 return createCXString("attribute(iboutlet)"); 3309 case CXCursor_IBOutletCollectionAttr: 3310 return createCXString("attribute(iboutletcollection)"); 3311 case CXCursor_PreprocessingDirective: 3312 return createCXString("preprocessing directive"); 3313 case CXCursor_MacroDefinition: 3314 return createCXString("macro definition"); 3315 case CXCursor_MacroInstantiation: 3316 return createCXString("macro instantiation"); 3317 case CXCursor_InclusionDirective: 3318 return createCXString("inclusion directive"); 3319 case CXCursor_Namespace: 3320 return createCXString("Namespace"); 3321 case CXCursor_LinkageSpec: 3322 return createCXString("LinkageSpec"); 3323 case CXCursor_CXXBaseSpecifier: 3324 return createCXString("C++ base class specifier"); 3325 case CXCursor_Constructor: 3326 return createCXString("CXXConstructor"); 3327 case CXCursor_Destructor: 3328 return createCXString("CXXDestructor"); 3329 case CXCursor_ConversionFunction: 3330 return createCXString("CXXConversion"); 3331 case CXCursor_TemplateTypeParameter: 3332 return createCXString("TemplateTypeParameter"); 3333 case CXCursor_NonTypeTemplateParameter: 3334 return createCXString("NonTypeTemplateParameter"); 3335 case CXCursor_TemplateTemplateParameter: 3336 return createCXString("TemplateTemplateParameter"); 3337 case CXCursor_FunctionTemplate: 3338 return createCXString("FunctionTemplate"); 3339 case CXCursor_ClassTemplate: 3340 return createCXString("ClassTemplate"); 3341 case CXCursor_ClassTemplatePartialSpecialization: 3342 return createCXString("ClassTemplatePartialSpecialization"); 3343 case CXCursor_NamespaceAlias: 3344 return createCXString("NamespaceAlias"); 3345 case CXCursor_UsingDirective: 3346 return createCXString("UsingDirective"); 3347 case CXCursor_UsingDeclaration: 3348 return createCXString("UsingDeclaration"); 3349 case CXCursor_TypeAliasDecl: 3350 return createCXString("TypeAliasDecl"); 3351 } 3352 3353 llvm_unreachable("Unhandled CXCursorKind"); 3354 return createCXString((const char*) 0); 3355} 3356 3357enum CXChildVisitResult GetCursorVisitor(CXCursor cursor, 3358 CXCursor parent, 3359 CXClientData client_data) { 3360 CXCursor *BestCursor = static_cast<CXCursor *>(client_data); 3361 3362 // If our current best cursor is the construction of a temporary object, 3363 // don't replace that cursor with a type reference, because we want 3364 // clang_getCursor() to point at the constructor. 3365 if (clang_isExpression(BestCursor->kind) && 3366 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) && 3367 cursor.kind == CXCursor_TypeRef) 3368 return CXChildVisit_Recurse; 3369 3370 // Don't override a preprocessing cursor with another preprocessing 3371 // cursor; we want the outermost preprocessing cursor. 3372 if (clang_isPreprocessing(cursor.kind) && 3373 clang_isPreprocessing(BestCursor->kind)) 3374 return CXChildVisit_Recurse; 3375 3376 *BestCursor = cursor; 3377 return CXChildVisit_Recurse; 3378} 3379 3380CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) { 3381 if (!TU) 3382 return clang_getNullCursor(); 3383 3384 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 3385 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 3386 3387 // Translate the given source location to make it point at the beginning of 3388 // the token under the cursor. 3389 SourceLocation SLoc = cxloc::translateSourceLocation(Loc); 3390 3391 // Guard against an invalid SourceLocation, or we may assert in one 3392 // of the following calls. 3393 if (SLoc.isInvalid()) 3394 return clang_getNullCursor(); 3395 3396 bool Logging = getenv("LIBCLANG_LOGGING"); 3397 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(), 3398 CXXUnit->getASTContext().getLangOptions()); 3399 3400 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound); 3401 if (SLoc.isValid()) { 3402 // FIXME: Would be great to have a "hint" cursor, then walk from that 3403 // hint cursor upward until we find a cursor whose source range encloses 3404 // the region of interest, rather than starting from the translation unit. 3405 CXCursor Parent = clang_getTranslationUnitCursor(TU); 3406 CursorVisitor CursorVis(TU, GetCursorVisitor, &Result, 3407 Decl::MaxPCHLevel, true, SourceLocation(SLoc)); 3408 CursorVis.VisitChildren(Parent); 3409 } 3410 3411 if (Logging) { 3412 CXFile SearchFile; 3413 unsigned SearchLine, SearchColumn; 3414 CXFile ResultFile; 3415 unsigned ResultLine, ResultColumn; 3416 CXString SearchFileName, ResultFileName, KindSpelling, USR; 3417 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : ""; 3418 CXSourceLocation ResultLoc = clang_getCursorLocation(Result); 3419 3420 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 3421 0); 3422 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine, 3423 &ResultColumn, 0); 3424 SearchFileName = clang_getFileName(SearchFile); 3425 ResultFileName = clang_getFileName(ResultFile); 3426 KindSpelling = clang_getCursorKindSpelling(Result.kind); 3427 USR = clang_getCursorUSR(Result); 3428 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n", 3429 clang_getCString(SearchFileName), SearchLine, SearchColumn, 3430 clang_getCString(KindSpelling), 3431 clang_getCString(ResultFileName), ResultLine, ResultColumn, 3432 clang_getCString(USR), IsDef); 3433 clang_disposeString(SearchFileName); 3434 clang_disposeString(ResultFileName); 3435 clang_disposeString(KindSpelling); 3436 clang_disposeString(USR); 3437 3438 CXCursor Definition = clang_getCursorDefinition(Result); 3439 if (!clang_equalCursors(Definition, clang_getNullCursor())) { 3440 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition); 3441 CXString DefinitionKindSpelling 3442 = clang_getCursorKindSpelling(Definition.kind); 3443 CXFile DefinitionFile; 3444 unsigned DefinitionLine, DefinitionColumn; 3445 clang_getInstantiationLocation(DefinitionLoc, &DefinitionFile, 3446 &DefinitionLine, &DefinitionColumn, 0); 3447 CXString DefinitionFileName = clang_getFileName(DefinitionFile); 3448 fprintf(stderr, " -> %s(%s:%d:%d)\n", 3449 clang_getCString(DefinitionKindSpelling), 3450 clang_getCString(DefinitionFileName), 3451 DefinitionLine, DefinitionColumn); 3452 clang_disposeString(DefinitionFileName); 3453 clang_disposeString(DefinitionKindSpelling); 3454 } 3455 } 3456 3457 return Result; 3458} 3459 3460CXCursor clang_getNullCursor(void) { 3461 return MakeCXCursorInvalid(CXCursor_InvalidFile); 3462} 3463 3464unsigned clang_equalCursors(CXCursor X, CXCursor Y) { 3465 return X == Y; 3466} 3467 3468unsigned clang_hashCursor(CXCursor C) { 3469 unsigned Index = 0; 3470 if (clang_isExpression(C.kind) || clang_isStatement(C.kind)) 3471 Index = 1; 3472 3473 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue( 3474 std::make_pair(C.kind, C.data[Index])); 3475} 3476 3477unsigned clang_isInvalid(enum CXCursorKind K) { 3478 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid; 3479} 3480 3481unsigned clang_isDeclaration(enum CXCursorKind K) { 3482 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl; 3483} 3484 3485unsigned clang_isReference(enum CXCursorKind K) { 3486 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef; 3487} 3488 3489unsigned clang_isExpression(enum CXCursorKind K) { 3490 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr; 3491} 3492 3493unsigned clang_isStatement(enum CXCursorKind K) { 3494 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt; 3495} 3496 3497unsigned clang_isTranslationUnit(enum CXCursorKind K) { 3498 return K == CXCursor_TranslationUnit; 3499} 3500 3501unsigned clang_isPreprocessing(enum CXCursorKind K) { 3502 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing; 3503} 3504 3505unsigned clang_isUnexposed(enum CXCursorKind K) { 3506 switch (K) { 3507 case CXCursor_UnexposedDecl: 3508 case CXCursor_UnexposedExpr: 3509 case CXCursor_UnexposedStmt: 3510 case CXCursor_UnexposedAttr: 3511 return true; 3512 default: 3513 return false; 3514 } 3515} 3516 3517CXCursorKind clang_getCursorKind(CXCursor C) { 3518 return C.kind; 3519} 3520 3521CXSourceLocation clang_getCursorLocation(CXCursor C) { 3522 if (clang_isReference(C.kind)) { 3523 switch (C.kind) { 3524 case CXCursor_ObjCSuperClassRef: { 3525 std::pair<ObjCInterfaceDecl *, SourceLocation> P 3526 = getCursorObjCSuperClassRef(C); 3527 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3528 } 3529 3530 case CXCursor_ObjCProtocolRef: { 3531 std::pair<ObjCProtocolDecl *, SourceLocation> P 3532 = getCursorObjCProtocolRef(C); 3533 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3534 } 3535 3536 case CXCursor_ObjCClassRef: { 3537 std::pair<ObjCInterfaceDecl *, SourceLocation> P 3538 = getCursorObjCClassRef(C); 3539 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3540 } 3541 3542 case CXCursor_TypeRef: { 3543 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C); 3544 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3545 } 3546 3547 case CXCursor_TemplateRef: { 3548 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C); 3549 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3550 } 3551 3552 case CXCursor_NamespaceRef: { 3553 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C); 3554 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3555 } 3556 3557 case CXCursor_MemberRef: { 3558 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C); 3559 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3560 } 3561 3562 case CXCursor_CXXBaseSpecifier: { 3563 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C); 3564 if (!BaseSpec) 3565 return clang_getNullLocation(); 3566 3567 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo()) 3568 return cxloc::translateSourceLocation(getCursorContext(C), 3569 TSInfo->getTypeLoc().getBeginLoc()); 3570 3571 return cxloc::translateSourceLocation(getCursorContext(C), 3572 BaseSpec->getSourceRange().getBegin()); 3573 } 3574 3575 case CXCursor_LabelRef: { 3576 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C); 3577 return cxloc::translateSourceLocation(getCursorContext(C), P.second); 3578 } 3579 3580 case CXCursor_OverloadedDeclRef: 3581 return cxloc::translateSourceLocation(getCursorContext(C), 3582 getCursorOverloadedDeclRef(C).second); 3583 3584 default: 3585 // FIXME: Need a way to enumerate all non-reference cases. 3586 llvm_unreachable("Missed a reference kind"); 3587 } 3588 } 3589 3590 if (clang_isExpression(C.kind)) 3591 return cxloc::translateSourceLocation(getCursorContext(C), 3592 getLocationFromExpr(getCursorExpr(C))); 3593 3594 if (clang_isStatement(C.kind)) 3595 return cxloc::translateSourceLocation(getCursorContext(C), 3596 getCursorStmt(C)->getLocStart()); 3597 3598 if (C.kind == CXCursor_PreprocessingDirective) { 3599 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin(); 3600 return cxloc::translateSourceLocation(getCursorContext(C), L); 3601 } 3602 3603 if (C.kind == CXCursor_MacroInstantiation) { 3604 SourceLocation L 3605 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin(); 3606 return cxloc::translateSourceLocation(getCursorContext(C), L); 3607 } 3608 3609 if (C.kind == CXCursor_MacroDefinition) { 3610 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation(); 3611 return cxloc::translateSourceLocation(getCursorContext(C), L); 3612 } 3613 3614 if (C.kind == CXCursor_InclusionDirective) { 3615 SourceLocation L 3616 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin(); 3617 return cxloc::translateSourceLocation(getCursorContext(C), L); 3618 } 3619 3620 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl) 3621 return clang_getNullLocation(); 3622 3623 Decl *D = getCursorDecl(C); 3624 SourceLocation Loc = D->getLocation(); 3625 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D)) 3626 Loc = Class->getClassLoc(); 3627 // FIXME: Multiple variables declared in a single declaration 3628 // currently lack the information needed to correctly determine their 3629 // ranges when accounting for the type-specifier. We use context 3630 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, 3631 // and if so, whether it is the first decl. 3632 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 3633 if (!cxcursor::isFirstInDeclGroup(C)) 3634 Loc = VD->getLocation(); 3635 } 3636 3637 return cxloc::translateSourceLocation(getCursorContext(C), Loc); 3638} 3639 3640} // end extern "C" 3641 3642static SourceRange getRawCursorExtent(CXCursor C) { 3643 if (clang_isReference(C.kind)) { 3644 switch (C.kind) { 3645 case CXCursor_ObjCSuperClassRef: 3646 return getCursorObjCSuperClassRef(C).second; 3647 3648 case CXCursor_ObjCProtocolRef: 3649 return getCursorObjCProtocolRef(C).second; 3650 3651 case CXCursor_ObjCClassRef: 3652 return getCursorObjCClassRef(C).second; 3653 3654 case CXCursor_TypeRef: 3655 return getCursorTypeRef(C).second; 3656 3657 case CXCursor_TemplateRef: 3658 return getCursorTemplateRef(C).second; 3659 3660 case CXCursor_NamespaceRef: 3661 return getCursorNamespaceRef(C).second; 3662 3663 case CXCursor_MemberRef: 3664 return getCursorMemberRef(C).second; 3665 3666 case CXCursor_CXXBaseSpecifier: 3667 return getCursorCXXBaseSpecifier(C)->getSourceRange(); 3668 3669 case CXCursor_LabelRef: 3670 return getCursorLabelRef(C).second; 3671 3672 case CXCursor_OverloadedDeclRef: 3673 return getCursorOverloadedDeclRef(C).second; 3674 3675 default: 3676 // FIXME: Need a way to enumerate all non-reference cases. 3677 llvm_unreachable("Missed a reference kind"); 3678 } 3679 } 3680 3681 if (clang_isExpression(C.kind)) 3682 return getCursorExpr(C)->getSourceRange(); 3683 3684 if (clang_isStatement(C.kind)) 3685 return getCursorStmt(C)->getSourceRange(); 3686 3687 if (C.kind == CXCursor_PreprocessingDirective) 3688 return cxcursor::getCursorPreprocessingDirective(C); 3689 3690 if (C.kind == CXCursor_MacroInstantiation) 3691 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange(); 3692 3693 if (C.kind == CXCursor_MacroDefinition) 3694 return cxcursor::getCursorMacroDefinition(C)->getSourceRange(); 3695 3696 if (C.kind == CXCursor_InclusionDirective) 3697 return cxcursor::getCursorInclusionDirective(C)->getSourceRange(); 3698 3699 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) { 3700 Decl *D = cxcursor::getCursorDecl(C); 3701 SourceRange R = D->getSourceRange(); 3702 // FIXME: Multiple variables declared in a single declaration 3703 // currently lack the information needed to correctly determine their 3704 // ranges when accounting for the type-specifier. We use context 3705 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, 3706 // and if so, whether it is the first decl. 3707 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 3708 if (!cxcursor::isFirstInDeclGroup(C)) 3709 R.setBegin(VD->getLocation()); 3710 } 3711 return R; 3712 } 3713 return SourceRange(); 3714} 3715 3716/// \brief Retrieves the "raw" cursor extent, which is then extended to include 3717/// the decl-specifier-seq for declarations. 3718static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) { 3719 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) { 3720 Decl *D = cxcursor::getCursorDecl(C); 3721 SourceRange R = D->getSourceRange(); 3722 3723 // Adjust the start of the location for declarations preceded by 3724 // declaration specifiers. 3725 SourceLocation StartLoc; 3726 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 3727 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) 3728 StartLoc = TI->getTypeLoc().getSourceRange().getBegin(); 3729 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) { 3730 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo()) 3731 StartLoc = TI->getTypeLoc().getSourceRange().getBegin(); 3732 } 3733 3734 if (StartLoc.isValid() && R.getBegin().isValid() && 3735 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin())) 3736 R.setBegin(StartLoc); 3737 3738 // FIXME: Multiple variables declared in a single declaration 3739 // currently lack the information needed to correctly determine their 3740 // ranges when accounting for the type-specifier. We use context 3741 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, 3742 // and if so, whether it is the first decl. 3743 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 3744 if (!cxcursor::isFirstInDeclGroup(C)) 3745 R.setBegin(VD->getLocation()); 3746 } 3747 3748 return R; 3749 } 3750 3751 return getRawCursorExtent(C); 3752} 3753 3754extern "C" { 3755 3756CXSourceRange clang_getCursorExtent(CXCursor C) { 3757 SourceRange R = getRawCursorExtent(C); 3758 if (R.isInvalid()) 3759 return clang_getNullRange(); 3760 3761 return cxloc::translateSourceRange(getCursorContext(C), R); 3762} 3763 3764CXCursor clang_getCursorReferenced(CXCursor C) { 3765 if (clang_isInvalid(C.kind)) 3766 return clang_getNullCursor(); 3767 3768 CXTranslationUnit tu = getCursorTU(C); 3769 if (clang_isDeclaration(C.kind)) { 3770 Decl *D = getCursorDecl(C); 3771 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) 3772 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu); 3773 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D)) 3774 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu); 3775 if (ObjCForwardProtocolDecl *Protocols 3776 = dyn_cast<ObjCForwardProtocolDecl>(D)) 3777 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu); 3778 if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D)) 3779 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl()) 3780 return MakeCXCursor(Property, tu); 3781 3782 return C; 3783 } 3784 3785 if (clang_isExpression(C.kind)) { 3786 Expr *E = getCursorExpr(C); 3787 Decl *D = getDeclFromExpr(E); 3788 if (D) 3789 return MakeCXCursor(D, tu); 3790 3791 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E)) 3792 return MakeCursorOverloadedDeclRef(Ovl, tu); 3793 3794 return clang_getNullCursor(); 3795 } 3796 3797 if (clang_isStatement(C.kind)) { 3798 Stmt *S = getCursorStmt(C); 3799 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S)) 3800 if (LabelDecl *label = Goto->getLabel()) 3801 if (LabelStmt *labelS = label->getStmt()) 3802 return MakeCXCursor(labelS, getCursorDecl(C), tu); 3803 3804 return clang_getNullCursor(); 3805 } 3806 3807 if (C.kind == CXCursor_MacroInstantiation) { 3808 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition()) 3809 return MakeMacroDefinitionCursor(Def, tu); 3810 } 3811 3812 if (!clang_isReference(C.kind)) 3813 return clang_getNullCursor(); 3814 3815 switch (C.kind) { 3816 case CXCursor_ObjCSuperClassRef: 3817 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu); 3818 3819 case CXCursor_ObjCProtocolRef: { 3820 return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu); 3821 3822 case CXCursor_ObjCClassRef: 3823 return MakeCXCursor(getCursorObjCClassRef(C).first, tu ); 3824 3825 case CXCursor_TypeRef: 3826 return MakeCXCursor(getCursorTypeRef(C).first, tu ); 3827 3828 case CXCursor_TemplateRef: 3829 return MakeCXCursor(getCursorTemplateRef(C).first, tu ); 3830 3831 case CXCursor_NamespaceRef: 3832 return MakeCXCursor(getCursorNamespaceRef(C).first, tu ); 3833 3834 case CXCursor_MemberRef: 3835 return MakeCXCursor(getCursorMemberRef(C).first, tu ); 3836 3837 case CXCursor_CXXBaseSpecifier: { 3838 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C); 3839 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(), 3840 tu )); 3841 } 3842 3843 case CXCursor_LabelRef: 3844 // FIXME: We end up faking the "parent" declaration here because we 3845 // don't want to make CXCursor larger. 3846 return MakeCXCursor(getCursorLabelRef(C).first, 3847 static_cast<ASTUnit*>(tu->TUData)->getASTContext() 3848 .getTranslationUnitDecl(), 3849 tu); 3850 3851 case CXCursor_OverloadedDeclRef: 3852 return C; 3853 3854 default: 3855 // We would prefer to enumerate all non-reference cursor kinds here. 3856 llvm_unreachable("Unhandled reference cursor kind"); 3857 break; 3858 } 3859 } 3860 3861 return clang_getNullCursor(); 3862} 3863 3864CXCursor clang_getCursorDefinition(CXCursor C) { 3865 if (clang_isInvalid(C.kind)) 3866 return clang_getNullCursor(); 3867 3868 CXTranslationUnit TU = getCursorTU(C); 3869 3870 bool WasReference = false; 3871 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) { 3872 C = clang_getCursorReferenced(C); 3873 WasReference = true; 3874 } 3875 3876 if (C.kind == CXCursor_MacroInstantiation) 3877 return clang_getCursorReferenced(C); 3878 3879 if (!clang_isDeclaration(C.kind)) 3880 return clang_getNullCursor(); 3881 3882 Decl *D = getCursorDecl(C); 3883 if (!D) 3884 return clang_getNullCursor(); 3885 3886 switch (D->getKind()) { 3887 // Declaration kinds that don't really separate the notions of 3888 // declaration and definition. 3889 case Decl::Namespace: 3890 case Decl::Typedef: 3891 case Decl::TypeAlias: 3892 case Decl::TemplateTypeParm: 3893 case Decl::EnumConstant: 3894 case Decl::Field: 3895 case Decl::IndirectField: 3896 case Decl::ObjCIvar: 3897 case Decl::ObjCAtDefsField: 3898 case Decl::ImplicitParam: 3899 case Decl::ParmVar: 3900 case Decl::NonTypeTemplateParm: 3901 case Decl::TemplateTemplateParm: 3902 case Decl::ObjCCategoryImpl: 3903 case Decl::ObjCImplementation: 3904 case Decl::AccessSpec: 3905 case Decl::LinkageSpec: 3906 case Decl::ObjCPropertyImpl: 3907 case Decl::FileScopeAsm: 3908 case Decl::StaticAssert: 3909 case Decl::Block: 3910 case Decl::Label: // FIXME: Is this right?? 3911 return C; 3912 3913 // Declaration kinds that don't make any sense here, but are 3914 // nonetheless harmless. 3915 case Decl::TranslationUnit: 3916 break; 3917 3918 // Declaration kinds for which the definition is not resolvable. 3919 case Decl::UnresolvedUsingTypename: 3920 case Decl::UnresolvedUsingValue: 3921 break; 3922 3923 case Decl::UsingDirective: 3924 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(), 3925 TU); 3926 3927 case Decl::NamespaceAlias: 3928 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU); 3929 3930 case Decl::Enum: 3931 case Decl::Record: 3932 case Decl::CXXRecord: 3933 case Decl::ClassTemplateSpecialization: 3934 case Decl::ClassTemplatePartialSpecialization: 3935 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition()) 3936 return MakeCXCursor(Def, TU); 3937 return clang_getNullCursor(); 3938 3939 case Decl::Function: 3940 case Decl::CXXMethod: 3941 case Decl::CXXConstructor: 3942 case Decl::CXXDestructor: 3943 case Decl::CXXConversion: { 3944 const FunctionDecl *Def = 0; 3945 if (cast<FunctionDecl>(D)->getBody(Def)) 3946 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU); 3947 return clang_getNullCursor(); 3948 } 3949 3950 case Decl::Var: { 3951 // Ask the variable if it has a definition. 3952 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition()) 3953 return MakeCXCursor(Def, TU); 3954 return clang_getNullCursor(); 3955 } 3956 3957 case Decl::FunctionTemplate: { 3958 const FunctionDecl *Def = 0; 3959 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def)) 3960 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU); 3961 return clang_getNullCursor(); 3962 } 3963 3964 case Decl::ClassTemplate: { 3965 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl() 3966 ->getDefinition()) 3967 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(), 3968 TU); 3969 return clang_getNullCursor(); 3970 } 3971 3972 case Decl::Using: 3973 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D), 3974 D->getLocation(), TU); 3975 3976 case Decl::UsingShadow: 3977 return clang_getCursorDefinition( 3978 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(), 3979 TU)); 3980 3981 case Decl::ObjCMethod: { 3982 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D); 3983 if (Method->isThisDeclarationADefinition()) 3984 return C; 3985 3986 // Dig out the method definition in the associated 3987 // @implementation, if we have it. 3988 // FIXME: The ASTs should make finding the definition easier. 3989 if (ObjCInterfaceDecl *Class 3990 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) 3991 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation()) 3992 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(), 3993 Method->isInstanceMethod())) 3994 if (Def->isThisDeclarationADefinition()) 3995 return MakeCXCursor(Def, TU); 3996 3997 return clang_getNullCursor(); 3998 } 3999 4000 case Decl::ObjCCategory: 4001 if (ObjCCategoryImplDecl *Impl 4002 = cast<ObjCCategoryDecl>(D)->getImplementation()) 4003 return MakeCXCursor(Impl, TU); 4004 return clang_getNullCursor(); 4005 4006 case Decl::ObjCProtocol: 4007 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl()) 4008 return C; 4009 return clang_getNullCursor(); 4010 4011 case Decl::ObjCInterface: 4012 // There are two notions of a "definition" for an Objective-C 4013 // class: the interface and its implementation. When we resolved a 4014 // reference to an Objective-C class, produce the @interface as 4015 // the definition; when we were provided with the interface, 4016 // produce the @implementation as the definition. 4017 if (WasReference) { 4018 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl()) 4019 return C; 4020 } else if (ObjCImplementationDecl *Impl 4021 = cast<ObjCInterfaceDecl>(D)->getImplementation()) 4022 return MakeCXCursor(Impl, TU); 4023 return clang_getNullCursor(); 4024 4025 case Decl::ObjCProperty: 4026 // FIXME: We don't really know where to find the 4027 // ObjCPropertyImplDecls that implement this property. 4028 return clang_getNullCursor(); 4029 4030 case Decl::ObjCCompatibleAlias: 4031 if (ObjCInterfaceDecl *Class 4032 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface()) 4033 if (!Class->isForwardDecl()) 4034 return MakeCXCursor(Class, TU); 4035 4036 return clang_getNullCursor(); 4037 4038 case Decl::ObjCForwardProtocol: 4039 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D), 4040 D->getLocation(), TU); 4041 4042 case Decl::ObjCClass: 4043 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(), 4044 TU); 4045 4046 case Decl::Friend: 4047 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl()) 4048 return clang_getCursorDefinition(MakeCXCursor(Friend, TU)); 4049 return clang_getNullCursor(); 4050 4051 case Decl::FriendTemplate: 4052 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl()) 4053 return clang_getCursorDefinition(MakeCXCursor(Friend, TU)); 4054 return clang_getNullCursor(); 4055 } 4056 4057 return clang_getNullCursor(); 4058} 4059 4060unsigned clang_isCursorDefinition(CXCursor C) { 4061 if (!clang_isDeclaration(C.kind)) 4062 return 0; 4063 4064 return clang_getCursorDefinition(C) == C; 4065} 4066 4067CXCursor clang_getCanonicalCursor(CXCursor C) { 4068 if (!clang_isDeclaration(C.kind)) 4069 return C; 4070 4071 if (Decl *D = getCursorDecl(C)) 4072 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C)); 4073 4074 return C; 4075} 4076 4077unsigned clang_getNumOverloadedDecls(CXCursor C) { 4078 if (C.kind != CXCursor_OverloadedDeclRef) 4079 return 0; 4080 4081 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first; 4082 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>()) 4083 return E->getNumDecls(); 4084 4085 if (OverloadedTemplateStorage *S 4086 = Storage.dyn_cast<OverloadedTemplateStorage*>()) 4087 return S->size(); 4088 4089 Decl *D = Storage.get<Decl*>(); 4090 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) 4091 return Using->shadow_size(); 4092 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D)) 4093 return Classes->size(); 4094 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D)) 4095 return Protocols->protocol_size(); 4096 4097 return 0; 4098} 4099 4100CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) { 4101 if (cursor.kind != CXCursor_OverloadedDeclRef) 4102 return clang_getNullCursor(); 4103 4104 if (index >= clang_getNumOverloadedDecls(cursor)) 4105 return clang_getNullCursor(); 4106 4107 CXTranslationUnit TU = getCursorTU(cursor); 4108 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first; 4109 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>()) 4110 return MakeCXCursor(E->decls_begin()[index], TU); 4111 4112 if (OverloadedTemplateStorage *S 4113 = Storage.dyn_cast<OverloadedTemplateStorage*>()) 4114 return MakeCXCursor(S->begin()[index], TU); 4115 4116 Decl *D = Storage.get<Decl*>(); 4117 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) { 4118 // FIXME: This is, unfortunately, linear time. 4119 UsingDecl::shadow_iterator Pos = Using->shadow_begin(); 4120 std::advance(Pos, index); 4121 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU); 4122 } 4123 4124 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D)) 4125 return MakeCXCursor(Classes->begin()[index].getInterface(), TU); 4126 4127 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D)) 4128 return MakeCXCursor(Protocols->protocol_begin()[index], TU); 4129 4130 return clang_getNullCursor(); 4131} 4132 4133void clang_getDefinitionSpellingAndExtent(CXCursor C, 4134 const char **startBuf, 4135 const char **endBuf, 4136 unsigned *startLine, 4137 unsigned *startColumn, 4138 unsigned *endLine, 4139 unsigned *endColumn) { 4140 assert(getCursorDecl(C) && "CXCursor has null decl"); 4141 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C)); 4142 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND); 4143 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody()); 4144 4145 SourceManager &SM = FD->getASTContext().getSourceManager(); 4146 *startBuf = SM.getCharacterData(Body->getLBracLoc()); 4147 *endBuf = SM.getCharacterData(Body->getRBracLoc()); 4148 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc()); 4149 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc()); 4150 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc()); 4151 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc()); 4152} 4153 4154void clang_enableStackTraces(void) { 4155 llvm::sys::PrintStackTraceOnErrorSignal(); 4156} 4157 4158void clang_executeOnThread(void (*fn)(void*), void *user_data, 4159 unsigned stack_size) { 4160 llvm::llvm_execute_on_thread(fn, user_data, stack_size); 4161} 4162 4163} // end: extern "C" 4164 4165//===----------------------------------------------------------------------===// 4166// Token-based Operations. 4167//===----------------------------------------------------------------------===// 4168 4169/* CXToken layout: 4170 * int_data[0]: a CXTokenKind 4171 * int_data[1]: starting token location 4172 * int_data[2]: token length 4173 * int_data[3]: reserved 4174 * ptr_data: for identifiers and keywords, an IdentifierInfo*. 4175 * otherwise unused. 4176 */ 4177extern "C" { 4178 4179CXTokenKind clang_getTokenKind(CXToken CXTok) { 4180 return static_cast<CXTokenKind>(CXTok.int_data[0]); 4181} 4182 4183CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) { 4184 switch (clang_getTokenKind(CXTok)) { 4185 case CXToken_Identifier: 4186 case CXToken_Keyword: 4187 // We know we have an IdentifierInfo*, so use that. 4188 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data) 4189 ->getNameStart()); 4190 4191 case CXToken_Literal: { 4192 // We have stashed the starting pointer in the ptr_data field. Use it. 4193 const char *Text = static_cast<const char *>(CXTok.ptr_data); 4194 return createCXString(llvm::StringRef(Text, CXTok.int_data[2])); 4195 } 4196 4197 case CXToken_Punctuation: 4198 case CXToken_Comment: 4199 break; 4200 } 4201 4202 // We have to find the starting buffer pointer the hard way, by 4203 // deconstructing the source location. 4204 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 4205 if (!CXXUnit) 4206 return createCXString(""); 4207 4208 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]); 4209 std::pair<FileID, unsigned> LocInfo 4210 = CXXUnit->getSourceManager().getDecomposedLoc(Loc); 4211 bool Invalid = false; 4212 llvm::StringRef Buffer 4213 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid); 4214 if (Invalid) 4215 return createCXString(""); 4216 4217 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2])); 4218} 4219 4220CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) { 4221 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 4222 if (!CXXUnit) 4223 return clang_getNullLocation(); 4224 4225 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), 4226 SourceLocation::getFromRawEncoding(CXTok.int_data[1])); 4227} 4228 4229CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) { 4230 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 4231 if (!CXXUnit) 4232 return clang_getNullRange(); 4233 4234 return cxloc::translateSourceRange(CXXUnit->getASTContext(), 4235 SourceLocation::getFromRawEncoding(CXTok.int_data[1])); 4236} 4237 4238void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range, 4239 CXToken **Tokens, unsigned *NumTokens) { 4240 if (Tokens) 4241 *Tokens = 0; 4242 if (NumTokens) 4243 *NumTokens = 0; 4244 4245 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 4246 if (!CXXUnit || !Tokens || !NumTokens) 4247 return; 4248 4249 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 4250 4251 SourceRange R = cxloc::translateCXSourceRange(Range); 4252 if (R.isInvalid()) 4253 return; 4254 4255 SourceManager &SourceMgr = CXXUnit->getSourceManager(); 4256 std::pair<FileID, unsigned> BeginLocInfo 4257 = SourceMgr.getDecomposedLoc(R.getBegin()); 4258 std::pair<FileID, unsigned> EndLocInfo 4259 = SourceMgr.getDecomposedLoc(R.getEnd()); 4260 4261 // Cannot tokenize across files. 4262 if (BeginLocInfo.first != EndLocInfo.first) 4263 return; 4264 4265 // Create a lexer 4266 bool Invalid = false; 4267 llvm::StringRef Buffer 4268 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid); 4269 if (Invalid) 4270 return; 4271 4272 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first), 4273 CXXUnit->getASTContext().getLangOptions(), 4274 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end()); 4275 Lex.SetCommentRetentionState(true); 4276 4277 // Lex tokens until we hit the end of the range. 4278 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second; 4279 llvm::SmallVector<CXToken, 32> CXTokens; 4280 Token Tok; 4281 bool previousWasAt = false; 4282 do { 4283 // Lex the next token 4284 Lex.LexFromRawLexer(Tok); 4285 if (Tok.is(tok::eof)) 4286 break; 4287 4288 // Initialize the CXToken. 4289 CXToken CXTok; 4290 4291 // - Common fields 4292 CXTok.int_data[1] = Tok.getLocation().getRawEncoding(); 4293 CXTok.int_data[2] = Tok.getLength(); 4294 CXTok.int_data[3] = 0; 4295 4296 // - Kind-specific fields 4297 if (Tok.isLiteral()) { 4298 CXTok.int_data[0] = CXToken_Literal; 4299 CXTok.ptr_data = (void *)Tok.getLiteralData(); 4300 } else if (Tok.is(tok::raw_identifier)) { 4301 // Lookup the identifier to determine whether we have a keyword. 4302 IdentifierInfo *II 4303 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok); 4304 4305 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) { 4306 CXTok.int_data[0] = CXToken_Keyword; 4307 } 4308 else { 4309 CXTok.int_data[0] = Tok.is(tok::identifier) 4310 ? CXToken_Identifier 4311 : CXToken_Keyword; 4312 } 4313 CXTok.ptr_data = II; 4314 } else if (Tok.is(tok::comment)) { 4315 CXTok.int_data[0] = CXToken_Comment; 4316 CXTok.ptr_data = 0; 4317 } else { 4318 CXTok.int_data[0] = CXToken_Punctuation; 4319 CXTok.ptr_data = 0; 4320 } 4321 CXTokens.push_back(CXTok); 4322 previousWasAt = Tok.is(tok::at); 4323 } while (Lex.getBufferLocation() <= EffectiveBufferEnd); 4324 4325 if (CXTokens.empty()) 4326 return; 4327 4328 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size()); 4329 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size()); 4330 *NumTokens = CXTokens.size(); 4331} 4332 4333void clang_disposeTokens(CXTranslationUnit TU, 4334 CXToken *Tokens, unsigned NumTokens) { 4335 free(Tokens); 4336} 4337 4338} // end: extern "C" 4339 4340//===----------------------------------------------------------------------===// 4341// Token annotation APIs. 4342//===----------------------------------------------------------------------===// 4343 4344typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData; 4345static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor, 4346 CXCursor parent, 4347 CXClientData client_data); 4348namespace { 4349class AnnotateTokensWorker { 4350 AnnotateTokensData &Annotated; 4351 CXToken *Tokens; 4352 CXCursor *Cursors; 4353 unsigned NumTokens; 4354 unsigned TokIdx; 4355 unsigned PreprocessingTokIdx; 4356 CursorVisitor AnnotateVis; 4357 SourceManager &SrcMgr; 4358 bool HasContextSensitiveKeywords; 4359 4360 bool MoreTokens() const { return TokIdx < NumTokens; } 4361 unsigned NextToken() const { return TokIdx; } 4362 void AdvanceToken() { ++TokIdx; } 4363 SourceLocation GetTokenLoc(unsigned tokI) { 4364 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]); 4365 } 4366 4367public: 4368 AnnotateTokensWorker(AnnotateTokensData &annotated, 4369 CXToken *tokens, CXCursor *cursors, unsigned numTokens, 4370 CXTranslationUnit tu, SourceRange RegionOfInterest) 4371 : Annotated(annotated), Tokens(tokens), Cursors(cursors), 4372 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0), 4373 AnnotateVis(tu, 4374 AnnotateTokensVisitor, this, 4375 Decl::MaxPCHLevel, true, RegionOfInterest), 4376 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()), 4377 HasContextSensitiveKeywords(false) { } 4378 4379 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); } 4380 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent); 4381 void AnnotateTokens(CXCursor parent); 4382 void AnnotateTokens() { 4383 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU())); 4384 } 4385 4386 /// \brief Determine whether the annotator saw any cursors that have 4387 /// context-sensitive keywords. 4388 bool hasContextSensitiveKeywords() const { 4389 return HasContextSensitiveKeywords; 4390 } 4391}; 4392} 4393 4394void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) { 4395 // Walk the AST within the region of interest, annotating tokens 4396 // along the way. 4397 VisitChildren(parent); 4398 4399 for (unsigned I = 0 ; I < TokIdx ; ++I) { 4400 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]); 4401 if (Pos != Annotated.end() && 4402 (clang_isInvalid(Cursors[I].kind) || 4403 Pos->second.kind != CXCursor_PreprocessingDirective)) 4404 Cursors[I] = Pos->second; 4405 } 4406 4407 // Finish up annotating any tokens left. 4408 if (!MoreTokens()) 4409 return; 4410 4411 const CXCursor &C = clang_getNullCursor(); 4412 for (unsigned I = TokIdx ; I < NumTokens ; ++I) { 4413 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]); 4414 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second; 4415 } 4416} 4417 4418enum CXChildVisitResult 4419AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) { 4420 CXSourceLocation Loc = clang_getCursorLocation(cursor); 4421 SourceRange cursorRange = getRawCursorExtent(cursor); 4422 if (cursorRange.isInvalid()) 4423 return CXChildVisit_Recurse; 4424 4425 if (!HasContextSensitiveKeywords) { 4426 // Objective-C properties can have context-sensitive keywords. 4427 if (cursor.kind == CXCursor_ObjCPropertyDecl) { 4428 if (ObjCPropertyDecl *Property 4429 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor))) 4430 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0; 4431 } 4432 // Objective-C methods can have context-sensitive keywords. 4433 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl || 4434 cursor.kind == CXCursor_ObjCClassMethodDecl) { 4435 if (ObjCMethodDecl *Method 4436 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) { 4437 if (Method->getObjCDeclQualifier()) 4438 HasContextSensitiveKeywords = true; 4439 else { 4440 for (ObjCMethodDecl::param_iterator P = Method->param_begin(), 4441 PEnd = Method->param_end(); 4442 P != PEnd; ++P) { 4443 if ((*P)->getObjCDeclQualifier()) { 4444 HasContextSensitiveKeywords = true; 4445 break; 4446 } 4447 } 4448 } 4449 } 4450 } 4451 // C++ methods can have context-sensitive keywords. 4452 else if (cursor.kind == CXCursor_CXXMethod) { 4453 if (CXXMethodDecl *Method 4454 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) { 4455 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>()) 4456 HasContextSensitiveKeywords = true; 4457 } 4458 } 4459 // C++ classes can have context-sensitive keywords. 4460 else if (cursor.kind == CXCursor_StructDecl || 4461 cursor.kind == CXCursor_ClassDecl || 4462 cursor.kind == CXCursor_ClassTemplate || 4463 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) { 4464 if (Decl *D = getCursorDecl(cursor)) 4465 if (D->hasAttr<FinalAttr>()) 4466 HasContextSensitiveKeywords = true; 4467 } 4468 } 4469 4470 if (clang_isPreprocessing(cursor.kind)) { 4471 // For macro instantiations, just note where the beginning of the macro 4472 // instantiation occurs. 4473 if (cursor.kind == CXCursor_MacroInstantiation) { 4474 Annotated[Loc.int_data] = cursor; 4475 return CXChildVisit_Recurse; 4476 } 4477 4478 // Items in the preprocessing record are kept separate from items in 4479 // declarations, so we keep a separate token index. 4480 unsigned SavedTokIdx = TokIdx; 4481 TokIdx = PreprocessingTokIdx; 4482 4483 // Skip tokens up until we catch up to the beginning of the preprocessing 4484 // entry. 4485 while (MoreTokens()) { 4486 const unsigned I = NextToken(); 4487 SourceLocation TokLoc = GetTokenLoc(I); 4488 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 4489 case RangeBefore: 4490 AdvanceToken(); 4491 continue; 4492 case RangeAfter: 4493 case RangeOverlap: 4494 break; 4495 } 4496 break; 4497 } 4498 4499 // Look at all of the tokens within this range. 4500 while (MoreTokens()) { 4501 const unsigned I = NextToken(); 4502 SourceLocation TokLoc = GetTokenLoc(I); 4503 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 4504 case RangeBefore: 4505 assert(0 && "Infeasible"); 4506 case RangeAfter: 4507 break; 4508 case RangeOverlap: 4509 Cursors[I] = cursor; 4510 AdvanceToken(); 4511 continue; 4512 } 4513 break; 4514 } 4515 4516 // Save the preprocessing token index; restore the non-preprocessing 4517 // token index. 4518 PreprocessingTokIdx = TokIdx; 4519 TokIdx = SavedTokIdx; 4520 return CXChildVisit_Recurse; 4521 } 4522 4523 if (cursorRange.isInvalid()) 4524 return CXChildVisit_Continue; 4525 4526 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data); 4527 4528 // Adjust the annotated range based specific declarations. 4529 const enum CXCursorKind cursorK = clang_getCursorKind(cursor); 4530 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) { 4531 Decl *D = cxcursor::getCursorDecl(cursor); 4532 // Don't visit synthesized ObjC methods, since they have no syntatic 4533 // representation in the source. 4534 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 4535 if (MD->isSynthesized()) 4536 return CXChildVisit_Continue; 4537 } 4538 4539 SourceLocation StartLoc; 4540 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 4541 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) 4542 StartLoc = TI->getTypeLoc().getSourceRange().getBegin(); 4543 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) { 4544 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo()) 4545 StartLoc = TI->getTypeLoc().getSourceRange().getBegin(); 4546 } 4547 4548 if (StartLoc.isValid() && L.isValid() && 4549 SrcMgr.isBeforeInTranslationUnit(StartLoc, L)) 4550 cursorRange.setBegin(StartLoc); 4551 } 4552 4553 // If the location of the cursor occurs within a macro instantiation, record 4554 // the spelling location of the cursor in our annotation map. We can then 4555 // paper over the token labelings during a post-processing step to try and 4556 // get cursor mappings for tokens that are the *arguments* of a macro 4557 // instantiation. 4558 if (L.isMacroID()) { 4559 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding(); 4560 // Only invalidate the old annotation if it isn't part of a preprocessing 4561 // directive. Here we assume that the default construction of CXCursor 4562 // results in CXCursor.kind being an initialized value (i.e., 0). If 4563 // this isn't the case, we can fix by doing lookup + insertion. 4564 4565 CXCursor &oldC = Annotated[rawEncoding]; 4566 if (!clang_isPreprocessing(oldC.kind)) 4567 oldC = cursor; 4568 } 4569 4570 const enum CXCursorKind K = clang_getCursorKind(parent); 4571 const CXCursor updateC = 4572 (clang_isInvalid(K) || K == CXCursor_TranslationUnit) 4573 ? clang_getNullCursor() : parent; 4574 4575 while (MoreTokens()) { 4576 const unsigned I = NextToken(); 4577 SourceLocation TokLoc = GetTokenLoc(I); 4578 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 4579 case RangeBefore: 4580 Cursors[I] = updateC; 4581 AdvanceToken(); 4582 continue; 4583 case RangeAfter: 4584 case RangeOverlap: 4585 break; 4586 } 4587 break; 4588 } 4589 4590 // Visit children to get their cursor information. 4591 const unsigned BeforeChildren = NextToken(); 4592 VisitChildren(cursor); 4593 const unsigned AfterChildren = NextToken(); 4594 4595 // Adjust 'Last' to the last token within the extent of the cursor. 4596 while (MoreTokens()) { 4597 const unsigned I = NextToken(); 4598 SourceLocation TokLoc = GetTokenLoc(I); 4599 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 4600 case RangeBefore: 4601 assert(0 && "Infeasible"); 4602 case RangeAfter: 4603 break; 4604 case RangeOverlap: 4605 Cursors[I] = updateC; 4606 AdvanceToken(); 4607 continue; 4608 } 4609 break; 4610 } 4611 const unsigned Last = NextToken(); 4612 4613 // Scan the tokens that are at the beginning of the cursor, but are not 4614 // capture by the child cursors. 4615 4616 // For AST elements within macros, rely on a post-annotate pass to 4617 // to correctly annotate the tokens with cursors. Otherwise we can 4618 // get confusing results of having tokens that map to cursors that really 4619 // are expanded by an instantiation. 4620 if (L.isMacroID()) 4621 cursor = clang_getNullCursor(); 4622 4623 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) { 4624 if (!clang_isInvalid(clang_getCursorKind(Cursors[I]))) 4625 break; 4626 4627 Cursors[I] = cursor; 4628 } 4629 // Scan the tokens that are at the end of the cursor, but are not captured 4630 // but the child cursors. 4631 for (unsigned I = AfterChildren; I != Last; ++I) 4632 Cursors[I] = cursor; 4633 4634 TokIdx = Last; 4635 return CXChildVisit_Continue; 4636} 4637 4638static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor, 4639 CXCursor parent, 4640 CXClientData client_data) { 4641 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent); 4642} 4643 4644namespace { 4645 struct clang_annotateTokens_Data { 4646 CXTranslationUnit TU; 4647 ASTUnit *CXXUnit; 4648 CXToken *Tokens; 4649 unsigned NumTokens; 4650 CXCursor *Cursors; 4651 }; 4652} 4653 4654// This gets run a separate thread to avoid stack blowout. 4655static void clang_annotateTokensImpl(void *UserData) { 4656 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU; 4657 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit; 4658 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens; 4659 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens; 4660 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors; 4661 4662 // Determine the region of interest, which contains all of the tokens. 4663 SourceRange RegionOfInterest; 4664 RegionOfInterest.setBegin( 4665 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0]))); 4666 RegionOfInterest.setEnd( 4667 cxloc::translateSourceLocation(clang_getTokenLocation(TU, 4668 Tokens[NumTokens-1]))); 4669 4670 // A mapping from the source locations found when re-lexing or traversing the 4671 // region of interest to the corresponding cursors. 4672 AnnotateTokensData Annotated; 4673 4674 // Relex the tokens within the source range to look for preprocessing 4675 // directives. 4676 SourceManager &SourceMgr = CXXUnit->getSourceManager(); 4677 std::pair<FileID, unsigned> BeginLocInfo 4678 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin()); 4679 std::pair<FileID, unsigned> EndLocInfo 4680 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd()); 4681 4682 llvm::StringRef Buffer; 4683 bool Invalid = false; 4684 if (BeginLocInfo.first == EndLocInfo.first && 4685 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) && 4686 !Invalid) { 4687 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first), 4688 CXXUnit->getASTContext().getLangOptions(), 4689 Buffer.begin(), Buffer.data() + BeginLocInfo.second, 4690 Buffer.end()); 4691 Lex.SetCommentRetentionState(true); 4692 4693 // Lex tokens in raw mode until we hit the end of the range, to avoid 4694 // entering #includes or expanding macros. 4695 while (true) { 4696 Token Tok; 4697 Lex.LexFromRawLexer(Tok); 4698 4699 reprocess: 4700 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) { 4701 // We have found a preprocessing directive. Gobble it up so that we 4702 // don't see it while preprocessing these tokens later, but keep track 4703 // of all of the token locations inside this preprocessing directive so 4704 // that we can annotate them appropriately. 4705 // 4706 // FIXME: Some simple tests here could identify macro definitions and 4707 // #undefs, to provide specific cursor kinds for those. 4708 llvm::SmallVector<SourceLocation, 32> Locations; 4709 do { 4710 Locations.push_back(Tok.getLocation()); 4711 Lex.LexFromRawLexer(Tok); 4712 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof)); 4713 4714 using namespace cxcursor; 4715 CXCursor Cursor 4716 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(), 4717 Locations.back()), 4718 TU); 4719 for (unsigned I = 0, N = Locations.size(); I != N; ++I) { 4720 Annotated[Locations[I].getRawEncoding()] = Cursor; 4721 } 4722 4723 if (Tok.isAtStartOfLine()) 4724 goto reprocess; 4725 4726 continue; 4727 } 4728 4729 if (Tok.is(tok::eof)) 4730 break; 4731 } 4732 } 4733 4734 // Annotate all of the source locations in the region of interest that map to 4735 // a specific cursor. 4736 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens, 4737 TU, RegionOfInterest); 4738 4739 // FIXME: We use a ridiculous stack size here because the data-recursion 4740 // algorithm uses a large stack frame than the non-data recursive version, 4741 // and AnnotationTokensWorker currently transforms the data-recursion 4742 // algorithm back into a traditional recursion by explicitly calling 4743 // VisitChildren(). We will need to remove this explicit recursive call. 4744 W.AnnotateTokens(); 4745 4746 // If we ran into any entities that involve context-sensitive keywords, 4747 // take another pass through the tokens to mark them as such. 4748 if (W.hasContextSensitiveKeywords()) { 4749 for (unsigned I = 0; I != NumTokens; ++I) { 4750 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier) 4751 continue; 4752 4753 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) { 4754 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data); 4755 if (ObjCPropertyDecl *Property 4756 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) { 4757 if (Property->getPropertyAttributesAsWritten() != 0 && 4758 llvm::StringSwitch<bool>(II->getName()) 4759 .Case("readonly", true) 4760 .Case("assign", true) 4761 .Case("readwrite", true) 4762 .Case("retain", true) 4763 .Case("copy", true) 4764 .Case("nonatomic", true) 4765 .Case("atomic", true) 4766 .Case("getter", true) 4767 .Case("setter", true) 4768 .Default(false)) 4769 Tokens[I].int_data[0] = CXToken_Keyword; 4770 } 4771 continue; 4772 } 4773 4774 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl || 4775 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) { 4776 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data); 4777 if (llvm::StringSwitch<bool>(II->getName()) 4778 .Case("in", true) 4779 .Case("out", true) 4780 .Case("inout", true) 4781 .Case("oneway", true) 4782 .Case("bycopy", true) 4783 .Case("byref", true) 4784 .Default(false)) 4785 Tokens[I].int_data[0] = CXToken_Keyword; 4786 continue; 4787 } 4788 4789 if (Cursors[I].kind == CXCursor_CXXMethod) { 4790 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data); 4791 if (CXXMethodDecl *Method 4792 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(Cursors[I]))) { 4793 if ((Method->hasAttr<FinalAttr>() || 4794 Method->hasAttr<OverrideAttr>()) && 4795 Method->getLocation().getRawEncoding() != Tokens[I].int_data[1] && 4796 llvm::StringSwitch<bool>(II->getName()) 4797 .Case("final", true) 4798 .Case("override", true) 4799 .Default(false)) 4800 Tokens[I].int_data[0] = CXToken_Keyword; 4801 } 4802 continue; 4803 } 4804 4805 if (Cursors[I].kind == CXCursor_ClassDecl || 4806 Cursors[I].kind == CXCursor_StructDecl || 4807 Cursors[I].kind == CXCursor_ClassTemplate) { 4808 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data); 4809 if (II->getName() == "final") { 4810 // We have to be careful with 'final', since it could be the name 4811 // of a member class rather than the context-sensitive keyword. 4812 // So, check whether the cursor associated with this 4813 Decl *D = getCursorDecl(Cursors[I]); 4814 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(D)) { 4815 if ((Record->hasAttr<FinalAttr>()) && 4816 Record->getIdentifier() != II) 4817 Tokens[I].int_data[0] = CXToken_Keyword; 4818 } else if (ClassTemplateDecl *ClassTemplate 4819 = dyn_cast_or_null<ClassTemplateDecl>(D)) { 4820 CXXRecordDecl *Record = ClassTemplate->getTemplatedDecl(); 4821 if ((Record->hasAttr<FinalAttr>()) && 4822 Record->getIdentifier() != II) 4823 Tokens[I].int_data[0] = CXToken_Keyword; 4824 } 4825 } 4826 continue; 4827 } 4828 } 4829 } 4830} 4831 4832extern "C" { 4833 4834void clang_annotateTokens(CXTranslationUnit TU, 4835 CXToken *Tokens, unsigned NumTokens, 4836 CXCursor *Cursors) { 4837 4838 if (NumTokens == 0 || !Tokens || !Cursors) 4839 return; 4840 4841 // Any token we don't specifically annotate will have a NULL cursor. 4842 CXCursor C = clang_getNullCursor(); 4843 for (unsigned I = 0; I != NumTokens; ++I) 4844 Cursors[I] = C; 4845 4846 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData); 4847 if (!CXXUnit) 4848 return; 4849 4850 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 4851 4852 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors }; 4853 llvm::CrashRecoveryContext CRC; 4854 if (!RunSafely(CRC, clang_annotateTokensImpl, &data, 4855 GetSafetyThreadStackSize() * 2)) { 4856 fprintf(stderr, "libclang: crash detected while annotating tokens\n"); 4857 } 4858} 4859 4860} // end: extern "C" 4861 4862//===----------------------------------------------------------------------===// 4863// Operations for querying linkage of a cursor. 4864//===----------------------------------------------------------------------===// 4865 4866extern "C" { 4867CXLinkageKind clang_getCursorLinkage(CXCursor cursor) { 4868 if (!clang_isDeclaration(cursor.kind)) 4869 return CXLinkage_Invalid; 4870 4871 Decl *D = cxcursor::getCursorDecl(cursor); 4872 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D)) 4873 switch (ND->getLinkage()) { 4874 case NoLinkage: return CXLinkage_NoLinkage; 4875 case InternalLinkage: return CXLinkage_Internal; 4876 case UniqueExternalLinkage: return CXLinkage_UniqueExternal; 4877 case ExternalLinkage: return CXLinkage_External; 4878 }; 4879 4880 return CXLinkage_Invalid; 4881} 4882} // end: extern "C" 4883 4884//===----------------------------------------------------------------------===// 4885// Operations for querying language of a cursor. 4886//===----------------------------------------------------------------------===// 4887 4888static CXLanguageKind getDeclLanguage(const Decl *D) { 4889 switch (D->getKind()) { 4890 default: 4891 break; 4892 case Decl::ImplicitParam: 4893 case Decl::ObjCAtDefsField: 4894 case Decl::ObjCCategory: 4895 case Decl::ObjCCategoryImpl: 4896 case Decl::ObjCClass: 4897 case Decl::ObjCCompatibleAlias: 4898 case Decl::ObjCForwardProtocol: 4899 case Decl::ObjCImplementation: 4900 case Decl::ObjCInterface: 4901 case Decl::ObjCIvar: 4902 case Decl::ObjCMethod: 4903 case Decl::ObjCProperty: 4904 case Decl::ObjCPropertyImpl: 4905 case Decl::ObjCProtocol: 4906 return CXLanguage_ObjC; 4907 case Decl::CXXConstructor: 4908 case Decl::CXXConversion: 4909 case Decl::CXXDestructor: 4910 case Decl::CXXMethod: 4911 case Decl::CXXRecord: 4912 case Decl::ClassTemplate: 4913 case Decl::ClassTemplatePartialSpecialization: 4914 case Decl::ClassTemplateSpecialization: 4915 case Decl::Friend: 4916 case Decl::FriendTemplate: 4917 case Decl::FunctionTemplate: 4918 case Decl::LinkageSpec: 4919 case Decl::Namespace: 4920 case Decl::NamespaceAlias: 4921 case Decl::NonTypeTemplateParm: 4922 case Decl::StaticAssert: 4923 case Decl::TemplateTemplateParm: 4924 case Decl::TemplateTypeParm: 4925 case Decl::UnresolvedUsingTypename: 4926 case Decl::UnresolvedUsingValue: 4927 case Decl::Using: 4928 case Decl::UsingDirective: 4929 case Decl::UsingShadow: 4930 return CXLanguage_CPlusPlus; 4931 } 4932 4933 return CXLanguage_C; 4934} 4935 4936extern "C" { 4937 4938enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) { 4939 if (clang_isDeclaration(cursor.kind)) 4940 if (Decl *D = cxcursor::getCursorDecl(cursor)) { 4941 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()) 4942 return CXAvailability_Available; 4943 4944 switch (D->getAvailability()) { 4945 case AR_Available: 4946 case AR_NotYetIntroduced: 4947 return CXAvailability_Available; 4948 4949 case AR_Deprecated: 4950 return CXAvailability_Deprecated; 4951 4952 case AR_Unavailable: 4953 return CXAvailability_NotAvailable; 4954 } 4955 } 4956 4957 return CXAvailability_Available; 4958} 4959 4960CXLanguageKind clang_getCursorLanguage(CXCursor cursor) { 4961 if (clang_isDeclaration(cursor.kind)) 4962 return getDeclLanguage(cxcursor::getCursorDecl(cursor)); 4963 4964 return CXLanguage_Invalid; 4965} 4966 4967 /// \brief If the given cursor is the "templated" declaration 4968 /// descibing a class or function template, return the class or 4969 /// function template. 4970static Decl *maybeGetTemplateCursor(Decl *D) { 4971 if (!D) 4972 return 0; 4973 4974 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 4975 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate()) 4976 return FunTmpl; 4977 4978 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) 4979 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate()) 4980 return ClassTmpl; 4981 4982 return D; 4983} 4984 4985CXCursor clang_getCursorSemanticParent(CXCursor cursor) { 4986 if (clang_isDeclaration(cursor.kind)) { 4987 if (Decl *D = getCursorDecl(cursor)) { 4988 DeclContext *DC = D->getDeclContext(); 4989 if (!DC) 4990 return clang_getNullCursor(); 4991 4992 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)), 4993 getCursorTU(cursor)); 4994 } 4995 } 4996 4997 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) { 4998 if (Decl *D = getCursorDecl(cursor)) 4999 return MakeCXCursor(D, getCursorTU(cursor)); 5000 } 5001 5002 return clang_getNullCursor(); 5003} 5004 5005CXCursor clang_getCursorLexicalParent(CXCursor cursor) { 5006 if (clang_isDeclaration(cursor.kind)) { 5007 if (Decl *D = getCursorDecl(cursor)) { 5008 DeclContext *DC = D->getLexicalDeclContext(); 5009 if (!DC) 5010 return clang_getNullCursor(); 5011 5012 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)), 5013 getCursorTU(cursor)); 5014 } 5015 } 5016 5017 // FIXME: Note that we can't easily compute the lexical context of a 5018 // statement or expression, so we return nothing. 5019 return clang_getNullCursor(); 5020} 5021 5022static void CollectOverriddenMethods(DeclContext *Ctx, 5023 ObjCMethodDecl *Method, 5024 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) { 5025 if (!Ctx) 5026 return; 5027 5028 // If we have a class or category implementation, jump straight to the 5029 // interface. 5030 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx)) 5031 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods); 5032 5033 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx); 5034 if (!Container) 5035 return; 5036 5037 // Check whether we have a matching method at this level. 5038 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(), 5039 Method->isInstanceMethod())) 5040 if (Method != Overridden) { 5041 // We found an override at this level; there is no need to look 5042 // into other protocols or categories. 5043 Methods.push_back(Overridden); 5044 return; 5045 } 5046 5047 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 5048 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(), 5049 PEnd = Protocol->protocol_end(); 5050 P != PEnd; ++P) 5051 CollectOverriddenMethods(*P, Method, Methods); 5052 } 5053 5054 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) { 5055 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(), 5056 PEnd = Category->protocol_end(); 5057 P != PEnd; ++P) 5058 CollectOverriddenMethods(*P, Method, Methods); 5059 } 5060 5061 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) { 5062 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(), 5063 PEnd = Interface->protocol_end(); 5064 P != PEnd; ++P) 5065 CollectOverriddenMethods(*P, Method, Methods); 5066 5067 for (ObjCCategoryDecl *Category = Interface->getCategoryList(); 5068 Category; Category = Category->getNextClassCategory()) 5069 CollectOverriddenMethods(Category, Method, Methods); 5070 5071 // We only look into the superclass if we haven't found anything yet. 5072 if (Methods.empty()) 5073 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) 5074 return CollectOverriddenMethods(Super, Method, Methods); 5075 } 5076} 5077 5078void clang_getOverriddenCursors(CXCursor cursor, 5079 CXCursor **overridden, 5080 unsigned *num_overridden) { 5081 if (overridden) 5082 *overridden = 0; 5083 if (num_overridden) 5084 *num_overridden = 0; 5085 if (!overridden || !num_overridden) 5086 return; 5087 5088 if (!clang_isDeclaration(cursor.kind)) 5089 return; 5090 5091 Decl *D = getCursorDecl(cursor); 5092 if (!D) 5093 return; 5094 5095 // Handle C++ member functions. 5096 CXTranslationUnit TU = getCursorTU(cursor); 5097 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) { 5098 *num_overridden = CXXMethod->size_overridden_methods(); 5099 if (!*num_overridden) 5100 return; 5101 5102 *overridden = new CXCursor [*num_overridden]; 5103 unsigned I = 0; 5104 for (CXXMethodDecl::method_iterator 5105 M = CXXMethod->begin_overridden_methods(), 5106 MEnd = CXXMethod->end_overridden_methods(); 5107 M != MEnd; (void)++M, ++I) 5108 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU); 5109 return; 5110 } 5111 5112 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D); 5113 if (!Method) 5114 return; 5115 5116 // Handle Objective-C methods. 5117 llvm::SmallVector<ObjCMethodDecl *, 4> Methods; 5118 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods); 5119 5120 if (Methods.empty()) 5121 return; 5122 5123 *num_overridden = Methods.size(); 5124 *overridden = new CXCursor [Methods.size()]; 5125 for (unsigned I = 0, N = Methods.size(); I != N; ++I) 5126 (*overridden)[I] = MakeCXCursor(Methods[I], TU); 5127} 5128 5129void clang_disposeOverriddenCursors(CXCursor *overridden) { 5130 delete [] overridden; 5131} 5132 5133CXFile clang_getIncludedFile(CXCursor cursor) { 5134 if (cursor.kind != CXCursor_InclusionDirective) 5135 return 0; 5136 5137 InclusionDirective *ID = getCursorInclusionDirective(cursor); 5138 return (void *)ID->getFile(); 5139} 5140 5141} // end: extern "C" 5142 5143 5144//===----------------------------------------------------------------------===// 5145// C++ AST instrospection. 5146//===----------------------------------------------------------------------===// 5147 5148extern "C" { 5149unsigned clang_CXXMethod_isStatic(CXCursor C) { 5150 if (!clang_isDeclaration(C.kind)) 5151 return 0; 5152 5153 CXXMethodDecl *Method = 0; 5154 Decl *D = cxcursor::getCursorDecl(C); 5155 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D)) 5156 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl()); 5157 else 5158 Method = dyn_cast_or_null<CXXMethodDecl>(D); 5159 return (Method && Method->isStatic()) ? 1 : 0; 5160} 5161 5162} // end: extern "C" 5163 5164//===----------------------------------------------------------------------===// 5165// Attribute introspection. 5166//===----------------------------------------------------------------------===// 5167 5168extern "C" { 5169CXType clang_getIBOutletCollectionType(CXCursor C) { 5170 if (C.kind != CXCursor_IBOutletCollectionAttr) 5171 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C)); 5172 5173 IBOutletCollectionAttr *A = 5174 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C)); 5175 5176 return cxtype::MakeCXType(A->getInterFace(), cxcursor::getCursorTU(C)); 5177} 5178} // end: extern "C" 5179 5180//===----------------------------------------------------------------------===// 5181// Inspecting memory usage. 5182//===----------------------------------------------------------------------===// 5183 5184typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries; 5185 5186static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries, 5187 enum CXTUResourceUsageKind k, 5188 double amount) { 5189 CXTUResourceUsageEntry entry = { k, amount }; 5190 entries.push_back(entry); 5191} 5192 5193extern "C" { 5194 5195const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) { 5196 const char *str = ""; 5197 switch (kind) { 5198 case CXTUResourceUsage_AST: 5199 str = "ASTContext: expressions, declarations, and types"; 5200 break; 5201 case CXTUResourceUsage_Identifiers: 5202 str = "ASTContext: identifiers"; 5203 break; 5204 case CXTUResourceUsage_Selectors: 5205 str = "ASTContext: selectors"; 5206 break; 5207 case CXTUResourceUsage_GlobalCompletionResults: 5208 str = "Code completion: cached global results"; 5209 break; 5210 } 5211 return str; 5212} 5213 5214CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) { 5215 if (!TU) { 5216 CXTUResourceUsage usage = { (void*) 0, 0, 0 }; 5217 return usage; 5218 } 5219 5220 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData); 5221 llvm::OwningPtr<MemUsageEntries> entries(new MemUsageEntries()); 5222 ASTContext &astContext = astUnit->getASTContext(); 5223 5224 // How much memory is used by AST nodes and types? 5225 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST, 5226 (unsigned long) astContext.getTotalAllocatedMemory()); 5227 5228 // How much memory is used by identifiers? 5229 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers, 5230 (unsigned long) astContext.Idents.getAllocator().getTotalMemory()); 5231 5232 // How much memory is used for selectors? 5233 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors, 5234 (unsigned long) astContext.Selectors.getTotalMemory()); 5235 5236 // How much memory is used for caching global code completion results? 5237 unsigned long completionBytes = 0; 5238 if (GlobalCodeCompletionAllocator *completionAllocator = 5239 astUnit->getCachedCompletionAllocator().getPtr()) { 5240 completionBytes = completionAllocator-> getTotalMemory(); 5241 } 5242 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_GlobalCompletionResults, 5243 completionBytes); 5244 5245 5246 CXTUResourceUsage usage = { (void*) entries.get(), 5247 (unsigned) entries->size(), 5248 entries->size() ? &(*entries)[0] : 0 }; 5249 entries.take(); 5250 return usage; 5251} 5252 5253void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) { 5254 if (usage.data) 5255 delete (MemUsageEntries*) usage.data; 5256} 5257 5258} // end extern "C" 5259 5260//===----------------------------------------------------------------------===// 5261// Misc. utility functions. 5262//===----------------------------------------------------------------------===// 5263 5264/// Default to using an 8 MB stack size on "safety" threads. 5265static unsigned SafetyStackThreadSize = 8 << 20; 5266 5267namespace clang { 5268 5269bool RunSafely(llvm::CrashRecoveryContext &CRC, 5270 void (*Fn)(void*), void *UserData, 5271 unsigned Size) { 5272 if (!Size) 5273 Size = GetSafetyThreadStackSize(); 5274 if (Size) 5275 return CRC.RunSafelyOnThread(Fn, UserData, Size); 5276 return CRC.RunSafely(Fn, UserData); 5277} 5278 5279unsigned GetSafetyThreadStackSize() { 5280 return SafetyStackThreadSize; 5281} 5282 5283void SetSafetyThreadStackSize(unsigned Value) { 5284 SafetyStackThreadSize = Value; 5285} 5286 5287} 5288 5289extern "C" { 5290 5291CXString clang_getClangVersion() { 5292 return createCXString(getClangFullVersion()); 5293} 5294 5295} // end: extern "C" 5296 5297