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