CIndex.cpp revision d1ded66c4eda8d170222071dec7ebba78bd86ea4
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/ADT/STLExtras.h" 34#include "llvm/ADT/Optional.h" 35#include "clang/Analysis/Support/SaveAndRestore.h" 36#include "llvm/Support/CrashRecoveryContext.h" 37#include "llvm/Support/PrettyStackTrace.h" 38#include "llvm/Support/MemoryBuffer.h" 39#include "llvm/Support/raw_ostream.h" 40#include "llvm/Support/Timer.h" 41#include "llvm/System/Mutex.h" 42#include "llvm/System/Program.h" 43#include "llvm/System/Signals.h" 44#include "llvm/System/Threading.h" 45#include "llvm/Support/Compiler.h" 46 47using namespace clang; 48using namespace clang::cxcursor; 49using namespace clang::cxstring; 50 51/// \brief The result of comparing two source ranges. 52enum RangeComparisonResult { 53 /// \brief Either the ranges overlap or one of the ranges is invalid. 54 RangeOverlap, 55 56 /// \brief The first range ends before the second range starts. 57 RangeBefore, 58 59 /// \brief The first range starts after the second range ends. 60 RangeAfter 61}; 62 63/// \brief Compare two source ranges to determine their relative position in 64/// the translation unit. 65static RangeComparisonResult RangeCompare(SourceManager &SM, 66 SourceRange R1, 67 SourceRange R2) { 68 assert(R1.isValid() && "First range is invalid?"); 69 assert(R2.isValid() && "Second range is invalid?"); 70 if (R1.getEnd() != R2.getBegin() && 71 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin())) 72 return RangeBefore; 73 if (R2.getEnd() != R1.getBegin() && 74 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin())) 75 return RangeAfter; 76 return RangeOverlap; 77} 78 79/// \brief Determine if a source location falls within, before, or after a 80/// a given source range. 81static RangeComparisonResult LocationCompare(SourceManager &SM, 82 SourceLocation L, SourceRange R) { 83 assert(R.isValid() && "First range is invalid?"); 84 assert(L.isValid() && "Second range is invalid?"); 85 if (L == R.getBegin() || L == R.getEnd()) 86 return RangeOverlap; 87 if (SM.isBeforeInTranslationUnit(L, R.getBegin())) 88 return RangeBefore; 89 if (SM.isBeforeInTranslationUnit(R.getEnd(), L)) 90 return RangeAfter; 91 return RangeOverlap; 92} 93 94/// \brief Translate a Clang source range into a CIndex source range. 95/// 96/// Clang internally represents ranges where the end location points to the 97/// start of the token at the end. However, for external clients it is more 98/// useful to have a CXSourceRange be a proper half-open interval. This routine 99/// does the appropriate translation. 100CXSourceRange cxloc::translateSourceRange(const SourceManager &SM, 101 const LangOptions &LangOpts, 102 const CharSourceRange &R) { 103 // We want the last character in this location, so we will adjust the 104 // location accordingly. 105 SourceLocation EndLoc = R.getEnd(); 106 if (EndLoc.isValid() && EndLoc.isMacroID()) 107 EndLoc = SM.getSpellingLoc(EndLoc); 108 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) { 109 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts); 110 EndLoc = EndLoc.getFileLocWithOffset(Length); 111 } 112 113 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts }, 114 R.getBegin().getRawEncoding(), 115 EndLoc.getRawEncoding() }; 116 return Result; 117} 118 119//===----------------------------------------------------------------------===// 120// Cursor visitor. 121//===----------------------------------------------------------------------===// 122 123namespace { 124 125class VisitorJob { 126public: 127 enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind, 128 TypeLocVisitKind, OverloadExprPartsKind, 129 DeclRefExprPartsKind }; 130protected: 131 void *dataA; 132 void *dataB; 133 CXCursor parent; 134 Kind K; 135 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0) 136 : dataA(d1), dataB(d2), parent(C), K(k) {} 137public: 138 Kind getKind() const { return K; } 139 const CXCursor &getParent() const { return parent; } 140 static bool classof(VisitorJob *VJ) { return true; } 141}; 142 143typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList; 144 145// Cursor visitor. 146class CursorVisitor : public DeclVisitor<CursorVisitor, bool>, 147 public TypeLocVisitor<CursorVisitor, bool>, 148 public StmtVisitor<CursorVisitor, bool> 149{ 150 /// \brief The translation unit we are traversing. 151 ASTUnit *TU; 152 153 /// \brief The parent cursor whose children we are traversing. 154 CXCursor Parent; 155 156 /// \brief The declaration that serves at the parent of any statement or 157 /// expression nodes. 158 Decl *StmtParent; 159 160 /// \brief The visitor function. 161 CXCursorVisitor Visitor; 162 163 /// \brief The opaque client data, to be passed along to the visitor. 164 CXClientData ClientData; 165 166 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on 167 // to the visitor. Declarations with a PCH level greater than this value will 168 // be suppressed. 169 unsigned MaxPCHLevel; 170 171 /// \brief When valid, a source range to which the cursor should restrict 172 /// its search. 173 SourceRange RegionOfInterest; 174 175 // FIXME: Eventually remove. This part of a hack to support proper 176 // iteration over all Decls contained lexically within an ObjC container. 177 DeclContext::decl_iterator *DI_current; 178 DeclContext::decl_iterator DE_current; 179 180 // Cache of pre-allocated worklists for data-recursion walk of Stmts. 181 llvm::SmallVector<VisitorWorkList*, 5> WorkListFreeList; 182 llvm::SmallVector<VisitorWorkList*, 5> WorkListCache; 183 184 using DeclVisitor<CursorVisitor, bool>::Visit; 185 using TypeLocVisitor<CursorVisitor, bool>::Visit; 186 using StmtVisitor<CursorVisitor, bool>::Visit; 187 188 /// \brief Determine whether this particular source range comes before, comes 189 /// after, or overlaps the region of interest. 190 /// 191 /// \param R a half-open source range retrieved from the abstract syntax tree. 192 RangeComparisonResult CompareRegionOfInterest(SourceRange R); 193 194 class SetParentRAII { 195 CXCursor &Parent; 196 Decl *&StmtParent; 197 CXCursor OldParent; 198 199 public: 200 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent) 201 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent) 202 { 203 Parent = NewParent; 204 if (clang_isDeclaration(Parent.kind)) 205 StmtParent = getCursorDecl(Parent); 206 } 207 208 ~SetParentRAII() { 209 Parent = OldParent; 210 if (clang_isDeclaration(Parent.kind)) 211 StmtParent = getCursorDecl(Parent); 212 } 213 }; 214 215public: 216 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData, 217 unsigned MaxPCHLevel, 218 SourceRange RegionOfInterest = SourceRange()) 219 : TU(TU), Visitor(Visitor), ClientData(ClientData), 220 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest), 221 DI_current(0) 222 { 223 Parent.kind = CXCursor_NoDeclFound; 224 Parent.data[0] = 0; 225 Parent.data[1] = 0; 226 Parent.data[2] = 0; 227 StmtParent = 0; 228 } 229 230 ~CursorVisitor() { 231 // Free the pre-allocated worklists for data-recursion. 232 for (llvm::SmallVectorImpl<VisitorWorkList*>::iterator 233 I = WorkListCache.begin(), E = WorkListCache.end(); I != E; ++I) { 234 delete *I; 235 } 236 } 237 238 ASTUnit *getASTUnit() const { return TU; } 239 240 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false); 241 242 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator> 243 getPreprocessedEntities(); 244 245 bool VisitChildren(CXCursor Parent); 246 247 // Declaration visitors 248 bool VisitAttributes(Decl *D); 249 bool VisitBlockDecl(BlockDecl *B); 250 bool VisitCXXRecordDecl(CXXRecordDecl *D); 251 llvm::Optional<bool> shouldVisitCursor(CXCursor C); 252 bool VisitDeclContext(DeclContext *DC); 253 bool VisitTranslationUnitDecl(TranslationUnitDecl *D); 254 bool VisitTypedefDecl(TypedefDecl *D); 255 bool VisitTagDecl(TagDecl *D); 256 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D); 257 bool VisitClassTemplatePartialSpecializationDecl( 258 ClassTemplatePartialSpecializationDecl *D); 259 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D); 260 bool VisitEnumConstantDecl(EnumConstantDecl *D); 261 bool VisitDeclaratorDecl(DeclaratorDecl *DD); 262 bool VisitFunctionDecl(FunctionDecl *ND); 263 bool VisitFieldDecl(FieldDecl *D); 264 bool VisitVarDecl(VarDecl *); 265 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D); 266 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D); 267 bool VisitClassTemplateDecl(ClassTemplateDecl *D); 268 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D); 269 bool VisitObjCMethodDecl(ObjCMethodDecl *ND); 270 bool VisitObjCContainerDecl(ObjCContainerDecl *D); 271 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND); 272 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID); 273 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD); 274 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D); 275 bool VisitObjCImplDecl(ObjCImplDecl *D); 276 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D); 277 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D); 278 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations. 279 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D); 280 bool VisitObjCClassDecl(ObjCClassDecl *D); 281 bool VisitLinkageSpecDecl(LinkageSpecDecl *D); 282 bool VisitNamespaceDecl(NamespaceDecl *D); 283 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D); 284 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D); 285 bool VisitUsingDecl(UsingDecl *D); 286 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D); 287 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D); 288 289 // Name visitor 290 bool VisitDeclarationNameInfo(DeclarationNameInfo Name); 291 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range); 292 293 // Template visitors 294 bool VisitTemplateParameters(const TemplateParameterList *Params); 295 bool VisitTemplateName(TemplateName Name, SourceLocation Loc); 296 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL); 297 298 // Type visitors 299 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL); 300 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL); 301 bool VisitTypedefTypeLoc(TypedefTypeLoc TL); 302 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL); 303 bool VisitTagTypeLoc(TagTypeLoc TL); 304 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL); 305 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL); 306 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL); 307 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL); 308 bool VisitPointerTypeLoc(PointerTypeLoc TL); 309 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL); 310 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL); 311 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL); 312 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL); 313 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false); 314 bool VisitArrayTypeLoc(ArrayTypeLoc TL); 315 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL); 316 // FIXME: Implement visitors here when the unimplemented TypeLocs get 317 // implemented 318 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL); 319 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL); 320 321 // Statement visitors 322 bool VisitStmt(Stmt *S); 323 324 // Expression visitors 325 bool VisitOffsetOfExpr(OffsetOfExpr *E); 326 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E); 327 bool VisitAddrLabelExpr(AddrLabelExpr *E); 328 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E); 329 bool VisitVAArgExpr(VAArgExpr *E); 330 bool VisitDesignatedInitExpr(DesignatedInitExpr *E); 331 bool VisitCXXTypeidExpr(CXXTypeidExpr *E); 332 bool VisitCXXUuidofExpr(CXXUuidofExpr *E); 333 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E); 334 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E); 335 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E); 336 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E); 337 bool VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E); 338 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E); 339 340 // Data-recursive visitor functions. 341 bool IsInRegionOfInterest(CXCursor C); 342 bool RunVisitorWorkList(VisitorWorkList &WL); 343 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S); 344 bool VisitDataRecursive(Stmt *S) LLVM_ATTRIBUTE_NOINLINE; 345}; 346 347} // end anonymous namespace 348 349static SourceRange getRawCursorExtent(CXCursor C); 350 351RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) { 352 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest); 353} 354 355/// \brief Visit the given cursor and, if requested by the visitor, 356/// its children. 357/// 358/// \param Cursor the cursor to visit. 359/// 360/// \param CheckRegionOfInterest if true, then the caller already checked that 361/// this cursor is within the region of interest. 362/// 363/// \returns true if the visitation should be aborted, false if it 364/// should continue. 365bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) { 366 if (clang_isInvalid(Cursor.kind)) 367 return false; 368 369 if (clang_isDeclaration(Cursor.kind)) { 370 Decl *D = getCursorDecl(Cursor); 371 assert(D && "Invalid declaration cursor"); 372 if (D->getPCHLevel() > MaxPCHLevel) 373 return false; 374 375 if (D->isImplicit()) 376 return false; 377 } 378 379 // If we have a range of interest, and this cursor doesn't intersect with it, 380 // we're done. 381 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) { 382 SourceRange Range = getRawCursorExtent(Cursor); 383 if (Range.isInvalid() || CompareRegionOfInterest(Range)) 384 return false; 385 } 386 387 switch (Visitor(Cursor, Parent, ClientData)) { 388 case CXChildVisit_Break: 389 return true; 390 391 case CXChildVisit_Continue: 392 return false; 393 394 case CXChildVisit_Recurse: 395 return VisitChildren(Cursor); 396 } 397 398 return false; 399} 400 401std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator> 402CursorVisitor::getPreprocessedEntities() { 403 PreprocessingRecord &PPRec 404 = *TU->getPreprocessor().getPreprocessingRecord(); 405 406 bool OnlyLocalDecls 407 = !TU->isMainFileAST() && TU->getOnlyLocalDecls(); 408 409 // There is no region of interest; we have to walk everything. 410 if (RegionOfInterest.isInvalid()) 411 return std::make_pair(PPRec.begin(OnlyLocalDecls), 412 PPRec.end(OnlyLocalDecls)); 413 414 // Find the file in which the region of interest lands. 415 SourceManager &SM = TU->getSourceManager(); 416 std::pair<FileID, unsigned> Begin 417 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin()); 418 std::pair<FileID, unsigned> End 419 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd()); 420 421 // The region of interest spans files; we have to walk everything. 422 if (Begin.first != End.first) 423 return std::make_pair(PPRec.begin(OnlyLocalDecls), 424 PPRec.end(OnlyLocalDecls)); 425 426 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap 427 = TU->getPreprocessedEntitiesByFile(); 428 if (ByFileMap.empty()) { 429 // Build the mapping from files to sets of preprocessed entities. 430 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls), 431 EEnd = PPRec.end(OnlyLocalDecls); 432 E != EEnd; ++E) { 433 std::pair<FileID, unsigned> P 434 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin()); 435 ByFileMap[P.first].push_back(*E); 436 } 437 } 438 439 return std::make_pair(ByFileMap[Begin.first].begin(), 440 ByFileMap[Begin.first].end()); 441} 442 443/// \brief Visit the children of the given cursor. 444/// 445/// \returns true if the visitation should be aborted, false if it 446/// should continue. 447bool CursorVisitor::VisitChildren(CXCursor Cursor) { 448 if (clang_isReference(Cursor.kind)) { 449 // By definition, references have no children. 450 return false; 451 } 452 453 // Set the Parent field to Cursor, then back to its old value once we're 454 // done. 455 SetParentRAII SetParent(Parent, StmtParent, Cursor); 456 457 if (clang_isDeclaration(Cursor.kind)) { 458 Decl *D = getCursorDecl(Cursor); 459 assert(D && "Invalid declaration cursor"); 460 return VisitAttributes(D) || Visit(D); 461 } 462 463 if (clang_isStatement(Cursor.kind)) 464 return Visit(getCursorStmt(Cursor)); 465 if (clang_isExpression(Cursor.kind)) 466 return Visit(getCursorExpr(Cursor)); 467 468 if (clang_isTranslationUnit(Cursor.kind)) { 469 ASTUnit *CXXUnit = getCursorASTUnit(Cursor); 470 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() && 471 RegionOfInterest.isInvalid()) { 472 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(), 473 TLEnd = CXXUnit->top_level_end(); 474 TL != TLEnd; ++TL) { 475 if (Visit(MakeCXCursor(*TL, CXXUnit), true)) 476 return true; 477 } 478 } else if (VisitDeclContext( 479 CXXUnit->getASTContext().getTranslationUnitDecl())) 480 return true; 481 482 // Walk the preprocessing record. 483 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) { 484 // FIXME: Once we have the ability to deserialize a preprocessing record, 485 // do so. 486 PreprocessingRecord::iterator E, EEnd; 487 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) { 488 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) { 489 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit))) 490 return true; 491 492 continue; 493 } 494 495 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) { 496 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit))) 497 return true; 498 499 continue; 500 } 501 502 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) { 503 if (Visit(MakeInclusionDirectiveCursor(ID, CXXUnit))) 504 return true; 505 506 continue; 507 } 508 } 509 } 510 return false; 511 } 512 513 // Nothing to visit at the moment. 514 return false; 515} 516 517bool CursorVisitor::VisitBlockDecl(BlockDecl *B) { 518 if (Visit(B->getSignatureAsWritten()->getTypeLoc())) 519 return true; 520 521 if (Stmt *Body = B->getBody()) 522 return Visit(MakeCXCursor(Body, StmtParent, TU)); 523 524 return false; 525} 526 527llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) { 528 if (RegionOfInterest.isValid()) { 529 SourceRange Range = getRawCursorExtent(Cursor); 530 if (Range.isInvalid()) 531 return llvm::Optional<bool>(); 532 533 switch (CompareRegionOfInterest(Range)) { 534 case RangeBefore: 535 // This declaration comes before the region of interest; skip it. 536 return llvm::Optional<bool>(); 537 538 case RangeAfter: 539 // This declaration comes after the region of interest; we're done. 540 return false; 541 542 case RangeOverlap: 543 // This declaration overlaps the region of interest; visit it. 544 break; 545 } 546 } 547 return true; 548} 549 550bool CursorVisitor::VisitDeclContext(DeclContext *DC) { 551 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end(); 552 553 // FIXME: Eventually remove. This part of a hack to support proper 554 // iteration over all Decls contained lexically within an ObjC container. 555 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I); 556 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E); 557 558 for ( ; I != E; ++I) { 559 Decl *D = *I; 560 if (D->getLexicalDeclContext() != DC) 561 continue; 562 CXCursor Cursor = MakeCXCursor(D, TU); 563 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor); 564 if (!V.hasValue()) 565 continue; 566 if (!V.getValue()) 567 return false; 568 if (Visit(Cursor, true)) 569 return true; 570 } 571 return false; 572} 573 574bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) { 575 llvm_unreachable("Translation units are visited directly by Visit()"); 576 return false; 577} 578 579bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) { 580 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo()) 581 return Visit(TSInfo->getTypeLoc()); 582 583 return false; 584} 585 586bool CursorVisitor::VisitTagDecl(TagDecl *D) { 587 return VisitDeclContext(D); 588} 589 590bool CursorVisitor::VisitClassTemplateSpecializationDecl( 591 ClassTemplateSpecializationDecl *D) { 592 bool ShouldVisitBody = false; 593 switch (D->getSpecializationKind()) { 594 case TSK_Undeclared: 595 case TSK_ImplicitInstantiation: 596 // Nothing to visit 597 return false; 598 599 case TSK_ExplicitInstantiationDeclaration: 600 case TSK_ExplicitInstantiationDefinition: 601 break; 602 603 case TSK_ExplicitSpecialization: 604 ShouldVisitBody = true; 605 break; 606 } 607 608 // Visit the template arguments used in the specialization. 609 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) { 610 TypeLoc TL = SpecType->getTypeLoc(); 611 if (TemplateSpecializationTypeLoc *TSTLoc 612 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) { 613 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I) 614 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I))) 615 return true; 616 } 617 } 618 619 if (ShouldVisitBody && VisitCXXRecordDecl(D)) 620 return true; 621 622 return false; 623} 624 625bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl( 626 ClassTemplatePartialSpecializationDecl *D) { 627 // FIXME: Visit the "outer" template parameter lists on the TagDecl 628 // before visiting these template parameters. 629 if (VisitTemplateParameters(D->getTemplateParameters())) 630 return true; 631 632 // Visit the partial specialization arguments. 633 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten(); 634 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I) 635 if (VisitTemplateArgumentLoc(TemplateArgs[I])) 636 return true; 637 638 return VisitCXXRecordDecl(D); 639} 640 641bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) { 642 // Visit the default argument. 643 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) 644 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo()) 645 if (Visit(DefArg->getTypeLoc())) 646 return true; 647 648 return false; 649} 650 651bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) { 652 if (Expr *Init = D->getInitExpr()) 653 return Visit(MakeCXCursor(Init, StmtParent, TU)); 654 return false; 655} 656 657bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) { 658 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo()) 659 if (Visit(TSInfo->getTypeLoc())) 660 return true; 661 662 return false; 663} 664 665/// \brief Compare two base or member initializers based on their source order. 666static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) { 667 CXXBaseOrMemberInitializer const * const *X 668 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp); 669 CXXBaseOrMemberInitializer const * const *Y 670 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp); 671 672 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder()) 673 return -1; 674 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder()) 675 return 1; 676 else 677 return 0; 678} 679 680bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) { 681 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) { 682 // Visit the function declaration's syntactic components in the order 683 // written. This requires a bit of work. 684 TypeLoc TL = TSInfo->getTypeLoc(); 685 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL); 686 687 // If we have a function declared directly (without the use of a typedef), 688 // visit just the return type. Otherwise, just visit the function's type 689 // now. 690 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) || 691 (!FTL && Visit(TL))) 692 return true; 693 694 // Visit the nested-name-specifier, if present. 695 if (NestedNameSpecifier *Qualifier = ND->getQualifier()) 696 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange())) 697 return true; 698 699 // Visit the declaration name. 700 if (VisitDeclarationNameInfo(ND->getNameInfo())) 701 return true; 702 703 // FIXME: Visit explicitly-specified template arguments! 704 705 // Visit the function parameters, if we have a function type. 706 if (FTL && VisitFunctionTypeLoc(*FTL, true)) 707 return true; 708 709 // FIXME: Attributes? 710 } 711 712 if (ND->isThisDeclarationADefinition()) { 713 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) { 714 // Find the initializers that were written in the source. 715 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits; 716 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(), 717 IEnd = Constructor->init_end(); 718 I != IEnd; ++I) { 719 if (!(*I)->isWritten()) 720 continue; 721 722 WrittenInits.push_back(*I); 723 } 724 725 // Sort the initializers in source order 726 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(), 727 &CompareCXXBaseOrMemberInitializers); 728 729 // Visit the initializers in source order 730 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) { 731 CXXBaseOrMemberInitializer *Init = WrittenInits[I]; 732 if (Init->isMemberInitializer()) { 733 if (Visit(MakeCursorMemberRef(Init->getMember(), 734 Init->getMemberLocation(), TU))) 735 return true; 736 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) { 737 if (Visit(BaseInfo->getTypeLoc())) 738 return true; 739 } 740 741 // Visit the initializer value. 742 if (Expr *Initializer = Init->getInit()) 743 if (Visit(MakeCXCursor(Initializer, ND, TU))) 744 return true; 745 } 746 } 747 748 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU))) 749 return true; 750 } 751 752 return false; 753} 754 755bool CursorVisitor::VisitFieldDecl(FieldDecl *D) { 756 if (VisitDeclaratorDecl(D)) 757 return true; 758 759 if (Expr *BitWidth = D->getBitWidth()) 760 return Visit(MakeCXCursor(BitWidth, StmtParent, TU)); 761 762 return false; 763} 764 765bool CursorVisitor::VisitVarDecl(VarDecl *D) { 766 if (VisitDeclaratorDecl(D)) 767 return true; 768 769 if (Expr *Init = D->getInit()) 770 return Visit(MakeCXCursor(Init, StmtParent, TU)); 771 772 return false; 773} 774 775bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) { 776 if (VisitDeclaratorDecl(D)) 777 return true; 778 779 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) 780 if (Expr *DefArg = D->getDefaultArgument()) 781 return Visit(MakeCXCursor(DefArg, StmtParent, TU)); 782 783 return false; 784} 785 786bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { 787 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl 788 // before visiting these template parameters. 789 if (VisitTemplateParameters(D->getTemplateParameters())) 790 return true; 791 792 return VisitFunctionDecl(D->getTemplatedDecl()); 793} 794 795bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) { 796 // FIXME: Visit the "outer" template parameter lists on the TagDecl 797 // before visiting these template parameters. 798 if (VisitTemplateParameters(D->getTemplateParameters())) 799 return true; 800 801 return VisitCXXRecordDecl(D->getTemplatedDecl()); 802} 803 804bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) { 805 if (VisitTemplateParameters(D->getTemplateParameters())) 806 return true; 807 808 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() && 809 VisitTemplateArgumentLoc(D->getDefaultArgument())) 810 return true; 811 812 return false; 813} 814 815bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) { 816 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo()) 817 if (Visit(TSInfo->getTypeLoc())) 818 return true; 819 820 for (ObjCMethodDecl::param_iterator P = ND->param_begin(), 821 PEnd = ND->param_end(); 822 P != PEnd; ++P) { 823 if (Visit(MakeCXCursor(*P, TU))) 824 return true; 825 } 826 827 if (ND->isThisDeclarationADefinition() && 828 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU))) 829 return true; 830 831 return false; 832} 833 834namespace { 835 struct ContainerDeclsSort { 836 SourceManager &SM; 837 ContainerDeclsSort(SourceManager &sm) : SM(sm) {} 838 bool operator()(Decl *A, Decl *B) { 839 SourceLocation L_A = A->getLocStart(); 840 SourceLocation L_B = B->getLocStart(); 841 assert(L_A.isValid() && L_B.isValid()); 842 return SM.isBeforeInTranslationUnit(L_A, L_B); 843 } 844 }; 845} 846 847bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) { 848 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially 849 // an @implementation can lexically contain Decls that are not properly 850 // nested in the AST. When we identify such cases, we need to retrofit 851 // this nesting here. 852 if (!DI_current) 853 return VisitDeclContext(D); 854 855 // Scan the Decls that immediately come after the container 856 // in the current DeclContext. If any fall within the 857 // container's lexical region, stash them into a vector 858 // for later processing. 859 llvm::SmallVector<Decl *, 24> DeclsInContainer; 860 SourceLocation EndLoc = D->getSourceRange().getEnd(); 861 SourceManager &SM = TU->getSourceManager(); 862 if (EndLoc.isValid()) { 863 DeclContext::decl_iterator next = *DI_current; 864 while (++next != DE_current) { 865 Decl *D_next = *next; 866 if (!D_next) 867 break; 868 SourceLocation L = D_next->getLocStart(); 869 if (!L.isValid()) 870 break; 871 if (SM.isBeforeInTranslationUnit(L, EndLoc)) { 872 *DI_current = next; 873 DeclsInContainer.push_back(D_next); 874 continue; 875 } 876 break; 877 } 878 } 879 880 // The common case. 881 if (DeclsInContainer.empty()) 882 return VisitDeclContext(D); 883 884 // Get all the Decls in the DeclContext, and sort them with the 885 // additional ones we've collected. Then visit them. 886 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end(); 887 I!=E; ++I) { 888 Decl *subDecl = *I; 889 if (!subDecl || subDecl->getLexicalDeclContext() != D || 890 subDecl->getLocStart().isInvalid()) 891 continue; 892 DeclsInContainer.push_back(subDecl); 893 } 894 895 // Now sort the Decls so that they appear in lexical order. 896 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(), 897 ContainerDeclsSort(SM)); 898 899 // Now visit the decls. 900 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(), 901 E = DeclsInContainer.end(); I != E; ++I) { 902 CXCursor Cursor = MakeCXCursor(*I, TU); 903 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor); 904 if (!V.hasValue()) 905 continue; 906 if (!V.getValue()) 907 return false; 908 if (Visit(Cursor, true)) 909 return true; 910 } 911 return false; 912} 913 914bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) { 915 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(), 916 TU))) 917 return true; 918 919 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin(); 920 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(), 921 E = ND->protocol_end(); I != E; ++I, ++PL) 922 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) 923 return true; 924 925 return VisitObjCContainerDecl(ND); 926} 927 928bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) { 929 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin(); 930 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(), 931 E = PID->protocol_end(); I != E; ++I, ++PL) 932 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) 933 return true; 934 935 return VisitObjCContainerDecl(PID); 936} 937 938bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) { 939 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc())) 940 return true; 941 942 // FIXME: This implements a workaround with @property declarations also being 943 // installed in the DeclContext for the @interface. Eventually this code 944 // should be removed. 945 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext()); 946 if (!CDecl || !CDecl->IsClassExtension()) 947 return false; 948 949 ObjCInterfaceDecl *ID = CDecl->getClassInterface(); 950 if (!ID) 951 return false; 952 953 IdentifierInfo *PropertyId = PD->getIdentifier(); 954 ObjCPropertyDecl *prevDecl = 955 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId); 956 957 if (!prevDecl) 958 return false; 959 960 // Visit synthesized methods since they will be skipped when visiting 961 // the @interface. 962 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl()) 963 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl) 964 if (Visit(MakeCXCursor(MD, TU))) 965 return true; 966 967 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl()) 968 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl) 969 if (Visit(MakeCXCursor(MD, TU))) 970 return true; 971 972 return false; 973} 974 975bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) { 976 // Issue callbacks for super class. 977 if (D->getSuperClass() && 978 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(), 979 D->getSuperClassLoc(), 980 TU))) 981 return true; 982 983 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin(); 984 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(), 985 E = D->protocol_end(); I != E; ++I, ++PL) 986 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) 987 return true; 988 989 return VisitObjCContainerDecl(D); 990} 991 992bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) { 993 return VisitObjCContainerDecl(D); 994} 995 996bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) { 997 // 'ID' could be null when dealing with invalid code. 998 if (ObjCInterfaceDecl *ID = D->getClassInterface()) 999 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU))) 1000 return true; 1001 1002 return VisitObjCImplDecl(D); 1003} 1004 1005bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) { 1006#if 0 1007 // Issue callbacks for super class. 1008 // FIXME: No source location information! 1009 if (D->getSuperClass() && 1010 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(), 1011 D->getSuperClassLoc(), 1012 TU))) 1013 return true; 1014#endif 1015 1016 return VisitObjCImplDecl(D); 1017} 1018 1019bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) { 1020 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin(); 1021 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(), 1022 E = D->protocol_end(); 1023 I != E; ++I, ++PL) 1024 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) 1025 return true; 1026 1027 return false; 1028} 1029 1030bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) { 1031 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C) 1032 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU))) 1033 return true; 1034 1035 return false; 1036} 1037 1038bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) { 1039 return VisitDeclContext(D); 1040} 1041 1042bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { 1043 // Visit nested-name-specifier. 1044 if (NestedNameSpecifier *Qualifier = D->getQualifier()) 1045 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange())) 1046 return true; 1047 1048 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(), 1049 D->getTargetNameLoc(), TU)); 1050} 1051 1052bool CursorVisitor::VisitUsingDecl(UsingDecl *D) { 1053 // Visit nested-name-specifier. 1054 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl()) 1055 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange())) 1056 return true; 1057 1058 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU))) 1059 return true; 1060 1061 return VisitDeclarationNameInfo(D->getNameInfo()); 1062} 1063 1064bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { 1065 // Visit nested-name-specifier. 1066 if (NestedNameSpecifier *Qualifier = D->getQualifier()) 1067 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange())) 1068 return true; 1069 1070 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(), 1071 D->getIdentLocation(), TU)); 1072} 1073 1074bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) { 1075 // Visit nested-name-specifier. 1076 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier()) 1077 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange())) 1078 return true; 1079 1080 return VisitDeclarationNameInfo(D->getNameInfo()); 1081} 1082 1083bool CursorVisitor::VisitUnresolvedUsingTypenameDecl( 1084 UnresolvedUsingTypenameDecl *D) { 1085 // Visit nested-name-specifier. 1086 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier()) 1087 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange())) 1088 return true; 1089 1090 return false; 1091} 1092 1093bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) { 1094 switch (Name.getName().getNameKind()) { 1095 case clang::DeclarationName::Identifier: 1096 case clang::DeclarationName::CXXLiteralOperatorName: 1097 case clang::DeclarationName::CXXOperatorName: 1098 case clang::DeclarationName::CXXUsingDirective: 1099 return false; 1100 1101 case clang::DeclarationName::CXXConstructorName: 1102 case clang::DeclarationName::CXXDestructorName: 1103 case clang::DeclarationName::CXXConversionFunctionName: 1104 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo()) 1105 return Visit(TSInfo->getTypeLoc()); 1106 return false; 1107 1108 case clang::DeclarationName::ObjCZeroArgSelector: 1109 case clang::DeclarationName::ObjCOneArgSelector: 1110 case clang::DeclarationName::ObjCMultiArgSelector: 1111 // FIXME: Per-identifier location info? 1112 return false; 1113 } 1114 1115 return false; 1116} 1117 1118bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS, 1119 SourceRange Range) { 1120 // FIXME: This whole routine is a hack to work around the lack of proper 1121 // source information in nested-name-specifiers (PR5791). Since we do have 1122 // a beginning source location, we can visit the first component of the 1123 // nested-name-specifier, if it's a single-token component. 1124 if (!NNS) 1125 return false; 1126 1127 // Get the first component in the nested-name-specifier. 1128 while (NestedNameSpecifier *Prefix = NNS->getPrefix()) 1129 NNS = Prefix; 1130 1131 switch (NNS->getKind()) { 1132 case NestedNameSpecifier::Namespace: 1133 // FIXME: The token at this source location might actually have been a 1134 // namespace alias, but we don't model that. Lame! 1135 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(), 1136 TU)); 1137 1138 case NestedNameSpecifier::TypeSpec: { 1139 // If the type has a form where we know that the beginning of the source 1140 // range matches up with a reference cursor. Visit the appropriate reference 1141 // cursor. 1142 Type *T = NNS->getAsType(); 1143 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T)) 1144 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU)); 1145 if (const TagType *Tag = dyn_cast<TagType>(T)) 1146 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU)); 1147 if (const TemplateSpecializationType *TST 1148 = dyn_cast<TemplateSpecializationType>(T)) 1149 return VisitTemplateName(TST->getTemplateName(), Range.getBegin()); 1150 break; 1151 } 1152 1153 case NestedNameSpecifier::TypeSpecWithTemplate: 1154 case NestedNameSpecifier::Global: 1155 case NestedNameSpecifier::Identifier: 1156 break; 1157 } 1158 1159 return false; 1160} 1161 1162bool CursorVisitor::VisitTemplateParameters( 1163 const TemplateParameterList *Params) { 1164 if (!Params) 1165 return false; 1166 1167 for (TemplateParameterList::const_iterator P = Params->begin(), 1168 PEnd = Params->end(); 1169 P != PEnd; ++P) { 1170 if (Visit(MakeCXCursor(*P, TU))) 1171 return true; 1172 } 1173 1174 return false; 1175} 1176 1177bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) { 1178 switch (Name.getKind()) { 1179 case TemplateName::Template: 1180 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU)); 1181 1182 case TemplateName::OverloadedTemplate: 1183 // Visit the overloaded template set. 1184 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU))) 1185 return true; 1186 1187 return false; 1188 1189 case TemplateName::DependentTemplate: 1190 // FIXME: Visit nested-name-specifier. 1191 return false; 1192 1193 case TemplateName::QualifiedTemplate: 1194 // FIXME: Visit nested-name-specifier. 1195 return Visit(MakeCursorTemplateRef( 1196 Name.getAsQualifiedTemplateName()->getDecl(), 1197 Loc, TU)); 1198 } 1199 1200 return false; 1201} 1202 1203bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) { 1204 switch (TAL.getArgument().getKind()) { 1205 case TemplateArgument::Null: 1206 case TemplateArgument::Integral: 1207 return false; 1208 1209 case TemplateArgument::Pack: 1210 // FIXME: Implement when variadic templates come along. 1211 return false; 1212 1213 case TemplateArgument::Type: 1214 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo()) 1215 return Visit(TSInfo->getTypeLoc()); 1216 return false; 1217 1218 case TemplateArgument::Declaration: 1219 if (Expr *E = TAL.getSourceDeclExpression()) 1220 return Visit(MakeCXCursor(E, StmtParent, TU)); 1221 return false; 1222 1223 case TemplateArgument::Expression: 1224 if (Expr *E = TAL.getSourceExpression()) 1225 return Visit(MakeCXCursor(E, StmtParent, TU)); 1226 return false; 1227 1228 case TemplateArgument::Template: 1229 return VisitTemplateName(TAL.getArgument().getAsTemplate(), 1230 TAL.getTemplateNameLoc()); 1231 } 1232 1233 return false; 1234} 1235 1236bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) { 1237 return VisitDeclContext(D); 1238} 1239 1240bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 1241 return Visit(TL.getUnqualifiedLoc()); 1242} 1243 1244bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 1245 ASTContext &Context = TU->getASTContext(); 1246 1247 // Some builtin types (such as Objective-C's "id", "sel", and 1248 // "Class") have associated declarations. Create cursors for those. 1249 QualType VisitType; 1250 switch (TL.getType()->getAs<BuiltinType>()->getKind()) { 1251 case BuiltinType::Void: 1252 case BuiltinType::Bool: 1253 case BuiltinType::Char_U: 1254 case BuiltinType::UChar: 1255 case BuiltinType::Char16: 1256 case BuiltinType::Char32: 1257 case BuiltinType::UShort: 1258 case BuiltinType::UInt: 1259 case BuiltinType::ULong: 1260 case BuiltinType::ULongLong: 1261 case BuiltinType::UInt128: 1262 case BuiltinType::Char_S: 1263 case BuiltinType::SChar: 1264 case BuiltinType::WChar: 1265 case BuiltinType::Short: 1266 case BuiltinType::Int: 1267 case BuiltinType::Long: 1268 case BuiltinType::LongLong: 1269 case BuiltinType::Int128: 1270 case BuiltinType::Float: 1271 case BuiltinType::Double: 1272 case BuiltinType::LongDouble: 1273 case BuiltinType::NullPtr: 1274 case BuiltinType::Overload: 1275 case BuiltinType::Dependent: 1276 break; 1277 1278 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor? 1279 break; 1280 1281 case BuiltinType::ObjCId: 1282 VisitType = Context.getObjCIdType(); 1283 break; 1284 1285 case BuiltinType::ObjCClass: 1286 VisitType = Context.getObjCClassType(); 1287 break; 1288 1289 case BuiltinType::ObjCSel: 1290 VisitType = Context.getObjCSelType(); 1291 break; 1292 } 1293 1294 if (!VisitType.isNull()) { 1295 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>()) 1296 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(), 1297 TU)); 1298 } 1299 1300 return false; 1301} 1302 1303bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) { 1304 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU)); 1305} 1306 1307bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) { 1308 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); 1309} 1310 1311bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) { 1312 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); 1313} 1314 1315bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) { 1316 // FIXME: We can't visit the template type parameter, because there's 1317 // no context information with which we can match up the depth/index in the 1318 // type to the appropriate 1319 return false; 1320} 1321 1322bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 1323 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU))) 1324 return true; 1325 1326 return false; 1327} 1328 1329bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 1330 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc())) 1331 return true; 1332 1333 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) { 1334 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I), 1335 TU))) 1336 return true; 1337 } 1338 1339 return false; 1340} 1341 1342bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 1343 return Visit(TL.getPointeeLoc()); 1344} 1345 1346bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) { 1347 return Visit(TL.getPointeeLoc()); 1348} 1349 1350bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 1351 return Visit(TL.getPointeeLoc()); 1352} 1353 1354bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 1355 return Visit(TL.getPointeeLoc()); 1356} 1357 1358bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 1359 return Visit(TL.getPointeeLoc()); 1360} 1361 1362bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 1363 return Visit(TL.getPointeeLoc()); 1364} 1365 1366bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL, 1367 bool SkipResultType) { 1368 if (!SkipResultType && Visit(TL.getResultLoc())) 1369 return true; 1370 1371 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I) 1372 if (Decl *D = TL.getArg(I)) 1373 if (Visit(MakeCXCursor(D, TU))) 1374 return true; 1375 1376 return false; 1377} 1378 1379bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) { 1380 if (Visit(TL.getElementLoc())) 1381 return true; 1382 1383 if (Expr *Size = TL.getSizeExpr()) 1384 return Visit(MakeCXCursor(Size, StmtParent, TU)); 1385 1386 return false; 1387} 1388 1389bool CursorVisitor::VisitTemplateSpecializationTypeLoc( 1390 TemplateSpecializationTypeLoc TL) { 1391 // Visit the template name. 1392 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(), 1393 TL.getTemplateNameLoc())) 1394 return true; 1395 1396 // Visit the template arguments. 1397 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I) 1398 if (VisitTemplateArgumentLoc(TL.getArgLoc(I))) 1399 return true; 1400 1401 return false; 1402} 1403 1404bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 1405 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU)); 1406} 1407 1408bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 1409 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo()) 1410 return Visit(TSInfo->getTypeLoc()); 1411 1412 return false; 1413} 1414 1415bool CursorVisitor::VisitStmt(Stmt *S) { 1416 return VisitDataRecursive(S); 1417} 1418 1419bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) { 1420 if (D->isDefinition()) { 1421 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(), 1422 E = D->bases_end(); I != E; ++I) { 1423 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU))) 1424 return true; 1425 } 1426 } 1427 1428 return VisitTagDecl(D); 1429} 1430 1431bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) { 1432 // Visit the type into which we're computing an offset. 1433 if (Visit(E->getTypeSourceInfo()->getTypeLoc())) 1434 return true; 1435 1436 // Visit the components of the offsetof expression. 1437 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) { 1438 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 1439 const OffsetOfNode &Node = E->getComponent(I); 1440 switch (Node.getKind()) { 1441 case OffsetOfNode::Array: 1442 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()), 1443 StmtParent, TU))) 1444 return true; 1445 break; 1446 1447 case OffsetOfNode::Field: 1448 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(), 1449 TU))) 1450 return true; 1451 break; 1452 1453 case OffsetOfNode::Identifier: 1454 case OffsetOfNode::Base: 1455 continue; 1456 } 1457 } 1458 1459 return false; 1460} 1461 1462bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) { 1463 if (E->isArgumentType()) { 1464 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo()) 1465 return Visit(TSInfo->getTypeLoc()); 1466 1467 return false; 1468 } 1469 1470 return VisitExpr(E); 1471} 1472 1473bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) { 1474 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU)); 1475} 1476 1477bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) { 1478 return Visit(E->getArgTInfo1()->getTypeLoc()) || 1479 Visit(E->getArgTInfo2()->getTypeLoc()); 1480} 1481 1482bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) { 1483 if (Visit(E->getWrittenTypeInfo()->getTypeLoc())) 1484 return true; 1485 1486 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU)); 1487} 1488 1489bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) { 1490 // Visit the designators. 1491 typedef DesignatedInitExpr::Designator Designator; 1492 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(), 1493 DEnd = E->designators_end(); 1494 D != DEnd; ++D) { 1495 if (D->isFieldDesignator()) { 1496 if (FieldDecl *Field = D->getField()) 1497 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU))) 1498 return true; 1499 1500 continue; 1501 } 1502 1503 if (D->isArrayDesignator()) { 1504 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU))) 1505 return true; 1506 1507 continue; 1508 } 1509 1510 assert(D->isArrayRangeDesignator() && "Unknown designator kind"); 1511 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) || 1512 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU))) 1513 return true; 1514 } 1515 1516 // Visit the initializer value itself. 1517 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU)); 1518} 1519 1520bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) { 1521 if (E->isTypeOperand()) { 1522 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo()) 1523 return Visit(TSInfo->getTypeLoc()); 1524 1525 return false; 1526 } 1527 1528 return VisitExpr(E); 1529} 1530 1531bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) { 1532 if (E->isTypeOperand()) { 1533 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo()) 1534 return Visit(TSInfo->getTypeLoc()); 1535 1536 return false; 1537 } 1538 1539 return VisitExpr(E); 1540} 1541 1542bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) { 1543 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo()) 1544 return Visit(TSInfo->getTypeLoc()); 1545 1546 return false; 1547} 1548 1549bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) { 1550 // Visit base expression. 1551 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU))) 1552 return true; 1553 1554 // Visit the nested-name-specifier. 1555 if (NestedNameSpecifier *Qualifier = E->getQualifier()) 1556 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange())) 1557 return true; 1558 1559 // Visit the scope type that looks disturbingly like the nested-name-specifier 1560 // but isn't. 1561 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo()) 1562 if (Visit(TSInfo->getTypeLoc())) 1563 return true; 1564 1565 // Visit the name of the type being destroyed. 1566 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo()) 1567 if (Visit(TSInfo->getTypeLoc())) 1568 return true; 1569 1570 return false; 1571} 1572 1573bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) { 1574 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc()); 1575} 1576 1577bool CursorVisitor::VisitDependentScopeDeclRefExpr( 1578 DependentScopeDeclRefExpr *E) { 1579 // Visit the nested-name-specifier. 1580 if (NestedNameSpecifier *Qualifier = E->getQualifier()) 1581 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange())) 1582 return true; 1583 1584 // Visit the declaration name. 1585 if (VisitDeclarationNameInfo(E->getNameInfo())) 1586 return true; 1587 1588 // Visit the explicitly-specified template arguments. 1589 if (const ExplicitTemplateArgumentList *ArgList 1590 = E->getOptionalExplicitTemplateArgs()) { 1591 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(), 1592 *ArgEnd = Arg + ArgList->NumTemplateArgs; 1593 Arg != ArgEnd; ++Arg) { 1594 if (VisitTemplateArgumentLoc(*Arg)) 1595 return true; 1596 } 1597 } 1598 1599 return false; 1600} 1601 1602bool CursorVisitor::VisitCXXUnresolvedConstructExpr( 1603 CXXUnresolvedConstructExpr *E) { 1604 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo()) 1605 if (Visit(TSInfo->getTypeLoc())) 1606 return true; 1607 1608 return VisitExpr(E); 1609} 1610 1611bool CursorVisitor::VisitCXXDependentScopeMemberExpr( 1612 CXXDependentScopeMemberExpr *E) { 1613 // Visit the base expression, if there is one. 1614 if (!E->isImplicitAccess() && 1615 Visit(MakeCXCursor(E->getBase(), StmtParent, TU))) 1616 return true; 1617 1618 // Visit the nested-name-specifier. 1619 if (NestedNameSpecifier *Qualifier = E->getQualifier()) 1620 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange())) 1621 return true; 1622 1623 // Visit the declaration name. 1624 if (VisitDeclarationNameInfo(E->getMemberNameInfo())) 1625 return true; 1626 1627 // Visit the explicitly-specified template arguments. 1628 if (const ExplicitTemplateArgumentList *ArgList 1629 = E->getOptionalExplicitTemplateArgs()) { 1630 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(), 1631 *ArgEnd = Arg + ArgList->NumTemplateArgs; 1632 Arg != ArgEnd; ++Arg) { 1633 if (VisitTemplateArgumentLoc(*Arg)) 1634 return true; 1635 } 1636 } 1637 1638 return false; 1639} 1640 1641bool CursorVisitor::VisitAttributes(Decl *D) { 1642 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end(); 1643 i != e; ++i) 1644 if (Visit(MakeCXCursor(*i, D, TU))) 1645 return true; 1646 1647 return false; 1648} 1649 1650//===----------------------------------------------------------------------===// 1651// Data-recursive visitor methods. 1652//===----------------------------------------------------------------------===// 1653 1654namespace { 1655#define DEF_JOB(NAME, DATA, KIND)\ 1656class NAME : public VisitorJob {\ 1657public:\ 1658 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \ 1659 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\ 1660 DATA *get() const { return static_cast<DATA*>(dataA); }\ 1661}; 1662 1663DEF_JOB(StmtVisit, Stmt, StmtVisitKind) 1664DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind) 1665DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind) 1666DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind) 1667#undef DEF_JOB 1668 1669class DeclVisit : public VisitorJob { 1670public: 1671 DeclVisit(Decl *d, CXCursor parent, bool isFirst) : 1672 VisitorJob(parent, VisitorJob::DeclVisitKind, 1673 d, isFirst ? (void*) 1 : (void*) 0) {} 1674 static bool classof(const VisitorJob *VJ) { 1675 return VJ->getKind() == DeclVisitKind; 1676 } 1677 Decl *get() const { return static_cast<Decl*>(dataA); } 1678 bool isFirst() const { return dataB ? true : false; } 1679}; 1680 1681class TypeLocVisit : public VisitorJob { 1682public: 1683 TypeLocVisit(TypeLoc tl, CXCursor parent) : 1684 VisitorJob(parent, VisitorJob::TypeLocVisitKind, 1685 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {} 1686 1687 static bool classof(const VisitorJob *VJ) { 1688 return VJ->getKind() == TypeLocVisitKind; 1689 } 1690 1691 TypeLoc get() const { 1692 QualType T = QualType::getFromOpaquePtr(dataA); 1693 return TypeLoc(T, dataB); 1694 } 1695}; 1696 1697class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> { 1698 VisitorWorkList &WL; 1699 CXCursor Parent; 1700public: 1701 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent) 1702 : WL(wl), Parent(parent) {} 1703 1704 void VisitBlockExpr(BlockExpr *B); 1705 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E); 1706 void VisitCompoundStmt(CompoundStmt *S); 1707 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ } 1708 void VisitCXXNewExpr(CXXNewExpr *E); 1709 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E); 1710 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E); 1711 void VisitDeclRefExpr(DeclRefExpr *D); 1712 void VisitDeclStmt(DeclStmt *S); 1713 void VisitExplicitCastExpr(ExplicitCastExpr *E); 1714 void VisitForStmt(ForStmt *FS); 1715 void VisitIfStmt(IfStmt *If); 1716 void VisitInitListExpr(InitListExpr *IE); 1717 void VisitMemberExpr(MemberExpr *M); 1718 void VisitObjCEncodeExpr(ObjCEncodeExpr *E); 1719 void VisitObjCMessageExpr(ObjCMessageExpr *M); 1720 void VisitOverloadExpr(OverloadExpr *E); 1721 void VisitStmt(Stmt *S); 1722 void VisitSwitchStmt(SwitchStmt *S); 1723 void VisitWhileStmt(WhileStmt *W); 1724 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U); 1725 1726private: 1727 void AddStmt(Stmt *S); 1728 void AddDecl(Decl *D, bool isFirst = true); 1729 void AddTypeLoc(TypeSourceInfo *TI); 1730 void EnqueueChildren(Stmt *S); 1731}; 1732} // end anonyous namespace 1733 1734void EnqueueVisitor::AddStmt(Stmt *S) { 1735 if (S) 1736 WL.push_back(StmtVisit(S, Parent)); 1737} 1738void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) { 1739 if (D) 1740 WL.push_back(DeclVisit(D, Parent, isFirst)); 1741} 1742void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) { 1743 if (TI) 1744 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent)); 1745 } 1746void EnqueueVisitor::EnqueueChildren(Stmt *S) { 1747 unsigned size = WL.size(); 1748 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end(); 1749 Child != ChildEnd; ++Child) { 1750 AddStmt(*Child); 1751 } 1752 if (size == WL.size()) 1753 return; 1754 // Now reverse the entries we just added. This will match the DFS 1755 // ordering performed by the worklist. 1756 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end(); 1757 std::reverse(I, E); 1758} 1759void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) { 1760 AddDecl(B->getBlockDecl()); 1761} 1762void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 1763 EnqueueChildren(E); 1764 AddTypeLoc(E->getTypeSourceInfo()); 1765} 1766void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) { 1767 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(), 1768 E = S->body_rend(); I != E; ++I) { 1769 AddStmt(*I); 1770 } 1771} 1772void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) { 1773 // Enqueue the initializer or constructor arguments. 1774 for (unsigned I = E->getNumConstructorArgs(); I > 0; --I) 1775 AddStmt(E->getConstructorArg(I-1)); 1776 // Enqueue the array size, if any. 1777 AddStmt(E->getArraySize()); 1778 // Enqueue the allocated type. 1779 AddTypeLoc(E->getAllocatedTypeSourceInfo()); 1780 // Enqueue the placement arguments. 1781 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I) 1782 AddStmt(E->getPlacementArg(I-1)); 1783} 1784void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) { 1785 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I) 1786 AddStmt(CE->getArg(I-1)); 1787 AddStmt(CE->getCallee()); 1788 AddStmt(CE->getArg(0)); 1789} 1790void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) { 1791 EnqueueChildren(E); 1792 AddTypeLoc(E->getTypeSourceInfo()); 1793} 1794void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) { 1795 WL.push_back(DeclRefExprParts(DR, Parent)); 1796} 1797void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) { 1798 unsigned size = WL.size(); 1799 bool isFirst = true; 1800 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end(); 1801 D != DEnd; ++D) { 1802 AddDecl(*D, isFirst); 1803 isFirst = false; 1804 } 1805 if (size == WL.size()) 1806 return; 1807 // Now reverse the entries we just added. This will match the DFS 1808 // ordering performed by the worklist. 1809 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end(); 1810 std::reverse(I, E); 1811} 1812void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) { 1813 EnqueueChildren(E); 1814 AddTypeLoc(E->getTypeInfoAsWritten()); 1815} 1816void EnqueueVisitor::VisitForStmt(ForStmt *FS) { 1817 AddStmt(FS->getBody()); 1818 AddStmt(FS->getInc()); 1819 AddStmt(FS->getCond()); 1820 AddDecl(FS->getConditionVariable()); 1821 AddStmt(FS->getInit()); 1822} 1823void EnqueueVisitor::VisitIfStmt(IfStmt *If) { 1824 AddStmt(If->getElse()); 1825 AddStmt(If->getThen()); 1826 AddStmt(If->getCond()); 1827 AddDecl(If->getConditionVariable()); 1828} 1829void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) { 1830 // We care about the syntactic form of the initializer list, only. 1831 if (InitListExpr *Syntactic = IE->getSyntacticForm()) 1832 IE = Syntactic; 1833 EnqueueChildren(IE); 1834} 1835void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) { 1836 WL.push_back(MemberExprParts(M, Parent)); 1837 AddStmt(M->getBase()); 1838} 1839void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) { 1840 AddTypeLoc(E->getEncodedTypeSourceInfo()); 1841} 1842void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) { 1843 EnqueueChildren(M); 1844 AddTypeLoc(M->getClassReceiverTypeInfo()); 1845} 1846void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) { 1847 WL.push_back(OverloadExprParts(E, Parent)); 1848} 1849void EnqueueVisitor::VisitStmt(Stmt *S) { 1850 EnqueueChildren(S); 1851} 1852void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) { 1853 AddStmt(S->getBody()); 1854 AddStmt(S->getCond()); 1855 AddDecl(S->getConditionVariable()); 1856} 1857void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) { 1858 AddStmt(W->getBody()); 1859 AddStmt(W->getCond()); 1860 AddDecl(W->getConditionVariable()); 1861} 1862void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) { 1863 VisitOverloadExpr(U); 1864 if (!U->isImplicitAccess()) 1865 AddStmt(U->getBase()); 1866} 1867 1868void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) { 1869 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S); 1870} 1871 1872bool CursorVisitor::IsInRegionOfInterest(CXCursor C) { 1873 if (RegionOfInterest.isValid()) { 1874 SourceRange Range = getRawCursorExtent(C); 1875 if (Range.isInvalid() || CompareRegionOfInterest(Range)) 1876 return false; 1877 } 1878 return true; 1879} 1880 1881bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) { 1882 while (!WL.empty()) { 1883 // Dequeue the worklist item. 1884 VisitorJob LI = WL.back(); 1885 WL.pop_back(); 1886 1887 // Set the Parent field, then back to its old value once we're done. 1888 SetParentRAII SetParent(Parent, StmtParent, LI.getParent()); 1889 1890 switch (LI.getKind()) { 1891 case VisitorJob::DeclVisitKind: { 1892 Decl *D = cast<DeclVisit>(&LI)->get(); 1893 if (!D) 1894 continue; 1895 1896 // For now, perform default visitation for Decls. 1897 if (Visit(MakeCXCursor(D, TU, cast<DeclVisit>(&LI)->isFirst()))) 1898 return true; 1899 1900 continue; 1901 } 1902 case VisitorJob::TypeLocVisitKind: { 1903 // Perform default visitation for TypeLocs. 1904 if (Visit(cast<TypeLocVisit>(&LI)->get())) 1905 return true; 1906 continue; 1907 } 1908 case VisitorJob::StmtVisitKind: { 1909 Stmt *S = cast<StmtVisit>(&LI)->get(); 1910 if (!S) 1911 continue; 1912 1913 // Update the current cursor. 1914 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU); 1915 1916 switch (S->getStmtClass()) { 1917 case Stmt::GotoStmtClass: { 1918 GotoStmt *GS = cast<GotoStmt>(S); 1919 if (Visit(MakeCursorLabelRef(GS->getLabel(), 1920 GS->getLabelLoc(), TU))) { 1921 return true; 1922 } 1923 continue; 1924 } 1925 // Cases not yet handled by the data-recursion 1926 // algorithm. 1927 case Stmt::OffsetOfExprClass: 1928 case Stmt::SizeOfAlignOfExprClass: 1929 case Stmt::AddrLabelExprClass: 1930 case Stmt::TypesCompatibleExprClass: 1931 case Stmt::VAArgExprClass: 1932 case Stmt::DesignatedInitExprClass: 1933 case Stmt::CXXTypeidExprClass: 1934 case Stmt::CXXUuidofExprClass: 1935 case Stmt::CXXScalarValueInitExprClass: 1936 case Stmt::CXXPseudoDestructorExprClass: 1937 case Stmt::UnaryTypeTraitExprClass: 1938 case Stmt::DependentScopeDeclRefExprClass: 1939 case Stmt::CXXUnresolvedConstructExprClass: 1940 case Stmt::CXXDependentScopeMemberExprClass: 1941 if (Visit(Cursor)) 1942 return true; 1943 break; 1944 default: 1945 if (!IsInRegionOfInterest(Cursor)) 1946 continue; 1947 switch (Visitor(Cursor, Parent, ClientData)) { 1948 case CXChildVisit_Break: 1949 return true; 1950 case CXChildVisit_Continue: 1951 break; 1952 case CXChildVisit_Recurse: 1953 EnqueueWorkList(WL, S); 1954 break; 1955 } 1956 break; 1957 } 1958 continue; 1959 } 1960 case VisitorJob::MemberExprPartsKind: { 1961 // Handle the other pieces in the MemberExpr besides the base. 1962 MemberExpr *M = cast<MemberExprParts>(&LI)->get(); 1963 1964 // Visit the nested-name-specifier 1965 if (NestedNameSpecifier *Qualifier = M->getQualifier()) 1966 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange())) 1967 return true; 1968 1969 // Visit the declaration name. 1970 if (VisitDeclarationNameInfo(M->getMemberNameInfo())) 1971 return true; 1972 1973 // Visit the explicitly-specified template arguments, if any. 1974 if (M->hasExplicitTemplateArgs()) { 1975 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(), 1976 *ArgEnd = Arg + M->getNumTemplateArgs(); 1977 Arg != ArgEnd; ++Arg) { 1978 if (VisitTemplateArgumentLoc(*Arg)) 1979 return true; 1980 } 1981 } 1982 continue; 1983 } 1984 case VisitorJob::DeclRefExprPartsKind: { 1985 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get(); 1986 // Visit nested-name-specifier, if present. 1987 if (NestedNameSpecifier *Qualifier = DR->getQualifier()) 1988 if (VisitNestedNameSpecifier(Qualifier, DR->getQualifierRange())) 1989 return true; 1990 // Visit declaration name. 1991 if (VisitDeclarationNameInfo(DR->getNameInfo())) 1992 return true; 1993 // Visit explicitly-specified template arguments. 1994 if (DR->hasExplicitTemplateArgs()) { 1995 ExplicitTemplateArgumentList &Args = DR->getExplicitTemplateArgs(); 1996 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(), 1997 *ArgEnd = Arg + Args.NumTemplateArgs; 1998 Arg != ArgEnd; ++Arg) 1999 if (VisitTemplateArgumentLoc(*Arg)) 2000 return true; 2001 } 2002 continue; 2003 } 2004 case VisitorJob::OverloadExprPartsKind: { 2005 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get(); 2006 // Visit the nested-name-specifier. 2007 if (NestedNameSpecifier *Qualifier = O->getQualifier()) 2008 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange())) 2009 return true; 2010 // Visit the declaration name. 2011 if (VisitDeclarationNameInfo(O->getNameInfo())) 2012 return true; 2013 // Visit the overloaded declaration reference. 2014 if (Visit(MakeCursorOverloadedDeclRef(O, TU))) 2015 return true; 2016 // Visit the explicitly-specified template arguments. 2017 if (const ExplicitTemplateArgumentList *ArgList 2018 = O->getOptionalExplicitTemplateArgs()) { 2019 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(), 2020 *ArgEnd = Arg + ArgList->NumTemplateArgs; 2021 Arg != ArgEnd; ++Arg) { 2022 if (VisitTemplateArgumentLoc(*Arg)) 2023 return true; 2024 } 2025 } 2026 continue; 2027 } 2028 } 2029 } 2030 return false; 2031} 2032 2033bool CursorVisitor::VisitDataRecursive(Stmt *S) { 2034 VisitorWorkList *WL = 0; 2035 if (!WorkListFreeList.empty()) { 2036 WL = WorkListFreeList.back(); 2037 WL->clear(); 2038 WorkListFreeList.pop_back(); 2039 } 2040 else { 2041 WL = new VisitorWorkList(); 2042 WorkListCache.push_back(WL); 2043 } 2044 EnqueueWorkList(*WL, S); 2045 bool result = RunVisitorWorkList(*WL); 2046 WorkListFreeList.push_back(WL); 2047 return result; 2048} 2049 2050//===----------------------------------------------------------------------===// 2051// Misc. API hooks. 2052//===----------------------------------------------------------------------===// 2053 2054static llvm::sys::Mutex EnableMultithreadingMutex; 2055static bool EnabledMultithreading; 2056 2057extern "C" { 2058CXIndex clang_createIndex(int excludeDeclarationsFromPCH, 2059 int displayDiagnostics) { 2060 // Disable pretty stack trace functionality, which will otherwise be a very 2061 // poor citizen of the world and set up all sorts of signal handlers. 2062 llvm::DisablePrettyStackTrace = true; 2063 2064 // We use crash recovery to make some of our APIs more reliable, implicitly 2065 // enable it. 2066 llvm::CrashRecoveryContext::Enable(); 2067 2068 // Enable support for multithreading in LLVM. 2069 { 2070 llvm::sys::ScopedLock L(EnableMultithreadingMutex); 2071 if (!EnabledMultithreading) { 2072 llvm::llvm_start_multithreaded(); 2073 EnabledMultithreading = true; 2074 } 2075 } 2076 2077 CIndexer *CIdxr = new CIndexer(); 2078 if (excludeDeclarationsFromPCH) 2079 CIdxr->setOnlyLocalDecls(); 2080 if (displayDiagnostics) 2081 CIdxr->setDisplayDiagnostics(); 2082 return CIdxr; 2083} 2084 2085void clang_disposeIndex(CXIndex CIdx) { 2086 if (CIdx) 2087 delete static_cast<CIndexer *>(CIdx); 2088} 2089 2090CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx, 2091 const char *ast_filename) { 2092 if (!CIdx) 2093 return 0; 2094 2095 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx); 2096 FileSystemOptions FileSystemOpts; 2097 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory(); 2098 2099 llvm::IntrusiveRefCntPtr<Diagnostic> Diags; 2100 return ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts, 2101 CXXIdx->getOnlyLocalDecls(), 2102 0, 0, true); 2103} 2104 2105unsigned clang_defaultEditingTranslationUnitOptions() { 2106 return CXTranslationUnit_PrecompiledPreamble | 2107 CXTranslationUnit_CacheCompletionResults | 2108 CXTranslationUnit_CXXPrecompiledPreamble; 2109} 2110 2111CXTranslationUnit 2112clang_createTranslationUnitFromSourceFile(CXIndex CIdx, 2113 const char *source_filename, 2114 int num_command_line_args, 2115 const char * const *command_line_args, 2116 unsigned num_unsaved_files, 2117 struct CXUnsavedFile *unsaved_files) { 2118 return clang_parseTranslationUnit(CIdx, source_filename, 2119 command_line_args, num_command_line_args, 2120 unsaved_files, num_unsaved_files, 2121 CXTranslationUnit_DetailedPreprocessingRecord); 2122} 2123 2124struct ParseTranslationUnitInfo { 2125 CXIndex CIdx; 2126 const char *source_filename; 2127 const char *const *command_line_args; 2128 int num_command_line_args; 2129 struct CXUnsavedFile *unsaved_files; 2130 unsigned num_unsaved_files; 2131 unsigned options; 2132 CXTranslationUnit result; 2133}; 2134static void clang_parseTranslationUnit_Impl(void *UserData) { 2135 ParseTranslationUnitInfo *PTUI = 2136 static_cast<ParseTranslationUnitInfo*>(UserData); 2137 CXIndex CIdx = PTUI->CIdx; 2138 const char *source_filename = PTUI->source_filename; 2139 const char * const *command_line_args = PTUI->command_line_args; 2140 int num_command_line_args = PTUI->num_command_line_args; 2141 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files; 2142 unsigned num_unsaved_files = PTUI->num_unsaved_files; 2143 unsigned options = PTUI->options; 2144 PTUI->result = 0; 2145 2146 if (!CIdx) 2147 return; 2148 2149 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx); 2150 2151 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble; 2152 bool CompleteTranslationUnit 2153 = ((options & CXTranslationUnit_Incomplete) == 0); 2154 bool CacheCodeCompetionResults 2155 = options & CXTranslationUnit_CacheCompletionResults; 2156 bool CXXPrecompilePreamble 2157 = options & CXTranslationUnit_CXXPrecompiledPreamble; 2158 bool CXXChainedPCH 2159 = options & CXTranslationUnit_CXXChainedPCH; 2160 2161 // Configure the diagnostics. 2162 DiagnosticOptions DiagOpts; 2163 llvm::IntrusiveRefCntPtr<Diagnostic> Diags; 2164 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0); 2165 2166 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles; 2167 for (unsigned I = 0; I != num_unsaved_files; ++I) { 2168 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length); 2169 const llvm::MemoryBuffer *Buffer 2170 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename); 2171 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename, 2172 Buffer)); 2173 } 2174 2175 llvm::SmallVector<const char *, 16> Args; 2176 2177 // The 'source_filename' argument is optional. If the caller does not 2178 // specify it then it is assumed that the source file is specified 2179 // in the actual argument list. 2180 if (source_filename) 2181 Args.push_back(source_filename); 2182 2183 // Since the Clang C library is primarily used by batch tools dealing with 2184 // (often very broken) source code, where spell-checking can have a 2185 // significant negative impact on performance (particularly when 2186 // precompiled headers are involved), we disable it by default. 2187 // Only do this if we haven't found a spell-checking-related argument. 2188 bool FoundSpellCheckingArgument = false; 2189 for (int I = 0; I != num_command_line_args; ++I) { 2190 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 || 2191 strcmp(command_line_args[I], "-fspell-checking") == 0) { 2192 FoundSpellCheckingArgument = true; 2193 break; 2194 } 2195 } 2196 if (!FoundSpellCheckingArgument) 2197 Args.push_back("-fno-spell-checking"); 2198 2199 Args.insert(Args.end(), command_line_args, 2200 command_line_args + num_command_line_args); 2201 2202 // Do we need the detailed preprocessing record? 2203 if (options & CXTranslationUnit_DetailedPreprocessingRecord) { 2204 Args.push_back("-Xclang"); 2205 Args.push_back("-detailed-preprocessing-record"); 2206 } 2207 2208 unsigned NumErrors = Diags->getNumErrors(); 2209 llvm::OwningPtr<ASTUnit> Unit( 2210 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(), 2211 Diags, 2212 CXXIdx->getClangResourcesPath(), 2213 CXXIdx->getOnlyLocalDecls(), 2214 /*CaptureDiagnostics=*/true, 2215 RemappedFiles.data(), 2216 RemappedFiles.size(), 2217 PrecompilePreamble, 2218 CompleteTranslationUnit, 2219 CacheCodeCompetionResults, 2220 CXXPrecompilePreamble, 2221 CXXChainedPCH)); 2222 2223 if (NumErrors != Diags->getNumErrors()) { 2224 // Make sure to check that 'Unit' is non-NULL. 2225 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) { 2226 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(), 2227 DEnd = Unit->stored_diag_end(); 2228 D != DEnd; ++D) { 2229 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions()); 2230 CXString Msg = clang_formatDiagnostic(&Diag, 2231 clang_defaultDiagnosticDisplayOptions()); 2232 fprintf(stderr, "%s\n", clang_getCString(Msg)); 2233 clang_disposeString(Msg); 2234 } 2235#ifdef LLVM_ON_WIN32 2236 // On Windows, force a flush, since there may be multiple copies of 2237 // stderr and stdout in the file system, all with different buffers 2238 // but writing to the same device. 2239 fflush(stderr); 2240#endif 2241 } 2242 } 2243 2244 PTUI->result = Unit.take(); 2245} 2246CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx, 2247 const char *source_filename, 2248 const char * const *command_line_args, 2249 int num_command_line_args, 2250 struct CXUnsavedFile *unsaved_files, 2251 unsigned num_unsaved_files, 2252 unsigned options) { 2253 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args, 2254 num_command_line_args, unsaved_files, 2255 num_unsaved_files, options, 0 }; 2256 llvm::CrashRecoveryContext CRC; 2257 2258 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) { 2259 fprintf(stderr, "libclang: crash detected during parsing: {\n"); 2260 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename); 2261 fprintf(stderr, " 'command_line_args' : ["); 2262 for (int i = 0; i != num_command_line_args; ++i) { 2263 if (i) 2264 fprintf(stderr, ", "); 2265 fprintf(stderr, "'%s'", command_line_args[i]); 2266 } 2267 fprintf(stderr, "],\n"); 2268 fprintf(stderr, " 'unsaved_files' : ["); 2269 for (unsigned i = 0; i != num_unsaved_files; ++i) { 2270 if (i) 2271 fprintf(stderr, ", "); 2272 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename, 2273 unsaved_files[i].Length); 2274 } 2275 fprintf(stderr, "],\n"); 2276 fprintf(stderr, " 'options' : %d,\n", options); 2277 fprintf(stderr, "}\n"); 2278 2279 return 0; 2280 } 2281 2282 return PTUI.result; 2283} 2284 2285unsigned clang_defaultSaveOptions(CXTranslationUnit TU) { 2286 return CXSaveTranslationUnit_None; 2287} 2288 2289int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName, 2290 unsigned options) { 2291 if (!TU) 2292 return 1; 2293 2294 return static_cast<ASTUnit *>(TU)->Save(FileName); 2295} 2296 2297void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) { 2298 if (CTUnit) { 2299 // If the translation unit has been marked as unsafe to free, just discard 2300 // it. 2301 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree()) 2302 return; 2303 2304 delete static_cast<ASTUnit *>(CTUnit); 2305 } 2306} 2307 2308unsigned clang_defaultReparseOptions(CXTranslationUnit TU) { 2309 return CXReparse_None; 2310} 2311 2312struct ReparseTranslationUnitInfo { 2313 CXTranslationUnit TU; 2314 unsigned num_unsaved_files; 2315 struct CXUnsavedFile *unsaved_files; 2316 unsigned options; 2317 int result; 2318}; 2319 2320static void clang_reparseTranslationUnit_Impl(void *UserData) { 2321 ReparseTranslationUnitInfo *RTUI = 2322 static_cast<ReparseTranslationUnitInfo*>(UserData); 2323 CXTranslationUnit TU = RTUI->TU; 2324 unsigned num_unsaved_files = RTUI->num_unsaved_files; 2325 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files; 2326 unsigned options = RTUI->options; 2327 (void) options; 2328 RTUI->result = 1; 2329 2330 if (!TU) 2331 return; 2332 2333 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU); 2334 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 2335 2336 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles; 2337 for (unsigned I = 0; I != num_unsaved_files; ++I) { 2338 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length); 2339 const llvm::MemoryBuffer *Buffer 2340 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename); 2341 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename, 2342 Buffer)); 2343 } 2344 2345 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size())) 2346 RTUI->result = 0; 2347} 2348 2349int clang_reparseTranslationUnit(CXTranslationUnit TU, 2350 unsigned num_unsaved_files, 2351 struct CXUnsavedFile *unsaved_files, 2352 unsigned options) { 2353 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files, 2354 options, 0 }; 2355 llvm::CrashRecoveryContext CRC; 2356 2357 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) { 2358 fprintf(stderr, "libclang: crash detected during reparsing\n"); 2359 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true); 2360 return 1; 2361 } 2362 2363 2364 return RTUI.result; 2365} 2366 2367 2368CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) { 2369 if (!CTUnit) 2370 return createCXString(""); 2371 2372 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit); 2373 return createCXString(CXXUnit->getOriginalSourceFileName(), true); 2374} 2375 2376CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) { 2377 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } }; 2378 return Result; 2379} 2380 2381} // end: extern "C" 2382 2383//===----------------------------------------------------------------------===// 2384// CXSourceLocation and CXSourceRange Operations. 2385//===----------------------------------------------------------------------===// 2386 2387extern "C" { 2388CXSourceLocation clang_getNullLocation() { 2389 CXSourceLocation Result = { { 0, 0 }, 0 }; 2390 return Result; 2391} 2392 2393unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) { 2394 return (loc1.ptr_data[0] == loc2.ptr_data[0] && 2395 loc1.ptr_data[1] == loc2.ptr_data[1] && 2396 loc1.int_data == loc2.int_data); 2397} 2398 2399CXSourceLocation clang_getLocation(CXTranslationUnit tu, 2400 CXFile file, 2401 unsigned line, 2402 unsigned column) { 2403 if (!tu || !file) 2404 return clang_getNullLocation(); 2405 2406 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu); 2407 SourceLocation SLoc 2408 = CXXUnit->getSourceManager().getLocation( 2409 static_cast<const FileEntry *>(file), 2410 line, column); 2411 if (SLoc.isInvalid()) return clang_getNullLocation(); 2412 2413 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc); 2414} 2415 2416CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu, 2417 CXFile file, 2418 unsigned offset) { 2419 if (!tu || !file) 2420 return clang_getNullLocation(); 2421 2422 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu); 2423 SourceLocation Start 2424 = CXXUnit->getSourceManager().getLocation( 2425 static_cast<const FileEntry *>(file), 2426 1, 1); 2427 if (Start.isInvalid()) return clang_getNullLocation(); 2428 2429 SourceLocation SLoc = Start.getFileLocWithOffset(offset); 2430 2431 if (SLoc.isInvalid()) return clang_getNullLocation(); 2432 2433 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc); 2434} 2435 2436CXSourceRange clang_getNullRange() { 2437 CXSourceRange Result = { { 0, 0 }, 0, 0 }; 2438 return Result; 2439} 2440 2441CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) { 2442 if (begin.ptr_data[0] != end.ptr_data[0] || 2443 begin.ptr_data[1] != end.ptr_data[1]) 2444 return clang_getNullRange(); 2445 2446 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] }, 2447 begin.int_data, end.int_data }; 2448 return Result; 2449} 2450 2451void clang_getInstantiationLocation(CXSourceLocation location, 2452 CXFile *file, 2453 unsigned *line, 2454 unsigned *column, 2455 unsigned *offset) { 2456 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data); 2457 2458 if (!location.ptr_data[0] || Loc.isInvalid()) { 2459 if (file) 2460 *file = 0; 2461 if (line) 2462 *line = 0; 2463 if (column) 2464 *column = 0; 2465 if (offset) 2466 *offset = 0; 2467 return; 2468 } 2469 2470 const SourceManager &SM = 2471 *static_cast<const SourceManager*>(location.ptr_data[0]); 2472 SourceLocation InstLoc = SM.getInstantiationLoc(Loc); 2473 2474 if (file) 2475 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc)); 2476 if (line) 2477 *line = SM.getInstantiationLineNumber(InstLoc); 2478 if (column) 2479 *column = SM.getInstantiationColumnNumber(InstLoc); 2480 if (offset) 2481 *offset = SM.getDecomposedLoc(InstLoc).second; 2482} 2483 2484void clang_getSpellingLocation(CXSourceLocation location, 2485 CXFile *file, 2486 unsigned *line, 2487 unsigned *column, 2488 unsigned *offset) { 2489 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data); 2490 2491 if (!location.ptr_data[0] || Loc.isInvalid()) { 2492 if (file) 2493 *file = 0; 2494 if (line) 2495 *line = 0; 2496 if (column) 2497 *column = 0; 2498 if (offset) 2499 *offset = 0; 2500 return; 2501 } 2502 2503 const SourceManager &SM = 2504 *static_cast<const SourceManager*>(location.ptr_data[0]); 2505 SourceLocation SpellLoc = Loc; 2506 if (SpellLoc.isMacroID()) { 2507 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc); 2508 if (SimpleSpellingLoc.isFileID() && 2509 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first)) 2510 SpellLoc = SimpleSpellingLoc; 2511 else 2512 SpellLoc = SM.getInstantiationLoc(SpellLoc); 2513 } 2514 2515 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc); 2516 FileID FID = LocInfo.first; 2517 unsigned FileOffset = LocInfo.second; 2518 2519 if (file) 2520 *file = (void *)SM.getFileEntryForID(FID); 2521 if (line) 2522 *line = SM.getLineNumber(FID, FileOffset); 2523 if (column) 2524 *column = SM.getColumnNumber(FID, FileOffset); 2525 if (offset) 2526 *offset = FileOffset; 2527} 2528 2529CXSourceLocation clang_getRangeStart(CXSourceRange range) { 2530 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] }, 2531 range.begin_int_data }; 2532 return Result; 2533} 2534 2535CXSourceLocation clang_getRangeEnd(CXSourceRange range) { 2536 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] }, 2537 range.end_int_data }; 2538 return Result; 2539} 2540 2541} // end: extern "C" 2542 2543//===----------------------------------------------------------------------===// 2544// CXFile Operations. 2545//===----------------------------------------------------------------------===// 2546 2547extern "C" { 2548CXString clang_getFileName(CXFile SFile) { 2549 if (!SFile) 2550 return createCXString(NULL); 2551 2552 FileEntry *FEnt = static_cast<FileEntry *>(SFile); 2553 return createCXString(FEnt->getName()); 2554} 2555 2556time_t clang_getFileTime(CXFile SFile) { 2557 if (!SFile) 2558 return 0; 2559 2560 FileEntry *FEnt = static_cast<FileEntry *>(SFile); 2561 return FEnt->getModificationTime(); 2562} 2563 2564CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) { 2565 if (!tu) 2566 return 0; 2567 2568 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu); 2569 2570 FileManager &FMgr = CXXUnit->getFileManager(); 2571 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name), 2572 CXXUnit->getFileSystemOpts()); 2573 return const_cast<FileEntry *>(File); 2574} 2575 2576} // end: extern "C" 2577 2578//===----------------------------------------------------------------------===// 2579// CXCursor Operations. 2580//===----------------------------------------------------------------------===// 2581 2582static Decl *getDeclFromExpr(Stmt *E) { 2583 if (CastExpr *CE = dyn_cast<CastExpr>(E)) 2584 return getDeclFromExpr(CE->getSubExpr()); 2585 2586 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E)) 2587 return RefExpr->getDecl(); 2588 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E)) 2589 return RefExpr->getDecl(); 2590 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) 2591 return ME->getMemberDecl(); 2592 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E)) 2593 return RE->getDecl(); 2594 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) 2595 return PRE->getProperty(); 2596 2597 if (CallExpr *CE = dyn_cast<CallExpr>(E)) 2598 return getDeclFromExpr(CE->getCallee()); 2599 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E)) 2600 if (!CE->isElidable()) 2601 return CE->getConstructor(); 2602 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E)) 2603 return OME->getMethodDecl(); 2604 2605 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E)) 2606 return PE->getProtocol(); 2607 2608 return 0; 2609} 2610 2611static SourceLocation getLocationFromExpr(Expr *E) { 2612 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) 2613 return /*FIXME:*/Msg->getLeftLoc(); 2614 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 2615 return DRE->getLocation(); 2616 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E)) 2617 return RefExpr->getLocation(); 2618 if (MemberExpr *Member = dyn_cast<MemberExpr>(E)) 2619 return Member->getMemberLoc(); 2620 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) 2621 return Ivar->getLocation(); 2622 return E->getLocStart(); 2623} 2624 2625extern "C" { 2626 2627unsigned clang_visitChildren(CXCursor parent, 2628 CXCursorVisitor visitor, 2629 CXClientData client_data) { 2630 ASTUnit *CXXUnit = getCursorASTUnit(parent); 2631 2632 CursorVisitor CursorVis(CXXUnit, visitor, client_data, 2633 CXXUnit->getMaxPCHLevel()); 2634 return CursorVis.VisitChildren(parent); 2635} 2636 2637#ifndef __has_feature 2638#define __has_feature(x) 0 2639#endif 2640#if __has_feature(blocks) 2641typedef enum CXChildVisitResult 2642 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent); 2643 2644static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent, 2645 CXClientData client_data) { 2646 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data; 2647 return block(cursor, parent); 2648} 2649#else 2650// If we are compiled with a compiler that doesn't have native blocks support, 2651// define and call the block manually, so the 2652typedef struct _CXChildVisitResult 2653{ 2654 void *isa; 2655 int flags; 2656 int reserved; 2657 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor, 2658 CXCursor); 2659} *CXCursorVisitorBlock; 2660 2661static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent, 2662 CXClientData client_data) { 2663 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data; 2664 return block->invoke(block, cursor, parent); 2665} 2666#endif 2667 2668 2669unsigned clang_visitChildrenWithBlock(CXCursor parent, 2670 CXCursorVisitorBlock block) { 2671 return clang_visitChildren(parent, visitWithBlock, block); 2672} 2673 2674static CXString getDeclSpelling(Decl *D) { 2675 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D); 2676 if (!ND) 2677 return createCXString(""); 2678 2679 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND)) 2680 return createCXString(OMD->getSelector().getAsString()); 2681 2682 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND)) 2683 // No, this isn't the same as the code below. getIdentifier() is non-virtual 2684 // and returns different names. NamedDecl returns the class name and 2685 // ObjCCategoryImplDecl returns the category name. 2686 return createCXString(CIMP->getIdentifier()->getNameStart()); 2687 2688 if (isa<UsingDirectiveDecl>(D)) 2689 return createCXString(""); 2690 2691 llvm::SmallString<1024> S; 2692 llvm::raw_svector_ostream os(S); 2693 ND->printName(os); 2694 2695 return createCXString(os.str()); 2696} 2697 2698CXString clang_getCursorSpelling(CXCursor C) { 2699 if (clang_isTranslationUnit(C.kind)) 2700 return clang_getTranslationUnitSpelling(C.data[2]); 2701 2702 if (clang_isReference(C.kind)) { 2703 switch (C.kind) { 2704 case CXCursor_ObjCSuperClassRef: { 2705 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first; 2706 return createCXString(Super->getIdentifier()->getNameStart()); 2707 } 2708 case CXCursor_ObjCClassRef: { 2709 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first; 2710 return createCXString(Class->getIdentifier()->getNameStart()); 2711 } 2712 case CXCursor_ObjCProtocolRef: { 2713 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first; 2714 assert(OID && "getCursorSpelling(): Missing protocol decl"); 2715 return createCXString(OID->getIdentifier()->getNameStart()); 2716 } 2717 case CXCursor_CXXBaseSpecifier: { 2718 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C); 2719 return createCXString(B->getType().getAsString()); 2720 } 2721 case CXCursor_TypeRef: { 2722 TypeDecl *Type = getCursorTypeRef(C).first; 2723 assert(Type && "Missing type decl"); 2724 2725 return createCXString(getCursorContext(C).getTypeDeclType(Type). 2726 getAsString()); 2727 } 2728 case CXCursor_TemplateRef: { 2729 TemplateDecl *Template = getCursorTemplateRef(C).first; 2730 assert(Template && "Missing template decl"); 2731 2732 return createCXString(Template->getNameAsString()); 2733 } 2734 2735 case CXCursor_NamespaceRef: { 2736 NamedDecl *NS = getCursorNamespaceRef(C).first; 2737 assert(NS && "Missing namespace decl"); 2738 2739 return createCXString(NS->getNameAsString()); 2740 } 2741 2742 case CXCursor_MemberRef: { 2743 FieldDecl *Field = getCursorMemberRef(C).first; 2744 assert(Field && "Missing member decl"); 2745 2746 return createCXString(Field->getNameAsString()); 2747 } 2748 2749 case CXCursor_LabelRef: { 2750 LabelStmt *Label = getCursorLabelRef(C).first; 2751 assert(Label && "Missing label"); 2752 2753 return createCXString(Label->getID()->getName()); 2754 } 2755 2756 case CXCursor_OverloadedDeclRef: { 2757 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first; 2758 if (Decl *D = Storage.dyn_cast<Decl *>()) { 2759 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) 2760 return createCXString(ND->getNameAsString()); 2761 return createCXString(""); 2762 } 2763 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>()) 2764 return createCXString(E->getName().getAsString()); 2765 OverloadedTemplateStorage *Ovl 2766 = Storage.get<OverloadedTemplateStorage*>(); 2767 if (Ovl->size() == 0) 2768 return createCXString(""); 2769 return createCXString((*Ovl->begin())->getNameAsString()); 2770 } 2771 2772 default: 2773 return createCXString("<not implemented>"); 2774 } 2775 } 2776 2777 if (clang_isExpression(C.kind)) { 2778 Decl *D = getDeclFromExpr(getCursorExpr(C)); 2779 if (D) 2780 return getDeclSpelling(D); 2781 return createCXString(""); 2782 } 2783 2784 if (clang_isStatement(C.kind)) { 2785 Stmt *S = getCursorStmt(C); 2786 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) 2787 return createCXString(Label->getID()->getName()); 2788 2789 return createCXString(""); 2790 } 2791 2792 if (C.kind == CXCursor_MacroInstantiation) 2793 return createCXString(getCursorMacroInstantiation(C)->getName() 2794 ->getNameStart()); 2795 2796 if (C.kind == CXCursor_MacroDefinition) 2797 return createCXString(getCursorMacroDefinition(C)->getName() 2798 ->getNameStart()); 2799 2800 if (C.kind == CXCursor_InclusionDirective) 2801 return createCXString(getCursorInclusionDirective(C)->getFileName()); 2802 2803 if (clang_isDeclaration(C.kind)) 2804 return getDeclSpelling(getCursorDecl(C)); 2805 2806 return createCXString(""); 2807} 2808 2809CXString clang_getCursorDisplayName(CXCursor C) { 2810 if (!clang_isDeclaration(C.kind)) 2811 return clang_getCursorSpelling(C); 2812 2813 Decl *D = getCursorDecl(C); 2814 if (!D) 2815 return createCXString(""); 2816 2817 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy; 2818 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 2819 D = FunTmpl->getTemplatedDecl(); 2820 2821 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 2822 llvm::SmallString<64> Str; 2823 llvm::raw_svector_ostream OS(Str); 2824 OS << Function->getNameAsString(); 2825 if (Function->getPrimaryTemplate()) 2826 OS << "<>"; 2827 OS << "("; 2828 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) { 2829 if (I) 2830 OS << ", "; 2831 OS << Function->getParamDecl(I)->getType().getAsString(Policy); 2832 } 2833 2834 if (Function->isVariadic()) { 2835 if (Function->getNumParams()) 2836 OS << ", "; 2837 OS << "..."; 2838 } 2839 OS << ")"; 2840 return createCXString(OS.str()); 2841 } 2842 2843 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) { 2844 llvm::SmallString<64> Str; 2845 llvm::raw_svector_ostream OS(Str); 2846 OS << ClassTemplate->getNameAsString(); 2847 OS << "<"; 2848 TemplateParameterList *Params = ClassTemplate->getTemplateParameters(); 2849 for (unsigned I = 0, N = Params->size(); I != N; ++I) { 2850 if (I) 2851 OS << ", "; 2852 2853 NamedDecl *Param = Params->getParam(I); 2854 if (Param->getIdentifier()) { 2855 OS << Param->getIdentifier()->getName(); 2856 continue; 2857 } 2858 2859 // There is no parameter name, which makes this tricky. Try to come up 2860 // with something useful that isn't too long. 2861 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) 2862 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class"); 2863 else if (NonTypeTemplateParmDecl *NTTP 2864 = dyn_cast<NonTypeTemplateParmDecl>(Param)) 2865 OS << NTTP->getType().getAsString(Policy); 2866 else 2867 OS << "template<...> class"; 2868 } 2869 2870 OS << ">"; 2871 return createCXString(OS.str()); 2872 } 2873 2874 if (ClassTemplateSpecializationDecl *ClassSpec 2875 = dyn_cast<ClassTemplateSpecializationDecl>(D)) { 2876 // If the type was explicitly written, use that. 2877 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten()) 2878 return createCXString(TSInfo->getType().getAsString(Policy)); 2879 2880 llvm::SmallString<64> Str; 2881 llvm::raw_svector_ostream OS(Str); 2882 OS << ClassSpec->getNameAsString(); 2883 OS << TemplateSpecializationType::PrintTemplateArgumentList( 2884 ClassSpec->getTemplateArgs().data(), 2885 ClassSpec->getTemplateArgs().size(), 2886 Policy); 2887 return createCXString(OS.str()); 2888 } 2889 2890 return clang_getCursorSpelling(C); 2891} 2892 2893CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) { 2894 switch (Kind) { 2895 case CXCursor_FunctionDecl: 2896 return createCXString("FunctionDecl"); 2897 case CXCursor_TypedefDecl: 2898 return createCXString("TypedefDecl"); 2899 case CXCursor_EnumDecl: 2900 return createCXString("EnumDecl"); 2901 case CXCursor_EnumConstantDecl: 2902 return createCXString("EnumConstantDecl"); 2903 case CXCursor_StructDecl: 2904 return createCXString("StructDecl"); 2905 case CXCursor_UnionDecl: 2906 return createCXString("UnionDecl"); 2907 case CXCursor_ClassDecl: 2908 return createCXString("ClassDecl"); 2909 case CXCursor_FieldDecl: 2910 return createCXString("FieldDecl"); 2911 case CXCursor_VarDecl: 2912 return createCXString("VarDecl"); 2913 case CXCursor_ParmDecl: 2914 return createCXString("ParmDecl"); 2915 case CXCursor_ObjCInterfaceDecl: 2916 return createCXString("ObjCInterfaceDecl"); 2917 case CXCursor_ObjCCategoryDecl: 2918 return createCXString("ObjCCategoryDecl"); 2919 case CXCursor_ObjCProtocolDecl: 2920 return createCXString("ObjCProtocolDecl"); 2921 case CXCursor_ObjCPropertyDecl: 2922 return createCXString("ObjCPropertyDecl"); 2923 case CXCursor_ObjCIvarDecl: 2924 return createCXString("ObjCIvarDecl"); 2925 case CXCursor_ObjCInstanceMethodDecl: 2926 return createCXString("ObjCInstanceMethodDecl"); 2927 case CXCursor_ObjCClassMethodDecl: 2928 return createCXString("ObjCClassMethodDecl"); 2929 case CXCursor_ObjCImplementationDecl: 2930 return createCXString("ObjCImplementationDecl"); 2931 case CXCursor_ObjCCategoryImplDecl: 2932 return createCXString("ObjCCategoryImplDecl"); 2933 case CXCursor_CXXMethod: 2934 return createCXString("CXXMethod"); 2935 case CXCursor_UnexposedDecl: 2936 return createCXString("UnexposedDecl"); 2937 case CXCursor_ObjCSuperClassRef: 2938 return createCXString("ObjCSuperClassRef"); 2939 case CXCursor_ObjCProtocolRef: 2940 return createCXString("ObjCProtocolRef"); 2941 case CXCursor_ObjCClassRef: 2942 return createCXString("ObjCClassRef"); 2943 case CXCursor_TypeRef: 2944 return createCXString("TypeRef"); 2945 case CXCursor_TemplateRef: 2946 return createCXString("TemplateRef"); 2947 case CXCursor_NamespaceRef: 2948 return createCXString("NamespaceRef"); 2949 case CXCursor_MemberRef: 2950 return createCXString("MemberRef"); 2951 case CXCursor_LabelRef: 2952 return createCXString("LabelRef"); 2953 case CXCursor_OverloadedDeclRef: 2954 return createCXString("OverloadedDeclRef"); 2955 case CXCursor_UnexposedExpr: 2956 return createCXString("UnexposedExpr"); 2957 case CXCursor_BlockExpr: 2958 return createCXString("BlockExpr"); 2959 case CXCursor_DeclRefExpr: 2960 return createCXString("DeclRefExpr"); 2961 case CXCursor_MemberRefExpr: 2962 return createCXString("MemberRefExpr"); 2963 case CXCursor_CallExpr: 2964 return createCXString("CallExpr"); 2965 case CXCursor_ObjCMessageExpr: 2966 return createCXString("ObjCMessageExpr"); 2967 case CXCursor_UnexposedStmt: 2968 return createCXString("UnexposedStmt"); 2969 case CXCursor_LabelStmt: 2970 return createCXString("LabelStmt"); 2971 case CXCursor_InvalidFile: 2972 return createCXString("InvalidFile"); 2973 case CXCursor_InvalidCode: 2974 return createCXString("InvalidCode"); 2975 case CXCursor_NoDeclFound: 2976 return createCXString("NoDeclFound"); 2977 case CXCursor_NotImplemented: 2978 return createCXString("NotImplemented"); 2979 case CXCursor_TranslationUnit: 2980 return createCXString("TranslationUnit"); 2981 case CXCursor_UnexposedAttr: 2982 return createCXString("UnexposedAttr"); 2983 case CXCursor_IBActionAttr: 2984 return createCXString("attribute(ibaction)"); 2985 case CXCursor_IBOutletAttr: 2986 return createCXString("attribute(iboutlet)"); 2987 case CXCursor_IBOutletCollectionAttr: 2988 return createCXString("attribute(iboutletcollection)"); 2989 case CXCursor_PreprocessingDirective: 2990 return createCXString("preprocessing directive"); 2991 case CXCursor_MacroDefinition: 2992 return createCXString("macro definition"); 2993 case CXCursor_MacroInstantiation: 2994 return createCXString("macro instantiation"); 2995 case CXCursor_InclusionDirective: 2996 return createCXString("inclusion directive"); 2997 case CXCursor_Namespace: 2998 return createCXString("Namespace"); 2999 case CXCursor_LinkageSpec: 3000 return createCXString("LinkageSpec"); 3001 case CXCursor_CXXBaseSpecifier: 3002 return createCXString("C++ base class specifier"); 3003 case CXCursor_Constructor: 3004 return createCXString("CXXConstructor"); 3005 case CXCursor_Destructor: 3006 return createCXString("CXXDestructor"); 3007 case CXCursor_ConversionFunction: 3008 return createCXString("CXXConversion"); 3009 case CXCursor_TemplateTypeParameter: 3010 return createCXString("TemplateTypeParameter"); 3011 case CXCursor_NonTypeTemplateParameter: 3012 return createCXString("NonTypeTemplateParameter"); 3013 case CXCursor_TemplateTemplateParameter: 3014 return createCXString("TemplateTemplateParameter"); 3015 case CXCursor_FunctionTemplate: 3016 return createCXString("FunctionTemplate"); 3017 case CXCursor_ClassTemplate: 3018 return createCXString("ClassTemplate"); 3019 case CXCursor_ClassTemplatePartialSpecialization: 3020 return createCXString("ClassTemplatePartialSpecialization"); 3021 case CXCursor_NamespaceAlias: 3022 return createCXString("NamespaceAlias"); 3023 case CXCursor_UsingDirective: 3024 return createCXString("UsingDirective"); 3025 case CXCursor_UsingDeclaration: 3026 return createCXString("UsingDeclaration"); 3027 } 3028 3029 llvm_unreachable("Unhandled CXCursorKind"); 3030 return createCXString(NULL); 3031} 3032 3033enum CXChildVisitResult GetCursorVisitor(CXCursor cursor, 3034 CXCursor parent, 3035 CXClientData client_data) { 3036 CXCursor *BestCursor = static_cast<CXCursor *>(client_data); 3037 3038 // If our current best cursor is the construction of a temporary object, 3039 // don't replace that cursor with a type reference, because we want 3040 // clang_getCursor() to point at the constructor. 3041 if (clang_isExpression(BestCursor->kind) && 3042 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) && 3043 cursor.kind == CXCursor_TypeRef) 3044 return CXChildVisit_Recurse; 3045 3046 *BestCursor = cursor; 3047 return CXChildVisit_Recurse; 3048} 3049 3050CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) { 3051 if (!TU) 3052 return clang_getNullCursor(); 3053 3054 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU); 3055 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 3056 3057 // Translate the given source location to make it point at the beginning of 3058 // the token under the cursor. 3059 SourceLocation SLoc = cxloc::translateSourceLocation(Loc); 3060 3061 // Guard against an invalid SourceLocation, or we may assert in one 3062 // of the following calls. 3063 if (SLoc.isInvalid()) 3064 return clang_getNullCursor(); 3065 3066 bool Logging = getenv("LIBCLANG_LOGGING"); 3067 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(), 3068 CXXUnit->getASTContext().getLangOptions()); 3069 3070 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound); 3071 if (SLoc.isValid()) { 3072 // FIXME: Would be great to have a "hint" cursor, then walk from that 3073 // hint cursor upward until we find a cursor whose source range encloses 3074 // the region of interest, rather than starting from the translation unit. 3075 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit); 3076 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result, 3077 Decl::MaxPCHLevel, SourceLocation(SLoc)); 3078 CursorVis.VisitChildren(Parent); 3079 } 3080 3081 if (Logging) { 3082 CXFile SearchFile; 3083 unsigned SearchLine, SearchColumn; 3084 CXFile ResultFile; 3085 unsigned ResultLine, ResultColumn; 3086 CXString SearchFileName, ResultFileName, KindSpelling; 3087 CXSourceLocation ResultLoc = clang_getCursorLocation(Result); 3088 3089 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 3090 0); 3091 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine, 3092 &ResultColumn, 0); 3093 SearchFileName = clang_getFileName(SearchFile); 3094 ResultFileName = clang_getFileName(ResultFile); 3095 KindSpelling = clang_getCursorKindSpelling(Result.kind); 3096 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n", 3097 clang_getCString(SearchFileName), SearchLine, SearchColumn, 3098 clang_getCString(KindSpelling), 3099 clang_getCString(ResultFileName), ResultLine, ResultColumn); 3100 clang_disposeString(SearchFileName); 3101 clang_disposeString(ResultFileName); 3102 clang_disposeString(KindSpelling); 3103 } 3104 3105 return Result; 3106} 3107 3108CXCursor clang_getNullCursor(void) { 3109 return MakeCXCursorInvalid(CXCursor_InvalidFile); 3110} 3111 3112unsigned clang_equalCursors(CXCursor X, CXCursor Y) { 3113 return X == Y; 3114} 3115 3116unsigned clang_isInvalid(enum CXCursorKind K) { 3117 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid; 3118} 3119 3120unsigned clang_isDeclaration(enum CXCursorKind K) { 3121 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl; 3122} 3123 3124unsigned clang_isReference(enum CXCursorKind K) { 3125 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef; 3126} 3127 3128unsigned clang_isExpression(enum CXCursorKind K) { 3129 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr; 3130} 3131 3132unsigned clang_isStatement(enum CXCursorKind K) { 3133 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt; 3134} 3135 3136unsigned clang_isTranslationUnit(enum CXCursorKind K) { 3137 return K == CXCursor_TranslationUnit; 3138} 3139 3140unsigned clang_isPreprocessing(enum CXCursorKind K) { 3141 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing; 3142} 3143 3144unsigned clang_isUnexposed(enum CXCursorKind K) { 3145 switch (K) { 3146 case CXCursor_UnexposedDecl: 3147 case CXCursor_UnexposedExpr: 3148 case CXCursor_UnexposedStmt: 3149 case CXCursor_UnexposedAttr: 3150 return true; 3151 default: 3152 return false; 3153 } 3154} 3155 3156CXCursorKind clang_getCursorKind(CXCursor C) { 3157 return C.kind; 3158} 3159 3160CXSourceLocation clang_getCursorLocation(CXCursor C) { 3161 if (clang_isReference(C.kind)) { 3162 switch (C.kind) { 3163 case CXCursor_ObjCSuperClassRef: { 3164 std::pair<ObjCInterfaceDecl *, SourceLocation> P 3165 = getCursorObjCSuperClassRef(C); 3166 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3167 } 3168 3169 case CXCursor_ObjCProtocolRef: { 3170 std::pair<ObjCProtocolDecl *, SourceLocation> P 3171 = getCursorObjCProtocolRef(C); 3172 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3173 } 3174 3175 case CXCursor_ObjCClassRef: { 3176 std::pair<ObjCInterfaceDecl *, SourceLocation> P 3177 = getCursorObjCClassRef(C); 3178 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3179 } 3180 3181 case CXCursor_TypeRef: { 3182 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C); 3183 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3184 } 3185 3186 case CXCursor_TemplateRef: { 3187 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C); 3188 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3189 } 3190 3191 case CXCursor_NamespaceRef: { 3192 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C); 3193 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3194 } 3195 3196 case CXCursor_MemberRef: { 3197 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C); 3198 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 3199 } 3200 3201 case CXCursor_CXXBaseSpecifier: { 3202 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C); 3203 if (!BaseSpec) 3204 return clang_getNullLocation(); 3205 3206 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo()) 3207 return cxloc::translateSourceLocation(getCursorContext(C), 3208 TSInfo->getTypeLoc().getBeginLoc()); 3209 3210 return cxloc::translateSourceLocation(getCursorContext(C), 3211 BaseSpec->getSourceRange().getBegin()); 3212 } 3213 3214 case CXCursor_LabelRef: { 3215 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C); 3216 return cxloc::translateSourceLocation(getCursorContext(C), P.second); 3217 } 3218 3219 case CXCursor_OverloadedDeclRef: 3220 return cxloc::translateSourceLocation(getCursorContext(C), 3221 getCursorOverloadedDeclRef(C).second); 3222 3223 default: 3224 // FIXME: Need a way to enumerate all non-reference cases. 3225 llvm_unreachable("Missed a reference kind"); 3226 } 3227 } 3228 3229 if (clang_isExpression(C.kind)) 3230 return cxloc::translateSourceLocation(getCursorContext(C), 3231 getLocationFromExpr(getCursorExpr(C))); 3232 3233 if (clang_isStatement(C.kind)) 3234 return cxloc::translateSourceLocation(getCursorContext(C), 3235 getCursorStmt(C)->getLocStart()); 3236 3237 if (C.kind == CXCursor_PreprocessingDirective) { 3238 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin(); 3239 return cxloc::translateSourceLocation(getCursorContext(C), L); 3240 } 3241 3242 if (C.kind == CXCursor_MacroInstantiation) { 3243 SourceLocation L 3244 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin(); 3245 return cxloc::translateSourceLocation(getCursorContext(C), L); 3246 } 3247 3248 if (C.kind == CXCursor_MacroDefinition) { 3249 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation(); 3250 return cxloc::translateSourceLocation(getCursorContext(C), L); 3251 } 3252 3253 if (C.kind == CXCursor_InclusionDirective) { 3254 SourceLocation L 3255 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin(); 3256 return cxloc::translateSourceLocation(getCursorContext(C), L); 3257 } 3258 3259 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl) 3260 return clang_getNullLocation(); 3261 3262 Decl *D = getCursorDecl(C); 3263 SourceLocation Loc = D->getLocation(); 3264 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D)) 3265 Loc = Class->getClassLoc(); 3266 // FIXME: Multiple variables declared in a single declaration 3267 // currently lack the information needed to correctly determine their 3268 // ranges when accounting for the type-specifier. We use context 3269 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, 3270 // and if so, whether it is the first decl. 3271 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 3272 if (!cxcursor::isFirstInDeclGroup(C)) 3273 Loc = VD->getLocation(); 3274 } 3275 3276 return cxloc::translateSourceLocation(getCursorContext(C), Loc); 3277} 3278 3279} // end extern "C" 3280 3281static SourceRange getRawCursorExtent(CXCursor C) { 3282 if (clang_isReference(C.kind)) { 3283 switch (C.kind) { 3284 case CXCursor_ObjCSuperClassRef: 3285 return getCursorObjCSuperClassRef(C).second; 3286 3287 case CXCursor_ObjCProtocolRef: 3288 return getCursorObjCProtocolRef(C).second; 3289 3290 case CXCursor_ObjCClassRef: 3291 return getCursorObjCClassRef(C).second; 3292 3293 case CXCursor_TypeRef: 3294 return getCursorTypeRef(C).second; 3295 3296 case CXCursor_TemplateRef: 3297 return getCursorTemplateRef(C).second; 3298 3299 case CXCursor_NamespaceRef: 3300 return getCursorNamespaceRef(C).second; 3301 3302 case CXCursor_MemberRef: 3303 return getCursorMemberRef(C).second; 3304 3305 case CXCursor_CXXBaseSpecifier: 3306 return getCursorCXXBaseSpecifier(C)->getSourceRange(); 3307 3308 case CXCursor_LabelRef: 3309 return getCursorLabelRef(C).second; 3310 3311 case CXCursor_OverloadedDeclRef: 3312 return getCursorOverloadedDeclRef(C).second; 3313 3314 default: 3315 // FIXME: Need a way to enumerate all non-reference cases. 3316 llvm_unreachable("Missed a reference kind"); 3317 } 3318 } 3319 3320 if (clang_isExpression(C.kind)) 3321 return getCursorExpr(C)->getSourceRange(); 3322 3323 if (clang_isStatement(C.kind)) 3324 return getCursorStmt(C)->getSourceRange(); 3325 3326 if (C.kind == CXCursor_PreprocessingDirective) 3327 return cxcursor::getCursorPreprocessingDirective(C); 3328 3329 if (C.kind == CXCursor_MacroInstantiation) 3330 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange(); 3331 3332 if (C.kind == CXCursor_MacroDefinition) 3333 return cxcursor::getCursorMacroDefinition(C)->getSourceRange(); 3334 3335 if (C.kind == CXCursor_InclusionDirective) 3336 return cxcursor::getCursorInclusionDirective(C)->getSourceRange(); 3337 3338 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) { 3339 Decl *D = cxcursor::getCursorDecl(C); 3340 SourceRange R = D->getSourceRange(); 3341 // FIXME: Multiple variables declared in a single declaration 3342 // currently lack the information needed to correctly determine their 3343 // ranges when accounting for the type-specifier. We use context 3344 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, 3345 // and if so, whether it is the first decl. 3346 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 3347 if (!cxcursor::isFirstInDeclGroup(C)) 3348 R.setBegin(VD->getLocation()); 3349 } 3350 return R; 3351 } 3352 return SourceRange();} 3353 3354extern "C" { 3355 3356CXSourceRange clang_getCursorExtent(CXCursor C) { 3357 SourceRange R = getRawCursorExtent(C); 3358 if (R.isInvalid()) 3359 return clang_getNullRange(); 3360 3361 return cxloc::translateSourceRange(getCursorContext(C), R); 3362} 3363 3364CXCursor clang_getCursorReferenced(CXCursor C) { 3365 if (clang_isInvalid(C.kind)) 3366 return clang_getNullCursor(); 3367 3368 ASTUnit *CXXUnit = getCursorASTUnit(C); 3369 if (clang_isDeclaration(C.kind)) { 3370 Decl *D = getCursorDecl(C); 3371 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) 3372 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit); 3373 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D)) 3374 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit); 3375 if (ObjCForwardProtocolDecl *Protocols 3376 = dyn_cast<ObjCForwardProtocolDecl>(D)) 3377 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit); 3378 3379 return C; 3380 } 3381 3382 if (clang_isExpression(C.kind)) { 3383 Expr *E = getCursorExpr(C); 3384 Decl *D = getDeclFromExpr(E); 3385 if (D) 3386 return MakeCXCursor(D, CXXUnit); 3387 3388 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E)) 3389 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit); 3390 3391 return clang_getNullCursor(); 3392 } 3393 3394 if (clang_isStatement(C.kind)) { 3395 Stmt *S = getCursorStmt(C); 3396 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S)) 3397 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C), 3398 getCursorASTUnit(C)); 3399 3400 return clang_getNullCursor(); 3401 } 3402 3403 if (C.kind == CXCursor_MacroInstantiation) { 3404 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition()) 3405 return MakeMacroDefinitionCursor(Def, CXXUnit); 3406 } 3407 3408 if (!clang_isReference(C.kind)) 3409 return clang_getNullCursor(); 3410 3411 switch (C.kind) { 3412 case CXCursor_ObjCSuperClassRef: 3413 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit); 3414 3415 case CXCursor_ObjCProtocolRef: { 3416 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit); 3417 3418 case CXCursor_ObjCClassRef: 3419 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit); 3420 3421 case CXCursor_TypeRef: 3422 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit); 3423 3424 case CXCursor_TemplateRef: 3425 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit); 3426 3427 case CXCursor_NamespaceRef: 3428 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit); 3429 3430 case CXCursor_MemberRef: 3431 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit); 3432 3433 case CXCursor_CXXBaseSpecifier: { 3434 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C); 3435 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(), 3436 CXXUnit)); 3437 } 3438 3439 case CXCursor_LabelRef: 3440 // FIXME: We end up faking the "parent" declaration here because we 3441 // don't want to make CXCursor larger. 3442 return MakeCXCursor(getCursorLabelRef(C).first, 3443 CXXUnit->getASTContext().getTranslationUnitDecl(), 3444 CXXUnit); 3445 3446 case CXCursor_OverloadedDeclRef: 3447 return C; 3448 3449 default: 3450 // We would prefer to enumerate all non-reference cursor kinds here. 3451 llvm_unreachable("Unhandled reference cursor kind"); 3452 break; 3453 } 3454 } 3455 3456 return clang_getNullCursor(); 3457} 3458 3459CXCursor clang_getCursorDefinition(CXCursor C) { 3460 if (clang_isInvalid(C.kind)) 3461 return clang_getNullCursor(); 3462 3463 ASTUnit *CXXUnit = getCursorASTUnit(C); 3464 3465 bool WasReference = false; 3466 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) { 3467 C = clang_getCursorReferenced(C); 3468 WasReference = true; 3469 } 3470 3471 if (C.kind == CXCursor_MacroInstantiation) 3472 return clang_getCursorReferenced(C); 3473 3474 if (!clang_isDeclaration(C.kind)) 3475 return clang_getNullCursor(); 3476 3477 Decl *D = getCursorDecl(C); 3478 if (!D) 3479 return clang_getNullCursor(); 3480 3481 switch (D->getKind()) { 3482 // Declaration kinds that don't really separate the notions of 3483 // declaration and definition. 3484 case Decl::Namespace: 3485 case Decl::Typedef: 3486 case Decl::TemplateTypeParm: 3487 case Decl::EnumConstant: 3488 case Decl::Field: 3489 case Decl::ObjCIvar: 3490 case Decl::ObjCAtDefsField: 3491 case Decl::ImplicitParam: 3492 case Decl::ParmVar: 3493 case Decl::NonTypeTemplateParm: 3494 case Decl::TemplateTemplateParm: 3495 case Decl::ObjCCategoryImpl: 3496 case Decl::ObjCImplementation: 3497 case Decl::AccessSpec: 3498 case Decl::LinkageSpec: 3499 case Decl::ObjCPropertyImpl: 3500 case Decl::FileScopeAsm: 3501 case Decl::StaticAssert: 3502 case Decl::Block: 3503 return C; 3504 3505 // Declaration kinds that don't make any sense here, but are 3506 // nonetheless harmless. 3507 case Decl::TranslationUnit: 3508 break; 3509 3510 // Declaration kinds for which the definition is not resolvable. 3511 case Decl::UnresolvedUsingTypename: 3512 case Decl::UnresolvedUsingValue: 3513 break; 3514 3515 case Decl::UsingDirective: 3516 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(), 3517 CXXUnit); 3518 3519 case Decl::NamespaceAlias: 3520 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit); 3521 3522 case Decl::Enum: 3523 case Decl::Record: 3524 case Decl::CXXRecord: 3525 case Decl::ClassTemplateSpecialization: 3526 case Decl::ClassTemplatePartialSpecialization: 3527 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition()) 3528 return MakeCXCursor(Def, CXXUnit); 3529 return clang_getNullCursor(); 3530 3531 case Decl::Function: 3532 case Decl::CXXMethod: 3533 case Decl::CXXConstructor: 3534 case Decl::CXXDestructor: 3535 case Decl::CXXConversion: { 3536 const FunctionDecl *Def = 0; 3537 if (cast<FunctionDecl>(D)->getBody(Def)) 3538 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit); 3539 return clang_getNullCursor(); 3540 } 3541 3542 case Decl::Var: { 3543 // Ask the variable if it has a definition. 3544 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition()) 3545 return MakeCXCursor(Def, CXXUnit); 3546 return clang_getNullCursor(); 3547 } 3548 3549 case Decl::FunctionTemplate: { 3550 const FunctionDecl *Def = 0; 3551 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def)) 3552 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit); 3553 return clang_getNullCursor(); 3554 } 3555 3556 case Decl::ClassTemplate: { 3557 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl() 3558 ->getDefinition()) 3559 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(), 3560 CXXUnit); 3561 return clang_getNullCursor(); 3562 } 3563 3564 case Decl::Using: 3565 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D), 3566 D->getLocation(), CXXUnit); 3567 3568 case Decl::UsingShadow: 3569 return clang_getCursorDefinition( 3570 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(), 3571 CXXUnit)); 3572 3573 case Decl::ObjCMethod: { 3574 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D); 3575 if (Method->isThisDeclarationADefinition()) 3576 return C; 3577 3578 // Dig out the method definition in the associated 3579 // @implementation, if we have it. 3580 // FIXME: The ASTs should make finding the definition easier. 3581 if (ObjCInterfaceDecl *Class 3582 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) 3583 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation()) 3584 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(), 3585 Method->isInstanceMethod())) 3586 if (Def->isThisDeclarationADefinition()) 3587 return MakeCXCursor(Def, CXXUnit); 3588 3589 return clang_getNullCursor(); 3590 } 3591 3592 case Decl::ObjCCategory: 3593 if (ObjCCategoryImplDecl *Impl 3594 = cast<ObjCCategoryDecl>(D)->getImplementation()) 3595 return MakeCXCursor(Impl, CXXUnit); 3596 return clang_getNullCursor(); 3597 3598 case Decl::ObjCProtocol: 3599 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl()) 3600 return C; 3601 return clang_getNullCursor(); 3602 3603 case Decl::ObjCInterface: 3604 // There are two notions of a "definition" for an Objective-C 3605 // class: the interface and its implementation. When we resolved a 3606 // reference to an Objective-C class, produce the @interface as 3607 // the definition; when we were provided with the interface, 3608 // produce the @implementation as the definition. 3609 if (WasReference) { 3610 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl()) 3611 return C; 3612 } else if (ObjCImplementationDecl *Impl 3613 = cast<ObjCInterfaceDecl>(D)->getImplementation()) 3614 return MakeCXCursor(Impl, CXXUnit); 3615 return clang_getNullCursor(); 3616 3617 case Decl::ObjCProperty: 3618 // FIXME: We don't really know where to find the 3619 // ObjCPropertyImplDecls that implement this property. 3620 return clang_getNullCursor(); 3621 3622 case Decl::ObjCCompatibleAlias: 3623 if (ObjCInterfaceDecl *Class 3624 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface()) 3625 if (!Class->isForwardDecl()) 3626 return MakeCXCursor(Class, CXXUnit); 3627 3628 return clang_getNullCursor(); 3629 3630 case Decl::ObjCForwardProtocol: 3631 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D), 3632 D->getLocation(), CXXUnit); 3633 3634 case Decl::ObjCClass: 3635 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(), 3636 CXXUnit); 3637 3638 case Decl::Friend: 3639 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl()) 3640 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit)); 3641 return clang_getNullCursor(); 3642 3643 case Decl::FriendTemplate: 3644 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl()) 3645 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit)); 3646 return clang_getNullCursor(); 3647 } 3648 3649 return clang_getNullCursor(); 3650} 3651 3652unsigned clang_isCursorDefinition(CXCursor C) { 3653 if (!clang_isDeclaration(C.kind)) 3654 return 0; 3655 3656 return clang_getCursorDefinition(C) == C; 3657} 3658 3659unsigned clang_getNumOverloadedDecls(CXCursor C) { 3660 if (C.kind != CXCursor_OverloadedDeclRef) 3661 return 0; 3662 3663 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first; 3664 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>()) 3665 return E->getNumDecls(); 3666 3667 if (OverloadedTemplateStorage *S 3668 = Storage.dyn_cast<OverloadedTemplateStorage*>()) 3669 return S->size(); 3670 3671 Decl *D = Storage.get<Decl*>(); 3672 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) 3673 return Using->shadow_size(); 3674 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D)) 3675 return Classes->size(); 3676 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D)) 3677 return Protocols->protocol_size(); 3678 3679 return 0; 3680} 3681 3682CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) { 3683 if (cursor.kind != CXCursor_OverloadedDeclRef) 3684 return clang_getNullCursor(); 3685 3686 if (index >= clang_getNumOverloadedDecls(cursor)) 3687 return clang_getNullCursor(); 3688 3689 ASTUnit *Unit = getCursorASTUnit(cursor); 3690 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first; 3691 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>()) 3692 return MakeCXCursor(E->decls_begin()[index], Unit); 3693 3694 if (OverloadedTemplateStorage *S 3695 = Storage.dyn_cast<OverloadedTemplateStorage*>()) 3696 return MakeCXCursor(S->begin()[index], Unit); 3697 3698 Decl *D = Storage.get<Decl*>(); 3699 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) { 3700 // FIXME: This is, unfortunately, linear time. 3701 UsingDecl::shadow_iterator Pos = Using->shadow_begin(); 3702 std::advance(Pos, index); 3703 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit); 3704 } 3705 3706 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D)) 3707 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit); 3708 3709 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D)) 3710 return MakeCXCursor(Protocols->protocol_begin()[index], Unit); 3711 3712 return clang_getNullCursor(); 3713} 3714 3715void clang_getDefinitionSpellingAndExtent(CXCursor C, 3716 const char **startBuf, 3717 const char **endBuf, 3718 unsigned *startLine, 3719 unsigned *startColumn, 3720 unsigned *endLine, 3721 unsigned *endColumn) { 3722 assert(getCursorDecl(C) && "CXCursor has null decl"); 3723 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C)); 3724 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND); 3725 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody()); 3726 3727 SourceManager &SM = FD->getASTContext().getSourceManager(); 3728 *startBuf = SM.getCharacterData(Body->getLBracLoc()); 3729 *endBuf = SM.getCharacterData(Body->getRBracLoc()); 3730 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc()); 3731 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc()); 3732 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc()); 3733 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc()); 3734} 3735 3736void clang_enableStackTraces(void) { 3737 llvm::sys::PrintStackTraceOnErrorSignal(); 3738} 3739 3740void clang_executeOnThread(void (*fn)(void*), void *user_data, 3741 unsigned stack_size) { 3742 llvm::llvm_execute_on_thread(fn, user_data, stack_size); 3743} 3744 3745} // end: extern "C" 3746 3747//===----------------------------------------------------------------------===// 3748// Token-based Operations. 3749//===----------------------------------------------------------------------===// 3750 3751/* CXToken layout: 3752 * int_data[0]: a CXTokenKind 3753 * int_data[1]: starting token location 3754 * int_data[2]: token length 3755 * int_data[3]: reserved 3756 * ptr_data: for identifiers and keywords, an IdentifierInfo*. 3757 * otherwise unused. 3758 */ 3759extern "C" { 3760 3761CXTokenKind clang_getTokenKind(CXToken CXTok) { 3762 return static_cast<CXTokenKind>(CXTok.int_data[0]); 3763} 3764 3765CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) { 3766 switch (clang_getTokenKind(CXTok)) { 3767 case CXToken_Identifier: 3768 case CXToken_Keyword: 3769 // We know we have an IdentifierInfo*, so use that. 3770 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data) 3771 ->getNameStart()); 3772 3773 case CXToken_Literal: { 3774 // We have stashed the starting pointer in the ptr_data field. Use it. 3775 const char *Text = static_cast<const char *>(CXTok.ptr_data); 3776 return createCXString(llvm::StringRef(Text, CXTok.int_data[2])); 3777 } 3778 3779 case CXToken_Punctuation: 3780 case CXToken_Comment: 3781 break; 3782 } 3783 3784 // We have to find the starting buffer pointer the hard way, by 3785 // deconstructing the source location. 3786 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU); 3787 if (!CXXUnit) 3788 return createCXString(""); 3789 3790 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]); 3791 std::pair<FileID, unsigned> LocInfo 3792 = CXXUnit->getSourceManager().getDecomposedLoc(Loc); 3793 bool Invalid = false; 3794 llvm::StringRef Buffer 3795 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid); 3796 if (Invalid) 3797 return createCXString(""); 3798 3799 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2])); 3800} 3801 3802CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) { 3803 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU); 3804 if (!CXXUnit) 3805 return clang_getNullLocation(); 3806 3807 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), 3808 SourceLocation::getFromRawEncoding(CXTok.int_data[1])); 3809} 3810 3811CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) { 3812 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU); 3813 if (!CXXUnit) 3814 return clang_getNullRange(); 3815 3816 return cxloc::translateSourceRange(CXXUnit->getASTContext(), 3817 SourceLocation::getFromRawEncoding(CXTok.int_data[1])); 3818} 3819 3820void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range, 3821 CXToken **Tokens, unsigned *NumTokens) { 3822 if (Tokens) 3823 *Tokens = 0; 3824 if (NumTokens) 3825 *NumTokens = 0; 3826 3827 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU); 3828 if (!CXXUnit || !Tokens || !NumTokens) 3829 return; 3830 3831 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 3832 3833 SourceRange R = cxloc::translateCXSourceRange(Range); 3834 if (R.isInvalid()) 3835 return; 3836 3837 SourceManager &SourceMgr = CXXUnit->getSourceManager(); 3838 std::pair<FileID, unsigned> BeginLocInfo 3839 = SourceMgr.getDecomposedLoc(R.getBegin()); 3840 std::pair<FileID, unsigned> EndLocInfo 3841 = SourceMgr.getDecomposedLoc(R.getEnd()); 3842 3843 // Cannot tokenize across files. 3844 if (BeginLocInfo.first != EndLocInfo.first) 3845 return; 3846 3847 // Create a lexer 3848 bool Invalid = false; 3849 llvm::StringRef Buffer 3850 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid); 3851 if (Invalid) 3852 return; 3853 3854 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first), 3855 CXXUnit->getASTContext().getLangOptions(), 3856 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end()); 3857 Lex.SetCommentRetentionState(true); 3858 3859 // Lex tokens until we hit the end of the range. 3860 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second; 3861 llvm::SmallVector<CXToken, 32> CXTokens; 3862 Token Tok; 3863 bool previousWasAt = false; 3864 do { 3865 // Lex the next token 3866 Lex.LexFromRawLexer(Tok); 3867 if (Tok.is(tok::eof)) 3868 break; 3869 3870 // Initialize the CXToken. 3871 CXToken CXTok; 3872 3873 // - Common fields 3874 CXTok.int_data[1] = Tok.getLocation().getRawEncoding(); 3875 CXTok.int_data[2] = Tok.getLength(); 3876 CXTok.int_data[3] = 0; 3877 3878 // - Kind-specific fields 3879 if (Tok.isLiteral()) { 3880 CXTok.int_data[0] = CXToken_Literal; 3881 CXTok.ptr_data = (void *)Tok.getLiteralData(); 3882 } else if (Tok.is(tok::identifier)) { 3883 // Lookup the identifier to determine whether we have a keyword. 3884 std::pair<FileID, unsigned> LocInfo 3885 = SourceMgr.getDecomposedLoc(Tok.getLocation()); 3886 bool Invalid = false; 3887 llvm::StringRef Buf 3888 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid); 3889 if (Invalid) 3890 return; 3891 3892 const char *StartPos = Buf.data() + LocInfo.second; 3893 IdentifierInfo *II 3894 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos); 3895 3896 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) { 3897 CXTok.int_data[0] = CXToken_Keyword; 3898 } 3899 else { 3900 CXTok.int_data[0] = II->getTokenID() == tok::identifier? 3901 CXToken_Identifier 3902 : CXToken_Keyword; 3903 } 3904 CXTok.ptr_data = II; 3905 } else if (Tok.is(tok::comment)) { 3906 CXTok.int_data[0] = CXToken_Comment; 3907 CXTok.ptr_data = 0; 3908 } else { 3909 CXTok.int_data[0] = CXToken_Punctuation; 3910 CXTok.ptr_data = 0; 3911 } 3912 CXTokens.push_back(CXTok); 3913 previousWasAt = Tok.is(tok::at); 3914 } while (Lex.getBufferLocation() <= EffectiveBufferEnd); 3915 3916 if (CXTokens.empty()) 3917 return; 3918 3919 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size()); 3920 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size()); 3921 *NumTokens = CXTokens.size(); 3922} 3923 3924void clang_disposeTokens(CXTranslationUnit TU, 3925 CXToken *Tokens, unsigned NumTokens) { 3926 free(Tokens); 3927} 3928 3929} // end: extern "C" 3930 3931//===----------------------------------------------------------------------===// 3932// Token annotation APIs. 3933//===----------------------------------------------------------------------===// 3934 3935typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData; 3936static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor, 3937 CXCursor parent, 3938 CXClientData client_data); 3939namespace { 3940class AnnotateTokensWorker { 3941 AnnotateTokensData &Annotated; 3942 CXToken *Tokens; 3943 CXCursor *Cursors; 3944 unsigned NumTokens; 3945 unsigned TokIdx; 3946 unsigned PreprocessingTokIdx; 3947 CursorVisitor AnnotateVis; 3948 SourceManager &SrcMgr; 3949 3950 bool MoreTokens() const { return TokIdx < NumTokens; } 3951 unsigned NextToken() const { return TokIdx; } 3952 void AdvanceToken() { ++TokIdx; } 3953 SourceLocation GetTokenLoc(unsigned tokI) { 3954 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]); 3955 } 3956 3957public: 3958 AnnotateTokensWorker(AnnotateTokensData &annotated, 3959 CXToken *tokens, CXCursor *cursors, unsigned numTokens, 3960 ASTUnit *CXXUnit, SourceRange RegionOfInterest) 3961 : Annotated(annotated), Tokens(tokens), Cursors(cursors), 3962 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0), 3963 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this, 3964 Decl::MaxPCHLevel, RegionOfInterest), 3965 SrcMgr(CXXUnit->getSourceManager()) {} 3966 3967 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); } 3968 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent); 3969 void AnnotateTokens(CXCursor parent); 3970 void AnnotateTokens() { 3971 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getASTUnit())); 3972 } 3973}; 3974} 3975 3976void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) { 3977 // Walk the AST within the region of interest, annotating tokens 3978 // along the way. 3979 VisitChildren(parent); 3980 3981 for (unsigned I = 0 ; I < TokIdx ; ++I) { 3982 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]); 3983 if (Pos != Annotated.end() && 3984 (clang_isInvalid(Cursors[I].kind) || 3985 Pos->second.kind != CXCursor_PreprocessingDirective)) 3986 Cursors[I] = Pos->second; 3987 } 3988 3989 // Finish up annotating any tokens left. 3990 if (!MoreTokens()) 3991 return; 3992 3993 const CXCursor &C = clang_getNullCursor(); 3994 for (unsigned I = TokIdx ; I < NumTokens ; ++I) { 3995 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]); 3996 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second; 3997 } 3998} 3999 4000enum CXChildVisitResult 4001AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) { 4002 CXSourceLocation Loc = clang_getCursorLocation(cursor); 4003 SourceRange cursorRange = getRawCursorExtent(cursor); 4004 if (cursorRange.isInvalid()) 4005 return CXChildVisit_Recurse; 4006 4007 if (clang_isPreprocessing(cursor.kind)) { 4008 // For macro instantiations, just note where the beginning of the macro 4009 // instantiation occurs. 4010 if (cursor.kind == CXCursor_MacroInstantiation) { 4011 Annotated[Loc.int_data] = cursor; 4012 return CXChildVisit_Recurse; 4013 } 4014 4015 // Items in the preprocessing record are kept separate from items in 4016 // declarations, so we keep a separate token index. 4017 unsigned SavedTokIdx = TokIdx; 4018 TokIdx = PreprocessingTokIdx; 4019 4020 // Skip tokens up until we catch up to the beginning of the preprocessing 4021 // entry. 4022 while (MoreTokens()) { 4023 const unsigned I = NextToken(); 4024 SourceLocation TokLoc = GetTokenLoc(I); 4025 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 4026 case RangeBefore: 4027 AdvanceToken(); 4028 continue; 4029 case RangeAfter: 4030 case RangeOverlap: 4031 break; 4032 } 4033 break; 4034 } 4035 4036 // Look at all of the tokens within this range. 4037 while (MoreTokens()) { 4038 const unsigned I = NextToken(); 4039 SourceLocation TokLoc = GetTokenLoc(I); 4040 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 4041 case RangeBefore: 4042 assert(0 && "Infeasible"); 4043 case RangeAfter: 4044 break; 4045 case RangeOverlap: 4046 Cursors[I] = cursor; 4047 AdvanceToken(); 4048 continue; 4049 } 4050 break; 4051 } 4052 4053 // Save the preprocessing token index; restore the non-preprocessing 4054 // token index. 4055 PreprocessingTokIdx = TokIdx; 4056 TokIdx = SavedTokIdx; 4057 return CXChildVisit_Recurse; 4058 } 4059 4060 if (cursorRange.isInvalid()) 4061 return CXChildVisit_Continue; 4062 4063 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data); 4064 4065 // Adjust the annotated range based specific declarations. 4066 const enum CXCursorKind cursorK = clang_getCursorKind(cursor); 4067 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) { 4068 Decl *D = cxcursor::getCursorDecl(cursor); 4069 // Don't visit synthesized ObjC methods, since they have no syntatic 4070 // representation in the source. 4071 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 4072 if (MD->isSynthesized()) 4073 return CXChildVisit_Continue; 4074 } 4075 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 4076 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) { 4077 TypeLoc TL = TI->getTypeLoc(); 4078 SourceLocation TLoc = TL.getSourceRange().getBegin(); 4079 if (TLoc.isValid() && L.isValid() && 4080 SrcMgr.isBeforeInTranslationUnit(TLoc, L)) 4081 cursorRange.setBegin(TLoc); 4082 } 4083 } 4084 } 4085 4086 // If the location of the cursor occurs within a macro instantiation, record 4087 // the spelling location of the cursor in our annotation map. We can then 4088 // paper over the token labelings during a post-processing step to try and 4089 // get cursor mappings for tokens that are the *arguments* of a macro 4090 // instantiation. 4091 if (L.isMacroID()) { 4092 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding(); 4093 // Only invalidate the old annotation if it isn't part of a preprocessing 4094 // directive. Here we assume that the default construction of CXCursor 4095 // results in CXCursor.kind being an initialized value (i.e., 0). If 4096 // this isn't the case, we can fix by doing lookup + insertion. 4097 4098 CXCursor &oldC = Annotated[rawEncoding]; 4099 if (!clang_isPreprocessing(oldC.kind)) 4100 oldC = cursor; 4101 } 4102 4103 const enum CXCursorKind K = clang_getCursorKind(parent); 4104 const CXCursor updateC = 4105 (clang_isInvalid(K) || K == CXCursor_TranslationUnit) 4106 ? clang_getNullCursor() : parent; 4107 4108 while (MoreTokens()) { 4109 const unsigned I = NextToken(); 4110 SourceLocation TokLoc = GetTokenLoc(I); 4111 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 4112 case RangeBefore: 4113 Cursors[I] = updateC; 4114 AdvanceToken(); 4115 continue; 4116 case RangeAfter: 4117 case RangeOverlap: 4118 break; 4119 } 4120 break; 4121 } 4122 4123 // Visit children to get their cursor information. 4124 const unsigned BeforeChildren = NextToken(); 4125 VisitChildren(cursor); 4126 const unsigned AfterChildren = NextToken(); 4127 4128 // Adjust 'Last' to the last token within the extent of the cursor. 4129 while (MoreTokens()) { 4130 const unsigned I = NextToken(); 4131 SourceLocation TokLoc = GetTokenLoc(I); 4132 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 4133 case RangeBefore: 4134 assert(0 && "Infeasible"); 4135 case RangeAfter: 4136 break; 4137 case RangeOverlap: 4138 Cursors[I] = updateC; 4139 AdvanceToken(); 4140 continue; 4141 } 4142 break; 4143 } 4144 const unsigned Last = NextToken(); 4145 4146 // Scan the tokens that are at the beginning of the cursor, but are not 4147 // capture by the child cursors. 4148 4149 // For AST elements within macros, rely on a post-annotate pass to 4150 // to correctly annotate the tokens with cursors. Otherwise we can 4151 // get confusing results of having tokens that map to cursors that really 4152 // are expanded by an instantiation. 4153 if (L.isMacroID()) 4154 cursor = clang_getNullCursor(); 4155 4156 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) { 4157 if (!clang_isInvalid(clang_getCursorKind(Cursors[I]))) 4158 break; 4159 4160 Cursors[I] = cursor; 4161 } 4162 // Scan the tokens that are at the end of the cursor, but are not captured 4163 // but the child cursors. 4164 for (unsigned I = AfterChildren; I != Last; ++I) 4165 Cursors[I] = cursor; 4166 4167 TokIdx = Last; 4168 return CXChildVisit_Continue; 4169} 4170 4171static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor, 4172 CXCursor parent, 4173 CXClientData client_data) { 4174 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent); 4175} 4176 4177// This gets run a separate thread to avoid stack blowout. 4178static void runAnnotateTokensWorker(void *UserData) { 4179 ((AnnotateTokensWorker*)UserData)->AnnotateTokens(); 4180} 4181 4182extern "C" { 4183 4184void clang_annotateTokens(CXTranslationUnit TU, 4185 CXToken *Tokens, unsigned NumTokens, 4186 CXCursor *Cursors) { 4187 4188 if (NumTokens == 0 || !Tokens || !Cursors) 4189 return; 4190 4191 // Any token we don't specifically annotate will have a NULL cursor. 4192 CXCursor C = clang_getNullCursor(); 4193 for (unsigned I = 0; I != NumTokens; ++I) 4194 Cursors[I] = C; 4195 4196 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU); 4197 if (!CXXUnit) 4198 return; 4199 4200 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 4201 4202 // Determine the region of interest, which contains all of the tokens. 4203 SourceRange RegionOfInterest; 4204 RegionOfInterest.setBegin(cxloc::translateSourceLocation( 4205 clang_getTokenLocation(TU, Tokens[0]))); 4206 RegionOfInterest.setEnd(cxloc::translateSourceLocation( 4207 clang_getTokenLocation(TU, 4208 Tokens[NumTokens - 1]))); 4209 4210 // A mapping from the source locations found when re-lexing or traversing the 4211 // region of interest to the corresponding cursors. 4212 AnnotateTokensData Annotated; 4213 4214 // Relex the tokens within the source range to look for preprocessing 4215 // directives. 4216 SourceManager &SourceMgr = CXXUnit->getSourceManager(); 4217 std::pair<FileID, unsigned> BeginLocInfo 4218 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin()); 4219 std::pair<FileID, unsigned> EndLocInfo 4220 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd()); 4221 4222 llvm::StringRef Buffer; 4223 bool Invalid = false; 4224 if (BeginLocInfo.first == EndLocInfo.first && 4225 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) && 4226 !Invalid) { 4227 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first), 4228 CXXUnit->getASTContext().getLangOptions(), 4229 Buffer.begin(), Buffer.data() + BeginLocInfo.second, 4230 Buffer.end()); 4231 Lex.SetCommentRetentionState(true); 4232 4233 // Lex tokens in raw mode until we hit the end of the range, to avoid 4234 // entering #includes or expanding macros. 4235 while (true) { 4236 Token Tok; 4237 Lex.LexFromRawLexer(Tok); 4238 4239 reprocess: 4240 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) { 4241 // We have found a preprocessing directive. Gobble it up so that we 4242 // don't see it while preprocessing these tokens later, but keep track 4243 // of all of the token locations inside this preprocessing directive so 4244 // that we can annotate them appropriately. 4245 // 4246 // FIXME: Some simple tests here could identify macro definitions and 4247 // #undefs, to provide specific cursor kinds for those. 4248 std::vector<SourceLocation> Locations; 4249 do { 4250 Locations.push_back(Tok.getLocation()); 4251 Lex.LexFromRawLexer(Tok); 4252 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof)); 4253 4254 using namespace cxcursor; 4255 CXCursor Cursor 4256 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(), 4257 Locations.back()), 4258 CXXUnit); 4259 for (unsigned I = 0, N = Locations.size(); I != N; ++I) { 4260 Annotated[Locations[I].getRawEncoding()] = Cursor; 4261 } 4262 4263 if (Tok.isAtStartOfLine()) 4264 goto reprocess; 4265 4266 continue; 4267 } 4268 4269 if (Tok.is(tok::eof)) 4270 break; 4271 } 4272 } 4273 4274 // Annotate all of the source locations in the region of interest that map to 4275 // a specific cursor. 4276 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens, 4277 CXXUnit, RegionOfInterest); 4278 4279 // Run the worker within a CrashRecoveryContext. 4280 // FIXME: We use a ridiculous stack size here because the data-recursion 4281 // algorithm uses a large stack frame than the non-data recursive version, 4282 // and AnnotationTokensWorker currently transforms the data-recursion 4283 // algorithm back into a traditional recursion by explicitly calling 4284 // VisitChildren(). We will need to remove this explicit recursive call. 4285 llvm::CrashRecoveryContext CRC; 4286 if (!RunSafely(CRC, runAnnotateTokensWorker, &W, 4287 GetSafetyThreadStackSize() * 2)) { 4288 fprintf(stderr, "libclang: crash detected while annotating tokens\n"); 4289 } 4290} 4291} // end: extern "C" 4292 4293//===----------------------------------------------------------------------===// 4294// Operations for querying linkage of a cursor. 4295//===----------------------------------------------------------------------===// 4296 4297extern "C" { 4298CXLinkageKind clang_getCursorLinkage(CXCursor cursor) { 4299 if (!clang_isDeclaration(cursor.kind)) 4300 return CXLinkage_Invalid; 4301 4302 Decl *D = cxcursor::getCursorDecl(cursor); 4303 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D)) 4304 switch (ND->getLinkage()) { 4305 case NoLinkage: return CXLinkage_NoLinkage; 4306 case InternalLinkage: return CXLinkage_Internal; 4307 case UniqueExternalLinkage: return CXLinkage_UniqueExternal; 4308 case ExternalLinkage: return CXLinkage_External; 4309 }; 4310 4311 return CXLinkage_Invalid; 4312} 4313} // end: extern "C" 4314 4315//===----------------------------------------------------------------------===// 4316// Operations for querying language of a cursor. 4317//===----------------------------------------------------------------------===// 4318 4319static CXLanguageKind getDeclLanguage(const Decl *D) { 4320 switch (D->getKind()) { 4321 default: 4322 break; 4323 case Decl::ImplicitParam: 4324 case Decl::ObjCAtDefsField: 4325 case Decl::ObjCCategory: 4326 case Decl::ObjCCategoryImpl: 4327 case Decl::ObjCClass: 4328 case Decl::ObjCCompatibleAlias: 4329 case Decl::ObjCForwardProtocol: 4330 case Decl::ObjCImplementation: 4331 case Decl::ObjCInterface: 4332 case Decl::ObjCIvar: 4333 case Decl::ObjCMethod: 4334 case Decl::ObjCProperty: 4335 case Decl::ObjCPropertyImpl: 4336 case Decl::ObjCProtocol: 4337 return CXLanguage_ObjC; 4338 case Decl::CXXConstructor: 4339 case Decl::CXXConversion: 4340 case Decl::CXXDestructor: 4341 case Decl::CXXMethod: 4342 case Decl::CXXRecord: 4343 case Decl::ClassTemplate: 4344 case Decl::ClassTemplatePartialSpecialization: 4345 case Decl::ClassTemplateSpecialization: 4346 case Decl::Friend: 4347 case Decl::FriendTemplate: 4348 case Decl::FunctionTemplate: 4349 case Decl::LinkageSpec: 4350 case Decl::Namespace: 4351 case Decl::NamespaceAlias: 4352 case Decl::NonTypeTemplateParm: 4353 case Decl::StaticAssert: 4354 case Decl::TemplateTemplateParm: 4355 case Decl::TemplateTypeParm: 4356 case Decl::UnresolvedUsingTypename: 4357 case Decl::UnresolvedUsingValue: 4358 case Decl::Using: 4359 case Decl::UsingDirective: 4360 case Decl::UsingShadow: 4361 return CXLanguage_CPlusPlus; 4362 } 4363 4364 return CXLanguage_C; 4365} 4366 4367extern "C" { 4368 4369enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) { 4370 if (clang_isDeclaration(cursor.kind)) 4371 if (Decl *D = cxcursor::getCursorDecl(cursor)) { 4372 if (D->hasAttr<UnavailableAttr>() || 4373 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())) 4374 return CXAvailability_Available; 4375 4376 if (D->hasAttr<DeprecatedAttr>()) 4377 return CXAvailability_Deprecated; 4378 } 4379 4380 return CXAvailability_Available; 4381} 4382 4383CXLanguageKind clang_getCursorLanguage(CXCursor cursor) { 4384 if (clang_isDeclaration(cursor.kind)) 4385 return getDeclLanguage(cxcursor::getCursorDecl(cursor)); 4386 4387 return CXLanguage_Invalid; 4388} 4389 4390CXCursor clang_getCursorSemanticParent(CXCursor cursor) { 4391 if (clang_isDeclaration(cursor.kind)) { 4392 if (Decl *D = getCursorDecl(cursor)) { 4393 DeclContext *DC = D->getDeclContext(); 4394 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor)); 4395 } 4396 } 4397 4398 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) { 4399 if (Decl *D = getCursorDecl(cursor)) 4400 return MakeCXCursor(D, getCursorASTUnit(cursor)); 4401 } 4402 4403 return clang_getNullCursor(); 4404} 4405 4406CXCursor clang_getCursorLexicalParent(CXCursor cursor) { 4407 if (clang_isDeclaration(cursor.kind)) { 4408 if (Decl *D = getCursorDecl(cursor)) { 4409 DeclContext *DC = D->getLexicalDeclContext(); 4410 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor)); 4411 } 4412 } 4413 4414 // FIXME: Note that we can't easily compute the lexical context of a 4415 // statement or expression, so we return nothing. 4416 return clang_getNullCursor(); 4417} 4418 4419static void CollectOverriddenMethods(DeclContext *Ctx, 4420 ObjCMethodDecl *Method, 4421 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) { 4422 if (!Ctx) 4423 return; 4424 4425 // If we have a class or category implementation, jump straight to the 4426 // interface. 4427 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx)) 4428 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods); 4429 4430 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx); 4431 if (!Container) 4432 return; 4433 4434 // Check whether we have a matching method at this level. 4435 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(), 4436 Method->isInstanceMethod())) 4437 if (Method != Overridden) { 4438 // We found an override at this level; there is no need to look 4439 // into other protocols or categories. 4440 Methods.push_back(Overridden); 4441 return; 4442 } 4443 4444 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 4445 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(), 4446 PEnd = Protocol->protocol_end(); 4447 P != PEnd; ++P) 4448 CollectOverriddenMethods(*P, Method, Methods); 4449 } 4450 4451 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) { 4452 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(), 4453 PEnd = Category->protocol_end(); 4454 P != PEnd; ++P) 4455 CollectOverriddenMethods(*P, Method, Methods); 4456 } 4457 4458 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) { 4459 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(), 4460 PEnd = Interface->protocol_end(); 4461 P != PEnd; ++P) 4462 CollectOverriddenMethods(*P, Method, Methods); 4463 4464 for (ObjCCategoryDecl *Category = Interface->getCategoryList(); 4465 Category; Category = Category->getNextClassCategory()) 4466 CollectOverriddenMethods(Category, Method, Methods); 4467 4468 // We only look into the superclass if we haven't found anything yet. 4469 if (Methods.empty()) 4470 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) 4471 return CollectOverriddenMethods(Super, Method, Methods); 4472 } 4473} 4474 4475void clang_getOverriddenCursors(CXCursor cursor, 4476 CXCursor **overridden, 4477 unsigned *num_overridden) { 4478 if (overridden) 4479 *overridden = 0; 4480 if (num_overridden) 4481 *num_overridden = 0; 4482 if (!overridden || !num_overridden) 4483 return; 4484 4485 if (!clang_isDeclaration(cursor.kind)) 4486 return; 4487 4488 Decl *D = getCursorDecl(cursor); 4489 if (!D) 4490 return; 4491 4492 // Handle C++ member functions. 4493 ASTUnit *CXXUnit = getCursorASTUnit(cursor); 4494 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) { 4495 *num_overridden = CXXMethod->size_overridden_methods(); 4496 if (!*num_overridden) 4497 return; 4498 4499 *overridden = new CXCursor [*num_overridden]; 4500 unsigned I = 0; 4501 for (CXXMethodDecl::method_iterator 4502 M = CXXMethod->begin_overridden_methods(), 4503 MEnd = CXXMethod->end_overridden_methods(); 4504 M != MEnd; (void)++M, ++I) 4505 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit); 4506 return; 4507 } 4508 4509 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D); 4510 if (!Method) 4511 return; 4512 4513 // Handle Objective-C methods. 4514 llvm::SmallVector<ObjCMethodDecl *, 4> Methods; 4515 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods); 4516 4517 if (Methods.empty()) 4518 return; 4519 4520 *num_overridden = Methods.size(); 4521 *overridden = new CXCursor [Methods.size()]; 4522 for (unsigned I = 0, N = Methods.size(); I != N; ++I) 4523 (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit); 4524} 4525 4526void clang_disposeOverriddenCursors(CXCursor *overridden) { 4527 delete [] overridden; 4528} 4529 4530CXFile clang_getIncludedFile(CXCursor cursor) { 4531 if (cursor.kind != CXCursor_InclusionDirective) 4532 return 0; 4533 4534 InclusionDirective *ID = getCursorInclusionDirective(cursor); 4535 return (void *)ID->getFile(); 4536} 4537 4538} // end: extern "C" 4539 4540 4541//===----------------------------------------------------------------------===// 4542// C++ AST instrospection. 4543//===----------------------------------------------------------------------===// 4544 4545extern "C" { 4546unsigned clang_CXXMethod_isStatic(CXCursor C) { 4547 if (!clang_isDeclaration(C.kind)) 4548 return 0; 4549 4550 CXXMethodDecl *Method = 0; 4551 Decl *D = cxcursor::getCursorDecl(C); 4552 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D)) 4553 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl()); 4554 else 4555 Method = dyn_cast_or_null<CXXMethodDecl>(D); 4556 return (Method && Method->isStatic()) ? 1 : 0; 4557} 4558 4559} // end: extern "C" 4560 4561//===----------------------------------------------------------------------===// 4562// Attribute introspection. 4563//===----------------------------------------------------------------------===// 4564 4565extern "C" { 4566CXType clang_getIBOutletCollectionType(CXCursor C) { 4567 if (C.kind != CXCursor_IBOutletCollectionAttr) 4568 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C)); 4569 4570 IBOutletCollectionAttr *A = 4571 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C)); 4572 4573 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C)); 4574} 4575} // end: extern "C" 4576 4577//===----------------------------------------------------------------------===// 4578// CXString Operations. 4579//===----------------------------------------------------------------------===// 4580 4581extern "C" { 4582const char *clang_getCString(CXString string) { 4583 return string.Spelling; 4584} 4585 4586void clang_disposeString(CXString string) { 4587 if (string.MustFreeString && string.Spelling) 4588 free((void*)string.Spelling); 4589} 4590 4591} // end: extern "C" 4592 4593namespace clang { namespace cxstring { 4594CXString createCXString(const char *String, bool DupString){ 4595 CXString Str; 4596 if (DupString) { 4597 Str.Spelling = strdup(String); 4598 Str.MustFreeString = 1; 4599 } else { 4600 Str.Spelling = String; 4601 Str.MustFreeString = 0; 4602 } 4603 return Str; 4604} 4605 4606CXString createCXString(llvm::StringRef String, bool DupString) { 4607 CXString Result; 4608 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) { 4609 char *Spelling = (char *)malloc(String.size() + 1); 4610 memmove(Spelling, String.data(), String.size()); 4611 Spelling[String.size()] = 0; 4612 Result.Spelling = Spelling; 4613 Result.MustFreeString = 1; 4614 } else { 4615 Result.Spelling = String.data(); 4616 Result.MustFreeString = 0; 4617 } 4618 return Result; 4619} 4620}} 4621 4622//===----------------------------------------------------------------------===// 4623// Misc. utility functions. 4624//===----------------------------------------------------------------------===// 4625 4626/// Default to using an 8 MB stack size on "safety" threads. 4627static unsigned SafetyStackThreadSize = 8 << 20; 4628 4629namespace clang { 4630 4631bool RunSafely(llvm::CrashRecoveryContext &CRC, 4632 void (*Fn)(void*), void *UserData, 4633 unsigned Size) { 4634 if (!Size) 4635 Size = GetSafetyThreadStackSize(); 4636 if (Size) 4637 return CRC.RunSafelyOnThread(Fn, UserData, Size); 4638 return CRC.RunSafely(Fn, UserData); 4639} 4640 4641unsigned GetSafetyThreadStackSize() { 4642 return SafetyStackThreadSize; 4643} 4644 4645void SetSafetyThreadStackSize(unsigned Value) { 4646 SafetyStackThreadSize = Value; 4647} 4648 4649} 4650 4651extern "C" { 4652 4653CXString clang_getClangVersion() { 4654 return createCXString(getClangFullVersion()); 4655} 4656 4657} // end: extern "C" 4658