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