blob: 7dcaa606e254440c49b5817e137f127b7a7ae283 [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
Douglas Gregorb1373d02010-01-20 20:59:29 +0000176// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000177class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000178 public TypeLocVisitor<CursorVisitor, bool>,
179 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000180{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000181 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000182 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000183
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000184 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000185 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000186
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000187 /// \brief The declaration that serves at the parent of any statement or
188 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000189 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000190
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000191 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000192 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000193
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000194 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000195 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000196
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000197 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
198 // to the visitor. Declarations with a PCH level greater than this value will
199 // be suppressed.
200 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000201
202 /// \brief When valid, a source range to which the cursor should restrict
203 /// its search.
204 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000205
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000206 // FIXME: Eventually remove. This part of a hack to support proper
207 // iteration over all Decls contained lexically within an ObjC container.
208 DeclContext::decl_iterator *DI_current;
209 DeclContext::decl_iterator DE_current;
210
Douglas Gregorb1373d02010-01-20 20:59:29 +0000211 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000212 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000213 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000214
215 /// \brief Determine whether this particular source range comes before, comes
216 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000217 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000218 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000219 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
220
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000221 class SetParentRAII {
222 CXCursor &Parent;
223 Decl *&StmtParent;
224 CXCursor OldParent;
225
226 public:
227 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
228 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
229 {
230 Parent = NewParent;
231 if (clang_isDeclaration(Parent.kind))
232 StmtParent = getCursorDecl(Parent);
233 }
234
235 ~SetParentRAII() {
236 Parent = OldParent;
237 if (clang_isDeclaration(Parent.kind))
238 StmtParent = getCursorDecl(Parent);
239 }
240 };
241
Steve Naroff89922f82009-08-31 00:59:03 +0000242public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000243 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
244 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000245 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000246 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000247 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
248 DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000249 {
250 Parent.kind = CXCursor_NoDeclFound;
251 Parent.data[0] = 0;
252 Parent.data[1] = 0;
253 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000254 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000255 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000256
Ted Kremenekab979612010-11-11 08:05:23 +0000257 ASTUnit *getASTUnit() const { return TU; }
258
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000259 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000260
261 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
262 getPreprocessedEntities();
263
Douglas Gregorb1373d02010-01-20 20:59:29 +0000264 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000265
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000266 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000267 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000268 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000269 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000270 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000271 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000272 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
273 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000274 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000275 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000276 bool VisitClassTemplatePartialSpecializationDecl(
277 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000278 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000279 bool VisitEnumConstantDecl(EnumConstantDecl *D);
280 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
281 bool VisitFunctionDecl(FunctionDecl *ND);
282 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000283 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000284 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000285 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000286 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000287 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000288 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
289 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
290 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
291 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000292 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000293 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
294 bool VisitObjCImplDecl(ObjCImplDecl *D);
295 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
296 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000297 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
298 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
299 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000300 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000301 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000302 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000303 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000304 bool VisitUsingDecl(UsingDecl *D);
305 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
306 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000307
Douglas Gregor01829d32010-08-31 14:41:23 +0000308 // Name visitor
309 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000310 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000311
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000312 // Template visitors
313 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000314 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000315 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
316
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000317 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000318 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000319 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000320 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000321 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
322 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000323 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000324 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000325 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000326 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
327 bool VisitPointerTypeLoc(PointerTypeLoc TL);
328 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
329 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
330 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
331 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000332 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000333 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000334 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000335 // FIXME: Implement visitors here when the unimplemented TypeLocs get
336 // implemented
337 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
338 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000339
Douglas Gregora59e3902010-01-21 23:27:09 +0000340 // Statement visitors
341 bool VisitStmt(Stmt *S);
342 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregor36897b02010-09-10 00:22:18 +0000343 bool VisitGotoStmt(GotoStmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000344
Douglas Gregor336fd812010-01-23 00:40:08 +0000345 // Expression visitors
Douglas Gregor8947a752010-09-02 20:35:02 +0000346 bool VisitDeclRefExpr(DeclRefExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000347 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor81d34662010-04-20 15:39:42 +0000348 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000349 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000350 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor36897b02010-09-10 00:22:18 +0000351 bool VisitAddrLabelExpr(AddrLabelExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000352 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
353 bool VisitVAArgExpr(VAArgExpr *E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +0000354 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
Douglas Gregor94802292010-09-02 21:20:16 +0000355 bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000356 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
Douglas Gregorda135b12010-09-02 21:38:13 +0000357 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { return false; }
Douglas Gregorab6677e2010-09-08 00:15:04 +0000358 bool VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
359 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000360 bool VisitCXXNewExpr(CXXNewExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000361 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000362 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000363 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000364 bool VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000365 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000366
367#define DATA_RECURSIVE_VISIT(NAME)\
368bool Visit##NAME(NAME *S) { return VisitDataRecursive(S); }
369 DATA_RECURSIVE_VISIT(BinaryOperator)
Ted Kremenekcdb4caf2010-11-12 21:34:12 +0000370 DATA_RECURSIVE_VISIT(CompoundLiteralExpr)
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000371 DATA_RECURSIVE_VISIT(CXXMemberCallExpr)
Ted Kremenek8c269ac2010-11-11 23:11:43 +0000372 DATA_RECURSIVE_VISIT(CXXOperatorCallExpr)
Ted Kremenek99394242010-11-12 22:24:57 +0000373 DATA_RECURSIVE_VISIT(ExplicitCastExpr)
Ted Kremenekbb677132010-11-12 18:27:04 +0000374 DATA_RECURSIVE_VISIT(DoStmt)
Ted Kremenekc70ebba2010-11-12 18:26:58 +0000375 DATA_RECURSIVE_VISIT(IfStmt)
Ted Kremeneka6b70432010-11-12 21:34:09 +0000376 DATA_RECURSIVE_VISIT(InitListExpr)
Ted Kremenekbb677132010-11-12 18:27:04 +0000377 DATA_RECURSIVE_VISIT(ForStmt)
Ted Kremenekc70ebba2010-11-12 18:26:58 +0000378 DATA_RECURSIVE_VISIT(MemberExpr)
Ted Kremenekc373e3c2010-11-12 22:24:55 +0000379 DATA_RECURSIVE_VISIT(ObjCMessageExpr)
Ted Kremenek60458782010-11-12 21:34:16 +0000380 DATA_RECURSIVE_VISIT(OverloadExpr)
Ted Kremenekf1107452010-11-12 18:26:56 +0000381 DATA_RECURSIVE_VISIT(SwitchStmt)
Ted Kremenekbb677132010-11-12 18:27:04 +0000382 DATA_RECURSIVE_VISIT(WhileStmt)
Ted Kremenek60458782010-11-12 21:34:16 +0000383 DATA_RECURSIVE_VISIT(UnresolvedMemberExpr)
Ted Kremeneka6b70432010-11-12 21:34:09 +0000384
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000385 // Data-recursive visitor functions.
386 bool IsInRegionOfInterest(CXCursor C);
387 bool RunVisitorWorkList(VisitorWorkList &WL);
388 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
389 bool VisitDataRecursive(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000390};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000391
Ted Kremenekab188932010-01-05 19:32:54 +0000392} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000393
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000394static SourceRange getRawCursorExtent(CXCursor C);
395
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000396RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000397 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
398}
399
Douglas Gregorb1373d02010-01-20 20:59:29 +0000400/// \brief Visit the given cursor and, if requested by the visitor,
401/// its children.
402///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000403/// \param Cursor the cursor to visit.
404///
405/// \param CheckRegionOfInterest if true, then the caller already checked that
406/// this cursor is within the region of interest.
407///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000408/// \returns true if the visitation should be aborted, false if it
409/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000410bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000411 if (clang_isInvalid(Cursor.kind))
412 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000413
Douglas Gregorb1373d02010-01-20 20:59:29 +0000414 if (clang_isDeclaration(Cursor.kind)) {
415 Decl *D = getCursorDecl(Cursor);
416 assert(D && "Invalid declaration cursor");
417 if (D->getPCHLevel() > MaxPCHLevel)
418 return false;
419
420 if (D->isImplicit())
421 return false;
422 }
423
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000424 // If we have a range of interest, and this cursor doesn't intersect with it,
425 // we're done.
426 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000427 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000428 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000429 return false;
430 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000431
Douglas Gregorb1373d02010-01-20 20:59:29 +0000432 switch (Visitor(Cursor, Parent, ClientData)) {
433 case CXChildVisit_Break:
434 return true;
435
436 case CXChildVisit_Continue:
437 return false;
438
439 case CXChildVisit_Recurse:
440 return VisitChildren(Cursor);
441 }
442
Douglas Gregorfd643772010-01-25 16:45:46 +0000443 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000444}
445
Douglas Gregor788f5a12010-03-20 00:41:21 +0000446std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
447CursorVisitor::getPreprocessedEntities() {
448 PreprocessingRecord &PPRec
449 = *TU->getPreprocessor().getPreprocessingRecord();
450
451 bool OnlyLocalDecls
452 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
453
454 // There is no region of interest; we have to walk everything.
455 if (RegionOfInterest.isInvalid())
456 return std::make_pair(PPRec.begin(OnlyLocalDecls),
457 PPRec.end(OnlyLocalDecls));
458
459 // Find the file in which the region of interest lands.
460 SourceManager &SM = TU->getSourceManager();
461 std::pair<FileID, unsigned> Begin
462 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
463 std::pair<FileID, unsigned> End
464 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
465
466 // The region of interest spans files; we have to walk everything.
467 if (Begin.first != End.first)
468 return std::make_pair(PPRec.begin(OnlyLocalDecls),
469 PPRec.end(OnlyLocalDecls));
470
471 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
472 = TU->getPreprocessedEntitiesByFile();
473 if (ByFileMap.empty()) {
474 // Build the mapping from files to sets of preprocessed entities.
475 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
476 EEnd = PPRec.end(OnlyLocalDecls);
477 E != EEnd; ++E) {
478 std::pair<FileID, unsigned> P
479 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
480 ByFileMap[P.first].push_back(*E);
481 }
482 }
483
484 return std::make_pair(ByFileMap[Begin.first].begin(),
485 ByFileMap[Begin.first].end());
486}
487
Douglas Gregorb1373d02010-01-20 20:59:29 +0000488/// \brief Visit the children of the given cursor.
489///
490/// \returns true if the visitation should be aborted, false if it
491/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000492bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000493 if (clang_isReference(Cursor.kind)) {
494 // By definition, references have no children.
495 return false;
496 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000497
498 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000499 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000500 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000501
Douglas Gregorb1373d02010-01-20 20:59:29 +0000502 if (clang_isDeclaration(Cursor.kind)) {
503 Decl *D = getCursorDecl(Cursor);
504 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000505 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000506 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000507
Douglas Gregora59e3902010-01-21 23:27:09 +0000508 if (clang_isStatement(Cursor.kind))
509 return Visit(getCursorStmt(Cursor));
510 if (clang_isExpression(Cursor.kind))
511 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000512
Douglas Gregorb1373d02010-01-20 20:59:29 +0000513 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000514 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000515 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
516 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000517 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
518 TLEnd = CXXUnit->top_level_end();
519 TL != TLEnd; ++TL) {
520 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000521 return true;
522 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000523 } else if (VisitDeclContext(
524 CXXUnit->getASTContext().getTranslationUnitDecl()))
525 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000526
Douglas Gregor0396f462010-03-19 05:22:59 +0000527 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000528 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000529 // FIXME: Once we have the ability to deserialize a preprocessing record,
530 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000531 PreprocessingRecord::iterator E, EEnd;
532 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000533 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
534 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
535 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000536
Douglas Gregor0396f462010-03-19 05:22:59 +0000537 continue;
538 }
539
540 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
541 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
542 return true;
543
544 continue;
545 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000546
547 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
548 if (Visit(MakeInclusionDirectiveCursor(ID, CXXUnit)))
549 return true;
550
551 continue;
552 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000553 }
554 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000555 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000556 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000557
Douglas Gregorb1373d02010-01-20 20:59:29 +0000558 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000559 return false;
560}
561
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000562bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000563 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
564 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000565
Ted Kremenek664cffd2010-07-22 11:30:19 +0000566 if (Stmt *Body = B->getBody())
567 return Visit(MakeCXCursor(Body, StmtParent, TU));
568
569 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000570}
571
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000572llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
573 if (RegionOfInterest.isValid()) {
574 SourceRange Range = getRawCursorExtent(Cursor);
575 if (Range.isInvalid())
576 return llvm::Optional<bool>();
Ted Kremenek09dfa372010-02-18 05:46:33 +0000577
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000578 switch (CompareRegionOfInterest(Range)) {
579 case RangeBefore:
580 // This declaration comes before the region of interest; skip it.
581 return llvm::Optional<bool>();
582
583 case RangeAfter:
584 // This declaration comes after the region of interest; we're done.
585 return false;
586
587 case RangeOverlap:
588 // This declaration overlaps the region of interest; visit it.
589 break;
590 }
591 }
592 return true;
593}
594
595bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
596 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
597
598 // FIXME: Eventually remove. This part of a hack to support proper
599 // iteration over all Decls contained lexically within an ObjC container.
600 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
601 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
602
603 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000604 Decl *D = *I;
605 if (D->getLexicalDeclContext() != DC)
606 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000607 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000608 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
609 if (!V.hasValue())
610 continue;
611 if (!V.getValue())
612 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000613 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000614 return true;
615 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000616 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000617}
618
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000619bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
620 llvm_unreachable("Translation units are visited directly by Visit()");
621 return false;
622}
623
624bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
625 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
626 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000627
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000628 return false;
629}
630
631bool CursorVisitor::VisitTagDecl(TagDecl *D) {
632 return VisitDeclContext(D);
633}
634
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000635bool CursorVisitor::VisitClassTemplateSpecializationDecl(
636 ClassTemplateSpecializationDecl *D) {
637 bool ShouldVisitBody = false;
638 switch (D->getSpecializationKind()) {
639 case TSK_Undeclared:
640 case TSK_ImplicitInstantiation:
641 // Nothing to visit
642 return false;
643
644 case TSK_ExplicitInstantiationDeclaration:
645 case TSK_ExplicitInstantiationDefinition:
646 break;
647
648 case TSK_ExplicitSpecialization:
649 ShouldVisitBody = true;
650 break;
651 }
652
653 // Visit the template arguments used in the specialization.
654 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
655 TypeLoc TL = SpecType->getTypeLoc();
656 if (TemplateSpecializationTypeLoc *TSTLoc
657 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
658 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
659 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
660 return true;
661 }
662 }
663
664 if (ShouldVisitBody && VisitCXXRecordDecl(D))
665 return true;
666
667 return false;
668}
669
Douglas Gregor74dbe642010-08-31 19:31:58 +0000670bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
671 ClassTemplatePartialSpecializationDecl *D) {
672 // FIXME: Visit the "outer" template parameter lists on the TagDecl
673 // before visiting these template parameters.
674 if (VisitTemplateParameters(D->getTemplateParameters()))
675 return true;
676
677 // Visit the partial specialization arguments.
678 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
679 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
680 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
681 return true;
682
683 return VisitCXXRecordDecl(D);
684}
685
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000686bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000687 // Visit the default argument.
688 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
689 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
690 if (Visit(DefArg->getTypeLoc()))
691 return true;
692
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000693 return false;
694}
695
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000696bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
697 if (Expr *Init = D->getInitExpr())
698 return Visit(MakeCXCursor(Init, StmtParent, TU));
699 return false;
700}
701
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000702bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
703 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
704 if (Visit(TSInfo->getTypeLoc()))
705 return true;
706
707 return false;
708}
709
Douglas Gregora67e03f2010-09-09 21:42:20 +0000710/// \brief Compare two base or member initializers based on their source order.
711static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
712 CXXBaseOrMemberInitializer const * const *X
713 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
714 CXXBaseOrMemberInitializer const * const *Y
715 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
716
717 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
718 return -1;
719 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
720 return 1;
721 else
722 return 0;
723}
724
Douglas Gregorb1373d02010-01-20 20:59:29 +0000725bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000726 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
727 // Visit the function declaration's syntactic components in the order
728 // written. This requires a bit of work.
729 TypeLoc TL = TSInfo->getTypeLoc();
730 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
731
732 // If we have a function declared directly (without the use of a typedef),
733 // visit just the return type. Otherwise, just visit the function's type
734 // now.
735 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
736 (!FTL && Visit(TL)))
737 return true;
738
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000739 // Visit the nested-name-specifier, if present.
740 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
741 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
742 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000743
744 // Visit the declaration name.
745 if (VisitDeclarationNameInfo(ND->getNameInfo()))
746 return true;
747
748 // FIXME: Visit explicitly-specified template arguments!
749
750 // Visit the function parameters, if we have a function type.
751 if (FTL && VisitFunctionTypeLoc(*FTL, true))
752 return true;
753
754 // FIXME: Attributes?
755 }
756
Douglas Gregora67e03f2010-09-09 21:42:20 +0000757 if (ND->isThisDeclarationADefinition()) {
758 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
759 // Find the initializers that were written in the source.
760 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
761 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
762 IEnd = Constructor->init_end();
763 I != IEnd; ++I) {
764 if (!(*I)->isWritten())
765 continue;
766
767 WrittenInits.push_back(*I);
768 }
769
770 // Sort the initializers in source order
771 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
772 &CompareCXXBaseOrMemberInitializers);
773
774 // Visit the initializers in source order
775 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
776 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
777 if (Init->isMemberInitializer()) {
778 if (Visit(MakeCursorMemberRef(Init->getMember(),
779 Init->getMemberLocation(), TU)))
780 return true;
781 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
782 if (Visit(BaseInfo->getTypeLoc()))
783 return true;
784 }
785
786 // Visit the initializer value.
787 if (Expr *Initializer = Init->getInit())
788 if (Visit(MakeCXCursor(Initializer, ND, TU)))
789 return true;
790 }
791 }
792
793 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
794 return true;
795 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000796
Douglas Gregorb1373d02010-01-20 20:59:29 +0000797 return false;
798}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000799
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000800bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
801 if (VisitDeclaratorDecl(D))
802 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000803
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000804 if (Expr *BitWidth = D->getBitWidth())
805 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000806
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000807 return false;
808}
809
810bool CursorVisitor::VisitVarDecl(VarDecl *D) {
811 if (VisitDeclaratorDecl(D))
812 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000813
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000814 if (Expr *Init = D->getInit())
815 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000816
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000817 return false;
818}
819
Douglas Gregor84b51d72010-09-01 20:16:53 +0000820bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
821 if (VisitDeclaratorDecl(D))
822 return true;
823
824 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
825 if (Expr *DefArg = D->getDefaultArgument())
826 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
827
828 return false;
829}
830
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000831bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
832 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
833 // before visiting these template parameters.
834 if (VisitTemplateParameters(D->getTemplateParameters()))
835 return true;
836
837 return VisitFunctionDecl(D->getTemplatedDecl());
838}
839
Douglas Gregor39d6f072010-08-31 19:02:00 +0000840bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
841 // FIXME: Visit the "outer" template parameter lists on the TagDecl
842 // before visiting these template parameters.
843 if (VisitTemplateParameters(D->getTemplateParameters()))
844 return true;
845
846 return VisitCXXRecordDecl(D->getTemplatedDecl());
847}
848
Douglas Gregor84b51d72010-09-01 20:16:53 +0000849bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
850 if (VisitTemplateParameters(D->getTemplateParameters()))
851 return true;
852
853 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
854 VisitTemplateArgumentLoc(D->getDefaultArgument()))
855 return true;
856
857 return false;
858}
859
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000860bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000861 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
862 if (Visit(TSInfo->getTypeLoc()))
863 return true;
864
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000865 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000866 PEnd = ND->param_end();
867 P != PEnd; ++P) {
868 if (Visit(MakeCXCursor(*P, TU)))
869 return true;
870 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000871
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000872 if (ND->isThisDeclarationADefinition() &&
873 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
874 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000875
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000876 return false;
877}
878
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000879namespace {
880 struct ContainerDeclsSort {
881 SourceManager &SM;
882 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
883 bool operator()(Decl *A, Decl *B) {
884 SourceLocation L_A = A->getLocStart();
885 SourceLocation L_B = B->getLocStart();
886 assert(L_A.isValid() && L_B.isValid());
887 return SM.isBeforeInTranslationUnit(L_A, L_B);
888 }
889 };
890}
891
Douglas Gregora59e3902010-01-21 23:27:09 +0000892bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000893 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
894 // an @implementation can lexically contain Decls that are not properly
895 // nested in the AST. When we identify such cases, we need to retrofit
896 // this nesting here.
897 if (!DI_current)
898 return VisitDeclContext(D);
899
900 // Scan the Decls that immediately come after the container
901 // in the current DeclContext. If any fall within the
902 // container's lexical region, stash them into a vector
903 // for later processing.
904 llvm::SmallVector<Decl *, 24> DeclsInContainer;
905 SourceLocation EndLoc = D->getSourceRange().getEnd();
906 SourceManager &SM = TU->getSourceManager();
907 if (EndLoc.isValid()) {
908 DeclContext::decl_iterator next = *DI_current;
909 while (++next != DE_current) {
910 Decl *D_next = *next;
911 if (!D_next)
912 break;
913 SourceLocation L = D_next->getLocStart();
914 if (!L.isValid())
915 break;
916 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
917 *DI_current = next;
918 DeclsInContainer.push_back(D_next);
919 continue;
920 }
921 break;
922 }
923 }
924
925 // The common case.
926 if (DeclsInContainer.empty())
927 return VisitDeclContext(D);
928
929 // Get all the Decls in the DeclContext, and sort them with the
930 // additional ones we've collected. Then visit them.
931 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
932 I!=E; ++I) {
933 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000934 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
935 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000936 continue;
937 DeclsInContainer.push_back(subDecl);
938 }
939
940 // Now sort the Decls so that they appear in lexical order.
941 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
942 ContainerDeclsSort(SM));
943
944 // Now visit the decls.
945 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
946 E = DeclsInContainer.end(); I != E; ++I) {
947 CXCursor Cursor = MakeCXCursor(*I, TU);
948 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
949 if (!V.hasValue())
950 continue;
951 if (!V.getValue())
952 return false;
953 if (Visit(Cursor, true))
954 return true;
955 }
956 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000957}
958
Douglas Gregorb1373d02010-01-20 20:59:29 +0000959bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000960 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
961 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000962 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000963
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000964 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
965 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
966 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000967 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000968 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000969
Douglas Gregora59e3902010-01-21 23:27:09 +0000970 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000971}
972
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000973bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
974 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
975 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
976 E = PID->protocol_end(); I != E; ++I, ++PL)
977 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
978 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000979
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000980 return VisitObjCContainerDecl(PID);
981}
982
Ted Kremenek23173d72010-05-18 21:09:07 +0000983bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000984 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000985 return true;
986
Ted Kremenek23173d72010-05-18 21:09:07 +0000987 // FIXME: This implements a workaround with @property declarations also being
988 // installed in the DeclContext for the @interface. Eventually this code
989 // should be removed.
990 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
991 if (!CDecl || !CDecl->IsClassExtension())
992 return false;
993
994 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
995 if (!ID)
996 return false;
997
998 IdentifierInfo *PropertyId = PD->getIdentifier();
999 ObjCPropertyDecl *prevDecl =
1000 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
1001
1002 if (!prevDecl)
1003 return false;
1004
1005 // Visit synthesized methods since they will be skipped when visiting
1006 // the @interface.
1007 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001008 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +00001009 if (Visit(MakeCXCursor(MD, TU)))
1010 return true;
1011
1012 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +00001013 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +00001014 if (Visit(MakeCXCursor(MD, TU)))
1015 return true;
1016
1017 return false;
1018}
1019
Douglas Gregorb1373d02010-01-20 20:59:29 +00001020bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001021 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001022 if (D->getSuperClass() &&
1023 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001024 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001025 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001026 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001027
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001028 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1029 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1030 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001031 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001032 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001033
Douglas Gregora59e3902010-01-21 23:27:09 +00001034 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001035}
1036
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001037bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1038 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001039}
1040
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001041bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001042 // 'ID' could be null when dealing with invalid code.
1043 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1044 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1045 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001046
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001047 return VisitObjCImplDecl(D);
1048}
1049
1050bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1051#if 0
1052 // Issue callbacks for super class.
1053 // FIXME: No source location information!
1054 if (D->getSuperClass() &&
1055 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001056 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001057 TU)))
1058 return true;
1059#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001060
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001061 return VisitObjCImplDecl(D);
1062}
1063
1064bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1065 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1066 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1067 E = D->protocol_end();
1068 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001069 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001070 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001071
1072 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001073}
1074
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001075bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1076 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1077 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1078 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001079
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001080 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001081}
1082
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001083bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1084 return VisitDeclContext(D);
1085}
1086
Douglas Gregor69319002010-08-31 23:48:11 +00001087bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001088 // Visit nested-name-specifier.
1089 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1090 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1091 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001092
1093 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1094 D->getTargetNameLoc(), TU));
1095}
1096
Douglas Gregor7e242562010-09-01 19:52:22 +00001097bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001098 // Visit nested-name-specifier.
1099 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1100 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1101 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001102
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001103 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1104 return true;
1105
Douglas Gregor7e242562010-09-01 19:52:22 +00001106 return VisitDeclarationNameInfo(D->getNameInfo());
1107}
1108
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001109bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001110 // Visit nested-name-specifier.
1111 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1112 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1113 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001114
1115 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1116 D->getIdentLocation(), TU));
1117}
1118
Douglas Gregor7e242562010-09-01 19:52:22 +00001119bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001120 // Visit nested-name-specifier.
1121 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1122 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1123 return true;
1124
Douglas Gregor7e242562010-09-01 19:52:22 +00001125 return VisitDeclarationNameInfo(D->getNameInfo());
1126}
1127
1128bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1129 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001130 // Visit nested-name-specifier.
1131 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1132 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1133 return true;
1134
Douglas Gregor7e242562010-09-01 19:52:22 +00001135 return false;
1136}
1137
Douglas Gregor01829d32010-08-31 14:41:23 +00001138bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1139 switch (Name.getName().getNameKind()) {
1140 case clang::DeclarationName::Identifier:
1141 case clang::DeclarationName::CXXLiteralOperatorName:
1142 case clang::DeclarationName::CXXOperatorName:
1143 case clang::DeclarationName::CXXUsingDirective:
1144 return false;
1145
1146 case clang::DeclarationName::CXXConstructorName:
1147 case clang::DeclarationName::CXXDestructorName:
1148 case clang::DeclarationName::CXXConversionFunctionName:
1149 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1150 return Visit(TSInfo->getTypeLoc());
1151 return false;
1152
1153 case clang::DeclarationName::ObjCZeroArgSelector:
1154 case clang::DeclarationName::ObjCOneArgSelector:
1155 case clang::DeclarationName::ObjCMultiArgSelector:
1156 // FIXME: Per-identifier location info?
1157 return false;
1158 }
1159
1160 return false;
1161}
1162
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001163bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1164 SourceRange Range) {
1165 // FIXME: This whole routine is a hack to work around the lack of proper
1166 // source information in nested-name-specifiers (PR5791). Since we do have
1167 // a beginning source location, we can visit the first component of the
1168 // nested-name-specifier, if it's a single-token component.
1169 if (!NNS)
1170 return false;
1171
1172 // Get the first component in the nested-name-specifier.
1173 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1174 NNS = Prefix;
1175
1176 switch (NNS->getKind()) {
1177 case NestedNameSpecifier::Namespace:
1178 // FIXME: The token at this source location might actually have been a
1179 // namespace alias, but we don't model that. Lame!
1180 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1181 TU));
1182
1183 case NestedNameSpecifier::TypeSpec: {
1184 // If the type has a form where we know that the beginning of the source
1185 // range matches up with a reference cursor. Visit the appropriate reference
1186 // cursor.
1187 Type *T = NNS->getAsType();
1188 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1189 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1190 if (const TagType *Tag = dyn_cast<TagType>(T))
1191 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1192 if (const TemplateSpecializationType *TST
1193 = dyn_cast<TemplateSpecializationType>(T))
1194 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1195 break;
1196 }
1197
1198 case NestedNameSpecifier::TypeSpecWithTemplate:
1199 case NestedNameSpecifier::Global:
1200 case NestedNameSpecifier::Identifier:
1201 break;
1202 }
1203
1204 return false;
1205}
1206
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001207bool CursorVisitor::VisitTemplateParameters(
1208 const TemplateParameterList *Params) {
1209 if (!Params)
1210 return false;
1211
1212 for (TemplateParameterList::const_iterator P = Params->begin(),
1213 PEnd = Params->end();
1214 P != PEnd; ++P) {
1215 if (Visit(MakeCXCursor(*P, TU)))
1216 return true;
1217 }
1218
1219 return false;
1220}
1221
Douglas Gregor0b36e612010-08-31 20:37:03 +00001222bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1223 switch (Name.getKind()) {
1224 case TemplateName::Template:
1225 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1226
1227 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001228 // Visit the overloaded template set.
1229 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1230 return true;
1231
Douglas Gregor0b36e612010-08-31 20:37:03 +00001232 return false;
1233
1234 case TemplateName::DependentTemplate:
1235 // FIXME: Visit nested-name-specifier.
1236 return false;
1237
1238 case TemplateName::QualifiedTemplate:
1239 // FIXME: Visit nested-name-specifier.
1240 return Visit(MakeCursorTemplateRef(
1241 Name.getAsQualifiedTemplateName()->getDecl(),
1242 Loc, TU));
1243 }
1244
1245 return false;
1246}
1247
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001248bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1249 switch (TAL.getArgument().getKind()) {
1250 case TemplateArgument::Null:
1251 case TemplateArgument::Integral:
1252 return false;
1253
1254 case TemplateArgument::Pack:
1255 // FIXME: Implement when variadic templates come along.
1256 return false;
1257
1258 case TemplateArgument::Type:
1259 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1260 return Visit(TSInfo->getTypeLoc());
1261 return false;
1262
1263 case TemplateArgument::Declaration:
1264 if (Expr *E = TAL.getSourceDeclExpression())
1265 return Visit(MakeCXCursor(E, StmtParent, TU));
1266 return false;
1267
1268 case TemplateArgument::Expression:
1269 if (Expr *E = TAL.getSourceExpression())
1270 return Visit(MakeCXCursor(E, StmtParent, TU));
1271 return false;
1272
1273 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001274 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1275 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001276 }
1277
1278 return false;
1279}
1280
Ted Kremeneka0536d82010-05-07 01:04:29 +00001281bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1282 return VisitDeclContext(D);
1283}
1284
Douglas Gregor01829d32010-08-31 14:41:23 +00001285bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1286 return Visit(TL.getUnqualifiedLoc());
1287}
1288
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001289bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1290 ASTContext &Context = TU->getASTContext();
1291
1292 // Some builtin types (such as Objective-C's "id", "sel", and
1293 // "Class") have associated declarations. Create cursors for those.
1294 QualType VisitType;
1295 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001296 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001297 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001298 case BuiltinType::Char_U:
1299 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001300 case BuiltinType::Char16:
1301 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001302 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001303 case BuiltinType::UInt:
1304 case BuiltinType::ULong:
1305 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001306 case BuiltinType::UInt128:
1307 case BuiltinType::Char_S:
1308 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001309 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001310 case BuiltinType::Short:
1311 case BuiltinType::Int:
1312 case BuiltinType::Long:
1313 case BuiltinType::LongLong:
1314 case BuiltinType::Int128:
1315 case BuiltinType::Float:
1316 case BuiltinType::Double:
1317 case BuiltinType::LongDouble:
1318 case BuiltinType::NullPtr:
1319 case BuiltinType::Overload:
1320 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001321 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001322
1323 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001324 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001325
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001326 case BuiltinType::ObjCId:
1327 VisitType = Context.getObjCIdType();
1328 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001329
1330 case BuiltinType::ObjCClass:
1331 VisitType = Context.getObjCClassType();
1332 break;
1333
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001334 case BuiltinType::ObjCSel:
1335 VisitType = Context.getObjCSelType();
1336 break;
1337 }
1338
1339 if (!VisitType.isNull()) {
1340 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001341 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001342 TU));
1343 }
1344
1345 return false;
1346}
1347
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001348bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1349 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1350}
1351
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001352bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1353 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1354}
1355
1356bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1357 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1358}
1359
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001360bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001361 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001362 // no context information with which we can match up the depth/index in the
1363 // type to the appropriate
1364 return false;
1365}
1366
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001367bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1368 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1369 return true;
1370
John McCallc12c5bb2010-05-15 11:32:37 +00001371 return false;
1372}
1373
1374bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1375 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1376 return true;
1377
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001378 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1379 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1380 TU)))
1381 return true;
1382 }
1383
1384 return false;
1385}
1386
1387bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001388 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001389}
1390
1391bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1392 return Visit(TL.getPointeeLoc());
1393}
1394
1395bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1396 return Visit(TL.getPointeeLoc());
1397}
1398
1399bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1400 return Visit(TL.getPointeeLoc());
1401}
1402
1403bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001404 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001405}
1406
1407bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001408 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001409}
1410
Douglas Gregor01829d32010-08-31 14:41:23 +00001411bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1412 bool SkipResultType) {
1413 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001414 return true;
1415
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001416 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001417 if (Decl *D = TL.getArg(I))
1418 if (Visit(MakeCXCursor(D, TU)))
1419 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001420
1421 return false;
1422}
1423
1424bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1425 if (Visit(TL.getElementLoc()))
1426 return true;
1427
1428 if (Expr *Size = TL.getSizeExpr())
1429 return Visit(MakeCXCursor(Size, StmtParent, TU));
1430
1431 return false;
1432}
1433
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001434bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1435 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001436 // Visit the template name.
1437 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1438 TL.getTemplateNameLoc()))
1439 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001440
1441 // Visit the template arguments.
1442 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1443 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1444 return true;
1445
1446 return false;
1447}
1448
Douglas Gregor2332c112010-01-21 20:48:56 +00001449bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1450 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1451}
1452
1453bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1454 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1455 return Visit(TSInfo->getTypeLoc());
1456
1457 return false;
1458}
1459
Douglas Gregora59e3902010-01-21 23:27:09 +00001460bool CursorVisitor::VisitStmt(Stmt *S) {
1461 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1462 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001463 if (Stmt *C = *Child)
1464 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1465 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001466 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001467
Douglas Gregora59e3902010-01-21 23:27:09 +00001468 return false;
1469}
1470
1471bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
Ted Kremenek007a7c92010-11-01 23:26:51 +00001472 bool isFirst = true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001473 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1474 D != DEnd; ++D) {
Ted Kremenek007a7c92010-11-01 23:26:51 +00001475 if (*D && Visit(MakeCXCursor(*D, TU, isFirst)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001476 return true;
Ted Kremenek007a7c92010-11-01 23:26:51 +00001477 isFirst = false;
Douglas Gregora59e3902010-01-21 23:27:09 +00001478 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001479
Douglas Gregora59e3902010-01-21 23:27:09 +00001480 return false;
1481}
1482
Douglas Gregor36897b02010-09-10 00:22:18 +00001483bool CursorVisitor::VisitGotoStmt(GotoStmt *S) {
1484 return Visit(MakeCursorLabelRef(S->getLabel(), S->getLabelLoc(), TU));
1485}
1486
Douglas Gregor8947a752010-09-02 20:35:02 +00001487bool CursorVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
1488 // Visit nested-name-specifier, if present.
1489 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1490 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1491 return true;
1492
1493 // Visit declaration name.
1494 if (VisitDeclarationNameInfo(E->getNameInfo()))
1495 return true;
1496
1497 // Visit explicitly-specified template arguments.
1498 if (E->hasExplicitTemplateArgs()) {
1499 ExplicitTemplateArgumentList &Args = E->getExplicitTemplateArgs();
1500 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1501 *ArgEnd = Arg + Args.NumTemplateArgs;
1502 Arg != ArgEnd; ++Arg)
1503 if (VisitTemplateArgumentLoc(*Arg))
1504 return true;
1505 }
1506
1507 return false;
1508}
1509
Ted Kremenek3064ef92010-08-27 21:34:58 +00001510bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1511 if (D->isDefinition()) {
1512 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1513 E = D->bases_end(); I != E; ++I) {
1514 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1515 return true;
1516 }
1517 }
1518
1519 return VisitTagDecl(D);
1520}
1521
1522
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001523bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1524 return Visit(B->getBlockDecl());
1525}
1526
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001527bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001528 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001529 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1530 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001531
1532 // Visit the components of the offsetof expression.
1533 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1534 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1535 const OffsetOfNode &Node = E->getComponent(I);
1536 switch (Node.getKind()) {
1537 case OffsetOfNode::Array:
1538 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1539 StmtParent, TU)))
1540 return true;
1541 break;
1542
1543 case OffsetOfNode::Field:
1544 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1545 TU)))
1546 return true;
1547 break;
1548
1549 case OffsetOfNode::Identifier:
1550 case OffsetOfNode::Base:
1551 continue;
1552 }
1553 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001554
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001555 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001556}
1557
Douglas Gregor336fd812010-01-23 00:40:08 +00001558bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1559 if (E->isArgumentType()) {
1560 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1561 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001562
Douglas Gregor336fd812010-01-23 00:40:08 +00001563 return false;
1564 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001565
Douglas Gregor336fd812010-01-23 00:40:08 +00001566 return VisitExpr(E);
1567}
1568
Douglas Gregor36897b02010-09-10 00:22:18 +00001569bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1570 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1571}
1572
Douglas Gregor648220e2010-08-10 15:02:34 +00001573bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1574 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1575 Visit(E->getArgTInfo2()->getTypeLoc());
1576}
1577
1578bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1579 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1580 return true;
1581
1582 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1583}
1584
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001585bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1586 // Visit the designators.
1587 typedef DesignatedInitExpr::Designator Designator;
1588 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1589 DEnd = E->designators_end();
1590 D != DEnd; ++D) {
1591 if (D->isFieldDesignator()) {
1592 if (FieldDecl *Field = D->getField())
1593 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1594 return true;
1595
1596 continue;
1597 }
1598
1599 if (D->isArrayDesignator()) {
1600 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1601 return true;
1602
1603 continue;
1604 }
1605
1606 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1607 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1608 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1609 return true;
1610 }
1611
1612 // Visit the initializer value itself.
1613 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1614}
1615
Douglas Gregor94802292010-09-02 21:20:16 +00001616bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1617 if (E->isTypeOperand()) {
1618 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1619 return Visit(TSInfo->getTypeLoc());
1620
1621 return false;
1622 }
1623
1624 return VisitExpr(E);
1625}
1626
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001627bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1628 if (E->isTypeOperand()) {
1629 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1630 return Visit(TSInfo->getTypeLoc());
1631
1632 return false;
1633 }
1634
1635 return VisitExpr(E);
1636}
1637
Douglas Gregorab6677e2010-09-08 00:15:04 +00001638bool CursorVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1639 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
Douglas Gregor40749ee2010-11-03 00:35:38 +00001640 if (Visit(TSInfo->getTypeLoc()))
1641 return true;
Douglas Gregorab6677e2010-09-08 00:15:04 +00001642
1643 return VisitExpr(E);
1644}
1645
1646bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1647 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1648 return Visit(TSInfo->getTypeLoc());
1649
1650 return false;
1651}
1652
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001653bool CursorVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1654 // Visit placement arguments.
1655 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1656 if (Visit(MakeCXCursor(E->getPlacementArg(I), StmtParent, TU)))
1657 return true;
1658
1659 // Visit the allocated type.
1660 if (TypeSourceInfo *TSInfo = E->getAllocatedTypeSourceInfo())
1661 if (Visit(TSInfo->getTypeLoc()))
1662 return true;
1663
1664 // Visit the array size, if any.
1665 if (E->isArray() && Visit(MakeCXCursor(E->getArraySize(), StmtParent, TU)))
1666 return true;
1667
1668 // Visit the initializer or constructor arguments.
1669 for (unsigned I = 0, N = E->getNumConstructorArgs(); I != N; ++I)
1670 if (Visit(MakeCXCursor(E->getConstructorArg(I), StmtParent, TU)))
1671 return true;
1672
1673 return false;
1674}
1675
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001676bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1677 // Visit base expression.
1678 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1679 return true;
1680
1681 // Visit the nested-name-specifier.
1682 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1683 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1684 return true;
1685
1686 // Visit the scope type that looks disturbingly like the nested-name-specifier
1687 // but isn't.
1688 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1689 if (Visit(TSInfo->getTypeLoc()))
1690 return true;
1691
1692 // Visit the name of the type being destroyed.
1693 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1694 if (Visit(TSInfo->getTypeLoc()))
1695 return true;
1696
1697 return false;
1698}
1699
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001700bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1701 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1702}
1703
Douglas Gregorbfebed22010-09-03 17:24:10 +00001704bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1705 DependentScopeDeclRefExpr *E) {
1706 // Visit the nested-name-specifier.
1707 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1708 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1709 return true;
1710
1711 // Visit the declaration name.
1712 if (VisitDeclarationNameInfo(E->getNameInfo()))
1713 return true;
1714
1715 // Visit the explicitly-specified template arguments.
1716 if (const ExplicitTemplateArgumentList *ArgList
1717 = E->getOptionalExplicitTemplateArgs()) {
1718 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1719 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1720 Arg != ArgEnd; ++Arg) {
1721 if (VisitTemplateArgumentLoc(*Arg))
1722 return true;
1723 }
1724 }
1725
1726 return false;
1727}
1728
Douglas Gregorab6677e2010-09-08 00:15:04 +00001729bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1730 CXXUnresolvedConstructExpr *E) {
1731 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1732 if (Visit(TSInfo->getTypeLoc()))
1733 return true;
1734
1735 return VisitExpr(E);
1736}
1737
Douglas Gregor25d63622010-09-03 17:35:34 +00001738bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1739 CXXDependentScopeMemberExpr *E) {
1740 // Visit the base expression, if there is one.
1741 if (!E->isImplicitAccess() &&
1742 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1743 return true;
1744
1745 // Visit the nested-name-specifier.
1746 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1747 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1748 return true;
1749
1750 // Visit the declaration name.
1751 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1752 return true;
1753
1754 // Visit the explicitly-specified template arguments.
1755 if (const ExplicitTemplateArgumentList *ArgList
1756 = E->getOptionalExplicitTemplateArgs()) {
1757 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1758 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1759 Arg != ArgEnd; ++Arg) {
1760 if (VisitTemplateArgumentLoc(*Arg))
1761 return true;
1762 }
1763 }
1764
1765 return false;
1766}
1767
Douglas Gregor81d34662010-04-20 15:39:42 +00001768bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1769 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1770}
1771
1772
Ted Kremenek09dfa372010-02-18 05:46:33 +00001773bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001774 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1775 i != e; ++i)
1776 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001777 return true;
1778
1779 return false;
1780}
1781
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001782//===----------------------------------------------------------------------===//
1783// Data-recursive visitor methods.
1784//===----------------------------------------------------------------------===//
1785
Ted Kremenek28a71942010-11-13 00:36:47 +00001786namespace {
1787class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1788 VisitorWorkList &WL;
1789 CXCursor Parent;
1790public:
1791 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1792 : WL(wl), Parent(parent) {}
1793
1794 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
1795 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
1796 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1797 void VisitForStmt(ForStmt *FS);
1798 void VisitIfStmt(IfStmt *If);
1799 void VisitInitListExpr(InitListExpr *IE);
1800 void VisitMemberExpr(MemberExpr *M);
1801 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1802 void VisitOverloadExpr(OverloadExpr *E);
1803 void VisitStmt(Stmt *S);
1804 void VisitSwitchStmt(SwitchStmt *S);
1805 void VisitWhileStmt(WhileStmt *W);
1806 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
1807
1808private:
1809 void AddStmt(Stmt *S);
1810 void AddDecl(Decl *D);
1811 void AddTypeLoc(TypeSourceInfo *TI);
1812 void EnqueueChildren(Stmt *S);
1813};
1814} // end anonyous namespace
1815
1816void EnqueueVisitor::AddStmt(Stmt *S) {
1817 if (S)
1818 WL.push_back(StmtVisit(S, Parent));
1819}
1820void EnqueueVisitor::AddDecl(Decl *D) {
1821 if (D)
1822 WL.push_back(DeclVisit(D, Parent));
1823}
1824void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1825 if (TI)
1826 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1827 }
1828void EnqueueVisitor::EnqueueChildren(Stmt *S) {
Ted Kremeneka6b70432010-11-12 21:34:09 +00001829 unsigned size = WL.size();
1830 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1831 Child != ChildEnd; ++Child) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001832 AddStmt(*Child);
Ted Kremeneka6b70432010-11-12 21:34:09 +00001833 }
1834 if (size == WL.size())
1835 return;
1836 // Now reverse the entries we just added. This will match the DFS
1837 // ordering performed by the worklist.
1838 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1839 std::reverse(I, E);
1840}
Ted Kremenek28a71942010-11-13 00:36:47 +00001841void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1842 EnqueueChildren(E);
1843 AddTypeLoc(E->getTypeSourceInfo());
1844}
1845void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
1846 // Note that we enqueue things in reverse order so that
1847 // they are visited correctly by the DFS.
1848 for (unsigned I = 1, N = CE->getNumArgs(); I != N; ++I)
1849 AddStmt(CE->getArg(N-I));
1850 AddStmt(CE->getCallee());
1851 AddStmt(CE->getArg(0));
1852}
1853void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1854 EnqueueChildren(E);
1855 AddTypeLoc(E->getTypeInfoAsWritten());
1856}
1857void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1858 AddStmt(FS->getBody());
1859 AddStmt(FS->getInc());
1860 AddStmt(FS->getCond());
1861 AddDecl(FS->getConditionVariable());
1862 AddStmt(FS->getInit());
1863}
1864void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1865 AddStmt(If->getElse());
1866 AddStmt(If->getThen());
1867 AddStmt(If->getCond());
1868 AddDecl(If->getConditionVariable());
1869}
1870void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1871 // We care about the syntactic form of the initializer list, only.
1872 if (InitListExpr *Syntactic = IE->getSyntacticForm())
1873 IE = Syntactic;
1874 EnqueueChildren(IE);
1875}
1876void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
1877 WL.push_back(MemberExprParts(M, Parent));
1878 AddStmt(M->getBase());
1879}
1880void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
1881 EnqueueChildren(M);
1882 AddTypeLoc(M->getClassReceiverTypeInfo());
1883}
1884void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
Ted Kremenek60458782010-11-12 21:34:16 +00001885 WL.push_back(OverloadExprParts(E, Parent));
1886}
Ted Kremenek28a71942010-11-13 00:36:47 +00001887void EnqueueVisitor::VisitStmt(Stmt *S) {
1888 EnqueueChildren(S);
1889}
1890void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
1891 AddStmt(S->getBody());
1892 AddStmt(S->getCond());
1893 AddDecl(S->getConditionVariable());
1894}
1895void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
1896 AddStmt(W->getBody());
1897 AddStmt(W->getCond());
1898 AddDecl(W->getConditionVariable());
1899}
1900void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
1901 VisitOverloadExpr(U);
1902 if (!U->isImplicitAccess())
1903 AddStmt(U->getBase());
1904}
Ted Kremenek60458782010-11-12 21:34:16 +00001905
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001906void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
Ted Kremenek28a71942010-11-13 00:36:47 +00001907 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU)).Visit(S);
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001908}
1909
1910bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1911 if (RegionOfInterest.isValid()) {
1912 SourceRange Range = getRawCursorExtent(C);
1913 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1914 return false;
1915 }
1916 return true;
1917}
1918
1919bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
1920 while (!WL.empty()) {
1921 // Dequeue the worklist item.
1922 VisitorJob LI = WL.back(); WL.pop_back();
1923
1924 // Set the Parent field, then back to its old value once we're done.
1925 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
1926
1927 switch (LI.getKind()) {
Ted Kremenekf1107452010-11-12 18:26:56 +00001928 case VisitorJob::DeclVisitKind: {
1929 Decl *D = cast<DeclVisit>(LI).get();
1930 if (!D)
1931 continue;
1932
1933 // For now, perform default visitation for Decls.
1934 if (Visit(MakeCXCursor(D, TU)))
1935 return true;
1936
1937 continue;
1938 }
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001939 case VisitorJob::TypeLocVisitKind: {
1940 // Perform default visitation for TypeLocs.
1941 if (Visit(cast<TypeLocVisit>(LI).get()))
1942 return true;
1943 continue;
1944 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001945 case VisitorJob::StmtVisitKind: {
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001946 Stmt *S = cast<StmtVisit>(LI).get();
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001947 if (!S)
1948 continue;
1949
Ted Kremenekf1107452010-11-12 18:26:56 +00001950 // Update the current cursor.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001951 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1952
1953 switch (S->getStmtClass()) {
1954 default: {
Ted Kremenek99394242010-11-12 22:24:57 +00001955 // FIXME: this entire switch stmt will eventually
1956 // go away.
1957 if (!isa<ExplicitCastExpr>(S)) {
1958 // Perform default visitation for other cases.
1959 if (Visit(Cursor))
1960 return true;
1961 continue;
1962 }
1963 // Fall-through.
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001964 }
Ted Kremenekf1107452010-11-12 18:26:56 +00001965 case Stmt::BinaryOperatorClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001966 case Stmt::CallExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001967 case Stmt::CaseStmtClass:
Ted Kremenekcdb4caf2010-11-12 21:34:12 +00001968 case Stmt::CompoundLiteralExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001969 case Stmt::CompoundStmtClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001970 case Stmt::CXXMemberCallExprClass:
Ted Kremenek8c269ac2010-11-11 23:11:43 +00001971 case Stmt::CXXOperatorCallExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001972 case Stmt::DefaultStmtClass:
Ted Kremenekbb677132010-11-12 18:27:04 +00001973 case Stmt::DoStmtClass:
1974 case Stmt::ForStmtClass:
Ted Kremenekc70ebba2010-11-12 18:26:58 +00001975 case Stmt::IfStmtClass:
Ted Kremeneka6b70432010-11-12 21:34:09 +00001976 case Stmt::InitListExprClass:
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001977 case Stmt::MemberExprClass:
Ted Kremenekc373e3c2010-11-12 22:24:55 +00001978 case Stmt::ObjCMessageExprClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001979 case Stmt::ParenExprClass:
1980 case Stmt::SwitchStmtClass:
Ted Kremenekae3c2202010-11-12 18:27:01 +00001981 case Stmt::UnaryOperatorClass:
Ted Kremenek60458782010-11-12 21:34:16 +00001982 case Stmt::UnresolvedLookupExprClass:
1983 case Stmt::UnresolvedMemberExprClass:
Ted Kremenekbb677132010-11-12 18:27:04 +00001984 case Stmt::WhileStmtClass:
Ted Kremenekf1107452010-11-12 18:26:56 +00001985 {
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001986 if (!IsInRegionOfInterest(Cursor))
1987 continue;
1988 switch (Visitor(Cursor, Parent, ClientData)) {
1989 case CXChildVisit_Break:
1990 return true;
1991 case CXChildVisit_Continue:
1992 break;
1993 case CXChildVisit_Recurse:
1994 EnqueueWorkList(WL, S);
1995 break;
1996 }
1997 }
1998 }
1999 continue;
2000 }
2001 case VisitorJob::MemberExprPartsKind: {
2002 // Handle the other pieces in the MemberExpr besides the base.
2003 MemberExpr *M = cast<MemberExprParts>(LI).get();
2004
2005 // Visit the nested-name-specifier
2006 if (NestedNameSpecifier *Qualifier = M->getQualifier())
2007 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
2008 return true;
2009
2010 // Visit the declaration name.
2011 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2012 return true;
2013
2014 // Visit the explicitly-specified template arguments, if any.
2015 if (M->hasExplicitTemplateArgs()) {
2016 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2017 *ArgEnd = Arg + M->getNumTemplateArgs();
2018 Arg != ArgEnd; ++Arg) {
2019 if (VisitTemplateArgumentLoc(*Arg))
2020 return true;
2021 }
2022 }
2023 continue;
2024 }
Ted Kremenek60458782010-11-12 21:34:16 +00002025 case VisitorJob::OverloadExprPartsKind: {
2026 OverloadExpr *O = cast<OverloadExprParts>(LI).get();
2027 // Visit the nested-name-specifier.
2028 if (NestedNameSpecifier *Qualifier = O->getQualifier())
2029 if (VisitNestedNameSpecifier(Qualifier, O->getQualifierRange()))
2030 return true;
2031 // Visit the declaration name.
2032 if (VisitDeclarationNameInfo(O->getNameInfo()))
2033 return true;
2034 // Visit the overloaded declaration reference.
2035 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2036 return true;
2037 // Visit the explicitly-specified template arguments.
2038 if (const ExplicitTemplateArgumentList *ArgList
2039 = O->getOptionalExplicitTemplateArgs()) {
2040 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2041 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2042 Arg != ArgEnd; ++Arg) {
2043 if (VisitTemplateArgumentLoc(*Arg))
2044 return true;
2045 }
2046 }
2047 continue;
2048 }
Ted Kremenekc0e1d922010-11-11 08:05:18 +00002049 }
2050 }
2051 return false;
2052}
2053
2054bool CursorVisitor::VisitDataRecursive(Stmt *S) {
2055 VisitorWorkList WL;
2056 EnqueueWorkList(WL, S);
2057 return RunVisitorWorkList(WL);
2058}
2059
2060//===----------------------------------------------------------------------===//
2061// Misc. API hooks.
2062//===----------------------------------------------------------------------===//
2063
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002064static llvm::sys::Mutex EnableMultithreadingMutex;
2065static bool EnabledMultithreading;
2066
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002067extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002068CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2069 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002070 // Disable pretty stack trace functionality, which will otherwise be a very
2071 // poor citizen of the world and set up all sorts of signal handlers.
2072 llvm::DisablePrettyStackTrace = true;
2073
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002074 // We use crash recovery to make some of our APIs more reliable, implicitly
2075 // enable it.
2076 llvm::CrashRecoveryContext::Enable();
2077
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002078 // Enable support for multithreading in LLVM.
2079 {
2080 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2081 if (!EnabledMultithreading) {
2082 llvm::llvm_start_multithreaded();
2083 EnabledMultithreading = true;
2084 }
2085 }
2086
Douglas Gregora030b7c2010-01-22 20:35:53 +00002087 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002088 if (excludeDeclarationsFromPCH)
2089 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002090 if (displayDiagnostics)
2091 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002092 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002093}
2094
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002095void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002096 if (CIdx)
2097 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002098}
2099
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002100CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002101 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002102 if (!CIdx)
2103 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002104
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002105 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002106 FileSystemOptions FileSystemOpts;
2107 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002108
Douglas Gregor28019772010-04-05 23:52:57 +00002109 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002110 return ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002111 CXXIdx->getOnlyLocalDecls(),
2112 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00002113}
2114
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002115unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002116 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002117 CXTranslationUnit_CacheCompletionResults |
2118 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002119}
2120
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002121CXTranslationUnit
2122clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2123 const char *source_filename,
2124 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002125 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002126 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002127 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002128 return clang_parseTranslationUnit(CIdx, source_filename,
2129 command_line_args, num_command_line_args,
2130 unsaved_files, num_unsaved_files,
2131 CXTranslationUnit_DetailedPreprocessingRecord);
2132}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002133
2134struct ParseTranslationUnitInfo {
2135 CXIndex CIdx;
2136 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002137 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002138 int num_command_line_args;
2139 struct CXUnsavedFile *unsaved_files;
2140 unsigned num_unsaved_files;
2141 unsigned options;
2142 CXTranslationUnit result;
2143};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002144static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002145 ParseTranslationUnitInfo *PTUI =
2146 static_cast<ParseTranslationUnitInfo*>(UserData);
2147 CXIndex CIdx = PTUI->CIdx;
2148 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002149 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002150 int num_command_line_args = PTUI->num_command_line_args;
2151 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2152 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2153 unsigned options = PTUI->options;
2154 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002155
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002156 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002157 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002158
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002159 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2160
Douglas Gregor44c181a2010-07-23 00:33:23 +00002161 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002162 bool CompleteTranslationUnit
2163 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002164 bool CacheCodeCompetionResults
2165 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002166 bool CXXPrecompilePreamble
2167 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2168 bool CXXChainedPCH
2169 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002170
Douglas Gregor5352ac02010-01-28 00:27:43 +00002171 // Configure the diagnostics.
2172 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002173 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2174 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002175
Douglas Gregor4db64a42010-01-23 00:14:00 +00002176 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2177 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002178 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002179 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002180 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002181 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2182 Buffer));
2183 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002184
Douglas Gregorb10daed2010-10-11 16:52:23 +00002185 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002186
Ted Kremenek139ba862009-10-22 00:03:57 +00002187 // The 'source_filename' argument is optional. If the caller does not
2188 // specify it then it is assumed that the source file is specified
2189 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002190 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002191 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002192
2193 // Since the Clang C library is primarily used by batch tools dealing with
2194 // (often very broken) source code, where spell-checking can have a
2195 // significant negative impact on performance (particularly when
2196 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002197 // Only do this if we haven't found a spell-checking-related argument.
2198 bool FoundSpellCheckingArgument = false;
2199 for (int I = 0; I != num_command_line_args; ++I) {
2200 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2201 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2202 FoundSpellCheckingArgument = true;
2203 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002204 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002205 }
2206 if (!FoundSpellCheckingArgument)
2207 Args.push_back("-fno-spell-checking");
2208
2209 Args.insert(Args.end(), command_line_args,
2210 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002211
Douglas Gregor44c181a2010-07-23 00:33:23 +00002212 // Do we need the detailed preprocessing record?
2213 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002214 Args.push_back("-Xclang");
2215 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002216 }
2217
Douglas Gregorb10daed2010-10-11 16:52:23 +00002218 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002219 llvm::OwningPtr<ASTUnit> Unit(
2220 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2221 Diags,
2222 CXXIdx->getClangResourcesPath(),
2223 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002224 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002225 RemappedFiles.data(),
2226 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002227 PrecompilePreamble,
2228 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002229 CacheCodeCompetionResults,
2230 CXXPrecompilePreamble,
2231 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002232
Douglas Gregorb10daed2010-10-11 16:52:23 +00002233 if (NumErrors != Diags->getNumErrors()) {
2234 // Make sure to check that 'Unit' is non-NULL.
2235 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2236 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2237 DEnd = Unit->stored_diag_end();
2238 D != DEnd; ++D) {
2239 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2240 CXString Msg = clang_formatDiagnostic(&Diag,
2241 clang_defaultDiagnosticDisplayOptions());
2242 fprintf(stderr, "%s\n", clang_getCString(Msg));
2243 clang_disposeString(Msg);
2244 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002245#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002246 // On Windows, force a flush, since there may be multiple copies of
2247 // stderr and stdout in the file system, all with different buffers
2248 // but writing to the same device.
2249 fflush(stderr);
2250#endif
2251 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002252 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002253
Douglas Gregorb10daed2010-10-11 16:52:23 +00002254 PTUI->result = Unit.take();
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002255}
2256CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2257 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002258 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002259 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002260 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002261 unsigned num_unsaved_files,
2262 unsigned options) {
2263 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002264 num_command_line_args, unsaved_files,
2265 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002266 llvm::CrashRecoveryContext CRC;
2267
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002268 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002269 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2270 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2271 fprintf(stderr, " 'command_line_args' : [");
2272 for (int i = 0; i != num_command_line_args; ++i) {
2273 if (i)
2274 fprintf(stderr, ", ");
2275 fprintf(stderr, "'%s'", command_line_args[i]);
2276 }
2277 fprintf(stderr, "],\n");
2278 fprintf(stderr, " 'unsaved_files' : [");
2279 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2280 if (i)
2281 fprintf(stderr, ", ");
2282 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2283 unsaved_files[i].Length);
2284 }
2285 fprintf(stderr, "],\n");
2286 fprintf(stderr, " 'options' : %d,\n", options);
2287 fprintf(stderr, "}\n");
2288
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002289 return 0;
2290 }
2291
2292 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002293}
2294
Douglas Gregor19998442010-08-13 15:35:05 +00002295unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2296 return CXSaveTranslationUnit_None;
2297}
2298
2299int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2300 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002301 if (!TU)
2302 return 1;
2303
2304 return static_cast<ASTUnit *>(TU)->Save(FileName);
2305}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002306
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002307void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002308 if (CTUnit) {
2309 // If the translation unit has been marked as unsafe to free, just discard
2310 // it.
2311 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2312 return;
2313
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002314 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002315 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002316}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002317
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002318unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2319 return CXReparse_None;
2320}
2321
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002322struct ReparseTranslationUnitInfo {
2323 CXTranslationUnit TU;
2324 unsigned num_unsaved_files;
2325 struct CXUnsavedFile *unsaved_files;
2326 unsigned options;
2327 int result;
2328};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002329
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002330static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002331 ReparseTranslationUnitInfo *RTUI =
2332 static_cast<ReparseTranslationUnitInfo*>(UserData);
2333 CXTranslationUnit TU = RTUI->TU;
2334 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2335 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2336 unsigned options = RTUI->options;
2337 (void) options;
2338 RTUI->result = 1;
2339
Douglas Gregorabc563f2010-07-19 21:46:24 +00002340 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002341 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002342
2343 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2344 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002345
2346 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2347 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2348 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2349 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002350 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002351 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2352 Buffer));
2353 }
2354
Douglas Gregor593b0c12010-09-23 18:47:53 +00002355 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2356 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002357}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002358
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002359int clang_reparseTranslationUnit(CXTranslationUnit TU,
2360 unsigned num_unsaved_files,
2361 struct CXUnsavedFile *unsaved_files,
2362 unsigned options) {
2363 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2364 options, 0 };
2365 llvm::CrashRecoveryContext CRC;
2366
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002367 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002368 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002369 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2370 return 1;
2371 }
2372
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002373
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002374 return RTUI.result;
2375}
2376
Douglas Gregordf95a132010-08-09 20:45:32 +00002377
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002378CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002379 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002380 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002381
Steve Naroff77accc12009-09-03 18:19:54 +00002382 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002383 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002384}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002385
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002386CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002387 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002388 return Result;
2389}
2390
Ted Kremenekfb480492010-01-13 21:46:36 +00002391} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002392
Ted Kremenekfb480492010-01-13 21:46:36 +00002393//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002394// CXSourceLocation and CXSourceRange Operations.
2395//===----------------------------------------------------------------------===//
2396
Douglas Gregorb9790342010-01-22 21:44:22 +00002397extern "C" {
2398CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002399 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002400 return Result;
2401}
2402
2403unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002404 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2405 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2406 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002407}
2408
2409CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2410 CXFile file,
2411 unsigned line,
2412 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002413 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002414 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002415
Douglas Gregorb9790342010-01-22 21:44:22 +00002416 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2417 SourceLocation SLoc
2418 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002419 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002420 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002421 if (SLoc.isInvalid()) return clang_getNullLocation();
2422
2423 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2424}
2425
2426CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2427 CXFile file,
2428 unsigned offset) {
2429 if (!tu || !file)
2430 return clang_getNullLocation();
2431
2432 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2433 SourceLocation Start
2434 = CXXUnit->getSourceManager().getLocation(
2435 static_cast<const FileEntry *>(file),
2436 1, 1);
2437 if (Start.isInvalid()) return clang_getNullLocation();
2438
2439 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2440
2441 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002442
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002443 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002444}
2445
Douglas Gregor5352ac02010-01-28 00:27:43 +00002446CXSourceRange clang_getNullRange() {
2447 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2448 return Result;
2449}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002450
Douglas Gregor5352ac02010-01-28 00:27:43 +00002451CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2452 if (begin.ptr_data[0] != end.ptr_data[0] ||
2453 begin.ptr_data[1] != end.ptr_data[1])
2454 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002455
2456 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002457 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002458 return Result;
2459}
2460
Douglas Gregor46766dc2010-01-26 19:19:08 +00002461void clang_getInstantiationLocation(CXSourceLocation location,
2462 CXFile *file,
2463 unsigned *line,
2464 unsigned *column,
2465 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002466 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2467
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002468 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002469 if (file)
2470 *file = 0;
2471 if (line)
2472 *line = 0;
2473 if (column)
2474 *column = 0;
2475 if (offset)
2476 *offset = 0;
2477 return;
2478 }
2479
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002480 const SourceManager &SM =
2481 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002482 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002483
2484 if (file)
2485 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2486 if (line)
2487 *line = SM.getInstantiationLineNumber(InstLoc);
2488 if (column)
2489 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002490 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002491 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002492}
2493
Douglas Gregora9b06d42010-11-09 06:24:54 +00002494void clang_getSpellingLocation(CXSourceLocation location,
2495 CXFile *file,
2496 unsigned *line,
2497 unsigned *column,
2498 unsigned *offset) {
2499 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2500
2501 if (!location.ptr_data[0] || Loc.isInvalid()) {
2502 if (file)
2503 *file = 0;
2504 if (line)
2505 *line = 0;
2506 if (column)
2507 *column = 0;
2508 if (offset)
2509 *offset = 0;
2510 return;
2511 }
2512
2513 const SourceManager &SM =
2514 *static_cast<const SourceManager*>(location.ptr_data[0]);
2515 SourceLocation SpellLoc = Loc;
2516 if (SpellLoc.isMacroID()) {
2517 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2518 if (SimpleSpellingLoc.isFileID() &&
2519 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2520 SpellLoc = SimpleSpellingLoc;
2521 else
2522 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2523 }
2524
2525 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2526 FileID FID = LocInfo.first;
2527 unsigned FileOffset = LocInfo.second;
2528
2529 if (file)
2530 *file = (void *)SM.getFileEntryForID(FID);
2531 if (line)
2532 *line = SM.getLineNumber(FID, FileOffset);
2533 if (column)
2534 *column = SM.getColumnNumber(FID, FileOffset);
2535 if (offset)
2536 *offset = FileOffset;
2537}
2538
Douglas Gregor1db19de2010-01-19 21:36:55 +00002539CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002540 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002541 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002542 return Result;
2543}
2544
2545CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002546 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002547 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002548 return Result;
2549}
2550
Douglas Gregorb9790342010-01-22 21:44:22 +00002551} // end: extern "C"
2552
Douglas Gregor1db19de2010-01-19 21:36:55 +00002553//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002554// CXFile Operations.
2555//===----------------------------------------------------------------------===//
2556
2557extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002558CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002559 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002560 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002561
Steve Naroff88145032009-10-27 14:35:18 +00002562 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002563 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002564}
2565
2566time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002567 if (!SFile)
2568 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002569
Steve Naroff88145032009-10-27 14:35:18 +00002570 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2571 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002572}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002573
Douglas Gregorb9790342010-01-22 21:44:22 +00002574CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2575 if (!tu)
2576 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002577
Douglas Gregorb9790342010-01-22 21:44:22 +00002578 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002579
Douglas Gregorb9790342010-01-22 21:44:22 +00002580 FileManager &FMgr = CXXUnit->getFileManager();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002581 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2582 CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002583 return const_cast<FileEntry *>(File);
2584}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002585
Ted Kremenekfb480492010-01-13 21:46:36 +00002586} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002587
Ted Kremenekfb480492010-01-13 21:46:36 +00002588//===----------------------------------------------------------------------===//
2589// CXCursor Operations.
2590//===----------------------------------------------------------------------===//
2591
Ted Kremenekfb480492010-01-13 21:46:36 +00002592static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002593 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2594 return getDeclFromExpr(CE->getSubExpr());
2595
Ted Kremenekfb480492010-01-13 21:46:36 +00002596 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2597 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002598 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2599 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002600 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2601 return ME->getMemberDecl();
2602 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2603 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002604 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2605 return PRE->getProperty();
2606
Ted Kremenekfb480492010-01-13 21:46:36 +00002607 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2608 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002609 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2610 if (!CE->isElidable())
2611 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002612 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2613 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002614
Douglas Gregordb1314e2010-10-01 21:11:22 +00002615 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2616 return PE->getProtocol();
2617
Ted Kremenekfb480492010-01-13 21:46:36 +00002618 return 0;
2619}
2620
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002621static SourceLocation getLocationFromExpr(Expr *E) {
2622 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2623 return /*FIXME:*/Msg->getLeftLoc();
2624 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2625 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002626 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2627 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002628 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2629 return Member->getMemberLoc();
2630 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2631 return Ivar->getLocation();
2632 return E->getLocStart();
2633}
2634
Ted Kremenekfb480492010-01-13 21:46:36 +00002635extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002636
2637unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002638 CXCursorVisitor visitor,
2639 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002640 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002641
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002642 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2643 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002644 return CursorVis.VisitChildren(parent);
2645}
2646
David Chisnall3387c652010-11-03 14:12:26 +00002647#ifndef __has_feature
2648#define __has_feature(x) 0
2649#endif
2650#if __has_feature(blocks)
2651typedef enum CXChildVisitResult
2652 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2653
2654static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2655 CXClientData client_data) {
2656 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2657 return block(cursor, parent);
2658}
2659#else
2660// If we are compiled with a compiler that doesn't have native blocks support,
2661// define and call the block manually, so the
2662typedef struct _CXChildVisitResult
2663{
2664 void *isa;
2665 int flags;
2666 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002667 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2668 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002669} *CXCursorVisitorBlock;
2670
2671static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2672 CXClientData client_data) {
2673 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2674 return block->invoke(block, cursor, parent);
2675}
2676#endif
2677
2678
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002679unsigned clang_visitChildrenWithBlock(CXCursor parent,
2680 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002681 return clang_visitChildren(parent, visitWithBlock, block);
2682}
2683
Douglas Gregor78205d42010-01-20 21:45:58 +00002684static CXString getDeclSpelling(Decl *D) {
2685 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2686 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002687 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002688
Douglas Gregor78205d42010-01-20 21:45:58 +00002689 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002690 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002691
Douglas Gregor78205d42010-01-20 21:45:58 +00002692 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2693 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2694 // and returns different names. NamedDecl returns the class name and
2695 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002696 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002697
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002698 if (isa<UsingDirectiveDecl>(D))
2699 return createCXString("");
2700
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002701 llvm::SmallString<1024> S;
2702 llvm::raw_svector_ostream os(S);
2703 ND->printName(os);
2704
2705 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002706}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002707
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002708CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002709 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002710 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002711
Steve Narofff334b4e2009-09-02 18:26:48 +00002712 if (clang_isReference(C.kind)) {
2713 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002714 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002715 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002716 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002717 }
2718 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002719 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002720 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002721 }
2722 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002723 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002724 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002725 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002726 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002727 case CXCursor_CXXBaseSpecifier: {
2728 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2729 return createCXString(B->getType().getAsString());
2730 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002731 case CXCursor_TypeRef: {
2732 TypeDecl *Type = getCursorTypeRef(C).first;
2733 assert(Type && "Missing type decl");
2734
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002735 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2736 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002737 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002738 case CXCursor_TemplateRef: {
2739 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002740 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002741
2742 return createCXString(Template->getNameAsString());
2743 }
Douglas Gregor69319002010-08-31 23:48:11 +00002744
2745 case CXCursor_NamespaceRef: {
2746 NamedDecl *NS = getCursorNamespaceRef(C).first;
2747 assert(NS && "Missing namespace decl");
2748
2749 return createCXString(NS->getNameAsString());
2750 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002751
Douglas Gregora67e03f2010-09-09 21:42:20 +00002752 case CXCursor_MemberRef: {
2753 FieldDecl *Field = getCursorMemberRef(C).first;
2754 assert(Field && "Missing member decl");
2755
2756 return createCXString(Field->getNameAsString());
2757 }
2758
Douglas Gregor36897b02010-09-10 00:22:18 +00002759 case CXCursor_LabelRef: {
2760 LabelStmt *Label = getCursorLabelRef(C).first;
2761 assert(Label && "Missing label");
2762
2763 return createCXString(Label->getID()->getName());
2764 }
2765
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002766 case CXCursor_OverloadedDeclRef: {
2767 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2768 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2769 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2770 return createCXString(ND->getNameAsString());
2771 return createCXString("");
2772 }
2773 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2774 return createCXString(E->getName().getAsString());
2775 OverloadedTemplateStorage *Ovl
2776 = Storage.get<OverloadedTemplateStorage*>();
2777 if (Ovl->size() == 0)
2778 return createCXString("");
2779 return createCXString((*Ovl->begin())->getNameAsString());
2780 }
2781
Daniel Dunbaracca7252009-11-30 20:42:49 +00002782 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002783 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002784 }
2785 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002786
2787 if (clang_isExpression(C.kind)) {
2788 Decl *D = getDeclFromExpr(getCursorExpr(C));
2789 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002790 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002791 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002792 }
2793
Douglas Gregor36897b02010-09-10 00:22:18 +00002794 if (clang_isStatement(C.kind)) {
2795 Stmt *S = getCursorStmt(C);
2796 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2797 return createCXString(Label->getID()->getName());
2798
2799 return createCXString("");
2800 }
2801
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002802 if (C.kind == CXCursor_MacroInstantiation)
2803 return createCXString(getCursorMacroInstantiation(C)->getName()
2804 ->getNameStart());
2805
Douglas Gregor572feb22010-03-18 18:04:21 +00002806 if (C.kind == CXCursor_MacroDefinition)
2807 return createCXString(getCursorMacroDefinition(C)->getName()
2808 ->getNameStart());
2809
Douglas Gregorecdcb882010-10-20 22:00:55 +00002810 if (C.kind == CXCursor_InclusionDirective)
2811 return createCXString(getCursorInclusionDirective(C)->getFileName());
2812
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002813 if (clang_isDeclaration(C.kind))
2814 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002815
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002816 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002817}
2818
Douglas Gregor358559d2010-10-02 22:49:11 +00002819CXString clang_getCursorDisplayName(CXCursor C) {
2820 if (!clang_isDeclaration(C.kind))
2821 return clang_getCursorSpelling(C);
2822
2823 Decl *D = getCursorDecl(C);
2824 if (!D)
2825 return createCXString("");
2826
2827 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2828 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2829 D = FunTmpl->getTemplatedDecl();
2830
2831 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2832 llvm::SmallString<64> Str;
2833 llvm::raw_svector_ostream OS(Str);
2834 OS << Function->getNameAsString();
2835 if (Function->getPrimaryTemplate())
2836 OS << "<>";
2837 OS << "(";
2838 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2839 if (I)
2840 OS << ", ";
2841 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2842 }
2843
2844 if (Function->isVariadic()) {
2845 if (Function->getNumParams())
2846 OS << ", ";
2847 OS << "...";
2848 }
2849 OS << ")";
2850 return createCXString(OS.str());
2851 }
2852
2853 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2854 llvm::SmallString<64> Str;
2855 llvm::raw_svector_ostream OS(Str);
2856 OS << ClassTemplate->getNameAsString();
2857 OS << "<";
2858 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2859 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2860 if (I)
2861 OS << ", ";
2862
2863 NamedDecl *Param = Params->getParam(I);
2864 if (Param->getIdentifier()) {
2865 OS << Param->getIdentifier()->getName();
2866 continue;
2867 }
2868
2869 // There is no parameter name, which makes this tricky. Try to come up
2870 // with something useful that isn't too long.
2871 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2872 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2873 else if (NonTypeTemplateParmDecl *NTTP
2874 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2875 OS << NTTP->getType().getAsString(Policy);
2876 else
2877 OS << "template<...> class";
2878 }
2879
2880 OS << ">";
2881 return createCXString(OS.str());
2882 }
2883
2884 if (ClassTemplateSpecializationDecl *ClassSpec
2885 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2886 // If the type was explicitly written, use that.
2887 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2888 return createCXString(TSInfo->getType().getAsString(Policy));
2889
2890 llvm::SmallString<64> Str;
2891 llvm::raw_svector_ostream OS(Str);
2892 OS << ClassSpec->getNameAsString();
2893 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002894 ClassSpec->getTemplateArgs().data(),
2895 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002896 Policy);
2897 return createCXString(OS.str());
2898 }
2899
2900 return clang_getCursorSpelling(C);
2901}
2902
Ted Kremeneke68fff62010-02-17 00:41:32 +00002903CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002904 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002905 case CXCursor_FunctionDecl:
2906 return createCXString("FunctionDecl");
2907 case CXCursor_TypedefDecl:
2908 return createCXString("TypedefDecl");
2909 case CXCursor_EnumDecl:
2910 return createCXString("EnumDecl");
2911 case CXCursor_EnumConstantDecl:
2912 return createCXString("EnumConstantDecl");
2913 case CXCursor_StructDecl:
2914 return createCXString("StructDecl");
2915 case CXCursor_UnionDecl:
2916 return createCXString("UnionDecl");
2917 case CXCursor_ClassDecl:
2918 return createCXString("ClassDecl");
2919 case CXCursor_FieldDecl:
2920 return createCXString("FieldDecl");
2921 case CXCursor_VarDecl:
2922 return createCXString("VarDecl");
2923 case CXCursor_ParmDecl:
2924 return createCXString("ParmDecl");
2925 case CXCursor_ObjCInterfaceDecl:
2926 return createCXString("ObjCInterfaceDecl");
2927 case CXCursor_ObjCCategoryDecl:
2928 return createCXString("ObjCCategoryDecl");
2929 case CXCursor_ObjCProtocolDecl:
2930 return createCXString("ObjCProtocolDecl");
2931 case CXCursor_ObjCPropertyDecl:
2932 return createCXString("ObjCPropertyDecl");
2933 case CXCursor_ObjCIvarDecl:
2934 return createCXString("ObjCIvarDecl");
2935 case CXCursor_ObjCInstanceMethodDecl:
2936 return createCXString("ObjCInstanceMethodDecl");
2937 case CXCursor_ObjCClassMethodDecl:
2938 return createCXString("ObjCClassMethodDecl");
2939 case CXCursor_ObjCImplementationDecl:
2940 return createCXString("ObjCImplementationDecl");
2941 case CXCursor_ObjCCategoryImplDecl:
2942 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002943 case CXCursor_CXXMethod:
2944 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002945 case CXCursor_UnexposedDecl:
2946 return createCXString("UnexposedDecl");
2947 case CXCursor_ObjCSuperClassRef:
2948 return createCXString("ObjCSuperClassRef");
2949 case CXCursor_ObjCProtocolRef:
2950 return createCXString("ObjCProtocolRef");
2951 case CXCursor_ObjCClassRef:
2952 return createCXString("ObjCClassRef");
2953 case CXCursor_TypeRef:
2954 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002955 case CXCursor_TemplateRef:
2956 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002957 case CXCursor_NamespaceRef:
2958 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002959 case CXCursor_MemberRef:
2960 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002961 case CXCursor_LabelRef:
2962 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002963 case CXCursor_OverloadedDeclRef:
2964 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002965 case CXCursor_UnexposedExpr:
2966 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002967 case CXCursor_BlockExpr:
2968 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002969 case CXCursor_DeclRefExpr:
2970 return createCXString("DeclRefExpr");
2971 case CXCursor_MemberRefExpr:
2972 return createCXString("MemberRefExpr");
2973 case CXCursor_CallExpr:
2974 return createCXString("CallExpr");
2975 case CXCursor_ObjCMessageExpr:
2976 return createCXString("ObjCMessageExpr");
2977 case CXCursor_UnexposedStmt:
2978 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002979 case CXCursor_LabelStmt:
2980 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002981 case CXCursor_InvalidFile:
2982 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002983 case CXCursor_InvalidCode:
2984 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002985 case CXCursor_NoDeclFound:
2986 return createCXString("NoDeclFound");
2987 case CXCursor_NotImplemented:
2988 return createCXString("NotImplemented");
2989 case CXCursor_TranslationUnit:
2990 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002991 case CXCursor_UnexposedAttr:
2992 return createCXString("UnexposedAttr");
2993 case CXCursor_IBActionAttr:
2994 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002995 case CXCursor_IBOutletAttr:
2996 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002997 case CXCursor_IBOutletCollectionAttr:
2998 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002999 case CXCursor_PreprocessingDirective:
3000 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003001 case CXCursor_MacroDefinition:
3002 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003003 case CXCursor_MacroInstantiation:
3004 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003005 case CXCursor_InclusionDirective:
3006 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003007 case CXCursor_Namespace:
3008 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003009 case CXCursor_LinkageSpec:
3010 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003011 case CXCursor_CXXBaseSpecifier:
3012 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003013 case CXCursor_Constructor:
3014 return createCXString("CXXConstructor");
3015 case CXCursor_Destructor:
3016 return createCXString("CXXDestructor");
3017 case CXCursor_ConversionFunction:
3018 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003019 case CXCursor_TemplateTypeParameter:
3020 return createCXString("TemplateTypeParameter");
3021 case CXCursor_NonTypeTemplateParameter:
3022 return createCXString("NonTypeTemplateParameter");
3023 case CXCursor_TemplateTemplateParameter:
3024 return createCXString("TemplateTemplateParameter");
3025 case CXCursor_FunctionTemplate:
3026 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003027 case CXCursor_ClassTemplate:
3028 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003029 case CXCursor_ClassTemplatePartialSpecialization:
3030 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003031 case CXCursor_NamespaceAlias:
3032 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003033 case CXCursor_UsingDirective:
3034 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003035 case CXCursor_UsingDeclaration:
3036 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003037 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003038
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003039 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003040 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00003041}
Steve Naroff89922f82009-08-31 00:59:03 +00003042
Ted Kremeneke68fff62010-02-17 00:41:32 +00003043enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3044 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003045 CXClientData client_data) {
3046 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003047
3048 // If our current best cursor is the construction of a temporary object,
3049 // don't replace that cursor with a type reference, because we want
3050 // clang_getCursor() to point at the constructor.
3051 if (clang_isExpression(BestCursor->kind) &&
3052 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3053 cursor.kind == CXCursor_TypeRef)
3054 return CXChildVisit_Recurse;
3055
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003056 *BestCursor = cursor;
3057 return CXChildVisit_Recurse;
3058}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003059
Douglas Gregorb9790342010-01-22 21:44:22 +00003060CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3061 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003062 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003063
Douglas Gregorb9790342010-01-22 21:44:22 +00003064 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003065 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3066
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003067 // Translate the given source location to make it point at the beginning of
3068 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003069 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003070
3071 // Guard against an invalid SourceLocation, or we may assert in one
3072 // of the following calls.
3073 if (SLoc.isInvalid())
3074 return clang_getNullCursor();
3075
Douglas Gregor40749ee2010-11-03 00:35:38 +00003076 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003077 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3078 CXXUnit->getASTContext().getLangOptions());
3079
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003080 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3081 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003082 // FIXME: Would be great to have a "hint" cursor, then walk from that
3083 // hint cursor upward until we find a cursor whose source range encloses
3084 // the region of interest, rather than starting from the translation unit.
3085 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00003086 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003087 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003088 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003089 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003090
3091 if (Logging) {
3092 CXFile SearchFile;
3093 unsigned SearchLine, SearchColumn;
3094 CXFile ResultFile;
3095 unsigned ResultLine, ResultColumn;
3096 CXString SearchFileName, ResultFileName, KindSpelling;
3097 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3098
3099 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3100 0);
3101 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3102 &ResultColumn, 0);
3103 SearchFileName = clang_getFileName(SearchFile);
3104 ResultFileName = clang_getFileName(ResultFile);
3105 KindSpelling = clang_getCursorKindSpelling(Result.kind);
3106 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n",
3107 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3108 clang_getCString(KindSpelling),
3109 clang_getCString(ResultFileName), ResultLine, ResultColumn);
3110 clang_disposeString(SearchFileName);
3111 clang_disposeString(ResultFileName);
3112 clang_disposeString(KindSpelling);
3113 }
3114
Ted Kremeneke68fff62010-02-17 00:41:32 +00003115 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003116}
3117
Ted Kremenek73885552009-11-17 19:28:59 +00003118CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003119 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003120}
3121
3122unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003123 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003124}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003125
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003126unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003127 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3128}
3129
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003130unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003131 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3132}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003133
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003134unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003135 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3136}
3137
Douglas Gregor97b98722010-01-19 23:20:36 +00003138unsigned clang_isExpression(enum CXCursorKind K) {
3139 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3140}
3141
3142unsigned clang_isStatement(enum CXCursorKind K) {
3143 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3144}
3145
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003146unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3147 return K == CXCursor_TranslationUnit;
3148}
3149
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003150unsigned clang_isPreprocessing(enum CXCursorKind K) {
3151 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3152}
3153
Ted Kremenekad6eff62010-03-08 21:17:29 +00003154unsigned clang_isUnexposed(enum CXCursorKind K) {
3155 switch (K) {
3156 case CXCursor_UnexposedDecl:
3157 case CXCursor_UnexposedExpr:
3158 case CXCursor_UnexposedStmt:
3159 case CXCursor_UnexposedAttr:
3160 return true;
3161 default:
3162 return false;
3163 }
3164}
3165
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003166CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003167 return C.kind;
3168}
3169
Douglas Gregor98258af2010-01-18 22:46:11 +00003170CXSourceLocation clang_getCursorLocation(CXCursor C) {
3171 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003172 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003173 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003174 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3175 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003176 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003177 }
3178
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003179 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003180 std::pair<ObjCProtocolDecl *, SourceLocation> P
3181 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003182 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003183 }
3184
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003185 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003186 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3187 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003188 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003189 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003190
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003191 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003192 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003193 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003194 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003195
3196 case CXCursor_TemplateRef: {
3197 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3198 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3199 }
3200
Douglas Gregor69319002010-08-31 23:48:11 +00003201 case CXCursor_NamespaceRef: {
3202 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3203 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3204 }
3205
Douglas Gregora67e03f2010-09-09 21:42:20 +00003206 case CXCursor_MemberRef: {
3207 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3208 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3209 }
3210
Ted Kremenek3064ef92010-08-27 21:34:58 +00003211 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003212 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3213 if (!BaseSpec)
3214 return clang_getNullLocation();
3215
3216 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3217 return cxloc::translateSourceLocation(getCursorContext(C),
3218 TSInfo->getTypeLoc().getBeginLoc());
3219
3220 return cxloc::translateSourceLocation(getCursorContext(C),
3221 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003222 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003223
Douglas Gregor36897b02010-09-10 00:22:18 +00003224 case CXCursor_LabelRef: {
3225 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3226 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3227 }
3228
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003229 case CXCursor_OverloadedDeclRef:
3230 return cxloc::translateSourceLocation(getCursorContext(C),
3231 getCursorOverloadedDeclRef(C).second);
3232
Douglas Gregorf46034a2010-01-18 23:41:10 +00003233 default:
3234 // FIXME: Need a way to enumerate all non-reference cases.
3235 llvm_unreachable("Missed a reference kind");
3236 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003237 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003238
3239 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003240 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003241 getLocationFromExpr(getCursorExpr(C)));
3242
Douglas Gregor36897b02010-09-10 00:22:18 +00003243 if (clang_isStatement(C.kind))
3244 return cxloc::translateSourceLocation(getCursorContext(C),
3245 getCursorStmt(C)->getLocStart());
3246
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003247 if (C.kind == CXCursor_PreprocessingDirective) {
3248 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3249 return cxloc::translateSourceLocation(getCursorContext(C), L);
3250 }
Douglas Gregor48072312010-03-18 15:23:44 +00003251
3252 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003253 SourceLocation L
3254 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003255 return cxloc::translateSourceLocation(getCursorContext(C), L);
3256 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003257
3258 if (C.kind == CXCursor_MacroDefinition) {
3259 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3260 return cxloc::translateSourceLocation(getCursorContext(C), L);
3261 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003262
3263 if (C.kind == CXCursor_InclusionDirective) {
3264 SourceLocation L
3265 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3266 return cxloc::translateSourceLocation(getCursorContext(C), L);
3267 }
3268
Ted Kremenek9a700d22010-05-12 06:16:13 +00003269 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003270 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003271
Douglas Gregorf46034a2010-01-18 23:41:10 +00003272 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003273 SourceLocation Loc = D->getLocation();
3274 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3275 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003276 // FIXME: Multiple variables declared in a single declaration
3277 // currently lack the information needed to correctly determine their
3278 // ranges when accounting for the type-specifier. We use context
3279 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3280 // and if so, whether it is the first decl.
3281 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3282 if (!cxcursor::isFirstInDeclGroup(C))
3283 Loc = VD->getLocation();
3284 }
3285
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003286 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003287}
Douglas Gregora7bde202010-01-19 00:34:46 +00003288
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003289} // end extern "C"
3290
3291static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003292 if (clang_isReference(C.kind)) {
3293 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003294 case CXCursor_ObjCSuperClassRef:
3295 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003296
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003297 case CXCursor_ObjCProtocolRef:
3298 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003299
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003300 case CXCursor_ObjCClassRef:
3301 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003302
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003303 case CXCursor_TypeRef:
3304 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003305
3306 case CXCursor_TemplateRef:
3307 return getCursorTemplateRef(C).second;
3308
Douglas Gregor69319002010-08-31 23:48:11 +00003309 case CXCursor_NamespaceRef:
3310 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003311
3312 case CXCursor_MemberRef:
3313 return getCursorMemberRef(C).second;
3314
Ted Kremenek3064ef92010-08-27 21:34:58 +00003315 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003316 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003317
Douglas Gregor36897b02010-09-10 00:22:18 +00003318 case CXCursor_LabelRef:
3319 return getCursorLabelRef(C).second;
3320
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003321 case CXCursor_OverloadedDeclRef:
3322 return getCursorOverloadedDeclRef(C).second;
3323
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003324 default:
3325 // FIXME: Need a way to enumerate all non-reference cases.
3326 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003327 }
3328 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003329
3330 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003331 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003332
3333 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003334 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003335
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003336 if (C.kind == CXCursor_PreprocessingDirective)
3337 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003338
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003339 if (C.kind == CXCursor_MacroInstantiation)
3340 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003341
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003342 if (C.kind == CXCursor_MacroDefinition)
3343 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003344
3345 if (C.kind == CXCursor_InclusionDirective)
3346 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3347
Ted Kremenek007a7c92010-11-01 23:26:51 +00003348 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3349 Decl *D = cxcursor::getCursorDecl(C);
3350 SourceRange R = D->getSourceRange();
3351 // FIXME: Multiple variables declared in a single declaration
3352 // currently lack the information needed to correctly determine their
3353 // ranges when accounting for the type-specifier. We use context
3354 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3355 // and if so, whether it is the first decl.
3356 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3357 if (!cxcursor::isFirstInDeclGroup(C))
3358 R.setBegin(VD->getLocation());
3359 }
3360 return R;
3361 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003362 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003363
3364extern "C" {
3365
3366CXSourceRange clang_getCursorExtent(CXCursor C) {
3367 SourceRange R = getRawCursorExtent(C);
3368 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003369 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003370
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003371 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003372}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003373
3374CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003375 if (clang_isInvalid(C.kind))
3376 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003377
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003378 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003379 if (clang_isDeclaration(C.kind)) {
3380 Decl *D = getCursorDecl(C);
3381 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3382 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3383 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3384 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3385 if (ObjCForwardProtocolDecl *Protocols
3386 = dyn_cast<ObjCForwardProtocolDecl>(D))
3387 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3388
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003389 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003390 }
3391
Douglas Gregor97b98722010-01-19 23:20:36 +00003392 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003393 Expr *E = getCursorExpr(C);
3394 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003395 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003396 return MakeCXCursor(D, CXXUnit);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003397
3398 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3399 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3400
Douglas Gregor97b98722010-01-19 23:20:36 +00003401 return clang_getNullCursor();
3402 }
3403
Douglas Gregor36897b02010-09-10 00:22:18 +00003404 if (clang_isStatement(C.kind)) {
3405 Stmt *S = getCursorStmt(C);
3406 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3407 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3408 getCursorASTUnit(C));
3409
3410 return clang_getNullCursor();
3411 }
3412
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003413 if (C.kind == CXCursor_MacroInstantiation) {
3414 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3415 return MakeMacroDefinitionCursor(Def, CXXUnit);
3416 }
3417
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003418 if (!clang_isReference(C.kind))
3419 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003420
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003421 switch (C.kind) {
3422 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003423 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003424
3425 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003426 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003427
3428 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003429 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003430
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003431 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003432 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00003433
3434 case CXCursor_TemplateRef:
3435 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3436
Douglas Gregor69319002010-08-31 23:48:11 +00003437 case CXCursor_NamespaceRef:
3438 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3439
Douglas Gregora67e03f2010-09-09 21:42:20 +00003440 case CXCursor_MemberRef:
3441 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3442
Ted Kremenek3064ef92010-08-27 21:34:58 +00003443 case CXCursor_CXXBaseSpecifier: {
3444 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3445 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3446 CXXUnit));
3447 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003448
Douglas Gregor36897b02010-09-10 00:22:18 +00003449 case CXCursor_LabelRef:
3450 // FIXME: We end up faking the "parent" declaration here because we
3451 // don't want to make CXCursor larger.
3452 return MakeCXCursor(getCursorLabelRef(C).first,
3453 CXXUnit->getASTContext().getTranslationUnitDecl(),
3454 CXXUnit);
3455
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003456 case CXCursor_OverloadedDeclRef:
3457 return C;
3458
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003459 default:
3460 // We would prefer to enumerate all non-reference cursor kinds here.
3461 llvm_unreachable("Unhandled reference cursor kind");
3462 break;
3463 }
3464 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003465
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003466 return clang_getNullCursor();
3467}
3468
Douglas Gregorb6998662010-01-19 19:34:47 +00003469CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003470 if (clang_isInvalid(C.kind))
3471 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003472
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003473 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003474
Douglas Gregorb6998662010-01-19 19:34:47 +00003475 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003476 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003477 C = clang_getCursorReferenced(C);
3478 WasReference = true;
3479 }
3480
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003481 if (C.kind == CXCursor_MacroInstantiation)
3482 return clang_getCursorReferenced(C);
3483
Douglas Gregorb6998662010-01-19 19:34:47 +00003484 if (!clang_isDeclaration(C.kind))
3485 return clang_getNullCursor();
3486
3487 Decl *D = getCursorDecl(C);
3488 if (!D)
3489 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003490
Douglas Gregorb6998662010-01-19 19:34:47 +00003491 switch (D->getKind()) {
3492 // Declaration kinds that don't really separate the notions of
3493 // declaration and definition.
3494 case Decl::Namespace:
3495 case Decl::Typedef:
3496 case Decl::TemplateTypeParm:
3497 case Decl::EnumConstant:
3498 case Decl::Field:
3499 case Decl::ObjCIvar:
3500 case Decl::ObjCAtDefsField:
3501 case Decl::ImplicitParam:
3502 case Decl::ParmVar:
3503 case Decl::NonTypeTemplateParm:
3504 case Decl::TemplateTemplateParm:
3505 case Decl::ObjCCategoryImpl:
3506 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003507 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003508 case Decl::LinkageSpec:
3509 case Decl::ObjCPropertyImpl:
3510 case Decl::FileScopeAsm:
3511 case Decl::StaticAssert:
3512 case Decl::Block:
3513 return C;
3514
3515 // Declaration kinds that don't make any sense here, but are
3516 // nonetheless harmless.
3517 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003518 break;
3519
3520 // Declaration kinds for which the definition is not resolvable.
3521 case Decl::UnresolvedUsingTypename:
3522 case Decl::UnresolvedUsingValue:
3523 break;
3524
3525 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003526 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3527 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003528
3529 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003530 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003531
3532 case Decl::Enum:
3533 case Decl::Record:
3534 case Decl::CXXRecord:
3535 case Decl::ClassTemplateSpecialization:
3536 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003537 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003538 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003539 return clang_getNullCursor();
3540
3541 case Decl::Function:
3542 case Decl::CXXMethod:
3543 case Decl::CXXConstructor:
3544 case Decl::CXXDestructor:
3545 case Decl::CXXConversion: {
3546 const FunctionDecl *Def = 0;
3547 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003548 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003549 return clang_getNullCursor();
3550 }
3551
3552 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003553 // Ask the variable if it has a definition.
3554 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3555 return MakeCXCursor(Def, CXXUnit);
3556 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003557 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003558
Douglas Gregorb6998662010-01-19 19:34:47 +00003559 case Decl::FunctionTemplate: {
3560 const FunctionDecl *Def = 0;
3561 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003562 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003563 return clang_getNullCursor();
3564 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003565
Douglas Gregorb6998662010-01-19 19:34:47 +00003566 case Decl::ClassTemplate: {
3567 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003568 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003569 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003570 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003571 return clang_getNullCursor();
3572 }
3573
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003574 case Decl::Using:
3575 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3576 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003577
3578 case Decl::UsingShadow:
3579 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003580 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003581 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003582
3583 case Decl::ObjCMethod: {
3584 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3585 if (Method->isThisDeclarationADefinition())
3586 return C;
3587
3588 // Dig out the method definition in the associated
3589 // @implementation, if we have it.
3590 // FIXME: The ASTs should make finding the definition easier.
3591 if (ObjCInterfaceDecl *Class
3592 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3593 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3594 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3595 Method->isInstanceMethod()))
3596 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003597 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003598
3599 return clang_getNullCursor();
3600 }
3601
3602 case Decl::ObjCCategory:
3603 if (ObjCCategoryImplDecl *Impl
3604 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003605 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003606 return clang_getNullCursor();
3607
3608 case Decl::ObjCProtocol:
3609 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3610 return C;
3611 return clang_getNullCursor();
3612
3613 case Decl::ObjCInterface:
3614 // There are two notions of a "definition" for an Objective-C
3615 // class: the interface and its implementation. When we resolved a
3616 // reference to an Objective-C class, produce the @interface as
3617 // the definition; when we were provided with the interface,
3618 // produce the @implementation as the definition.
3619 if (WasReference) {
3620 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3621 return C;
3622 } else if (ObjCImplementationDecl *Impl
3623 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003624 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003625 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003626
Douglas Gregorb6998662010-01-19 19:34:47 +00003627 case Decl::ObjCProperty:
3628 // FIXME: We don't really know where to find the
3629 // ObjCPropertyImplDecls that implement this property.
3630 return clang_getNullCursor();
3631
3632 case Decl::ObjCCompatibleAlias:
3633 if (ObjCInterfaceDecl *Class
3634 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3635 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003636 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003637
Douglas Gregorb6998662010-01-19 19:34:47 +00003638 return clang_getNullCursor();
3639
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003640 case Decl::ObjCForwardProtocol:
3641 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3642 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003643
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003644 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003645 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003646 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003647
3648 case Decl::Friend:
3649 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003650 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003651 return clang_getNullCursor();
3652
3653 case Decl::FriendTemplate:
3654 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003655 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003656 return clang_getNullCursor();
3657 }
3658
3659 return clang_getNullCursor();
3660}
3661
3662unsigned clang_isCursorDefinition(CXCursor C) {
3663 if (!clang_isDeclaration(C.kind))
3664 return 0;
3665
3666 return clang_getCursorDefinition(C) == C;
3667}
3668
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003669unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003670 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003671 return 0;
3672
3673 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3674 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3675 return E->getNumDecls();
3676
3677 if (OverloadedTemplateStorage *S
3678 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3679 return S->size();
3680
3681 Decl *D = Storage.get<Decl*>();
3682 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003683 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003684 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3685 return Classes->size();
3686 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3687 return Protocols->protocol_size();
3688
3689 return 0;
3690}
3691
3692CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003693 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003694 return clang_getNullCursor();
3695
3696 if (index >= clang_getNumOverloadedDecls(cursor))
3697 return clang_getNullCursor();
3698
3699 ASTUnit *Unit = getCursorASTUnit(cursor);
3700 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3701 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3702 return MakeCXCursor(E->decls_begin()[index], Unit);
3703
3704 if (OverloadedTemplateStorage *S
3705 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3706 return MakeCXCursor(S->begin()[index], Unit);
3707
3708 Decl *D = Storage.get<Decl*>();
3709 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3710 // FIXME: This is, unfortunately, linear time.
3711 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3712 std::advance(Pos, index);
3713 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3714 }
3715
3716 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3717 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3718
3719 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3720 return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3721
3722 return clang_getNullCursor();
3723}
3724
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003725void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003726 const char **startBuf,
3727 const char **endBuf,
3728 unsigned *startLine,
3729 unsigned *startColumn,
3730 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003731 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003732 assert(getCursorDecl(C) && "CXCursor has null decl");
3733 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003734 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3735 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003736
Steve Naroff4ade6d62009-09-23 17:52:52 +00003737 SourceManager &SM = FD->getASTContext().getSourceManager();
3738 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3739 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3740 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3741 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3742 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3743 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3744}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003745
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003746void clang_enableStackTraces(void) {
3747 llvm::sys::PrintStackTraceOnErrorSignal();
3748}
3749
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003750void clang_executeOnThread(void (*fn)(void*), void *user_data,
3751 unsigned stack_size) {
3752 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3753}
3754
Ted Kremenekfb480492010-01-13 21:46:36 +00003755} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003756
Ted Kremenekfb480492010-01-13 21:46:36 +00003757//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003758// Token-based Operations.
3759//===----------------------------------------------------------------------===//
3760
3761/* CXToken layout:
3762 * int_data[0]: a CXTokenKind
3763 * int_data[1]: starting token location
3764 * int_data[2]: token length
3765 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003766 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003767 * otherwise unused.
3768 */
3769extern "C" {
3770
3771CXTokenKind clang_getTokenKind(CXToken CXTok) {
3772 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3773}
3774
3775CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3776 switch (clang_getTokenKind(CXTok)) {
3777 case CXToken_Identifier:
3778 case CXToken_Keyword:
3779 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003780 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3781 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003782
3783 case CXToken_Literal: {
3784 // We have stashed the starting pointer in the ptr_data field. Use it.
3785 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003786 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003787 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003788
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003789 case CXToken_Punctuation:
3790 case CXToken_Comment:
3791 break;
3792 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003793
3794 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003795 // deconstructing the source location.
3796 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3797 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003798 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003799
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003800 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3801 std::pair<FileID, unsigned> LocInfo
3802 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003803 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003804 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003805 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3806 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003807 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003808
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003809 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003810}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003811
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003812CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3813 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3814 if (!CXXUnit)
3815 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003816
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003817 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3818 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3819}
3820
3821CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3822 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003823 if (!CXXUnit)
3824 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003825
3826 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003827 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3828}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003829
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003830void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3831 CXToken **Tokens, unsigned *NumTokens) {
3832 if (Tokens)
3833 *Tokens = 0;
3834 if (NumTokens)
3835 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003836
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003837 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3838 if (!CXXUnit || !Tokens || !NumTokens)
3839 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003840
Douglas Gregorbdf60622010-03-05 21:16:25 +00003841 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3842
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003843 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003844 if (R.isInvalid())
3845 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003846
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003847 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3848 std::pair<FileID, unsigned> BeginLocInfo
3849 = SourceMgr.getDecomposedLoc(R.getBegin());
3850 std::pair<FileID, unsigned> EndLocInfo
3851 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003852
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003853 // Cannot tokenize across files.
3854 if (BeginLocInfo.first != EndLocInfo.first)
3855 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003856
3857 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003858 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003859 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003860 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003861 if (Invalid)
3862 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003863
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003864 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3865 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003866 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003867 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003868
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003869 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003870 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003871 llvm::SmallVector<CXToken, 32> CXTokens;
3872 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003873 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003874 do {
3875 // Lex the next token
3876 Lex.LexFromRawLexer(Tok);
3877 if (Tok.is(tok::eof))
3878 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003879
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003880 // Initialize the CXToken.
3881 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003882
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003883 // - Common fields
3884 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3885 CXTok.int_data[2] = Tok.getLength();
3886 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003887
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003888 // - Kind-specific fields
3889 if (Tok.isLiteral()) {
3890 CXTok.int_data[0] = CXToken_Literal;
3891 CXTok.ptr_data = (void *)Tok.getLiteralData();
3892 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003893 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003894 std::pair<FileID, unsigned> LocInfo
3895 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003896 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003897 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003898 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3899 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003900 return;
3901
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003902 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003903 IdentifierInfo *II
3904 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003905
David Chisnall096428b2010-10-13 21:44:48 +00003906 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003907 CXTok.int_data[0] = CXToken_Keyword;
3908 }
3909 else {
3910 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3911 CXToken_Identifier
3912 : CXToken_Keyword;
3913 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003914 CXTok.ptr_data = II;
3915 } else if (Tok.is(tok::comment)) {
3916 CXTok.int_data[0] = CXToken_Comment;
3917 CXTok.ptr_data = 0;
3918 } else {
3919 CXTok.int_data[0] = CXToken_Punctuation;
3920 CXTok.ptr_data = 0;
3921 }
3922 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003923 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003924 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003925
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003926 if (CXTokens.empty())
3927 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003928
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003929 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3930 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3931 *NumTokens = CXTokens.size();
3932}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003933
Ted Kremenek6db61092010-05-05 00:55:15 +00003934void clang_disposeTokens(CXTranslationUnit TU,
3935 CXToken *Tokens, unsigned NumTokens) {
3936 free(Tokens);
3937}
3938
3939} // end: extern "C"
3940
3941//===----------------------------------------------------------------------===//
3942// Token annotation APIs.
3943//===----------------------------------------------------------------------===//
3944
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003945typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003946static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3947 CXCursor parent,
3948 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003949namespace {
3950class AnnotateTokensWorker {
3951 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003952 CXToken *Tokens;
3953 CXCursor *Cursors;
3954 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003955 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003956 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003957 CursorVisitor AnnotateVis;
3958 SourceManager &SrcMgr;
3959
3960 bool MoreTokens() const { return TokIdx < NumTokens; }
3961 unsigned NextToken() const { return TokIdx; }
3962 void AdvanceToken() { ++TokIdx; }
3963 SourceLocation GetTokenLoc(unsigned tokI) {
3964 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3965 }
3966
Ted Kremenek6db61092010-05-05 00:55:15 +00003967public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003968 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003969 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3970 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003971 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003972 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003973 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3974 Decl::MaxPCHLevel, RegionOfInterest),
3975 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003976
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003977 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003978 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003979 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00003980 void AnnotateTokens() {
3981 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getASTUnit()));
3982 }
Ted Kremenek6db61092010-05-05 00:55:15 +00003983};
3984}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003985
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003986void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3987 // Walk the AST within the region of interest, annotating tokens
3988 // along the way.
3989 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003990
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003991 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3992 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00003993 if (Pos != Annotated.end() &&
3994 (clang_isInvalid(Cursors[I].kind) ||
3995 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003996 Cursors[I] = Pos->second;
3997 }
3998
3999 // Finish up annotating any tokens left.
4000 if (!MoreTokens())
4001 return;
4002
4003 const CXCursor &C = clang_getNullCursor();
4004 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4005 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4006 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004007 }
4008}
4009
Ted Kremenek6db61092010-05-05 00:55:15 +00004010enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004011AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004012 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004013 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004014 if (cursorRange.isInvalid())
4015 return CXChildVisit_Recurse;
4016
Douglas Gregor4419b672010-10-21 06:10:04 +00004017 if (clang_isPreprocessing(cursor.kind)) {
4018 // For macro instantiations, just note where the beginning of the macro
4019 // instantiation occurs.
4020 if (cursor.kind == CXCursor_MacroInstantiation) {
4021 Annotated[Loc.int_data] = cursor;
4022 return CXChildVisit_Recurse;
4023 }
4024
Douglas Gregor4419b672010-10-21 06:10:04 +00004025 // Items in the preprocessing record are kept separate from items in
4026 // declarations, so we keep a separate token index.
4027 unsigned SavedTokIdx = TokIdx;
4028 TokIdx = PreprocessingTokIdx;
4029
4030 // Skip tokens up until we catch up to the beginning of the preprocessing
4031 // entry.
4032 while (MoreTokens()) {
4033 const unsigned I = NextToken();
4034 SourceLocation TokLoc = GetTokenLoc(I);
4035 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4036 case RangeBefore:
4037 AdvanceToken();
4038 continue;
4039 case RangeAfter:
4040 case RangeOverlap:
4041 break;
4042 }
4043 break;
4044 }
4045
4046 // Look at all of the tokens within this range.
4047 while (MoreTokens()) {
4048 const unsigned I = NextToken();
4049 SourceLocation TokLoc = GetTokenLoc(I);
4050 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4051 case RangeBefore:
4052 assert(0 && "Infeasible");
4053 case RangeAfter:
4054 break;
4055 case RangeOverlap:
4056 Cursors[I] = cursor;
4057 AdvanceToken();
4058 continue;
4059 }
4060 break;
4061 }
4062
4063 // Save the preprocessing token index; restore the non-preprocessing
4064 // token index.
4065 PreprocessingTokIdx = TokIdx;
4066 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004067 return CXChildVisit_Recurse;
4068 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004069
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004070 if (cursorRange.isInvalid())
4071 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004072
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004073 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4074
Ted Kremeneka333c662010-05-12 05:29:33 +00004075 // Adjust the annotated range based specific declarations.
4076 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4077 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004078 Decl *D = cxcursor::getCursorDecl(cursor);
4079 // Don't visit synthesized ObjC methods, since they have no syntatic
4080 // representation in the source.
4081 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4082 if (MD->isSynthesized())
4083 return CXChildVisit_Continue;
4084 }
4085 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004086 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4087 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004088 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004089 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004090 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004091 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004092 }
4093 }
4094 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004095
Ted Kremenek3f404602010-08-14 01:14:06 +00004096 // If the location of the cursor occurs within a macro instantiation, record
4097 // the spelling location of the cursor in our annotation map. We can then
4098 // paper over the token labelings during a post-processing step to try and
4099 // get cursor mappings for tokens that are the *arguments* of a macro
4100 // instantiation.
4101 if (L.isMacroID()) {
4102 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4103 // Only invalidate the old annotation if it isn't part of a preprocessing
4104 // directive. Here we assume that the default construction of CXCursor
4105 // results in CXCursor.kind being an initialized value (i.e., 0). If
4106 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004107
Ted Kremenek3f404602010-08-14 01:14:06 +00004108 CXCursor &oldC = Annotated[rawEncoding];
4109 if (!clang_isPreprocessing(oldC.kind))
4110 oldC = cursor;
4111 }
4112
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004113 const enum CXCursorKind K = clang_getCursorKind(parent);
4114 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004115 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4116 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004117
4118 while (MoreTokens()) {
4119 const unsigned I = NextToken();
4120 SourceLocation TokLoc = GetTokenLoc(I);
4121 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4122 case RangeBefore:
4123 Cursors[I] = updateC;
4124 AdvanceToken();
4125 continue;
4126 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004127 case RangeOverlap:
4128 break;
4129 }
4130 break;
4131 }
4132
4133 // Visit children to get their cursor information.
4134 const unsigned BeforeChildren = NextToken();
4135 VisitChildren(cursor);
4136 const unsigned AfterChildren = NextToken();
4137
4138 // Adjust 'Last' to the last token within the extent of the cursor.
4139 while (MoreTokens()) {
4140 const unsigned I = NextToken();
4141 SourceLocation TokLoc = GetTokenLoc(I);
4142 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4143 case RangeBefore:
4144 assert(0 && "Infeasible");
4145 case RangeAfter:
4146 break;
4147 case RangeOverlap:
4148 Cursors[I] = updateC;
4149 AdvanceToken();
4150 continue;
4151 }
4152 break;
4153 }
4154 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004155
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004156 // Scan the tokens that are at the beginning of the cursor, but are not
4157 // capture by the child cursors.
4158
4159 // For AST elements within macros, rely on a post-annotate pass to
4160 // to correctly annotate the tokens with cursors. Otherwise we can
4161 // get confusing results of having tokens that map to cursors that really
4162 // are expanded by an instantiation.
4163 if (L.isMacroID())
4164 cursor = clang_getNullCursor();
4165
4166 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4167 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4168 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004169
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004170 Cursors[I] = cursor;
4171 }
4172 // Scan the tokens that are at the end of the cursor, but are not captured
4173 // but the child cursors.
4174 for (unsigned I = AfterChildren; I != Last; ++I)
4175 Cursors[I] = cursor;
4176
4177 TokIdx = Last;
4178 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004179}
4180
Ted Kremenek6db61092010-05-05 00:55:15 +00004181static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4182 CXCursor parent,
4183 CXClientData client_data) {
4184 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4185}
4186
Ted Kremenekab979612010-11-11 08:05:23 +00004187// This gets run a separate thread to avoid stack blowout.
4188static void runAnnotateTokensWorker(void *UserData) {
4189 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4190}
4191
Ted Kremenek6db61092010-05-05 00:55:15 +00004192extern "C" {
4193
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004194void clang_annotateTokens(CXTranslationUnit TU,
4195 CXToken *Tokens, unsigned NumTokens,
4196 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004197
4198 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004199 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004200
Douglas Gregor4419b672010-10-21 06:10:04 +00004201 // Any token we don't specifically annotate will have a NULL cursor.
4202 CXCursor C = clang_getNullCursor();
4203 for (unsigned I = 0; I != NumTokens; ++I)
4204 Cursors[I] = C;
4205
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004206 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor4419b672010-10-21 06:10:04 +00004207 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004208 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004209
Douglas Gregorbdf60622010-03-05 21:16:25 +00004210 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004211
Douglas Gregor0396f462010-03-19 05:22:59 +00004212 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004213 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004214 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4215 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004216 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4217 clang_getTokenLocation(TU,
4218 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004219
Douglas Gregor0396f462010-03-19 05:22:59 +00004220 // A mapping from the source locations found when re-lexing or traversing the
4221 // region of interest to the corresponding cursors.
4222 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004223
4224 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004225 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004226 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4227 std::pair<FileID, unsigned> BeginLocInfo
4228 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4229 std::pair<FileID, unsigned> EndLocInfo
4230 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004231
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004232 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004233 bool Invalid = false;
4234 if (BeginLocInfo.first == EndLocInfo.first &&
4235 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4236 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004237 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4238 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004239 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004240 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004241 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004242
4243 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004244 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004245 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004246 Token Tok;
4247 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004248
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004249 reprocess:
4250 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4251 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004252 // don't see it while preprocessing these tokens later, but keep track
4253 // of all of the token locations inside this preprocessing directive so
4254 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004255 //
4256 // FIXME: Some simple tests here could identify macro definitions and
4257 // #undefs, to provide specific cursor kinds for those.
4258 std::vector<SourceLocation> Locations;
4259 do {
4260 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004261 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004262 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004263
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004264 using namespace cxcursor;
4265 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004266 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4267 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00004268 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004269 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4270 Annotated[Locations[I].getRawEncoding()] = Cursor;
4271 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004272
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004273 if (Tok.isAtStartOfLine())
4274 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004275
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004276 continue;
4277 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004278
Douglas Gregor48072312010-03-18 15:23:44 +00004279 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004280 break;
4281 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004282 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004283
Douglas Gregor0396f462010-03-19 05:22:59 +00004284 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004285 // a specific cursor.
4286 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4287 CXXUnit, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004288
4289 // Run the worker within a CrashRecoveryContext.
4290 llvm::CrashRecoveryContext CRC;
4291 if (!RunSafely(CRC, runAnnotateTokensWorker, &W)) {
4292 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4293 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004294}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004295} // end: extern "C"
4296
4297//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004298// Operations for querying linkage of a cursor.
4299//===----------------------------------------------------------------------===//
4300
4301extern "C" {
4302CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004303 if (!clang_isDeclaration(cursor.kind))
4304 return CXLinkage_Invalid;
4305
Ted Kremenek16b42592010-03-03 06:36:57 +00004306 Decl *D = cxcursor::getCursorDecl(cursor);
4307 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4308 switch (ND->getLinkage()) {
4309 case NoLinkage: return CXLinkage_NoLinkage;
4310 case InternalLinkage: return CXLinkage_Internal;
4311 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4312 case ExternalLinkage: return CXLinkage_External;
4313 };
4314
4315 return CXLinkage_Invalid;
4316}
4317} // end: extern "C"
4318
4319//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004320// Operations for querying language of a cursor.
4321//===----------------------------------------------------------------------===//
4322
4323static CXLanguageKind getDeclLanguage(const Decl *D) {
4324 switch (D->getKind()) {
4325 default:
4326 break;
4327 case Decl::ImplicitParam:
4328 case Decl::ObjCAtDefsField:
4329 case Decl::ObjCCategory:
4330 case Decl::ObjCCategoryImpl:
4331 case Decl::ObjCClass:
4332 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004333 case Decl::ObjCForwardProtocol:
4334 case Decl::ObjCImplementation:
4335 case Decl::ObjCInterface:
4336 case Decl::ObjCIvar:
4337 case Decl::ObjCMethod:
4338 case Decl::ObjCProperty:
4339 case Decl::ObjCPropertyImpl:
4340 case Decl::ObjCProtocol:
4341 return CXLanguage_ObjC;
4342 case Decl::CXXConstructor:
4343 case Decl::CXXConversion:
4344 case Decl::CXXDestructor:
4345 case Decl::CXXMethod:
4346 case Decl::CXXRecord:
4347 case Decl::ClassTemplate:
4348 case Decl::ClassTemplatePartialSpecialization:
4349 case Decl::ClassTemplateSpecialization:
4350 case Decl::Friend:
4351 case Decl::FriendTemplate:
4352 case Decl::FunctionTemplate:
4353 case Decl::LinkageSpec:
4354 case Decl::Namespace:
4355 case Decl::NamespaceAlias:
4356 case Decl::NonTypeTemplateParm:
4357 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004358 case Decl::TemplateTemplateParm:
4359 case Decl::TemplateTypeParm:
4360 case Decl::UnresolvedUsingTypename:
4361 case Decl::UnresolvedUsingValue:
4362 case Decl::Using:
4363 case Decl::UsingDirective:
4364 case Decl::UsingShadow:
4365 return CXLanguage_CPlusPlus;
4366 }
4367
4368 return CXLanguage_C;
4369}
4370
4371extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004372
4373enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4374 if (clang_isDeclaration(cursor.kind))
4375 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4376 if (D->hasAttr<UnavailableAttr>() ||
4377 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4378 return CXAvailability_Available;
4379
4380 if (D->hasAttr<DeprecatedAttr>())
4381 return CXAvailability_Deprecated;
4382 }
4383
4384 return CXAvailability_Available;
4385}
4386
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004387CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4388 if (clang_isDeclaration(cursor.kind))
4389 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4390
4391 return CXLanguage_Invalid;
4392}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004393
4394CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4395 if (clang_isDeclaration(cursor.kind)) {
4396 if (Decl *D = getCursorDecl(cursor)) {
4397 DeclContext *DC = D->getDeclContext();
4398 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4399 }
4400 }
4401
4402 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4403 if (Decl *D = getCursorDecl(cursor))
4404 return MakeCXCursor(D, getCursorASTUnit(cursor));
4405 }
4406
4407 return clang_getNullCursor();
4408}
4409
4410CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4411 if (clang_isDeclaration(cursor.kind)) {
4412 if (Decl *D = getCursorDecl(cursor)) {
4413 DeclContext *DC = D->getLexicalDeclContext();
4414 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4415 }
4416 }
4417
4418 // FIXME: Note that we can't easily compute the lexical context of a
4419 // statement or expression, so we return nothing.
4420 return clang_getNullCursor();
4421}
4422
Douglas Gregor9f592342010-10-01 20:25:15 +00004423static void CollectOverriddenMethods(DeclContext *Ctx,
4424 ObjCMethodDecl *Method,
4425 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4426 if (!Ctx)
4427 return;
4428
4429 // If we have a class or category implementation, jump straight to the
4430 // interface.
4431 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4432 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4433
4434 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4435 if (!Container)
4436 return;
4437
4438 // Check whether we have a matching method at this level.
4439 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4440 Method->isInstanceMethod()))
4441 if (Method != Overridden) {
4442 // We found an override at this level; there is no need to look
4443 // into other protocols or categories.
4444 Methods.push_back(Overridden);
4445 return;
4446 }
4447
4448 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4449 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4450 PEnd = Protocol->protocol_end();
4451 P != PEnd; ++P)
4452 CollectOverriddenMethods(*P, Method, Methods);
4453 }
4454
4455 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4456 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4457 PEnd = Category->protocol_end();
4458 P != PEnd; ++P)
4459 CollectOverriddenMethods(*P, Method, Methods);
4460 }
4461
4462 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4463 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4464 PEnd = Interface->protocol_end();
4465 P != PEnd; ++P)
4466 CollectOverriddenMethods(*P, Method, Methods);
4467
4468 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4469 Category; Category = Category->getNextClassCategory())
4470 CollectOverriddenMethods(Category, Method, Methods);
4471
4472 // We only look into the superclass if we haven't found anything yet.
4473 if (Methods.empty())
4474 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4475 return CollectOverriddenMethods(Super, Method, Methods);
4476 }
4477}
4478
4479void clang_getOverriddenCursors(CXCursor cursor,
4480 CXCursor **overridden,
4481 unsigned *num_overridden) {
4482 if (overridden)
4483 *overridden = 0;
4484 if (num_overridden)
4485 *num_overridden = 0;
4486 if (!overridden || !num_overridden)
4487 return;
4488
4489 if (!clang_isDeclaration(cursor.kind))
4490 return;
4491
4492 Decl *D = getCursorDecl(cursor);
4493 if (!D)
4494 return;
4495
4496 // Handle C++ member functions.
4497 ASTUnit *CXXUnit = getCursorASTUnit(cursor);
4498 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4499 *num_overridden = CXXMethod->size_overridden_methods();
4500 if (!*num_overridden)
4501 return;
4502
4503 *overridden = new CXCursor [*num_overridden];
4504 unsigned I = 0;
4505 for (CXXMethodDecl::method_iterator
4506 M = CXXMethod->begin_overridden_methods(),
4507 MEnd = CXXMethod->end_overridden_methods();
4508 M != MEnd; (void)++M, ++I)
4509 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit);
4510 return;
4511 }
4512
4513 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4514 if (!Method)
4515 return;
4516
4517 // Handle Objective-C methods.
4518 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4519 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4520
4521 if (Methods.empty())
4522 return;
4523
4524 *num_overridden = Methods.size();
4525 *overridden = new CXCursor [Methods.size()];
4526 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4527 (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit);
4528}
4529
4530void clang_disposeOverriddenCursors(CXCursor *overridden) {
4531 delete [] overridden;
4532}
4533
Douglas Gregorecdcb882010-10-20 22:00:55 +00004534CXFile clang_getIncludedFile(CXCursor cursor) {
4535 if (cursor.kind != CXCursor_InclusionDirective)
4536 return 0;
4537
4538 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4539 return (void *)ID->getFile();
4540}
4541
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004542} // end: extern "C"
4543
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004544
4545//===----------------------------------------------------------------------===//
4546// C++ AST instrospection.
4547//===----------------------------------------------------------------------===//
4548
4549extern "C" {
4550unsigned clang_CXXMethod_isStatic(CXCursor C) {
4551 if (!clang_isDeclaration(C.kind))
4552 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004553
4554 CXXMethodDecl *Method = 0;
4555 Decl *D = cxcursor::getCursorDecl(C);
4556 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4557 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4558 else
4559 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4560 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004561}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004562
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004563} // end: extern "C"
4564
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004565//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004566// Attribute introspection.
4567//===----------------------------------------------------------------------===//
4568
4569extern "C" {
4570CXType clang_getIBOutletCollectionType(CXCursor C) {
4571 if (C.kind != CXCursor_IBOutletCollectionAttr)
4572 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4573
4574 IBOutletCollectionAttr *A =
4575 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4576
4577 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4578}
4579} // end: extern "C"
4580
4581//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00004582// CXString Operations.
4583//===----------------------------------------------------------------------===//
4584
4585extern "C" {
4586const char *clang_getCString(CXString string) {
4587 return string.Spelling;
4588}
4589
4590void clang_disposeString(CXString string) {
4591 if (string.MustFreeString && string.Spelling)
4592 free((void*)string.Spelling);
4593}
Ted Kremenek04bb7162010-01-22 22:44:15 +00004594
Ted Kremenekfb480492010-01-13 21:46:36 +00004595} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00004596
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004597namespace clang { namespace cxstring {
4598CXString createCXString(const char *String, bool DupString){
4599 CXString Str;
4600 if (DupString) {
4601 Str.Spelling = strdup(String);
4602 Str.MustFreeString = 1;
4603 } else {
4604 Str.Spelling = String;
4605 Str.MustFreeString = 0;
4606 }
4607 return Str;
4608}
4609
4610CXString createCXString(llvm::StringRef String, bool DupString) {
4611 CXString Result;
4612 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
4613 char *Spelling = (char *)malloc(String.size() + 1);
4614 memmove(Spelling, String.data(), String.size());
4615 Spelling[String.size()] = 0;
4616 Result.Spelling = Spelling;
4617 Result.MustFreeString = 1;
4618 } else {
4619 Result.Spelling = String.data();
4620 Result.MustFreeString = 0;
4621 }
4622 return Result;
4623}
4624}}
4625
Ted Kremenek04bb7162010-01-22 22:44:15 +00004626//===----------------------------------------------------------------------===//
4627// Misc. utility functions.
4628//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004629
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004630/// Default to using an 8 MB stack size on "safety" threads.
4631static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004632
4633namespace clang {
4634
4635bool RunSafely(llvm::CrashRecoveryContext &CRC,
4636 void (*Fn)(void*), void *UserData) {
4637 if (unsigned Size = GetSafetyThreadStackSize())
4638 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4639 return CRC.RunSafely(Fn, UserData);
4640}
4641
4642unsigned GetSafetyThreadStackSize() {
4643 return SafetyStackThreadSize;
4644}
4645
4646void SetSafetyThreadStackSize(unsigned Value) {
4647 SafetyStackThreadSize = Value;
4648}
4649
4650}
4651
Ted Kremenek04bb7162010-01-22 22:44:15 +00004652extern "C" {
4653
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004654CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004655 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004656}
4657
4658} // end: extern "C"