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