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