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