blob: df1937a90bfc44c6fd96a3c18c80c00955598fcf [file] [log] [blame]
Ted Kremenekd2fa5662009-08-26 22:36:44 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00007//
Ted Kremenekd2fa5662009-08-26 22:36:44 +00008//===----------------------------------------------------------------------===//
9//
Ted Kremenekab188932010-01-05 19:32:54 +000010// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
Ted Kremenekd2fa5662009-08-26 22:36:44 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenekab188932010-01-05 19:32:54 +000015#include "CIndexer.h"
Ted Kremenek16c440a2010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremenek95f33552010-08-26 01:42:22 +000017#include "CXType.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000018#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000019#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000020
Ted Kremenek04bb7162010-01-22 22:44:15 +000021#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000022
Steve Naroff50398192009-08-28 15:28:48 +000023#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000024#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000025#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000026#include "clang/Basic/Diagnostic.h"
27#include "clang/Frontend/ASTUnit.h"
28#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000029#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000030#include "clang/Lex/Lexer.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000031#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000032#include "clang/Lex/Preprocessor.h"
Douglas Gregora67e03f2010-09-09 21:42:20 +000033#include "llvm/ADT/STLExtras.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000034#include "llvm/ADT/Optional.h"
35#include "clang/Analysis/Support/SaveAndRestore.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000036#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000037#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000038#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000039#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000040#include "llvm/Support/Timer.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000041#include "llvm/System/Mutex.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000042#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000043#include "llvm/System/Signals.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000044#include "llvm/System/Threading.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000045
Benjamin Kramerc2a98162010-03-13 21:22:49 +000046// Needed to define L_TMPNAM on some systems.
47#include <cstdio>
48
Steve Naroff50398192009-08-28 15:28:48 +000049using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000050using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000051using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000052
Douglas Gregor33e9abd2010-01-22 19:49:59 +000053/// \brief The result of comparing two source ranges.
54enum RangeComparisonResult {
55 /// \brief Either the ranges overlap or one of the ranges is invalid.
56 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000057
Douglas Gregor33e9abd2010-01-22 19:49:59 +000058 /// \brief The first range ends before the second range starts.
59 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000060
Douglas Gregor33e9abd2010-01-22 19:49:59 +000061 /// \brief The first range starts after the second range ends.
62 RangeAfter
63};
64
Ted Kremenekf0e23e82010-02-17 00:41:40 +000065/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000066/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000067static RangeComparisonResult RangeCompare(SourceManager &SM,
68 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000069 SourceRange R2) {
70 assert(R1.isValid() && "First range is invalid?");
71 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000072 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000073 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000074 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000075 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000076 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000077 return RangeAfter;
78 return RangeOverlap;
79}
80
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000081/// \brief Determine if a source location falls within, before, or after a
82/// a given source range.
83static RangeComparisonResult LocationCompare(SourceManager &SM,
84 SourceLocation L, SourceRange R) {
85 assert(R.isValid() && "First range is invalid?");
86 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000087 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000088 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000089 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
90 return RangeBefore;
91 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
92 return RangeAfter;
93 return RangeOverlap;
94}
95
Daniel Dunbar76dd3c22010-02-14 01:47:29 +000096/// \brief Translate a Clang source range into a CIndex source range.
97///
98/// Clang internally represents ranges where the end location points to the
99/// start of the token at the end. However, for external clients it is more
100/// useful to have a CXSourceRange be a proper half-open interval. This routine
101/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000102CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000103 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000104 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000105 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000106 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000107 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000108 if (EndLoc.isValid() && EndLoc.isMacroID())
109 EndLoc = SM.getSpellingLoc(EndLoc);
Chris Lattner0a76aae2010-06-18 22:45:06 +0000110 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000111 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000112 EndLoc = EndLoc.getFileLocWithOffset(Length);
113 }
114
115 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
116 R.getBegin().getRawEncoding(),
117 EndLoc.getRawEncoding() };
118 return Result;
119}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000120
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000121//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000122// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000123//===----------------------------------------------------------------------===//
124
Steve Naroff89922f82009-08-31 00:59:03 +0000125namespace {
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000126
127class VisitorJob {
128public:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000129 enum Kind { DeclVisitKind, StmtVisitKind, MemberExprPartsKind,
Ted Kremenek60458782010-11-12 21:34:16 +0000130 TypeLocVisitKind, OverloadExprPartsKind };
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000131protected:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000132 void *dataA;
133 void *dataB;
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000134 CXCursor parent;
135 Kind K;
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000136 VisitorJob(CXCursor C, Kind k, void *d1, void *d2 = 0)
137 : dataA(d1), dataB(d2), parent(C), K(k) {}
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000138public:
139 Kind getKind() const { return K; }
140 const CXCursor &getParent() const { return parent; }
141 static bool classof(VisitorJob *VJ) { return true; }
142};
143
144typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList;
145
146#define DEF_JOB(NAME, DATA, KIND)\
147class NAME : public VisitorJob {\
148public:\
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000149 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000150 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000151 DATA *get() const { return static_cast<DATA*>(dataA); }\
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000152};
153
Ted Kremenekf1107452010-11-12 18:26:56 +0000154DEF_JOB(DeclVisit, Decl, DeclVisitKind)
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000155DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
156DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
Ted Kremenek60458782010-11-12 21:34:16 +0000157DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000158#undef DEF_JOB
159
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000160class TypeLocVisit : public VisitorJob {
161public:
162 TypeLocVisit(TypeLoc tl, CXCursor parent) :
163 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
164 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
165
166 static bool classof(const VisitorJob *VJ) {
167 return VJ->getKind() == TypeLocVisitKind;
168 }
169
170 TypeLoc get() {
171 QualType T = QualType::getFromOpaquePtr(dataA);
172 return TypeLoc(T, dataB);
173 }
174};
175
Ted Kremenekc70ebba2010-11-12 18:26:58 +0000176static inline void WLAddStmt(VisitorWorkList &WL, CXCursor Parent, Stmt *S) {
177 if (S)
178 WL.push_back(StmtVisit(S, Parent));
179}
180static inline void WLAddDecl(VisitorWorkList &WL, CXCursor Parent, Decl *D) {
181 if (D)
182 WL.push_back(DeclVisit(D, Parent));
183}
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000184static inline void WLAddTypeLoc(VisitorWorkList &WL, CXCursor Parent,
185 TypeSourceInfo *TI) {
186 if (TI)
187 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
188}
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000189
Douglas Gregorb1373d02010-01-20 20:59:29 +0000190// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000191class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000192 public TypeLocVisitor<CursorVisitor, bool>,
193 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000194{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000195 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000196 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000197
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000198 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000199 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000200
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000201 /// \brief The declaration that serves at the parent of any statement or
202 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000203 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000204
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000205 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000206 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000207
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000208 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000209 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000210
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000211 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
212 // to the visitor. Declarations with a PCH level greater than this value will
213 // be suppressed.
214 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000215
216 /// \brief When valid, a source range to which the cursor should restrict
217 /// its search.
218 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000219
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000220 // FIXME: Eventually remove. This part of a hack to support proper
221 // iteration over all Decls contained lexically within an ObjC container.
222 DeclContext::decl_iterator *DI_current;
223 DeclContext::decl_iterator DE_current;
224
Douglas Gregorb1373d02010-01-20 20:59:29 +0000225 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000226 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000227 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000228
229 /// \brief Determine whether this particular source range comes before, comes
230 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000231 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000232 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000233 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
234
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000235 class SetParentRAII {
236 CXCursor &Parent;
237 Decl *&StmtParent;
238 CXCursor OldParent;
239
240 public:
241 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
242 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
243 {
244 Parent = NewParent;
245 if (clang_isDeclaration(Parent.kind))
246 StmtParent = getCursorDecl(Parent);
247 }
248
249 ~SetParentRAII() {
250 Parent = OldParent;
251 if (clang_isDeclaration(Parent.kind))
252 StmtParent = getCursorDecl(Parent);
253 }
254 };
255
Steve Naroff89922f82009-08-31 00:59:03 +0000256public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000257 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
258 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000259 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000260 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000261 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
262 DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000263 {
264 Parent.kind = CXCursor_NoDeclFound;
265 Parent.data[0] = 0;
266 Parent.data[1] = 0;
267 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000268 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000269 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000270
Ted Kremenekab979612010-11-11 08:05:23 +0000271 ASTUnit *getASTUnit() const { return TU; }
272
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000273 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000274
275 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
276 getPreprocessedEntities();
277
Douglas Gregorb1373d02010-01-20 20:59:29 +0000278 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000279
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000280 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000281 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000282 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000283 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000284 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000285 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000286 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
287 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000288 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000289 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000290 bool VisitClassTemplatePartialSpecializationDecl(
291 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000292 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000293 bool VisitEnumConstantDecl(EnumConstantDecl *D);
294 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
295 bool VisitFunctionDecl(FunctionDecl *ND);
296 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000297 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000298 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000299 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000300 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000301 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000302 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
303 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
304 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
305 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000306 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000307 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
308 bool VisitObjCImplDecl(ObjCImplDecl *D);
309 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
310 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000311 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
312 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
313 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000314 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000315 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000316 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000317 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000318 bool VisitUsingDecl(UsingDecl *D);
319 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
320 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000321
Douglas Gregor01829d32010-08-31 14:41:23 +0000322 // Name visitor
323 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000324 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000325
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000326 // Template visitors
327 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000328 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000329 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
330
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000331 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000332 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000333 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000334 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000335 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
336 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000337 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000338 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000339 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000340 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
341 bool VisitPointerTypeLoc(PointerTypeLoc TL);
342 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
343 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
344 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
345 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000346 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000347 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000348 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000349 // FIXME: Implement visitors here when the unimplemented TypeLocs get
350 // implemented
351 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
352 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000353
Douglas Gregora59e3902010-01-21 23:27:09 +0000354 // Statement visitors
355 bool VisitStmt(Stmt *S);
356 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregor36897b02010-09-10 00:22:18 +0000357 bool VisitGotoStmt(GotoStmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000358
Douglas Gregor336fd812010-01-23 00:40:08 +0000359 // Expression visitors
Douglas Gregor8947a752010-09-02 20:35:02 +0000360 bool VisitDeclRefExpr(DeclRefExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000361 bool VisitBlockExpr(BlockExpr *B);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000362 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000363 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000364 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000365 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor36897b02010-09-10 00:22:18 +0000366 bool VisitAddrLabelExpr(AddrLabelExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000367 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
368 bool VisitVAArgExpr(VAArgExpr *E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +0000369 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
Douglas Gregor94802292010-09-02 21:20:16 +0000370 bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000371 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
Douglas Gregorda135b12010-09-02 21:38:13 +0000372 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { return false; }
Douglas Gregorab6677e2010-09-08 00:15:04 +0000373 bool VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
374 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000375 bool VisitCXXNewExpr(CXXNewExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000376 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000377 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000378 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000379 bool VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000380 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000381
382#define DATA_RECURSIVE_VISIT(NAME)\
383bool Visit##NAME(NAME *S) { return VisitDataRecursive(S); }
384 DATA_RECURSIVE_VISIT(BinaryOperator)
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000385 DATA_RECURSIVE_VISIT(CompoundLiteralExpr)
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000386 DATA_RECURSIVE_VISIT(CXXMemberCallExpr)
Ted Kremenek8c269ac2010-11-11 23:11:43 +0000387 DATA_RECURSIVE_VISIT(CXXOperatorCallExpr)
Ted Kremenekbb677132010-11-12 18:27:04 +0000388 DATA_RECURSIVE_VISIT(DoStmt)
Ted Kremenekc70ebba2010-11-12 18:26:58 +0000389 DATA_RECURSIVE_VISIT(IfStmt)
Ted Kremeneka6b70432010-11-12 21:34:09 +0000390 DATA_RECURSIVE_VISIT(InitListExpr)
Ted Kremenekbb677132010-11-12 18:27:04 +0000391 DATA_RECURSIVE_VISIT(ForStmt)
Ted Kremenekc70ebba2010-11-12 18:26:58 +0000392 DATA_RECURSIVE_VISIT(MemberExpr)
Ted Kremenekc373e3c2010-11-12 22:24:55 +0000393 DATA_RECURSIVE_VISIT(ObjCMessageExpr)
Ted Kremenek60458782010-11-12 21:34:16 +0000394 DATA_RECURSIVE_VISIT(OverloadExpr)
Ted Kremenekf1107452010-11-12 18:26:56 +0000395 DATA_RECURSIVE_VISIT(SwitchStmt)
Ted Kremenekbb677132010-11-12 18:27:04 +0000396 DATA_RECURSIVE_VISIT(WhileStmt)
Ted Kremenek60458782010-11-12 21:34:16 +0000397 DATA_RECURSIVE_VISIT(UnresolvedMemberExpr)
Ted Kremeneka6b70432010-11-12 21:34:09 +0000398
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000399 // Data-recursive visitor functions.
400 bool IsInRegionOfInterest(CXCursor C);
401 bool RunVisitorWorkList(VisitorWorkList &WL);
402 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
403 bool VisitDataRecursive(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000404};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000405
Ted Kremenekab188932010-01-05 19:32:54 +0000406} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000407
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000408static SourceRange getRawCursorExtent(CXCursor C);
409
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000410RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000411 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
412}
413
Douglas Gregorb1373d02010-01-20 20:59:29 +0000414/// \brief Visit the given cursor and, if requested by the visitor,
415/// its children.
416///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000417/// \param Cursor the cursor to visit.
418///
419/// \param CheckRegionOfInterest if true, then the caller already checked that
420/// this cursor is within the region of interest.
421///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000422/// \returns true if the visitation should be aborted, false if it
423/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000424bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000425 if (clang_isInvalid(Cursor.kind))
426 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000427
Douglas Gregorb1373d02010-01-20 20:59:29 +0000428 if (clang_isDeclaration(Cursor.kind)) {
429 Decl *D = getCursorDecl(Cursor);
430 assert(D && "Invalid declaration cursor");
431 if (D->getPCHLevel() > MaxPCHLevel)
432 return false;
433
434 if (D->isImplicit())
435 return false;
436 }
437
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000438 // If we have a range of interest, and this cursor doesn't intersect with it,
439 // we're done.
440 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000441 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000442 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000443 return false;
444 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000445
Douglas Gregorb1373d02010-01-20 20:59:29 +0000446 switch (Visitor(Cursor, Parent, ClientData)) {
447 case CXChildVisit_Break:
448 return true;
449
450 case CXChildVisit_Continue:
451 return false;
452
453 case CXChildVisit_Recurse:
454 return VisitChildren(Cursor);
455 }
456
Douglas Gregorfd643772010-01-25 16:45:46 +0000457 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000458}
459
Douglas Gregor788f5a12010-03-20 00:41:21 +0000460std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
461CursorVisitor::getPreprocessedEntities() {
462 PreprocessingRecord &PPRec
463 = *TU->getPreprocessor().getPreprocessingRecord();
464
465 bool OnlyLocalDecls
466 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
467
468 // There is no region of interest; we have to walk everything.
469 if (RegionOfInterest.isInvalid())
470 return std::make_pair(PPRec.begin(OnlyLocalDecls),
471 PPRec.end(OnlyLocalDecls));
472
473 // Find the file in which the region of interest lands.
474 SourceManager &SM = TU->getSourceManager();
475 std::pair<FileID, unsigned> Begin
476 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
477 std::pair<FileID, unsigned> End
478 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
479
480 // The region of interest spans files; we have to walk everything.
481 if (Begin.first != End.first)
482 return std::make_pair(PPRec.begin(OnlyLocalDecls),
483 PPRec.end(OnlyLocalDecls));
484
485 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
486 = TU->getPreprocessedEntitiesByFile();
487 if (ByFileMap.empty()) {
488 // Build the mapping from files to sets of preprocessed entities.
489 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
490 EEnd = PPRec.end(OnlyLocalDecls);
491 E != EEnd; ++E) {
492 std::pair<FileID, unsigned> P
493 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
494 ByFileMap[P.first].push_back(*E);
495 }
496 }
497
498 return std::make_pair(ByFileMap[Begin.first].begin(),
499 ByFileMap[Begin.first].end());
500}
501
Douglas Gregorb1373d02010-01-20 20:59:29 +0000502/// \brief Visit the children of the given cursor.
503///
504/// \returns true if the visitation should be aborted, false if it
505/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000506bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000507 if (clang_isReference(Cursor.kind)) {
508 // By definition, references have no children.
509 return false;
510 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000511
512 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000513 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000514 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000515
Douglas Gregorb1373d02010-01-20 20:59:29 +0000516 if (clang_isDeclaration(Cursor.kind)) {
517 Decl *D = getCursorDecl(Cursor);
518 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000519 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000520 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000521
Douglas Gregora59e3902010-01-21 23:27:09 +0000522 if (clang_isStatement(Cursor.kind))
523 return Visit(getCursorStmt(Cursor));
524 if (clang_isExpression(Cursor.kind))
525 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000526
Douglas Gregorb1373d02010-01-20 20:59:29 +0000527 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000528 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000529 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
530 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000531 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
532 TLEnd = CXXUnit->top_level_end();
533 TL != TLEnd; ++TL) {
534 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000535 return true;
536 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000537 } else if (VisitDeclContext(
538 CXXUnit->getASTContext().getTranslationUnitDecl()))
539 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000540
Douglas Gregor0396f462010-03-19 05:22:59 +0000541 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000542 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000543 // FIXME: Once we have the ability to deserialize a preprocessing record,
544 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000545 PreprocessingRecord::iterator E, EEnd;
546 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000547 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
548 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
549 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000550
Douglas Gregor0396f462010-03-19 05:22:59 +0000551 continue;
552 }
553
554 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
555 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
556 return true;
557
558 continue;
559 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000560
561 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
562 if (Visit(MakeInclusionDirectiveCursor(ID, CXXUnit)))
563 return true;
564
565 continue;
566 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000567 }
568 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000569 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000570 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000571
Douglas Gregorb1373d02010-01-20 20:59:29 +0000572 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000573 return false;
574}
575
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000576bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000577 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
578 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000579
Ted Kremenek664cffd2010-07-22 11:30:19 +0000580 if (Stmt *Body = B->getBody())
581 return Visit(MakeCXCursor(Body, StmtParent, TU));
582
583 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000584}
585
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000586llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
587 if (RegionOfInterest.isValid()) {
588 SourceRange Range = getRawCursorExtent(Cursor);
589 if (Range.isInvalid())
590 return llvm::Optional<bool>();
Ted Kremenek09dfa372010-02-18 05:46:33 +0000591
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000592 switch (CompareRegionOfInterest(Range)) {
593 case RangeBefore:
594 // This declaration comes before the region of interest; skip it.
595 return llvm::Optional<bool>();
596
597 case RangeAfter:
598 // This declaration comes after the region of interest; we're done.
599 return false;
600
601 case RangeOverlap:
602 // This declaration overlaps the region of interest; visit it.
603 break;
604 }
605 }
606 return true;
607}
608
609bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
610 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
611
612 // FIXME: Eventually remove. This part of a hack to support proper
613 // iteration over all Decls contained lexically within an ObjC container.
614 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
615 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
616
617 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000618 Decl *D = *I;
619 if (D->getLexicalDeclContext() != DC)
620 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000621 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000622 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
623 if (!V.hasValue())
624 continue;
625 if (!V.getValue())
626 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000627 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000628 return true;
629 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000630 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000631}
632
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000633bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
634 llvm_unreachable("Translation units are visited directly by Visit()");
635 return false;
636}
637
638bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
639 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
640 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000641
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000642 return false;
643}
644
645bool CursorVisitor::VisitTagDecl(TagDecl *D) {
646 return VisitDeclContext(D);
647}
648
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000649bool CursorVisitor::VisitClassTemplateSpecializationDecl(
650 ClassTemplateSpecializationDecl *D) {
651 bool ShouldVisitBody = false;
652 switch (D->getSpecializationKind()) {
653 case TSK_Undeclared:
654 case TSK_ImplicitInstantiation:
655 // Nothing to visit
656 return false;
657
658 case TSK_ExplicitInstantiationDeclaration:
659 case TSK_ExplicitInstantiationDefinition:
660 break;
661
662 case TSK_ExplicitSpecialization:
663 ShouldVisitBody = true;
664 break;
665 }
666
667 // Visit the template arguments used in the specialization.
668 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
669 TypeLoc TL = SpecType->getTypeLoc();
670 if (TemplateSpecializationTypeLoc *TSTLoc
671 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
672 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
673 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
674 return true;
675 }
676 }
677
678 if (ShouldVisitBody && VisitCXXRecordDecl(D))
679 return true;
680
681 return false;
682}
683
Douglas Gregor74dbe642010-08-31 19:31:58 +0000684bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
685 ClassTemplatePartialSpecializationDecl *D) {
686 // FIXME: Visit the "outer" template parameter lists on the TagDecl
687 // before visiting these template parameters.
688 if (VisitTemplateParameters(D->getTemplateParameters()))
689 return true;
690
691 // Visit the partial specialization arguments.
692 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
693 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
694 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
695 return true;
696
697 return VisitCXXRecordDecl(D);
698}
699
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000700bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000701 // Visit the default argument.
702 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
703 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
704 if (Visit(DefArg->getTypeLoc()))
705 return true;
706
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000707 return false;
708}
709
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000710bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
711 if (Expr *Init = D->getInitExpr())
712 return Visit(MakeCXCursor(Init, StmtParent, TU));
713 return false;
714}
715
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000716bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
717 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
718 if (Visit(TSInfo->getTypeLoc()))
719 return true;
720
721 return false;
722}
723
Douglas Gregora67e03f2010-09-09 21:42:20 +0000724/// \brief Compare two base or member initializers based on their source order.
725static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
726 CXXBaseOrMemberInitializer const * const *X
727 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
728 CXXBaseOrMemberInitializer const * const *Y
729 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
730
731 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
732 return -1;
733 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
734 return 1;
735 else
736 return 0;
737}
738
Douglas Gregorb1373d02010-01-20 20:59:29 +0000739bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000740 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
741 // Visit the function declaration's syntactic components in the order
742 // written. This requires a bit of work.
743 TypeLoc TL = TSInfo->getTypeLoc();
744 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
745
746 // If we have a function declared directly (without the use of a typedef),
747 // visit just the return type. Otherwise, just visit the function's type
748 // now.
749 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
750 (!FTL && Visit(TL)))
751 return true;
752
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000753 // Visit the nested-name-specifier, if present.
754 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
755 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
756 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000757
758 // Visit the declaration name.
759 if (VisitDeclarationNameInfo(ND->getNameInfo()))
760 return true;
761
762 // FIXME: Visit explicitly-specified template arguments!
763
764 // Visit the function parameters, if we have a function type.
765 if (FTL && VisitFunctionTypeLoc(*FTL, true))
766 return true;
767
768 // FIXME: Attributes?
769 }
770
Douglas Gregora67e03f2010-09-09 21:42:20 +0000771 if (ND->isThisDeclarationADefinition()) {
772 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
773 // Find the initializers that were written in the source.
774 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
775 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
776 IEnd = Constructor->init_end();
777 I != IEnd; ++I) {
778 if (!(*I)->isWritten())
779 continue;
780
781 WrittenInits.push_back(*I);
782 }
783
784 // Sort the initializers in source order
785 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
786 &CompareCXXBaseOrMemberInitializers);
787
788 // Visit the initializers in source order
789 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
790 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
791 if (Init->isMemberInitializer()) {
792 if (Visit(MakeCursorMemberRef(Init->getMember(),
793 Init->getMemberLocation(), TU)))
794 return true;
795 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
796 if (Visit(BaseInfo->getTypeLoc()))
797 return true;
798 }
799
800 // Visit the initializer value.
801 if (Expr *Initializer = Init->getInit())
802 if (Visit(MakeCXCursor(Initializer, ND, TU)))
803 return true;
804 }
805 }
806
807 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
808 return true;
809 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000810
Douglas Gregorb1373d02010-01-20 20:59:29 +0000811 return false;
812}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000813
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000814bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
815 if (VisitDeclaratorDecl(D))
816 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000817
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000818 if (Expr *BitWidth = D->getBitWidth())
819 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000820
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000821 return false;
822}
823
824bool CursorVisitor::VisitVarDecl(VarDecl *D) {
825 if (VisitDeclaratorDecl(D))
826 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000827
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000828 if (Expr *Init = D->getInit())
829 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000830
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000831 return false;
832}
833
Douglas Gregor84b51d72010-09-01 20:16:53 +0000834bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
835 if (VisitDeclaratorDecl(D))
836 return true;
837
838 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
839 if (Expr *DefArg = D->getDefaultArgument())
840 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
841
842 return false;
843}
844
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000845bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
846 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
847 // before visiting these template parameters.
848 if (VisitTemplateParameters(D->getTemplateParameters()))
849 return true;
850
851 return VisitFunctionDecl(D->getTemplatedDecl());
852}
853
Douglas Gregor39d6f072010-08-31 19:02:00 +0000854bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
855 // FIXME: Visit the "outer" template parameter lists on the TagDecl
856 // before visiting these template parameters.
857 if (VisitTemplateParameters(D->getTemplateParameters()))
858 return true;
859
860 return VisitCXXRecordDecl(D->getTemplatedDecl());
861}
862
Douglas Gregor84b51d72010-09-01 20:16:53 +0000863bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
864 if (VisitTemplateParameters(D->getTemplateParameters()))
865 return true;
866
867 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
868 VisitTemplateArgumentLoc(D->getDefaultArgument()))
869 return true;
870
871 return false;
872}
873
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000874bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000875 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
876 if (Visit(TSInfo->getTypeLoc()))
877 return true;
878
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000879 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000880 PEnd = ND->param_end();
881 P != PEnd; ++P) {
882 if (Visit(MakeCXCursor(*P, TU)))
883 return true;
884 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000885
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000886 if (ND->isThisDeclarationADefinition() &&
887 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
888 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000889
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000890 return false;
891}
892
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000893namespace {
894 struct ContainerDeclsSort {
895 SourceManager &SM;
896 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
897 bool operator()(Decl *A, Decl *B) {
898 SourceLocation L_A = A->getLocStart();
899 SourceLocation L_B = B->getLocStart();
900 assert(L_A.isValid() && L_B.isValid());
901 return SM.isBeforeInTranslationUnit(L_A, L_B);
902 }
903 };
904}
905
Douglas Gregora59e3902010-01-21 23:27:09 +0000906bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000907 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
908 // an @implementation can lexically contain Decls that are not properly
909 // nested in the AST. When we identify such cases, we need to retrofit
910 // this nesting here.
911 if (!DI_current)
912 return VisitDeclContext(D);
913
914 // Scan the Decls that immediately come after the container
915 // in the current DeclContext. If any fall within the
916 // container's lexical region, stash them into a vector
917 // for later processing.
918 llvm::SmallVector<Decl *, 24> DeclsInContainer;
919 SourceLocation EndLoc = D->getSourceRange().getEnd();
920 SourceManager &SM = TU->getSourceManager();
921 if (EndLoc.isValid()) {
922 DeclContext::decl_iterator next = *DI_current;
923 while (++next != DE_current) {
924 Decl *D_next = *next;
925 if (!D_next)
926 break;
927 SourceLocation L = D_next->getLocStart();
928 if (!L.isValid())
929 break;
930 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
931 *DI_current = next;
932 DeclsInContainer.push_back(D_next);
933 continue;
934 }
935 break;
936 }
937 }
938
939 // The common case.
940 if (DeclsInContainer.empty())
941 return VisitDeclContext(D);
942
943 // Get all the Decls in the DeclContext, and sort them with the
944 // additional ones we've collected. Then visit them.
945 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
946 I!=E; ++I) {
947 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000948 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
949 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000950 continue;
951 DeclsInContainer.push_back(subDecl);
952 }
953
954 // Now sort the Decls so that they appear in lexical order.
955 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
956 ContainerDeclsSort(SM));
957
958 // Now visit the decls.
959 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
960 E = DeclsInContainer.end(); I != E; ++I) {
961 CXCursor Cursor = MakeCXCursor(*I, TU);
962 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
963 if (!V.hasValue())
964 continue;
965 if (!V.getValue())
966 return false;
967 if (Visit(Cursor, true))
968 return true;
969 }
970 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000971}
972
Douglas Gregorb1373d02010-01-20 20:59:29 +0000973bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000974 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
975 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000976 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000977
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000978 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
979 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
980 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000981 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000982 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000983
Douglas Gregora59e3902010-01-21 23:27:09 +0000984 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000985}
986
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000987bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
988 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
989 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
990 E = PID->protocol_end(); I != E; ++I, ++PL)
991 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
992 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000993
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000994 return VisitObjCContainerDecl(PID);
995}
996
Ted Kremenek23173d72010-05-18 21:09:07 +0000997bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000998 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000999 return true;
1000
Ted Kremenek23173d72010-05-18 21:09:07 +00001001 // FIXME: This implements a workaround with @property declarations also being
1002 // installed in the DeclContext for the @interface. Eventually this code
1003 // should be removed.
1004 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1005 if (!CDecl || !CDecl->IsClassExtension())
1006 return false;
1007
1008 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1009 if (!ID)
1010 return false;
1011
1012 IdentifierInfo *PropertyId = PD->getIdentifier();
1013 ObjCPropertyDecl *prevDecl =
1014 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
1015
1016 if (!prevDecl)
1017 return false;
1018
1019 // Visit synthesized methods since they will be skipped when visiting
1020 // the @interface.
1021 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001022 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +00001023 if (Visit(MakeCXCursor(MD, TU)))
1024 return true;
1025
1026 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001027 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +00001028 if (Visit(MakeCXCursor(MD, TU)))
1029 return true;
1030
1031 return false;
1032}
1033
Douglas Gregorb1373d02010-01-20 20:59:29 +00001034bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001035 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001036 if (D->getSuperClass() &&
1037 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001038 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001039 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001040 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001041
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001042 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1043 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1044 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001045 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001046 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001047
Douglas Gregora59e3902010-01-21 23:27:09 +00001048 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001049}
1050
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001051bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1052 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001053}
1054
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001055bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001056 // 'ID' could be null when dealing with invalid code.
1057 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1058 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1059 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001060
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001061 return VisitObjCImplDecl(D);
1062}
1063
1064bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1065#if 0
1066 // Issue callbacks for super class.
1067 // FIXME: No source location information!
1068 if (D->getSuperClass() &&
1069 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001070 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001071 TU)))
1072 return true;
1073#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001074
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001075 return VisitObjCImplDecl(D);
1076}
1077
1078bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1079 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1080 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1081 E = D->protocol_end();
1082 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001083 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001084 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001085
1086 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001087}
1088
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001089bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1090 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1091 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1092 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001093
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001094 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001095}
1096
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001097bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1098 return VisitDeclContext(D);
1099}
1100
Douglas Gregor69319002010-08-31 23:48:11 +00001101bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001102 // Visit nested-name-specifier.
1103 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1104 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1105 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001106
1107 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1108 D->getTargetNameLoc(), TU));
1109}
1110
Douglas Gregor7e242562010-09-01 19:52:22 +00001111bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001112 // Visit nested-name-specifier.
1113 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1114 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1115 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001116
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001117 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1118 return true;
1119
Douglas Gregor7e242562010-09-01 19:52:22 +00001120 return VisitDeclarationNameInfo(D->getNameInfo());
1121}
1122
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001123bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001124 // Visit nested-name-specifier.
1125 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1126 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1127 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001128
1129 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1130 D->getIdentLocation(), TU));
1131}
1132
Douglas Gregor7e242562010-09-01 19:52:22 +00001133bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001134 // Visit nested-name-specifier.
1135 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1136 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1137 return true;
1138
Douglas Gregor7e242562010-09-01 19:52:22 +00001139 return VisitDeclarationNameInfo(D->getNameInfo());
1140}
1141
1142bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1143 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001144 // Visit nested-name-specifier.
1145 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1146 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1147 return true;
1148
Douglas Gregor7e242562010-09-01 19:52:22 +00001149 return false;
1150}
1151
Douglas Gregor01829d32010-08-31 14:41:23 +00001152bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1153 switch (Name.getName().getNameKind()) {
1154 case clang::DeclarationName::Identifier:
1155 case clang::DeclarationName::CXXLiteralOperatorName:
1156 case clang::DeclarationName::CXXOperatorName:
1157 case clang::DeclarationName::CXXUsingDirective:
1158 return false;
1159
1160 case clang::DeclarationName::CXXConstructorName:
1161 case clang::DeclarationName::CXXDestructorName:
1162 case clang::DeclarationName::CXXConversionFunctionName:
1163 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1164 return Visit(TSInfo->getTypeLoc());
1165 return false;
1166
1167 case clang::DeclarationName::ObjCZeroArgSelector:
1168 case clang::DeclarationName::ObjCOneArgSelector:
1169 case clang::DeclarationName::ObjCMultiArgSelector:
1170 // FIXME: Per-identifier location info?
1171 return false;
1172 }
1173
1174 return false;
1175}
1176
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001177bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1178 SourceRange Range) {
1179 // FIXME: This whole routine is a hack to work around the lack of proper
1180 // source information in nested-name-specifiers (PR5791). Since we do have
1181 // a beginning source location, we can visit the first component of the
1182 // nested-name-specifier, if it's a single-token component.
1183 if (!NNS)
1184 return false;
1185
1186 // Get the first component in the nested-name-specifier.
1187 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1188 NNS = Prefix;
1189
1190 switch (NNS->getKind()) {
1191 case NestedNameSpecifier::Namespace:
1192 // FIXME: The token at this source location might actually have been a
1193 // namespace alias, but we don't model that. Lame!
1194 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1195 TU));
1196
1197 case NestedNameSpecifier::TypeSpec: {
1198 // If the type has a form where we know that the beginning of the source
1199 // range matches up with a reference cursor. Visit the appropriate reference
1200 // cursor.
1201 Type *T = NNS->getAsType();
1202 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1203 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1204 if (const TagType *Tag = dyn_cast<TagType>(T))
1205 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1206 if (const TemplateSpecializationType *TST
1207 = dyn_cast<TemplateSpecializationType>(T))
1208 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1209 break;
1210 }
1211
1212 case NestedNameSpecifier::TypeSpecWithTemplate:
1213 case NestedNameSpecifier::Global:
1214 case NestedNameSpecifier::Identifier:
1215 break;
1216 }
1217
1218 return false;
1219}
1220
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001221bool CursorVisitor::VisitTemplateParameters(
1222 const TemplateParameterList *Params) {
1223 if (!Params)
1224 return false;
1225
1226 for (TemplateParameterList::const_iterator P = Params->begin(),
1227 PEnd = Params->end();
1228 P != PEnd; ++P) {
1229 if (Visit(MakeCXCursor(*P, TU)))
1230 return true;
1231 }
1232
1233 return false;
1234}
1235
Douglas Gregor0b36e612010-08-31 20:37:03 +00001236bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1237 switch (Name.getKind()) {
1238 case TemplateName::Template:
1239 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1240
1241 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001242 // Visit the overloaded template set.
1243 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1244 return true;
1245
Douglas Gregor0b36e612010-08-31 20:37:03 +00001246 return false;
1247
1248 case TemplateName::DependentTemplate:
1249 // FIXME: Visit nested-name-specifier.
1250 return false;
1251
1252 case TemplateName::QualifiedTemplate:
1253 // FIXME: Visit nested-name-specifier.
1254 return Visit(MakeCursorTemplateRef(
1255 Name.getAsQualifiedTemplateName()->getDecl(),
1256 Loc, TU));
1257 }
1258
1259 return false;
1260}
1261
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001262bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1263 switch (TAL.getArgument().getKind()) {
1264 case TemplateArgument::Null:
1265 case TemplateArgument::Integral:
1266 return false;
1267
1268 case TemplateArgument::Pack:
1269 // FIXME: Implement when variadic templates come along.
1270 return false;
1271
1272 case TemplateArgument::Type:
1273 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1274 return Visit(TSInfo->getTypeLoc());
1275 return false;
1276
1277 case TemplateArgument::Declaration:
1278 if (Expr *E = TAL.getSourceDeclExpression())
1279 return Visit(MakeCXCursor(E, StmtParent, TU));
1280 return false;
1281
1282 case TemplateArgument::Expression:
1283 if (Expr *E = TAL.getSourceExpression())
1284 return Visit(MakeCXCursor(E, StmtParent, TU));
1285 return false;
1286
1287 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001288 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1289 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001290 }
1291
1292 return false;
1293}
1294
Ted Kremeneka0536d82010-05-07 01:04:29 +00001295bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1296 return VisitDeclContext(D);
1297}
1298
Douglas Gregor01829d32010-08-31 14:41:23 +00001299bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1300 return Visit(TL.getUnqualifiedLoc());
1301}
1302
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001303bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1304 ASTContext &Context = TU->getASTContext();
1305
1306 // Some builtin types (such as Objective-C's "id", "sel", and
1307 // "Class") have associated declarations. Create cursors for those.
1308 QualType VisitType;
1309 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001310 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001311 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001312 case BuiltinType::Char_U:
1313 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001314 case BuiltinType::Char16:
1315 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001316 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001317 case BuiltinType::UInt:
1318 case BuiltinType::ULong:
1319 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001320 case BuiltinType::UInt128:
1321 case BuiltinType::Char_S:
1322 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001323 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001324 case BuiltinType::Short:
1325 case BuiltinType::Int:
1326 case BuiltinType::Long:
1327 case BuiltinType::LongLong:
1328 case BuiltinType::Int128:
1329 case BuiltinType::Float:
1330 case BuiltinType::Double:
1331 case BuiltinType::LongDouble:
1332 case BuiltinType::NullPtr:
1333 case BuiltinType::Overload:
1334 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001335 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001336
1337 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001338 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001339
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001340 case BuiltinType::ObjCId:
1341 VisitType = Context.getObjCIdType();
1342 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001343
1344 case BuiltinType::ObjCClass:
1345 VisitType = Context.getObjCClassType();
1346 break;
1347
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001348 case BuiltinType::ObjCSel:
1349 VisitType = Context.getObjCSelType();
1350 break;
1351 }
1352
1353 if (!VisitType.isNull()) {
1354 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001355 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001356 TU));
1357 }
1358
1359 return false;
1360}
1361
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001362bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1363 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1364}
1365
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001366bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1367 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1368}
1369
1370bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1371 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1372}
1373
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001374bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001375 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001376 // no context information with which we can match up the depth/index in the
1377 // type to the appropriate
1378 return false;
1379}
1380
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001381bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1382 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1383 return true;
1384
John McCallc12c5bb2010-05-15 11:32:37 +00001385 return false;
1386}
1387
1388bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1389 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1390 return true;
1391
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001392 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1393 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1394 TU)))
1395 return true;
1396 }
1397
1398 return false;
1399}
1400
1401bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001402 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001403}
1404
1405bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1406 return Visit(TL.getPointeeLoc());
1407}
1408
1409bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1410 return Visit(TL.getPointeeLoc());
1411}
1412
1413bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1414 return Visit(TL.getPointeeLoc());
1415}
1416
1417bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001418 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001419}
1420
1421bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001422 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001423}
1424
Douglas Gregor01829d32010-08-31 14:41:23 +00001425bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1426 bool SkipResultType) {
1427 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001428 return true;
1429
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001430 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001431 if (Decl *D = TL.getArg(I))
1432 if (Visit(MakeCXCursor(D, TU)))
1433 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001434
1435 return false;
1436}
1437
1438bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1439 if (Visit(TL.getElementLoc()))
1440 return true;
1441
1442 if (Expr *Size = TL.getSizeExpr())
1443 return Visit(MakeCXCursor(Size, StmtParent, TU));
1444
1445 return false;
1446}
1447
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001448bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1449 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001450 // Visit the template name.
1451 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1452 TL.getTemplateNameLoc()))
1453 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001454
1455 // Visit the template arguments.
1456 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1457 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1458 return true;
1459
1460 return false;
1461}
1462
Douglas Gregor2332c112010-01-21 20:48:56 +00001463bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1464 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1465}
1466
1467bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1468 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1469 return Visit(TSInfo->getTypeLoc());
1470
1471 return false;
1472}
1473
Douglas Gregora59e3902010-01-21 23:27:09 +00001474bool CursorVisitor::VisitStmt(Stmt *S) {
1475 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1476 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001477 if (Stmt *C = *Child)
1478 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1479 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001480 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001481
Douglas Gregora59e3902010-01-21 23:27:09 +00001482 return false;
1483}
1484
1485bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
Ted Kremenek007a7c92010-11-01 23:26:51 +00001486 bool isFirst = true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001487 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1488 D != DEnd; ++D) {
Ted Kremenek007a7c92010-11-01 23:26:51 +00001489 if (*D && Visit(MakeCXCursor(*D, TU, isFirst)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001490 return true;
Ted Kremenek007a7c92010-11-01 23:26:51 +00001491 isFirst = false;
Douglas Gregora59e3902010-01-21 23:27:09 +00001492 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001493
Douglas Gregora59e3902010-01-21 23:27:09 +00001494 return false;
1495}
1496
Douglas Gregor36897b02010-09-10 00:22:18 +00001497bool CursorVisitor::VisitGotoStmt(GotoStmt *S) {
1498 return Visit(MakeCursorLabelRef(S->getLabel(), S->getLabelLoc(), TU));
1499}
1500
Douglas Gregor8947a752010-09-02 20:35:02 +00001501bool CursorVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
1502 // Visit nested-name-specifier, if present.
1503 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1504 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1505 return true;
1506
1507 // Visit declaration name.
1508 if (VisitDeclarationNameInfo(E->getNameInfo()))
1509 return true;
1510
1511 // Visit explicitly-specified template arguments.
1512 if (E->hasExplicitTemplateArgs()) {
1513 ExplicitTemplateArgumentList &Args = E->getExplicitTemplateArgs();
1514 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1515 *ArgEnd = Arg + Args.NumTemplateArgs;
1516 Arg != ArgEnd; ++Arg)
1517 if (VisitTemplateArgumentLoc(*Arg))
1518 return true;
1519 }
1520
1521 return false;
1522}
1523
Ted Kremenek3064ef92010-08-27 21:34:58 +00001524bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1525 if (D->isDefinition()) {
1526 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1527 E = D->bases_end(); I != E; ++I) {
1528 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1529 return true;
1530 }
1531 }
1532
1533 return VisitTagDecl(D);
1534}
1535
1536
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001537bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1538 return Visit(B->getBlockDecl());
1539}
1540
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001541bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001542 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001543 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1544 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001545
1546 // Visit the components of the offsetof expression.
1547 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1548 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1549 const OffsetOfNode &Node = E->getComponent(I);
1550 switch (Node.getKind()) {
1551 case OffsetOfNode::Array:
1552 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1553 StmtParent, TU)))
1554 return true;
1555 break;
1556
1557 case OffsetOfNode::Field:
1558 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1559 TU)))
1560 return true;
1561 break;
1562
1563 case OffsetOfNode::Identifier:
1564 case OffsetOfNode::Base:
1565 continue;
1566 }
1567 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001568
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001569 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001570}
1571
Douglas Gregor336fd812010-01-23 00:40:08 +00001572bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1573 if (E->isArgumentType()) {
1574 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1575 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001576
Douglas Gregor336fd812010-01-23 00:40:08 +00001577 return false;
1578 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001579
Douglas Gregor336fd812010-01-23 00:40:08 +00001580 return VisitExpr(E);
1581}
1582
1583bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1584 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1585 if (Visit(TSInfo->getTypeLoc()))
1586 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001587
Douglas Gregor336fd812010-01-23 00:40:08 +00001588 return VisitCastExpr(E);
1589}
1590
Douglas Gregor36897b02010-09-10 00:22:18 +00001591bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1592 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1593}
1594
Douglas Gregor648220e2010-08-10 15:02:34 +00001595bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1596 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1597 Visit(E->getArgTInfo2()->getTypeLoc());
1598}
1599
1600bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1601 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1602 return true;
1603
1604 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1605}
1606
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001607bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1608 // Visit the designators.
1609 typedef DesignatedInitExpr::Designator Designator;
1610 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1611 DEnd = E->designators_end();
1612 D != DEnd; ++D) {
1613 if (D->isFieldDesignator()) {
1614 if (FieldDecl *Field = D->getField())
1615 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1616 return true;
1617
1618 continue;
1619 }
1620
1621 if (D->isArrayDesignator()) {
1622 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1623 return true;
1624
1625 continue;
1626 }
1627
1628 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1629 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1630 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1631 return true;
1632 }
1633
1634 // Visit the initializer value itself.
1635 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1636}
1637
Douglas Gregor94802292010-09-02 21:20:16 +00001638bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1639 if (E->isTypeOperand()) {
1640 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1641 return Visit(TSInfo->getTypeLoc());
1642
1643 return false;
1644 }
1645
1646 return VisitExpr(E);
1647}
1648
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001649bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1650 if (E->isTypeOperand()) {
1651 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1652 return Visit(TSInfo->getTypeLoc());
1653
1654 return false;
1655 }
1656
1657 return VisitExpr(E);
1658}
1659
Douglas Gregorab6677e2010-09-08 00:15:04 +00001660bool CursorVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1661 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
Douglas Gregor40749ee2010-11-03 00:35:38 +00001662 if (Visit(TSInfo->getTypeLoc()))
1663 return true;
Douglas Gregorab6677e2010-09-08 00:15:04 +00001664
1665 return VisitExpr(E);
1666}
1667
1668bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1669 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1670 return Visit(TSInfo->getTypeLoc());
1671
1672 return false;
1673}
1674
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001675bool CursorVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1676 // Visit placement arguments.
1677 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1678 if (Visit(MakeCXCursor(E->getPlacementArg(I), StmtParent, TU)))
1679 return true;
1680
1681 // Visit the allocated type.
1682 if (TypeSourceInfo *TSInfo = E->getAllocatedTypeSourceInfo())
1683 if (Visit(TSInfo->getTypeLoc()))
1684 return true;
1685
1686 // Visit the array size, if any.
1687 if (E->isArray() && Visit(MakeCXCursor(E->getArraySize(), StmtParent, TU)))
1688 return true;
1689
1690 // Visit the initializer or constructor arguments.
1691 for (unsigned I = 0, N = E->getNumConstructorArgs(); I != N; ++I)
1692 if (Visit(MakeCXCursor(E->getConstructorArg(I), StmtParent, TU)))
1693 return true;
1694
1695 return false;
1696}
1697
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001698bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1699 // Visit base expression.
1700 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1701 return true;
1702
1703 // Visit the nested-name-specifier.
1704 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1705 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1706 return true;
1707
1708 // Visit the scope type that looks disturbingly like the nested-name-specifier
1709 // but isn't.
1710 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1711 if (Visit(TSInfo->getTypeLoc()))
1712 return true;
1713
1714 // Visit the name of the type being destroyed.
1715 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1716 if (Visit(TSInfo->getTypeLoc()))
1717 return true;
1718
1719 return false;
1720}
1721
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001722bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1723 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1724}
1725
Douglas Gregorbfebed22010-09-03 17:24:10 +00001726bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1727 DependentScopeDeclRefExpr *E) {
1728 // Visit the nested-name-specifier.
1729 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1730 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1731 return true;
1732
1733 // Visit the declaration name.
1734 if (VisitDeclarationNameInfo(E->getNameInfo()))
1735 return true;
1736
1737 // Visit the explicitly-specified template arguments.
1738 if (const ExplicitTemplateArgumentList *ArgList
1739 = E->getOptionalExplicitTemplateArgs()) {
1740 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1741 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1742 Arg != ArgEnd; ++Arg) {
1743 if (VisitTemplateArgumentLoc(*Arg))
1744 return true;
1745 }
1746 }
1747
1748 return false;
1749}
1750
Douglas Gregorab6677e2010-09-08 00:15:04 +00001751bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1752 CXXUnresolvedConstructExpr *E) {
1753 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1754 if (Visit(TSInfo->getTypeLoc()))
1755 return true;
1756
1757 return VisitExpr(E);
1758}
1759
Douglas Gregor25d63622010-09-03 17:35:34 +00001760bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1761 CXXDependentScopeMemberExpr *E) {
1762 // Visit the base expression, if there is one.
1763 if (!E->isImplicitAccess() &&
1764 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1765 return true;
1766
1767 // Visit the nested-name-specifier.
1768 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1769 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1770 return true;
1771
1772 // Visit the declaration name.
1773 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1774 return true;
1775
1776 // Visit the explicitly-specified template arguments.
1777 if (const ExplicitTemplateArgumentList *ArgList
1778 = E->getOptionalExplicitTemplateArgs()) {
1779 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1780 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1781 Arg != ArgEnd; ++Arg) {
1782 if (VisitTemplateArgumentLoc(*Arg))
1783 return true;
1784 }
1785 }
1786
1787 return false;
1788}
1789
Douglas Gregor81d34662010-04-20 15:39:42 +00001790bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1791 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1792}
1793
1794
Ted Kremenek09dfa372010-02-18 05:46:33 +00001795bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001796 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1797 i != e; ++i)
1798 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001799 return true;
1800
1801 return false;
1802}
1803
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001804//===----------------------------------------------------------------------===//
1805// Data-recursive visitor methods.
1806//===----------------------------------------------------------------------===//
1807
Ted Kremeneka6b70432010-11-12 21:34:09 +00001808static void EnqueueChildren(VisitorWorkList &WL, CXCursor Parent, Stmt *S) {
1809 unsigned size = WL.size();
1810 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1811 Child != ChildEnd; ++Child) {
1812 WLAddStmt(WL, Parent, *Child);
1813 }
1814 if (size == WL.size())
1815 return;
1816 // Now reverse the entries we just added. This will match the DFS
1817 // ordering performed by the worklist.
1818 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1819 std::reverse(I, E);
1820}
1821
Ted Kremenek60458782010-11-12 21:34:16 +00001822static void EnqueueOverloadExpr(VisitorWorkList &WL, CXCursor Parent,
1823 OverloadExpr *E) {
1824 WL.push_back(OverloadExprParts(E, Parent));
1825}
1826
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001827void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
1828 CXCursor C = MakeCXCursor(S, StmtParent, TU);
1829 switch (S->getStmtClass()) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001830 default:
1831 EnqueueChildren(WL, C, S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001832 break;
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001833 case Stmt::CompoundLiteralExprClass: {
1834 CompoundLiteralExpr *CL = cast<CompoundLiteralExpr>(S);
1835 EnqueueChildren(WL, C, CL);
1836 WLAddTypeLoc(WL, C, CL->getTypeSourceInfo());
1837 break;
1838 }
Ted Kremenekf1107452010-11-12 18:26:56 +00001839 case Stmt::CXXOperatorCallExprClass: {
1840 CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(S);
1841 // Note that we enqueue things in reverse order so that
1842 // they are visited correctly by the DFS.
Ted Kremenekf1107452010-11-12 18:26:56 +00001843 for (unsigned I = 1, N = CE->getNumArgs(); I != N; ++I)
Ted Kremenekae3c2202010-11-12 18:27:01 +00001844 WLAddStmt(WL, C, CE->getArg(N-I));
Ted Kremenekf1107452010-11-12 18:26:56 +00001845
Ted Kremenekae3c2202010-11-12 18:27:01 +00001846 WLAddStmt(WL, C, CE->getCallee());
1847 WLAddStmt(WL, C, CE->getArg(0));
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001848 break;
1849 }
1850 case Stmt::BinaryOperatorClass: {
1851 BinaryOperator *B = cast<BinaryOperator>(S);
Ted Kremenekae3c2202010-11-12 18:27:01 +00001852 WLAddStmt(WL, C, B->getRHS());
1853 WLAddStmt(WL, C, B->getLHS());
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001854 break;
1855 }
Ted Kremenekbb677132010-11-12 18:27:04 +00001856 case Stmt::ForStmtClass: {
1857 ForStmt *FS = cast<ForStmt>(S);
1858 WLAddStmt(WL, C, FS->getBody());
1859 WLAddStmt(WL, C, FS->getInc());
1860 WLAddStmt(WL, C, FS->getCond());
1861 WLAddDecl(WL, C, FS->getConditionVariable());
1862 WLAddStmt(WL, C, FS->getInit());
1863 break;
1864 }
Ted Kremenekc70ebba2010-11-12 18:26:58 +00001865 case Stmt::IfStmtClass: {
1866 IfStmt *If = cast<IfStmt>(S);
1867 WLAddStmt(WL, C, If->getElse());
1868 WLAddStmt(WL, C, If->getThen());
1869 WLAddStmt(WL, C, If->getCond());
Ted Kremenekae3c2202010-11-12 18:27:01 +00001870 WLAddDecl(WL, C, If->getConditionVariable());
Ted Kremenekc70ebba2010-11-12 18:26:58 +00001871 break;
1872 }
Ted Kremeneka6b70432010-11-12 21:34:09 +00001873 case Stmt::InitListExprClass: {
1874 InitListExpr *IE = cast<InitListExpr>(S);
1875 // We care about the syntactic form of the initializer list, only.
1876 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1877 IE = Syntactic;
1878 EnqueueChildren(WL, C, IE);
1879 break;
1880 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001881 case Stmt::MemberExprClass: {
1882 MemberExpr *M = cast<MemberExpr>(S);
1883 WL.push_back(MemberExprParts(M, C));
Ted Kremenekae3c2202010-11-12 18:27:01 +00001884 WLAddStmt(WL, C, M->getBase());
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001885 break;
1886 }
Ted Kremenekc373e3c2010-11-12 22:24:55 +00001887 case Stmt::ObjCMessageExprClass:
1888 EnqueueChildren(WL, C, S);
1889 WLAddTypeLoc(WL, C, cast<ObjCMessageExpr>(S)->getClassReceiverTypeInfo());
1890 break;
Ted Kremenekf1107452010-11-12 18:26:56 +00001891 case Stmt::ParenExprClass: {
Ted Kremenekae3c2202010-11-12 18:27:01 +00001892 WLAddStmt(WL, C, cast<ParenExpr>(S)->getSubExpr());
Ted Kremenekf1107452010-11-12 18:26:56 +00001893 break;
1894 }
1895 case Stmt::SwitchStmtClass: {
1896 SwitchStmt *SS = cast<SwitchStmt>(S);
Ted Kremenekae3c2202010-11-12 18:27:01 +00001897 WLAddStmt(WL, C, SS->getBody());
1898 WLAddStmt(WL, C, SS->getCond());
1899 WLAddDecl(WL, C, SS->getConditionVariable());
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001900 break;
1901 }
Ted Kremenekbb677132010-11-12 18:27:04 +00001902 case Stmt::WhileStmtClass: {
1903 WhileStmt *W = cast<WhileStmt>(S);
1904 WLAddStmt(WL, C, W->getBody());
1905 WLAddStmt(WL, C, W->getCond());
1906 WLAddDecl(WL, C, W->getConditionVariable());
1907 break;
1908 }
Ted Kremenek60458782010-11-12 21:34:16 +00001909 case Stmt::UnresolvedLookupExprClass:
1910 EnqueueOverloadExpr(WL, C, cast<OverloadExpr>(S));
1911 break;
1912 case Stmt::UnresolvedMemberExprClass: {
1913 UnresolvedMemberExpr *U = cast<UnresolvedMemberExpr>(S);
1914 EnqueueOverloadExpr(WL, C, U);
1915 if (!U->isImplicitAccess())
1916 WLAddStmt(WL, C, U->getBase());
1917 break;
1918 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001919 }
1920}
1921
1922bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1923 if (RegionOfInterest.isValid()) {
1924 SourceRange Range = getRawCursorExtent(C);
1925 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1926 return false;
1927 }
1928 return true;
1929}
1930
1931bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1932 while (!WL.empty()) {
1933 // Dequeue the worklist item.
1934 VisitorJob LI = WL.back(); WL.pop_back();
1935
1936 // Set the Parent field, then back to its old value once we're done.
1937 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1938
1939 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001940 case VisitorJob::DeclVisitKind: {
1941 Decl *D = cast<DeclVisit>(LI).get();
1942 if (!D)
1943 continue;
1944
1945 // For now, perform default visitation for Decls.
1946 if (Visit(MakeCXCursor(D, TU)))
1947 return true;
1948
1949 continue;
1950 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001951 case VisitorJob::TypeLocVisitKind: {
1952 // Perform default visitation for TypeLocs.
1953 if (Visit(cast<TypeLocVisit>(LI).get()))
1954 return true;
1955 continue;
1956 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001957 case VisitorJob::StmtVisitKind: {
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001958 Stmt *S = cast<StmtVisit>(LI).get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001959 if (!S)
1960 continue;
1961
Ted Kremenekf1107452010-11-12 18:26:56 +00001962 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001963 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1964
1965 switch (S->getStmtClass()) {
1966 default: {
1967 // Perform default visitation for other cases.
1968 if (Visit(Cursor))
1969 return true;
1970 continue;
1971 }
Ted Kremenekf1107452010-11-12 18:26:56 +00001972 case Stmt::BinaryOperatorClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001973 case Stmt::CallExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001974 case Stmt::CaseStmtClass:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001975 case Stmt::CompoundLiteralExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001976 case Stmt::CompoundStmtClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001977 case Stmt::CXXMemberCallExprClass:
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001978 case Stmt::CXXOperatorCallExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001979 case Stmt::DefaultStmtClass:
Ted Kremenekbb677132010-11-12 18:27:04 +00001980 case Stmt::DoStmtClass:
1981 case Stmt::ForStmtClass:
Ted Kremenekc70ebba2010-11-12 18:26:58 +00001982 case Stmt::IfStmtClass:
Ted Kremeneka6b70432010-11-12 21:34:09 +00001983 case Stmt::InitListExprClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001984 case Stmt::MemberExprClass:
Ted Kremenekc373e3c2010-11-12 22:24:55 +00001985 case Stmt::ObjCMessageExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001986 case Stmt::ParenExprClass:
1987 case Stmt::SwitchStmtClass:
Ted Kremenekae3c2202010-11-12 18:27:01 +00001988 case Stmt::UnaryOperatorClass:
Ted Kremenek60458782010-11-12 21:34:16 +00001989 case Stmt::UnresolvedLookupExprClass:
1990 case Stmt::UnresolvedMemberExprClass:
Ted Kremenekbb677132010-11-12 18:27:04 +00001991 case Stmt::WhileStmtClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001992 {
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001993 if (!IsInRegionOfInterest(Cursor))
1994 continue;
1995 switch (Visitor(Cursor, Parent, ClientData)) {
1996 case CXChildVisit_Break:
1997 return true;
1998 case CXChildVisit_Continue:
1999 break;
2000 case CXChildVisit_Recurse:
2001 EnqueueWorkList(WL, S);
2002 break;
2003 }
2004 }
2005 }
2006 continue;
2007 }
2008 case VisitorJob::MemberExprPartsKind: {
2009 // Handle the other pieces in the MemberExpr besides the base.
2010 MemberExpr *M = cast<MemberExprParts>(LI).get();
2011
2012 // Visit the nested-name-specifier
2013 if (NestedNameSpecifier *Qualifier = M->getQualifier())
2014 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
2015 return true;
2016
2017 // Visit the declaration name.
2018 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2019 return true;
2020
2021 // Visit the explicitly-specified template arguments, if any.
2022 if (M->hasExplicitTemplateArgs()) {
2023 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2024 *ArgEnd = Arg + M->getNumTemplateArgs();
2025 Arg != ArgEnd; ++Arg) {
2026 if (VisitTemplateArgumentLoc(*Arg))
2027 return true;
2028 }
2029 }
2030 continue;
2031 }
Ted Kremenek60458782010-11-12 21:34:16 +00002032 case VisitorJob::OverloadExprPartsKind: {
2033 OverloadExpr *O = cast<OverloadExprParts>(LI).get();
2034 // Visit the nested-name-specifier.
2035 if (NestedNameSpecifier *Qualifier = O->getQualifier())
2036 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
2037 return true;
2038 // Visit the declaration name.
2039 if (VisitDeclarationNameInfo(O->getNameInfo()))
2040 return true;
2041 // Visit the overloaded declaration reference.
2042 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2043 return true;
2044 // Visit the explicitly-specified template arguments.
2045 if (const ExplicitTemplateArgumentList *ArgList
2046 = O->getOptionalExplicitTemplateArgs()) {
2047 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2048 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2049 Arg != ArgEnd; ++Arg) {
2050 if (VisitTemplateArgumentLoc(*Arg))
2051 return true;
2052 }
2053 }
2054 continue;
2055 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002056 }
2057 }
2058 return false;
2059}
2060
2061bool CursorVisitor::VisitDataRecursive(Stmt *S) {
2062 VisitorWorkList WL;
2063 EnqueueWorkList(WL, S);
2064 return RunVisitorWorkList(WL);
2065}
2066
2067//===----------------------------------------------------------------------===//
2068// Misc. API hooks.
2069//===----------------------------------------------------------------------===//
2070
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002071static llvm::sys::Mutex EnableMultithreadingMutex;
2072static bool EnabledMultithreading;
2073
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002074extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002075CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2076 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002077 // Disable pretty stack trace functionality, which will otherwise be a very
2078 // poor citizen of the world and set up all sorts of signal handlers.
2079 llvm::DisablePrettyStackTrace = true;
2080
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002081 // We use crash recovery to make some of our APIs more reliable, implicitly
2082 // enable it.
2083 llvm::CrashRecoveryContext::Enable();
2084
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002085 // Enable support for multithreading in LLVM.
2086 {
2087 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2088 if (!EnabledMultithreading) {
2089 llvm::llvm_start_multithreaded();
2090 EnabledMultithreading = true;
2091 }
2092 }
2093
Douglas Gregora030b7c2010-01-22 20:35:53 +00002094 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002095 if (excludeDeclarationsFromPCH)
2096 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002097 if (displayDiagnostics)
2098 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002099 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002100}
2101
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002102void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002103 if (CIdx)
2104 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002105}
2106
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002107CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002108 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002109 if (!CIdx)
2110 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002111
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002112 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002113 FileSystemOptions FileSystemOpts;
2114 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002115
Douglas Gregor28019772010-04-05 23:52:57 +00002116 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002117 return ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002118 CXXIdx->getOnlyLocalDecls(),
2119 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00002120}
2121
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002122unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002123 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002124 CXTranslationUnit_CacheCompletionResults |
2125 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002126}
2127
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002128CXTranslationUnit
2129clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2130 const char *source_filename,
2131 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002132 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002133 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002134 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002135 return clang_parseTranslationUnit(CIdx, source_filename,
2136 command_line_args, num_command_line_args,
2137 unsaved_files, num_unsaved_files,
2138 CXTranslationUnit_DetailedPreprocessingRecord);
2139}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002140
2141struct ParseTranslationUnitInfo {
2142 CXIndex CIdx;
2143 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002144 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002145 int num_command_line_args;
2146 struct CXUnsavedFile *unsaved_files;
2147 unsigned num_unsaved_files;
2148 unsigned options;
2149 CXTranslationUnit result;
2150};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002151static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002152 ParseTranslationUnitInfo *PTUI =
2153 static_cast<ParseTranslationUnitInfo*>(UserData);
2154 CXIndex CIdx = PTUI->CIdx;
2155 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002156 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002157 int num_command_line_args = PTUI->num_command_line_args;
2158 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2159 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2160 unsigned options = PTUI->options;
2161 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002162
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002163 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002164 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002165
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002166 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2167
Douglas Gregor44c181a2010-07-23 00:33:23 +00002168 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002169 bool CompleteTranslationUnit
2170 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002171 bool CacheCodeCompetionResults
2172 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002173 bool CXXPrecompilePreamble
2174 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2175 bool CXXChainedPCH
2176 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002177
Douglas Gregor5352ac02010-01-28 00:27:43 +00002178 // Configure the diagnostics.
2179 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002180 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2181 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002182
Douglas Gregor4db64a42010-01-23 00:14:00 +00002183 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2184 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002185 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002186 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002187 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002188 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2189 Buffer));
2190 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002191
Douglas Gregorb10daed2010-10-11 16:52:23 +00002192 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002193
Ted Kremenek139ba862009-10-22 00:03:57 +00002194 // The 'source_filename' argument is optional. If the caller does not
2195 // specify it then it is assumed that the source file is specified
2196 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002197 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002198 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002199
2200 // Since the Clang C library is primarily used by batch tools dealing with
2201 // (often very broken) source code, where spell-checking can have a
2202 // significant negative impact on performance (particularly when
2203 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002204 // Only do this if we haven't found a spell-checking-related argument.
2205 bool FoundSpellCheckingArgument = false;
2206 for (int I = 0; I != num_command_line_args; ++I) {
2207 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2208 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2209 FoundSpellCheckingArgument = true;
2210 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002211 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002212 }
2213 if (!FoundSpellCheckingArgument)
2214 Args.push_back("-fno-spell-checking");
2215
2216 Args.insert(Args.end(), command_line_args,
2217 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002218
Douglas Gregor44c181a2010-07-23 00:33:23 +00002219 // Do we need the detailed preprocessing record?
2220 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002221 Args.push_back("-Xclang");
2222 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002223 }
2224
Douglas Gregorb10daed2010-10-11 16:52:23 +00002225 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002226 llvm::OwningPtr<ASTUnit> Unit(
2227 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2228 Diags,
2229 CXXIdx->getClangResourcesPath(),
2230 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002231 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002232 RemappedFiles.data(),
2233 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002234 PrecompilePreamble,
2235 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002236 CacheCodeCompetionResults,
2237 CXXPrecompilePreamble,
2238 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002239
Douglas Gregorb10daed2010-10-11 16:52:23 +00002240 if (NumErrors != Diags->getNumErrors()) {
2241 // Make sure to check that 'Unit' is non-NULL.
2242 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2243 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2244 DEnd = Unit->stored_diag_end();
2245 D != DEnd; ++D) {
2246 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2247 CXString Msg = clang_formatDiagnostic(&Diag,
2248 clang_defaultDiagnosticDisplayOptions());
2249 fprintf(stderr, "%s\n", clang_getCString(Msg));
2250 clang_disposeString(Msg);
2251 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002252#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002253 // On Windows, force a flush, since there may be multiple copies of
2254 // stderr and stdout in the file system, all with different buffers
2255 // but writing to the same device.
2256 fflush(stderr);
2257#endif
2258 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002259 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002260
Douglas Gregorb10daed2010-10-11 16:52:23 +00002261 PTUI->result = Unit.take();
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002262}
2263CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2264 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002265 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002266 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002267 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002268 unsigned num_unsaved_files,
2269 unsigned options) {
2270 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002271 num_command_line_args, unsaved_files,
2272 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002273 llvm::CrashRecoveryContext CRC;
2274
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002275 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002276 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2277 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2278 fprintf(stderr, " 'command_line_args' : [");
2279 for (int i = 0; i != num_command_line_args; ++i) {
2280 if (i)
2281 fprintf(stderr, ", ");
2282 fprintf(stderr, "'%s'", command_line_args[i]);
2283 }
2284 fprintf(stderr, "],\n");
2285 fprintf(stderr, " 'unsaved_files' : [");
2286 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2287 if (i)
2288 fprintf(stderr, ", ");
2289 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2290 unsaved_files[i].Length);
2291 }
2292 fprintf(stderr, "],\n");
2293 fprintf(stderr, " 'options' : %d,\n", options);
2294 fprintf(stderr, "}\n");
2295
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002296 return 0;
2297 }
2298
2299 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002300}
2301
Douglas Gregor19998442010-08-13 15:35:05 +00002302unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2303 return CXSaveTranslationUnit_None;
2304}
2305
2306int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2307 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002308 if (!TU)
2309 return 1;
2310
2311 return static_cast<ASTUnit *>(TU)->Save(FileName);
2312}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002313
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002314void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002315 if (CTUnit) {
2316 // If the translation unit has been marked as unsafe to free, just discard
2317 // it.
2318 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2319 return;
2320
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002321 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002322 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002323}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002324
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002325unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2326 return CXReparse_None;
2327}
2328
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002329struct ReparseTranslationUnitInfo {
2330 CXTranslationUnit TU;
2331 unsigned num_unsaved_files;
2332 struct CXUnsavedFile *unsaved_files;
2333 unsigned options;
2334 int result;
2335};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002336
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002337static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002338 ReparseTranslationUnitInfo *RTUI =
2339 static_cast<ReparseTranslationUnitInfo*>(UserData);
2340 CXTranslationUnit TU = RTUI->TU;
2341 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2342 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2343 unsigned options = RTUI->options;
2344 (void) options;
2345 RTUI->result = 1;
2346
Douglas Gregorabc563f2010-07-19 21:46:24 +00002347 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002348 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002349
2350 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2351 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002352
2353 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2354 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2355 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2356 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002357 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002358 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2359 Buffer));
2360 }
2361
Douglas Gregor593b0c12010-09-23 18:47:53 +00002362 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2363 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002364}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002365
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002366int clang_reparseTranslationUnit(CXTranslationUnit TU,
2367 unsigned num_unsaved_files,
2368 struct CXUnsavedFile *unsaved_files,
2369 unsigned options) {
2370 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2371 options, 0 };
2372 llvm::CrashRecoveryContext CRC;
2373
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002374 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002375 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002376 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2377 return 1;
2378 }
2379
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002380
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002381 return RTUI.result;
2382}
2383
Douglas Gregordf95a132010-08-09 20:45:32 +00002384
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002385CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002386 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002387 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002388
Steve Naroff77accc12009-09-03 18:19:54 +00002389 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002390 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002391}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002392
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002393CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002394 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002395 return Result;
2396}
2397
Ted Kremenekfb480492010-01-13 21:46:36 +00002398} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002399
Ted Kremenekfb480492010-01-13 21:46:36 +00002400//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002401// CXSourceLocation and CXSourceRange Operations.
2402//===----------------------------------------------------------------------===//
2403
Douglas Gregorb9790342010-01-22 21:44:22 +00002404extern "C" {
2405CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002406 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002407 return Result;
2408}
2409
2410unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002411 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2412 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2413 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002414}
2415
2416CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2417 CXFile file,
2418 unsigned line,
2419 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002420 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002421 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002422
Douglas Gregorb9790342010-01-22 21:44:22 +00002423 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2424 SourceLocation SLoc
2425 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002426 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002427 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002428 if (SLoc.isInvalid()) return clang_getNullLocation();
2429
2430 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2431}
2432
2433CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2434 CXFile file,
2435 unsigned offset) {
2436 if (!tu || !file)
2437 return clang_getNullLocation();
2438
2439 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2440 SourceLocation Start
2441 = CXXUnit->getSourceManager().getLocation(
2442 static_cast<const FileEntry *>(file),
2443 1, 1);
2444 if (Start.isInvalid()) return clang_getNullLocation();
2445
2446 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2447
2448 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002449
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002450 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002451}
2452
Douglas Gregor5352ac02010-01-28 00:27:43 +00002453CXSourceRange clang_getNullRange() {
2454 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2455 return Result;
2456}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002457
Douglas Gregor5352ac02010-01-28 00:27:43 +00002458CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2459 if (begin.ptr_data[0] != end.ptr_data[0] ||
2460 begin.ptr_data[1] != end.ptr_data[1])
2461 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002462
2463 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002464 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002465 return Result;
2466}
2467
Douglas Gregor46766dc2010-01-26 19:19:08 +00002468void clang_getInstantiationLocation(CXSourceLocation location,
2469 CXFile *file,
2470 unsigned *line,
2471 unsigned *column,
2472 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002473 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2474
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002475 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002476 if (file)
2477 *file = 0;
2478 if (line)
2479 *line = 0;
2480 if (column)
2481 *column = 0;
2482 if (offset)
2483 *offset = 0;
2484 return;
2485 }
2486
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002487 const SourceManager &SM =
2488 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002489 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002490
2491 if (file)
2492 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2493 if (line)
2494 *line = SM.getInstantiationLineNumber(InstLoc);
2495 if (column)
2496 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002497 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002498 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002499}
2500
Douglas Gregora9b06d42010-11-09 06:24:54 +00002501void clang_getSpellingLocation(CXSourceLocation location,
2502 CXFile *file,
2503 unsigned *line,
2504 unsigned *column,
2505 unsigned *offset) {
2506 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2507
2508 if (!location.ptr_data[0] || Loc.isInvalid()) {
2509 if (file)
2510 *file = 0;
2511 if (line)
2512 *line = 0;
2513 if (column)
2514 *column = 0;
2515 if (offset)
2516 *offset = 0;
2517 return;
2518 }
2519
2520 const SourceManager &SM =
2521 *static_cast<const SourceManager*>(location.ptr_data[0]);
2522 SourceLocation SpellLoc = Loc;
2523 if (SpellLoc.isMacroID()) {
2524 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2525 if (SimpleSpellingLoc.isFileID() &&
2526 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2527 SpellLoc = SimpleSpellingLoc;
2528 else
2529 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2530 }
2531
2532 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2533 FileID FID = LocInfo.first;
2534 unsigned FileOffset = LocInfo.second;
2535
2536 if (file)
2537 *file = (void *)SM.getFileEntryForID(FID);
2538 if (line)
2539 *line = SM.getLineNumber(FID, FileOffset);
2540 if (column)
2541 *column = SM.getColumnNumber(FID, FileOffset);
2542 if (offset)
2543 *offset = FileOffset;
2544}
2545
Douglas Gregor1db19de2010-01-19 21:36:55 +00002546CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002547 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002548 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002549 return Result;
2550}
2551
2552CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002553 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002554 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002555 return Result;
2556}
2557
Douglas Gregorb9790342010-01-22 21:44:22 +00002558} // end: extern "C"
2559
Douglas Gregor1db19de2010-01-19 21:36:55 +00002560//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002561// CXFile Operations.
2562//===----------------------------------------------------------------------===//
2563
2564extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002565CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002566 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002567 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002568
Steve Naroff88145032009-10-27 14:35:18 +00002569 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002570 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002571}
2572
2573time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002574 if (!SFile)
2575 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002576
Steve Naroff88145032009-10-27 14:35:18 +00002577 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2578 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002579}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002580
Douglas Gregorb9790342010-01-22 21:44:22 +00002581CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2582 if (!tu)
2583 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002584
Douglas Gregorb9790342010-01-22 21:44:22 +00002585 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002586
Douglas Gregorb9790342010-01-22 21:44:22 +00002587 FileManager &FMgr = CXXUnit->getFileManager();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002588 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2589 CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002590 return const_cast<FileEntry *>(File);
2591}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002592
Ted Kremenekfb480492010-01-13 21:46:36 +00002593} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002594
Ted Kremenekfb480492010-01-13 21:46:36 +00002595//===----------------------------------------------------------------------===//
2596// CXCursor Operations.
2597//===----------------------------------------------------------------------===//
2598
Ted Kremenekfb480492010-01-13 21:46:36 +00002599static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002600 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2601 return getDeclFromExpr(CE->getSubExpr());
2602
Ted Kremenekfb480492010-01-13 21:46:36 +00002603 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2604 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002605 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2606 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002607 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2608 return ME->getMemberDecl();
2609 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2610 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002611 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2612 return PRE->getProperty();
2613
Ted Kremenekfb480492010-01-13 21:46:36 +00002614 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2615 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002616 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2617 if (!CE->isElidable())
2618 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002619 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2620 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002621
Douglas Gregordb1314e2010-10-01 21:11:22 +00002622 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2623 return PE->getProtocol();
2624
Ted Kremenekfb480492010-01-13 21:46:36 +00002625 return 0;
2626}
2627
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002628static SourceLocation getLocationFromExpr(Expr *E) {
2629 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2630 return /*FIXME:*/Msg->getLeftLoc();
2631 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2632 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002633 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2634 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002635 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2636 return Member->getMemberLoc();
2637 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2638 return Ivar->getLocation();
2639 return E->getLocStart();
2640}
2641
Ted Kremenekfb480492010-01-13 21:46:36 +00002642extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002643
2644unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002645 CXCursorVisitor visitor,
2646 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002647 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002648
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002649 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2650 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002651 return CursorVis.VisitChildren(parent);
2652}
2653
David Chisnall3387c652010-11-03 14:12:26 +00002654#ifndef __has_feature
2655#define __has_feature(x) 0
2656#endif
2657#if __has_feature(blocks)
2658typedef enum CXChildVisitResult
2659 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2660
2661static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2662 CXClientData client_data) {
2663 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2664 return block(cursor, parent);
2665}
2666#else
2667// If we are compiled with a compiler that doesn't have native blocks support,
2668// define and call the block manually, so the
2669typedef struct _CXChildVisitResult
2670{
2671 void *isa;
2672 int flags;
2673 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002674 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2675 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002676} *CXCursorVisitorBlock;
2677
2678static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2679 CXClientData client_data) {
2680 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2681 return block->invoke(block, cursor, parent);
2682}
2683#endif
2684
2685
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002686unsigned clang_visitChildrenWithBlock(CXCursor parent,
2687 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002688 return clang_visitChildren(parent, visitWithBlock, block);
2689}
2690
Douglas Gregor78205d42010-01-20 21:45:58 +00002691static CXString getDeclSpelling(Decl *D) {
2692 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2693 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002694 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002695
Douglas Gregor78205d42010-01-20 21:45:58 +00002696 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002697 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002698
Douglas Gregor78205d42010-01-20 21:45:58 +00002699 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2700 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2701 // and returns different names. NamedDecl returns the class name and
2702 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002703 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002704
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002705 if (isa<UsingDirectiveDecl>(D))
2706 return createCXString("");
2707
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002708 llvm::SmallString<1024> S;
2709 llvm::raw_svector_ostream os(S);
2710 ND->printName(os);
2711
2712 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002713}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002714
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002715CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002716 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002717 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002718
Steve Narofff334b4e2009-09-02 18:26:48 +00002719 if (clang_isReference(C.kind)) {
2720 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002721 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002722 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002723 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002724 }
2725 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002726 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002727 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002728 }
2729 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002730 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002731 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002732 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002733 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002734 case CXCursor_CXXBaseSpecifier: {
2735 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2736 return createCXString(B->getType().getAsString());
2737 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002738 case CXCursor_TypeRef: {
2739 TypeDecl *Type = getCursorTypeRef(C).first;
2740 assert(Type && "Missing type decl");
2741
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002742 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2743 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002744 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002745 case CXCursor_TemplateRef: {
2746 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002747 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002748
2749 return createCXString(Template->getNameAsString());
2750 }
Douglas Gregor69319002010-08-31 23:48:11 +00002751
2752 case CXCursor_NamespaceRef: {
2753 NamedDecl *NS = getCursorNamespaceRef(C).first;
2754 assert(NS && "Missing namespace decl");
2755
2756 return createCXString(NS->getNameAsString());
2757 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002758
Douglas Gregora67e03f2010-09-09 21:42:20 +00002759 case CXCursor_MemberRef: {
2760 FieldDecl *Field = getCursorMemberRef(C).first;
2761 assert(Field && "Missing member decl");
2762
2763 return createCXString(Field->getNameAsString());
2764 }
2765
Douglas Gregor36897b02010-09-10 00:22:18 +00002766 case CXCursor_LabelRef: {
2767 LabelStmt *Label = getCursorLabelRef(C).first;
2768 assert(Label && "Missing label");
2769
2770 return createCXString(Label->getID()->getName());
2771 }
2772
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002773 case CXCursor_OverloadedDeclRef: {
2774 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2775 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2776 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2777 return createCXString(ND->getNameAsString());
2778 return createCXString("");
2779 }
2780 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2781 return createCXString(E->getName().getAsString());
2782 OverloadedTemplateStorage *Ovl
2783 = Storage.get<OverloadedTemplateStorage*>();
2784 if (Ovl->size() == 0)
2785 return createCXString("");
2786 return createCXString((*Ovl->begin())->getNameAsString());
2787 }
2788
Daniel Dunbaracca7252009-11-30 20:42:49 +00002789 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002790 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002791 }
2792 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002793
2794 if (clang_isExpression(C.kind)) {
2795 Decl *D = getDeclFromExpr(getCursorExpr(C));
2796 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002797 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002798 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002799 }
2800
Douglas Gregor36897b02010-09-10 00:22:18 +00002801 if (clang_isStatement(C.kind)) {
2802 Stmt *S = getCursorStmt(C);
2803 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2804 return createCXString(Label->getID()->getName());
2805
2806 return createCXString("");
2807 }
2808
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002809 if (C.kind == CXCursor_MacroInstantiation)
2810 return createCXString(getCursorMacroInstantiation(C)->getName()
2811 ->getNameStart());
2812
Douglas Gregor572feb22010-03-18 18:04:21 +00002813 if (C.kind == CXCursor_MacroDefinition)
2814 return createCXString(getCursorMacroDefinition(C)->getName()
2815 ->getNameStart());
2816
Douglas Gregorecdcb882010-10-20 22:00:55 +00002817 if (C.kind == CXCursor_InclusionDirective)
2818 return createCXString(getCursorInclusionDirective(C)->getFileName());
2819
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002820 if (clang_isDeclaration(C.kind))
2821 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002822
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002823 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002824}
2825
Douglas Gregor358559d2010-10-02 22:49:11 +00002826CXString clang_getCursorDisplayName(CXCursor C) {
2827 if (!clang_isDeclaration(C.kind))
2828 return clang_getCursorSpelling(C);
2829
2830 Decl *D = getCursorDecl(C);
2831 if (!D)
2832 return createCXString("");
2833
2834 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2835 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2836 D = FunTmpl->getTemplatedDecl();
2837
2838 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2839 llvm::SmallString<64> Str;
2840 llvm::raw_svector_ostream OS(Str);
2841 OS << Function->getNameAsString();
2842 if (Function->getPrimaryTemplate())
2843 OS << "<>";
2844 OS << "(";
2845 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2846 if (I)
2847 OS << ", ";
2848 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2849 }
2850
2851 if (Function->isVariadic()) {
2852 if (Function->getNumParams())
2853 OS << ", ";
2854 OS << "...";
2855 }
2856 OS << ")";
2857 return createCXString(OS.str());
2858 }
2859
2860 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2861 llvm::SmallString<64> Str;
2862 llvm::raw_svector_ostream OS(Str);
2863 OS << ClassTemplate->getNameAsString();
2864 OS << "<";
2865 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2866 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2867 if (I)
2868 OS << ", ";
2869
2870 NamedDecl *Param = Params->getParam(I);
2871 if (Param->getIdentifier()) {
2872 OS << Param->getIdentifier()->getName();
2873 continue;
2874 }
2875
2876 // There is no parameter name, which makes this tricky. Try to come up
2877 // with something useful that isn't too long.
2878 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2879 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2880 else if (NonTypeTemplateParmDecl *NTTP
2881 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2882 OS << NTTP->getType().getAsString(Policy);
2883 else
2884 OS << "template<...> class";
2885 }
2886
2887 OS << ">";
2888 return createCXString(OS.str());
2889 }
2890
2891 if (ClassTemplateSpecializationDecl *ClassSpec
2892 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2893 // If the type was explicitly written, use that.
2894 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2895 return createCXString(TSInfo->getType().getAsString(Policy));
2896
2897 llvm::SmallString<64> Str;
2898 llvm::raw_svector_ostream OS(Str);
2899 OS << ClassSpec->getNameAsString();
2900 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002901 ClassSpec->getTemplateArgs().data(),
2902 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002903 Policy);
2904 return createCXString(OS.str());
2905 }
2906
2907 return clang_getCursorSpelling(C);
2908}
2909
Ted Kremeneke68fff62010-02-17 00:41:32 +00002910CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002911 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002912 case CXCursor_FunctionDecl:
2913 return createCXString("FunctionDecl");
2914 case CXCursor_TypedefDecl:
2915 return createCXString("TypedefDecl");
2916 case CXCursor_EnumDecl:
2917 return createCXString("EnumDecl");
2918 case CXCursor_EnumConstantDecl:
2919 return createCXString("EnumConstantDecl");
2920 case CXCursor_StructDecl:
2921 return createCXString("StructDecl");
2922 case CXCursor_UnionDecl:
2923 return createCXString("UnionDecl");
2924 case CXCursor_ClassDecl:
2925 return createCXString("ClassDecl");
2926 case CXCursor_FieldDecl:
2927 return createCXString("FieldDecl");
2928 case CXCursor_VarDecl:
2929 return createCXString("VarDecl");
2930 case CXCursor_ParmDecl:
2931 return createCXString("ParmDecl");
2932 case CXCursor_ObjCInterfaceDecl:
2933 return createCXString("ObjCInterfaceDecl");
2934 case CXCursor_ObjCCategoryDecl:
2935 return createCXString("ObjCCategoryDecl");
2936 case CXCursor_ObjCProtocolDecl:
2937 return createCXString("ObjCProtocolDecl");
2938 case CXCursor_ObjCPropertyDecl:
2939 return createCXString("ObjCPropertyDecl");
2940 case CXCursor_ObjCIvarDecl:
2941 return createCXString("ObjCIvarDecl");
2942 case CXCursor_ObjCInstanceMethodDecl:
2943 return createCXString("ObjCInstanceMethodDecl");
2944 case CXCursor_ObjCClassMethodDecl:
2945 return createCXString("ObjCClassMethodDecl");
2946 case CXCursor_ObjCImplementationDecl:
2947 return createCXString("ObjCImplementationDecl");
2948 case CXCursor_ObjCCategoryImplDecl:
2949 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002950 case CXCursor_CXXMethod:
2951 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002952 case CXCursor_UnexposedDecl:
2953 return createCXString("UnexposedDecl");
2954 case CXCursor_ObjCSuperClassRef:
2955 return createCXString("ObjCSuperClassRef");
2956 case CXCursor_ObjCProtocolRef:
2957 return createCXString("ObjCProtocolRef");
2958 case CXCursor_ObjCClassRef:
2959 return createCXString("ObjCClassRef");
2960 case CXCursor_TypeRef:
2961 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002962 case CXCursor_TemplateRef:
2963 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002964 case CXCursor_NamespaceRef:
2965 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002966 case CXCursor_MemberRef:
2967 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002968 case CXCursor_LabelRef:
2969 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002970 case CXCursor_OverloadedDeclRef:
2971 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002972 case CXCursor_UnexposedExpr:
2973 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002974 case CXCursor_BlockExpr:
2975 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002976 case CXCursor_DeclRefExpr:
2977 return createCXString("DeclRefExpr");
2978 case CXCursor_MemberRefExpr:
2979 return createCXString("MemberRefExpr");
2980 case CXCursor_CallExpr:
2981 return createCXString("CallExpr");
2982 case CXCursor_ObjCMessageExpr:
2983 return createCXString("ObjCMessageExpr");
2984 case CXCursor_UnexposedStmt:
2985 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002986 case CXCursor_LabelStmt:
2987 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002988 case CXCursor_InvalidFile:
2989 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002990 case CXCursor_InvalidCode:
2991 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002992 case CXCursor_NoDeclFound:
2993 return createCXString("NoDeclFound");
2994 case CXCursor_NotImplemented:
2995 return createCXString("NotImplemented");
2996 case CXCursor_TranslationUnit:
2997 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002998 case CXCursor_UnexposedAttr:
2999 return createCXString("UnexposedAttr");
3000 case CXCursor_IBActionAttr:
3001 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003002 case CXCursor_IBOutletAttr:
3003 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003004 case CXCursor_IBOutletCollectionAttr:
3005 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003006 case CXCursor_PreprocessingDirective:
3007 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003008 case CXCursor_MacroDefinition:
3009 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003010 case CXCursor_MacroInstantiation:
3011 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003012 case CXCursor_InclusionDirective:
3013 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003014 case CXCursor_Namespace:
3015 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003016 case CXCursor_LinkageSpec:
3017 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003018 case CXCursor_CXXBaseSpecifier:
3019 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003020 case CXCursor_Constructor:
3021 return createCXString("CXXConstructor");
3022 case CXCursor_Destructor:
3023 return createCXString("CXXDestructor");
3024 case CXCursor_ConversionFunction:
3025 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003026 case CXCursor_TemplateTypeParameter:
3027 return createCXString("TemplateTypeParameter");
3028 case CXCursor_NonTypeTemplateParameter:
3029 return createCXString("NonTypeTemplateParameter");
3030 case CXCursor_TemplateTemplateParameter:
3031 return createCXString("TemplateTemplateParameter");
3032 case CXCursor_FunctionTemplate:
3033 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003034 case CXCursor_ClassTemplate:
3035 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003036 case CXCursor_ClassTemplatePartialSpecialization:
3037 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003038 case CXCursor_NamespaceAlias:
3039 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003040 case CXCursor_UsingDirective:
3041 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003042 case CXCursor_UsingDeclaration:
3043 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003044 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003045
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003046 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003047 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00003048}
Steve Naroff89922f82009-08-31 00:59:03 +00003049
Ted Kremeneke68fff62010-02-17 00:41:32 +00003050enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3051 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003052 CXClientData client_data) {
3053 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003054
3055 // If our current best cursor is the construction of a temporary object,
3056 // don't replace that cursor with a type reference, because we want
3057 // clang_getCursor() to point at the constructor.
3058 if (clang_isExpression(BestCursor->kind) &&
3059 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3060 cursor.kind == CXCursor_TypeRef)
3061 return CXChildVisit_Recurse;
3062
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003063 *BestCursor = cursor;
3064 return CXChildVisit_Recurse;
3065}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003066
Douglas Gregorb9790342010-01-22 21:44:22 +00003067CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3068 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003069 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003070
Douglas Gregorb9790342010-01-22 21:44:22 +00003071 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003072 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3073
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003074 // Translate the given source location to make it point at the beginning of
3075 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003076 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003077
3078 // Guard against an invalid SourceLocation, or we may assert in one
3079 // of the following calls.
3080 if (SLoc.isInvalid())
3081 return clang_getNullCursor();
3082
Douglas Gregor40749ee2010-11-03 00:35:38 +00003083 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003084 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3085 CXXUnit->getASTContext().getLangOptions());
3086
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003087 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3088 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003089 // FIXME: Would be great to have a "hint" cursor, then walk from that
3090 // hint cursor upward until we find a cursor whose source range encloses
3091 // the region of interest, rather than starting from the translation unit.
3092 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00003093 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003094 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003095 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003096 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003097
3098 if (Logging) {
3099 CXFile SearchFile;
3100 unsigned SearchLine, SearchColumn;
3101 CXFile ResultFile;
3102 unsigned ResultLine, ResultColumn;
3103 CXString SearchFileName, ResultFileName, KindSpelling;
3104 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3105
3106 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3107 0);
3108 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3109 &ResultColumn, 0);
3110 SearchFileName = clang_getFileName(SearchFile);
3111 ResultFileName = clang_getFileName(ResultFile);
3112 KindSpelling = clang_getCursorKindSpelling(Result.kind);
3113 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n",
3114 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3115 clang_getCString(KindSpelling),
3116 clang_getCString(ResultFileName), ResultLine, ResultColumn);
3117 clang_disposeString(SearchFileName);
3118 clang_disposeString(ResultFileName);
3119 clang_disposeString(KindSpelling);
3120 }
3121
Ted Kremeneke68fff62010-02-17 00:41:32 +00003122 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003123}
3124
Ted Kremenek73885552009-11-17 19:28:59 +00003125CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003126 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003127}
3128
3129unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003130 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003131}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003132
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003133unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003134 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3135}
3136
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003137unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003138 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3139}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003140
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003141unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003142 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3143}
3144
Douglas Gregor97b98722010-01-19 23:20:36 +00003145unsigned clang_isExpression(enum CXCursorKind K) {
3146 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3147}
3148
3149unsigned clang_isStatement(enum CXCursorKind K) {
3150 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3151}
3152
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003153unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3154 return K == CXCursor_TranslationUnit;
3155}
3156
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003157unsigned clang_isPreprocessing(enum CXCursorKind K) {
3158 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3159}
3160
Ted Kremenekad6eff62010-03-08 21:17:29 +00003161unsigned clang_isUnexposed(enum CXCursorKind K) {
3162 switch (K) {
3163 case CXCursor_UnexposedDecl:
3164 case CXCursor_UnexposedExpr:
3165 case CXCursor_UnexposedStmt:
3166 case CXCursor_UnexposedAttr:
3167 return true;
3168 default:
3169 return false;
3170 }
3171}
3172
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003173CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003174 return C.kind;
3175}
3176
Douglas Gregor98258af2010-01-18 22:46:11 +00003177CXSourceLocation clang_getCursorLocation(CXCursor C) {
3178 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003179 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003180 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003181 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3182 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003183 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003184 }
3185
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003186 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003187 std::pair<ObjCProtocolDecl *, SourceLocation> P
3188 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003189 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003190 }
3191
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003192 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003193 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3194 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003195 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003196 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003197
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003198 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003199 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003200 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003201 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003202
3203 case CXCursor_TemplateRef: {
3204 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3205 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3206 }
3207
Douglas Gregor69319002010-08-31 23:48:11 +00003208 case CXCursor_NamespaceRef: {
3209 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3210 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3211 }
3212
Douglas Gregora67e03f2010-09-09 21:42:20 +00003213 case CXCursor_MemberRef: {
3214 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3215 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3216 }
3217
Ted Kremenek3064ef92010-08-27 21:34:58 +00003218 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003219 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3220 if (!BaseSpec)
3221 return clang_getNullLocation();
3222
3223 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3224 return cxloc::translateSourceLocation(getCursorContext(C),
3225 TSInfo->getTypeLoc().getBeginLoc());
3226
3227 return cxloc::translateSourceLocation(getCursorContext(C),
3228 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003229 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003230
Douglas Gregor36897b02010-09-10 00:22:18 +00003231 case CXCursor_LabelRef: {
3232 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3233 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3234 }
3235
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003236 case CXCursor_OverloadedDeclRef:
3237 return cxloc::translateSourceLocation(getCursorContext(C),
3238 getCursorOverloadedDeclRef(C).second);
3239
Douglas Gregorf46034a2010-01-18 23:41:10 +00003240 default:
3241 // FIXME: Need a way to enumerate all non-reference cases.
3242 llvm_unreachable("Missed a reference kind");
3243 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003244 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003245
3246 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003247 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003248 getLocationFromExpr(getCursorExpr(C)));
3249
Douglas Gregor36897b02010-09-10 00:22:18 +00003250 if (clang_isStatement(C.kind))
3251 return cxloc::translateSourceLocation(getCursorContext(C),
3252 getCursorStmt(C)->getLocStart());
3253
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003254 if (C.kind == CXCursor_PreprocessingDirective) {
3255 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3256 return cxloc::translateSourceLocation(getCursorContext(C), L);
3257 }
Douglas Gregor48072312010-03-18 15:23:44 +00003258
3259 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003260 SourceLocation L
3261 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003262 return cxloc::translateSourceLocation(getCursorContext(C), L);
3263 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003264
3265 if (C.kind == CXCursor_MacroDefinition) {
3266 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3267 return cxloc::translateSourceLocation(getCursorContext(C), L);
3268 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003269
3270 if (C.kind == CXCursor_InclusionDirective) {
3271 SourceLocation L
3272 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3273 return cxloc::translateSourceLocation(getCursorContext(C), L);
3274 }
3275
Ted Kremenek9a700d22010-05-12 06:16:13 +00003276 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003277 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003278
Douglas Gregorf46034a2010-01-18 23:41:10 +00003279 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003280 SourceLocation Loc = D->getLocation();
3281 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3282 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003283 // FIXME: Multiple variables declared in a single declaration
3284 // currently lack the information needed to correctly determine their
3285 // ranges when accounting for the type-specifier. We use context
3286 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3287 // and if so, whether it is the first decl.
3288 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3289 if (!cxcursor::isFirstInDeclGroup(C))
3290 Loc = VD->getLocation();
3291 }
3292
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003293 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003294}
Douglas Gregora7bde202010-01-19 00:34:46 +00003295
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003296} // end extern "C"
3297
3298static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003299 if (clang_isReference(C.kind)) {
3300 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003301 case CXCursor_ObjCSuperClassRef:
3302 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003303
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003304 case CXCursor_ObjCProtocolRef:
3305 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003306
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003307 case CXCursor_ObjCClassRef:
3308 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003309
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003310 case CXCursor_TypeRef:
3311 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003312
3313 case CXCursor_TemplateRef:
3314 return getCursorTemplateRef(C).second;
3315
Douglas Gregor69319002010-08-31 23:48:11 +00003316 case CXCursor_NamespaceRef:
3317 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003318
3319 case CXCursor_MemberRef:
3320 return getCursorMemberRef(C).second;
3321
Ted Kremenek3064ef92010-08-27 21:34:58 +00003322 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003323 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003324
Douglas Gregor36897b02010-09-10 00:22:18 +00003325 case CXCursor_LabelRef:
3326 return getCursorLabelRef(C).second;
3327
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003328 case CXCursor_OverloadedDeclRef:
3329 return getCursorOverloadedDeclRef(C).second;
3330
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003331 default:
3332 // FIXME: Need a way to enumerate all non-reference cases.
3333 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003334 }
3335 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003336
3337 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003338 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003339
3340 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003341 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003342
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003343 if (C.kind == CXCursor_PreprocessingDirective)
3344 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003345
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003346 if (C.kind == CXCursor_MacroInstantiation)
3347 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003348
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003349 if (C.kind == CXCursor_MacroDefinition)
3350 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003351
3352 if (C.kind == CXCursor_InclusionDirective)
3353 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3354
Ted Kremenek007a7c92010-11-01 23:26:51 +00003355 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3356 Decl *D = cxcursor::getCursorDecl(C);
3357 SourceRange R = D->getSourceRange();
3358 // FIXME: Multiple variables declared in a single declaration
3359 // currently lack the information needed to correctly determine their
3360 // ranges when accounting for the type-specifier. We use context
3361 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3362 // and if so, whether it is the first decl.
3363 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3364 if (!cxcursor::isFirstInDeclGroup(C))
3365 R.setBegin(VD->getLocation());
3366 }
3367 return R;
3368 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003369 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003370
3371extern "C" {
3372
3373CXSourceRange clang_getCursorExtent(CXCursor C) {
3374 SourceRange R = getRawCursorExtent(C);
3375 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003376 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003377
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003378 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003379}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003380
3381CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003382 if (clang_isInvalid(C.kind))
3383 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003384
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003385 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003386 if (clang_isDeclaration(C.kind)) {
3387 Decl *D = getCursorDecl(C);
3388 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3389 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3390 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3391 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3392 if (ObjCForwardProtocolDecl *Protocols
3393 = dyn_cast<ObjCForwardProtocolDecl>(D))
3394 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3395
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003396 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003397 }
3398
Douglas Gregor97b98722010-01-19 23:20:36 +00003399 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003400 Expr *E = getCursorExpr(C);
3401 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003402 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003403 return MakeCXCursor(D, CXXUnit);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003404
3405 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3406 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3407
Douglas Gregor97b98722010-01-19 23:20:36 +00003408 return clang_getNullCursor();
3409 }
3410
Douglas Gregor36897b02010-09-10 00:22:18 +00003411 if (clang_isStatement(C.kind)) {
3412 Stmt *S = getCursorStmt(C);
3413 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3414 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3415 getCursorASTUnit(C));
3416
3417 return clang_getNullCursor();
3418 }
3419
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003420 if (C.kind == CXCursor_MacroInstantiation) {
3421 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3422 return MakeMacroDefinitionCursor(Def, CXXUnit);
3423 }
3424
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003425 if (!clang_isReference(C.kind))
3426 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003427
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003428 switch (C.kind) {
3429 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003430 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003431
3432 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003433 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003434
3435 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003436 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003437
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003438 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003439 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00003440
3441 case CXCursor_TemplateRef:
3442 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3443
Douglas Gregor69319002010-08-31 23:48:11 +00003444 case CXCursor_NamespaceRef:
3445 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3446
Douglas Gregora67e03f2010-09-09 21:42:20 +00003447 case CXCursor_MemberRef:
3448 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3449
Ted Kremenek3064ef92010-08-27 21:34:58 +00003450 case CXCursor_CXXBaseSpecifier: {
3451 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3452 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3453 CXXUnit));
3454 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003455
Douglas Gregor36897b02010-09-10 00:22:18 +00003456 case CXCursor_LabelRef:
3457 // FIXME: We end up faking the "parent" declaration here because we
3458 // don't want to make CXCursor larger.
3459 return MakeCXCursor(getCursorLabelRef(C).first,
3460 CXXUnit->getASTContext().getTranslationUnitDecl(),
3461 CXXUnit);
3462
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003463 case CXCursor_OverloadedDeclRef:
3464 return C;
3465
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003466 default:
3467 // We would prefer to enumerate all non-reference cursor kinds here.
3468 llvm_unreachable("Unhandled reference cursor kind");
3469 break;
3470 }
3471 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003472
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003473 return clang_getNullCursor();
3474}
3475
Douglas Gregorb6998662010-01-19 19:34:47 +00003476CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003477 if (clang_isInvalid(C.kind))
3478 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003479
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003480 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003481
Douglas Gregorb6998662010-01-19 19:34:47 +00003482 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003483 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003484 C = clang_getCursorReferenced(C);
3485 WasReference = true;
3486 }
3487
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003488 if (C.kind == CXCursor_MacroInstantiation)
3489 return clang_getCursorReferenced(C);
3490
Douglas Gregorb6998662010-01-19 19:34:47 +00003491 if (!clang_isDeclaration(C.kind))
3492 return clang_getNullCursor();
3493
3494 Decl *D = getCursorDecl(C);
3495 if (!D)
3496 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003497
Douglas Gregorb6998662010-01-19 19:34:47 +00003498 switch (D->getKind()) {
3499 // Declaration kinds that don't really separate the notions of
3500 // declaration and definition.
3501 case Decl::Namespace:
3502 case Decl::Typedef:
3503 case Decl::TemplateTypeParm:
3504 case Decl::EnumConstant:
3505 case Decl::Field:
3506 case Decl::ObjCIvar:
3507 case Decl::ObjCAtDefsField:
3508 case Decl::ImplicitParam:
3509 case Decl::ParmVar:
3510 case Decl::NonTypeTemplateParm:
3511 case Decl::TemplateTemplateParm:
3512 case Decl::ObjCCategoryImpl:
3513 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003514 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003515 case Decl::LinkageSpec:
3516 case Decl::ObjCPropertyImpl:
3517 case Decl::FileScopeAsm:
3518 case Decl::StaticAssert:
3519 case Decl::Block:
3520 return C;
3521
3522 // Declaration kinds that don't make any sense here, but are
3523 // nonetheless harmless.
3524 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003525 break;
3526
3527 // Declaration kinds for which the definition is not resolvable.
3528 case Decl::UnresolvedUsingTypename:
3529 case Decl::UnresolvedUsingValue:
3530 break;
3531
3532 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003533 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3534 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003535
3536 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003537 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003538
3539 case Decl::Enum:
3540 case Decl::Record:
3541 case Decl::CXXRecord:
3542 case Decl::ClassTemplateSpecialization:
3543 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003544 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003545 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003546 return clang_getNullCursor();
3547
3548 case Decl::Function:
3549 case Decl::CXXMethod:
3550 case Decl::CXXConstructor:
3551 case Decl::CXXDestructor:
3552 case Decl::CXXConversion: {
3553 const FunctionDecl *Def = 0;
3554 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003555 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003556 return clang_getNullCursor();
3557 }
3558
3559 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003560 // Ask the variable if it has a definition.
3561 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3562 return MakeCXCursor(Def, CXXUnit);
3563 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003564 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003565
Douglas Gregorb6998662010-01-19 19:34:47 +00003566 case Decl::FunctionTemplate: {
3567 const FunctionDecl *Def = 0;
3568 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003569 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003570 return clang_getNullCursor();
3571 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003572
Douglas Gregorb6998662010-01-19 19:34:47 +00003573 case Decl::ClassTemplate: {
3574 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003575 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003576 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003577 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003578 return clang_getNullCursor();
3579 }
3580
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003581 case Decl::Using:
3582 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3583 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003584
3585 case Decl::UsingShadow:
3586 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003587 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003588 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003589
3590 case Decl::ObjCMethod: {
3591 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3592 if (Method->isThisDeclarationADefinition())
3593 return C;
3594
3595 // Dig out the method definition in the associated
3596 // @implementation, if we have it.
3597 // FIXME: The ASTs should make finding the definition easier.
3598 if (ObjCInterfaceDecl *Class
3599 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3600 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3601 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3602 Method->isInstanceMethod()))
3603 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003604 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003605
3606 return clang_getNullCursor();
3607 }
3608
3609 case Decl::ObjCCategory:
3610 if (ObjCCategoryImplDecl *Impl
3611 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003612 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003613 return clang_getNullCursor();
3614
3615 case Decl::ObjCProtocol:
3616 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3617 return C;
3618 return clang_getNullCursor();
3619
3620 case Decl::ObjCInterface:
3621 // There are two notions of a "definition" for an Objective-C
3622 // class: the interface and its implementation. When we resolved a
3623 // reference to an Objective-C class, produce the @interface as
3624 // the definition; when we were provided with the interface,
3625 // produce the @implementation as the definition.
3626 if (WasReference) {
3627 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3628 return C;
3629 } else if (ObjCImplementationDecl *Impl
3630 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003631 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003632 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003633
Douglas Gregorb6998662010-01-19 19:34:47 +00003634 case Decl::ObjCProperty:
3635 // FIXME: We don't really know where to find the
3636 // ObjCPropertyImplDecls that implement this property.
3637 return clang_getNullCursor();
3638
3639 case Decl::ObjCCompatibleAlias:
3640 if (ObjCInterfaceDecl *Class
3641 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3642 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003643 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003644
Douglas Gregorb6998662010-01-19 19:34:47 +00003645 return clang_getNullCursor();
3646
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003647 case Decl::ObjCForwardProtocol:
3648 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3649 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003650
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003651 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003652 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003653 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003654
3655 case Decl::Friend:
3656 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003657 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003658 return clang_getNullCursor();
3659
3660 case Decl::FriendTemplate:
3661 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003662 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003663 return clang_getNullCursor();
3664 }
3665
3666 return clang_getNullCursor();
3667}
3668
3669unsigned clang_isCursorDefinition(CXCursor C) {
3670 if (!clang_isDeclaration(C.kind))
3671 return 0;
3672
3673 return clang_getCursorDefinition(C) == C;
3674}
3675
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003676unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003677 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003678 return 0;
3679
3680 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3681 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3682 return E->getNumDecls();
3683
3684 if (OverloadedTemplateStorage *S
3685 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3686 return S->size();
3687
3688 Decl *D = Storage.get<Decl*>();
3689 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003690 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003691 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3692 return Classes->size();
3693 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3694 return Protocols->protocol_size();
3695
3696 return 0;
3697}
3698
3699CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003700 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003701 return clang_getNullCursor();
3702
3703 if (index >= clang_getNumOverloadedDecls(cursor))
3704 return clang_getNullCursor();
3705
3706 ASTUnit *Unit = getCursorASTUnit(cursor);
3707 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3708 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3709 return MakeCXCursor(E->decls_begin()[index], Unit);
3710
3711 if (OverloadedTemplateStorage *S
3712 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3713 return MakeCXCursor(S->begin()[index], Unit);
3714
3715 Decl *D = Storage.get<Decl*>();
3716 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3717 // FIXME: This is, unfortunately, linear time.
3718 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3719 std::advance(Pos, index);
3720 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3721 }
3722
3723 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3724 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3725
3726 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3727 return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3728
3729 return clang_getNullCursor();
3730}
3731
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003732void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003733 const char **startBuf,
3734 const char **endBuf,
3735 unsigned *startLine,
3736 unsigned *startColumn,
3737 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003738 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003739 assert(getCursorDecl(C) && "CXCursor has null decl");
3740 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003741 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3742 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003743
Steve Naroff4ade6d62009-09-23 17:52:52 +00003744 SourceManager &SM = FD->getASTContext().getSourceManager();
3745 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3746 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3747 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3748 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3749 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3750 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3751}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003752
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003753void clang_enableStackTraces(void) {
3754 llvm::sys::PrintStackTraceOnErrorSignal();
3755}
3756
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003757void clang_executeOnThread(void (*fn)(void*), void *user_data,
3758 unsigned stack_size) {
3759 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3760}
3761
Ted Kremenekfb480492010-01-13 21:46:36 +00003762} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003763
Ted Kremenekfb480492010-01-13 21:46:36 +00003764//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003765// Token-based Operations.
3766//===----------------------------------------------------------------------===//
3767
3768/* CXToken layout:
3769 * int_data[0]: a CXTokenKind
3770 * int_data[1]: starting token location
3771 * int_data[2]: token length
3772 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003773 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003774 * otherwise unused.
3775 */
3776extern "C" {
3777
3778CXTokenKind clang_getTokenKind(CXToken CXTok) {
3779 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3780}
3781
3782CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3783 switch (clang_getTokenKind(CXTok)) {
3784 case CXToken_Identifier:
3785 case CXToken_Keyword:
3786 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003787 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3788 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003789
3790 case CXToken_Literal: {
3791 // We have stashed the starting pointer in the ptr_data field. Use it.
3792 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003793 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003794 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003795
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003796 case CXToken_Punctuation:
3797 case CXToken_Comment:
3798 break;
3799 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003800
3801 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003802 // deconstructing the source location.
3803 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3804 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003805 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003806
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003807 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3808 std::pair<FileID, unsigned> LocInfo
3809 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003810 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003811 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003812 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3813 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003814 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003815
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003816 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003817}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003818
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003819CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3820 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3821 if (!CXXUnit)
3822 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003823
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003824 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3825 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3826}
3827
3828CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3829 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003830 if (!CXXUnit)
3831 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003832
3833 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003834 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3835}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003836
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003837void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3838 CXToken **Tokens, unsigned *NumTokens) {
3839 if (Tokens)
3840 *Tokens = 0;
3841 if (NumTokens)
3842 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003843
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003844 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3845 if (!CXXUnit || !Tokens || !NumTokens)
3846 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003847
Douglas Gregorbdf60622010-03-05 21:16:25 +00003848 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3849
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003850 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003851 if (R.isInvalid())
3852 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003853
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003854 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3855 std::pair<FileID, unsigned> BeginLocInfo
3856 = SourceMgr.getDecomposedLoc(R.getBegin());
3857 std::pair<FileID, unsigned> EndLocInfo
3858 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003859
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003860 // Cannot tokenize across files.
3861 if (BeginLocInfo.first != EndLocInfo.first)
3862 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003863
3864 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003865 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003866 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003867 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003868 if (Invalid)
3869 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003870
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003871 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3872 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003873 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003874 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003875
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003876 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003877 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003878 llvm::SmallVector<CXToken, 32> CXTokens;
3879 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003880 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003881 do {
3882 // Lex the next token
3883 Lex.LexFromRawLexer(Tok);
3884 if (Tok.is(tok::eof))
3885 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003886
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003887 // Initialize the CXToken.
3888 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003889
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003890 // - Common fields
3891 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3892 CXTok.int_data[2] = Tok.getLength();
3893 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003894
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003895 // - Kind-specific fields
3896 if (Tok.isLiteral()) {
3897 CXTok.int_data[0] = CXToken_Literal;
3898 CXTok.ptr_data = (void *)Tok.getLiteralData();
3899 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003900 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003901 std::pair<FileID, unsigned> LocInfo
3902 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003903 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003904 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003905 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3906 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003907 return;
3908
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003909 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003910 IdentifierInfo *II
3911 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003912
David Chisnall096428b2010-10-13 21:44:48 +00003913 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003914 CXTok.int_data[0] = CXToken_Keyword;
3915 }
3916 else {
3917 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3918 CXToken_Identifier
3919 : CXToken_Keyword;
3920 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003921 CXTok.ptr_data = II;
3922 } else if (Tok.is(tok::comment)) {
3923 CXTok.int_data[0] = CXToken_Comment;
3924 CXTok.ptr_data = 0;
3925 } else {
3926 CXTok.int_data[0] = CXToken_Punctuation;
3927 CXTok.ptr_data = 0;
3928 }
3929 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003930 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003931 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003932
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003933 if (CXTokens.empty())
3934 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003935
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003936 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3937 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3938 *NumTokens = CXTokens.size();
3939}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003940
Ted Kremenek6db61092010-05-05 00:55:15 +00003941void clang_disposeTokens(CXTranslationUnit TU,
3942 CXToken *Tokens, unsigned NumTokens) {
3943 free(Tokens);
3944}
3945
3946} // end: extern "C"
3947
3948//===----------------------------------------------------------------------===//
3949// Token annotation APIs.
3950//===----------------------------------------------------------------------===//
3951
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003952typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003953static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3954 CXCursor parent,
3955 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003956namespace {
3957class AnnotateTokensWorker {
3958 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003959 CXToken *Tokens;
3960 CXCursor *Cursors;
3961 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003962 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003963 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003964 CursorVisitor AnnotateVis;
3965 SourceManager &SrcMgr;
3966
3967 bool MoreTokens() const { return TokIdx < NumTokens; }
3968 unsigned NextToken() const { return TokIdx; }
3969 void AdvanceToken() { ++TokIdx; }
3970 SourceLocation GetTokenLoc(unsigned tokI) {
3971 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3972 }
3973
Ted Kremenek6db61092010-05-05 00:55:15 +00003974public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003975 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003976 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3977 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003978 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003979 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003980 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3981 Decl::MaxPCHLevel, RegionOfInterest),
3982 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003983
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003984 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003985 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003986 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00003987 void AnnotateTokens() {
3988 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getASTUnit()));
3989 }
Ted Kremenek6db61092010-05-05 00:55:15 +00003990};
3991}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003992
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003993void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3994 // Walk the AST within the region of interest, annotating tokens
3995 // along the way.
3996 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003997
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003998 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3999 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004000 if (Pos != Annotated.end() &&
4001 (clang_isInvalid(Cursors[I].kind) ||
4002 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004003 Cursors[I] = Pos->second;
4004 }
4005
4006 // Finish up annotating any tokens left.
4007 if (!MoreTokens())
4008 return;
4009
4010 const CXCursor &C = clang_getNullCursor();
4011 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4012 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4013 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004014 }
4015}
4016
Ted Kremenek6db61092010-05-05 00:55:15 +00004017enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004018AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004019 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004020 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004021 if (cursorRange.isInvalid())
4022 return CXChildVisit_Recurse;
4023
Douglas Gregor4419b672010-10-21 06:10:04 +00004024 if (clang_isPreprocessing(cursor.kind)) {
4025 // For macro instantiations, just note where the beginning of the macro
4026 // instantiation occurs.
4027 if (cursor.kind == CXCursor_MacroInstantiation) {
4028 Annotated[Loc.int_data] = cursor;
4029 return CXChildVisit_Recurse;
4030 }
4031
Douglas Gregor4419b672010-10-21 06:10:04 +00004032 // Items in the preprocessing record are kept separate from items in
4033 // declarations, so we keep a separate token index.
4034 unsigned SavedTokIdx = TokIdx;
4035 TokIdx = PreprocessingTokIdx;
4036
4037 // Skip tokens up until we catch up to the beginning of the preprocessing
4038 // entry.
4039 while (MoreTokens()) {
4040 const unsigned I = NextToken();
4041 SourceLocation TokLoc = GetTokenLoc(I);
4042 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4043 case RangeBefore:
4044 AdvanceToken();
4045 continue;
4046 case RangeAfter:
4047 case RangeOverlap:
4048 break;
4049 }
4050 break;
4051 }
4052
4053 // Look at all of the tokens within this range.
4054 while (MoreTokens()) {
4055 const unsigned I = NextToken();
4056 SourceLocation TokLoc = GetTokenLoc(I);
4057 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4058 case RangeBefore:
4059 assert(0 && "Infeasible");
4060 case RangeAfter:
4061 break;
4062 case RangeOverlap:
4063 Cursors[I] = cursor;
4064 AdvanceToken();
4065 continue;
4066 }
4067 break;
4068 }
4069
4070 // Save the preprocessing token index; restore the non-preprocessing
4071 // token index.
4072 PreprocessingTokIdx = TokIdx;
4073 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004074 return CXChildVisit_Recurse;
4075 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004076
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004077 if (cursorRange.isInvalid())
4078 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004079
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004080 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4081
Ted Kremeneka333c662010-05-12 05:29:33 +00004082 // Adjust the annotated range based specific declarations.
4083 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4084 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004085 Decl *D = cxcursor::getCursorDecl(cursor);
4086 // Don't visit synthesized ObjC methods, since they have no syntatic
4087 // representation in the source.
4088 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4089 if (MD->isSynthesized())
4090 return CXChildVisit_Continue;
4091 }
4092 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004093 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4094 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004095 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004096 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004097 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004098 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004099 }
4100 }
4101 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004102
Ted Kremenek3f404602010-08-14 01:14:06 +00004103 // If the location of the cursor occurs within a macro instantiation, record
4104 // the spelling location of the cursor in our annotation map. We can then
4105 // paper over the token labelings during a post-processing step to try and
4106 // get cursor mappings for tokens that are the *arguments* of a macro
4107 // instantiation.
4108 if (L.isMacroID()) {
4109 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4110 // Only invalidate the old annotation if it isn't part of a preprocessing
4111 // directive. Here we assume that the default construction of CXCursor
4112 // results in CXCursor.kind being an initialized value (i.e., 0). If
4113 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004114
Ted Kremenek3f404602010-08-14 01:14:06 +00004115 CXCursor &oldC = Annotated[rawEncoding];
4116 if (!clang_isPreprocessing(oldC.kind))
4117 oldC = cursor;
4118 }
4119
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004120 const enum CXCursorKind K = clang_getCursorKind(parent);
4121 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004122 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4123 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004124
4125 while (MoreTokens()) {
4126 const unsigned I = NextToken();
4127 SourceLocation TokLoc = GetTokenLoc(I);
4128 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4129 case RangeBefore:
4130 Cursors[I] = updateC;
4131 AdvanceToken();
4132 continue;
4133 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004134 case RangeOverlap:
4135 break;
4136 }
4137 break;
4138 }
4139
4140 // Visit children to get their cursor information.
4141 const unsigned BeforeChildren = NextToken();
4142 VisitChildren(cursor);
4143 const unsigned AfterChildren = NextToken();
4144
4145 // Adjust 'Last' to the last token within the extent of the cursor.
4146 while (MoreTokens()) {
4147 const unsigned I = NextToken();
4148 SourceLocation TokLoc = GetTokenLoc(I);
4149 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4150 case RangeBefore:
4151 assert(0 && "Infeasible");
4152 case RangeAfter:
4153 break;
4154 case RangeOverlap:
4155 Cursors[I] = updateC;
4156 AdvanceToken();
4157 continue;
4158 }
4159 break;
4160 }
4161 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004162
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004163 // Scan the tokens that are at the beginning of the cursor, but are not
4164 // capture by the child cursors.
4165
4166 // For AST elements within macros, rely on a post-annotate pass to
4167 // to correctly annotate the tokens with cursors. Otherwise we can
4168 // get confusing results of having tokens that map to cursors that really
4169 // are expanded by an instantiation.
4170 if (L.isMacroID())
4171 cursor = clang_getNullCursor();
4172
4173 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4174 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4175 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004176
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004177 Cursors[I] = cursor;
4178 }
4179 // Scan the tokens that are at the end of the cursor, but are not captured
4180 // but the child cursors.
4181 for (unsigned I = AfterChildren; I != Last; ++I)
4182 Cursors[I] = cursor;
4183
4184 TokIdx = Last;
4185 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004186}
4187
Ted Kremenek6db61092010-05-05 00:55:15 +00004188static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4189 CXCursor parent,
4190 CXClientData client_data) {
4191 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4192}
4193
Ted Kremenekab979612010-11-11 08:05:23 +00004194// This gets run a separate thread to avoid stack blowout.
4195static void runAnnotateTokensWorker(void *UserData) {
4196 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4197}
4198
Ted Kremenek6db61092010-05-05 00:55:15 +00004199extern "C" {
4200
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004201void clang_annotateTokens(CXTranslationUnit TU,
4202 CXToken *Tokens, unsigned NumTokens,
4203 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004204
4205 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004206 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004207
Douglas Gregor4419b672010-10-21 06:10:04 +00004208 // Any token we don't specifically annotate will have a NULL cursor.
4209 CXCursor C = clang_getNullCursor();
4210 for (unsigned I = 0; I != NumTokens; ++I)
4211 Cursors[I] = C;
4212
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004213 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor4419b672010-10-21 06:10:04 +00004214 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004215 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004216
Douglas Gregorbdf60622010-03-05 21:16:25 +00004217 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004218
Douglas Gregor0396f462010-03-19 05:22:59 +00004219 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004220 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004221 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4222 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004223 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4224 clang_getTokenLocation(TU,
4225 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004226
Douglas Gregor0396f462010-03-19 05:22:59 +00004227 // A mapping from the source locations found when re-lexing or traversing the
4228 // region of interest to the corresponding cursors.
4229 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004230
4231 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004232 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004233 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4234 std::pair<FileID, unsigned> BeginLocInfo
4235 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4236 std::pair<FileID, unsigned> EndLocInfo
4237 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004238
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004239 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004240 bool Invalid = false;
4241 if (BeginLocInfo.first == EndLocInfo.first &&
4242 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4243 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004244 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4245 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004246 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004247 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004248 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004249
4250 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004251 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004252 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004253 Token Tok;
4254 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004255
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004256 reprocess:
4257 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4258 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004259 // don't see it while preprocessing these tokens later, but keep track
4260 // of all of the token locations inside this preprocessing directive so
4261 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004262 //
4263 // FIXME: Some simple tests here could identify macro definitions and
4264 // #undefs, to provide specific cursor kinds for those.
4265 std::vector<SourceLocation> Locations;
4266 do {
4267 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004268 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004269 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004270
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004271 using namespace cxcursor;
4272 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004273 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4274 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00004275 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004276 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4277 Annotated[Locations[I].getRawEncoding()] = Cursor;
4278 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004279
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004280 if (Tok.isAtStartOfLine())
4281 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004282
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004283 continue;
4284 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004285
Douglas Gregor48072312010-03-18 15:23:44 +00004286 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004287 break;
4288 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004289 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004290
Douglas Gregor0396f462010-03-19 05:22:59 +00004291 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004292 // a specific cursor.
4293 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4294 CXXUnit, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004295
4296 // Run the worker within a CrashRecoveryContext.
4297 llvm::CrashRecoveryContext CRC;
4298 if (!RunSafely(CRC, runAnnotateTokensWorker, &W)) {
4299 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4300 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004301}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004302} // end: extern "C"
4303
4304//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004305// Operations for querying linkage of a cursor.
4306//===----------------------------------------------------------------------===//
4307
4308extern "C" {
4309CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004310 if (!clang_isDeclaration(cursor.kind))
4311 return CXLinkage_Invalid;
4312
Ted Kremenek16b42592010-03-03 06:36:57 +00004313 Decl *D = cxcursor::getCursorDecl(cursor);
4314 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4315 switch (ND->getLinkage()) {
4316 case NoLinkage: return CXLinkage_NoLinkage;
4317 case InternalLinkage: return CXLinkage_Internal;
4318 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4319 case ExternalLinkage: return CXLinkage_External;
4320 };
4321
4322 return CXLinkage_Invalid;
4323}
4324} // end: extern "C"
4325
4326//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004327// Operations for querying language of a cursor.
4328//===----------------------------------------------------------------------===//
4329
4330static CXLanguageKind getDeclLanguage(const Decl *D) {
4331 switch (D->getKind()) {
4332 default:
4333 break;
4334 case Decl::ImplicitParam:
4335 case Decl::ObjCAtDefsField:
4336 case Decl::ObjCCategory:
4337 case Decl::ObjCCategoryImpl:
4338 case Decl::ObjCClass:
4339 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004340 case Decl::ObjCForwardProtocol:
4341 case Decl::ObjCImplementation:
4342 case Decl::ObjCInterface:
4343 case Decl::ObjCIvar:
4344 case Decl::ObjCMethod:
4345 case Decl::ObjCProperty:
4346 case Decl::ObjCPropertyImpl:
4347 case Decl::ObjCProtocol:
4348 return CXLanguage_ObjC;
4349 case Decl::CXXConstructor:
4350 case Decl::CXXConversion:
4351 case Decl::CXXDestructor:
4352 case Decl::CXXMethod:
4353 case Decl::CXXRecord:
4354 case Decl::ClassTemplate:
4355 case Decl::ClassTemplatePartialSpecialization:
4356 case Decl::ClassTemplateSpecialization:
4357 case Decl::Friend:
4358 case Decl::FriendTemplate:
4359 case Decl::FunctionTemplate:
4360 case Decl::LinkageSpec:
4361 case Decl::Namespace:
4362 case Decl::NamespaceAlias:
4363 case Decl::NonTypeTemplateParm:
4364 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004365 case Decl::TemplateTemplateParm:
4366 case Decl::TemplateTypeParm:
4367 case Decl::UnresolvedUsingTypename:
4368 case Decl::UnresolvedUsingValue:
4369 case Decl::Using:
4370 case Decl::UsingDirective:
4371 case Decl::UsingShadow:
4372 return CXLanguage_CPlusPlus;
4373 }
4374
4375 return CXLanguage_C;
4376}
4377
4378extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004379
4380enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4381 if (clang_isDeclaration(cursor.kind))
4382 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4383 if (D->hasAttr<UnavailableAttr>() ||
4384 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4385 return CXAvailability_Available;
4386
4387 if (D->hasAttr<DeprecatedAttr>())
4388 return CXAvailability_Deprecated;
4389 }
4390
4391 return CXAvailability_Available;
4392}
4393
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004394CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4395 if (clang_isDeclaration(cursor.kind))
4396 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4397
4398 return CXLanguage_Invalid;
4399}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004400
4401CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4402 if (clang_isDeclaration(cursor.kind)) {
4403 if (Decl *D = getCursorDecl(cursor)) {
4404 DeclContext *DC = D->getDeclContext();
4405 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4406 }
4407 }
4408
4409 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4410 if (Decl *D = getCursorDecl(cursor))
4411 return MakeCXCursor(D, getCursorASTUnit(cursor));
4412 }
4413
4414 return clang_getNullCursor();
4415}
4416
4417CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4418 if (clang_isDeclaration(cursor.kind)) {
4419 if (Decl *D = getCursorDecl(cursor)) {
4420 DeclContext *DC = D->getLexicalDeclContext();
4421 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4422 }
4423 }
4424
4425 // FIXME: Note that we can't easily compute the lexical context of a
4426 // statement or expression, so we return nothing.
4427 return clang_getNullCursor();
4428}
4429
Douglas Gregor9f592342010-10-01 20:25:15 +00004430static void CollectOverriddenMethods(DeclContext *Ctx,
4431 ObjCMethodDecl *Method,
4432 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4433 if (!Ctx)
4434 return;
4435
4436 // If we have a class or category implementation, jump straight to the
4437 // interface.
4438 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4439 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4440
4441 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4442 if (!Container)
4443 return;
4444
4445 // Check whether we have a matching method at this level.
4446 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4447 Method->isInstanceMethod()))
4448 if (Method != Overridden) {
4449 // We found an override at this level; there is no need to look
4450 // into other protocols or categories.
4451 Methods.push_back(Overridden);
4452 return;
4453 }
4454
4455 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4456 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4457 PEnd = Protocol->protocol_end();
4458 P != PEnd; ++P)
4459 CollectOverriddenMethods(*P, Method, Methods);
4460 }
4461
4462 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4463 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4464 PEnd = Category->protocol_end();
4465 P != PEnd; ++P)
4466 CollectOverriddenMethods(*P, Method, Methods);
4467 }
4468
4469 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4470 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4471 PEnd = Interface->protocol_end();
4472 P != PEnd; ++P)
4473 CollectOverriddenMethods(*P, Method, Methods);
4474
4475 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4476 Category; Category = Category->getNextClassCategory())
4477 CollectOverriddenMethods(Category, Method, Methods);
4478
4479 // We only look into the superclass if we haven't found anything yet.
4480 if (Methods.empty())
4481 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4482 return CollectOverriddenMethods(Super, Method, Methods);
4483 }
4484}
4485
4486void clang_getOverriddenCursors(CXCursor cursor,
4487 CXCursor **overridden,
4488 unsigned *num_overridden) {
4489 if (overridden)
4490 *overridden = 0;
4491 if (num_overridden)
4492 *num_overridden = 0;
4493 if (!overridden || !num_overridden)
4494 return;
4495
4496 if (!clang_isDeclaration(cursor.kind))
4497 return;
4498
4499 Decl *D = getCursorDecl(cursor);
4500 if (!D)
4501 return;
4502
4503 // Handle C++ member functions.
4504 ASTUnit *CXXUnit = getCursorASTUnit(cursor);
4505 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4506 *num_overridden = CXXMethod->size_overridden_methods();
4507 if (!*num_overridden)
4508 return;
4509
4510 *overridden = new CXCursor [*num_overridden];
4511 unsigned I = 0;
4512 for (CXXMethodDecl::method_iterator
4513 M = CXXMethod->begin_overridden_methods(),
4514 MEnd = CXXMethod->end_overridden_methods();
4515 M != MEnd; (void)++M, ++I)
4516 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit);
4517 return;
4518 }
4519
4520 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4521 if (!Method)
4522 return;
4523
4524 // Handle Objective-C methods.
4525 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4526 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4527
4528 if (Methods.empty())
4529 return;
4530
4531 *num_overridden = Methods.size();
4532 *overridden = new CXCursor [Methods.size()];
4533 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4534 (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit);
4535}
4536
4537void clang_disposeOverriddenCursors(CXCursor *overridden) {
4538 delete [] overridden;
4539}
4540
Douglas Gregorecdcb882010-10-20 22:00:55 +00004541CXFile clang_getIncludedFile(CXCursor cursor) {
4542 if (cursor.kind != CXCursor_InclusionDirective)
4543 return 0;
4544
4545 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4546 return (void *)ID->getFile();
4547}
4548
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004549} // end: extern "C"
4550
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004551
4552//===----------------------------------------------------------------------===//
4553// C++ AST instrospection.
4554//===----------------------------------------------------------------------===//
4555
4556extern "C" {
4557unsigned clang_CXXMethod_isStatic(CXCursor C) {
4558 if (!clang_isDeclaration(C.kind))
4559 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004560
4561 CXXMethodDecl *Method = 0;
4562 Decl *D = cxcursor::getCursorDecl(C);
4563 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4564 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4565 else
4566 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4567 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004568}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004569
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004570} // end: extern "C"
4571
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004572//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004573// Attribute introspection.
4574//===----------------------------------------------------------------------===//
4575
4576extern "C" {
4577CXType clang_getIBOutletCollectionType(CXCursor C) {
4578 if (C.kind != CXCursor_IBOutletCollectionAttr)
4579 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4580
4581 IBOutletCollectionAttr *A =
4582 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4583
4584 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4585}
4586} // end: extern "C"
4587
4588//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00004589// CXString Operations.
4590//===----------------------------------------------------------------------===//
4591
4592extern "C" {
4593const char *clang_getCString(CXString string) {
4594 return string.Spelling;
4595}
4596
4597void clang_disposeString(CXString string) {
4598 if (string.MustFreeString && string.Spelling)
4599 free((void*)string.Spelling);
4600}
Ted Kremenek04bb7162010-01-22 22:44:15 +00004601
Ted Kremenekfb480492010-01-13 21:46:36 +00004602} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00004603
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004604namespace clang { namespace cxstring {
4605CXString createCXString(const char *String, bool DupString){
4606 CXString Str;
4607 if (DupString) {
4608 Str.Spelling = strdup(String);
4609 Str.MustFreeString = 1;
4610 } else {
4611 Str.Spelling = String;
4612 Str.MustFreeString = 0;
4613 }
4614 return Str;
4615}
4616
4617CXString createCXString(llvm::StringRef String, bool DupString) {
4618 CXString Result;
4619 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
4620 char *Spelling = (char *)malloc(String.size() + 1);
4621 memmove(Spelling, String.data(), String.size());
4622 Spelling[String.size()] = 0;
4623 Result.Spelling = Spelling;
4624 Result.MustFreeString = 1;
4625 } else {
4626 Result.Spelling = String.data();
4627 Result.MustFreeString = 0;
4628 }
4629 return Result;
4630}
4631}}
4632
Ted Kremenek04bb7162010-01-22 22:44:15 +00004633//===----------------------------------------------------------------------===//
4634// Misc. utility functions.
4635//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004636
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004637/// Default to using an 8 MB stack size on "safety" threads.
4638static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004639
4640namespace clang {
4641
4642bool RunSafely(llvm::CrashRecoveryContext &CRC,
4643 void (*Fn)(void*), void *UserData) {
4644 if (unsigned Size = GetSafetyThreadStackSize())
4645 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4646 return CRC.RunSafely(Fn, UserData);
4647}
4648
4649unsigned GetSafetyThreadStackSize() {
4650 return SafetyStackThreadSize;
4651}
4652
4653void SetSafetyThreadStackSize(unsigned Value) {
4654 SafetyStackThreadSize = Value;
4655}
4656
4657}
4658
Ted Kremenek04bb7162010-01-22 22:44:15 +00004659extern "C" {
4660
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004661CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004662 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004663}
4664
4665} // end: extern "C"