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