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