CIndex.cpp revision 36897b05ca2886e287f01802614bc10cbadcec22
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 // FIXME: Provide a multi-reference of some kind for all of the declarations 1019 // that the using declaration refers to. We don't have this kind of cursor 1020 // yet. 1021 1022 return VisitDeclarationNameInfo(D->getNameInfo()); 1023} 1024 1025bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { 1026 // Visit nested-name-specifier. 1027 if (NestedNameSpecifier *Qualifier = D->getQualifier()) 1028 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange())) 1029 return true; 1030 1031 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(), 1032 D->getIdentLocation(), TU)); 1033} 1034 1035bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) { 1036 // Visit nested-name-specifier. 1037 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier()) 1038 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange())) 1039 return true; 1040 1041 return VisitDeclarationNameInfo(D->getNameInfo()); 1042} 1043 1044bool CursorVisitor::VisitUnresolvedUsingTypenameDecl( 1045 UnresolvedUsingTypenameDecl *D) { 1046 // Visit nested-name-specifier. 1047 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier()) 1048 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange())) 1049 return true; 1050 1051 return false; 1052} 1053 1054bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) { 1055 switch (Name.getName().getNameKind()) { 1056 case clang::DeclarationName::Identifier: 1057 case clang::DeclarationName::CXXLiteralOperatorName: 1058 case clang::DeclarationName::CXXOperatorName: 1059 case clang::DeclarationName::CXXUsingDirective: 1060 return false; 1061 1062 case clang::DeclarationName::CXXConstructorName: 1063 case clang::DeclarationName::CXXDestructorName: 1064 case clang::DeclarationName::CXXConversionFunctionName: 1065 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo()) 1066 return Visit(TSInfo->getTypeLoc()); 1067 return false; 1068 1069 case clang::DeclarationName::ObjCZeroArgSelector: 1070 case clang::DeclarationName::ObjCOneArgSelector: 1071 case clang::DeclarationName::ObjCMultiArgSelector: 1072 // FIXME: Per-identifier location info? 1073 return false; 1074 } 1075 1076 return false; 1077} 1078 1079bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS, 1080 SourceRange Range) { 1081 // FIXME: This whole routine is a hack to work around the lack of proper 1082 // source information in nested-name-specifiers (PR5791). Since we do have 1083 // a beginning source location, we can visit the first component of the 1084 // nested-name-specifier, if it's a single-token component. 1085 if (!NNS) 1086 return false; 1087 1088 // Get the first component in the nested-name-specifier. 1089 while (NestedNameSpecifier *Prefix = NNS->getPrefix()) 1090 NNS = Prefix; 1091 1092 switch (NNS->getKind()) { 1093 case NestedNameSpecifier::Namespace: 1094 // FIXME: The token at this source location might actually have been a 1095 // namespace alias, but we don't model that. Lame! 1096 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(), 1097 TU)); 1098 1099 case NestedNameSpecifier::TypeSpec: { 1100 // If the type has a form where we know that the beginning of the source 1101 // range matches up with a reference cursor. Visit the appropriate reference 1102 // cursor. 1103 Type *T = NNS->getAsType(); 1104 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T)) 1105 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU)); 1106 if (const TagType *Tag = dyn_cast<TagType>(T)) 1107 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU)); 1108 if (const TemplateSpecializationType *TST 1109 = dyn_cast<TemplateSpecializationType>(T)) 1110 return VisitTemplateName(TST->getTemplateName(), Range.getBegin()); 1111 break; 1112 } 1113 1114 case NestedNameSpecifier::TypeSpecWithTemplate: 1115 case NestedNameSpecifier::Global: 1116 case NestedNameSpecifier::Identifier: 1117 break; 1118 } 1119 1120 return false; 1121} 1122 1123bool CursorVisitor::VisitTemplateParameters( 1124 const TemplateParameterList *Params) { 1125 if (!Params) 1126 return false; 1127 1128 for (TemplateParameterList::const_iterator P = Params->begin(), 1129 PEnd = Params->end(); 1130 P != PEnd; ++P) { 1131 if (Visit(MakeCXCursor(*P, TU))) 1132 return true; 1133 } 1134 1135 return false; 1136} 1137 1138bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) { 1139 switch (Name.getKind()) { 1140 case TemplateName::Template: 1141 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU)); 1142 1143 case TemplateName::OverloadedTemplate: 1144 // FIXME: We need a way to return multiple lookup results in a single 1145 // cursor. 1146 return false; 1147 1148 case TemplateName::DependentTemplate: 1149 // FIXME: Visit nested-name-specifier. 1150 return false; 1151 1152 case TemplateName::QualifiedTemplate: 1153 // FIXME: Visit nested-name-specifier. 1154 return Visit(MakeCursorTemplateRef( 1155 Name.getAsQualifiedTemplateName()->getDecl(), 1156 Loc, TU)); 1157 } 1158 1159 return false; 1160} 1161 1162bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) { 1163 switch (TAL.getArgument().getKind()) { 1164 case TemplateArgument::Null: 1165 case TemplateArgument::Integral: 1166 return false; 1167 1168 case TemplateArgument::Pack: 1169 // FIXME: Implement when variadic templates come along. 1170 return false; 1171 1172 case TemplateArgument::Type: 1173 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo()) 1174 return Visit(TSInfo->getTypeLoc()); 1175 return false; 1176 1177 case TemplateArgument::Declaration: 1178 if (Expr *E = TAL.getSourceDeclExpression()) 1179 return Visit(MakeCXCursor(E, StmtParent, TU)); 1180 return false; 1181 1182 case TemplateArgument::Expression: 1183 if (Expr *E = TAL.getSourceExpression()) 1184 return Visit(MakeCXCursor(E, StmtParent, TU)); 1185 return false; 1186 1187 case TemplateArgument::Template: 1188 return VisitTemplateName(TAL.getArgument().getAsTemplate(), 1189 TAL.getTemplateNameLoc()); 1190 } 1191 1192 return false; 1193} 1194 1195bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) { 1196 return VisitDeclContext(D); 1197} 1198 1199bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 1200 return Visit(TL.getUnqualifiedLoc()); 1201} 1202 1203bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 1204 ASTContext &Context = TU->getASTContext(); 1205 1206 // Some builtin types (such as Objective-C's "id", "sel", and 1207 // "Class") have associated declarations. Create cursors for those. 1208 QualType VisitType; 1209 switch (TL.getType()->getAs<BuiltinType>()->getKind()) { 1210 case BuiltinType::Void: 1211 case BuiltinType::Bool: 1212 case BuiltinType::Char_U: 1213 case BuiltinType::UChar: 1214 case BuiltinType::Char16: 1215 case BuiltinType::Char32: 1216 case BuiltinType::UShort: 1217 case BuiltinType::UInt: 1218 case BuiltinType::ULong: 1219 case BuiltinType::ULongLong: 1220 case BuiltinType::UInt128: 1221 case BuiltinType::Char_S: 1222 case BuiltinType::SChar: 1223 case BuiltinType::WChar: 1224 case BuiltinType::Short: 1225 case BuiltinType::Int: 1226 case BuiltinType::Long: 1227 case BuiltinType::LongLong: 1228 case BuiltinType::Int128: 1229 case BuiltinType::Float: 1230 case BuiltinType::Double: 1231 case BuiltinType::LongDouble: 1232 case BuiltinType::NullPtr: 1233 case BuiltinType::Overload: 1234 case BuiltinType::Dependent: 1235 break; 1236 1237 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor? 1238 break; 1239 1240 case BuiltinType::ObjCId: 1241 VisitType = Context.getObjCIdType(); 1242 break; 1243 1244 case BuiltinType::ObjCClass: 1245 VisitType = Context.getObjCClassType(); 1246 break; 1247 1248 case BuiltinType::ObjCSel: 1249 VisitType = Context.getObjCSelType(); 1250 break; 1251 } 1252 1253 if (!VisitType.isNull()) { 1254 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>()) 1255 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(), 1256 TU)); 1257 } 1258 1259 return false; 1260} 1261 1262bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) { 1263 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU)); 1264} 1265 1266bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) { 1267 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); 1268} 1269 1270bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) { 1271 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); 1272} 1273 1274bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) { 1275 // FIXME: We can't visit the template template parameter, but there's 1276 // no context information with which we can match up the depth/index in the 1277 // type to the appropriate 1278 return false; 1279} 1280 1281bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 1282 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU))) 1283 return true; 1284 1285 return false; 1286} 1287 1288bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 1289 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc())) 1290 return true; 1291 1292 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) { 1293 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I), 1294 TU))) 1295 return true; 1296 } 1297 1298 return false; 1299} 1300 1301bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 1302 return Visit(TL.getPointeeLoc()); 1303} 1304 1305bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) { 1306 return Visit(TL.getPointeeLoc()); 1307} 1308 1309bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 1310 return Visit(TL.getPointeeLoc()); 1311} 1312 1313bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 1314 return Visit(TL.getPointeeLoc()); 1315} 1316 1317bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 1318 return Visit(TL.getPointeeLoc()); 1319} 1320 1321bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 1322 return Visit(TL.getPointeeLoc()); 1323} 1324 1325bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL, 1326 bool SkipResultType) { 1327 if (!SkipResultType && Visit(TL.getResultLoc())) 1328 return true; 1329 1330 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I) 1331 if (Decl *D = TL.getArg(I)) 1332 if (Visit(MakeCXCursor(D, TU))) 1333 return true; 1334 1335 return false; 1336} 1337 1338bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) { 1339 if (Visit(TL.getElementLoc())) 1340 return true; 1341 1342 if (Expr *Size = TL.getSizeExpr()) 1343 return Visit(MakeCXCursor(Size, StmtParent, TU)); 1344 1345 return false; 1346} 1347 1348bool CursorVisitor::VisitTemplateSpecializationTypeLoc( 1349 TemplateSpecializationTypeLoc TL) { 1350 // Visit the template name. 1351 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(), 1352 TL.getTemplateNameLoc())) 1353 return true; 1354 1355 // Visit the template arguments. 1356 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I) 1357 if (VisitTemplateArgumentLoc(TL.getArgLoc(I))) 1358 return true; 1359 1360 return false; 1361} 1362 1363bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 1364 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU)); 1365} 1366 1367bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 1368 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo()) 1369 return Visit(TSInfo->getTypeLoc()); 1370 1371 return false; 1372} 1373 1374bool CursorVisitor::VisitStmt(Stmt *S) { 1375 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end(); 1376 Child != ChildEnd; ++Child) { 1377 if (Stmt *C = *Child) 1378 if (Visit(MakeCXCursor(C, StmtParent, TU))) 1379 return true; 1380 } 1381 1382 return false; 1383} 1384 1385bool CursorVisitor::VisitCaseStmt(CaseStmt *S) { 1386 // Specially handle CaseStmts because they can be nested, e.g.: 1387 // 1388 // case 1: 1389 // case 2: 1390 // 1391 // In this case the second CaseStmt is the child of the first. Walking 1392 // these recursively can blow out the stack. 1393 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU); 1394 while (true) { 1395 // Set the Parent field to Cursor, then back to its old value once we're 1396 // done. 1397 SetParentRAII SetParent(Parent, StmtParent, Cursor); 1398 1399 if (Stmt *LHS = S->getLHS()) 1400 if (Visit(MakeCXCursor(LHS, StmtParent, TU))) 1401 return true; 1402 if (Stmt *RHS = S->getRHS()) 1403 if (Visit(MakeCXCursor(RHS, StmtParent, TU))) 1404 return true; 1405 if (Stmt *SubStmt = S->getSubStmt()) { 1406 if (!isa<CaseStmt>(SubStmt)) 1407 return Visit(MakeCXCursor(SubStmt, StmtParent, TU)); 1408 1409 // Specially handle 'CaseStmt' so that we don't blow out the stack. 1410 CaseStmt *CS = cast<CaseStmt>(SubStmt); 1411 Cursor = MakeCXCursor(CS, StmtParent, TU); 1412 if (RegionOfInterest.isValid()) { 1413 SourceRange Range = CS->getSourceRange(); 1414 if (Range.isInvalid() || CompareRegionOfInterest(Range)) 1415 return false; 1416 } 1417 1418 switch (Visitor(Cursor, Parent, ClientData)) { 1419 case CXChildVisit_Break: return true; 1420 case CXChildVisit_Continue: return false; 1421 case CXChildVisit_Recurse: 1422 // Perform tail-recursion manually. 1423 S = CS; 1424 continue; 1425 } 1426 } 1427 return false; 1428 } 1429} 1430 1431bool CursorVisitor::VisitDeclStmt(DeclStmt *S) { 1432 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end(); 1433 D != DEnd; ++D) { 1434 if (*D && Visit(MakeCXCursor(*D, TU))) 1435 return true; 1436 } 1437 1438 return false; 1439} 1440 1441bool CursorVisitor::VisitGotoStmt(GotoStmt *S) { 1442 return Visit(MakeCursorLabelRef(S->getLabel(), S->getLabelLoc(), TU)); 1443} 1444 1445bool CursorVisitor::VisitIfStmt(IfStmt *S) { 1446 if (VarDecl *Var = S->getConditionVariable()) { 1447 if (Visit(MakeCXCursor(Var, TU))) 1448 return true; 1449 } 1450 1451 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU))) 1452 return true; 1453 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU))) 1454 return true; 1455 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU))) 1456 return true; 1457 1458 return false; 1459} 1460 1461bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) { 1462 if (VarDecl *Var = S->getConditionVariable()) { 1463 if (Visit(MakeCXCursor(Var, TU))) 1464 return true; 1465 } 1466 1467 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU))) 1468 return true; 1469 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU))) 1470 return true; 1471 1472 return false; 1473} 1474 1475bool CursorVisitor::VisitWhileStmt(WhileStmt *S) { 1476 if (VarDecl *Var = S->getConditionVariable()) { 1477 if (Visit(MakeCXCursor(Var, TU))) 1478 return true; 1479 } 1480 1481 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU))) 1482 return true; 1483 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU))) 1484 return true; 1485 1486 return false; 1487} 1488 1489bool CursorVisitor::VisitForStmt(ForStmt *S) { 1490 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU))) 1491 return true; 1492 if (VarDecl *Var = S->getConditionVariable()) { 1493 if (Visit(MakeCXCursor(Var, TU))) 1494 return true; 1495 } 1496 1497 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU))) 1498 return true; 1499 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU))) 1500 return true; 1501 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU))) 1502 return true; 1503 1504 return false; 1505} 1506 1507bool CursorVisitor::VisitDeclRefExpr(DeclRefExpr *E) { 1508 // Visit nested-name-specifier, if present. 1509 if (NestedNameSpecifier *Qualifier = E->getQualifier()) 1510 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange())) 1511 return true; 1512 1513 // Visit declaration name. 1514 if (VisitDeclarationNameInfo(E->getNameInfo())) 1515 return true; 1516 1517 // Visit explicitly-specified template arguments. 1518 if (E->hasExplicitTemplateArgs()) { 1519 ExplicitTemplateArgumentList &Args = E->getExplicitTemplateArgs(); 1520 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(), 1521 *ArgEnd = Arg + Args.NumTemplateArgs; 1522 Arg != ArgEnd; ++Arg) 1523 if (VisitTemplateArgumentLoc(*Arg)) 1524 return true; 1525 } 1526 1527 return false; 1528} 1529 1530bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 1531 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU))) 1532 return true; 1533 1534 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU))) 1535 return true; 1536 1537 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) 1538 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU))) 1539 return true; 1540 1541 return false; 1542} 1543 1544bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) { 1545 if (D->isDefinition()) { 1546 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(), 1547 E = D->bases_end(); I != E; ++I) { 1548 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU))) 1549 return true; 1550 } 1551 } 1552 1553 return VisitTagDecl(D); 1554} 1555 1556 1557bool CursorVisitor::VisitBlockExpr(BlockExpr *B) { 1558 return Visit(B->getBlockDecl()); 1559} 1560 1561bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) { 1562 // Visit the type into which we're computing an offset. 1563 if (Visit(E->getTypeSourceInfo()->getTypeLoc())) 1564 return true; 1565 1566 // Visit the components of the offsetof expression. 1567 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) { 1568 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 1569 const OffsetOfNode &Node = E->getComponent(I); 1570 switch (Node.getKind()) { 1571 case OffsetOfNode::Array: 1572 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()), 1573 StmtParent, TU))) 1574 return true; 1575 break; 1576 1577 case OffsetOfNode::Field: 1578 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(), 1579 TU))) 1580 return true; 1581 break; 1582 1583 case OffsetOfNode::Identifier: 1584 case OffsetOfNode::Base: 1585 continue; 1586 } 1587 } 1588 1589 return false; 1590} 1591 1592bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) { 1593 if (E->isArgumentType()) { 1594 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo()) 1595 return Visit(TSInfo->getTypeLoc()); 1596 1597 return false; 1598 } 1599 1600 return VisitExpr(E); 1601} 1602 1603bool CursorVisitor::VisitMemberExpr(MemberExpr *E) { 1604 // Visit the base expression. 1605 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU))) 1606 return true; 1607 1608 // Visit the nested-name-specifier 1609 if (NestedNameSpecifier *Qualifier = E->getQualifier()) 1610 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange())) 1611 return true; 1612 1613 // Visit the declaration name. 1614 if (VisitDeclarationNameInfo(E->getMemberNameInfo())) 1615 return true; 1616 1617 // Visit the explicitly-specified template arguments, if any. 1618 if (E->hasExplicitTemplateArgs()) { 1619 for (const TemplateArgumentLoc *Arg = E->getTemplateArgs(), 1620 *ArgEnd = Arg + E->getNumTemplateArgs(); 1621 Arg != ArgEnd; 1622 ++Arg) { 1623 if (VisitTemplateArgumentLoc(*Arg)) 1624 return true; 1625 } 1626 } 1627 1628 return false; 1629} 1630 1631bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) { 1632 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten()) 1633 if (Visit(TSInfo->getTypeLoc())) 1634 return true; 1635 1636 return VisitCastExpr(E); 1637} 1638 1639bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 1640 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo()) 1641 if (Visit(TSInfo->getTypeLoc())) 1642 return true; 1643 1644 return VisitExpr(E); 1645} 1646 1647bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) { 1648 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU)); 1649} 1650 1651bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) { 1652 return Visit(E->getArgTInfo1()->getTypeLoc()) || 1653 Visit(E->getArgTInfo2()->getTypeLoc()); 1654} 1655 1656bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) { 1657 if (Visit(E->getWrittenTypeInfo()->getTypeLoc())) 1658 return true; 1659 1660 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU)); 1661} 1662 1663bool CursorVisitor::VisitInitListExpr(InitListExpr *E) { 1664 // We care about the syntactic form of the initializer list, only. 1665 return VisitExpr(E->getSyntacticForm()); 1666} 1667 1668bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) { 1669 // Visit the designators. 1670 typedef DesignatedInitExpr::Designator Designator; 1671 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(), 1672 DEnd = E->designators_end(); 1673 D != DEnd; ++D) { 1674 if (D->isFieldDesignator()) { 1675 if (FieldDecl *Field = D->getField()) 1676 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU))) 1677 return true; 1678 1679 continue; 1680 } 1681 1682 if (D->isArrayDesignator()) { 1683 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU))) 1684 return true; 1685 1686 continue; 1687 } 1688 1689 assert(D->isArrayRangeDesignator() && "Unknown designator kind"); 1690 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) || 1691 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU))) 1692 return true; 1693 } 1694 1695 // Visit the initializer value itself. 1696 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU)); 1697} 1698 1699bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) { 1700 if (E->isTypeOperand()) { 1701 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo()) 1702 return Visit(TSInfo->getTypeLoc()); 1703 1704 return false; 1705 } 1706 1707 return VisitExpr(E); 1708} 1709 1710bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) { 1711 if (E->isTypeOperand()) { 1712 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo()) 1713 return Visit(TSInfo->getTypeLoc()); 1714 1715 return false; 1716 } 1717 1718 return VisitExpr(E); 1719} 1720 1721bool CursorVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) { 1722 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo()) 1723 return Visit(TSInfo->getTypeLoc()); 1724 1725 return VisitExpr(E); 1726} 1727 1728bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) { 1729 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo()) 1730 return Visit(TSInfo->getTypeLoc()); 1731 1732 return false; 1733} 1734 1735bool CursorVisitor::VisitCXXNewExpr(CXXNewExpr *E) { 1736 // Visit placement arguments. 1737 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) 1738 if (Visit(MakeCXCursor(E->getPlacementArg(I), StmtParent, TU))) 1739 return true; 1740 1741 // Visit the allocated type. 1742 if (TypeSourceInfo *TSInfo = E->getAllocatedTypeSourceInfo()) 1743 if (Visit(TSInfo->getTypeLoc())) 1744 return true; 1745 1746 // Visit the array size, if any. 1747 if (E->isArray() && Visit(MakeCXCursor(E->getArraySize(), StmtParent, TU))) 1748 return true; 1749 1750 // Visit the initializer or constructor arguments. 1751 for (unsigned I = 0, N = E->getNumConstructorArgs(); I != N; ++I) 1752 if (Visit(MakeCXCursor(E->getConstructorArg(I), StmtParent, TU))) 1753 return true; 1754 1755 return false; 1756} 1757 1758bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) { 1759 // Visit base expression. 1760 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU))) 1761 return true; 1762 1763 // Visit the nested-name-specifier. 1764 if (NestedNameSpecifier *Qualifier = E->getQualifier()) 1765 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange())) 1766 return true; 1767 1768 // Visit the scope type that looks disturbingly like the nested-name-specifier 1769 // but isn't. 1770 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo()) 1771 if (Visit(TSInfo->getTypeLoc())) 1772 return true; 1773 1774 // Visit the name of the type being destroyed. 1775 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo()) 1776 if (Visit(TSInfo->getTypeLoc())) 1777 return true; 1778 1779 return false; 1780} 1781 1782bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) { 1783 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc()); 1784} 1785 1786bool CursorVisitor::VisitOverloadExpr(OverloadExpr *E) { 1787 // Visit the nested-name-specifier. 1788 if (NestedNameSpecifier *Qualifier = E->getQualifier()) 1789 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange())) 1790 return true; 1791 1792 // Visit the declaration name. 1793 if (VisitDeclarationNameInfo(E->getNameInfo())) 1794 return true; 1795 1796 // Visit the explicitly-specified template arguments. 1797 if (const ExplicitTemplateArgumentList *ArgList 1798 = E->getOptionalExplicitTemplateArgs()) { 1799 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(), 1800 *ArgEnd = Arg + ArgList->NumTemplateArgs; 1801 Arg != ArgEnd; ++Arg) { 1802 if (VisitTemplateArgumentLoc(*Arg)) 1803 return true; 1804 } 1805 } 1806 1807 // FIXME: We don't have a way to visit all of the declarations referenced 1808 // here. 1809 return false; 1810} 1811 1812bool CursorVisitor::VisitDependentScopeDeclRefExpr( 1813 DependentScopeDeclRefExpr *E) { 1814 // Visit the nested-name-specifier. 1815 if (NestedNameSpecifier *Qualifier = E->getQualifier()) 1816 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange())) 1817 return true; 1818 1819 // Visit the declaration name. 1820 if (VisitDeclarationNameInfo(E->getNameInfo())) 1821 return true; 1822 1823 // Visit the explicitly-specified template arguments. 1824 if (const ExplicitTemplateArgumentList *ArgList 1825 = E->getOptionalExplicitTemplateArgs()) { 1826 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(), 1827 *ArgEnd = Arg + ArgList->NumTemplateArgs; 1828 Arg != ArgEnd; ++Arg) { 1829 if (VisitTemplateArgumentLoc(*Arg)) 1830 return true; 1831 } 1832 } 1833 1834 return false; 1835} 1836 1837bool CursorVisitor::VisitCXXUnresolvedConstructExpr( 1838 CXXUnresolvedConstructExpr *E) { 1839 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo()) 1840 if (Visit(TSInfo->getTypeLoc())) 1841 return true; 1842 1843 return VisitExpr(E); 1844} 1845 1846bool CursorVisitor::VisitCXXDependentScopeMemberExpr( 1847 CXXDependentScopeMemberExpr *E) { 1848 // Visit the base expression, if there is one. 1849 if (!E->isImplicitAccess() && 1850 Visit(MakeCXCursor(E->getBase(), StmtParent, TU))) 1851 return true; 1852 1853 // Visit the nested-name-specifier. 1854 if (NestedNameSpecifier *Qualifier = E->getQualifier()) 1855 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange())) 1856 return true; 1857 1858 // Visit the declaration name. 1859 if (VisitDeclarationNameInfo(E->getMemberNameInfo())) 1860 return true; 1861 1862 // Visit the explicitly-specified template arguments. 1863 if (const ExplicitTemplateArgumentList *ArgList 1864 = E->getOptionalExplicitTemplateArgs()) { 1865 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(), 1866 *ArgEnd = Arg + ArgList->NumTemplateArgs; 1867 Arg != ArgEnd; ++Arg) { 1868 if (VisitTemplateArgumentLoc(*Arg)) 1869 return true; 1870 } 1871 } 1872 1873 return false; 1874} 1875 1876bool CursorVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) { 1877 // Visit the base expression, if there is one. 1878 if (!E->isImplicitAccess() && 1879 Visit(MakeCXCursor(E->getBase(), StmtParent, TU))) 1880 return true; 1881 1882 return VisitOverloadExpr(E); 1883} 1884 1885bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) { 1886 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo()) 1887 if (Visit(TSInfo->getTypeLoc())) 1888 return true; 1889 1890 return VisitExpr(E); 1891} 1892 1893bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) { 1894 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc()); 1895} 1896 1897 1898bool CursorVisitor::VisitAttributes(Decl *D) { 1899 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end(); 1900 i != e; ++i) 1901 if (Visit(MakeCXCursor(*i, D, TU))) 1902 return true; 1903 1904 return false; 1905} 1906 1907extern "C" { 1908CXIndex clang_createIndex(int excludeDeclarationsFromPCH, 1909 int displayDiagnostics) { 1910 // We use crash recovery to make some of our APIs more reliable, implicitly 1911 // enable it. 1912 llvm::CrashRecoveryContext::Enable(); 1913 1914 CIndexer *CIdxr = new CIndexer(); 1915 if (excludeDeclarationsFromPCH) 1916 CIdxr->setOnlyLocalDecls(); 1917 if (displayDiagnostics) 1918 CIdxr->setDisplayDiagnostics(); 1919 return CIdxr; 1920} 1921 1922void clang_disposeIndex(CXIndex CIdx) { 1923 if (CIdx) 1924 delete static_cast<CIndexer *>(CIdx); 1925 if (getenv("LIBCLANG_TIMING")) 1926 llvm::TimerGroup::printAll(llvm::errs()); 1927} 1928 1929void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) { 1930 if (CIdx) { 1931 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx); 1932 CXXIdx->setUseExternalASTGeneration(value); 1933 } 1934} 1935 1936CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx, 1937 const char *ast_filename) { 1938 if (!CIdx) 1939 return 0; 1940 1941 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx); 1942 1943 llvm::IntrusiveRefCntPtr<Diagnostic> Diags; 1944 return ASTUnit::LoadFromASTFile(ast_filename, Diags, 1945 CXXIdx->getOnlyLocalDecls(), 1946 0, 0, true); 1947} 1948 1949unsigned clang_defaultEditingTranslationUnitOptions() { 1950 return CXTranslationUnit_PrecompiledPreamble; 1951} 1952 1953CXTranslationUnit 1954clang_createTranslationUnitFromSourceFile(CXIndex CIdx, 1955 const char *source_filename, 1956 int num_command_line_args, 1957 const char * const *command_line_args, 1958 unsigned num_unsaved_files, 1959 struct CXUnsavedFile *unsaved_files) { 1960 return clang_parseTranslationUnit(CIdx, source_filename, 1961 command_line_args, num_command_line_args, 1962 unsaved_files, num_unsaved_files, 1963 CXTranslationUnit_DetailedPreprocessingRecord); 1964} 1965 1966struct ParseTranslationUnitInfo { 1967 CXIndex CIdx; 1968 const char *source_filename; 1969 const char *const *command_line_args; 1970 int num_command_line_args; 1971 struct CXUnsavedFile *unsaved_files; 1972 unsigned num_unsaved_files; 1973 unsigned options; 1974 CXTranslationUnit result; 1975}; 1976static void clang_parseTranslationUnit_Impl(void *UserData) { 1977 ParseTranslationUnitInfo *PTUI = 1978 static_cast<ParseTranslationUnitInfo*>(UserData); 1979 CXIndex CIdx = PTUI->CIdx; 1980 const char *source_filename = PTUI->source_filename; 1981 const char * const *command_line_args = PTUI->command_line_args; 1982 int num_command_line_args = PTUI->num_command_line_args; 1983 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files; 1984 unsigned num_unsaved_files = PTUI->num_unsaved_files; 1985 unsigned options = PTUI->options; 1986 PTUI->result = 0; 1987 1988 if (!CIdx) 1989 return; 1990 1991 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx); 1992 1993 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble; 1994 bool CompleteTranslationUnit 1995 = ((options & CXTranslationUnit_Incomplete) == 0); 1996 bool CacheCodeCompetionResults 1997 = options & CXTranslationUnit_CacheCompletionResults; 1998 1999 // Configure the diagnostics. 2000 DiagnosticOptions DiagOpts; 2001 llvm::IntrusiveRefCntPtr<Diagnostic> Diags; 2002 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0); 2003 2004 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles; 2005 for (unsigned I = 0; I != num_unsaved_files; ++I) { 2006 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length); 2007 const llvm::MemoryBuffer *Buffer 2008 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename); 2009 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename, 2010 Buffer)); 2011 } 2012 2013 if (!CXXIdx->getUseExternalASTGeneration()) { 2014 llvm::SmallVector<const char *, 16> Args; 2015 2016 // The 'source_filename' argument is optional. If the caller does not 2017 // specify it then it is assumed that the source file is specified 2018 // in the actual argument list. 2019 if (source_filename) 2020 Args.push_back(source_filename); 2021 2022 // Since the Clang C library is primarily used by batch tools dealing with 2023 // (often very broken) source code, where spell-checking can have a 2024 // significant negative impact on performance (particularly when 2025 // precompiled headers are involved), we disable it by default. 2026 // Note that we place this argument early in the list, so that it can be 2027 // overridden by the caller with "-fspell-checking". 2028 Args.push_back("-fno-spell-checking"); 2029 2030 Args.insert(Args.end(), command_line_args, 2031 command_line_args + num_command_line_args); 2032 2033 // Do we need the detailed preprocessing record? 2034 if (options & CXTranslationUnit_DetailedPreprocessingRecord) { 2035 Args.push_back("-Xclang"); 2036 Args.push_back("-detailed-preprocessing-record"); 2037 } 2038 2039 unsigned NumErrors = Diags->getNumErrors(); 2040 2041#ifdef USE_CRASHTRACER 2042 ArgsCrashTracerInfo ACTI(Args); 2043#endif 2044 2045 llvm::OwningPtr<ASTUnit> Unit( 2046 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(), 2047 Diags, 2048 CXXIdx->getClangResourcesPath(), 2049 CXXIdx->getOnlyLocalDecls(), 2050 RemappedFiles.data(), 2051 RemappedFiles.size(), 2052 /*CaptureDiagnostics=*/true, 2053 PrecompilePreamble, 2054 CompleteTranslationUnit, 2055 CacheCodeCompetionResults)); 2056 2057 if (NumErrors != Diags->getNumErrors()) { 2058 // Make sure to check that 'Unit' is non-NULL. 2059 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) { 2060 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(), 2061 DEnd = Unit->stored_diag_end(); 2062 D != DEnd; ++D) { 2063 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions()); 2064 CXString Msg = clang_formatDiagnostic(&Diag, 2065 clang_defaultDiagnosticDisplayOptions()); 2066 fprintf(stderr, "%s\n", clang_getCString(Msg)); 2067 clang_disposeString(Msg); 2068 } 2069#ifdef LLVM_ON_WIN32 2070 // On Windows, force a flush, since there may be multiple copies of 2071 // stderr and stdout in the file system, all with different buffers 2072 // but writing to the same device. 2073 fflush(stderr); 2074#endif 2075 } 2076 } 2077 2078 PTUI->result = Unit.take(); 2079 return; 2080 } 2081 2082 // Build up the arguments for invoking 'clang'. 2083 std::vector<const char *> argv; 2084 2085 // First add the complete path to the 'clang' executable. 2086 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath(); 2087 argv.push_back(ClangPath.c_str()); 2088 2089 // Add the '-emit-ast' option as our execution mode for 'clang'. 2090 argv.push_back("-emit-ast"); 2091 2092 // The 'source_filename' argument is optional. If the caller does not 2093 // specify it then it is assumed that the source file is specified 2094 // in the actual argument list. 2095 if (source_filename) 2096 argv.push_back(source_filename); 2097 2098 // Generate a temporary name for the AST file. 2099 argv.push_back("-o"); 2100 char astTmpFile[L_tmpnam]; 2101 argv.push_back(tmpnam(astTmpFile)); 2102 2103 // Since the Clang C library is primarily used by batch tools dealing with 2104 // (often very broken) source code, where spell-checking can have a 2105 // significant negative impact on performance (particularly when 2106 // precompiled headers are involved), we disable it by default. 2107 // Note that we place this argument early in the list, so that it can be 2108 // overridden by the caller with "-fspell-checking". 2109 argv.push_back("-fno-spell-checking"); 2110 2111 // Remap any unsaved files to temporary files. 2112 std::vector<llvm::sys::Path> TemporaryFiles; 2113 std::vector<std::string> RemapArgs; 2114 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles)) 2115 return; 2116 2117 // The pointers into the elements of RemapArgs are stable because we 2118 // won't be adding anything to RemapArgs after this point. 2119 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i) 2120 argv.push_back(RemapArgs[i].c_str()); 2121 2122 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'. 2123 for (int i = 0; i < num_command_line_args; ++i) 2124 if (const char *arg = command_line_args[i]) { 2125 if (strcmp(arg, "-o") == 0) { 2126 ++i; // Also skip the matching argument. 2127 continue; 2128 } 2129 if (strcmp(arg, "-emit-ast") == 0 || 2130 strcmp(arg, "-c") == 0 || 2131 strcmp(arg, "-fsyntax-only") == 0) { 2132 continue; 2133 } 2134 2135 // Keep the argument. 2136 argv.push_back(arg); 2137 } 2138 2139 // Generate a temporary name for the diagnostics file. 2140 char tmpFileResults[L_tmpnam]; 2141 char *tmpResultsFileName = tmpnam(tmpFileResults); 2142 llvm::sys::Path DiagnosticsFile(tmpResultsFileName); 2143 TemporaryFiles.push_back(DiagnosticsFile); 2144 argv.push_back("-fdiagnostics-binary"); 2145 2146 // Do we need the detailed preprocessing record? 2147 if (options & CXTranslationUnit_DetailedPreprocessingRecord) { 2148 argv.push_back("-Xclang"); 2149 argv.push_back("-detailed-preprocessing-record"); 2150 } 2151 2152 // Add the null terminator. 2153 argv.push_back(NULL); 2154 2155 // Invoke 'clang'. 2156 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null 2157 // on Unix or NUL (Windows). 2158 std::string ErrMsg; 2159 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile, 2160 NULL }; 2161 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL, 2162 /* redirects */ &Redirects[0], 2163 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg); 2164 2165 if (!ErrMsg.empty()) { 2166 std::string AllArgs; 2167 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end(); 2168 I != E; ++I) { 2169 AllArgs += ' '; 2170 if (*I) 2171 AllArgs += *I; 2172 } 2173 2174 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg; 2175 } 2176 2177 ASTUnit *ATU = ASTUnit::LoadFromASTFile(astTmpFile, Diags, 2178 CXXIdx->getOnlyLocalDecls(), 2179 RemappedFiles.data(), 2180 RemappedFiles.size(), 2181 /*CaptureDiagnostics=*/true); 2182 if (ATU) { 2183 LoadSerializedDiagnostics(DiagnosticsFile, 2184 num_unsaved_files, unsaved_files, 2185 ATU->getFileManager(), 2186 ATU->getSourceManager(), 2187 ATU->getStoredDiagnostics()); 2188 } else if (CXXIdx->getDisplayDiagnostics()) { 2189 // We failed to load the ASTUnit, but we can still deserialize the 2190 // diagnostics and emit them. 2191 FileManager FileMgr; 2192 Diagnostic Diag; 2193 SourceManager SourceMgr(Diag); 2194 // FIXME: Faked LangOpts! 2195 LangOptions LangOpts; 2196 llvm::SmallVector<StoredDiagnostic, 4> Diags; 2197 LoadSerializedDiagnostics(DiagnosticsFile, 2198 num_unsaved_files, unsaved_files, 2199 FileMgr, SourceMgr, Diags); 2200 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(), 2201 DEnd = Diags.end(); 2202 D != DEnd; ++D) { 2203 CXStoredDiagnostic Diag(*D, LangOpts); 2204 CXString Msg = clang_formatDiagnostic(&Diag, 2205 clang_defaultDiagnosticDisplayOptions()); 2206 fprintf(stderr, "%s\n", clang_getCString(Msg)); 2207 clang_disposeString(Msg); 2208 } 2209 2210#ifdef LLVM_ON_WIN32 2211 // On Windows, force a flush, since there may be multiple copies of 2212 // stderr and stdout in the file system, all with different buffers 2213 // but writing to the same device. 2214 fflush(stderr); 2215#endif 2216 } 2217 2218 if (ATU) { 2219 // Make the translation unit responsible for destroying all temporary files. 2220 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i) 2221 ATU->addTemporaryFile(TemporaryFiles[i]); 2222 ATU->addTemporaryFile(llvm::sys::Path(ATU->getASTFileName())); 2223 } else { 2224 // Destroy all of the temporary files now; they can't be referenced any 2225 // longer. 2226 llvm::sys::Path(astTmpFile).eraseFromDisk(); 2227 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i) 2228 TemporaryFiles[i].eraseFromDisk(); 2229 } 2230 2231 PTUI->result = ATU; 2232} 2233CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx, 2234 const char *source_filename, 2235 const char * const *command_line_args, 2236 int num_command_line_args, 2237 struct CXUnsavedFile *unsaved_files, 2238 unsigned num_unsaved_files, 2239 unsigned options) { 2240 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args, 2241 num_command_line_args, unsaved_files, num_unsaved_files, 2242 options, 0 }; 2243 llvm::CrashRecoveryContext CRC; 2244 2245 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) { 2246 fprintf(stderr, "libclang: crash detected during parsing: {\n"); 2247 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename); 2248 fprintf(stderr, " 'command_line_args' : ["); 2249 for (int i = 0; i != num_command_line_args; ++i) { 2250 if (i) 2251 fprintf(stderr, ", "); 2252 fprintf(stderr, "'%s'", command_line_args[i]); 2253 } 2254 fprintf(stderr, "],\n"); 2255 fprintf(stderr, " 'unsaved_files' : ["); 2256 for (unsigned i = 0; i != num_unsaved_files; ++i) { 2257 if (i) 2258 fprintf(stderr, ", "); 2259 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename, 2260 unsaved_files[i].Length); 2261 } 2262 fprintf(stderr, "],\n"); 2263 fprintf(stderr, " 'options' : %d,\n", options); 2264 fprintf(stderr, "}\n"); 2265 2266 return 0; 2267 } 2268 2269 return PTUI.result; 2270} 2271 2272unsigned clang_defaultSaveOptions(CXTranslationUnit TU) { 2273 return CXSaveTranslationUnit_None; 2274} 2275 2276int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName, 2277 unsigned options) { 2278 if (!TU) 2279 return 1; 2280 2281 return static_cast<ASTUnit *>(TU)->Save(FileName); 2282} 2283 2284void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) { 2285 if (CTUnit) { 2286 // If the translation unit has been marked as unsafe to free, just discard 2287 // it. 2288 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree()) 2289 return; 2290 2291 delete static_cast<ASTUnit *>(CTUnit); 2292 } 2293} 2294 2295unsigned clang_defaultReparseOptions(CXTranslationUnit TU) { 2296 return CXReparse_None; 2297} 2298 2299struct ReparseTranslationUnitInfo { 2300 CXTranslationUnit TU; 2301 unsigned num_unsaved_files; 2302 struct CXUnsavedFile *unsaved_files; 2303 unsigned options; 2304 int result; 2305}; 2306static void clang_reparseTranslationUnit_Impl(void *UserData) { 2307 ReparseTranslationUnitInfo *RTUI = 2308 static_cast<ReparseTranslationUnitInfo*>(UserData); 2309 CXTranslationUnit TU = RTUI->TU; 2310 unsigned num_unsaved_files = RTUI->num_unsaved_files; 2311 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files; 2312 unsigned options = RTUI->options; 2313 (void) options; 2314 RTUI->result = 1; 2315 2316 if (!TU) 2317 return; 2318 2319 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles; 2320 for (unsigned I = 0; I != num_unsaved_files; ++I) { 2321 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length); 2322 const llvm::MemoryBuffer *Buffer 2323 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename); 2324 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename, 2325 Buffer)); 2326 } 2327 2328 if (!static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(), 2329 RemappedFiles.size())) 2330 RTUI->result = 0; 2331} 2332int clang_reparseTranslationUnit(CXTranslationUnit TU, 2333 unsigned num_unsaved_files, 2334 struct CXUnsavedFile *unsaved_files, 2335 unsigned options) { 2336 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files, 2337 options, 0 }; 2338 llvm::CrashRecoveryContext CRC; 2339 2340 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) { 2341 fprintf(stderr, "libclang: crash detected during reparsing\n"); 2342 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true); 2343 return 1; 2344 } 2345 2346 return RTUI.result; 2347} 2348 2349 2350CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) { 2351 if (!CTUnit) 2352 return createCXString(""); 2353 2354 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit); 2355 return createCXString(CXXUnit->getOriginalSourceFileName(), true); 2356} 2357 2358CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) { 2359 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } }; 2360 return Result; 2361} 2362 2363} // end: extern "C" 2364 2365//===----------------------------------------------------------------------===// 2366// CXSourceLocation and CXSourceRange Operations. 2367//===----------------------------------------------------------------------===// 2368 2369extern "C" { 2370CXSourceLocation clang_getNullLocation() { 2371 CXSourceLocation Result = { { 0, 0 }, 0 }; 2372 return Result; 2373} 2374 2375unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) { 2376 return (loc1.ptr_data[0] == loc2.ptr_data[0] && 2377 loc1.ptr_data[1] == loc2.ptr_data[1] && 2378 loc1.int_data == loc2.int_data); 2379} 2380 2381CXSourceLocation clang_getLocation(CXTranslationUnit tu, 2382 CXFile file, 2383 unsigned line, 2384 unsigned column) { 2385 if (!tu || !file) 2386 return clang_getNullLocation(); 2387 2388 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu); 2389 SourceLocation SLoc 2390 = CXXUnit->getSourceManager().getLocation( 2391 static_cast<const FileEntry *>(file), 2392 line, column); 2393 2394 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc); 2395} 2396 2397CXSourceRange clang_getNullRange() { 2398 CXSourceRange Result = { { 0, 0 }, 0, 0 }; 2399 return Result; 2400} 2401 2402CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) { 2403 if (begin.ptr_data[0] != end.ptr_data[0] || 2404 begin.ptr_data[1] != end.ptr_data[1]) 2405 return clang_getNullRange(); 2406 2407 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] }, 2408 begin.int_data, end.int_data }; 2409 return Result; 2410} 2411 2412void clang_getInstantiationLocation(CXSourceLocation location, 2413 CXFile *file, 2414 unsigned *line, 2415 unsigned *column, 2416 unsigned *offset) { 2417 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data); 2418 2419 if (!location.ptr_data[0] || Loc.isInvalid()) { 2420 if (file) 2421 *file = 0; 2422 if (line) 2423 *line = 0; 2424 if (column) 2425 *column = 0; 2426 if (offset) 2427 *offset = 0; 2428 return; 2429 } 2430 2431 const SourceManager &SM = 2432 *static_cast<const SourceManager*>(location.ptr_data[0]); 2433 SourceLocation InstLoc = SM.getInstantiationLoc(Loc); 2434 2435 if (file) 2436 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc)); 2437 if (line) 2438 *line = SM.getInstantiationLineNumber(InstLoc); 2439 if (column) 2440 *column = SM.getInstantiationColumnNumber(InstLoc); 2441 if (offset) 2442 *offset = SM.getDecomposedLoc(InstLoc).second; 2443} 2444 2445CXSourceLocation clang_getRangeStart(CXSourceRange range) { 2446 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] }, 2447 range.begin_int_data }; 2448 return Result; 2449} 2450 2451CXSourceLocation clang_getRangeEnd(CXSourceRange range) { 2452 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] }, 2453 range.end_int_data }; 2454 return Result; 2455} 2456 2457} // end: extern "C" 2458 2459//===----------------------------------------------------------------------===// 2460// CXFile Operations. 2461//===----------------------------------------------------------------------===// 2462 2463extern "C" { 2464CXString clang_getFileName(CXFile SFile) { 2465 if (!SFile) 2466 return createCXString(NULL); 2467 2468 FileEntry *FEnt = static_cast<FileEntry *>(SFile); 2469 return createCXString(FEnt->getName()); 2470} 2471 2472time_t clang_getFileTime(CXFile SFile) { 2473 if (!SFile) 2474 return 0; 2475 2476 FileEntry *FEnt = static_cast<FileEntry *>(SFile); 2477 return FEnt->getModificationTime(); 2478} 2479 2480CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) { 2481 if (!tu) 2482 return 0; 2483 2484 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu); 2485 2486 FileManager &FMgr = CXXUnit->getFileManager(); 2487 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name)); 2488 return const_cast<FileEntry *>(File); 2489} 2490 2491} // end: extern "C" 2492 2493//===----------------------------------------------------------------------===// 2494// CXCursor Operations. 2495//===----------------------------------------------------------------------===// 2496 2497static Decl *getDeclFromExpr(Stmt *E) { 2498 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E)) 2499 return RefExpr->getDecl(); 2500 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) 2501 return ME->getMemberDecl(); 2502 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E)) 2503 return RE->getDecl(); 2504 2505 if (CallExpr *CE = dyn_cast<CallExpr>(E)) 2506 return getDeclFromExpr(CE->getCallee()); 2507 if (CastExpr *CE = dyn_cast<CastExpr>(E)) 2508 return getDeclFromExpr(CE->getSubExpr()); 2509 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E)) 2510 return OME->getMethodDecl(); 2511 2512 return 0; 2513} 2514 2515static SourceLocation getLocationFromExpr(Expr *E) { 2516 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) 2517 return /*FIXME:*/Msg->getLeftLoc(); 2518 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 2519 return DRE->getLocation(); 2520 if (MemberExpr *Member = dyn_cast<MemberExpr>(E)) 2521 return Member->getMemberLoc(); 2522 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) 2523 return Ivar->getLocation(); 2524 return E->getLocStart(); 2525} 2526 2527extern "C" { 2528 2529unsigned clang_visitChildren(CXCursor parent, 2530 CXCursorVisitor visitor, 2531 CXClientData client_data) { 2532 ASTUnit *CXXUnit = getCursorASTUnit(parent); 2533 2534 CursorVisitor CursorVis(CXXUnit, visitor, client_data, 2535 CXXUnit->getMaxPCHLevel()); 2536 return CursorVis.VisitChildren(parent); 2537} 2538 2539static CXString getDeclSpelling(Decl *D) { 2540 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D); 2541 if (!ND) 2542 return createCXString(""); 2543 2544 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND)) 2545 return createCXString(OMD->getSelector().getAsString()); 2546 2547 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND)) 2548 // No, this isn't the same as the code below. getIdentifier() is non-virtual 2549 // and returns different names. NamedDecl returns the class name and 2550 // ObjCCategoryImplDecl returns the category name. 2551 return createCXString(CIMP->getIdentifier()->getNameStart()); 2552 2553 if (isa<UsingDirectiveDecl>(D)) 2554 return createCXString(""); 2555 2556 llvm::SmallString<1024> S; 2557 llvm::raw_svector_ostream os(S); 2558 ND->printName(os); 2559 2560 return createCXString(os.str()); 2561} 2562 2563CXString clang_getCursorSpelling(CXCursor C) { 2564 if (clang_isTranslationUnit(C.kind)) 2565 return clang_getTranslationUnitSpelling(C.data[2]); 2566 2567 if (clang_isReference(C.kind)) { 2568 switch (C.kind) { 2569 case CXCursor_ObjCSuperClassRef: { 2570 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first; 2571 return createCXString(Super->getIdentifier()->getNameStart()); 2572 } 2573 case CXCursor_ObjCClassRef: { 2574 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first; 2575 return createCXString(Class->getIdentifier()->getNameStart()); 2576 } 2577 case CXCursor_ObjCProtocolRef: { 2578 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first; 2579 assert(OID && "getCursorSpelling(): Missing protocol decl"); 2580 return createCXString(OID->getIdentifier()->getNameStart()); 2581 } 2582 case CXCursor_CXXBaseSpecifier: { 2583 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C); 2584 return createCXString(B->getType().getAsString()); 2585 } 2586 case CXCursor_TypeRef: { 2587 TypeDecl *Type = getCursorTypeRef(C).first; 2588 assert(Type && "Missing type decl"); 2589 2590 return createCXString(getCursorContext(C).getTypeDeclType(Type). 2591 getAsString()); 2592 } 2593 case CXCursor_TemplateRef: { 2594 TemplateDecl *Template = getCursorTemplateRef(C).first; 2595 assert(Template && "Missing template decl"); 2596 2597 return createCXString(Template->getNameAsString()); 2598 } 2599 2600 case CXCursor_NamespaceRef: { 2601 NamedDecl *NS = getCursorNamespaceRef(C).first; 2602 assert(NS && "Missing namespace decl"); 2603 2604 return createCXString(NS->getNameAsString()); 2605 } 2606 2607 case CXCursor_MemberRef: { 2608 FieldDecl *Field = getCursorMemberRef(C).first; 2609 assert(Field && "Missing member decl"); 2610 2611 return createCXString(Field->getNameAsString()); 2612 } 2613 2614 case CXCursor_LabelRef: { 2615 LabelStmt *Label = getCursorLabelRef(C).first; 2616 assert(Label && "Missing label"); 2617 2618 return createCXString(Label->getID()->getName()); 2619 } 2620 2621 default: 2622 return createCXString("<not implemented>"); 2623 } 2624 } 2625 2626 if (clang_isExpression(C.kind)) { 2627 Decl *D = getDeclFromExpr(getCursorExpr(C)); 2628 if (D) 2629 return getDeclSpelling(D); 2630 return createCXString(""); 2631 } 2632 2633 if (clang_isStatement(C.kind)) { 2634 Stmt *S = getCursorStmt(C); 2635 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) 2636 return createCXString(Label->getID()->getName()); 2637 2638 return createCXString(""); 2639 } 2640 2641 if (C.kind == CXCursor_MacroInstantiation) 2642 return createCXString(getCursorMacroInstantiation(C)->getName() 2643 ->getNameStart()); 2644 2645 if (C.kind == CXCursor_MacroDefinition) 2646 return createCXString(getCursorMacroDefinition(C)->getName() 2647 ->getNameStart()); 2648 2649 if (clang_isDeclaration(C.kind)) 2650 return getDeclSpelling(getCursorDecl(C)); 2651 2652 return createCXString(""); 2653} 2654 2655CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) { 2656 switch (Kind) { 2657 case CXCursor_FunctionDecl: 2658 return createCXString("FunctionDecl"); 2659 case CXCursor_TypedefDecl: 2660 return createCXString("TypedefDecl"); 2661 case CXCursor_EnumDecl: 2662 return createCXString("EnumDecl"); 2663 case CXCursor_EnumConstantDecl: 2664 return createCXString("EnumConstantDecl"); 2665 case CXCursor_StructDecl: 2666 return createCXString("StructDecl"); 2667 case CXCursor_UnionDecl: 2668 return createCXString("UnionDecl"); 2669 case CXCursor_ClassDecl: 2670 return createCXString("ClassDecl"); 2671 case CXCursor_FieldDecl: 2672 return createCXString("FieldDecl"); 2673 case CXCursor_VarDecl: 2674 return createCXString("VarDecl"); 2675 case CXCursor_ParmDecl: 2676 return createCXString("ParmDecl"); 2677 case CXCursor_ObjCInterfaceDecl: 2678 return createCXString("ObjCInterfaceDecl"); 2679 case CXCursor_ObjCCategoryDecl: 2680 return createCXString("ObjCCategoryDecl"); 2681 case CXCursor_ObjCProtocolDecl: 2682 return createCXString("ObjCProtocolDecl"); 2683 case CXCursor_ObjCPropertyDecl: 2684 return createCXString("ObjCPropertyDecl"); 2685 case CXCursor_ObjCIvarDecl: 2686 return createCXString("ObjCIvarDecl"); 2687 case CXCursor_ObjCInstanceMethodDecl: 2688 return createCXString("ObjCInstanceMethodDecl"); 2689 case CXCursor_ObjCClassMethodDecl: 2690 return createCXString("ObjCClassMethodDecl"); 2691 case CXCursor_ObjCImplementationDecl: 2692 return createCXString("ObjCImplementationDecl"); 2693 case CXCursor_ObjCCategoryImplDecl: 2694 return createCXString("ObjCCategoryImplDecl"); 2695 case CXCursor_CXXMethod: 2696 return createCXString("CXXMethod"); 2697 case CXCursor_UnexposedDecl: 2698 return createCXString("UnexposedDecl"); 2699 case CXCursor_ObjCSuperClassRef: 2700 return createCXString("ObjCSuperClassRef"); 2701 case CXCursor_ObjCProtocolRef: 2702 return createCXString("ObjCProtocolRef"); 2703 case CXCursor_ObjCClassRef: 2704 return createCXString("ObjCClassRef"); 2705 case CXCursor_TypeRef: 2706 return createCXString("TypeRef"); 2707 case CXCursor_TemplateRef: 2708 return createCXString("TemplateRef"); 2709 case CXCursor_NamespaceRef: 2710 return createCXString("NamespaceRef"); 2711 case CXCursor_MemberRef: 2712 return createCXString("MemberRef"); 2713 case CXCursor_LabelRef: 2714 return createCXString("LabelRef"); 2715 case CXCursor_UnexposedExpr: 2716 return createCXString("UnexposedExpr"); 2717 case CXCursor_BlockExpr: 2718 return createCXString("BlockExpr"); 2719 case CXCursor_DeclRefExpr: 2720 return createCXString("DeclRefExpr"); 2721 case CXCursor_MemberRefExpr: 2722 return createCXString("MemberRefExpr"); 2723 case CXCursor_CallExpr: 2724 return createCXString("CallExpr"); 2725 case CXCursor_ObjCMessageExpr: 2726 return createCXString("ObjCMessageExpr"); 2727 case CXCursor_UnexposedStmt: 2728 return createCXString("UnexposedStmt"); 2729 case CXCursor_LabelStmt: 2730 return createCXString("LabelStmt"); 2731 case CXCursor_InvalidFile: 2732 return createCXString("InvalidFile"); 2733 case CXCursor_InvalidCode: 2734 return createCXString("InvalidCode"); 2735 case CXCursor_NoDeclFound: 2736 return createCXString("NoDeclFound"); 2737 case CXCursor_NotImplemented: 2738 return createCXString("NotImplemented"); 2739 case CXCursor_TranslationUnit: 2740 return createCXString("TranslationUnit"); 2741 case CXCursor_UnexposedAttr: 2742 return createCXString("UnexposedAttr"); 2743 case CXCursor_IBActionAttr: 2744 return createCXString("attribute(ibaction)"); 2745 case CXCursor_IBOutletAttr: 2746 return createCXString("attribute(iboutlet)"); 2747 case CXCursor_IBOutletCollectionAttr: 2748 return createCXString("attribute(iboutletcollection)"); 2749 case CXCursor_PreprocessingDirective: 2750 return createCXString("preprocessing directive"); 2751 case CXCursor_MacroDefinition: 2752 return createCXString("macro definition"); 2753 case CXCursor_MacroInstantiation: 2754 return createCXString("macro instantiation"); 2755 case CXCursor_Namespace: 2756 return createCXString("Namespace"); 2757 case CXCursor_LinkageSpec: 2758 return createCXString("LinkageSpec"); 2759 case CXCursor_CXXBaseSpecifier: 2760 return createCXString("C++ base class specifier"); 2761 case CXCursor_Constructor: 2762 return createCXString("CXXConstructor"); 2763 case CXCursor_Destructor: 2764 return createCXString("CXXDestructor"); 2765 case CXCursor_ConversionFunction: 2766 return createCXString("CXXConversion"); 2767 case CXCursor_TemplateTypeParameter: 2768 return createCXString("TemplateTypeParameter"); 2769 case CXCursor_NonTypeTemplateParameter: 2770 return createCXString("NonTypeTemplateParameter"); 2771 case CXCursor_TemplateTemplateParameter: 2772 return createCXString("TemplateTemplateParameter"); 2773 case CXCursor_FunctionTemplate: 2774 return createCXString("FunctionTemplate"); 2775 case CXCursor_ClassTemplate: 2776 return createCXString("ClassTemplate"); 2777 case CXCursor_ClassTemplatePartialSpecialization: 2778 return createCXString("ClassTemplatePartialSpecialization"); 2779 case CXCursor_NamespaceAlias: 2780 return createCXString("NamespaceAlias"); 2781 case CXCursor_UsingDirective: 2782 return createCXString("UsingDirective"); 2783 case CXCursor_UsingDeclaration: 2784 return createCXString("UsingDeclaration"); 2785 } 2786 2787 llvm_unreachable("Unhandled CXCursorKind"); 2788 return createCXString(NULL); 2789} 2790 2791enum CXChildVisitResult GetCursorVisitor(CXCursor cursor, 2792 CXCursor parent, 2793 CXClientData client_data) { 2794 CXCursor *BestCursor = static_cast<CXCursor *>(client_data); 2795 *BestCursor = cursor; 2796 return CXChildVisit_Recurse; 2797} 2798 2799CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) { 2800 if (!TU) 2801 return clang_getNullCursor(); 2802 2803 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU); 2804 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 2805 2806 // Translate the given source location to make it point at the beginning of 2807 // the token under the cursor. 2808 SourceLocation SLoc = cxloc::translateSourceLocation(Loc); 2809 2810 // Guard against an invalid SourceLocation, or we may assert in one 2811 // of the following calls. 2812 if (SLoc.isInvalid()) 2813 return clang_getNullCursor(); 2814 2815 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(), 2816 CXXUnit->getASTContext().getLangOptions()); 2817 2818 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound); 2819 if (SLoc.isValid()) { 2820 // FIXME: Would be great to have a "hint" cursor, then walk from that 2821 // hint cursor upward until we find a cursor whose source range encloses 2822 // the region of interest, rather than starting from the translation unit. 2823 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit); 2824 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result, 2825 Decl::MaxPCHLevel, SourceLocation(SLoc)); 2826 CursorVis.VisitChildren(Parent); 2827 } 2828 return Result; 2829} 2830 2831CXCursor clang_getNullCursor(void) { 2832 return MakeCXCursorInvalid(CXCursor_InvalidFile); 2833} 2834 2835unsigned clang_equalCursors(CXCursor X, CXCursor Y) { 2836 return X == Y; 2837} 2838 2839unsigned clang_isInvalid(enum CXCursorKind K) { 2840 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid; 2841} 2842 2843unsigned clang_isDeclaration(enum CXCursorKind K) { 2844 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl; 2845} 2846 2847unsigned clang_isReference(enum CXCursorKind K) { 2848 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef; 2849} 2850 2851unsigned clang_isExpression(enum CXCursorKind K) { 2852 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr; 2853} 2854 2855unsigned clang_isStatement(enum CXCursorKind K) { 2856 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt; 2857} 2858 2859unsigned clang_isTranslationUnit(enum CXCursorKind K) { 2860 return K == CXCursor_TranslationUnit; 2861} 2862 2863unsigned clang_isPreprocessing(enum CXCursorKind K) { 2864 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing; 2865} 2866 2867unsigned clang_isUnexposed(enum CXCursorKind K) { 2868 switch (K) { 2869 case CXCursor_UnexposedDecl: 2870 case CXCursor_UnexposedExpr: 2871 case CXCursor_UnexposedStmt: 2872 case CXCursor_UnexposedAttr: 2873 return true; 2874 default: 2875 return false; 2876 } 2877} 2878 2879CXCursorKind clang_getCursorKind(CXCursor C) { 2880 return C.kind; 2881} 2882 2883CXSourceLocation clang_getCursorLocation(CXCursor C) { 2884 if (clang_isReference(C.kind)) { 2885 switch (C.kind) { 2886 case CXCursor_ObjCSuperClassRef: { 2887 std::pair<ObjCInterfaceDecl *, SourceLocation> P 2888 = getCursorObjCSuperClassRef(C); 2889 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 2890 } 2891 2892 case CXCursor_ObjCProtocolRef: { 2893 std::pair<ObjCProtocolDecl *, SourceLocation> P 2894 = getCursorObjCProtocolRef(C); 2895 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 2896 } 2897 2898 case CXCursor_ObjCClassRef: { 2899 std::pair<ObjCInterfaceDecl *, SourceLocation> P 2900 = getCursorObjCClassRef(C); 2901 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 2902 } 2903 2904 case CXCursor_TypeRef: { 2905 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C); 2906 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 2907 } 2908 2909 case CXCursor_TemplateRef: { 2910 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C); 2911 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 2912 } 2913 2914 case CXCursor_NamespaceRef: { 2915 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C); 2916 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 2917 } 2918 2919 case CXCursor_MemberRef: { 2920 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C); 2921 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 2922 } 2923 2924 case CXCursor_CXXBaseSpecifier: { 2925 // FIXME: Figure out what location to return for a CXXBaseSpecifier. 2926 return clang_getNullLocation(); 2927 } 2928 2929 case CXCursor_LabelRef: { 2930 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C); 2931 return cxloc::translateSourceLocation(getCursorContext(C), P.second); 2932 } 2933 2934 default: 2935 // FIXME: Need a way to enumerate all non-reference cases. 2936 llvm_unreachable("Missed a reference kind"); 2937 } 2938 } 2939 2940 if (clang_isExpression(C.kind)) 2941 return cxloc::translateSourceLocation(getCursorContext(C), 2942 getLocationFromExpr(getCursorExpr(C))); 2943 2944 if (clang_isStatement(C.kind)) 2945 return cxloc::translateSourceLocation(getCursorContext(C), 2946 getCursorStmt(C)->getLocStart()); 2947 2948 if (C.kind == CXCursor_PreprocessingDirective) { 2949 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin(); 2950 return cxloc::translateSourceLocation(getCursorContext(C), L); 2951 } 2952 2953 if (C.kind == CXCursor_MacroInstantiation) { 2954 SourceLocation L 2955 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin(); 2956 return cxloc::translateSourceLocation(getCursorContext(C), L); 2957 } 2958 2959 if (C.kind == CXCursor_MacroDefinition) { 2960 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation(); 2961 return cxloc::translateSourceLocation(getCursorContext(C), L); 2962 } 2963 2964 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl) 2965 return clang_getNullLocation(); 2966 2967 Decl *D = getCursorDecl(C); 2968 SourceLocation Loc = D->getLocation(); 2969 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D)) 2970 Loc = Class->getClassLoc(); 2971 return cxloc::translateSourceLocation(getCursorContext(C), Loc); 2972} 2973 2974} // end extern "C" 2975 2976static SourceRange getRawCursorExtent(CXCursor C) { 2977 if (clang_isReference(C.kind)) { 2978 switch (C.kind) { 2979 case CXCursor_ObjCSuperClassRef: 2980 return getCursorObjCSuperClassRef(C).second; 2981 2982 case CXCursor_ObjCProtocolRef: 2983 return getCursorObjCProtocolRef(C).second; 2984 2985 case CXCursor_ObjCClassRef: 2986 return getCursorObjCClassRef(C).second; 2987 2988 case CXCursor_TypeRef: 2989 return getCursorTypeRef(C).second; 2990 2991 case CXCursor_TemplateRef: 2992 return getCursorTemplateRef(C).second; 2993 2994 case CXCursor_NamespaceRef: 2995 return getCursorNamespaceRef(C).second; 2996 2997 case CXCursor_MemberRef: 2998 return getCursorMemberRef(C).second; 2999 3000 case CXCursor_CXXBaseSpecifier: 3001 // FIXME: Figure out what source range to use for a CXBaseSpecifier. 3002 return SourceRange(); 3003 3004 case CXCursor_LabelRef: 3005 return getCursorLabelRef(C).second; 3006 3007 default: 3008 // FIXME: Need a way to enumerate all non-reference cases. 3009 llvm_unreachable("Missed a reference kind"); 3010 } 3011 } 3012 3013 if (clang_isExpression(C.kind)) 3014 return getCursorExpr(C)->getSourceRange(); 3015 3016 if (clang_isStatement(C.kind)) 3017 return getCursorStmt(C)->getSourceRange(); 3018 3019 if (C.kind == CXCursor_PreprocessingDirective) 3020 return cxcursor::getCursorPreprocessingDirective(C); 3021 3022 if (C.kind == CXCursor_MacroInstantiation) 3023 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange(); 3024 3025 if (C.kind == CXCursor_MacroDefinition) 3026 return cxcursor::getCursorMacroDefinition(C)->getSourceRange(); 3027 3028 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) 3029 return getCursorDecl(C)->getSourceRange(); 3030 3031 return SourceRange(); 3032} 3033 3034extern "C" { 3035 3036CXSourceRange clang_getCursorExtent(CXCursor C) { 3037 SourceRange R = getRawCursorExtent(C); 3038 if (R.isInvalid()) 3039 return clang_getNullRange(); 3040 3041 return cxloc::translateSourceRange(getCursorContext(C), R); 3042} 3043 3044CXCursor clang_getCursorReferenced(CXCursor C) { 3045 if (clang_isInvalid(C.kind)) 3046 return clang_getNullCursor(); 3047 3048 ASTUnit *CXXUnit = getCursorASTUnit(C); 3049 if (clang_isDeclaration(C.kind)) 3050 return C; 3051 3052 if (clang_isExpression(C.kind)) { 3053 Decl *D = getDeclFromExpr(getCursorExpr(C)); 3054 if (D) 3055 return MakeCXCursor(D, CXXUnit); 3056 return clang_getNullCursor(); 3057 } 3058 3059 if (clang_isStatement(C.kind)) { 3060 Stmt *S = getCursorStmt(C); 3061 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S)) 3062 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C), 3063 getCursorASTUnit(C)); 3064 3065 return clang_getNullCursor(); 3066 } 3067 3068 if (C.kind == CXCursor_MacroInstantiation) { 3069 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition()) 3070 return MakeMacroDefinitionCursor(Def, CXXUnit); 3071 } 3072 3073 if (!clang_isReference(C.kind)) 3074 return clang_getNullCursor(); 3075 3076 switch (C.kind) { 3077 case CXCursor_ObjCSuperClassRef: 3078 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit); 3079 3080 case CXCursor_ObjCProtocolRef: { 3081 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit); 3082 3083 case CXCursor_ObjCClassRef: 3084 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit); 3085 3086 case CXCursor_TypeRef: 3087 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit); 3088 3089 case CXCursor_TemplateRef: 3090 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit); 3091 3092 case CXCursor_NamespaceRef: 3093 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit); 3094 3095 case CXCursor_MemberRef: 3096 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit); 3097 3098 case CXCursor_CXXBaseSpecifier: { 3099 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C); 3100 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(), 3101 CXXUnit)); 3102 } 3103 3104 case CXCursor_LabelRef: 3105 // FIXME: We end up faking the "parent" declaration here because we 3106 // don't want to make CXCursor larger. 3107 return MakeCXCursor(getCursorLabelRef(C).first, 3108 CXXUnit->getASTContext().getTranslationUnitDecl(), 3109 CXXUnit); 3110 3111 default: 3112 // We would prefer to enumerate all non-reference cursor kinds here. 3113 llvm_unreachable("Unhandled reference cursor kind"); 3114 break; 3115 } 3116 } 3117 3118 return clang_getNullCursor(); 3119} 3120 3121CXCursor clang_getCursorDefinition(CXCursor C) { 3122 if (clang_isInvalid(C.kind)) 3123 return clang_getNullCursor(); 3124 3125 ASTUnit *CXXUnit = getCursorASTUnit(C); 3126 3127 bool WasReference = false; 3128 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) { 3129 C = clang_getCursorReferenced(C); 3130 WasReference = true; 3131 } 3132 3133 if (C.kind == CXCursor_MacroInstantiation) 3134 return clang_getCursorReferenced(C); 3135 3136 if (!clang_isDeclaration(C.kind)) 3137 return clang_getNullCursor(); 3138 3139 Decl *D = getCursorDecl(C); 3140 if (!D) 3141 return clang_getNullCursor(); 3142 3143 switch (D->getKind()) { 3144 // Declaration kinds that don't really separate the notions of 3145 // declaration and definition. 3146 case Decl::Namespace: 3147 case Decl::Typedef: 3148 case Decl::TemplateTypeParm: 3149 case Decl::EnumConstant: 3150 case Decl::Field: 3151 case Decl::ObjCIvar: 3152 case Decl::ObjCAtDefsField: 3153 case Decl::ImplicitParam: 3154 case Decl::ParmVar: 3155 case Decl::NonTypeTemplateParm: 3156 case Decl::TemplateTemplateParm: 3157 case Decl::ObjCCategoryImpl: 3158 case Decl::ObjCImplementation: 3159 case Decl::AccessSpec: 3160 case Decl::LinkageSpec: 3161 case Decl::ObjCPropertyImpl: 3162 case Decl::FileScopeAsm: 3163 case Decl::StaticAssert: 3164 case Decl::Block: 3165 return C; 3166 3167 // Declaration kinds that don't make any sense here, but are 3168 // nonetheless harmless. 3169 case Decl::TranslationUnit: 3170 break; 3171 3172 // Declaration kinds for which the definition is not resolvable. 3173 case Decl::UnresolvedUsingTypename: 3174 case Decl::UnresolvedUsingValue: 3175 break; 3176 3177 case Decl::UsingDirective: 3178 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(), 3179 CXXUnit); 3180 3181 case Decl::NamespaceAlias: 3182 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit); 3183 3184 case Decl::Enum: 3185 case Decl::Record: 3186 case Decl::CXXRecord: 3187 case Decl::ClassTemplateSpecialization: 3188 case Decl::ClassTemplatePartialSpecialization: 3189 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition()) 3190 return MakeCXCursor(Def, CXXUnit); 3191 return clang_getNullCursor(); 3192 3193 case Decl::Function: 3194 case Decl::CXXMethod: 3195 case Decl::CXXConstructor: 3196 case Decl::CXXDestructor: 3197 case Decl::CXXConversion: { 3198 const FunctionDecl *Def = 0; 3199 if (cast<FunctionDecl>(D)->getBody(Def)) 3200 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit); 3201 return clang_getNullCursor(); 3202 } 3203 3204 case Decl::Var: { 3205 // Ask the variable if it has a definition. 3206 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition()) 3207 return MakeCXCursor(Def, CXXUnit); 3208 return clang_getNullCursor(); 3209 } 3210 3211 case Decl::FunctionTemplate: { 3212 const FunctionDecl *Def = 0; 3213 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def)) 3214 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit); 3215 return clang_getNullCursor(); 3216 } 3217 3218 case Decl::ClassTemplate: { 3219 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl() 3220 ->getDefinition()) 3221 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(), 3222 CXXUnit); 3223 return clang_getNullCursor(); 3224 } 3225 3226 case Decl::Using: { 3227 UsingDecl *Using = cast<UsingDecl>(D); 3228 CXCursor Def = clang_getNullCursor(); 3229 for (UsingDecl::shadow_iterator S = Using->shadow_begin(), 3230 SEnd = Using->shadow_end(); 3231 S != SEnd; ++S) { 3232 if (Def != clang_getNullCursor()) { 3233 // FIXME: We have no way to return multiple results. 3234 return clang_getNullCursor(); 3235 } 3236 3237 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(), 3238 CXXUnit)); 3239 } 3240 3241 return Def; 3242 } 3243 3244 case Decl::UsingShadow: 3245 return clang_getCursorDefinition( 3246 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(), 3247 CXXUnit)); 3248 3249 case Decl::ObjCMethod: { 3250 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D); 3251 if (Method->isThisDeclarationADefinition()) 3252 return C; 3253 3254 // Dig out the method definition in the associated 3255 // @implementation, if we have it. 3256 // FIXME: The ASTs should make finding the definition easier. 3257 if (ObjCInterfaceDecl *Class 3258 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) 3259 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation()) 3260 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(), 3261 Method->isInstanceMethod())) 3262 if (Def->isThisDeclarationADefinition()) 3263 return MakeCXCursor(Def, CXXUnit); 3264 3265 return clang_getNullCursor(); 3266 } 3267 3268 case Decl::ObjCCategory: 3269 if (ObjCCategoryImplDecl *Impl 3270 = cast<ObjCCategoryDecl>(D)->getImplementation()) 3271 return MakeCXCursor(Impl, CXXUnit); 3272 return clang_getNullCursor(); 3273 3274 case Decl::ObjCProtocol: 3275 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl()) 3276 return C; 3277 return clang_getNullCursor(); 3278 3279 case Decl::ObjCInterface: 3280 // There are two notions of a "definition" for an Objective-C 3281 // class: the interface and its implementation. When we resolved a 3282 // reference to an Objective-C class, produce the @interface as 3283 // the definition; when we were provided with the interface, 3284 // produce the @implementation as the definition. 3285 if (WasReference) { 3286 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl()) 3287 return C; 3288 } else if (ObjCImplementationDecl *Impl 3289 = cast<ObjCInterfaceDecl>(D)->getImplementation()) 3290 return MakeCXCursor(Impl, CXXUnit); 3291 return clang_getNullCursor(); 3292 3293 case Decl::ObjCProperty: 3294 // FIXME: We don't really know where to find the 3295 // ObjCPropertyImplDecls that implement this property. 3296 return clang_getNullCursor(); 3297 3298 case Decl::ObjCCompatibleAlias: 3299 if (ObjCInterfaceDecl *Class 3300 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface()) 3301 if (!Class->isForwardDecl()) 3302 return MakeCXCursor(Class, CXXUnit); 3303 3304 return clang_getNullCursor(); 3305 3306 case Decl::ObjCForwardProtocol: { 3307 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D); 3308 if (Forward->protocol_size() == 1) 3309 return clang_getCursorDefinition( 3310 MakeCXCursor(*Forward->protocol_begin(), 3311 CXXUnit)); 3312 3313 // FIXME: Cannot return multiple definitions. 3314 return clang_getNullCursor(); 3315 } 3316 3317 case Decl::ObjCClass: { 3318 ObjCClassDecl *Class = cast<ObjCClassDecl>(D); 3319 if (Class->size() == 1) { 3320 ObjCInterfaceDecl *IFace = Class->begin()->getInterface(); 3321 if (!IFace->isForwardDecl()) 3322 return MakeCXCursor(IFace, CXXUnit); 3323 return clang_getNullCursor(); 3324 } 3325 3326 // FIXME: Cannot return multiple definitions. 3327 return clang_getNullCursor(); 3328 } 3329 3330 case Decl::Friend: 3331 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl()) 3332 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit)); 3333 return clang_getNullCursor(); 3334 3335 case Decl::FriendTemplate: 3336 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl()) 3337 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit)); 3338 return clang_getNullCursor(); 3339 } 3340 3341 return clang_getNullCursor(); 3342} 3343 3344unsigned clang_isCursorDefinition(CXCursor C) { 3345 if (!clang_isDeclaration(C.kind)) 3346 return 0; 3347 3348 return clang_getCursorDefinition(C) == C; 3349} 3350 3351void clang_getDefinitionSpellingAndExtent(CXCursor C, 3352 const char **startBuf, 3353 const char **endBuf, 3354 unsigned *startLine, 3355 unsigned *startColumn, 3356 unsigned *endLine, 3357 unsigned *endColumn) { 3358 assert(getCursorDecl(C) && "CXCursor has null decl"); 3359 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C)); 3360 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND); 3361 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody()); 3362 3363 SourceManager &SM = FD->getASTContext().getSourceManager(); 3364 *startBuf = SM.getCharacterData(Body->getLBracLoc()); 3365 *endBuf = SM.getCharacterData(Body->getRBracLoc()); 3366 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc()); 3367 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc()); 3368 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc()); 3369 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc()); 3370} 3371 3372void clang_enableStackTraces(void) { 3373 llvm::sys::PrintStackTraceOnErrorSignal(); 3374} 3375 3376} // end: extern "C" 3377 3378//===----------------------------------------------------------------------===// 3379// Token-based Operations. 3380//===----------------------------------------------------------------------===// 3381 3382/* CXToken layout: 3383 * int_data[0]: a CXTokenKind 3384 * int_data[1]: starting token location 3385 * int_data[2]: token length 3386 * int_data[3]: reserved 3387 * ptr_data: for identifiers and keywords, an IdentifierInfo*. 3388 * otherwise unused. 3389 */ 3390extern "C" { 3391 3392CXTokenKind clang_getTokenKind(CXToken CXTok) { 3393 return static_cast<CXTokenKind>(CXTok.int_data[0]); 3394} 3395 3396CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) { 3397 switch (clang_getTokenKind(CXTok)) { 3398 case CXToken_Identifier: 3399 case CXToken_Keyword: 3400 // We know we have an IdentifierInfo*, so use that. 3401 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data) 3402 ->getNameStart()); 3403 3404 case CXToken_Literal: { 3405 // We have stashed the starting pointer in the ptr_data field. Use it. 3406 const char *Text = static_cast<const char *>(CXTok.ptr_data); 3407 return createCXString(llvm::StringRef(Text, CXTok.int_data[2])); 3408 } 3409 3410 case CXToken_Punctuation: 3411 case CXToken_Comment: 3412 break; 3413 } 3414 3415 // We have to find the starting buffer pointer the hard way, by 3416 // deconstructing the source location. 3417 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU); 3418 if (!CXXUnit) 3419 return createCXString(""); 3420 3421 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]); 3422 std::pair<FileID, unsigned> LocInfo 3423 = CXXUnit->getSourceManager().getDecomposedLoc(Loc); 3424 bool Invalid = false; 3425 llvm::StringRef Buffer 3426 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid); 3427 if (Invalid) 3428 return createCXString(""); 3429 3430 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2])); 3431} 3432 3433CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) { 3434 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU); 3435 if (!CXXUnit) 3436 return clang_getNullLocation(); 3437 3438 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), 3439 SourceLocation::getFromRawEncoding(CXTok.int_data[1])); 3440} 3441 3442CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) { 3443 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU); 3444 if (!CXXUnit) 3445 return clang_getNullRange(); 3446 3447 return cxloc::translateSourceRange(CXXUnit->getASTContext(), 3448 SourceLocation::getFromRawEncoding(CXTok.int_data[1])); 3449} 3450 3451void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range, 3452 CXToken **Tokens, unsigned *NumTokens) { 3453 if (Tokens) 3454 *Tokens = 0; 3455 if (NumTokens) 3456 *NumTokens = 0; 3457 3458 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU); 3459 if (!CXXUnit || !Tokens || !NumTokens) 3460 return; 3461 3462 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 3463 3464 SourceRange R = cxloc::translateCXSourceRange(Range); 3465 if (R.isInvalid()) 3466 return; 3467 3468 SourceManager &SourceMgr = CXXUnit->getSourceManager(); 3469 std::pair<FileID, unsigned> BeginLocInfo 3470 = SourceMgr.getDecomposedLoc(R.getBegin()); 3471 std::pair<FileID, unsigned> EndLocInfo 3472 = SourceMgr.getDecomposedLoc(R.getEnd()); 3473 3474 // Cannot tokenize across files. 3475 if (BeginLocInfo.first != EndLocInfo.first) 3476 return; 3477 3478 // Create a lexer 3479 bool Invalid = false; 3480 llvm::StringRef Buffer 3481 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid); 3482 if (Invalid) 3483 return; 3484 3485 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first), 3486 CXXUnit->getASTContext().getLangOptions(), 3487 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end()); 3488 Lex.SetCommentRetentionState(true); 3489 3490 // Lex tokens until we hit the end of the range. 3491 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second; 3492 llvm::SmallVector<CXToken, 32> CXTokens; 3493 Token Tok; 3494 do { 3495 // Lex the next token 3496 Lex.LexFromRawLexer(Tok); 3497 if (Tok.is(tok::eof)) 3498 break; 3499 3500 // Initialize the CXToken. 3501 CXToken CXTok; 3502 3503 // - Common fields 3504 CXTok.int_data[1] = Tok.getLocation().getRawEncoding(); 3505 CXTok.int_data[2] = Tok.getLength(); 3506 CXTok.int_data[3] = 0; 3507 3508 // - Kind-specific fields 3509 if (Tok.isLiteral()) { 3510 CXTok.int_data[0] = CXToken_Literal; 3511 CXTok.ptr_data = (void *)Tok.getLiteralData(); 3512 } else if (Tok.is(tok::identifier)) { 3513 // Lookup the identifier to determine whether we have a keyword. 3514 std::pair<FileID, unsigned> LocInfo 3515 = SourceMgr.getDecomposedLoc(Tok.getLocation()); 3516 bool Invalid = false; 3517 llvm::StringRef Buf 3518 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid); 3519 if (Invalid) 3520 return; 3521 3522 const char *StartPos = Buf.data() + LocInfo.second; 3523 IdentifierInfo *II 3524 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos); 3525 3526 if (II->getObjCKeywordID() != tok::objc_not_keyword) { 3527 CXTok.int_data[0] = CXToken_Keyword; 3528 } 3529 else { 3530 CXTok.int_data[0] = II->getTokenID() == tok::identifier? 3531 CXToken_Identifier 3532 : CXToken_Keyword; 3533 } 3534 CXTok.ptr_data = II; 3535 } else if (Tok.is(tok::comment)) { 3536 CXTok.int_data[0] = CXToken_Comment; 3537 CXTok.ptr_data = 0; 3538 } else { 3539 CXTok.int_data[0] = CXToken_Punctuation; 3540 CXTok.ptr_data = 0; 3541 } 3542 CXTokens.push_back(CXTok); 3543 } while (Lex.getBufferLocation() <= EffectiveBufferEnd); 3544 3545 if (CXTokens.empty()) 3546 return; 3547 3548 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size()); 3549 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size()); 3550 *NumTokens = CXTokens.size(); 3551} 3552 3553void clang_disposeTokens(CXTranslationUnit TU, 3554 CXToken *Tokens, unsigned NumTokens) { 3555 free(Tokens); 3556} 3557 3558} // end: extern "C" 3559 3560//===----------------------------------------------------------------------===// 3561// Token annotation APIs. 3562//===----------------------------------------------------------------------===// 3563 3564typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData; 3565static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor, 3566 CXCursor parent, 3567 CXClientData client_data); 3568namespace { 3569class AnnotateTokensWorker { 3570 AnnotateTokensData &Annotated; 3571 CXToken *Tokens; 3572 CXCursor *Cursors; 3573 unsigned NumTokens; 3574 unsigned TokIdx; 3575 CursorVisitor AnnotateVis; 3576 SourceManager &SrcMgr; 3577 3578 bool MoreTokens() const { return TokIdx < NumTokens; } 3579 unsigned NextToken() const { return TokIdx; } 3580 void AdvanceToken() { ++TokIdx; } 3581 SourceLocation GetTokenLoc(unsigned tokI) { 3582 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]); 3583 } 3584 3585public: 3586 AnnotateTokensWorker(AnnotateTokensData &annotated, 3587 CXToken *tokens, CXCursor *cursors, unsigned numTokens, 3588 ASTUnit *CXXUnit, SourceRange RegionOfInterest) 3589 : Annotated(annotated), Tokens(tokens), Cursors(cursors), 3590 NumTokens(numTokens), TokIdx(0), 3591 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this, 3592 Decl::MaxPCHLevel, RegionOfInterest), 3593 SrcMgr(CXXUnit->getSourceManager()) {} 3594 3595 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); } 3596 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent); 3597 void AnnotateTokens(CXCursor parent); 3598}; 3599} 3600 3601void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) { 3602 // Walk the AST within the region of interest, annotating tokens 3603 // along the way. 3604 VisitChildren(parent); 3605 3606 for (unsigned I = 0 ; I < TokIdx ; ++I) { 3607 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]); 3608 if (Pos != Annotated.end()) 3609 Cursors[I] = Pos->second; 3610 } 3611 3612 // Finish up annotating any tokens left. 3613 if (!MoreTokens()) 3614 return; 3615 3616 const CXCursor &C = clang_getNullCursor(); 3617 for (unsigned I = TokIdx ; I < NumTokens ; ++I) { 3618 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]); 3619 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second; 3620 } 3621} 3622 3623enum CXChildVisitResult 3624AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) { 3625 CXSourceLocation Loc = clang_getCursorLocation(cursor); 3626 // We can always annotate a preprocessing directive/macro instantiation. 3627 if (clang_isPreprocessing(cursor.kind)) { 3628 Annotated[Loc.int_data] = cursor; 3629 return CXChildVisit_Recurse; 3630 } 3631 3632 SourceRange cursorRange = getRawCursorExtent(cursor); 3633 3634 if (cursorRange.isInvalid()) 3635 return CXChildVisit_Continue; 3636 3637 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data); 3638 3639 // Adjust the annotated range based specific declarations. 3640 const enum CXCursorKind cursorK = clang_getCursorKind(cursor); 3641 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) { 3642 Decl *D = cxcursor::getCursorDecl(cursor); 3643 // Don't visit synthesized ObjC methods, since they have no syntatic 3644 // representation in the source. 3645 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 3646 if (MD->isSynthesized()) 3647 return CXChildVisit_Continue; 3648 } 3649 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 3650 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) { 3651 TypeLoc TL = TI->getTypeLoc(); 3652 SourceLocation TLoc = TL.getSourceRange().getBegin(); 3653 if (TLoc.isValid() && 3654 SrcMgr.isBeforeInTranslationUnit(TLoc, L)) 3655 cursorRange.setBegin(TLoc); 3656 } 3657 } 3658 } 3659 3660 // If the location of the cursor occurs within a macro instantiation, record 3661 // the spelling location of the cursor in our annotation map. We can then 3662 // paper over the token labelings during a post-processing step to try and 3663 // get cursor mappings for tokens that are the *arguments* of a macro 3664 // instantiation. 3665 if (L.isMacroID()) { 3666 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding(); 3667 // Only invalidate the old annotation if it isn't part of a preprocessing 3668 // directive. Here we assume that the default construction of CXCursor 3669 // results in CXCursor.kind being an initialized value (i.e., 0). If 3670 // this isn't the case, we can fix by doing lookup + insertion. 3671 3672 CXCursor &oldC = Annotated[rawEncoding]; 3673 if (!clang_isPreprocessing(oldC.kind)) 3674 oldC = cursor; 3675 } 3676 3677 const enum CXCursorKind K = clang_getCursorKind(parent); 3678 const CXCursor updateC = 3679 (clang_isInvalid(K) || K == CXCursor_TranslationUnit) 3680 ? clang_getNullCursor() : parent; 3681 3682 while (MoreTokens()) { 3683 const unsigned I = NextToken(); 3684 SourceLocation TokLoc = GetTokenLoc(I); 3685 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 3686 case RangeBefore: 3687 Cursors[I] = updateC; 3688 AdvanceToken(); 3689 continue; 3690 case RangeAfter: 3691 case RangeOverlap: 3692 break; 3693 } 3694 break; 3695 } 3696 3697 // Visit children to get their cursor information. 3698 const unsigned BeforeChildren = NextToken(); 3699 VisitChildren(cursor); 3700 const unsigned AfterChildren = NextToken(); 3701 3702 // Adjust 'Last' to the last token within the extent of the cursor. 3703 while (MoreTokens()) { 3704 const unsigned I = NextToken(); 3705 SourceLocation TokLoc = GetTokenLoc(I); 3706 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 3707 case RangeBefore: 3708 assert(0 && "Infeasible"); 3709 case RangeAfter: 3710 break; 3711 case RangeOverlap: 3712 Cursors[I] = updateC; 3713 AdvanceToken(); 3714 continue; 3715 } 3716 break; 3717 } 3718 const unsigned Last = NextToken(); 3719 3720 // Scan the tokens that are at the beginning of the cursor, but are not 3721 // capture by the child cursors. 3722 3723 // For AST elements within macros, rely on a post-annotate pass to 3724 // to correctly annotate the tokens with cursors. Otherwise we can 3725 // get confusing results of having tokens that map to cursors that really 3726 // are expanded by an instantiation. 3727 if (L.isMacroID()) 3728 cursor = clang_getNullCursor(); 3729 3730 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) { 3731 if (!clang_isInvalid(clang_getCursorKind(Cursors[I]))) 3732 break; 3733 Cursors[I] = cursor; 3734 } 3735 // Scan the tokens that are at the end of the cursor, but are not captured 3736 // but the child cursors. 3737 for (unsigned I = AfterChildren; I != Last; ++I) 3738 Cursors[I] = cursor; 3739 3740 TokIdx = Last; 3741 return CXChildVisit_Continue; 3742} 3743 3744static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor, 3745 CXCursor parent, 3746 CXClientData client_data) { 3747 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent); 3748} 3749 3750extern "C" { 3751 3752void clang_annotateTokens(CXTranslationUnit TU, 3753 CXToken *Tokens, unsigned NumTokens, 3754 CXCursor *Cursors) { 3755 3756 if (NumTokens == 0 || !Tokens || !Cursors) 3757 return; 3758 3759 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU); 3760 if (!CXXUnit) { 3761 // Any token we don't specifically annotate will have a NULL cursor. 3762 const CXCursor &C = clang_getNullCursor(); 3763 for (unsigned I = 0; I != NumTokens; ++I) 3764 Cursors[I] = C; 3765 return; 3766 } 3767 3768 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 3769 3770 // Determine the region of interest, which contains all of the tokens. 3771 SourceRange RegionOfInterest; 3772 RegionOfInterest.setBegin(cxloc::translateSourceLocation( 3773 clang_getTokenLocation(TU, Tokens[0]))); 3774 RegionOfInterest.setEnd(cxloc::translateSourceLocation( 3775 clang_getTokenLocation(TU, 3776 Tokens[NumTokens - 1]))); 3777 3778 // A mapping from the source locations found when re-lexing or traversing the 3779 // region of interest to the corresponding cursors. 3780 AnnotateTokensData Annotated; 3781 3782 // Relex the tokens within the source range to look for preprocessing 3783 // directives. 3784 SourceManager &SourceMgr = CXXUnit->getSourceManager(); 3785 std::pair<FileID, unsigned> BeginLocInfo 3786 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin()); 3787 std::pair<FileID, unsigned> EndLocInfo 3788 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd()); 3789 3790 llvm::StringRef Buffer; 3791 bool Invalid = false; 3792 if (BeginLocInfo.first == EndLocInfo.first && 3793 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) && 3794 !Invalid) { 3795 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first), 3796 CXXUnit->getASTContext().getLangOptions(), 3797 Buffer.begin(), Buffer.data() + BeginLocInfo.second, 3798 Buffer.end()); 3799 Lex.SetCommentRetentionState(true); 3800 3801 // Lex tokens in raw mode until we hit the end of the range, to avoid 3802 // entering #includes or expanding macros. 3803 while (true) { 3804 Token Tok; 3805 Lex.LexFromRawLexer(Tok); 3806 3807 reprocess: 3808 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) { 3809 // We have found a preprocessing directive. Gobble it up so that we 3810 // don't see it while preprocessing these tokens later, but keep track of 3811 // all of the token locations inside this preprocessing directive so that 3812 // we can annotate them appropriately. 3813 // 3814 // FIXME: Some simple tests here could identify macro definitions and 3815 // #undefs, to provide specific cursor kinds for those. 3816 std::vector<SourceLocation> Locations; 3817 do { 3818 Locations.push_back(Tok.getLocation()); 3819 Lex.LexFromRawLexer(Tok); 3820 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof)); 3821 3822 using namespace cxcursor; 3823 CXCursor Cursor 3824 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(), 3825 Locations.back()), 3826 CXXUnit); 3827 for (unsigned I = 0, N = Locations.size(); I != N; ++I) { 3828 Annotated[Locations[I].getRawEncoding()] = Cursor; 3829 } 3830 3831 if (Tok.isAtStartOfLine()) 3832 goto reprocess; 3833 3834 continue; 3835 } 3836 3837 if (Tok.is(tok::eof)) 3838 break; 3839 } 3840 } 3841 3842 // Annotate all of the source locations in the region of interest that map to 3843 // a specific cursor. 3844 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens, 3845 CXXUnit, RegionOfInterest); 3846 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit)); 3847} 3848} // end: extern "C" 3849 3850//===----------------------------------------------------------------------===// 3851// Operations for querying linkage of a cursor. 3852//===----------------------------------------------------------------------===// 3853 3854extern "C" { 3855CXLinkageKind clang_getCursorLinkage(CXCursor cursor) { 3856 if (!clang_isDeclaration(cursor.kind)) 3857 return CXLinkage_Invalid; 3858 3859 Decl *D = cxcursor::getCursorDecl(cursor); 3860 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D)) 3861 switch (ND->getLinkage()) { 3862 case NoLinkage: return CXLinkage_NoLinkage; 3863 case InternalLinkage: return CXLinkage_Internal; 3864 case UniqueExternalLinkage: return CXLinkage_UniqueExternal; 3865 case ExternalLinkage: return CXLinkage_External; 3866 }; 3867 3868 return CXLinkage_Invalid; 3869} 3870} // end: extern "C" 3871 3872//===----------------------------------------------------------------------===// 3873// Operations for querying language of a cursor. 3874//===----------------------------------------------------------------------===// 3875 3876static CXLanguageKind getDeclLanguage(const Decl *D) { 3877 switch (D->getKind()) { 3878 default: 3879 break; 3880 case Decl::ImplicitParam: 3881 case Decl::ObjCAtDefsField: 3882 case Decl::ObjCCategory: 3883 case Decl::ObjCCategoryImpl: 3884 case Decl::ObjCClass: 3885 case Decl::ObjCCompatibleAlias: 3886 case Decl::ObjCForwardProtocol: 3887 case Decl::ObjCImplementation: 3888 case Decl::ObjCInterface: 3889 case Decl::ObjCIvar: 3890 case Decl::ObjCMethod: 3891 case Decl::ObjCProperty: 3892 case Decl::ObjCPropertyImpl: 3893 case Decl::ObjCProtocol: 3894 return CXLanguage_ObjC; 3895 case Decl::CXXConstructor: 3896 case Decl::CXXConversion: 3897 case Decl::CXXDestructor: 3898 case Decl::CXXMethod: 3899 case Decl::CXXRecord: 3900 case Decl::ClassTemplate: 3901 case Decl::ClassTemplatePartialSpecialization: 3902 case Decl::ClassTemplateSpecialization: 3903 case Decl::Friend: 3904 case Decl::FriendTemplate: 3905 case Decl::FunctionTemplate: 3906 case Decl::LinkageSpec: 3907 case Decl::Namespace: 3908 case Decl::NamespaceAlias: 3909 case Decl::NonTypeTemplateParm: 3910 case Decl::StaticAssert: 3911 case Decl::TemplateTemplateParm: 3912 case Decl::TemplateTypeParm: 3913 case Decl::UnresolvedUsingTypename: 3914 case Decl::UnresolvedUsingValue: 3915 case Decl::Using: 3916 case Decl::UsingDirective: 3917 case Decl::UsingShadow: 3918 return CXLanguage_CPlusPlus; 3919 } 3920 3921 return CXLanguage_C; 3922} 3923 3924extern "C" { 3925 3926enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) { 3927 if (clang_isDeclaration(cursor.kind)) 3928 if (Decl *D = cxcursor::getCursorDecl(cursor)) { 3929 if (D->hasAttr<UnavailableAttr>() || 3930 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())) 3931 return CXAvailability_Available; 3932 3933 if (D->hasAttr<DeprecatedAttr>()) 3934 return CXAvailability_Deprecated; 3935 } 3936 3937 return CXAvailability_Available; 3938} 3939 3940CXLanguageKind clang_getCursorLanguage(CXCursor cursor) { 3941 if (clang_isDeclaration(cursor.kind)) 3942 return getDeclLanguage(cxcursor::getCursorDecl(cursor)); 3943 3944 return CXLanguage_Invalid; 3945} 3946} // end: extern "C" 3947 3948 3949//===----------------------------------------------------------------------===// 3950// C++ AST instrospection. 3951//===----------------------------------------------------------------------===// 3952 3953extern "C" { 3954unsigned clang_CXXMethod_isStatic(CXCursor C) { 3955 if (!clang_isDeclaration(C.kind)) 3956 return 0; 3957 3958 CXXMethodDecl *Method = 0; 3959 Decl *D = cxcursor::getCursorDecl(C); 3960 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D)) 3961 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl()); 3962 else 3963 Method = dyn_cast_or_null<CXXMethodDecl>(D); 3964 return (Method && Method->isStatic()) ? 1 : 0; 3965} 3966 3967} // end: extern "C" 3968 3969//===----------------------------------------------------------------------===// 3970// Attribute introspection. 3971//===----------------------------------------------------------------------===// 3972 3973extern "C" { 3974CXType clang_getIBOutletCollectionType(CXCursor C) { 3975 if (C.kind != CXCursor_IBOutletCollectionAttr) 3976 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C)); 3977 3978 IBOutletCollectionAttr *A = 3979 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C)); 3980 3981 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C)); 3982} 3983} // end: extern "C" 3984 3985//===----------------------------------------------------------------------===// 3986// CXString Operations. 3987//===----------------------------------------------------------------------===// 3988 3989extern "C" { 3990const char *clang_getCString(CXString string) { 3991 return string.Spelling; 3992} 3993 3994void clang_disposeString(CXString string) { 3995 if (string.MustFreeString && string.Spelling) 3996 free((void*)string.Spelling); 3997} 3998 3999} // end: extern "C" 4000 4001namespace clang { namespace cxstring { 4002CXString createCXString(const char *String, bool DupString){ 4003 CXString Str; 4004 if (DupString) { 4005 Str.Spelling = strdup(String); 4006 Str.MustFreeString = 1; 4007 } else { 4008 Str.Spelling = String; 4009 Str.MustFreeString = 0; 4010 } 4011 return Str; 4012} 4013 4014CXString createCXString(llvm::StringRef String, bool DupString) { 4015 CXString Result; 4016 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) { 4017 char *Spelling = (char *)malloc(String.size() + 1); 4018 memmove(Spelling, String.data(), String.size()); 4019 Spelling[String.size()] = 0; 4020 Result.Spelling = Spelling; 4021 Result.MustFreeString = 1; 4022 } else { 4023 Result.Spelling = String.data(); 4024 Result.MustFreeString = 0; 4025 } 4026 return Result; 4027} 4028}} 4029 4030//===----------------------------------------------------------------------===// 4031// Misc. utility functions. 4032//===----------------------------------------------------------------------===// 4033 4034extern "C" { 4035 4036CXString clang_getClangVersion() { 4037 return createCXString(getClangFullVersion()); 4038} 4039 4040} // end: extern "C" 4041