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