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