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