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