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