CIndex.cpp revision 83889a7f1f338e343ef72aeeef9c27f7b62c0f0f
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 if (SLoc.isInvalid()) return clang_getNullLocation(); 2270 2271 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc); 2272} 2273 2274CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu, 2275 CXFile file, 2276 unsigned offset) { 2277 if (!tu || !file) 2278 return clang_getNullLocation(); 2279 2280 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu); 2281 SourceLocation Start 2282 = CXXUnit->getSourceManager().getLocation( 2283 static_cast<const FileEntry *>(file), 2284 1, 1); 2285 if (Start.isInvalid()) return clang_getNullLocation(); 2286 2287 SourceLocation SLoc = Start.getFileLocWithOffset(offset); 2288 2289 if (SLoc.isInvalid()) return clang_getNullLocation(); 2290 2291 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc); 2292} 2293 2294CXSourceRange clang_getNullRange() { 2295 CXSourceRange Result = { { 0, 0 }, 0, 0 }; 2296 return Result; 2297} 2298 2299CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) { 2300 if (begin.ptr_data[0] != end.ptr_data[0] || 2301 begin.ptr_data[1] != end.ptr_data[1]) 2302 return clang_getNullRange(); 2303 2304 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] }, 2305 begin.int_data, end.int_data }; 2306 return Result; 2307} 2308 2309void clang_getInstantiationLocation(CXSourceLocation location, 2310 CXFile *file, 2311 unsigned *line, 2312 unsigned *column, 2313 unsigned *offset) { 2314 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data); 2315 2316 if (!location.ptr_data[0] || Loc.isInvalid()) { 2317 if (file) 2318 *file = 0; 2319 if (line) 2320 *line = 0; 2321 if (column) 2322 *column = 0; 2323 if (offset) 2324 *offset = 0; 2325 return; 2326 } 2327 2328 const SourceManager &SM = 2329 *static_cast<const SourceManager*>(location.ptr_data[0]); 2330 SourceLocation InstLoc = SM.getInstantiationLoc(Loc); 2331 2332 if (file) 2333 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc)); 2334 if (line) 2335 *line = SM.getInstantiationLineNumber(InstLoc); 2336 if (column) 2337 *column = SM.getInstantiationColumnNumber(InstLoc); 2338 if (offset) 2339 *offset = SM.getDecomposedLoc(InstLoc).second; 2340} 2341 2342CXSourceLocation clang_getRangeStart(CXSourceRange range) { 2343 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] }, 2344 range.begin_int_data }; 2345 return Result; 2346} 2347 2348CXSourceLocation clang_getRangeEnd(CXSourceRange range) { 2349 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] }, 2350 range.end_int_data }; 2351 return Result; 2352} 2353 2354} // end: extern "C" 2355 2356//===----------------------------------------------------------------------===// 2357// CXFile Operations. 2358//===----------------------------------------------------------------------===// 2359 2360extern "C" { 2361CXString clang_getFileName(CXFile SFile) { 2362 if (!SFile) 2363 return createCXString(NULL); 2364 2365 FileEntry *FEnt = static_cast<FileEntry *>(SFile); 2366 return createCXString(FEnt->getName()); 2367} 2368 2369time_t clang_getFileTime(CXFile SFile) { 2370 if (!SFile) 2371 return 0; 2372 2373 FileEntry *FEnt = static_cast<FileEntry *>(SFile); 2374 return FEnt->getModificationTime(); 2375} 2376 2377CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) { 2378 if (!tu) 2379 return 0; 2380 2381 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu); 2382 2383 FileManager &FMgr = CXXUnit->getFileManager(); 2384 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name)); 2385 return const_cast<FileEntry *>(File); 2386} 2387 2388} // end: extern "C" 2389 2390//===----------------------------------------------------------------------===// 2391// CXCursor Operations. 2392//===----------------------------------------------------------------------===// 2393 2394static Decl *getDeclFromExpr(Stmt *E) { 2395 if (CastExpr *CE = dyn_cast<CastExpr>(E)) 2396 return getDeclFromExpr(CE->getSubExpr()); 2397 2398 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E)) 2399 return RefExpr->getDecl(); 2400 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) 2401 return ME->getMemberDecl(); 2402 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E)) 2403 return RE->getDecl(); 2404 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) 2405 return PRE->getProperty(); 2406 2407 if (CallExpr *CE = dyn_cast<CallExpr>(E)) 2408 return getDeclFromExpr(CE->getCallee()); 2409 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E)) 2410 return OME->getMethodDecl(); 2411 2412 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E)) 2413 return PE->getProtocol(); 2414 2415 return 0; 2416} 2417 2418static SourceLocation getLocationFromExpr(Expr *E) { 2419 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) 2420 return /*FIXME:*/Msg->getLeftLoc(); 2421 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 2422 return DRE->getLocation(); 2423 if (MemberExpr *Member = dyn_cast<MemberExpr>(E)) 2424 return Member->getMemberLoc(); 2425 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) 2426 return Ivar->getLocation(); 2427 return E->getLocStart(); 2428} 2429 2430extern "C" { 2431 2432unsigned clang_visitChildren(CXCursor parent, 2433 CXCursorVisitor visitor, 2434 CXClientData client_data) { 2435 ASTUnit *CXXUnit = getCursorASTUnit(parent); 2436 2437 CursorVisitor CursorVis(CXXUnit, visitor, client_data, 2438 CXXUnit->getMaxPCHLevel()); 2439 return CursorVis.VisitChildren(parent); 2440} 2441 2442static CXString getDeclSpelling(Decl *D) { 2443 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D); 2444 if (!ND) 2445 return createCXString(""); 2446 2447 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND)) 2448 return createCXString(OMD->getSelector().getAsString()); 2449 2450 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND)) 2451 // No, this isn't the same as the code below. getIdentifier() is non-virtual 2452 // and returns different names. NamedDecl returns the class name and 2453 // ObjCCategoryImplDecl returns the category name. 2454 return createCXString(CIMP->getIdentifier()->getNameStart()); 2455 2456 if (isa<UsingDirectiveDecl>(D)) 2457 return createCXString(""); 2458 2459 llvm::SmallString<1024> S; 2460 llvm::raw_svector_ostream os(S); 2461 ND->printName(os); 2462 2463 return createCXString(os.str()); 2464} 2465 2466CXString clang_getCursorSpelling(CXCursor C) { 2467 if (clang_isTranslationUnit(C.kind)) 2468 return clang_getTranslationUnitSpelling(C.data[2]); 2469 2470 if (clang_isReference(C.kind)) { 2471 switch (C.kind) { 2472 case CXCursor_ObjCSuperClassRef: { 2473 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first; 2474 return createCXString(Super->getIdentifier()->getNameStart()); 2475 } 2476 case CXCursor_ObjCClassRef: { 2477 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first; 2478 return createCXString(Class->getIdentifier()->getNameStart()); 2479 } 2480 case CXCursor_ObjCProtocolRef: { 2481 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first; 2482 assert(OID && "getCursorSpelling(): Missing protocol decl"); 2483 return createCXString(OID->getIdentifier()->getNameStart()); 2484 } 2485 case CXCursor_CXXBaseSpecifier: { 2486 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C); 2487 return createCXString(B->getType().getAsString()); 2488 } 2489 case CXCursor_TypeRef: { 2490 TypeDecl *Type = getCursorTypeRef(C).first; 2491 assert(Type && "Missing type decl"); 2492 2493 return createCXString(getCursorContext(C).getTypeDeclType(Type). 2494 getAsString()); 2495 } 2496 case CXCursor_TemplateRef: { 2497 TemplateDecl *Template = getCursorTemplateRef(C).first; 2498 assert(Template && "Missing template decl"); 2499 2500 return createCXString(Template->getNameAsString()); 2501 } 2502 2503 case CXCursor_NamespaceRef: { 2504 NamedDecl *NS = getCursorNamespaceRef(C).first; 2505 assert(NS && "Missing namespace decl"); 2506 2507 return createCXString(NS->getNameAsString()); 2508 } 2509 2510 case CXCursor_MemberRef: { 2511 FieldDecl *Field = getCursorMemberRef(C).first; 2512 assert(Field && "Missing member decl"); 2513 2514 return createCXString(Field->getNameAsString()); 2515 } 2516 2517 case CXCursor_LabelRef: { 2518 LabelStmt *Label = getCursorLabelRef(C).first; 2519 assert(Label && "Missing label"); 2520 2521 return createCXString(Label->getID()->getName()); 2522 } 2523 2524 case CXCursor_OverloadedDeclRef: { 2525 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first; 2526 if (Decl *D = Storage.dyn_cast<Decl *>()) { 2527 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) 2528 return createCXString(ND->getNameAsString()); 2529 return createCXString(""); 2530 } 2531 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>()) 2532 return createCXString(E->getName().getAsString()); 2533 OverloadedTemplateStorage *Ovl 2534 = Storage.get<OverloadedTemplateStorage*>(); 2535 if (Ovl->size() == 0) 2536 return createCXString(""); 2537 return createCXString((*Ovl->begin())->getNameAsString()); 2538 } 2539 2540 default: 2541 return createCXString("<not implemented>"); 2542 } 2543 } 2544 2545 if (clang_isExpression(C.kind)) { 2546 Decl *D = getDeclFromExpr(getCursorExpr(C)); 2547 if (D) 2548 return getDeclSpelling(D); 2549 return createCXString(""); 2550 } 2551 2552 if (clang_isStatement(C.kind)) { 2553 Stmt *S = getCursorStmt(C); 2554 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) 2555 return createCXString(Label->getID()->getName()); 2556 2557 return createCXString(""); 2558 } 2559 2560 if (C.kind == CXCursor_MacroInstantiation) 2561 return createCXString(getCursorMacroInstantiation(C)->getName() 2562 ->getNameStart()); 2563 2564 if (C.kind == CXCursor_MacroDefinition) 2565 return createCXString(getCursorMacroDefinition(C)->getName() 2566 ->getNameStart()); 2567 2568 if (clang_isDeclaration(C.kind)) 2569 return getDeclSpelling(getCursorDecl(C)); 2570 2571 return createCXString(""); 2572} 2573 2574CXString clang_getCursorDisplayName(CXCursor C) { 2575 if (!clang_isDeclaration(C.kind)) 2576 return clang_getCursorSpelling(C); 2577 2578 Decl *D = getCursorDecl(C); 2579 if (!D) 2580 return createCXString(""); 2581 2582 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy; 2583 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 2584 D = FunTmpl->getTemplatedDecl(); 2585 2586 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 2587 llvm::SmallString<64> Str; 2588 llvm::raw_svector_ostream OS(Str); 2589 OS << Function->getNameAsString(); 2590 if (Function->getPrimaryTemplate()) 2591 OS << "<>"; 2592 OS << "("; 2593 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) { 2594 if (I) 2595 OS << ", "; 2596 OS << Function->getParamDecl(I)->getType().getAsString(Policy); 2597 } 2598 2599 if (Function->isVariadic()) { 2600 if (Function->getNumParams()) 2601 OS << ", "; 2602 OS << "..."; 2603 } 2604 OS << ")"; 2605 return createCXString(OS.str()); 2606 } 2607 2608 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) { 2609 llvm::SmallString<64> Str; 2610 llvm::raw_svector_ostream OS(Str); 2611 OS << ClassTemplate->getNameAsString(); 2612 OS << "<"; 2613 TemplateParameterList *Params = ClassTemplate->getTemplateParameters(); 2614 for (unsigned I = 0, N = Params->size(); I != N; ++I) { 2615 if (I) 2616 OS << ", "; 2617 2618 NamedDecl *Param = Params->getParam(I); 2619 if (Param->getIdentifier()) { 2620 OS << Param->getIdentifier()->getName(); 2621 continue; 2622 } 2623 2624 // There is no parameter name, which makes this tricky. Try to come up 2625 // with something useful that isn't too long. 2626 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) 2627 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class"); 2628 else if (NonTypeTemplateParmDecl *NTTP 2629 = dyn_cast<NonTypeTemplateParmDecl>(Param)) 2630 OS << NTTP->getType().getAsString(Policy); 2631 else 2632 OS << "template<...> class"; 2633 } 2634 2635 OS << ">"; 2636 return createCXString(OS.str()); 2637 } 2638 2639 if (ClassTemplateSpecializationDecl *ClassSpec 2640 = dyn_cast<ClassTemplateSpecializationDecl>(D)) { 2641 // If the type was explicitly written, use that. 2642 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten()) 2643 return createCXString(TSInfo->getType().getAsString(Policy)); 2644 2645 llvm::SmallString<64> Str; 2646 llvm::raw_svector_ostream OS(Str); 2647 OS << ClassSpec->getNameAsString(); 2648 OS << TemplateSpecializationType::PrintTemplateArgumentList( 2649 ClassSpec->getTemplateArgs().getFlatArgumentList(), 2650 ClassSpec->getTemplateArgs().flat_size(), 2651 Policy); 2652 return createCXString(OS.str()); 2653 } 2654 2655 return clang_getCursorSpelling(C); 2656} 2657 2658CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) { 2659 switch (Kind) { 2660 case CXCursor_FunctionDecl: 2661 return createCXString("FunctionDecl"); 2662 case CXCursor_TypedefDecl: 2663 return createCXString("TypedefDecl"); 2664 case CXCursor_EnumDecl: 2665 return createCXString("EnumDecl"); 2666 case CXCursor_EnumConstantDecl: 2667 return createCXString("EnumConstantDecl"); 2668 case CXCursor_StructDecl: 2669 return createCXString("StructDecl"); 2670 case CXCursor_UnionDecl: 2671 return createCXString("UnionDecl"); 2672 case CXCursor_ClassDecl: 2673 return createCXString("ClassDecl"); 2674 case CXCursor_FieldDecl: 2675 return createCXString("FieldDecl"); 2676 case CXCursor_VarDecl: 2677 return createCXString("VarDecl"); 2678 case CXCursor_ParmDecl: 2679 return createCXString("ParmDecl"); 2680 case CXCursor_ObjCInterfaceDecl: 2681 return createCXString("ObjCInterfaceDecl"); 2682 case CXCursor_ObjCCategoryDecl: 2683 return createCXString("ObjCCategoryDecl"); 2684 case CXCursor_ObjCProtocolDecl: 2685 return createCXString("ObjCProtocolDecl"); 2686 case CXCursor_ObjCPropertyDecl: 2687 return createCXString("ObjCPropertyDecl"); 2688 case CXCursor_ObjCIvarDecl: 2689 return createCXString("ObjCIvarDecl"); 2690 case CXCursor_ObjCInstanceMethodDecl: 2691 return createCXString("ObjCInstanceMethodDecl"); 2692 case CXCursor_ObjCClassMethodDecl: 2693 return createCXString("ObjCClassMethodDecl"); 2694 case CXCursor_ObjCImplementationDecl: 2695 return createCXString("ObjCImplementationDecl"); 2696 case CXCursor_ObjCCategoryImplDecl: 2697 return createCXString("ObjCCategoryImplDecl"); 2698 case CXCursor_CXXMethod: 2699 return createCXString("CXXMethod"); 2700 case CXCursor_UnexposedDecl: 2701 return createCXString("UnexposedDecl"); 2702 case CXCursor_ObjCSuperClassRef: 2703 return createCXString("ObjCSuperClassRef"); 2704 case CXCursor_ObjCProtocolRef: 2705 return createCXString("ObjCProtocolRef"); 2706 case CXCursor_ObjCClassRef: 2707 return createCXString("ObjCClassRef"); 2708 case CXCursor_TypeRef: 2709 return createCXString("TypeRef"); 2710 case CXCursor_TemplateRef: 2711 return createCXString("TemplateRef"); 2712 case CXCursor_NamespaceRef: 2713 return createCXString("NamespaceRef"); 2714 case CXCursor_MemberRef: 2715 return createCXString("MemberRef"); 2716 case CXCursor_LabelRef: 2717 return createCXString("LabelRef"); 2718 case CXCursor_OverloadedDeclRef: 2719 return createCXString("OverloadedDeclRef"); 2720 case CXCursor_UnexposedExpr: 2721 return createCXString("UnexposedExpr"); 2722 case CXCursor_BlockExpr: 2723 return createCXString("BlockExpr"); 2724 case CXCursor_DeclRefExpr: 2725 return createCXString("DeclRefExpr"); 2726 case CXCursor_MemberRefExpr: 2727 return createCXString("MemberRefExpr"); 2728 case CXCursor_CallExpr: 2729 return createCXString("CallExpr"); 2730 case CXCursor_ObjCMessageExpr: 2731 return createCXString("ObjCMessageExpr"); 2732 case CXCursor_UnexposedStmt: 2733 return createCXString("UnexposedStmt"); 2734 case CXCursor_LabelStmt: 2735 return createCXString("LabelStmt"); 2736 case CXCursor_InvalidFile: 2737 return createCXString("InvalidFile"); 2738 case CXCursor_InvalidCode: 2739 return createCXString("InvalidCode"); 2740 case CXCursor_NoDeclFound: 2741 return createCXString("NoDeclFound"); 2742 case CXCursor_NotImplemented: 2743 return createCXString("NotImplemented"); 2744 case CXCursor_TranslationUnit: 2745 return createCXString("TranslationUnit"); 2746 case CXCursor_UnexposedAttr: 2747 return createCXString("UnexposedAttr"); 2748 case CXCursor_IBActionAttr: 2749 return createCXString("attribute(ibaction)"); 2750 case CXCursor_IBOutletAttr: 2751 return createCXString("attribute(iboutlet)"); 2752 case CXCursor_IBOutletCollectionAttr: 2753 return createCXString("attribute(iboutletcollection)"); 2754 case CXCursor_PreprocessingDirective: 2755 return createCXString("preprocessing directive"); 2756 case CXCursor_MacroDefinition: 2757 return createCXString("macro definition"); 2758 case CXCursor_MacroInstantiation: 2759 return createCXString("macro instantiation"); 2760 case CXCursor_Namespace: 2761 return createCXString("Namespace"); 2762 case CXCursor_LinkageSpec: 2763 return createCXString("LinkageSpec"); 2764 case CXCursor_CXXBaseSpecifier: 2765 return createCXString("C++ base class specifier"); 2766 case CXCursor_Constructor: 2767 return createCXString("CXXConstructor"); 2768 case CXCursor_Destructor: 2769 return createCXString("CXXDestructor"); 2770 case CXCursor_ConversionFunction: 2771 return createCXString("CXXConversion"); 2772 case CXCursor_TemplateTypeParameter: 2773 return createCXString("TemplateTypeParameter"); 2774 case CXCursor_NonTypeTemplateParameter: 2775 return createCXString("NonTypeTemplateParameter"); 2776 case CXCursor_TemplateTemplateParameter: 2777 return createCXString("TemplateTemplateParameter"); 2778 case CXCursor_FunctionTemplate: 2779 return createCXString("FunctionTemplate"); 2780 case CXCursor_ClassTemplate: 2781 return createCXString("ClassTemplate"); 2782 case CXCursor_ClassTemplatePartialSpecialization: 2783 return createCXString("ClassTemplatePartialSpecialization"); 2784 case CXCursor_NamespaceAlias: 2785 return createCXString("NamespaceAlias"); 2786 case CXCursor_UsingDirective: 2787 return createCXString("UsingDirective"); 2788 case CXCursor_UsingDeclaration: 2789 return createCXString("UsingDeclaration"); 2790 } 2791 2792 llvm_unreachable("Unhandled CXCursorKind"); 2793 return createCXString(NULL); 2794} 2795 2796enum CXChildVisitResult GetCursorVisitor(CXCursor cursor, 2797 CXCursor parent, 2798 CXClientData client_data) { 2799 CXCursor *BestCursor = static_cast<CXCursor *>(client_data); 2800 *BestCursor = cursor; 2801 return CXChildVisit_Recurse; 2802} 2803 2804CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) { 2805 if (!TU) 2806 return clang_getNullCursor(); 2807 2808 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU); 2809 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 2810 2811 // Translate the given source location to make it point at the beginning of 2812 // the token under the cursor. 2813 SourceLocation SLoc = cxloc::translateSourceLocation(Loc); 2814 2815 // Guard against an invalid SourceLocation, or we may assert in one 2816 // of the following calls. 2817 if (SLoc.isInvalid()) 2818 return clang_getNullCursor(); 2819 2820 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(), 2821 CXXUnit->getASTContext().getLangOptions()); 2822 2823 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound); 2824 if (SLoc.isValid()) { 2825 // FIXME: Would be great to have a "hint" cursor, then walk from that 2826 // hint cursor upward until we find a cursor whose source range encloses 2827 // the region of interest, rather than starting from the translation unit. 2828 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit); 2829 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result, 2830 Decl::MaxPCHLevel, SourceLocation(SLoc)); 2831 CursorVis.VisitChildren(Parent); 2832 } 2833 return Result; 2834} 2835 2836CXCursor clang_getNullCursor(void) { 2837 return MakeCXCursorInvalid(CXCursor_InvalidFile); 2838} 2839 2840unsigned clang_equalCursors(CXCursor X, CXCursor Y) { 2841 return X == Y; 2842} 2843 2844unsigned clang_isInvalid(enum CXCursorKind K) { 2845 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid; 2846} 2847 2848unsigned clang_isDeclaration(enum CXCursorKind K) { 2849 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl; 2850} 2851 2852unsigned clang_isReference(enum CXCursorKind K) { 2853 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef; 2854} 2855 2856unsigned clang_isExpression(enum CXCursorKind K) { 2857 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr; 2858} 2859 2860unsigned clang_isStatement(enum CXCursorKind K) { 2861 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt; 2862} 2863 2864unsigned clang_isTranslationUnit(enum CXCursorKind K) { 2865 return K == CXCursor_TranslationUnit; 2866} 2867 2868unsigned clang_isPreprocessing(enum CXCursorKind K) { 2869 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing; 2870} 2871 2872unsigned clang_isUnexposed(enum CXCursorKind K) { 2873 switch (K) { 2874 case CXCursor_UnexposedDecl: 2875 case CXCursor_UnexposedExpr: 2876 case CXCursor_UnexposedStmt: 2877 case CXCursor_UnexposedAttr: 2878 return true; 2879 default: 2880 return false; 2881 } 2882} 2883 2884CXCursorKind clang_getCursorKind(CXCursor C) { 2885 return C.kind; 2886} 2887 2888CXSourceLocation clang_getCursorLocation(CXCursor C) { 2889 if (clang_isReference(C.kind)) { 2890 switch (C.kind) { 2891 case CXCursor_ObjCSuperClassRef: { 2892 std::pair<ObjCInterfaceDecl *, SourceLocation> P 2893 = getCursorObjCSuperClassRef(C); 2894 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 2895 } 2896 2897 case CXCursor_ObjCProtocolRef: { 2898 std::pair<ObjCProtocolDecl *, SourceLocation> P 2899 = getCursorObjCProtocolRef(C); 2900 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 2901 } 2902 2903 case CXCursor_ObjCClassRef: { 2904 std::pair<ObjCInterfaceDecl *, SourceLocation> P 2905 = getCursorObjCClassRef(C); 2906 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 2907 } 2908 2909 case CXCursor_TypeRef: { 2910 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C); 2911 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 2912 } 2913 2914 case CXCursor_TemplateRef: { 2915 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C); 2916 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 2917 } 2918 2919 case CXCursor_NamespaceRef: { 2920 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C); 2921 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 2922 } 2923 2924 case CXCursor_MemberRef: { 2925 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C); 2926 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 2927 } 2928 2929 case CXCursor_CXXBaseSpecifier: { 2930 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C); 2931 if (!BaseSpec) 2932 return clang_getNullLocation(); 2933 2934 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo()) 2935 return cxloc::translateSourceLocation(getCursorContext(C), 2936 TSInfo->getTypeLoc().getBeginLoc()); 2937 2938 return cxloc::translateSourceLocation(getCursorContext(C), 2939 BaseSpec->getSourceRange().getBegin()); 2940 } 2941 2942 case CXCursor_LabelRef: { 2943 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C); 2944 return cxloc::translateSourceLocation(getCursorContext(C), P.second); 2945 } 2946 2947 case CXCursor_OverloadedDeclRef: 2948 return cxloc::translateSourceLocation(getCursorContext(C), 2949 getCursorOverloadedDeclRef(C).second); 2950 2951 default: 2952 // FIXME: Need a way to enumerate all non-reference cases. 2953 llvm_unreachable("Missed a reference kind"); 2954 } 2955 } 2956 2957 if (clang_isExpression(C.kind)) 2958 return cxloc::translateSourceLocation(getCursorContext(C), 2959 getLocationFromExpr(getCursorExpr(C))); 2960 2961 if (clang_isStatement(C.kind)) 2962 return cxloc::translateSourceLocation(getCursorContext(C), 2963 getCursorStmt(C)->getLocStart()); 2964 2965 if (C.kind == CXCursor_PreprocessingDirective) { 2966 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin(); 2967 return cxloc::translateSourceLocation(getCursorContext(C), L); 2968 } 2969 2970 if (C.kind == CXCursor_MacroInstantiation) { 2971 SourceLocation L 2972 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin(); 2973 return cxloc::translateSourceLocation(getCursorContext(C), L); 2974 } 2975 2976 if (C.kind == CXCursor_MacroDefinition) { 2977 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation(); 2978 return cxloc::translateSourceLocation(getCursorContext(C), L); 2979 } 2980 2981 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl) 2982 return clang_getNullLocation(); 2983 2984 Decl *D = getCursorDecl(C); 2985 SourceLocation Loc = D->getLocation(); 2986 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D)) 2987 Loc = Class->getClassLoc(); 2988 return cxloc::translateSourceLocation(getCursorContext(C), Loc); 2989} 2990 2991} // end extern "C" 2992 2993static SourceRange getRawCursorExtent(CXCursor C) { 2994 if (clang_isReference(C.kind)) { 2995 switch (C.kind) { 2996 case CXCursor_ObjCSuperClassRef: 2997 return getCursorObjCSuperClassRef(C).second; 2998 2999 case CXCursor_ObjCProtocolRef: 3000 return getCursorObjCProtocolRef(C).second; 3001 3002 case CXCursor_ObjCClassRef: 3003 return getCursorObjCClassRef(C).second; 3004 3005 case CXCursor_TypeRef: 3006 return getCursorTypeRef(C).second; 3007 3008 case CXCursor_TemplateRef: 3009 return getCursorTemplateRef(C).second; 3010 3011 case CXCursor_NamespaceRef: 3012 return getCursorNamespaceRef(C).second; 3013 3014 case CXCursor_MemberRef: 3015 return getCursorMemberRef(C).second; 3016 3017 case CXCursor_CXXBaseSpecifier: 3018 return getCursorCXXBaseSpecifier(C)->getSourceRange(); 3019 3020 case CXCursor_LabelRef: 3021 return getCursorLabelRef(C).second; 3022 3023 case CXCursor_OverloadedDeclRef: 3024 return getCursorOverloadedDeclRef(C).second; 3025 3026 default: 3027 // FIXME: Need a way to enumerate all non-reference cases. 3028 llvm_unreachable("Missed a reference kind"); 3029 } 3030 } 3031 3032 if (clang_isExpression(C.kind)) 3033 return getCursorExpr(C)->getSourceRange(); 3034 3035 if (clang_isStatement(C.kind)) 3036 return getCursorStmt(C)->getSourceRange(); 3037 3038 if (C.kind == CXCursor_PreprocessingDirective) 3039 return cxcursor::getCursorPreprocessingDirective(C); 3040 3041 if (C.kind == CXCursor_MacroInstantiation) 3042 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange(); 3043 3044 if (C.kind == CXCursor_MacroDefinition) 3045 return cxcursor::getCursorMacroDefinition(C)->getSourceRange(); 3046 3047 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) 3048 return getCursorDecl(C)->getSourceRange(); 3049 3050 return SourceRange(); 3051} 3052 3053extern "C" { 3054 3055CXSourceRange clang_getCursorExtent(CXCursor C) { 3056 SourceRange R = getRawCursorExtent(C); 3057 if (R.isInvalid()) 3058 return clang_getNullRange(); 3059 3060 return cxloc::translateSourceRange(getCursorContext(C), R); 3061} 3062 3063CXCursor clang_getCursorReferenced(CXCursor C) { 3064 if (clang_isInvalid(C.kind)) 3065 return clang_getNullCursor(); 3066 3067 ASTUnit *CXXUnit = getCursorASTUnit(C); 3068 if (clang_isDeclaration(C.kind)) { 3069 Decl *D = getCursorDecl(C); 3070 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) 3071 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit); 3072 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D)) 3073 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit); 3074 if (ObjCForwardProtocolDecl *Protocols 3075 = dyn_cast<ObjCForwardProtocolDecl>(D)) 3076 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit); 3077 3078 return C; 3079 } 3080 3081 if (clang_isExpression(C.kind)) { 3082 Expr *E = getCursorExpr(C); 3083 Decl *D = getDeclFromExpr(E); 3084 if (D) 3085 return MakeCXCursor(D, CXXUnit); 3086 3087 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E)) 3088 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit); 3089 3090 return clang_getNullCursor(); 3091 } 3092 3093 if (clang_isStatement(C.kind)) { 3094 Stmt *S = getCursorStmt(C); 3095 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S)) 3096 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C), 3097 getCursorASTUnit(C)); 3098 3099 return clang_getNullCursor(); 3100 } 3101 3102 if (C.kind == CXCursor_MacroInstantiation) { 3103 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition()) 3104 return MakeMacroDefinitionCursor(Def, CXXUnit); 3105 } 3106 3107 if (!clang_isReference(C.kind)) 3108 return clang_getNullCursor(); 3109 3110 switch (C.kind) { 3111 case CXCursor_ObjCSuperClassRef: 3112 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit); 3113 3114 case CXCursor_ObjCProtocolRef: { 3115 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit); 3116 3117 case CXCursor_ObjCClassRef: 3118 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit); 3119 3120 case CXCursor_TypeRef: 3121 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit); 3122 3123 case CXCursor_TemplateRef: 3124 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit); 3125 3126 case CXCursor_NamespaceRef: 3127 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit); 3128 3129 case CXCursor_MemberRef: 3130 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit); 3131 3132 case CXCursor_CXXBaseSpecifier: { 3133 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C); 3134 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(), 3135 CXXUnit)); 3136 } 3137 3138 case CXCursor_LabelRef: 3139 // FIXME: We end up faking the "parent" declaration here because we 3140 // don't want to make CXCursor larger. 3141 return MakeCXCursor(getCursorLabelRef(C).first, 3142 CXXUnit->getASTContext().getTranslationUnitDecl(), 3143 CXXUnit); 3144 3145 case CXCursor_OverloadedDeclRef: 3146 return C; 3147 3148 default: 3149 // We would prefer to enumerate all non-reference cursor kinds here. 3150 llvm_unreachable("Unhandled reference cursor kind"); 3151 break; 3152 } 3153 } 3154 3155 return clang_getNullCursor(); 3156} 3157 3158CXCursor clang_getCursorDefinition(CXCursor C) { 3159 if (clang_isInvalid(C.kind)) 3160 return clang_getNullCursor(); 3161 3162 ASTUnit *CXXUnit = getCursorASTUnit(C); 3163 3164 bool WasReference = false; 3165 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) { 3166 C = clang_getCursorReferenced(C); 3167 WasReference = true; 3168 } 3169 3170 if (C.kind == CXCursor_MacroInstantiation) 3171 return clang_getCursorReferenced(C); 3172 3173 if (!clang_isDeclaration(C.kind)) 3174 return clang_getNullCursor(); 3175 3176 Decl *D = getCursorDecl(C); 3177 if (!D) 3178 return clang_getNullCursor(); 3179 3180 switch (D->getKind()) { 3181 // Declaration kinds that don't really separate the notions of 3182 // declaration and definition. 3183 case Decl::Namespace: 3184 case Decl::Typedef: 3185 case Decl::TemplateTypeParm: 3186 case Decl::EnumConstant: 3187 case Decl::Field: 3188 case Decl::ObjCIvar: 3189 case Decl::ObjCAtDefsField: 3190 case Decl::ImplicitParam: 3191 case Decl::ParmVar: 3192 case Decl::NonTypeTemplateParm: 3193 case Decl::TemplateTemplateParm: 3194 case Decl::ObjCCategoryImpl: 3195 case Decl::ObjCImplementation: 3196 case Decl::AccessSpec: 3197 case Decl::LinkageSpec: 3198 case Decl::ObjCPropertyImpl: 3199 case Decl::FileScopeAsm: 3200 case Decl::StaticAssert: 3201 case Decl::Block: 3202 return C; 3203 3204 // Declaration kinds that don't make any sense here, but are 3205 // nonetheless harmless. 3206 case Decl::TranslationUnit: 3207 break; 3208 3209 // Declaration kinds for which the definition is not resolvable. 3210 case Decl::UnresolvedUsingTypename: 3211 case Decl::UnresolvedUsingValue: 3212 break; 3213 3214 case Decl::UsingDirective: 3215 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(), 3216 CXXUnit); 3217 3218 case Decl::NamespaceAlias: 3219 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit); 3220 3221 case Decl::Enum: 3222 case Decl::Record: 3223 case Decl::CXXRecord: 3224 case Decl::ClassTemplateSpecialization: 3225 case Decl::ClassTemplatePartialSpecialization: 3226 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition()) 3227 return MakeCXCursor(Def, CXXUnit); 3228 return clang_getNullCursor(); 3229 3230 case Decl::Function: 3231 case Decl::CXXMethod: 3232 case Decl::CXXConstructor: 3233 case Decl::CXXDestructor: 3234 case Decl::CXXConversion: { 3235 const FunctionDecl *Def = 0; 3236 if (cast<FunctionDecl>(D)->getBody(Def)) 3237 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit); 3238 return clang_getNullCursor(); 3239 } 3240 3241 case Decl::Var: { 3242 // Ask the variable if it has a definition. 3243 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition()) 3244 return MakeCXCursor(Def, CXXUnit); 3245 return clang_getNullCursor(); 3246 } 3247 3248 case Decl::FunctionTemplate: { 3249 const FunctionDecl *Def = 0; 3250 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def)) 3251 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit); 3252 return clang_getNullCursor(); 3253 } 3254 3255 case Decl::ClassTemplate: { 3256 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl() 3257 ->getDefinition()) 3258 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(), 3259 CXXUnit); 3260 return clang_getNullCursor(); 3261 } 3262 3263 case Decl::Using: 3264 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D), 3265 D->getLocation(), CXXUnit); 3266 3267 case Decl::UsingShadow: 3268 return clang_getCursorDefinition( 3269 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(), 3270 CXXUnit)); 3271 3272 case Decl::ObjCMethod: { 3273 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D); 3274 if (Method->isThisDeclarationADefinition()) 3275 return C; 3276 3277 // Dig out the method definition in the associated 3278 // @implementation, if we have it. 3279 // FIXME: The ASTs should make finding the definition easier. 3280 if (ObjCInterfaceDecl *Class 3281 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) 3282 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation()) 3283 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(), 3284 Method->isInstanceMethod())) 3285 if (Def->isThisDeclarationADefinition()) 3286 return MakeCXCursor(Def, CXXUnit); 3287 3288 return clang_getNullCursor(); 3289 } 3290 3291 case Decl::ObjCCategory: 3292 if (ObjCCategoryImplDecl *Impl 3293 = cast<ObjCCategoryDecl>(D)->getImplementation()) 3294 return MakeCXCursor(Impl, CXXUnit); 3295 return clang_getNullCursor(); 3296 3297 case Decl::ObjCProtocol: 3298 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl()) 3299 return C; 3300 return clang_getNullCursor(); 3301 3302 case Decl::ObjCInterface: 3303 // There are two notions of a "definition" for an Objective-C 3304 // class: the interface and its implementation. When we resolved a 3305 // reference to an Objective-C class, produce the @interface as 3306 // the definition; when we were provided with the interface, 3307 // produce the @implementation as the definition. 3308 if (WasReference) { 3309 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl()) 3310 return C; 3311 } else if (ObjCImplementationDecl *Impl 3312 = cast<ObjCInterfaceDecl>(D)->getImplementation()) 3313 return MakeCXCursor(Impl, CXXUnit); 3314 return clang_getNullCursor(); 3315 3316 case Decl::ObjCProperty: 3317 // FIXME: We don't really know where to find the 3318 // ObjCPropertyImplDecls that implement this property. 3319 return clang_getNullCursor(); 3320 3321 case Decl::ObjCCompatibleAlias: 3322 if (ObjCInterfaceDecl *Class 3323 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface()) 3324 if (!Class->isForwardDecl()) 3325 return MakeCXCursor(Class, CXXUnit); 3326 3327 return clang_getNullCursor(); 3328 3329 case Decl::ObjCForwardProtocol: 3330 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D), 3331 D->getLocation(), CXXUnit); 3332 3333 case Decl::ObjCClass: 3334 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(), 3335 CXXUnit); 3336 3337 case Decl::Friend: 3338 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl()) 3339 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit)); 3340 return clang_getNullCursor(); 3341 3342 case Decl::FriendTemplate: 3343 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl()) 3344 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit)); 3345 return clang_getNullCursor(); 3346 } 3347 3348 return clang_getNullCursor(); 3349} 3350 3351unsigned clang_isCursorDefinition(CXCursor C) { 3352 if (!clang_isDeclaration(C.kind)) 3353 return 0; 3354 3355 return clang_getCursorDefinition(C) == C; 3356} 3357 3358unsigned clang_getNumOverloadedDecls(CXCursor C) { 3359 if (C.kind != CXCursor_OverloadedDeclRef) 3360 return 0; 3361 3362 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first; 3363 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>()) 3364 return E->getNumDecls(); 3365 3366 if (OverloadedTemplateStorage *S 3367 = Storage.dyn_cast<OverloadedTemplateStorage*>()) 3368 return S->size(); 3369 3370 Decl *D = Storage.get<Decl*>(); 3371 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) 3372 return Using->getNumShadowDecls(); 3373 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D)) 3374 return Classes->size(); 3375 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D)) 3376 return Protocols->protocol_size(); 3377 3378 return 0; 3379} 3380 3381CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) { 3382 if (cursor.kind != CXCursor_OverloadedDeclRef) 3383 return clang_getNullCursor(); 3384 3385 if (index >= clang_getNumOverloadedDecls(cursor)) 3386 return clang_getNullCursor(); 3387 3388 ASTUnit *Unit = getCursorASTUnit(cursor); 3389 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first; 3390 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>()) 3391 return MakeCXCursor(E->decls_begin()[index], Unit); 3392 3393 if (OverloadedTemplateStorage *S 3394 = Storage.dyn_cast<OverloadedTemplateStorage*>()) 3395 return MakeCXCursor(S->begin()[index], Unit); 3396 3397 Decl *D = Storage.get<Decl*>(); 3398 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) { 3399 // FIXME: This is, unfortunately, linear time. 3400 UsingDecl::shadow_iterator Pos = Using->shadow_begin(); 3401 std::advance(Pos, index); 3402 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit); 3403 } 3404 3405 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D)) 3406 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit); 3407 3408 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D)) 3409 return MakeCXCursor(Protocols->protocol_begin()[index], Unit); 3410 3411 return clang_getNullCursor(); 3412} 3413 3414void clang_getDefinitionSpellingAndExtent(CXCursor C, 3415 const char **startBuf, 3416 const char **endBuf, 3417 unsigned *startLine, 3418 unsigned *startColumn, 3419 unsigned *endLine, 3420 unsigned *endColumn) { 3421 assert(getCursorDecl(C) && "CXCursor has null decl"); 3422 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C)); 3423 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND); 3424 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody()); 3425 3426 SourceManager &SM = FD->getASTContext().getSourceManager(); 3427 *startBuf = SM.getCharacterData(Body->getLBracLoc()); 3428 *endBuf = SM.getCharacterData(Body->getRBracLoc()); 3429 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc()); 3430 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc()); 3431 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc()); 3432 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc()); 3433} 3434 3435void clang_enableStackTraces(void) { 3436 llvm::sys::PrintStackTraceOnErrorSignal(); 3437} 3438 3439} // end: extern "C" 3440 3441//===----------------------------------------------------------------------===// 3442// Token-based Operations. 3443//===----------------------------------------------------------------------===// 3444 3445/* CXToken layout: 3446 * int_data[0]: a CXTokenKind 3447 * int_data[1]: starting token location 3448 * int_data[2]: token length 3449 * int_data[3]: reserved 3450 * ptr_data: for identifiers and keywords, an IdentifierInfo*. 3451 * otherwise unused. 3452 */ 3453extern "C" { 3454 3455CXTokenKind clang_getTokenKind(CXToken CXTok) { 3456 return static_cast<CXTokenKind>(CXTok.int_data[0]); 3457} 3458 3459CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) { 3460 switch (clang_getTokenKind(CXTok)) { 3461 case CXToken_Identifier: 3462 case CXToken_Keyword: 3463 // We know we have an IdentifierInfo*, so use that. 3464 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data) 3465 ->getNameStart()); 3466 3467 case CXToken_Literal: { 3468 // We have stashed the starting pointer in the ptr_data field. Use it. 3469 const char *Text = static_cast<const char *>(CXTok.ptr_data); 3470 return createCXString(llvm::StringRef(Text, CXTok.int_data[2])); 3471 } 3472 3473 case CXToken_Punctuation: 3474 case CXToken_Comment: 3475 break; 3476 } 3477 3478 // We have to find the starting buffer pointer the hard way, by 3479 // deconstructing the source location. 3480 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU); 3481 if (!CXXUnit) 3482 return createCXString(""); 3483 3484 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]); 3485 std::pair<FileID, unsigned> LocInfo 3486 = CXXUnit->getSourceManager().getDecomposedLoc(Loc); 3487 bool Invalid = false; 3488 llvm::StringRef Buffer 3489 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid); 3490 if (Invalid) 3491 return createCXString(""); 3492 3493 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2])); 3494} 3495 3496CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) { 3497 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU); 3498 if (!CXXUnit) 3499 return clang_getNullLocation(); 3500 3501 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), 3502 SourceLocation::getFromRawEncoding(CXTok.int_data[1])); 3503} 3504 3505CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) { 3506 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU); 3507 if (!CXXUnit) 3508 return clang_getNullRange(); 3509 3510 return cxloc::translateSourceRange(CXXUnit->getASTContext(), 3511 SourceLocation::getFromRawEncoding(CXTok.int_data[1])); 3512} 3513 3514void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range, 3515 CXToken **Tokens, unsigned *NumTokens) { 3516 if (Tokens) 3517 *Tokens = 0; 3518 if (NumTokens) 3519 *NumTokens = 0; 3520 3521 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU); 3522 if (!CXXUnit || !Tokens || !NumTokens) 3523 return; 3524 3525 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 3526 3527 SourceRange R = cxloc::translateCXSourceRange(Range); 3528 if (R.isInvalid()) 3529 return; 3530 3531 SourceManager &SourceMgr = CXXUnit->getSourceManager(); 3532 std::pair<FileID, unsigned> BeginLocInfo 3533 = SourceMgr.getDecomposedLoc(R.getBegin()); 3534 std::pair<FileID, unsigned> EndLocInfo 3535 = SourceMgr.getDecomposedLoc(R.getEnd()); 3536 3537 // Cannot tokenize across files. 3538 if (BeginLocInfo.first != EndLocInfo.first) 3539 return; 3540 3541 // Create a lexer 3542 bool Invalid = false; 3543 llvm::StringRef Buffer 3544 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid); 3545 if (Invalid) 3546 return; 3547 3548 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first), 3549 CXXUnit->getASTContext().getLangOptions(), 3550 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end()); 3551 Lex.SetCommentRetentionState(true); 3552 3553 // Lex tokens until we hit the end of the range. 3554 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second; 3555 llvm::SmallVector<CXToken, 32> CXTokens; 3556 Token Tok; 3557 bool previousWasAt = false; 3558 do { 3559 // Lex the next token 3560 Lex.LexFromRawLexer(Tok); 3561 if (Tok.is(tok::eof)) 3562 break; 3563 3564 // Initialize the CXToken. 3565 CXToken CXTok; 3566 3567 // - Common fields 3568 CXTok.int_data[1] = Tok.getLocation().getRawEncoding(); 3569 CXTok.int_data[2] = Tok.getLength(); 3570 CXTok.int_data[3] = 0; 3571 3572 // - Kind-specific fields 3573 if (Tok.isLiteral()) { 3574 CXTok.int_data[0] = CXToken_Literal; 3575 CXTok.ptr_data = (void *)Tok.getLiteralData(); 3576 } else if (Tok.is(tok::identifier)) { 3577 // Lookup the identifier to determine whether we have a keyword. 3578 std::pair<FileID, unsigned> LocInfo 3579 = SourceMgr.getDecomposedLoc(Tok.getLocation()); 3580 bool Invalid = false; 3581 llvm::StringRef Buf 3582 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid); 3583 if (Invalid) 3584 return; 3585 3586 const char *StartPos = Buf.data() + LocInfo.second; 3587 IdentifierInfo *II 3588 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos); 3589 3590 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) { 3591 CXTok.int_data[0] = CXToken_Keyword; 3592 } 3593 else { 3594 CXTok.int_data[0] = II->getTokenID() == tok::identifier? 3595 CXToken_Identifier 3596 : CXToken_Keyword; 3597 } 3598 CXTok.ptr_data = II; 3599 } else if (Tok.is(tok::comment)) { 3600 CXTok.int_data[0] = CXToken_Comment; 3601 CXTok.ptr_data = 0; 3602 } else { 3603 CXTok.int_data[0] = CXToken_Punctuation; 3604 CXTok.ptr_data = 0; 3605 } 3606 CXTokens.push_back(CXTok); 3607 previousWasAt = Tok.is(tok::at); 3608 } while (Lex.getBufferLocation() <= EffectiveBufferEnd); 3609 3610 if (CXTokens.empty()) 3611 return; 3612 3613 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size()); 3614 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size()); 3615 *NumTokens = CXTokens.size(); 3616} 3617 3618void clang_disposeTokens(CXTranslationUnit TU, 3619 CXToken *Tokens, unsigned NumTokens) { 3620 free(Tokens); 3621} 3622 3623} // end: extern "C" 3624 3625//===----------------------------------------------------------------------===// 3626// Token annotation APIs. 3627//===----------------------------------------------------------------------===// 3628 3629typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData; 3630static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor, 3631 CXCursor parent, 3632 CXClientData client_data); 3633namespace { 3634class AnnotateTokensWorker { 3635 AnnotateTokensData &Annotated; 3636 CXToken *Tokens; 3637 CXCursor *Cursors; 3638 unsigned NumTokens; 3639 unsigned TokIdx; 3640 CursorVisitor AnnotateVis; 3641 SourceManager &SrcMgr; 3642 3643 bool MoreTokens() const { return TokIdx < NumTokens; } 3644 unsigned NextToken() const { return TokIdx; } 3645 void AdvanceToken() { ++TokIdx; } 3646 SourceLocation GetTokenLoc(unsigned tokI) { 3647 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]); 3648 } 3649 3650public: 3651 AnnotateTokensWorker(AnnotateTokensData &annotated, 3652 CXToken *tokens, CXCursor *cursors, unsigned numTokens, 3653 ASTUnit *CXXUnit, SourceRange RegionOfInterest) 3654 : Annotated(annotated), Tokens(tokens), Cursors(cursors), 3655 NumTokens(numTokens), TokIdx(0), 3656 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this, 3657 Decl::MaxPCHLevel, RegionOfInterest), 3658 SrcMgr(CXXUnit->getSourceManager()) {} 3659 3660 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); } 3661 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent); 3662 void AnnotateTokens(CXCursor parent); 3663}; 3664} 3665 3666void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) { 3667 // Walk the AST within the region of interest, annotating tokens 3668 // along the way. 3669 VisitChildren(parent); 3670 3671 for (unsigned I = 0 ; I < TokIdx ; ++I) { 3672 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]); 3673 if (Pos != Annotated.end()) 3674 Cursors[I] = Pos->second; 3675 } 3676 3677 // Finish up annotating any tokens left. 3678 if (!MoreTokens()) 3679 return; 3680 3681 const CXCursor &C = clang_getNullCursor(); 3682 for (unsigned I = TokIdx ; I < NumTokens ; ++I) { 3683 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]); 3684 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second; 3685 } 3686} 3687 3688enum CXChildVisitResult 3689AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) { 3690 CXSourceLocation Loc = clang_getCursorLocation(cursor); 3691 // We can always annotate a preprocessing directive/macro instantiation. 3692 if (clang_isPreprocessing(cursor.kind)) { 3693 Annotated[Loc.int_data] = cursor; 3694 return CXChildVisit_Recurse; 3695 } 3696 3697 SourceRange cursorRange = getRawCursorExtent(cursor); 3698 3699 if (cursorRange.isInvalid()) 3700 return CXChildVisit_Continue; 3701 3702 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data); 3703 3704 // Adjust the annotated range based specific declarations. 3705 const enum CXCursorKind cursorK = clang_getCursorKind(cursor); 3706 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) { 3707 Decl *D = cxcursor::getCursorDecl(cursor); 3708 // Don't visit synthesized ObjC methods, since they have no syntatic 3709 // representation in the source. 3710 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 3711 if (MD->isSynthesized()) 3712 return CXChildVisit_Continue; 3713 } 3714 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 3715 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) { 3716 TypeLoc TL = TI->getTypeLoc(); 3717 SourceLocation TLoc = TL.getSourceRange().getBegin(); 3718 if (TLoc.isValid() && 3719 SrcMgr.isBeforeInTranslationUnit(TLoc, L)) 3720 cursorRange.setBegin(TLoc); 3721 } 3722 } 3723 } 3724 3725 // If the location of the cursor occurs within a macro instantiation, record 3726 // the spelling location of the cursor in our annotation map. We can then 3727 // paper over the token labelings during a post-processing step to try and 3728 // get cursor mappings for tokens that are the *arguments* of a macro 3729 // instantiation. 3730 if (L.isMacroID()) { 3731 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding(); 3732 // Only invalidate the old annotation if it isn't part of a preprocessing 3733 // directive. Here we assume that the default construction of CXCursor 3734 // results in CXCursor.kind being an initialized value (i.e., 0). If 3735 // this isn't the case, we can fix by doing lookup + insertion. 3736 3737 CXCursor &oldC = Annotated[rawEncoding]; 3738 if (!clang_isPreprocessing(oldC.kind)) 3739 oldC = cursor; 3740 } 3741 3742 const enum CXCursorKind K = clang_getCursorKind(parent); 3743 const CXCursor updateC = 3744 (clang_isInvalid(K) || K == CXCursor_TranslationUnit) 3745 ? clang_getNullCursor() : parent; 3746 3747 while (MoreTokens()) { 3748 const unsigned I = NextToken(); 3749 SourceLocation TokLoc = GetTokenLoc(I); 3750 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 3751 case RangeBefore: 3752 Cursors[I] = updateC; 3753 AdvanceToken(); 3754 continue; 3755 case RangeAfter: 3756 case RangeOverlap: 3757 break; 3758 } 3759 break; 3760 } 3761 3762 // Visit children to get their cursor information. 3763 const unsigned BeforeChildren = NextToken(); 3764 VisitChildren(cursor); 3765 const unsigned AfterChildren = NextToken(); 3766 3767 // Adjust 'Last' to the last token within the extent of the cursor. 3768 while (MoreTokens()) { 3769 const unsigned I = NextToken(); 3770 SourceLocation TokLoc = GetTokenLoc(I); 3771 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 3772 case RangeBefore: 3773 assert(0 && "Infeasible"); 3774 case RangeAfter: 3775 break; 3776 case RangeOverlap: 3777 Cursors[I] = updateC; 3778 AdvanceToken(); 3779 continue; 3780 } 3781 break; 3782 } 3783 const unsigned Last = NextToken(); 3784 3785 // Scan the tokens that are at the beginning of the cursor, but are not 3786 // capture by the child cursors. 3787 3788 // For AST elements within macros, rely on a post-annotate pass to 3789 // to correctly annotate the tokens with cursors. Otherwise we can 3790 // get confusing results of having tokens that map to cursors that really 3791 // are expanded by an instantiation. 3792 if (L.isMacroID()) 3793 cursor = clang_getNullCursor(); 3794 3795 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) { 3796 if (!clang_isInvalid(clang_getCursorKind(Cursors[I]))) 3797 break; 3798 Cursors[I] = cursor; 3799 } 3800 // Scan the tokens that are at the end of the cursor, but are not captured 3801 // but the child cursors. 3802 for (unsigned I = AfterChildren; I != Last; ++I) 3803 Cursors[I] = cursor; 3804 3805 TokIdx = Last; 3806 return CXChildVisit_Continue; 3807} 3808 3809static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor, 3810 CXCursor parent, 3811 CXClientData client_data) { 3812 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent); 3813} 3814 3815extern "C" { 3816 3817void clang_annotateTokens(CXTranslationUnit TU, 3818 CXToken *Tokens, unsigned NumTokens, 3819 CXCursor *Cursors) { 3820 3821 if (NumTokens == 0 || !Tokens || !Cursors) 3822 return; 3823 3824 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU); 3825 if (!CXXUnit) { 3826 // Any token we don't specifically annotate will have a NULL cursor. 3827 const CXCursor &C = clang_getNullCursor(); 3828 for (unsigned I = 0; I != NumTokens; ++I) 3829 Cursors[I] = C; 3830 return; 3831 } 3832 3833 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 3834 3835 // Determine the region of interest, which contains all of the tokens. 3836 SourceRange RegionOfInterest; 3837 RegionOfInterest.setBegin(cxloc::translateSourceLocation( 3838 clang_getTokenLocation(TU, Tokens[0]))); 3839 RegionOfInterest.setEnd(cxloc::translateSourceLocation( 3840 clang_getTokenLocation(TU, 3841 Tokens[NumTokens - 1]))); 3842 3843 // A mapping from the source locations found when re-lexing or traversing the 3844 // region of interest to the corresponding cursors. 3845 AnnotateTokensData Annotated; 3846 3847 // Relex the tokens within the source range to look for preprocessing 3848 // directives. 3849 SourceManager &SourceMgr = CXXUnit->getSourceManager(); 3850 std::pair<FileID, unsigned> BeginLocInfo 3851 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin()); 3852 std::pair<FileID, unsigned> EndLocInfo 3853 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd()); 3854 3855 llvm::StringRef Buffer; 3856 bool Invalid = false; 3857 if (BeginLocInfo.first == EndLocInfo.first && 3858 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) && 3859 !Invalid) { 3860 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first), 3861 CXXUnit->getASTContext().getLangOptions(), 3862 Buffer.begin(), Buffer.data() + BeginLocInfo.second, 3863 Buffer.end()); 3864 Lex.SetCommentRetentionState(true); 3865 3866 // Lex tokens in raw mode until we hit the end of the range, to avoid 3867 // entering #includes or expanding macros. 3868 while (true) { 3869 Token Tok; 3870 Lex.LexFromRawLexer(Tok); 3871 3872 reprocess: 3873 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) { 3874 // We have found a preprocessing directive. Gobble it up so that we 3875 // don't see it while preprocessing these tokens later, but keep track of 3876 // all of the token locations inside this preprocessing directive so that 3877 // we can annotate them appropriately. 3878 // 3879 // FIXME: Some simple tests here could identify macro definitions and 3880 // #undefs, to provide specific cursor kinds for those. 3881 std::vector<SourceLocation> Locations; 3882 do { 3883 Locations.push_back(Tok.getLocation()); 3884 Lex.LexFromRawLexer(Tok); 3885 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof)); 3886 3887 using namespace cxcursor; 3888 CXCursor Cursor 3889 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(), 3890 Locations.back()), 3891 CXXUnit); 3892 for (unsigned I = 0, N = Locations.size(); I != N; ++I) { 3893 Annotated[Locations[I].getRawEncoding()] = Cursor; 3894 } 3895 3896 if (Tok.isAtStartOfLine()) 3897 goto reprocess; 3898 3899 continue; 3900 } 3901 3902 if (Tok.is(tok::eof)) 3903 break; 3904 } 3905 } 3906 3907 // Annotate all of the source locations in the region of interest that map to 3908 // a specific cursor. 3909 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens, 3910 CXXUnit, RegionOfInterest); 3911 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit)); 3912} 3913} // end: extern "C" 3914 3915//===----------------------------------------------------------------------===// 3916// Operations for querying linkage of a cursor. 3917//===----------------------------------------------------------------------===// 3918 3919extern "C" { 3920CXLinkageKind clang_getCursorLinkage(CXCursor cursor) { 3921 if (!clang_isDeclaration(cursor.kind)) 3922 return CXLinkage_Invalid; 3923 3924 Decl *D = cxcursor::getCursorDecl(cursor); 3925 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D)) 3926 switch (ND->getLinkage()) { 3927 case NoLinkage: return CXLinkage_NoLinkage; 3928 case InternalLinkage: return CXLinkage_Internal; 3929 case UniqueExternalLinkage: return CXLinkage_UniqueExternal; 3930 case ExternalLinkage: return CXLinkage_External; 3931 }; 3932 3933 return CXLinkage_Invalid; 3934} 3935} // end: extern "C" 3936 3937//===----------------------------------------------------------------------===// 3938// Operations for querying language of a cursor. 3939//===----------------------------------------------------------------------===// 3940 3941static CXLanguageKind getDeclLanguage(const Decl *D) { 3942 switch (D->getKind()) { 3943 default: 3944 break; 3945 case Decl::ImplicitParam: 3946 case Decl::ObjCAtDefsField: 3947 case Decl::ObjCCategory: 3948 case Decl::ObjCCategoryImpl: 3949 case Decl::ObjCClass: 3950 case Decl::ObjCCompatibleAlias: 3951 case Decl::ObjCForwardProtocol: 3952 case Decl::ObjCImplementation: 3953 case Decl::ObjCInterface: 3954 case Decl::ObjCIvar: 3955 case Decl::ObjCMethod: 3956 case Decl::ObjCProperty: 3957 case Decl::ObjCPropertyImpl: 3958 case Decl::ObjCProtocol: 3959 return CXLanguage_ObjC; 3960 case Decl::CXXConstructor: 3961 case Decl::CXXConversion: 3962 case Decl::CXXDestructor: 3963 case Decl::CXXMethod: 3964 case Decl::CXXRecord: 3965 case Decl::ClassTemplate: 3966 case Decl::ClassTemplatePartialSpecialization: 3967 case Decl::ClassTemplateSpecialization: 3968 case Decl::Friend: 3969 case Decl::FriendTemplate: 3970 case Decl::FunctionTemplate: 3971 case Decl::LinkageSpec: 3972 case Decl::Namespace: 3973 case Decl::NamespaceAlias: 3974 case Decl::NonTypeTemplateParm: 3975 case Decl::StaticAssert: 3976 case Decl::TemplateTemplateParm: 3977 case Decl::TemplateTypeParm: 3978 case Decl::UnresolvedUsingTypename: 3979 case Decl::UnresolvedUsingValue: 3980 case Decl::Using: 3981 case Decl::UsingDirective: 3982 case Decl::UsingShadow: 3983 return CXLanguage_CPlusPlus; 3984 } 3985 3986 return CXLanguage_C; 3987} 3988 3989extern "C" { 3990 3991enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) { 3992 if (clang_isDeclaration(cursor.kind)) 3993 if (Decl *D = cxcursor::getCursorDecl(cursor)) { 3994 if (D->hasAttr<UnavailableAttr>() || 3995 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())) 3996 return CXAvailability_Available; 3997 3998 if (D->hasAttr<DeprecatedAttr>()) 3999 return CXAvailability_Deprecated; 4000 } 4001 4002 return CXAvailability_Available; 4003} 4004 4005CXLanguageKind clang_getCursorLanguage(CXCursor cursor) { 4006 if (clang_isDeclaration(cursor.kind)) 4007 return getDeclLanguage(cxcursor::getCursorDecl(cursor)); 4008 4009 return CXLanguage_Invalid; 4010} 4011 4012CXCursor clang_getCursorSemanticParent(CXCursor cursor) { 4013 if (clang_isDeclaration(cursor.kind)) { 4014 if (Decl *D = getCursorDecl(cursor)) { 4015 DeclContext *DC = D->getDeclContext(); 4016 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor)); 4017 } 4018 } 4019 4020 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) { 4021 if (Decl *D = getCursorDecl(cursor)) 4022 return MakeCXCursor(D, getCursorASTUnit(cursor)); 4023 } 4024 4025 return clang_getNullCursor(); 4026} 4027 4028CXCursor clang_getCursorLexicalParent(CXCursor cursor) { 4029 if (clang_isDeclaration(cursor.kind)) { 4030 if (Decl *D = getCursorDecl(cursor)) { 4031 DeclContext *DC = D->getLexicalDeclContext(); 4032 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor)); 4033 } 4034 } 4035 4036 // FIXME: Note that we can't easily compute the lexical context of a 4037 // statement or expression, so we return nothing. 4038 return clang_getNullCursor(); 4039} 4040 4041static void CollectOverriddenMethods(DeclContext *Ctx, 4042 ObjCMethodDecl *Method, 4043 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) { 4044 if (!Ctx) 4045 return; 4046 4047 // If we have a class or category implementation, jump straight to the 4048 // interface. 4049 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx)) 4050 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods); 4051 4052 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx); 4053 if (!Container) 4054 return; 4055 4056 // Check whether we have a matching method at this level. 4057 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(), 4058 Method->isInstanceMethod())) 4059 if (Method != Overridden) { 4060 // We found an override at this level; there is no need to look 4061 // into other protocols or categories. 4062 Methods.push_back(Overridden); 4063 return; 4064 } 4065 4066 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 4067 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(), 4068 PEnd = Protocol->protocol_end(); 4069 P != PEnd; ++P) 4070 CollectOverriddenMethods(*P, Method, Methods); 4071 } 4072 4073 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) { 4074 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(), 4075 PEnd = Category->protocol_end(); 4076 P != PEnd; ++P) 4077 CollectOverriddenMethods(*P, Method, Methods); 4078 } 4079 4080 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) { 4081 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(), 4082 PEnd = Interface->protocol_end(); 4083 P != PEnd; ++P) 4084 CollectOverriddenMethods(*P, Method, Methods); 4085 4086 for (ObjCCategoryDecl *Category = Interface->getCategoryList(); 4087 Category; Category = Category->getNextClassCategory()) 4088 CollectOverriddenMethods(Category, Method, Methods); 4089 4090 // We only look into the superclass if we haven't found anything yet. 4091 if (Methods.empty()) 4092 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) 4093 return CollectOverriddenMethods(Super, Method, Methods); 4094 } 4095} 4096 4097void clang_getOverriddenCursors(CXCursor cursor, 4098 CXCursor **overridden, 4099 unsigned *num_overridden) { 4100 if (overridden) 4101 *overridden = 0; 4102 if (num_overridden) 4103 *num_overridden = 0; 4104 if (!overridden || !num_overridden) 4105 return; 4106 4107 if (!clang_isDeclaration(cursor.kind)) 4108 return; 4109 4110 Decl *D = getCursorDecl(cursor); 4111 if (!D) 4112 return; 4113 4114 // Handle C++ member functions. 4115 ASTUnit *CXXUnit = getCursorASTUnit(cursor); 4116 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) { 4117 *num_overridden = CXXMethod->size_overridden_methods(); 4118 if (!*num_overridden) 4119 return; 4120 4121 *overridden = new CXCursor [*num_overridden]; 4122 unsigned I = 0; 4123 for (CXXMethodDecl::method_iterator 4124 M = CXXMethod->begin_overridden_methods(), 4125 MEnd = CXXMethod->end_overridden_methods(); 4126 M != MEnd; (void)++M, ++I) 4127 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit); 4128 return; 4129 } 4130 4131 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D); 4132 if (!Method) 4133 return; 4134 4135 // Handle Objective-C methods. 4136 llvm::SmallVector<ObjCMethodDecl *, 4> Methods; 4137 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods); 4138 4139 if (Methods.empty()) 4140 return; 4141 4142 *num_overridden = Methods.size(); 4143 *overridden = new CXCursor [Methods.size()]; 4144 for (unsigned I = 0, N = Methods.size(); I != N; ++I) 4145 (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit); 4146} 4147 4148void clang_disposeOverriddenCursors(CXCursor *overridden) { 4149 delete [] overridden; 4150} 4151 4152} // end: extern "C" 4153 4154 4155//===----------------------------------------------------------------------===// 4156// C++ AST instrospection. 4157//===----------------------------------------------------------------------===// 4158 4159extern "C" { 4160unsigned clang_CXXMethod_isStatic(CXCursor C) { 4161 if (!clang_isDeclaration(C.kind)) 4162 return 0; 4163 4164 CXXMethodDecl *Method = 0; 4165 Decl *D = cxcursor::getCursorDecl(C); 4166 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D)) 4167 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl()); 4168 else 4169 Method = dyn_cast_or_null<CXXMethodDecl>(D); 4170 return (Method && Method->isStatic()) ? 1 : 0; 4171} 4172 4173} // end: extern "C" 4174 4175//===----------------------------------------------------------------------===// 4176// Attribute introspection. 4177//===----------------------------------------------------------------------===// 4178 4179extern "C" { 4180CXType clang_getIBOutletCollectionType(CXCursor C) { 4181 if (C.kind != CXCursor_IBOutletCollectionAttr) 4182 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C)); 4183 4184 IBOutletCollectionAttr *A = 4185 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C)); 4186 4187 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C)); 4188} 4189} // end: extern "C" 4190 4191//===----------------------------------------------------------------------===// 4192// CXString Operations. 4193//===----------------------------------------------------------------------===// 4194 4195extern "C" { 4196const char *clang_getCString(CXString string) { 4197 return string.Spelling; 4198} 4199 4200void clang_disposeString(CXString string) { 4201 if (string.MustFreeString && string.Spelling) 4202 free((void*)string.Spelling); 4203} 4204 4205} // end: extern "C" 4206 4207namespace clang { namespace cxstring { 4208CXString createCXString(const char *String, bool DupString){ 4209 CXString Str; 4210 if (DupString) { 4211 Str.Spelling = strdup(String); 4212 Str.MustFreeString = 1; 4213 } else { 4214 Str.Spelling = String; 4215 Str.MustFreeString = 0; 4216 } 4217 return Str; 4218} 4219 4220CXString createCXString(llvm::StringRef String, bool DupString) { 4221 CXString Result; 4222 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) { 4223 char *Spelling = (char *)malloc(String.size() + 1); 4224 memmove(Spelling, String.data(), String.size()); 4225 Spelling[String.size()] = 0; 4226 Result.Spelling = Spelling; 4227 Result.MustFreeString = 1; 4228 } else { 4229 Result.Spelling = String.data(); 4230 Result.MustFreeString = 0; 4231 } 4232 return Result; 4233} 4234}} 4235 4236//===----------------------------------------------------------------------===// 4237// Misc. utility functions. 4238//===----------------------------------------------------------------------===// 4239 4240extern "C" { 4241 4242CXString clang_getClangVersion() { 4243 return createCXString(getClangFullVersion()); 4244} 4245 4246} // end: extern "C" 4247