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