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