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