CIndex.cpp revision 25d63629cc37a9737c6d8d5c6aa08b356649212f
1//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements the main API hooks in the Clang-C Source Indexing 11// library. 12// 13//===----------------------------------------------------------------------===// 14 15#include "CIndexer.h" 16#include "CXCursor.h" 17#include "CXType.h" 18#include "CXSourceLocation.h" 19#include "CIndexDiagnostic.h" 20 21#include "clang/Basic/Version.h" 22 23#include "clang/AST/DeclVisitor.h" 24#include "clang/AST/StmtVisitor.h" 25#include "clang/AST/TypeLocVisitor.h" 26#include "clang/Basic/Diagnostic.h" 27#include "clang/Frontend/ASTUnit.h" 28#include "clang/Frontend/CompilerInstance.h" 29#include "clang/Frontend/FrontendDiagnostic.h" 30#include "clang/Lex/Lexer.h" 31#include "clang/Lex/PreprocessingRecord.h" 32#include "clang/Lex/Preprocessor.h" 33#include "llvm/Support/CrashRecoveryContext.h" 34#include "llvm/Support/MemoryBuffer.h" 35#include "llvm/Support/Timer.h" 36#include "llvm/System/Program.h" 37#include "llvm/System/Signals.h" 38 39// Needed to define L_TMPNAM on some systems. 40#include <cstdio> 41 42using namespace clang; 43using namespace clang::cxcursor; 44using namespace clang::cxstring; 45 46//===----------------------------------------------------------------------===// 47// Crash Reporting. 48//===----------------------------------------------------------------------===// 49 50#ifdef USE_CRASHTRACER 51#include "clang/Analysis/Support/SaveAndRestore.h" 52// Integrate with crash reporter. 53static const char *__crashreporter_info__ = 0; 54asm(".desc ___crashreporter_info__, 0x10"); 55#define NUM_CRASH_STRINGS 32 56static unsigned crashtracer_counter = 0; 57static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 }; 58static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 }; 59static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 }; 60 61static unsigned SetCrashTracerInfo(const char *str, 62 llvm::SmallString<1024> &AggStr) { 63 64 unsigned slot = 0; 65 while (crashtracer_strings[slot]) { 66 if (++slot == NUM_CRASH_STRINGS) 67 slot = 0; 68 } 69 crashtracer_strings[slot] = str; 70 crashtracer_counter_id[slot] = ++crashtracer_counter; 71 72 // We need to create an aggregate string because multiple threads 73 // may be in this method at one time. The crash reporter string 74 // will attempt to overapproximate the set of in-flight invocations 75 // of this function. Race conditions can still cause this goal 76 // to not be achieved. 77 { 78 llvm::raw_svector_ostream Out(AggStr); 79 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i) 80 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n'; 81 } 82 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str(); 83 return slot; 84} 85 86static void ResetCrashTracerInfo(unsigned slot) { 87 unsigned max_slot = 0; 88 unsigned max_value = 0; 89 90 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0; 91 92 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i) 93 if (agg_crashtracer_strings[i] && 94 crashtracer_counter_id[i] > max_value) { 95 max_slot = i; 96 max_value = crashtracer_counter_id[i]; 97 } 98 99 __crashreporter_info__ = agg_crashtracer_strings[max_slot]; 100} 101 102namespace { 103class ArgsCrashTracerInfo { 104 llvm::SmallString<1024> CrashString; 105 llvm::SmallString<1024> AggregateString; 106 unsigned crashtracerSlot; 107public: 108 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args) 109 : crashtracerSlot(0) 110 { 111 { 112 llvm::raw_svector_ostream Out(CrashString); 113 Out << "ClangCIndex [" << getClangFullVersion() << "]" 114 << "[createTranslationUnitFromSourceFile]: clang"; 115 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(), 116 E=Args.end(); I!=E; ++I) 117 Out << ' ' << *I; 118 } 119 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(), 120 AggregateString); 121 } 122 123 ~ArgsCrashTracerInfo() { 124 ResetCrashTracerInfo(crashtracerSlot); 125 } 126}; 127} 128#endif 129 130/// \brief The result of comparing two source ranges. 131enum RangeComparisonResult { 132 /// \brief Either the ranges overlap or one of the ranges is invalid. 133 RangeOverlap, 134 135 /// \brief The first range ends before the second range starts. 136 RangeBefore, 137 138 /// \brief The first range starts after the second range ends. 139 RangeAfter 140}; 141 142/// \brief Compare two source ranges to determine their relative position in 143/// the translation unit. 144static RangeComparisonResult RangeCompare(SourceManager &SM, 145 SourceRange R1, 146 SourceRange R2) { 147 assert(R1.isValid() && "First range is invalid?"); 148 assert(R2.isValid() && "Second range is invalid?"); 149 if (R1.getEnd() != R2.getBegin() && 150 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin())) 151 return RangeBefore; 152 if (R2.getEnd() != R1.getBegin() && 153 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin())) 154 return RangeAfter; 155 return RangeOverlap; 156} 157 158/// \brief Determine if a source location falls within, before, or after a 159/// a given source range. 160static RangeComparisonResult LocationCompare(SourceManager &SM, 161 SourceLocation L, SourceRange R) { 162 assert(R.isValid() && "First range is invalid?"); 163 assert(L.isValid() && "Second range is invalid?"); 164 if (L == R.getBegin() || L == R.getEnd()) 165 return RangeOverlap; 166 if (SM.isBeforeInTranslationUnit(L, R.getBegin())) 167 return RangeBefore; 168 if (SM.isBeforeInTranslationUnit(R.getEnd(), L)) 169 return RangeAfter; 170 return RangeOverlap; 171} 172 173/// \brief Translate a Clang source range into a CIndex source range. 174/// 175/// Clang internally represents ranges where the end location points to the 176/// start of the token at the end. However, for external clients it is more 177/// useful to have a CXSourceRange be a proper half-open interval. This routine 178/// does the appropriate translation. 179CXSourceRange cxloc::translateSourceRange(const SourceManager &SM, 180 const LangOptions &LangOpts, 181 const CharSourceRange &R) { 182 // We want the last character in this location, so we will adjust the 183 // location accordingly. 184 // FIXME: How do do this with a macro instantiation location? 185 SourceLocation EndLoc = R.getEnd(); 186 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) { 187 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts); 188 EndLoc = EndLoc.getFileLocWithOffset(Length); 189 } 190 191 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts }, 192 R.getBegin().getRawEncoding(), 193 EndLoc.getRawEncoding() }; 194 return Result; 195} 196 197//===----------------------------------------------------------------------===// 198// Cursor visitor. 199//===----------------------------------------------------------------------===// 200 201namespace { 202 203// Cursor visitor. 204class CursorVisitor : public DeclVisitor<CursorVisitor, bool>, 205 public TypeLocVisitor<CursorVisitor, bool>, 206 public StmtVisitor<CursorVisitor, bool> 207{ 208 /// \brief The translation unit we are traversing. 209 ASTUnit *TU; 210 211 /// \brief The parent cursor whose children we are traversing. 212 CXCursor Parent; 213 214 /// \brief The declaration that serves at the parent of any statement or 215 /// expression nodes. 216 Decl *StmtParent; 217 218 /// \brief The visitor function. 219 CXCursorVisitor Visitor; 220 221 /// \brief The opaque client data, to be passed along to the visitor. 222 CXClientData ClientData; 223 224 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on 225 // to the visitor. Declarations with a PCH level greater than this value will 226 // be suppressed. 227 unsigned MaxPCHLevel; 228 229 /// \brief When valid, a source range to which the cursor should restrict 230 /// its search. 231 SourceRange RegionOfInterest; 232 233 using DeclVisitor<CursorVisitor, bool>::Visit; 234 using TypeLocVisitor<CursorVisitor, bool>::Visit; 235 using StmtVisitor<CursorVisitor, bool>::Visit; 236 237 /// \brief Determine whether this particular source range comes before, comes 238 /// after, or overlaps the region of interest. 239 /// 240 /// \param R a half-open source range retrieved from the abstract syntax tree. 241 RangeComparisonResult CompareRegionOfInterest(SourceRange R); 242 243 class SetParentRAII { 244 CXCursor &Parent; 245 Decl *&StmtParent; 246 CXCursor OldParent; 247 248 public: 249 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent) 250 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent) 251 { 252 Parent = NewParent; 253 if (clang_isDeclaration(Parent.kind)) 254 StmtParent = getCursorDecl(Parent); 255 } 256 257 ~SetParentRAII() { 258 Parent = OldParent; 259 if (clang_isDeclaration(Parent.kind)) 260 StmtParent = getCursorDecl(Parent); 261 } 262 }; 263 264public: 265 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData, 266 unsigned MaxPCHLevel, 267 SourceRange RegionOfInterest = SourceRange()) 268 : TU(TU), Visitor(Visitor), ClientData(ClientData), 269 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest) 270 { 271 Parent.kind = CXCursor_NoDeclFound; 272 Parent.data[0] = 0; 273 Parent.data[1] = 0; 274 Parent.data[2] = 0; 275 StmtParent = 0; 276 } 277 278 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false); 279 280 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator> 281 getPreprocessedEntities(); 282 283 bool VisitChildren(CXCursor Parent); 284 285 // Declaration visitors 286 bool VisitAttributes(Decl *D); 287 bool VisitBlockDecl(BlockDecl *B); 288 bool VisitCXXRecordDecl(CXXRecordDecl *D); 289 bool VisitDeclContext(DeclContext *DC); 290 bool VisitTranslationUnitDecl(TranslationUnitDecl *D); 291 bool VisitTypedefDecl(TypedefDecl *D); 292 bool VisitTagDecl(TagDecl *D); 293 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D); 294 bool VisitClassTemplatePartialSpecializationDecl( 295 ClassTemplatePartialSpecializationDecl *D); 296 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D); 297 bool VisitEnumConstantDecl(EnumConstantDecl *D); 298 bool VisitDeclaratorDecl(DeclaratorDecl *DD); 299 bool VisitFunctionDecl(FunctionDecl *ND); 300 bool VisitFieldDecl(FieldDecl *D); 301 bool VisitVarDecl(VarDecl *); 302 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D); 303 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D); 304 bool VisitClassTemplateDecl(ClassTemplateDecl *D); 305 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D); 306 bool VisitObjCMethodDecl(ObjCMethodDecl *ND); 307 bool VisitObjCContainerDecl(ObjCContainerDecl *D); 308 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND); 309 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID); 310 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD); 311 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D); 312 bool VisitObjCImplDecl(ObjCImplDecl *D); 313 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D); 314 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D); 315 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations, 316 // etc. 317 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations. 318 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D); 319 bool VisitObjCClassDecl(ObjCClassDecl *D); 320 bool VisitLinkageSpecDecl(LinkageSpecDecl *D); 321 bool VisitNamespaceDecl(NamespaceDecl *D); 322 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D); 323 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D); 324 bool VisitUsingDecl(UsingDecl *D); 325 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D); 326 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D); 327 328 // Name visitor 329 bool VisitDeclarationNameInfo(DeclarationNameInfo Name); 330 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range); 331 332 // Template visitors 333 bool VisitTemplateParameters(const TemplateParameterList *Params); 334 bool VisitTemplateName(TemplateName Name, SourceLocation Loc); 335 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL); 336 337 // Type visitors 338 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL); 339 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL); 340 bool VisitTypedefTypeLoc(TypedefTypeLoc TL); 341 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL); 342 bool VisitTagTypeLoc(TagTypeLoc TL); 343 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL); 344 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL); 345 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL); 346 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL); 347 bool VisitPointerTypeLoc(PointerTypeLoc TL); 348 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL); 349 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL); 350 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL); 351 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL); 352 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false); 353 bool VisitArrayTypeLoc(ArrayTypeLoc TL); 354 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL); 355 // FIXME: Implement visitors here when the unimplemented TypeLocs get 356 // implemented 357 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL); 358 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL); 359 360 // Statement visitors 361 bool VisitStmt(Stmt *S); 362 bool VisitDeclStmt(DeclStmt *S); 363 // FIXME: LabelStmt label? 364 bool VisitIfStmt(IfStmt *S); 365 bool VisitSwitchStmt(SwitchStmt *S); 366 bool VisitCaseStmt(CaseStmt *S); 367 bool VisitWhileStmt(WhileStmt *S); 368 bool VisitForStmt(ForStmt *S); 369// bool VisitSwitchCase(SwitchCase *S); 370 371 // Expression visitors 372 bool VisitDeclRefExpr(DeclRefExpr *E); 373 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E); 374 bool VisitBlockExpr(BlockExpr *B); 375 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E); 376 bool VisitExplicitCastExpr(ExplicitCastExpr *E); 377 bool VisitObjCMessageExpr(ObjCMessageExpr *E); 378 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E); 379 bool VisitOffsetOfExpr(OffsetOfExpr *E); 380 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E); 381 bool VisitMemberExpr(MemberExpr *E); 382 // FIXME: AddrLabelExpr (once we have cursors for labels) 383 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E); 384 bool VisitVAArgExpr(VAArgExpr *E); 385 // FIXME: InitListExpr (for the designators) 386 // FIXME: DesignatedInitExpr 387 bool VisitCXXTypeidExpr(CXXTypeidExpr *E); 388 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { return false; } 389 // FIXME: CXXTemporaryObjectExpr has poor source-location information. 390 // FIXME: CXXScalarValueInitExpr has poor source-location information. 391 // FIXME: CXXNewExpr has poor source-location information 392 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E); 393 // FIXME: UnaryTypeTraitExpr has poor source-location information. 394 bool VisitOverloadExpr(OverloadExpr *E); 395 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E); 396 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *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 (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::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) { 1592 // Visit base expression. 1593 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU))) 1594 return true; 1595 1596 // Visit the nested-name-specifier. 1597 if (NestedNameSpecifier *Qualifier = E->getQualifier()) 1598 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange())) 1599 return true; 1600 1601 // Visit the scope type that looks disturbingly like the nested-name-specifier 1602 // but isn't. 1603 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo()) 1604 if (Visit(TSInfo->getTypeLoc())) 1605 return true; 1606 1607 // Visit the name of the type being destroyed. 1608 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo()) 1609 if (Visit(TSInfo->getTypeLoc())) 1610 return true; 1611 1612 return false; 1613} 1614 1615bool CursorVisitor::VisitOverloadExpr(OverloadExpr *E) { 1616 // Visit the nested-name-specifier. 1617 if (NestedNameSpecifier *Qualifier = E->getQualifier()) 1618 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange())) 1619 return true; 1620 1621 // Visit the declaration name. 1622 if (VisitDeclarationNameInfo(E->getNameInfo())) 1623 return true; 1624 1625 // Visit the explicitly-specified template arguments. 1626 if (const ExplicitTemplateArgumentList *ArgList 1627 = E->getOptionalExplicitTemplateArgs()) { 1628 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(), 1629 *ArgEnd = Arg + ArgList->NumTemplateArgs; 1630 Arg != ArgEnd; ++Arg) { 1631 if (VisitTemplateArgumentLoc(*Arg)) 1632 return true; 1633 } 1634 } 1635 1636 // FIXME: We don't have a way to visit all of the declarations referenced 1637 // here. 1638 return false; 1639} 1640 1641bool CursorVisitor::VisitDependentScopeDeclRefExpr( 1642 DependentScopeDeclRefExpr *E) { 1643 // Visit the nested-name-specifier. 1644 if (NestedNameSpecifier *Qualifier = E->getQualifier()) 1645 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange())) 1646 return true; 1647 1648 // Visit the declaration name. 1649 if (VisitDeclarationNameInfo(E->getNameInfo())) 1650 return true; 1651 1652 // Visit the explicitly-specified template arguments. 1653 if (const ExplicitTemplateArgumentList *ArgList 1654 = E->getOptionalExplicitTemplateArgs()) { 1655 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(), 1656 *ArgEnd = Arg + ArgList->NumTemplateArgs; 1657 Arg != ArgEnd; ++Arg) { 1658 if (VisitTemplateArgumentLoc(*Arg)) 1659 return true; 1660 } 1661 } 1662 1663 return false; 1664} 1665 1666bool CursorVisitor::VisitCXXDependentScopeMemberExpr( 1667 CXXDependentScopeMemberExpr *E) { 1668 // Visit the base expression, if there is one. 1669 if (!E->isImplicitAccess() && 1670 Visit(MakeCXCursor(E->getBase(), StmtParent, TU))) 1671 return true; 1672 1673 // Visit the nested-name-specifier. 1674 if (NestedNameSpecifier *Qualifier = E->getQualifier()) 1675 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange())) 1676 return true; 1677 1678 // Visit the declaration name. 1679 if (VisitDeclarationNameInfo(E->getMemberNameInfo())) 1680 return true; 1681 1682 // Visit the explicitly-specified template arguments. 1683 if (const ExplicitTemplateArgumentList *ArgList 1684 = E->getOptionalExplicitTemplateArgs()) { 1685 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(), 1686 *ArgEnd = Arg + ArgList->NumTemplateArgs; 1687 Arg != ArgEnd; ++Arg) { 1688 if (VisitTemplateArgumentLoc(*Arg)) 1689 return true; 1690 } 1691 } 1692 1693 return false; 1694} 1695 1696 1697bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) { 1698 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo()) 1699 if (Visit(TSInfo->getTypeLoc())) 1700 return true; 1701 1702 return VisitExpr(E); 1703} 1704 1705bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) { 1706 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc()); 1707} 1708 1709 1710bool CursorVisitor::VisitAttributes(Decl *D) { 1711 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end(); 1712 i != e; ++i) 1713 if (Visit(MakeCXCursor(*i, D, TU))) 1714 return true; 1715 1716 return false; 1717} 1718 1719extern "C" { 1720CXIndex clang_createIndex(int excludeDeclarationsFromPCH, 1721 int displayDiagnostics) { 1722 // We use crash recovery to make some of our APIs more reliable, implicitly 1723 // enable it. 1724 llvm::CrashRecoveryContext::Enable(); 1725 1726 CIndexer *CIdxr = new CIndexer(); 1727 if (excludeDeclarationsFromPCH) 1728 CIdxr->setOnlyLocalDecls(); 1729 if (displayDiagnostics) 1730 CIdxr->setDisplayDiagnostics(); 1731 return CIdxr; 1732} 1733 1734void clang_disposeIndex(CXIndex CIdx) { 1735 if (CIdx) 1736 delete static_cast<CIndexer *>(CIdx); 1737 if (getenv("LIBCLANG_TIMING")) 1738 llvm::TimerGroup::printAll(llvm::errs()); 1739} 1740 1741void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) { 1742 if (CIdx) { 1743 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx); 1744 CXXIdx->setUseExternalASTGeneration(value); 1745 } 1746} 1747 1748CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx, 1749 const char *ast_filename) { 1750 if (!CIdx) 1751 return 0; 1752 1753 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx); 1754 1755 llvm::IntrusiveRefCntPtr<Diagnostic> Diags; 1756 return ASTUnit::LoadFromASTFile(ast_filename, Diags, 1757 CXXIdx->getOnlyLocalDecls(), 1758 0, 0, true); 1759} 1760 1761unsigned clang_defaultEditingTranslationUnitOptions() { 1762 return CXTranslationUnit_PrecompiledPreamble; 1763} 1764 1765CXTranslationUnit 1766clang_createTranslationUnitFromSourceFile(CXIndex CIdx, 1767 const char *source_filename, 1768 int num_command_line_args, 1769 const char * const *command_line_args, 1770 unsigned num_unsaved_files, 1771 struct CXUnsavedFile *unsaved_files) { 1772 return clang_parseTranslationUnit(CIdx, source_filename, 1773 command_line_args, num_command_line_args, 1774 unsaved_files, num_unsaved_files, 1775 CXTranslationUnit_DetailedPreprocessingRecord); 1776} 1777 1778struct ParseTranslationUnitInfo { 1779 CXIndex CIdx; 1780 const char *source_filename; 1781 const char *const *command_line_args; 1782 int num_command_line_args; 1783 struct CXUnsavedFile *unsaved_files; 1784 unsigned num_unsaved_files; 1785 unsigned options; 1786 CXTranslationUnit result; 1787}; 1788static void clang_parseTranslationUnit_Impl(void *UserData) { 1789 ParseTranslationUnitInfo *PTUI = 1790 static_cast<ParseTranslationUnitInfo*>(UserData); 1791 CXIndex CIdx = PTUI->CIdx; 1792 const char *source_filename = PTUI->source_filename; 1793 const char * const *command_line_args = PTUI->command_line_args; 1794 int num_command_line_args = PTUI->num_command_line_args; 1795 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files; 1796 unsigned num_unsaved_files = PTUI->num_unsaved_files; 1797 unsigned options = PTUI->options; 1798 PTUI->result = 0; 1799 1800 if (!CIdx) 1801 return; 1802 1803 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx); 1804 1805 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble; 1806 bool CompleteTranslationUnit 1807 = ((options & CXTranslationUnit_Incomplete) == 0); 1808 bool CacheCodeCompetionResults 1809 = options & CXTranslationUnit_CacheCompletionResults; 1810 1811 // Configure the diagnostics. 1812 DiagnosticOptions DiagOpts; 1813 llvm::IntrusiveRefCntPtr<Diagnostic> Diags; 1814 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0); 1815 1816 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles; 1817 for (unsigned I = 0; I != num_unsaved_files; ++I) { 1818 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length); 1819 const llvm::MemoryBuffer *Buffer 1820 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename); 1821 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename, 1822 Buffer)); 1823 } 1824 1825 if (!CXXIdx->getUseExternalASTGeneration()) { 1826 llvm::SmallVector<const char *, 16> Args; 1827 1828 // The 'source_filename' argument is optional. If the caller does not 1829 // specify it then it is assumed that the source file is specified 1830 // in the actual argument list. 1831 if (source_filename) 1832 Args.push_back(source_filename); 1833 1834 // Since the Clang C library is primarily used by batch tools dealing with 1835 // (often very broken) source code, where spell-checking can have a 1836 // significant negative impact on performance (particularly when 1837 // precompiled headers are involved), we disable it by default. 1838 // Note that we place this argument early in the list, so that it can be 1839 // overridden by the caller with "-fspell-checking". 1840 Args.push_back("-fno-spell-checking"); 1841 1842 Args.insert(Args.end(), command_line_args, 1843 command_line_args + num_command_line_args); 1844 1845 // Do we need the detailed preprocessing record? 1846 if (options & CXTranslationUnit_DetailedPreprocessingRecord) { 1847 Args.push_back("-Xclang"); 1848 Args.push_back("-detailed-preprocessing-record"); 1849 } 1850 1851 unsigned NumErrors = Diags->getNumErrors(); 1852 1853#ifdef USE_CRASHTRACER 1854 ArgsCrashTracerInfo ACTI(Args); 1855#endif 1856 1857 llvm::OwningPtr<ASTUnit> Unit( 1858 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(), 1859 Diags, 1860 CXXIdx->getClangResourcesPath(), 1861 CXXIdx->getOnlyLocalDecls(), 1862 RemappedFiles.data(), 1863 RemappedFiles.size(), 1864 /*CaptureDiagnostics=*/true, 1865 PrecompilePreamble, 1866 CompleteTranslationUnit, 1867 CacheCodeCompetionResults)); 1868 1869 if (NumErrors != Diags->getNumErrors()) { 1870 // Make sure to check that 'Unit' is non-NULL. 1871 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) { 1872 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(), 1873 DEnd = Unit->stored_diag_end(); 1874 D != DEnd; ++D) { 1875 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions()); 1876 CXString Msg = clang_formatDiagnostic(&Diag, 1877 clang_defaultDiagnosticDisplayOptions()); 1878 fprintf(stderr, "%s\n", clang_getCString(Msg)); 1879 clang_disposeString(Msg); 1880 } 1881#ifdef LLVM_ON_WIN32 1882 // On Windows, force a flush, since there may be multiple copies of 1883 // stderr and stdout in the file system, all with different buffers 1884 // but writing to the same device. 1885 fflush(stderr); 1886#endif 1887 } 1888 } 1889 1890 PTUI->result = Unit.take(); 1891 return; 1892 } 1893 1894 // Build up the arguments for invoking 'clang'. 1895 std::vector<const char *> argv; 1896 1897 // First add the complete path to the 'clang' executable. 1898 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath(); 1899 argv.push_back(ClangPath.c_str()); 1900 1901 // Add the '-emit-ast' option as our execution mode for 'clang'. 1902 argv.push_back("-emit-ast"); 1903 1904 // The 'source_filename' argument is optional. If the caller does not 1905 // specify it then it is assumed that the source file is specified 1906 // in the actual argument list. 1907 if (source_filename) 1908 argv.push_back(source_filename); 1909 1910 // Generate a temporary name for the AST file. 1911 argv.push_back("-o"); 1912 char astTmpFile[L_tmpnam]; 1913 argv.push_back(tmpnam(astTmpFile)); 1914 1915 // Since the Clang C library is primarily used by batch tools dealing with 1916 // (often very broken) source code, where spell-checking can have a 1917 // significant negative impact on performance (particularly when 1918 // precompiled headers are involved), we disable it by default. 1919 // Note that we place this argument early in the list, so that it can be 1920 // overridden by the caller with "-fspell-checking". 1921 argv.push_back("-fno-spell-checking"); 1922 1923 // Remap any unsaved files to temporary files. 1924 std::vector<llvm::sys::Path> TemporaryFiles; 1925 std::vector<std::string> RemapArgs; 1926 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles)) 1927 return; 1928 1929 // The pointers into the elements of RemapArgs are stable because we 1930 // won't be adding anything to RemapArgs after this point. 1931 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i) 1932 argv.push_back(RemapArgs[i].c_str()); 1933 1934 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'. 1935 for (int i = 0; i < num_command_line_args; ++i) 1936 if (const char *arg = command_line_args[i]) { 1937 if (strcmp(arg, "-o") == 0) { 1938 ++i; // Also skip the matching argument. 1939 continue; 1940 } 1941 if (strcmp(arg, "-emit-ast") == 0 || 1942 strcmp(arg, "-c") == 0 || 1943 strcmp(arg, "-fsyntax-only") == 0) { 1944 continue; 1945 } 1946 1947 // Keep the argument. 1948 argv.push_back(arg); 1949 } 1950 1951 // Generate a temporary name for the diagnostics file. 1952 char tmpFileResults[L_tmpnam]; 1953 char *tmpResultsFileName = tmpnam(tmpFileResults); 1954 llvm::sys::Path DiagnosticsFile(tmpResultsFileName); 1955 TemporaryFiles.push_back(DiagnosticsFile); 1956 argv.push_back("-fdiagnostics-binary"); 1957 1958 // Do we need the detailed preprocessing record? 1959 if (options & CXTranslationUnit_DetailedPreprocessingRecord) { 1960 argv.push_back("-Xclang"); 1961 argv.push_back("-detailed-preprocessing-record"); 1962 } 1963 1964 // Add the null terminator. 1965 argv.push_back(NULL); 1966 1967 // Invoke 'clang'. 1968 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null 1969 // on Unix or NUL (Windows). 1970 std::string ErrMsg; 1971 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile, 1972 NULL }; 1973 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL, 1974 /* redirects */ &Redirects[0], 1975 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg); 1976 1977 if (!ErrMsg.empty()) { 1978 std::string AllArgs; 1979 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end(); 1980 I != E; ++I) { 1981 AllArgs += ' '; 1982 if (*I) 1983 AllArgs += *I; 1984 } 1985 1986 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg; 1987 } 1988 1989 ASTUnit *ATU = ASTUnit::LoadFromASTFile(astTmpFile, Diags, 1990 CXXIdx->getOnlyLocalDecls(), 1991 RemappedFiles.data(), 1992 RemappedFiles.size(), 1993 /*CaptureDiagnostics=*/true); 1994 if (ATU) { 1995 LoadSerializedDiagnostics(DiagnosticsFile, 1996 num_unsaved_files, unsaved_files, 1997 ATU->getFileManager(), 1998 ATU->getSourceManager(), 1999 ATU->getStoredDiagnostics()); 2000 } else if (CXXIdx->getDisplayDiagnostics()) { 2001 // We failed to load the ASTUnit, but we can still deserialize the 2002 // diagnostics and emit them. 2003 FileManager FileMgr; 2004 Diagnostic Diag; 2005 SourceManager SourceMgr(Diag); 2006 // FIXME: Faked LangOpts! 2007 LangOptions LangOpts; 2008 llvm::SmallVector<StoredDiagnostic, 4> Diags; 2009 LoadSerializedDiagnostics(DiagnosticsFile, 2010 num_unsaved_files, unsaved_files, 2011 FileMgr, SourceMgr, Diags); 2012 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(), 2013 DEnd = Diags.end(); 2014 D != DEnd; ++D) { 2015 CXStoredDiagnostic Diag(*D, LangOpts); 2016 CXString Msg = clang_formatDiagnostic(&Diag, 2017 clang_defaultDiagnosticDisplayOptions()); 2018 fprintf(stderr, "%s\n", clang_getCString(Msg)); 2019 clang_disposeString(Msg); 2020 } 2021 2022#ifdef LLVM_ON_WIN32 2023 // On Windows, force a flush, since there may be multiple copies of 2024 // stderr and stdout in the file system, all with different buffers 2025 // but writing to the same device. 2026 fflush(stderr); 2027#endif 2028 } 2029 2030 if (ATU) { 2031 // Make the translation unit responsible for destroying all temporary files. 2032 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i) 2033 ATU->addTemporaryFile(TemporaryFiles[i]); 2034 ATU->addTemporaryFile(llvm::sys::Path(ATU->getASTFileName())); 2035 } else { 2036 // Destroy all of the temporary files now; they can't be referenced any 2037 // longer. 2038 llvm::sys::Path(astTmpFile).eraseFromDisk(); 2039 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i) 2040 TemporaryFiles[i].eraseFromDisk(); 2041 } 2042 2043 PTUI->result = ATU; 2044} 2045CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx, 2046 const char *source_filename, 2047 const char * const *command_line_args, 2048 int num_command_line_args, 2049 struct CXUnsavedFile *unsaved_files, 2050 unsigned num_unsaved_files, 2051 unsigned options) { 2052 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args, 2053 num_command_line_args, unsaved_files, num_unsaved_files, 2054 options, 0 }; 2055 llvm::CrashRecoveryContext CRC; 2056 2057 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) { 2058 fprintf(stderr, "libclang: crash detected during parsing: {\n"); 2059 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename); 2060 fprintf(stderr, " 'command_line_args' : ["); 2061 for (int i = 0; i != num_command_line_args; ++i) { 2062 if (i) 2063 fprintf(stderr, ", "); 2064 fprintf(stderr, "'%s'", command_line_args[i]); 2065 } 2066 fprintf(stderr, "],\n"); 2067 fprintf(stderr, " 'unsaved_files' : ["); 2068 for (unsigned i = 0; i != num_unsaved_files; ++i) { 2069 if (i) 2070 fprintf(stderr, ", "); 2071 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename, 2072 unsaved_files[i].Length); 2073 } 2074 fprintf(stderr, "],\n"); 2075 fprintf(stderr, " 'options' : %d,\n", options); 2076 fprintf(stderr, "}\n"); 2077 2078 return 0; 2079 } 2080 2081 return PTUI.result; 2082} 2083 2084unsigned clang_defaultSaveOptions(CXTranslationUnit TU) { 2085 return CXSaveTranslationUnit_None; 2086} 2087 2088int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName, 2089 unsigned options) { 2090 if (!TU) 2091 return 1; 2092 2093 return static_cast<ASTUnit *>(TU)->Save(FileName); 2094} 2095 2096void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) { 2097 if (CTUnit) { 2098 // If the translation unit has been marked as unsafe to free, just discard 2099 // it. 2100 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree()) 2101 return; 2102 2103 delete static_cast<ASTUnit *>(CTUnit); 2104 } 2105} 2106 2107unsigned clang_defaultReparseOptions(CXTranslationUnit TU) { 2108 return CXReparse_None; 2109} 2110 2111struct ReparseTranslationUnitInfo { 2112 CXTranslationUnit TU; 2113 unsigned num_unsaved_files; 2114 struct CXUnsavedFile *unsaved_files; 2115 unsigned options; 2116 int result; 2117}; 2118static void clang_reparseTranslationUnit_Impl(void *UserData) { 2119 ReparseTranslationUnitInfo *RTUI = 2120 static_cast<ReparseTranslationUnitInfo*>(UserData); 2121 CXTranslationUnit TU = RTUI->TU; 2122 unsigned num_unsaved_files = RTUI->num_unsaved_files; 2123 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files; 2124 unsigned options = RTUI->options; 2125 (void) options; 2126 RTUI->result = 1; 2127 2128 if (!TU) 2129 return; 2130 2131 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles; 2132 for (unsigned I = 0; I != num_unsaved_files; ++I) { 2133 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length); 2134 const llvm::MemoryBuffer *Buffer 2135 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename); 2136 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename, 2137 Buffer)); 2138 } 2139 2140 if (!static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(), 2141 RemappedFiles.size())) 2142 RTUI->result = 0; 2143} 2144int clang_reparseTranslationUnit(CXTranslationUnit TU, 2145 unsigned num_unsaved_files, 2146 struct CXUnsavedFile *unsaved_files, 2147 unsigned options) { 2148 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files, 2149 options, 0 }; 2150 llvm::CrashRecoveryContext CRC; 2151 2152 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) { 2153 fprintf(stderr, "libclang: crash detected during reparsing\n"); 2154 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true); 2155 return 1; 2156 } 2157 2158 return RTUI.result; 2159} 2160 2161 2162CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) { 2163 if (!CTUnit) 2164 return createCXString(""); 2165 2166 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit); 2167 return createCXString(CXXUnit->getOriginalSourceFileName(), true); 2168} 2169 2170CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) { 2171 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } }; 2172 return Result; 2173} 2174 2175} // end: extern "C" 2176 2177//===----------------------------------------------------------------------===// 2178// CXSourceLocation and CXSourceRange Operations. 2179//===----------------------------------------------------------------------===// 2180 2181extern "C" { 2182CXSourceLocation clang_getNullLocation() { 2183 CXSourceLocation Result = { { 0, 0 }, 0 }; 2184 return Result; 2185} 2186 2187unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) { 2188 return (loc1.ptr_data[0] == loc2.ptr_data[0] && 2189 loc1.ptr_data[1] == loc2.ptr_data[1] && 2190 loc1.int_data == loc2.int_data); 2191} 2192 2193CXSourceLocation clang_getLocation(CXTranslationUnit tu, 2194 CXFile file, 2195 unsigned line, 2196 unsigned column) { 2197 if (!tu || !file) 2198 return clang_getNullLocation(); 2199 2200 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu); 2201 SourceLocation SLoc 2202 = CXXUnit->getSourceManager().getLocation( 2203 static_cast<const FileEntry *>(file), 2204 line, column); 2205 2206 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc); 2207} 2208 2209CXSourceRange clang_getNullRange() { 2210 CXSourceRange Result = { { 0, 0 }, 0, 0 }; 2211 return Result; 2212} 2213 2214CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) { 2215 if (begin.ptr_data[0] != end.ptr_data[0] || 2216 begin.ptr_data[1] != end.ptr_data[1]) 2217 return clang_getNullRange(); 2218 2219 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] }, 2220 begin.int_data, end.int_data }; 2221 return Result; 2222} 2223 2224void clang_getInstantiationLocation(CXSourceLocation location, 2225 CXFile *file, 2226 unsigned *line, 2227 unsigned *column, 2228 unsigned *offset) { 2229 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data); 2230 2231 if (!location.ptr_data[0] || Loc.isInvalid()) { 2232 if (file) 2233 *file = 0; 2234 if (line) 2235 *line = 0; 2236 if (column) 2237 *column = 0; 2238 if (offset) 2239 *offset = 0; 2240 return; 2241 } 2242 2243 const SourceManager &SM = 2244 *static_cast<const SourceManager*>(location.ptr_data[0]); 2245 SourceLocation InstLoc = SM.getInstantiationLoc(Loc); 2246 2247 if (file) 2248 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc)); 2249 if (line) 2250 *line = SM.getInstantiationLineNumber(InstLoc); 2251 if (column) 2252 *column = SM.getInstantiationColumnNumber(InstLoc); 2253 if (offset) 2254 *offset = SM.getDecomposedLoc(InstLoc).second; 2255} 2256 2257CXSourceLocation clang_getRangeStart(CXSourceRange range) { 2258 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] }, 2259 range.begin_int_data }; 2260 return Result; 2261} 2262 2263CXSourceLocation clang_getRangeEnd(CXSourceRange range) { 2264 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] }, 2265 range.end_int_data }; 2266 return Result; 2267} 2268 2269} // end: extern "C" 2270 2271//===----------------------------------------------------------------------===// 2272// CXFile Operations. 2273//===----------------------------------------------------------------------===// 2274 2275extern "C" { 2276CXString clang_getFileName(CXFile SFile) { 2277 if (!SFile) 2278 return createCXString(NULL); 2279 2280 FileEntry *FEnt = static_cast<FileEntry *>(SFile); 2281 return createCXString(FEnt->getName()); 2282} 2283 2284time_t clang_getFileTime(CXFile SFile) { 2285 if (!SFile) 2286 return 0; 2287 2288 FileEntry *FEnt = static_cast<FileEntry *>(SFile); 2289 return FEnt->getModificationTime(); 2290} 2291 2292CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) { 2293 if (!tu) 2294 return 0; 2295 2296 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu); 2297 2298 FileManager &FMgr = CXXUnit->getFileManager(); 2299 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name)); 2300 return const_cast<FileEntry *>(File); 2301} 2302 2303} // end: extern "C" 2304 2305//===----------------------------------------------------------------------===// 2306// CXCursor Operations. 2307//===----------------------------------------------------------------------===// 2308 2309static Decl *getDeclFromExpr(Stmt *E) { 2310 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E)) 2311 return RefExpr->getDecl(); 2312 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) 2313 return ME->getMemberDecl(); 2314 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E)) 2315 return RE->getDecl(); 2316 2317 if (CallExpr *CE = dyn_cast<CallExpr>(E)) 2318 return getDeclFromExpr(CE->getCallee()); 2319 if (CastExpr *CE = dyn_cast<CastExpr>(E)) 2320 return getDeclFromExpr(CE->getSubExpr()); 2321 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E)) 2322 return OME->getMethodDecl(); 2323 2324 return 0; 2325} 2326 2327static SourceLocation getLocationFromExpr(Expr *E) { 2328 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) 2329 return /*FIXME:*/Msg->getLeftLoc(); 2330 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 2331 return DRE->getLocation(); 2332 if (MemberExpr *Member = dyn_cast<MemberExpr>(E)) 2333 return Member->getMemberLoc(); 2334 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) 2335 return Ivar->getLocation(); 2336 return E->getLocStart(); 2337} 2338 2339extern "C" { 2340 2341unsigned clang_visitChildren(CXCursor parent, 2342 CXCursorVisitor visitor, 2343 CXClientData client_data) { 2344 ASTUnit *CXXUnit = getCursorASTUnit(parent); 2345 2346 CursorVisitor CursorVis(CXXUnit, visitor, client_data, 2347 CXXUnit->getMaxPCHLevel()); 2348 return CursorVis.VisitChildren(parent); 2349} 2350 2351static CXString getDeclSpelling(Decl *D) { 2352 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D); 2353 if (!ND) 2354 return createCXString(""); 2355 2356 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND)) 2357 return createCXString(OMD->getSelector().getAsString()); 2358 2359 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND)) 2360 // No, this isn't the same as the code below. getIdentifier() is non-virtual 2361 // and returns different names. NamedDecl returns the class name and 2362 // ObjCCategoryImplDecl returns the category name. 2363 return createCXString(CIMP->getIdentifier()->getNameStart()); 2364 2365 if (isa<UsingDirectiveDecl>(D)) 2366 return createCXString(""); 2367 2368 llvm::SmallString<1024> S; 2369 llvm::raw_svector_ostream os(S); 2370 ND->printName(os); 2371 2372 return createCXString(os.str()); 2373} 2374 2375CXString clang_getCursorSpelling(CXCursor C) { 2376 if (clang_isTranslationUnit(C.kind)) 2377 return clang_getTranslationUnitSpelling(C.data[2]); 2378 2379 if (clang_isReference(C.kind)) { 2380 switch (C.kind) { 2381 case CXCursor_ObjCSuperClassRef: { 2382 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first; 2383 return createCXString(Super->getIdentifier()->getNameStart()); 2384 } 2385 case CXCursor_ObjCClassRef: { 2386 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first; 2387 return createCXString(Class->getIdentifier()->getNameStart()); 2388 } 2389 case CXCursor_ObjCProtocolRef: { 2390 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first; 2391 assert(OID && "getCursorSpelling(): Missing protocol decl"); 2392 return createCXString(OID->getIdentifier()->getNameStart()); 2393 } 2394 case CXCursor_CXXBaseSpecifier: { 2395 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C); 2396 return createCXString(B->getType().getAsString()); 2397 } 2398 case CXCursor_TypeRef: { 2399 TypeDecl *Type = getCursorTypeRef(C).first; 2400 assert(Type && "Missing type decl"); 2401 2402 return createCXString(getCursorContext(C).getTypeDeclType(Type). 2403 getAsString()); 2404 } 2405 case CXCursor_TemplateRef: { 2406 TemplateDecl *Template = getCursorTemplateRef(C).first; 2407 assert(Template && "Missing template decl"); 2408 2409 return createCXString(Template->getNameAsString()); 2410 } 2411 2412 case CXCursor_NamespaceRef: { 2413 NamedDecl *NS = getCursorNamespaceRef(C).first; 2414 assert(NS && "Missing namespace decl"); 2415 2416 return createCXString(NS->getNameAsString()); 2417 } 2418 2419 default: 2420 return createCXString("<not implemented>"); 2421 } 2422 } 2423 2424 if (clang_isExpression(C.kind)) { 2425 Decl *D = getDeclFromExpr(getCursorExpr(C)); 2426 if (D) 2427 return getDeclSpelling(D); 2428 return createCXString(""); 2429 } 2430 2431 if (C.kind == CXCursor_MacroInstantiation) 2432 return createCXString(getCursorMacroInstantiation(C)->getName() 2433 ->getNameStart()); 2434 2435 if (C.kind == CXCursor_MacroDefinition) 2436 return createCXString(getCursorMacroDefinition(C)->getName() 2437 ->getNameStart()); 2438 2439 if (clang_isDeclaration(C.kind)) 2440 return getDeclSpelling(getCursorDecl(C)); 2441 2442 return createCXString(""); 2443} 2444 2445CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) { 2446 switch (Kind) { 2447 case CXCursor_FunctionDecl: 2448 return createCXString("FunctionDecl"); 2449 case CXCursor_TypedefDecl: 2450 return createCXString("TypedefDecl"); 2451 case CXCursor_EnumDecl: 2452 return createCXString("EnumDecl"); 2453 case CXCursor_EnumConstantDecl: 2454 return createCXString("EnumConstantDecl"); 2455 case CXCursor_StructDecl: 2456 return createCXString("StructDecl"); 2457 case CXCursor_UnionDecl: 2458 return createCXString("UnionDecl"); 2459 case CXCursor_ClassDecl: 2460 return createCXString("ClassDecl"); 2461 case CXCursor_FieldDecl: 2462 return createCXString("FieldDecl"); 2463 case CXCursor_VarDecl: 2464 return createCXString("VarDecl"); 2465 case CXCursor_ParmDecl: 2466 return createCXString("ParmDecl"); 2467 case CXCursor_ObjCInterfaceDecl: 2468 return createCXString("ObjCInterfaceDecl"); 2469 case CXCursor_ObjCCategoryDecl: 2470 return createCXString("ObjCCategoryDecl"); 2471 case CXCursor_ObjCProtocolDecl: 2472 return createCXString("ObjCProtocolDecl"); 2473 case CXCursor_ObjCPropertyDecl: 2474 return createCXString("ObjCPropertyDecl"); 2475 case CXCursor_ObjCIvarDecl: 2476 return createCXString("ObjCIvarDecl"); 2477 case CXCursor_ObjCInstanceMethodDecl: 2478 return createCXString("ObjCInstanceMethodDecl"); 2479 case CXCursor_ObjCClassMethodDecl: 2480 return createCXString("ObjCClassMethodDecl"); 2481 case CXCursor_ObjCImplementationDecl: 2482 return createCXString("ObjCImplementationDecl"); 2483 case CXCursor_ObjCCategoryImplDecl: 2484 return createCXString("ObjCCategoryImplDecl"); 2485 case CXCursor_CXXMethod: 2486 return createCXString("CXXMethod"); 2487 case CXCursor_UnexposedDecl: 2488 return createCXString("UnexposedDecl"); 2489 case CXCursor_ObjCSuperClassRef: 2490 return createCXString("ObjCSuperClassRef"); 2491 case CXCursor_ObjCProtocolRef: 2492 return createCXString("ObjCProtocolRef"); 2493 case CXCursor_ObjCClassRef: 2494 return createCXString("ObjCClassRef"); 2495 case CXCursor_TypeRef: 2496 return createCXString("TypeRef"); 2497 case CXCursor_TemplateRef: 2498 return createCXString("TemplateRef"); 2499 case CXCursor_NamespaceRef: 2500 return createCXString("NamespaceRef"); 2501 case CXCursor_UnexposedExpr: 2502 return createCXString("UnexposedExpr"); 2503 case CXCursor_BlockExpr: 2504 return createCXString("BlockExpr"); 2505 case CXCursor_DeclRefExpr: 2506 return createCXString("DeclRefExpr"); 2507 case CXCursor_MemberRefExpr: 2508 return createCXString("MemberRefExpr"); 2509 case CXCursor_CallExpr: 2510 return createCXString("CallExpr"); 2511 case CXCursor_ObjCMessageExpr: 2512 return createCXString("ObjCMessageExpr"); 2513 case CXCursor_UnexposedStmt: 2514 return createCXString("UnexposedStmt"); 2515 case CXCursor_InvalidFile: 2516 return createCXString("InvalidFile"); 2517 case CXCursor_InvalidCode: 2518 return createCXString("InvalidCode"); 2519 case CXCursor_NoDeclFound: 2520 return createCXString("NoDeclFound"); 2521 case CXCursor_NotImplemented: 2522 return createCXString("NotImplemented"); 2523 case CXCursor_TranslationUnit: 2524 return createCXString("TranslationUnit"); 2525 case CXCursor_UnexposedAttr: 2526 return createCXString("UnexposedAttr"); 2527 case CXCursor_IBActionAttr: 2528 return createCXString("attribute(ibaction)"); 2529 case CXCursor_IBOutletAttr: 2530 return createCXString("attribute(iboutlet)"); 2531 case CXCursor_IBOutletCollectionAttr: 2532 return createCXString("attribute(iboutletcollection)"); 2533 case CXCursor_PreprocessingDirective: 2534 return createCXString("preprocessing directive"); 2535 case CXCursor_MacroDefinition: 2536 return createCXString("macro definition"); 2537 case CXCursor_MacroInstantiation: 2538 return createCXString("macro instantiation"); 2539 case CXCursor_Namespace: 2540 return createCXString("Namespace"); 2541 case CXCursor_LinkageSpec: 2542 return createCXString("LinkageSpec"); 2543 case CXCursor_CXXBaseSpecifier: 2544 return createCXString("C++ base class specifier"); 2545 case CXCursor_Constructor: 2546 return createCXString("CXXConstructor"); 2547 case CXCursor_Destructor: 2548 return createCXString("CXXDestructor"); 2549 case CXCursor_ConversionFunction: 2550 return createCXString("CXXConversion"); 2551 case CXCursor_TemplateTypeParameter: 2552 return createCXString("TemplateTypeParameter"); 2553 case CXCursor_NonTypeTemplateParameter: 2554 return createCXString("NonTypeTemplateParameter"); 2555 case CXCursor_TemplateTemplateParameter: 2556 return createCXString("TemplateTemplateParameter"); 2557 case CXCursor_FunctionTemplate: 2558 return createCXString("FunctionTemplate"); 2559 case CXCursor_ClassTemplate: 2560 return createCXString("ClassTemplate"); 2561 case CXCursor_ClassTemplatePartialSpecialization: 2562 return createCXString("ClassTemplatePartialSpecialization"); 2563 case CXCursor_NamespaceAlias: 2564 return createCXString("NamespaceAlias"); 2565 case CXCursor_UsingDirective: 2566 return createCXString("UsingDirective"); 2567 case CXCursor_UsingDeclaration: 2568 return createCXString("UsingDeclaration"); 2569 } 2570 2571 llvm_unreachable("Unhandled CXCursorKind"); 2572 return createCXString(NULL); 2573} 2574 2575enum CXChildVisitResult GetCursorVisitor(CXCursor cursor, 2576 CXCursor parent, 2577 CXClientData client_data) { 2578 CXCursor *BestCursor = static_cast<CXCursor *>(client_data); 2579 *BestCursor = cursor; 2580 return CXChildVisit_Recurse; 2581} 2582 2583CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) { 2584 if (!TU) 2585 return clang_getNullCursor(); 2586 2587 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU); 2588 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 2589 2590 // Translate the given source location to make it point at the beginning of 2591 // the token under the cursor. 2592 SourceLocation SLoc = cxloc::translateSourceLocation(Loc); 2593 2594 // Guard against an invalid SourceLocation, or we may assert in one 2595 // of the following calls. 2596 if (SLoc.isInvalid()) 2597 return clang_getNullCursor(); 2598 2599 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(), 2600 CXXUnit->getASTContext().getLangOptions()); 2601 2602 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound); 2603 if (SLoc.isValid()) { 2604 // FIXME: Would be great to have a "hint" cursor, then walk from that 2605 // hint cursor upward until we find a cursor whose source range encloses 2606 // the region of interest, rather than starting from the translation unit. 2607 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit); 2608 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result, 2609 Decl::MaxPCHLevel, SourceLocation(SLoc)); 2610 CursorVis.VisitChildren(Parent); 2611 } 2612 return Result; 2613} 2614 2615CXCursor clang_getNullCursor(void) { 2616 return MakeCXCursorInvalid(CXCursor_InvalidFile); 2617} 2618 2619unsigned clang_equalCursors(CXCursor X, CXCursor Y) { 2620 return X == Y; 2621} 2622 2623unsigned clang_isInvalid(enum CXCursorKind K) { 2624 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid; 2625} 2626 2627unsigned clang_isDeclaration(enum CXCursorKind K) { 2628 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl; 2629} 2630 2631unsigned clang_isReference(enum CXCursorKind K) { 2632 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef; 2633} 2634 2635unsigned clang_isExpression(enum CXCursorKind K) { 2636 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr; 2637} 2638 2639unsigned clang_isStatement(enum CXCursorKind K) { 2640 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt; 2641} 2642 2643unsigned clang_isTranslationUnit(enum CXCursorKind K) { 2644 return K == CXCursor_TranslationUnit; 2645} 2646 2647unsigned clang_isPreprocessing(enum CXCursorKind K) { 2648 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing; 2649} 2650 2651unsigned clang_isUnexposed(enum CXCursorKind K) { 2652 switch (K) { 2653 case CXCursor_UnexposedDecl: 2654 case CXCursor_UnexposedExpr: 2655 case CXCursor_UnexposedStmt: 2656 case CXCursor_UnexposedAttr: 2657 return true; 2658 default: 2659 return false; 2660 } 2661} 2662 2663CXCursorKind clang_getCursorKind(CXCursor C) { 2664 return C.kind; 2665} 2666 2667CXSourceLocation clang_getCursorLocation(CXCursor C) { 2668 if (clang_isReference(C.kind)) { 2669 switch (C.kind) { 2670 case CXCursor_ObjCSuperClassRef: { 2671 std::pair<ObjCInterfaceDecl *, SourceLocation> P 2672 = getCursorObjCSuperClassRef(C); 2673 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 2674 } 2675 2676 case CXCursor_ObjCProtocolRef: { 2677 std::pair<ObjCProtocolDecl *, SourceLocation> P 2678 = getCursorObjCProtocolRef(C); 2679 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 2680 } 2681 2682 case CXCursor_ObjCClassRef: { 2683 std::pair<ObjCInterfaceDecl *, SourceLocation> P 2684 = getCursorObjCClassRef(C); 2685 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 2686 } 2687 2688 case CXCursor_TypeRef: { 2689 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C); 2690 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 2691 } 2692 2693 case CXCursor_TemplateRef: { 2694 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C); 2695 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 2696 } 2697 2698 case CXCursor_NamespaceRef: { 2699 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C); 2700 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 2701 } 2702 2703 case CXCursor_CXXBaseSpecifier: { 2704 // FIXME: Figure out what location to return for a CXXBaseSpecifier. 2705 return clang_getNullLocation(); 2706 } 2707 2708 default: 2709 // FIXME: Need a way to enumerate all non-reference cases. 2710 llvm_unreachable("Missed a reference kind"); 2711 } 2712 } 2713 2714 if (clang_isExpression(C.kind)) 2715 return cxloc::translateSourceLocation(getCursorContext(C), 2716 getLocationFromExpr(getCursorExpr(C))); 2717 2718 if (C.kind == CXCursor_PreprocessingDirective) { 2719 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin(); 2720 return cxloc::translateSourceLocation(getCursorContext(C), L); 2721 } 2722 2723 if (C.kind == CXCursor_MacroInstantiation) { 2724 SourceLocation L 2725 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin(); 2726 return cxloc::translateSourceLocation(getCursorContext(C), L); 2727 } 2728 2729 if (C.kind == CXCursor_MacroDefinition) { 2730 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation(); 2731 return cxloc::translateSourceLocation(getCursorContext(C), L); 2732 } 2733 2734 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl) 2735 return clang_getNullLocation(); 2736 2737 Decl *D = getCursorDecl(C); 2738 SourceLocation Loc = D->getLocation(); 2739 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D)) 2740 Loc = Class->getClassLoc(); 2741 return cxloc::translateSourceLocation(getCursorContext(C), Loc); 2742} 2743 2744} // end extern "C" 2745 2746static SourceRange getRawCursorExtent(CXCursor C) { 2747 if (clang_isReference(C.kind)) { 2748 switch (C.kind) { 2749 case CXCursor_ObjCSuperClassRef: 2750 return getCursorObjCSuperClassRef(C).second; 2751 2752 case CXCursor_ObjCProtocolRef: 2753 return getCursorObjCProtocolRef(C).second; 2754 2755 case CXCursor_ObjCClassRef: 2756 return getCursorObjCClassRef(C).second; 2757 2758 case CXCursor_TypeRef: 2759 return getCursorTypeRef(C).second; 2760 2761 case CXCursor_TemplateRef: 2762 return getCursorTemplateRef(C).second; 2763 2764 case CXCursor_NamespaceRef: 2765 return getCursorNamespaceRef(C).second; 2766 2767 case CXCursor_CXXBaseSpecifier: 2768 // FIXME: Figure out what source range to use for a CXBaseSpecifier. 2769 return SourceRange(); 2770 2771 default: 2772 // FIXME: Need a way to enumerate all non-reference cases. 2773 llvm_unreachable("Missed a reference kind"); 2774 } 2775 } 2776 2777 if (clang_isExpression(C.kind)) 2778 return getCursorExpr(C)->getSourceRange(); 2779 2780 if (clang_isStatement(C.kind)) 2781 return getCursorStmt(C)->getSourceRange(); 2782 2783 if (C.kind == CXCursor_PreprocessingDirective) 2784 return cxcursor::getCursorPreprocessingDirective(C); 2785 2786 if (C.kind == CXCursor_MacroInstantiation) 2787 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange(); 2788 2789 if (C.kind == CXCursor_MacroDefinition) 2790 return cxcursor::getCursorMacroDefinition(C)->getSourceRange(); 2791 2792 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) 2793 return getCursorDecl(C)->getSourceRange(); 2794 2795 return SourceRange(); 2796} 2797 2798extern "C" { 2799 2800CXSourceRange clang_getCursorExtent(CXCursor C) { 2801 SourceRange R = getRawCursorExtent(C); 2802 if (R.isInvalid()) 2803 return clang_getNullRange(); 2804 2805 return cxloc::translateSourceRange(getCursorContext(C), R); 2806} 2807 2808CXCursor clang_getCursorReferenced(CXCursor C) { 2809 if (clang_isInvalid(C.kind)) 2810 return clang_getNullCursor(); 2811 2812 ASTUnit *CXXUnit = getCursorASTUnit(C); 2813 if (clang_isDeclaration(C.kind)) 2814 return C; 2815 2816 if (clang_isExpression(C.kind)) { 2817 Decl *D = getDeclFromExpr(getCursorExpr(C)); 2818 if (D) 2819 return MakeCXCursor(D, CXXUnit); 2820 return clang_getNullCursor(); 2821 } 2822 2823 if (C.kind == CXCursor_MacroInstantiation) { 2824 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition()) 2825 return MakeMacroDefinitionCursor(Def, CXXUnit); 2826 } 2827 2828 if (!clang_isReference(C.kind)) 2829 return clang_getNullCursor(); 2830 2831 switch (C.kind) { 2832 case CXCursor_ObjCSuperClassRef: 2833 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit); 2834 2835 case CXCursor_ObjCProtocolRef: { 2836 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit); 2837 2838 case CXCursor_ObjCClassRef: 2839 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit); 2840 2841 case CXCursor_TypeRef: 2842 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit); 2843 2844 case CXCursor_TemplateRef: 2845 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit); 2846 2847 case CXCursor_NamespaceRef: 2848 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit); 2849 2850 case CXCursor_CXXBaseSpecifier: { 2851 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C); 2852 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(), 2853 CXXUnit)); 2854 } 2855 2856 default: 2857 // We would prefer to enumerate all non-reference cursor kinds here. 2858 llvm_unreachable("Unhandled reference cursor kind"); 2859 break; 2860 } 2861 } 2862 2863 return clang_getNullCursor(); 2864} 2865 2866CXCursor clang_getCursorDefinition(CXCursor C) { 2867 if (clang_isInvalid(C.kind)) 2868 return clang_getNullCursor(); 2869 2870 ASTUnit *CXXUnit = getCursorASTUnit(C); 2871 2872 bool WasReference = false; 2873 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) { 2874 C = clang_getCursorReferenced(C); 2875 WasReference = true; 2876 } 2877 2878 if (C.kind == CXCursor_MacroInstantiation) 2879 return clang_getCursorReferenced(C); 2880 2881 if (!clang_isDeclaration(C.kind)) 2882 return clang_getNullCursor(); 2883 2884 Decl *D = getCursorDecl(C); 2885 if (!D) 2886 return clang_getNullCursor(); 2887 2888 switch (D->getKind()) { 2889 // Declaration kinds that don't really separate the notions of 2890 // declaration and definition. 2891 case Decl::Namespace: 2892 case Decl::Typedef: 2893 case Decl::TemplateTypeParm: 2894 case Decl::EnumConstant: 2895 case Decl::Field: 2896 case Decl::ObjCIvar: 2897 case Decl::ObjCAtDefsField: 2898 case Decl::ImplicitParam: 2899 case Decl::ParmVar: 2900 case Decl::NonTypeTemplateParm: 2901 case Decl::TemplateTemplateParm: 2902 case Decl::ObjCCategoryImpl: 2903 case Decl::ObjCImplementation: 2904 case Decl::AccessSpec: 2905 case Decl::LinkageSpec: 2906 case Decl::ObjCPropertyImpl: 2907 case Decl::FileScopeAsm: 2908 case Decl::StaticAssert: 2909 case Decl::Block: 2910 return C; 2911 2912 // Declaration kinds that don't make any sense here, but are 2913 // nonetheless harmless. 2914 case Decl::TranslationUnit: 2915 break; 2916 2917 // Declaration kinds for which the definition is not resolvable. 2918 case Decl::UnresolvedUsingTypename: 2919 case Decl::UnresolvedUsingValue: 2920 break; 2921 2922 case Decl::UsingDirective: 2923 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(), 2924 CXXUnit); 2925 2926 case Decl::NamespaceAlias: 2927 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit); 2928 2929 case Decl::Enum: 2930 case Decl::Record: 2931 case Decl::CXXRecord: 2932 case Decl::ClassTemplateSpecialization: 2933 case Decl::ClassTemplatePartialSpecialization: 2934 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition()) 2935 return MakeCXCursor(Def, CXXUnit); 2936 return clang_getNullCursor(); 2937 2938 case Decl::Function: 2939 case Decl::CXXMethod: 2940 case Decl::CXXConstructor: 2941 case Decl::CXXDestructor: 2942 case Decl::CXXConversion: { 2943 const FunctionDecl *Def = 0; 2944 if (cast<FunctionDecl>(D)->getBody(Def)) 2945 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit); 2946 return clang_getNullCursor(); 2947 } 2948 2949 case Decl::Var: { 2950 // Ask the variable if it has a definition. 2951 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition()) 2952 return MakeCXCursor(Def, CXXUnit); 2953 return clang_getNullCursor(); 2954 } 2955 2956 case Decl::FunctionTemplate: { 2957 const FunctionDecl *Def = 0; 2958 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def)) 2959 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit); 2960 return clang_getNullCursor(); 2961 } 2962 2963 case Decl::ClassTemplate: { 2964 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl() 2965 ->getDefinition()) 2966 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(), 2967 CXXUnit); 2968 return clang_getNullCursor(); 2969 } 2970 2971 case Decl::Using: { 2972 UsingDecl *Using = cast<UsingDecl>(D); 2973 CXCursor Def = clang_getNullCursor(); 2974 for (UsingDecl::shadow_iterator S = Using->shadow_begin(), 2975 SEnd = Using->shadow_end(); 2976 S != SEnd; ++S) { 2977 if (Def != clang_getNullCursor()) { 2978 // FIXME: We have no way to return multiple results. 2979 return clang_getNullCursor(); 2980 } 2981 2982 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(), 2983 CXXUnit)); 2984 } 2985 2986 return Def; 2987 } 2988 2989 case Decl::UsingShadow: 2990 return clang_getCursorDefinition( 2991 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(), 2992 CXXUnit)); 2993 2994 case Decl::ObjCMethod: { 2995 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D); 2996 if (Method->isThisDeclarationADefinition()) 2997 return C; 2998 2999 // Dig out the method definition in the associated 3000 // @implementation, if we have it. 3001 // FIXME: The ASTs should make finding the definition easier. 3002 if (ObjCInterfaceDecl *Class 3003 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) 3004 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation()) 3005 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(), 3006 Method->isInstanceMethod())) 3007 if (Def->isThisDeclarationADefinition()) 3008 return MakeCXCursor(Def, CXXUnit); 3009 3010 return clang_getNullCursor(); 3011 } 3012 3013 case Decl::ObjCCategory: 3014 if (ObjCCategoryImplDecl *Impl 3015 = cast<ObjCCategoryDecl>(D)->getImplementation()) 3016 return MakeCXCursor(Impl, CXXUnit); 3017 return clang_getNullCursor(); 3018 3019 case Decl::ObjCProtocol: 3020 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl()) 3021 return C; 3022 return clang_getNullCursor(); 3023 3024 case Decl::ObjCInterface: 3025 // There are two notions of a "definition" for an Objective-C 3026 // class: the interface and its implementation. When we resolved a 3027 // reference to an Objective-C class, produce the @interface as 3028 // the definition; when we were provided with the interface, 3029 // produce the @implementation as the definition. 3030 if (WasReference) { 3031 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl()) 3032 return C; 3033 } else if (ObjCImplementationDecl *Impl 3034 = cast<ObjCInterfaceDecl>(D)->getImplementation()) 3035 return MakeCXCursor(Impl, CXXUnit); 3036 return clang_getNullCursor(); 3037 3038 case Decl::ObjCProperty: 3039 // FIXME: We don't really know where to find the 3040 // ObjCPropertyImplDecls that implement this property. 3041 return clang_getNullCursor(); 3042 3043 case Decl::ObjCCompatibleAlias: 3044 if (ObjCInterfaceDecl *Class 3045 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface()) 3046 if (!Class->isForwardDecl()) 3047 return MakeCXCursor(Class, CXXUnit); 3048 3049 return clang_getNullCursor(); 3050 3051 case Decl::ObjCForwardProtocol: { 3052 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D); 3053 if (Forward->protocol_size() == 1) 3054 return clang_getCursorDefinition( 3055 MakeCXCursor(*Forward->protocol_begin(), 3056 CXXUnit)); 3057 3058 // FIXME: Cannot return multiple definitions. 3059 return clang_getNullCursor(); 3060 } 3061 3062 case Decl::ObjCClass: { 3063 ObjCClassDecl *Class = cast<ObjCClassDecl>(D); 3064 if (Class->size() == 1) { 3065 ObjCInterfaceDecl *IFace = Class->begin()->getInterface(); 3066 if (!IFace->isForwardDecl()) 3067 return MakeCXCursor(IFace, CXXUnit); 3068 return clang_getNullCursor(); 3069 } 3070 3071 // FIXME: Cannot return multiple definitions. 3072 return clang_getNullCursor(); 3073 } 3074 3075 case Decl::Friend: 3076 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl()) 3077 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit)); 3078 return clang_getNullCursor(); 3079 3080 case Decl::FriendTemplate: 3081 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl()) 3082 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit)); 3083 return clang_getNullCursor(); 3084 } 3085 3086 return clang_getNullCursor(); 3087} 3088 3089unsigned clang_isCursorDefinition(CXCursor C) { 3090 if (!clang_isDeclaration(C.kind)) 3091 return 0; 3092 3093 return clang_getCursorDefinition(C) == C; 3094} 3095 3096void clang_getDefinitionSpellingAndExtent(CXCursor C, 3097 const char **startBuf, 3098 const char **endBuf, 3099 unsigned *startLine, 3100 unsigned *startColumn, 3101 unsigned *endLine, 3102 unsigned *endColumn) { 3103 assert(getCursorDecl(C) && "CXCursor has null decl"); 3104 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C)); 3105 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND); 3106 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody()); 3107 3108 SourceManager &SM = FD->getASTContext().getSourceManager(); 3109 *startBuf = SM.getCharacterData(Body->getLBracLoc()); 3110 *endBuf = SM.getCharacterData(Body->getRBracLoc()); 3111 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc()); 3112 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc()); 3113 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc()); 3114 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc()); 3115} 3116 3117void clang_enableStackTraces(void) { 3118 llvm::sys::PrintStackTraceOnErrorSignal(); 3119} 3120 3121} // end: extern "C" 3122 3123//===----------------------------------------------------------------------===// 3124// Token-based Operations. 3125//===----------------------------------------------------------------------===// 3126 3127/* CXToken layout: 3128 * int_data[0]: a CXTokenKind 3129 * int_data[1]: starting token location 3130 * int_data[2]: token length 3131 * int_data[3]: reserved 3132 * ptr_data: for identifiers and keywords, an IdentifierInfo*. 3133 * otherwise unused. 3134 */ 3135extern "C" { 3136 3137CXTokenKind clang_getTokenKind(CXToken CXTok) { 3138 return static_cast<CXTokenKind>(CXTok.int_data[0]); 3139} 3140 3141CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) { 3142 switch (clang_getTokenKind(CXTok)) { 3143 case CXToken_Identifier: 3144 case CXToken_Keyword: 3145 // We know we have an IdentifierInfo*, so use that. 3146 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data) 3147 ->getNameStart()); 3148 3149 case CXToken_Literal: { 3150 // We have stashed the starting pointer in the ptr_data field. Use it. 3151 const char *Text = static_cast<const char *>(CXTok.ptr_data); 3152 return createCXString(llvm::StringRef(Text, CXTok.int_data[2])); 3153 } 3154 3155 case CXToken_Punctuation: 3156 case CXToken_Comment: 3157 break; 3158 } 3159 3160 // We have to find the starting buffer pointer the hard way, by 3161 // deconstructing the source location. 3162 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU); 3163 if (!CXXUnit) 3164 return createCXString(""); 3165 3166 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]); 3167 std::pair<FileID, unsigned> LocInfo 3168 = CXXUnit->getSourceManager().getDecomposedLoc(Loc); 3169 bool Invalid = false; 3170 llvm::StringRef Buffer 3171 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid); 3172 if (Invalid) 3173 return createCXString(""); 3174 3175 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2])); 3176} 3177 3178CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) { 3179 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU); 3180 if (!CXXUnit) 3181 return clang_getNullLocation(); 3182 3183 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), 3184 SourceLocation::getFromRawEncoding(CXTok.int_data[1])); 3185} 3186 3187CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) { 3188 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU); 3189 if (!CXXUnit) 3190 return clang_getNullRange(); 3191 3192 return cxloc::translateSourceRange(CXXUnit->getASTContext(), 3193 SourceLocation::getFromRawEncoding(CXTok.int_data[1])); 3194} 3195 3196void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range, 3197 CXToken **Tokens, unsigned *NumTokens) { 3198 if (Tokens) 3199 *Tokens = 0; 3200 if (NumTokens) 3201 *NumTokens = 0; 3202 3203 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU); 3204 if (!CXXUnit || !Tokens || !NumTokens) 3205 return; 3206 3207 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 3208 3209 SourceRange R = cxloc::translateCXSourceRange(Range); 3210 if (R.isInvalid()) 3211 return; 3212 3213 SourceManager &SourceMgr = CXXUnit->getSourceManager(); 3214 std::pair<FileID, unsigned> BeginLocInfo 3215 = SourceMgr.getDecomposedLoc(R.getBegin()); 3216 std::pair<FileID, unsigned> EndLocInfo 3217 = SourceMgr.getDecomposedLoc(R.getEnd()); 3218 3219 // Cannot tokenize across files. 3220 if (BeginLocInfo.first != EndLocInfo.first) 3221 return; 3222 3223 // Create a lexer 3224 bool Invalid = false; 3225 llvm::StringRef Buffer 3226 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid); 3227 if (Invalid) 3228 return; 3229 3230 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first), 3231 CXXUnit->getASTContext().getLangOptions(), 3232 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end()); 3233 Lex.SetCommentRetentionState(true); 3234 3235 // Lex tokens until we hit the end of the range. 3236 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second; 3237 llvm::SmallVector<CXToken, 32> CXTokens; 3238 Token Tok; 3239 do { 3240 // Lex the next token 3241 Lex.LexFromRawLexer(Tok); 3242 if (Tok.is(tok::eof)) 3243 break; 3244 3245 // Initialize the CXToken. 3246 CXToken CXTok; 3247 3248 // - Common fields 3249 CXTok.int_data[1] = Tok.getLocation().getRawEncoding(); 3250 CXTok.int_data[2] = Tok.getLength(); 3251 CXTok.int_data[3] = 0; 3252 3253 // - Kind-specific fields 3254 if (Tok.isLiteral()) { 3255 CXTok.int_data[0] = CXToken_Literal; 3256 CXTok.ptr_data = (void *)Tok.getLiteralData(); 3257 } else if (Tok.is(tok::identifier)) { 3258 // Lookup the identifier to determine whether we have a keyword. 3259 std::pair<FileID, unsigned> LocInfo 3260 = SourceMgr.getDecomposedLoc(Tok.getLocation()); 3261 bool Invalid = false; 3262 llvm::StringRef Buf 3263 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid); 3264 if (Invalid) 3265 return; 3266 3267 const char *StartPos = Buf.data() + LocInfo.second; 3268 IdentifierInfo *II 3269 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos); 3270 3271 if (II->getObjCKeywordID() != tok::objc_not_keyword) { 3272 CXTok.int_data[0] = CXToken_Keyword; 3273 } 3274 else { 3275 CXTok.int_data[0] = II->getTokenID() == tok::identifier? 3276 CXToken_Identifier 3277 : CXToken_Keyword; 3278 } 3279 CXTok.ptr_data = II; 3280 } else if (Tok.is(tok::comment)) { 3281 CXTok.int_data[0] = CXToken_Comment; 3282 CXTok.ptr_data = 0; 3283 } else { 3284 CXTok.int_data[0] = CXToken_Punctuation; 3285 CXTok.ptr_data = 0; 3286 } 3287 CXTokens.push_back(CXTok); 3288 } while (Lex.getBufferLocation() <= EffectiveBufferEnd); 3289 3290 if (CXTokens.empty()) 3291 return; 3292 3293 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size()); 3294 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size()); 3295 *NumTokens = CXTokens.size(); 3296} 3297 3298void clang_disposeTokens(CXTranslationUnit TU, 3299 CXToken *Tokens, unsigned NumTokens) { 3300 free(Tokens); 3301} 3302 3303} // end: extern "C" 3304 3305//===----------------------------------------------------------------------===// 3306// Token annotation APIs. 3307//===----------------------------------------------------------------------===// 3308 3309typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData; 3310static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor, 3311 CXCursor parent, 3312 CXClientData client_data); 3313namespace { 3314class AnnotateTokensWorker { 3315 AnnotateTokensData &Annotated; 3316 CXToken *Tokens; 3317 CXCursor *Cursors; 3318 unsigned NumTokens; 3319 unsigned TokIdx; 3320 CursorVisitor AnnotateVis; 3321 SourceManager &SrcMgr; 3322 3323 bool MoreTokens() const { return TokIdx < NumTokens; } 3324 unsigned NextToken() const { return TokIdx; } 3325 void AdvanceToken() { ++TokIdx; } 3326 SourceLocation GetTokenLoc(unsigned tokI) { 3327 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]); 3328 } 3329 3330public: 3331 AnnotateTokensWorker(AnnotateTokensData &annotated, 3332 CXToken *tokens, CXCursor *cursors, unsigned numTokens, 3333 ASTUnit *CXXUnit, SourceRange RegionOfInterest) 3334 : Annotated(annotated), Tokens(tokens), Cursors(cursors), 3335 NumTokens(numTokens), TokIdx(0), 3336 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this, 3337 Decl::MaxPCHLevel, RegionOfInterest), 3338 SrcMgr(CXXUnit->getSourceManager()) {} 3339 3340 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); } 3341 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent); 3342 void AnnotateTokens(CXCursor parent); 3343}; 3344} 3345 3346void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) { 3347 // Walk the AST within the region of interest, annotating tokens 3348 // along the way. 3349 VisitChildren(parent); 3350 3351 for (unsigned I = 0 ; I < TokIdx ; ++I) { 3352 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]); 3353 if (Pos != Annotated.end()) 3354 Cursors[I] = Pos->second; 3355 } 3356 3357 // Finish up annotating any tokens left. 3358 if (!MoreTokens()) 3359 return; 3360 3361 const CXCursor &C = clang_getNullCursor(); 3362 for (unsigned I = TokIdx ; I < NumTokens ; ++I) { 3363 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]); 3364 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second; 3365 } 3366} 3367 3368enum CXChildVisitResult 3369AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) { 3370 CXSourceLocation Loc = clang_getCursorLocation(cursor); 3371 // We can always annotate a preprocessing directive/macro instantiation. 3372 if (clang_isPreprocessing(cursor.kind)) { 3373 Annotated[Loc.int_data] = cursor; 3374 return CXChildVisit_Recurse; 3375 } 3376 3377 SourceRange cursorRange = getRawCursorExtent(cursor); 3378 3379 if (cursorRange.isInvalid()) 3380 return CXChildVisit_Continue; 3381 3382 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data); 3383 3384 // Adjust the annotated range based specific declarations. 3385 const enum CXCursorKind cursorK = clang_getCursorKind(cursor); 3386 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) { 3387 Decl *D = cxcursor::getCursorDecl(cursor); 3388 // Don't visit synthesized ObjC methods, since they have no syntatic 3389 // representation in the source. 3390 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 3391 if (MD->isSynthesized()) 3392 return CXChildVisit_Continue; 3393 } 3394 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 3395 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) { 3396 TypeLoc TL = TI->getTypeLoc(); 3397 SourceLocation TLoc = TL.getSourceRange().getBegin(); 3398 if (TLoc.isValid() && 3399 SrcMgr.isBeforeInTranslationUnit(TLoc, L)) 3400 cursorRange.setBegin(TLoc); 3401 } 3402 } 3403 } 3404 3405 // If the location of the cursor occurs within a macro instantiation, record 3406 // the spelling location of the cursor in our annotation map. We can then 3407 // paper over the token labelings during a post-processing step to try and 3408 // get cursor mappings for tokens that are the *arguments* of a macro 3409 // instantiation. 3410 if (L.isMacroID()) { 3411 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding(); 3412 // Only invalidate the old annotation if it isn't part of a preprocessing 3413 // directive. Here we assume that the default construction of CXCursor 3414 // results in CXCursor.kind being an initialized value (i.e., 0). If 3415 // this isn't the case, we can fix by doing lookup + insertion. 3416 3417 CXCursor &oldC = Annotated[rawEncoding]; 3418 if (!clang_isPreprocessing(oldC.kind)) 3419 oldC = cursor; 3420 } 3421 3422 const enum CXCursorKind K = clang_getCursorKind(parent); 3423 const CXCursor updateC = 3424 (clang_isInvalid(K) || K == CXCursor_TranslationUnit) 3425 ? clang_getNullCursor() : parent; 3426 3427 while (MoreTokens()) { 3428 const unsigned I = NextToken(); 3429 SourceLocation TokLoc = GetTokenLoc(I); 3430 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 3431 case RangeBefore: 3432 Cursors[I] = updateC; 3433 AdvanceToken(); 3434 continue; 3435 case RangeAfter: 3436 case RangeOverlap: 3437 break; 3438 } 3439 break; 3440 } 3441 3442 // Visit children to get their cursor information. 3443 const unsigned BeforeChildren = NextToken(); 3444 VisitChildren(cursor); 3445 const unsigned AfterChildren = NextToken(); 3446 3447 // Adjust 'Last' to the last token within the extent of the cursor. 3448 while (MoreTokens()) { 3449 const unsigned I = NextToken(); 3450 SourceLocation TokLoc = GetTokenLoc(I); 3451 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 3452 case RangeBefore: 3453 assert(0 && "Infeasible"); 3454 case RangeAfter: 3455 break; 3456 case RangeOverlap: 3457 Cursors[I] = updateC; 3458 AdvanceToken(); 3459 continue; 3460 } 3461 break; 3462 } 3463 const unsigned Last = NextToken(); 3464 3465 // Scan the tokens that are at the beginning of the cursor, but are not 3466 // capture by the child cursors. 3467 3468 // For AST elements within macros, rely on a post-annotate pass to 3469 // to correctly annotate the tokens with cursors. Otherwise we can 3470 // get confusing results of having tokens that map to cursors that really 3471 // are expanded by an instantiation. 3472 if (L.isMacroID()) 3473 cursor = clang_getNullCursor(); 3474 3475 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) { 3476 if (!clang_isInvalid(clang_getCursorKind(Cursors[I]))) 3477 break; 3478 Cursors[I] = cursor; 3479 } 3480 // Scan the tokens that are at the end of the cursor, but are not captured 3481 // but the child cursors. 3482 for (unsigned I = AfterChildren; I != Last; ++I) 3483 Cursors[I] = cursor; 3484 3485 TokIdx = Last; 3486 return CXChildVisit_Continue; 3487} 3488 3489static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor, 3490 CXCursor parent, 3491 CXClientData client_data) { 3492 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent); 3493} 3494 3495extern "C" { 3496 3497void clang_annotateTokens(CXTranslationUnit TU, 3498 CXToken *Tokens, unsigned NumTokens, 3499 CXCursor *Cursors) { 3500 3501 if (NumTokens == 0 || !Tokens || !Cursors) 3502 return; 3503 3504 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU); 3505 if (!CXXUnit) { 3506 // Any token we don't specifically annotate will have a NULL cursor. 3507 const CXCursor &C = clang_getNullCursor(); 3508 for (unsigned I = 0; I != NumTokens; ++I) 3509 Cursors[I] = C; 3510 return; 3511 } 3512 3513 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 3514 3515 // Determine the region of interest, which contains all of the tokens. 3516 SourceRange RegionOfInterest; 3517 RegionOfInterest.setBegin(cxloc::translateSourceLocation( 3518 clang_getTokenLocation(TU, Tokens[0]))); 3519 RegionOfInterest.setEnd(cxloc::translateSourceLocation( 3520 clang_getTokenLocation(TU, 3521 Tokens[NumTokens - 1]))); 3522 3523 // A mapping from the source locations found when re-lexing or traversing the 3524 // region of interest to the corresponding cursors. 3525 AnnotateTokensData Annotated; 3526 3527 // Relex the tokens within the source range to look for preprocessing 3528 // directives. 3529 SourceManager &SourceMgr = CXXUnit->getSourceManager(); 3530 std::pair<FileID, unsigned> BeginLocInfo 3531 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin()); 3532 std::pair<FileID, unsigned> EndLocInfo 3533 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd()); 3534 3535 llvm::StringRef Buffer; 3536 bool Invalid = false; 3537 if (BeginLocInfo.first == EndLocInfo.first && 3538 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) && 3539 !Invalid) { 3540 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first), 3541 CXXUnit->getASTContext().getLangOptions(), 3542 Buffer.begin(), Buffer.data() + BeginLocInfo.second, 3543 Buffer.end()); 3544 Lex.SetCommentRetentionState(true); 3545 3546 // Lex tokens in raw mode until we hit the end of the range, to avoid 3547 // entering #includes or expanding macros. 3548 while (true) { 3549 Token Tok; 3550 Lex.LexFromRawLexer(Tok); 3551 3552 reprocess: 3553 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) { 3554 // We have found a preprocessing directive. Gobble it up so that we 3555 // don't see it while preprocessing these tokens later, but keep track of 3556 // all of the token locations inside this preprocessing directive so that 3557 // we can annotate them appropriately. 3558 // 3559 // FIXME: Some simple tests here could identify macro definitions and 3560 // #undefs, to provide specific cursor kinds for those. 3561 std::vector<SourceLocation> Locations; 3562 do { 3563 Locations.push_back(Tok.getLocation()); 3564 Lex.LexFromRawLexer(Tok); 3565 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof)); 3566 3567 using namespace cxcursor; 3568 CXCursor Cursor 3569 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(), 3570 Locations.back()), 3571 CXXUnit); 3572 for (unsigned I = 0, N = Locations.size(); I != N; ++I) { 3573 Annotated[Locations[I].getRawEncoding()] = Cursor; 3574 } 3575 3576 if (Tok.isAtStartOfLine()) 3577 goto reprocess; 3578 3579 continue; 3580 } 3581 3582 if (Tok.is(tok::eof)) 3583 break; 3584 } 3585 } 3586 3587 // Annotate all of the source locations in the region of interest that map to 3588 // a specific cursor. 3589 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens, 3590 CXXUnit, RegionOfInterest); 3591 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit)); 3592} 3593} // end: extern "C" 3594 3595//===----------------------------------------------------------------------===// 3596// Operations for querying linkage of a cursor. 3597//===----------------------------------------------------------------------===// 3598 3599extern "C" { 3600CXLinkageKind clang_getCursorLinkage(CXCursor cursor) { 3601 if (!clang_isDeclaration(cursor.kind)) 3602 return CXLinkage_Invalid; 3603 3604 Decl *D = cxcursor::getCursorDecl(cursor); 3605 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D)) 3606 switch (ND->getLinkage()) { 3607 case NoLinkage: return CXLinkage_NoLinkage; 3608 case InternalLinkage: return CXLinkage_Internal; 3609 case UniqueExternalLinkage: return CXLinkage_UniqueExternal; 3610 case ExternalLinkage: return CXLinkage_External; 3611 }; 3612 3613 return CXLinkage_Invalid; 3614} 3615} // end: extern "C" 3616 3617//===----------------------------------------------------------------------===// 3618// Operations for querying language of a cursor. 3619//===----------------------------------------------------------------------===// 3620 3621static CXLanguageKind getDeclLanguage(const Decl *D) { 3622 switch (D->getKind()) { 3623 default: 3624 break; 3625 case Decl::ImplicitParam: 3626 case Decl::ObjCAtDefsField: 3627 case Decl::ObjCCategory: 3628 case Decl::ObjCCategoryImpl: 3629 case Decl::ObjCClass: 3630 case Decl::ObjCCompatibleAlias: 3631 case Decl::ObjCForwardProtocol: 3632 case Decl::ObjCImplementation: 3633 case Decl::ObjCInterface: 3634 case Decl::ObjCIvar: 3635 case Decl::ObjCMethod: 3636 case Decl::ObjCProperty: 3637 case Decl::ObjCPropertyImpl: 3638 case Decl::ObjCProtocol: 3639 return CXLanguage_ObjC; 3640 case Decl::CXXConstructor: 3641 case Decl::CXXConversion: 3642 case Decl::CXXDestructor: 3643 case Decl::CXXMethod: 3644 case Decl::CXXRecord: 3645 case Decl::ClassTemplate: 3646 case Decl::ClassTemplatePartialSpecialization: 3647 case Decl::ClassTemplateSpecialization: 3648 case Decl::Friend: 3649 case Decl::FriendTemplate: 3650 case Decl::FunctionTemplate: 3651 case Decl::LinkageSpec: 3652 case Decl::Namespace: 3653 case Decl::NamespaceAlias: 3654 case Decl::NonTypeTemplateParm: 3655 case Decl::StaticAssert: 3656 case Decl::TemplateTemplateParm: 3657 case Decl::TemplateTypeParm: 3658 case Decl::UnresolvedUsingTypename: 3659 case Decl::UnresolvedUsingValue: 3660 case Decl::Using: 3661 case Decl::UsingDirective: 3662 case Decl::UsingShadow: 3663 return CXLanguage_CPlusPlus; 3664 } 3665 3666 return CXLanguage_C; 3667} 3668 3669extern "C" { 3670 3671enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) { 3672 if (clang_isDeclaration(cursor.kind)) 3673 if (Decl *D = cxcursor::getCursorDecl(cursor)) { 3674 if (D->hasAttr<UnavailableAttr>() || 3675 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())) 3676 return CXAvailability_Available; 3677 3678 if (D->hasAttr<DeprecatedAttr>()) 3679 return CXAvailability_Deprecated; 3680 } 3681 3682 return CXAvailability_Available; 3683} 3684 3685CXLanguageKind clang_getCursorLanguage(CXCursor cursor) { 3686 if (clang_isDeclaration(cursor.kind)) 3687 return getDeclLanguage(cxcursor::getCursorDecl(cursor)); 3688 3689 return CXLanguage_Invalid; 3690} 3691} // end: extern "C" 3692 3693 3694//===----------------------------------------------------------------------===// 3695// C++ AST instrospection. 3696//===----------------------------------------------------------------------===// 3697 3698extern "C" { 3699unsigned clang_CXXMethod_isStatic(CXCursor C) { 3700 if (!clang_isDeclaration(C.kind)) 3701 return 0; 3702 3703 CXXMethodDecl *Method = 0; 3704 Decl *D = cxcursor::getCursorDecl(C); 3705 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D)) 3706 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl()); 3707 else 3708 Method = dyn_cast_or_null<CXXMethodDecl>(D); 3709 return (Method && Method->isStatic()) ? 1 : 0; 3710} 3711 3712} // end: extern "C" 3713 3714//===----------------------------------------------------------------------===// 3715// Attribute introspection. 3716//===----------------------------------------------------------------------===// 3717 3718extern "C" { 3719CXType clang_getIBOutletCollectionType(CXCursor C) { 3720 if (C.kind != CXCursor_IBOutletCollectionAttr) 3721 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C)); 3722 3723 IBOutletCollectionAttr *A = 3724 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C)); 3725 3726 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C)); 3727} 3728} // end: extern "C" 3729 3730//===----------------------------------------------------------------------===// 3731// CXString Operations. 3732//===----------------------------------------------------------------------===// 3733 3734extern "C" { 3735const char *clang_getCString(CXString string) { 3736 return string.Spelling; 3737} 3738 3739void clang_disposeString(CXString string) { 3740 if (string.MustFreeString && string.Spelling) 3741 free((void*)string.Spelling); 3742} 3743 3744} // end: extern "C" 3745 3746namespace clang { namespace cxstring { 3747CXString createCXString(const char *String, bool DupString){ 3748 CXString Str; 3749 if (DupString) { 3750 Str.Spelling = strdup(String); 3751 Str.MustFreeString = 1; 3752 } else { 3753 Str.Spelling = String; 3754 Str.MustFreeString = 0; 3755 } 3756 return Str; 3757} 3758 3759CXString createCXString(llvm::StringRef String, bool DupString) { 3760 CXString Result; 3761 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) { 3762 char *Spelling = (char *)malloc(String.size() + 1); 3763 memmove(Spelling, String.data(), String.size()); 3764 Spelling[String.size()] = 0; 3765 Result.Spelling = Spelling; 3766 Result.MustFreeString = 1; 3767 } else { 3768 Result.Spelling = String.data(); 3769 Result.MustFreeString = 0; 3770 } 3771 return Result; 3772} 3773}} 3774 3775//===----------------------------------------------------------------------===// 3776// Misc. utility functions. 3777//===----------------------------------------------------------------------===// 3778 3779extern "C" { 3780 3781CXString clang_getClangVersion() { 3782 return createCXString(getClangFullVersion()); 3783} 3784 3785} // end: extern "C" 3786