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