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