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