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