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