blob: a561b4a7f3c80e5c8c8be08a19c3b49df96e7121 [file] [log] [blame]
Ted Kremenekb60d87c2009-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 Dunbarbbc569c2009-11-30 20:42:43 +00007//
Ted Kremenekb60d87c2009-08-26 22:36:44 +00008//===----------------------------------------------------------------------===//
9//
Ted Kremenek0ec2cca2010-01-05 19:32:54 +000010// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
Ted Kremenekb60d87c2009-08-26 22:36:44 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenek0ec2cca2010-01-05 19:32:54 +000015#include "CIndexer.h"
Ted Kremenek87553c42010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremeneka5940822010-08-26 01:42:22 +000017#include "CXType.h"
Ted Kremenek97a45372010-01-25 22:34:44 +000018#include "CXSourceLocation.h"
Douglas Gregor4f9c3762010-01-28 00:27:43 +000019#include "CIndexDiagnostic.h"
Ted Kremenek0ec2cca2010-01-05 19:32:54 +000020
Ted Kremenekc0f3f722010-01-22 22:44:15 +000021#include "clang/Basic/Version.h"
Douglas Gregorba965fb2010-01-28 00:56:43 +000022
Steve Naroffa1c72842009-08-28 15:28:48 +000023#include "clang/AST/DeclVisitor.h"
Steve Naroff66af1ae2009-09-22 19:25:29 +000024#include "clang/AST/StmtVisitor.h"
Douglas Gregor93f89952010-01-21 16:28:34 +000025#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramer064414532010-04-12 19:45:50 +000026#include "clang/Basic/Diagnostic.h"
27#include "clang/Frontend/ASTUnit.h"
28#include "clang/Frontend/CompilerInstance.h"
Douglas Gregorba965fb2010-01-28 00:56:43 +000029#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenek2a43fd52010-01-06 23:43:31 +000030#include "clang/Lex/Lexer.h"
Benjamin Kramer064414532010-04-12 19:45:50 +000031#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor562c1f92010-01-22 19:49:59 +000032#include "clang/Lex/Preprocessor.h"
Daniel Dunbarc91f2ff2010-08-18 18:43:14 +000033#include "llvm/Support/CrashRecoveryContext.h"
Douglas Gregord3d923a2009-10-16 21:24:31 +000034#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor8ef4c802010-08-09 21:00:09 +000035#include "llvm/Support/Timer.h"
Benjamin Kramer2836c4c2009-10-18 11:19:36 +000036#include "llvm/System/Program.h"
Douglas Gregor1e21cc72010-02-18 23:07:20 +000037#include "llvm/System/Signals.h"
Ted Kremenek428c6372009-10-19 21:44:57 +000038
Benjamin Kramerf156b9d2010-03-13 21:22:49 +000039// Needed to define L_TMPNAM on some systems.
40#include <cstdio>
41
Steve Naroffa1c72842009-08-28 15:28:48 +000042using namespace clang;
Ted Kremenek87553c42010-01-15 20:35:54 +000043using namespace clang::cxcursor;
Ted Kremenek5cca6eb2010-02-17 00:41:08 +000044using namespace clang::cxstring;
Steve Naroffa1c72842009-08-28 15:28:48 +000045
Ted Kremenek991eb3f2010-01-06 03:42:32 +000046//===----------------------------------------------------------------------===//
47// Crash Reporting.
48//===----------------------------------------------------------------------===//
49
Ted Kremenekea465e12010-05-22 00:06:46 +000050#ifdef USE_CRASHTRACER
Ted Kremenek991eb3f2010-01-06 03:42:32 +000051#include "clang/Analysis/Support/SaveAndRestore.h"
52// Integrate with crash reporter.
Daniel Dunbar6ac7d7d2010-05-20 23:50:23 +000053static const char *__crashreporter_info__ = 0;
54asm(".desc ___crashreporter_info__, 0x10");
Ted Kremenek896e1642010-02-17 21:12:23 +000055#define NUM_CRASH_STRINGS 32
Ted Kremenek7a5ede22010-01-07 22:49:05 +000056static unsigned crashtracer_counter = 0;
Ted Kremenek32b79312010-01-07 23:13:53 +000057static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek7a5ede22010-01-07 22:49:05 +000058static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
59static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
60
61static unsigned SetCrashTracerInfo(const char *str,
62 llvm::SmallString<1024> &AggStr) {
Ted Kremenekf441baf2010-02-17 00:41:40 +000063
Ted Kremenek32b79312010-01-07 23:13:53 +000064 unsigned slot = 0;
Ted Kremenek7a5ede22010-01-07 22:49:05 +000065 while (crashtracer_strings[slot]) {
66 if (++slot == NUM_CRASH_STRINGS)
67 slot = 0;
68 }
69 crashtracer_strings[slot] = str;
Ted Kremenek32b79312010-01-07 23:13:53 +000070 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek7a5ede22010-01-07 22:49:05 +000071
72 // We need to create an aggregate string because multiple threads
73 // may be in this method at one time. The crash reporter string
74 // will attempt to overapproximate the set of in-flight invocations
75 // of this function. Race conditions can still cause this goal
76 // to not be achieved.
77 {
Ted Kremenekf441baf2010-02-17 00:41:40 +000078 llvm::raw_svector_ostream Out(AggStr);
Ted Kremenek7a5ede22010-01-07 22:49:05 +000079 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
80 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
81 }
82 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
83 return slot;
84}
85
86static void ResetCrashTracerInfo(unsigned slot) {
Ted Kremenek32b79312010-01-07 23:13:53 +000087 unsigned max_slot = 0;
88 unsigned max_value = 0;
Ted Kremenekf441baf2010-02-17 00:41:40 +000089
Ted Kremenek32b79312010-01-07 23:13:53 +000090 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
91
92 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
93 if (agg_crashtracer_strings[i] &&
94 crashtracer_counter_id[i] > max_value) {
95 max_slot = i;
96 max_value = crashtracer_counter_id[i];
Ted Kremenek7a5ede22010-01-07 22:49:05 +000097 }
Ted Kremenek32b79312010-01-07 23:13:53 +000098
99 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek7a5ede22010-01-07 22:49:05 +0000100}
101
102namespace {
103class ArgsCrashTracerInfo {
104 llvm::SmallString<1024> CrashString;
105 llvm::SmallString<1024> AggregateString;
106 unsigned crashtracerSlot;
107public:
108 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
109 : crashtracerSlot(0)
110 {
111 {
112 llvm::raw_svector_ostream Out(CrashString);
Ted Kremenekb3908402010-03-05 22:43:25 +0000113 Out << "ClangCIndex [" << getClangFullVersion() << "]"
114 << "[createTranslationUnitFromSourceFile]: clang";
Ted Kremenek7a5ede22010-01-07 22:49:05 +0000115 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
116 E=Args.end(); I!=E; ++I)
117 Out << ' ' << *I;
118 }
119 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
120 AggregateString);
121 }
Ted Kremenekf441baf2010-02-17 00:41:40 +0000122
Ted Kremenek7a5ede22010-01-07 22:49:05 +0000123 ~ArgsCrashTracerInfo() {
124 ResetCrashTracerInfo(crashtracerSlot);
125 }
126};
127}
128#endif
Ted Kremenek991eb3f2010-01-06 03:42:32 +0000129
Douglas Gregor562c1f92010-01-22 19:49:59 +0000130/// \brief The result of comparing two source ranges.
131enum RangeComparisonResult {
132 /// \brief Either the ranges overlap or one of the ranges is invalid.
133 RangeOverlap,
Ted Kremenekf441baf2010-02-17 00:41:40 +0000134
Douglas Gregor562c1f92010-01-22 19:49:59 +0000135 /// \brief The first range ends before the second range starts.
136 RangeBefore,
Ted Kremenekf441baf2010-02-17 00:41:40 +0000137
Douglas Gregor562c1f92010-01-22 19:49:59 +0000138 /// \brief The first range starts after the second range ends.
139 RangeAfter
140};
141
Ted Kremenekf441baf2010-02-17 00:41:40 +0000142/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor562c1f92010-01-22 19:49:59 +0000143/// the translation unit.
Ted Kremenekf441baf2010-02-17 00:41:40 +0000144static RangeComparisonResult RangeCompare(SourceManager &SM,
145 SourceRange R1,
Douglas Gregor562c1f92010-01-22 19:49:59 +0000146 SourceRange R2) {
147 assert(R1.isValid() && "First range is invalid?");
148 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000149 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbar02968e52010-02-14 10:02:57 +0000150 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor562c1f92010-01-22 19:49:59 +0000151 return RangeBefore;
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000152 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbar02968e52010-02-14 10:02:57 +0000153 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor562c1f92010-01-22 19:49:59 +0000154 return RangeAfter;
155 return RangeOverlap;
156}
157
Ted Kremenek680fe512010-05-05 00:55:23 +0000158/// \brief Determine if a source location falls within, before, or after a
159/// a given source range.
160static RangeComparisonResult LocationCompare(SourceManager &SM,
161 SourceLocation L, SourceRange R) {
162 assert(R.isValid() && "First range is invalid?");
163 assert(L.isValid() && "Second range is invalid?");
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000164 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenek680fe512010-05-05 00:55:23 +0000165 return RangeOverlap;
Ted Kremenek680fe512010-05-05 00:55:23 +0000166 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
167 return RangeBefore;
168 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
169 return RangeAfter;
170 return RangeOverlap;
171}
172
Daniel Dunbar474b2072010-02-14 01:47:29 +0000173/// \brief Translate a Clang source range into a CIndex source range.
174///
175/// Clang internally represents ranges where the end location points to the
176/// start of the token at the end. However, for external clients it is more
177/// useful to have a CXSourceRange be a proper half-open interval. This routine
178/// does the appropriate translation.
Ted Kremenekf441baf2010-02-17 00:41:40 +0000179CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar474b2072010-02-14 01:47:29 +0000180 const LangOptions &LangOpts,
Chris Lattnered8b6b72010-06-18 22:45:06 +0000181 const CharSourceRange &R) {
Daniel Dunbar474b2072010-02-14 01:47:29 +0000182 // We want the last character in this location, so we will adjust the
Douglas Gregoraae92242010-03-19 21:51:54 +0000183 // location accordingly.
184 // FIXME: How do do this with a macro instantiation location?
Daniel Dunbar474b2072010-02-14 01:47:29 +0000185 SourceLocation EndLoc = R.getEnd();
Chris Lattnered8b6b72010-06-18 22:45:06 +0000186 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregoraae92242010-03-19 21:51:54 +0000187 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar474b2072010-02-14 01:47:29 +0000188 EndLoc = EndLoc.getFileLocWithOffset(Length);
189 }
190
191 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
192 R.getBegin().getRawEncoding(),
193 EndLoc.getRawEncoding() };
194 return Result;
195}
Douglas Gregor4f46e782010-01-19 21:36:55 +0000196
Ted Kremenek991eb3f2010-01-06 03:42:32 +0000197//===----------------------------------------------------------------------===//
Douglas Gregor562c1f92010-01-22 19:49:59 +0000198// Cursor visitor.
Ted Kremenek991eb3f2010-01-06 03:42:32 +0000199//===----------------------------------------------------------------------===//
200
Steve Naroff1054e602009-08-31 00:59:03 +0000201namespace {
Ted Kremenekf441baf2010-02-17 00:41:40 +0000202
Douglas Gregor71f3d942010-01-20 20:59:29 +0000203// Cursor visitor.
Douglas Gregor93f89952010-01-21 16:28:34 +0000204class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000205 public TypeLocVisitor<CursorVisitor, bool>,
206 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor93f89952010-01-21 16:28:34 +0000207{
Douglas Gregor562c1f92010-01-22 19:49:59 +0000208 /// \brief The translation unit we are traversing.
Douglas Gregorfed36b12010-01-20 23:57:43 +0000209 ASTUnit *TU;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000210
Douglas Gregor562c1f92010-01-22 19:49:59 +0000211 /// \brief The parent cursor whose children we are traversing.
Douglas Gregor71f3d942010-01-20 20:59:29 +0000212 CXCursor Parent;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000213
Douglas Gregor562c1f92010-01-22 19:49:59 +0000214 /// \brief The declaration that serves at the parent of any statement or
215 /// expression nodes.
Douglas Gregord1824312010-01-21 17:29:07 +0000216 Decl *StmtParent;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000217
Douglas Gregor562c1f92010-01-22 19:49:59 +0000218 /// \brief The visitor function.
Douglas Gregor71f3d942010-01-20 20:59:29 +0000219 CXCursorVisitor Visitor;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000220
Douglas Gregor562c1f92010-01-22 19:49:59 +0000221 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregor71f3d942010-01-20 20:59:29 +0000222 CXClientData ClientData;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000223
Douglas Gregor16bef852009-10-16 20:01:17 +0000224 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
225 // to the visitor. Declarations with a PCH level greater than this value will
226 // be suppressed.
227 unsigned MaxPCHLevel;
Douglas Gregor562c1f92010-01-22 19:49:59 +0000228
229 /// \brief When valid, a source range to which the cursor should restrict
230 /// its search.
231 SourceRange RegionOfInterest;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000232
Douglas Gregor71f3d942010-01-20 20:59:29 +0000233 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor93f89952010-01-21 16:28:34 +0000234 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000235 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000236
237 /// \brief Determine whether this particular source range comes before, comes
238 /// after, or overlaps the region of interest.
Douglas Gregor562c1f92010-01-22 19:49:59 +0000239 ///
Daniel Dunbar02968e52010-02-14 10:02:57 +0000240 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf441baf2010-02-17 00:41:40 +0000241 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
242
Ted Kremenek12e0f292010-05-13 00:25:00 +0000243 class SetParentRAII {
244 CXCursor &Parent;
245 Decl *&StmtParent;
246 CXCursor OldParent;
247
248 public:
249 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
250 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
251 {
252 Parent = NewParent;
253 if (clang_isDeclaration(Parent.kind))
254 StmtParent = getCursorDecl(Parent);
255 }
256
257 ~SetParentRAII() {
258 Parent = OldParent;
259 if (clang_isDeclaration(Parent.kind))
260 StmtParent = getCursorDecl(Parent);
261 }
262 };
263
Steve Naroff1054e602009-08-31 00:59:03 +0000264public:
Ted Kremenekf441baf2010-02-17 00:41:40 +0000265 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
266 unsigned MaxPCHLevel,
Douglas Gregor562c1f92010-01-22 19:49:59 +0000267 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf441baf2010-02-17 00:41:40 +0000268 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Douglas Gregor562c1f92010-01-22 19:49:59 +0000269 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregor71f3d942010-01-20 20:59:29 +0000270 {
271 Parent.kind = CXCursor_NoDeclFound;
272 Parent.data[0] = 0;
273 Parent.data[1] = 0;
274 Parent.data[2] = 0;
Douglas Gregord1824312010-01-21 17:29:07 +0000275 StmtParent = 0;
Douglas Gregor71f3d942010-01-20 20:59:29 +0000276 }
Ted Kremenekf441baf2010-02-17 00:41:40 +0000277
Douglas Gregor562c1f92010-01-22 19:49:59 +0000278 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor3dc10b52010-03-20 00:41:21 +0000279
280 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
281 getPreprocessedEntities();
282
Douglas Gregor71f3d942010-01-20 20:59:29 +0000283 bool VisitChildren(CXCursor Parent);
Ted Kremenekf441baf2010-02-17 00:41:40 +0000284
Douglas Gregor93f89952010-01-21 16:28:34 +0000285 // Declaration visitors
Ted Kremenek6ab9aa022010-02-18 05:46:33 +0000286 bool VisitAttributes(Decl *D);
Ted Kremenek33b9a422010-04-11 21:47:37 +0000287 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenekae9e2212010-08-27 21:34:58 +0000288 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregor71f3d942010-01-20 20:59:29 +0000289 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek7dff4162010-02-18 18:47:08 +0000290 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
291 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremeneke2110252010-02-18 22:36:18 +0000292 bool VisitTagDecl(TagDecl *D);
Douglas Gregor9dc243c2010-09-01 17:32:36 +0000293 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregorf96abb22010-08-31 19:31:58 +0000294 bool VisitClassTemplatePartialSpecializationDecl(
295 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregor713602b2010-08-31 17:01:39 +0000296 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremeneke2110252010-02-18 22:36:18 +0000297 bool VisitEnumConstantDecl(EnumConstantDecl *D);
298 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
299 bool VisitFunctionDecl(FunctionDecl *ND);
300 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek7dff4162010-02-18 18:47:08 +0000301 bool VisitVarDecl(VarDecl *);
Douglas Gregor06c7d2d2010-09-01 20:16:53 +0000302 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregor713602b2010-08-31 17:01:39 +0000303 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor1fbaeb12010-08-31 19:02:00 +0000304 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor06c7d2d2010-09-01 20:16:53 +0000305 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremeneke2110252010-02-18 22:36:18 +0000306 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
307 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
308 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
309 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek49be9e02010-05-18 21:09:07 +0000310 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremeneke2110252010-02-18 22:36:18 +0000311 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
312 bool VisitObjCImplDecl(ObjCImplDecl *D);
313 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
314 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
315 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
316 // etc.
317 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
318 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
319 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremenekb80cba52010-05-07 01:04:29 +0000320 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenekbd67fb22010-05-06 23:38:21 +0000321 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregora89314e2010-08-31 23:48:11 +0000322 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor01a430132010-09-01 03:07:18 +0000323 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregora9aa29c2010-09-01 19:52:22 +0000324 bool VisitUsingDecl(UsingDecl *D);
325 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
326 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor01a430132010-09-01 03:07:18 +0000327
Douglas Gregor12bca222010-08-31 14:41:23 +0000328 // Name visitor
329 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregor3335f482010-09-02 17:35:32 +0000330 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor12bca222010-08-31 14:41:23 +0000331
Douglas Gregor713602b2010-08-31 17:01:39 +0000332 // Template visitors
333 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregora23e8f72010-08-31 20:37:03 +0000334 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregor713602b2010-08-31 17:01:39 +0000335 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
336
Douglas Gregor93f89952010-01-21 16:28:34 +0000337 // Type visitors
Douglas Gregor12bca222010-08-31 14:41:23 +0000338 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregord1824312010-01-21 17:29:07 +0000339 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor93f89952010-01-21 16:28:34 +0000340 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregord1824312010-01-21 17:29:07 +0000341 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
342 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregor713602b2010-08-31 17:01:39 +0000343 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregord1824312010-01-21 17:29:07 +0000344 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCall8b07ec22010-05-15 11:32:37 +0000345 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregord1824312010-01-21 17:29:07 +0000346 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
347 bool VisitPointerTypeLoc(PointerTypeLoc TL);
348 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
349 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
350 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
351 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor12bca222010-08-31 14:41:23 +0000352 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregord1824312010-01-21 17:29:07 +0000353 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor713602b2010-08-31 17:01:39 +0000354 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor6479fc42010-01-21 20:48:56 +0000355 // FIXME: Implement visitors here when the unimplemented TypeLocs get
356 // implemented
357 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
358 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf441baf2010-02-17 00:41:40 +0000359
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000360 // Statement visitors
361 bool VisitStmt(Stmt *S);
362 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregore1084fa2010-01-22 01:00:11 +0000363 // FIXME: LabelStmt label?
364 bool VisitIfStmt(IfStmt *S);
365 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek12e0f292010-05-13 00:25:00 +0000366 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor7201f9f2010-01-25 16:12:32 +0000367 bool VisitWhileStmt(WhileStmt *S);
368 bool VisitForStmt(ForStmt *S);
Ted Kremenek12e0f292010-05-13 00:25:00 +0000369// bool VisitSwitchCase(SwitchCase *S);
Ted Kremenekf441baf2010-02-17 00:41:40 +0000370
Douglas Gregor625a5152010-01-23 00:40:08 +0000371 // Expression visitors
Douglas Gregoraac7c812010-09-02 20:35:02 +0000372 bool VisitDeclRefExpr(DeclRefExpr *E);
Douglas Gregorb59d21c2010-07-29 00:26:18 +0000373 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek33b9a422010-04-11 21:47:37 +0000374 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor625a5152010-01-23 00:40:08 +0000375 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek33b9a422010-04-11 21:47:37 +0000376 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorde4827d2010-03-08 16:40:19 +0000377 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregorabd9e962010-04-20 15:39:42 +0000378 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor882211c2010-04-28 22:16:22 +0000379 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek33b9a422010-04-11 21:47:37 +0000380 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor32e4c862010-09-02 21:07:44 +0000381 bool VisitMemberExpr(MemberExpr *E);
Douglas Gregore68aaca2010-08-10 15:02:34 +0000382 // FIXME: AddrLabelExpr (once we have cursors for labels)
383 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
384 bool VisitVAArgExpr(VAArgExpr *E);
385 // FIXME: InitListExpr (for the designators)
386 // FIXME: DesignatedInitExpr
Douglas Gregor46af5012010-09-02 21:20:16 +0000387 bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
Douglas Gregorfd81cea2010-09-02 21:38:13 +0000388 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { return false; }
Douglas Gregor2b88c112010-09-08 00:15:04 +0000389 bool VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
390 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor0744ef62010-09-07 21:49:58 +0000391 bool VisitCXXNewExpr(CXXNewExpr *E);
Douglas Gregor4edb2ff2010-09-02 22:09:03 +0000392 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor3ca46b42010-09-02 22:19:24 +0000393 // FIXME: UnaryTypeTraitExpr has poor source-location information.
Douglas Gregorf24eaee2010-09-02 22:29:21 +0000394 bool VisitOverloadExpr(OverloadExpr *E);
Douglas Gregor4ae34af2010-09-03 17:24:10 +0000395 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregor2b88c112010-09-08 00:15:04 +0000396 bool VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Douglas Gregor45838272010-09-03 17:35:34 +0000397 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Douglas Gregor901a0fa2010-09-03 18:01:25 +0000398 bool VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E);
Steve Naroff1054e602009-08-31 00:59:03 +0000399};
Ted Kremenekf441baf2010-02-17 00:41:40 +0000400
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000401} // end anonymous namespace
Benjamin Kramer61f5d0c2009-10-18 16:11:04 +0000402
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000403static SourceRange getRawCursorExtent(CXCursor C);
404
Douglas Gregor562c1f92010-01-22 19:49:59 +0000405RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor562c1f92010-01-22 19:49:59 +0000406 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
407}
408
Douglas Gregor71f3d942010-01-20 20:59:29 +0000409/// \brief Visit the given cursor and, if requested by the visitor,
410/// its children.
411///
Douglas Gregor562c1f92010-01-22 19:49:59 +0000412/// \param Cursor the cursor to visit.
413///
414/// \param CheckRegionOfInterest if true, then the caller already checked that
415/// this cursor is within the region of interest.
416///
Douglas Gregor71f3d942010-01-20 20:59:29 +0000417/// \returns true if the visitation should be aborted, false if it
418/// should continue.
Douglas Gregor562c1f92010-01-22 19:49:59 +0000419bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregor71f3d942010-01-20 20:59:29 +0000420 if (clang_isInvalid(Cursor.kind))
421 return false;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000422
Douglas Gregor71f3d942010-01-20 20:59:29 +0000423 if (clang_isDeclaration(Cursor.kind)) {
424 Decl *D = getCursorDecl(Cursor);
425 assert(D && "Invalid declaration cursor");
426 if (D->getPCHLevel() > MaxPCHLevel)
427 return false;
428
429 if (D->isImplicit())
430 return false;
431 }
432
Douglas Gregor562c1f92010-01-22 19:49:59 +0000433 // If we have a range of interest, and this cursor doesn't intersect with it,
434 // we're done.
435 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000436 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbar2f4ba172010-02-14 08:32:05 +0000437 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor562c1f92010-01-22 19:49:59 +0000438 return false;
439 }
Ted Kremenekf441baf2010-02-17 00:41:40 +0000440
Douglas Gregor71f3d942010-01-20 20:59:29 +0000441 switch (Visitor(Cursor, Parent, ClientData)) {
442 case CXChildVisit_Break:
443 return true;
444
445 case CXChildVisit_Continue:
446 return false;
447
448 case CXChildVisit_Recurse:
449 return VisitChildren(Cursor);
450 }
451
Douglas Gregor33f16852010-01-25 16:45:46 +0000452 return false;
Douglas Gregor71f3d942010-01-20 20:59:29 +0000453}
454
Douglas Gregor3dc10b52010-03-20 00:41:21 +0000455std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
456CursorVisitor::getPreprocessedEntities() {
457 PreprocessingRecord &PPRec
458 = *TU->getPreprocessor().getPreprocessingRecord();
459
460 bool OnlyLocalDecls
461 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
462
463 // There is no region of interest; we have to walk everything.
464 if (RegionOfInterest.isInvalid())
465 return std::make_pair(PPRec.begin(OnlyLocalDecls),
466 PPRec.end(OnlyLocalDecls));
467
468 // Find the file in which the region of interest lands.
469 SourceManager &SM = TU->getSourceManager();
470 std::pair<FileID, unsigned> Begin
471 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
472 std::pair<FileID, unsigned> End
473 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
474
475 // The region of interest spans files; we have to walk everything.
476 if (Begin.first != End.first)
477 return std::make_pair(PPRec.begin(OnlyLocalDecls),
478 PPRec.end(OnlyLocalDecls));
479
480 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
481 = TU->getPreprocessedEntitiesByFile();
482 if (ByFileMap.empty()) {
483 // Build the mapping from files to sets of preprocessed entities.
484 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
485 EEnd = PPRec.end(OnlyLocalDecls);
486 E != EEnd; ++E) {
487 std::pair<FileID, unsigned> P
488 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
489 ByFileMap[P.first].push_back(*E);
490 }
491 }
492
493 return std::make_pair(ByFileMap[Begin.first].begin(),
494 ByFileMap[Begin.first].end());
495}
496
Douglas Gregor71f3d942010-01-20 20:59:29 +0000497/// \brief Visit the children of the given cursor.
498///
499/// \returns true if the visitation should be aborted, false if it
500/// should continue.
Ted Kremenekf441baf2010-02-17 00:41:40 +0000501bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000502 if (clang_isReference(Cursor.kind)) {
503 // By definition, references have no children.
504 return false;
505 }
Ted Kremenekf441baf2010-02-17 00:41:40 +0000506
507 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregor71f3d942010-01-20 20:59:29 +0000508 // done.
Ted Kremenek12e0f292010-05-13 00:25:00 +0000509 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf441baf2010-02-17 00:41:40 +0000510
Douglas Gregor71f3d942010-01-20 20:59:29 +0000511 if (clang_isDeclaration(Cursor.kind)) {
512 Decl *D = getCursorDecl(Cursor);
513 assert(D && "Invalid declaration cursor");
Ted Kremenek0e293092010-02-18 18:47:01 +0000514 return VisitAttributes(D) || Visit(D);
Douglas Gregor71f3d942010-01-20 20:59:29 +0000515 }
Ted Kremenekf441baf2010-02-17 00:41:40 +0000516
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000517 if (clang_isStatement(Cursor.kind))
518 return Visit(getCursorStmt(Cursor));
519 if (clang_isExpression(Cursor.kind))
520 return Visit(getCursorExpr(Cursor));
Ted Kremenekf441baf2010-02-17 00:41:40 +0000521
Douglas Gregor71f3d942010-01-20 20:59:29 +0000522 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorfed36b12010-01-20 23:57:43 +0000523 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor562c1f92010-01-22 19:49:59 +0000524 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
525 RegionOfInterest.isInvalid()) {
Douglas Gregore9db88f2010-08-03 19:06:41 +0000526 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
527 TLEnd = CXXUnit->top_level_end();
528 TL != TLEnd; ++TL) {
529 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregorbefc4a12010-01-20 21:13:59 +0000530 return true;
531 }
Douglas Gregor5272e802010-03-19 05:22:59 +0000532 } else if (VisitDeclContext(
533 CXXUnit->getASTContext().getTranslationUnitDecl()))
534 return true;
Bob Wilson4f559a32010-03-19 03:57:57 +0000535
Douglas Gregor5272e802010-03-19 05:22:59 +0000536 // Walk the preprocessing record.
Daniel Dunbaraef1db12010-03-20 01:11:56 +0000537 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor5272e802010-03-19 05:22:59 +0000538 // FIXME: Once we have the ability to deserialize a preprocessing record,
539 // do so.
Douglas Gregor3dc10b52010-03-20 00:41:21 +0000540 PreprocessingRecord::iterator E, EEnd;
541 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor5272e802010-03-19 05:22:59 +0000542 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
543 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
544 return true;
Douglas Gregor3dc10b52010-03-20 00:41:21 +0000545
Douglas Gregor5272e802010-03-19 05:22:59 +0000546 continue;
547 }
548
549 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
550 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
551 return true;
552
553 continue;
554 }
555 }
556 }
Douglas Gregorbefc4a12010-01-20 21:13:59 +0000557 return false;
Douglas Gregor71f3d942010-01-20 20:59:29 +0000558 }
Ted Kremenekf441baf2010-02-17 00:41:40 +0000559
Douglas Gregor71f3d942010-01-20 20:59:29 +0000560 // Nothing to visit at the moment.
Douglas Gregor71f3d942010-01-20 20:59:29 +0000561 return false;
562}
563
Ted Kremenek33b9a422010-04-11 21:47:37 +0000564bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCalla3cecb62010-06-04 22:33:30 +0000565 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
566 return true;
Ted Kremenek33b9a422010-04-11 21:47:37 +0000567
Ted Kremenek60fe71a2010-07-22 11:30:19 +0000568 if (Stmt *Body = B->getBody())
569 return Visit(MakeCXCursor(Body, StmtParent, TU));
570
571 return false;
Ted Kremenek33b9a422010-04-11 21:47:37 +0000572}
573
Douglas Gregor71f3d942010-01-20 20:59:29 +0000574bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenek78668fd2010-01-13 00:22:49 +0000575 for (DeclContext::decl_iterator
Douglas Gregor71f3d942010-01-20 20:59:29 +0000576 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek6ab9aa022010-02-18 05:46:33 +0000577
Ted Kremenek49be9e02010-05-18 21:09:07 +0000578 Decl *D = *I;
579 if (D->getLexicalDeclContext() != DC)
580 continue;
581
582 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbar02968e52010-02-14 10:02:57 +0000583
Douglas Gregor562c1f92010-01-22 19:49:59 +0000584 if (RegionOfInterest.isValid()) {
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000585 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbar02968e52010-02-14 10:02:57 +0000586 if (Range.isInvalid())
Douglas Gregor562c1f92010-01-22 19:49:59 +0000587 continue;
Daniel Dunbar02968e52010-02-14 10:02:57 +0000588
589 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor562c1f92010-01-22 19:49:59 +0000590 case RangeBefore:
591 // This declaration comes before the region of interest; skip it.
592 continue;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000593
Douglas Gregor562c1f92010-01-22 19:49:59 +0000594 case RangeAfter:
595 // This declaration comes after the region of interest; we're done.
596 return false;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000597
Douglas Gregor562c1f92010-01-22 19:49:59 +0000598 case RangeOverlap:
599 // This declaration overlaps the region of interest; visit it.
600 break;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000601 }
Douglas Gregor562c1f92010-01-22 19:49:59 +0000602 }
Ted Kremenekf441baf2010-02-17 00:41:40 +0000603
Daniel Dunbar02968e52010-02-14 10:02:57 +0000604 if (Visit(Cursor, true))
Douglas Gregor71f3d942010-01-20 20:59:29 +0000605 return true;
606 }
Ted Kremenekf441baf2010-02-17 00:41:40 +0000607
Douglas Gregor71f3d942010-01-20 20:59:29 +0000608 return false;
Ted Kremenek78668fd2010-01-13 00:22:49 +0000609}
610
Douglas Gregord824f882010-01-22 00:50:27 +0000611bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
612 llvm_unreachable("Translation units are visited directly by Visit()");
613 return false;
614}
615
616bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
617 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
618 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf441baf2010-02-17 00:41:40 +0000619
Douglas Gregord824f882010-01-22 00:50:27 +0000620 return false;
621}
622
623bool CursorVisitor::VisitTagDecl(TagDecl *D) {
624 return VisitDeclContext(D);
625}
626
Douglas Gregor9dc243c2010-09-01 17:32:36 +0000627bool CursorVisitor::VisitClassTemplateSpecializationDecl(
628 ClassTemplateSpecializationDecl *D) {
629 bool ShouldVisitBody = false;
630 switch (D->getSpecializationKind()) {
631 case TSK_Undeclared:
632 case TSK_ImplicitInstantiation:
633 // Nothing to visit
634 return false;
635
636 case TSK_ExplicitInstantiationDeclaration:
637 case TSK_ExplicitInstantiationDefinition:
638 break;
639
640 case TSK_ExplicitSpecialization:
641 ShouldVisitBody = true;
642 break;
643 }
644
645 // Visit the template arguments used in the specialization.
646 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
647 TypeLoc TL = SpecType->getTypeLoc();
648 if (TemplateSpecializationTypeLoc *TSTLoc
649 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
650 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
651 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
652 return true;
653 }
654 }
655
656 if (ShouldVisitBody && VisitCXXRecordDecl(D))
657 return true;
658
659 return false;
660}
661
Douglas Gregorf96abb22010-08-31 19:31:58 +0000662bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
663 ClassTemplatePartialSpecializationDecl *D) {
664 // FIXME: Visit the "outer" template parameter lists on the TagDecl
665 // before visiting these template parameters.
666 if (VisitTemplateParameters(D->getTemplateParameters()))
667 return true;
668
669 // Visit the partial specialization arguments.
670 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
671 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
672 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
673 return true;
674
675 return VisitCXXRecordDecl(D);
676}
677
Douglas Gregor713602b2010-08-31 17:01:39 +0000678bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor06c7d2d2010-09-01 20:16:53 +0000679 // Visit the default argument.
680 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
681 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
682 if (Visit(DefArg->getTypeLoc()))
683 return true;
684
Douglas Gregor713602b2010-08-31 17:01:39 +0000685 return false;
686}
687
Douglas Gregord824f882010-01-22 00:50:27 +0000688bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
689 if (Expr *Init = D->getInitExpr())
690 return Visit(MakeCXCursor(Init, StmtParent, TU));
691 return false;
692}
693
Douglas Gregor93f89952010-01-21 16:28:34 +0000694bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
695 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
696 if (Visit(TSInfo->getTypeLoc()))
697 return true;
698
699 return false;
700}
701
Douglas Gregor71f3d942010-01-20 20:59:29 +0000702bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor12bca222010-08-31 14:41:23 +0000703 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
704 // Visit the function declaration's syntactic components in the order
705 // written. This requires a bit of work.
706 TypeLoc TL = TSInfo->getTypeLoc();
707 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
708
709 // If we have a function declared directly (without the use of a typedef),
710 // visit just the return type. Otherwise, just visit the function's type
711 // now.
712 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
713 (!FTL && Visit(TL)))
714 return true;
715
Douglas Gregor3335f482010-09-02 17:35:32 +0000716 // Visit the nested-name-specifier, if present.
717 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
718 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
719 return true;
Douglas Gregor12bca222010-08-31 14:41:23 +0000720
721 // Visit the declaration name.
722 if (VisitDeclarationNameInfo(ND->getNameInfo()))
723 return true;
724
725 // FIXME: Visit explicitly-specified template arguments!
726
727 // Visit the function parameters, if we have a function type.
728 if (FTL && VisitFunctionTypeLoc(*FTL, true))
729 return true;
730
731 // FIXME: Attributes?
732 }
733
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000734 if (ND->isThisDeclarationADefinition() &&
735 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
736 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000737
Douglas Gregor71f3d942010-01-20 20:59:29 +0000738 return false;
739}
Ted Kremenek78668fd2010-01-13 00:22:49 +0000740
Douglas Gregord824f882010-01-22 00:50:27 +0000741bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
742 if (VisitDeclaratorDecl(D))
743 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000744
Douglas Gregord824f882010-01-22 00:50:27 +0000745 if (Expr *BitWidth = D->getBitWidth())
746 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf441baf2010-02-17 00:41:40 +0000747
Douglas Gregord824f882010-01-22 00:50:27 +0000748 return false;
749}
750
751bool CursorVisitor::VisitVarDecl(VarDecl *D) {
752 if (VisitDeclaratorDecl(D))
753 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000754
Douglas Gregord824f882010-01-22 00:50:27 +0000755 if (Expr *Init = D->getInit())
756 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf441baf2010-02-17 00:41:40 +0000757
Douglas Gregord824f882010-01-22 00:50:27 +0000758 return false;
759}
760
Douglas Gregor06c7d2d2010-09-01 20:16:53 +0000761bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
762 if (VisitDeclaratorDecl(D))
763 return true;
764
765 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
766 if (Expr *DefArg = D->getDefaultArgument())
767 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
768
769 return false;
770}
771
Douglas Gregor713602b2010-08-31 17:01:39 +0000772bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
773 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
774 // before visiting these template parameters.
775 if (VisitTemplateParameters(D->getTemplateParameters()))
776 return true;
777
778 return VisitFunctionDecl(D->getTemplatedDecl());
779}
780
Douglas Gregor1fbaeb12010-08-31 19:02:00 +0000781bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
782 // FIXME: Visit the "outer" template parameter lists on the TagDecl
783 // before visiting these template parameters.
784 if (VisitTemplateParameters(D->getTemplateParameters()))
785 return true;
786
787 return VisitCXXRecordDecl(D->getTemplatedDecl());
788}
789
Douglas Gregor06c7d2d2010-09-01 20:16:53 +0000790bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
791 if (VisitTemplateParameters(D->getTemplateParameters()))
792 return true;
793
794 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
795 VisitTemplateArgumentLoc(D->getDefaultArgument()))
796 return true;
797
798 return false;
799}
800
Douglas Gregord824f882010-01-22 00:50:27 +0000801bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor12852d92010-03-08 14:59:44 +0000802 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
803 if (Visit(TSInfo->getTypeLoc()))
804 return true;
805
Ted Kremenekf441baf2010-02-17 00:41:40 +0000806 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregord824f882010-01-22 00:50:27 +0000807 PEnd = ND->param_end();
808 P != PEnd; ++P) {
809 if (Visit(MakeCXCursor(*P, TU)))
810 return true;
811 }
Ted Kremenekf441baf2010-02-17 00:41:40 +0000812
Douglas Gregord824f882010-01-22 00:50:27 +0000813 if (ND->isThisDeclarationADefinition() &&
814 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
815 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000816
Douglas Gregord824f882010-01-22 00:50:27 +0000817 return false;
818}
819
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000820bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
821 return VisitDeclContext(D);
822}
823
Douglas Gregor71f3d942010-01-20 20:59:29 +0000824bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorfed36b12010-01-20 23:57:43 +0000825 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
826 TU)))
Douglas Gregor71f3d942010-01-20 20:59:29 +0000827 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000828
Douglas Gregoref6eb842010-01-16 15:44:18 +0000829 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
830 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
831 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorfed36b12010-01-20 23:57:43 +0000832 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregor71f3d942010-01-20 20:59:29 +0000833 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000834
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000835 return VisitObjCContainerDecl(ND);
Ted Kremenek78668fd2010-01-13 00:22:49 +0000836}
837
Douglas Gregord824f882010-01-22 00:50:27 +0000838bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
839 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
840 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
841 E = PID->protocol_end(); I != E; ++I, ++PL)
842 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
843 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000844
Douglas Gregord824f882010-01-22 00:50:27 +0000845 return VisitObjCContainerDecl(PID);
846}
847
Ted Kremenek49be9e02010-05-18 21:09:07 +0000848bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
John McCalla3cecb62010-06-04 22:33:30 +0000849 if (Visit(PD->getTypeSourceInfo()->getTypeLoc()))
850 return true;
851
Ted Kremenek49be9e02010-05-18 21:09:07 +0000852 // FIXME: This implements a workaround with @property declarations also being
853 // installed in the DeclContext for the @interface. Eventually this code
854 // should be removed.
855 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
856 if (!CDecl || !CDecl->IsClassExtension())
857 return false;
858
859 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
860 if (!ID)
861 return false;
862
863 IdentifierInfo *PropertyId = PD->getIdentifier();
864 ObjCPropertyDecl *prevDecl =
865 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
866
867 if (!prevDecl)
868 return false;
869
870 // Visit synthesized methods since they will be skipped when visiting
871 // the @interface.
872 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
873 if (MD->isSynthesized())
874 if (Visit(MakeCXCursor(MD, TU)))
875 return true;
876
877 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
878 if (MD->isSynthesized())
879 if (Visit(MakeCXCursor(MD, TU)))
880 return true;
881
882 return false;
883}
884
Douglas Gregor71f3d942010-01-20 20:59:29 +0000885bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenek78668fd2010-01-13 00:22:49 +0000886 // Issue callbacks for super class.
Douglas Gregor71f3d942010-01-20 20:59:29 +0000887 if (D->getSuperClass() &&
888 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf441baf2010-02-17 00:41:40 +0000889 D->getSuperClassLoc(),
Douglas Gregorfed36b12010-01-20 23:57:43 +0000890 TU)))
Douglas Gregor71f3d942010-01-20 20:59:29 +0000891 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000892
Douglas Gregoref6eb842010-01-16 15:44:18 +0000893 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
894 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
895 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorfed36b12010-01-20 23:57:43 +0000896 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregor71f3d942010-01-20 20:59:29 +0000897 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000898
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000899 return VisitObjCContainerDecl(D);
Ted Kremenek78668fd2010-01-13 00:22:49 +0000900}
901
Douglas Gregord824f882010-01-22 00:50:27 +0000902bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
903 return VisitObjCContainerDecl(D);
Ted Kremenek78668fd2010-01-13 00:22:49 +0000904}
905
Douglas Gregord824f882010-01-22 00:50:27 +0000906bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremeneke184ac52010-03-19 20:39:03 +0000907 // 'ID' could be null when dealing with invalid code.
908 if (ObjCInterfaceDecl *ID = D->getClassInterface())
909 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
910 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000911
Douglas Gregord824f882010-01-22 00:50:27 +0000912 return VisitObjCImplDecl(D);
913}
914
915bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
916#if 0
917 // Issue callbacks for super class.
918 // FIXME: No source location information!
919 if (D->getSuperClass() &&
920 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf441baf2010-02-17 00:41:40 +0000921 D->getSuperClassLoc(),
Douglas Gregord824f882010-01-22 00:50:27 +0000922 TU)))
923 return true;
924#endif
Ted Kremenekf441baf2010-02-17 00:41:40 +0000925
Douglas Gregord824f882010-01-22 00:50:27 +0000926 return VisitObjCImplDecl(D);
927}
928
929bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
930 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
931 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
932 E = D->protocol_end();
933 I != E; ++I, ++PL)
Douglas Gregorfed36b12010-01-20 23:57:43 +0000934 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregor71f3d942010-01-20 20:59:29 +0000935 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000936
937 return false;
Ted Kremenek78668fd2010-01-13 00:22:49 +0000938}
939
Douglas Gregord824f882010-01-22 00:50:27 +0000940bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
941 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
942 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
943 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000944
Douglas Gregord824f882010-01-22 00:50:27 +0000945 return false;
Ted Kremenek78668fd2010-01-13 00:22:49 +0000946}
947
Ted Kremenekbd67fb22010-05-06 23:38:21 +0000948bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
949 return VisitDeclContext(D);
950}
951
Douglas Gregora89314e2010-08-31 23:48:11 +0000952bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregor3335f482010-09-02 17:35:32 +0000953 // Visit nested-name-specifier.
954 if (NestedNameSpecifier *Qualifier = D->getQualifier())
955 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
956 return true;
Douglas Gregora89314e2010-08-31 23:48:11 +0000957
958 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
959 D->getTargetNameLoc(), TU));
960}
961
Douglas Gregora9aa29c2010-09-01 19:52:22 +0000962bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregor3335f482010-09-02 17:35:32 +0000963 // Visit nested-name-specifier.
964 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
965 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
966 return true;
Douglas Gregora9aa29c2010-09-01 19:52:22 +0000967
968 // FIXME: Provide a multi-reference of some kind for all of the declarations
969 // that the using declaration refers to. We don't have this kind of cursor
970 // yet.
971
972 return VisitDeclarationNameInfo(D->getNameInfo());
973}
974
Douglas Gregor01a430132010-09-01 03:07:18 +0000975bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregor3335f482010-09-02 17:35:32 +0000976 // Visit nested-name-specifier.
977 if (NestedNameSpecifier *Qualifier = D->getQualifier())
978 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
979 return true;
Douglas Gregor01a430132010-09-01 03:07:18 +0000980
981 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
982 D->getIdentLocation(), TU));
983}
984
Douglas Gregora9aa29c2010-09-01 19:52:22 +0000985bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregor3335f482010-09-02 17:35:32 +0000986 // Visit nested-name-specifier.
987 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
988 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
989 return true;
990
Douglas Gregora9aa29c2010-09-01 19:52:22 +0000991 return VisitDeclarationNameInfo(D->getNameInfo());
992}
993
994bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
995 UnresolvedUsingTypenameDecl *D) {
Douglas Gregor3335f482010-09-02 17:35:32 +0000996 // Visit nested-name-specifier.
997 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
998 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
999 return true;
1000
Douglas Gregora9aa29c2010-09-01 19:52:22 +00001001 return false;
1002}
1003
Douglas Gregor12bca222010-08-31 14:41:23 +00001004bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1005 switch (Name.getName().getNameKind()) {
1006 case clang::DeclarationName::Identifier:
1007 case clang::DeclarationName::CXXLiteralOperatorName:
1008 case clang::DeclarationName::CXXOperatorName:
1009 case clang::DeclarationName::CXXUsingDirective:
1010 return false;
1011
1012 case clang::DeclarationName::CXXConstructorName:
1013 case clang::DeclarationName::CXXDestructorName:
1014 case clang::DeclarationName::CXXConversionFunctionName:
1015 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1016 return Visit(TSInfo->getTypeLoc());
1017 return false;
1018
1019 case clang::DeclarationName::ObjCZeroArgSelector:
1020 case clang::DeclarationName::ObjCOneArgSelector:
1021 case clang::DeclarationName::ObjCMultiArgSelector:
1022 // FIXME: Per-identifier location info?
1023 return false;
1024 }
1025
1026 return false;
1027}
1028
Douglas Gregor3335f482010-09-02 17:35:32 +00001029bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1030 SourceRange Range) {
1031 // FIXME: This whole routine is a hack to work around the lack of proper
1032 // source information in nested-name-specifiers (PR5791). Since we do have
1033 // a beginning source location, we can visit the first component of the
1034 // nested-name-specifier, if it's a single-token component.
1035 if (!NNS)
1036 return false;
1037
1038 // Get the first component in the nested-name-specifier.
1039 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1040 NNS = Prefix;
1041
1042 switch (NNS->getKind()) {
1043 case NestedNameSpecifier::Namespace:
1044 // FIXME: The token at this source location might actually have been a
1045 // namespace alias, but we don't model that. Lame!
1046 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1047 TU));
1048
1049 case NestedNameSpecifier::TypeSpec: {
1050 // If the type has a form where we know that the beginning of the source
1051 // range matches up with a reference cursor. Visit the appropriate reference
1052 // cursor.
1053 Type *T = NNS->getAsType();
1054 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1055 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1056 if (const TagType *Tag = dyn_cast<TagType>(T))
1057 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1058 if (const TemplateSpecializationType *TST
1059 = dyn_cast<TemplateSpecializationType>(T))
1060 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1061 break;
1062 }
1063
1064 case NestedNameSpecifier::TypeSpecWithTemplate:
1065 case NestedNameSpecifier::Global:
1066 case NestedNameSpecifier::Identifier:
1067 break;
1068 }
1069
1070 return false;
1071}
1072
Douglas Gregor713602b2010-08-31 17:01:39 +00001073bool CursorVisitor::VisitTemplateParameters(
1074 const TemplateParameterList *Params) {
1075 if (!Params)
1076 return false;
1077
1078 for (TemplateParameterList::const_iterator P = Params->begin(),
1079 PEnd = Params->end();
1080 P != PEnd; ++P) {
1081 if (Visit(MakeCXCursor(*P, TU)))
1082 return true;
1083 }
1084
1085 return false;
1086}
1087
Douglas Gregora23e8f72010-08-31 20:37:03 +00001088bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1089 switch (Name.getKind()) {
1090 case TemplateName::Template:
1091 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1092
1093 case TemplateName::OverloadedTemplate:
1094 // FIXME: We need a way to return multiple lookup results in a single
1095 // cursor.
1096 return false;
1097
1098 case TemplateName::DependentTemplate:
1099 // FIXME: Visit nested-name-specifier.
1100 return false;
1101
1102 case TemplateName::QualifiedTemplate:
1103 // FIXME: Visit nested-name-specifier.
1104 return Visit(MakeCursorTemplateRef(
1105 Name.getAsQualifiedTemplateName()->getDecl(),
1106 Loc, TU));
1107 }
1108
1109 return false;
1110}
1111
Douglas Gregor713602b2010-08-31 17:01:39 +00001112bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1113 switch (TAL.getArgument().getKind()) {
1114 case TemplateArgument::Null:
1115 case TemplateArgument::Integral:
1116 return false;
1117
1118 case TemplateArgument::Pack:
1119 // FIXME: Implement when variadic templates come along.
1120 return false;
1121
1122 case TemplateArgument::Type:
1123 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1124 return Visit(TSInfo->getTypeLoc());
1125 return false;
1126
1127 case TemplateArgument::Declaration:
1128 if (Expr *E = TAL.getSourceDeclExpression())
1129 return Visit(MakeCXCursor(E, StmtParent, TU));
1130 return false;
1131
1132 case TemplateArgument::Expression:
1133 if (Expr *E = TAL.getSourceExpression())
1134 return Visit(MakeCXCursor(E, StmtParent, TU));
1135 return false;
1136
1137 case TemplateArgument::Template:
Douglas Gregora23e8f72010-08-31 20:37:03 +00001138 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1139 TAL.getTemplateNameLoc());
Douglas Gregor713602b2010-08-31 17:01:39 +00001140 }
1141
1142 return false;
1143}
1144
Ted Kremenekb80cba52010-05-07 01:04:29 +00001145bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1146 return VisitDeclContext(D);
1147}
1148
Douglas Gregor12bca222010-08-31 14:41:23 +00001149bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1150 return Visit(TL.getUnqualifiedLoc());
1151}
1152
Douglas Gregord1824312010-01-21 17:29:07 +00001153bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1154 ASTContext &Context = TU->getASTContext();
1155
1156 // Some builtin types (such as Objective-C's "id", "sel", and
1157 // "Class") have associated declarations. Create cursors for those.
1158 QualType VisitType;
1159 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenekaaaf2bf2010-02-18 22:32:43 +00001160 case BuiltinType::Void:
Douglas Gregord1824312010-01-21 17:29:07 +00001161 case BuiltinType::Bool:
Ted Kremenekaaaf2bf2010-02-18 22:32:43 +00001162 case BuiltinType::Char_U:
1163 case BuiltinType::UChar:
Douglas Gregord1824312010-01-21 17:29:07 +00001164 case BuiltinType::Char16:
1165 case BuiltinType::Char32:
Ted Kremenekaaaf2bf2010-02-18 22:32:43 +00001166 case BuiltinType::UShort:
Douglas Gregord1824312010-01-21 17:29:07 +00001167 case BuiltinType::UInt:
1168 case BuiltinType::ULong:
1169 case BuiltinType::ULongLong:
Ted Kremenekaaaf2bf2010-02-18 22:32:43 +00001170 case BuiltinType::UInt128:
1171 case BuiltinType::Char_S:
1172 case BuiltinType::SChar:
Douglas Gregord1824312010-01-21 17:29:07 +00001173 case BuiltinType::WChar:
Ted Kremenekaaaf2bf2010-02-18 22:32:43 +00001174 case BuiltinType::Short:
1175 case BuiltinType::Int:
1176 case BuiltinType::Long:
1177 case BuiltinType::LongLong:
1178 case BuiltinType::Int128:
1179 case BuiltinType::Float:
1180 case BuiltinType::Double:
1181 case BuiltinType::LongDouble:
1182 case BuiltinType::NullPtr:
1183 case BuiltinType::Overload:
1184 case BuiltinType::Dependent:
Douglas Gregord1824312010-01-21 17:29:07 +00001185 break;
Ted Kremenekaaaf2bf2010-02-18 22:32:43 +00001186
1187 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregord1824312010-01-21 17:29:07 +00001188 break;
Ted Kremenekaaaf2bf2010-02-18 22:32:43 +00001189
Ted Kremenekfcb3db72010-02-18 18:52:18 +00001190 case BuiltinType::ObjCId:
1191 VisitType = Context.getObjCIdType();
1192 break;
Ted Kremenekaaaf2bf2010-02-18 22:32:43 +00001193
1194 case BuiltinType::ObjCClass:
1195 VisitType = Context.getObjCClassType();
1196 break;
1197
Douglas Gregord1824312010-01-21 17:29:07 +00001198 case BuiltinType::ObjCSel:
1199 VisitType = Context.getObjCSelType();
1200 break;
1201 }
1202
1203 if (!VisitType.isNull()) {
1204 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf441baf2010-02-17 00:41:40 +00001205 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregord1824312010-01-21 17:29:07 +00001206 TU));
1207 }
1208
1209 return false;
1210}
1211
Douglas Gregor93f89952010-01-21 16:28:34 +00001212bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1213 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1214}
1215
Douglas Gregord1824312010-01-21 17:29:07 +00001216bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1217 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1218}
1219
1220bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1221 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1222}
1223
Douglas Gregor713602b2010-08-31 17:01:39 +00001224bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1225 // FIXME: We can't visit the template template parameter, but there's
1226 // no context information with which we can match up the depth/index in the
1227 // type to the appropriate
1228 return false;
1229}
1230
Douglas Gregord1824312010-01-21 17:29:07 +00001231bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1232 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1233 return true;
1234
John McCall8b07ec22010-05-15 11:32:37 +00001235 return false;
1236}
1237
1238bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1239 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1240 return true;
1241
Douglas Gregord1824312010-01-21 17:29:07 +00001242 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1243 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1244 TU)))
1245 return true;
1246 }
1247
1248 return false;
1249}
1250
1251bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCall8b07ec22010-05-15 11:32:37 +00001252 return Visit(TL.getPointeeLoc());
Douglas Gregord1824312010-01-21 17:29:07 +00001253}
1254
1255bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1256 return Visit(TL.getPointeeLoc());
1257}
1258
1259bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1260 return Visit(TL.getPointeeLoc());
1261}
1262
1263bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1264 return Visit(TL.getPointeeLoc());
1265}
1266
1267bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf441baf2010-02-17 00:41:40 +00001268 return Visit(TL.getPointeeLoc());
Douglas Gregord1824312010-01-21 17:29:07 +00001269}
1270
1271bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf441baf2010-02-17 00:41:40 +00001272 return Visit(TL.getPointeeLoc());
Douglas Gregord1824312010-01-21 17:29:07 +00001273}
1274
Douglas Gregor12bca222010-08-31 14:41:23 +00001275bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1276 bool SkipResultType) {
1277 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregord1824312010-01-21 17:29:07 +00001278 return true;
1279
Douglas Gregord1824312010-01-21 17:29:07 +00001280 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek6ca136a2010-04-07 00:27:13 +00001281 if (Decl *D = TL.getArg(I))
1282 if (Visit(MakeCXCursor(D, TU)))
1283 return true;
Douglas Gregord1824312010-01-21 17:29:07 +00001284
1285 return false;
1286}
1287
1288bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1289 if (Visit(TL.getElementLoc()))
1290 return true;
1291
1292 if (Expr *Size = TL.getSizeExpr())
1293 return Visit(MakeCXCursor(Size, StmtParent, TU));
1294
1295 return false;
1296}
1297
Douglas Gregor713602b2010-08-31 17:01:39 +00001298bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1299 TemplateSpecializationTypeLoc TL) {
Douglas Gregora23e8f72010-08-31 20:37:03 +00001300 // Visit the template name.
1301 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1302 TL.getTemplateNameLoc()))
1303 return true;
Douglas Gregor713602b2010-08-31 17:01:39 +00001304
1305 // Visit the template arguments.
1306 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1307 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1308 return true;
1309
1310 return false;
1311}
1312
Douglas Gregor6479fc42010-01-21 20:48:56 +00001313bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1314 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1315}
1316
1317bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1318 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1319 return Visit(TSInfo->getTypeLoc());
1320
1321 return false;
1322}
1323
Douglas Gregor5e8cf372010-01-21 23:27:09 +00001324bool CursorVisitor::VisitStmt(Stmt *S) {
1325 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1326 Child != ChildEnd; ++Child) {
Ted Kremenek12e0f292010-05-13 00:25:00 +00001327 if (Stmt *C = *Child)
1328 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1329 return true;
Douglas Gregor5e8cf372010-01-21 23:27:09 +00001330 }
Ted Kremenekf441baf2010-02-17 00:41:40 +00001331
Douglas Gregor5e8cf372010-01-21 23:27:09 +00001332 return false;
1333}
1334
Ted Kremenek12e0f292010-05-13 00:25:00 +00001335bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
1336 // Specially handle CaseStmts because they can be nested, e.g.:
1337 //
1338 // case 1:
1339 // case 2:
1340 //
1341 // In this case the second CaseStmt is the child of the first. Walking
1342 // these recursively can blow out the stack.
1343 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1344 while (true) {
1345 // Set the Parent field to Cursor, then back to its old value once we're
1346 // done.
1347 SetParentRAII SetParent(Parent, StmtParent, Cursor);
1348
1349 if (Stmt *LHS = S->getLHS())
1350 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
1351 return true;
1352 if (Stmt *RHS = S->getRHS())
1353 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
1354 return true;
1355 if (Stmt *SubStmt = S->getSubStmt()) {
1356 if (!isa<CaseStmt>(SubStmt))
1357 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
1358
1359 // Specially handle 'CaseStmt' so that we don't blow out the stack.
1360 CaseStmt *CS = cast<CaseStmt>(SubStmt);
1361 Cursor = MakeCXCursor(CS, StmtParent, TU);
1362 if (RegionOfInterest.isValid()) {
1363 SourceRange Range = CS->getSourceRange();
1364 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1365 return false;
1366 }
1367
1368 switch (Visitor(Cursor, Parent, ClientData)) {
1369 case CXChildVisit_Break: return true;
1370 case CXChildVisit_Continue: return false;
1371 case CXChildVisit_Recurse:
1372 // Perform tail-recursion manually.
1373 S = CS;
1374 continue;
1375 }
1376 }
1377 return false;
1378 }
1379}
1380
Douglas Gregor5e8cf372010-01-21 23:27:09 +00001381bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
1382 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1383 D != DEnd; ++D) {
Douglas Gregor7201f9f2010-01-25 16:12:32 +00001384 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregor5e8cf372010-01-21 23:27:09 +00001385 return true;
1386 }
Ted Kremenekf441baf2010-02-17 00:41:40 +00001387
Douglas Gregor5e8cf372010-01-21 23:27:09 +00001388 return false;
1389}
1390
Douglas Gregore1084fa2010-01-22 01:00:11 +00001391bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1392 if (VarDecl *Var = S->getConditionVariable()) {
1393 if (Visit(MakeCXCursor(Var, TU)))
1394 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001395 }
1396
Douglas Gregor7201f9f2010-01-25 16:12:32 +00001397 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1398 return true;
Douglas Gregore1084fa2010-01-22 01:00:11 +00001399 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1400 return true;
Douglas Gregore1084fa2010-01-22 01:00:11 +00001401 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1402 return true;
1403
1404 return false;
1405}
1406
1407bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1408 if (VarDecl *Var = S->getConditionVariable()) {
1409 if (Visit(MakeCXCursor(Var, TU)))
1410 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001411 }
1412
Douglas Gregor7201f9f2010-01-25 16:12:32 +00001413 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1414 return true;
1415 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1416 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001417
Douglas Gregor7201f9f2010-01-25 16:12:32 +00001418 return false;
1419}
1420
1421bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1422 if (VarDecl *Var = S->getConditionVariable()) {
1423 if (Visit(MakeCXCursor(Var, TU)))
1424 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001425 }
1426
Douglas Gregor7201f9f2010-01-25 16:12:32 +00001427 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1428 return true;
1429 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregore1084fa2010-01-22 01:00:11 +00001430 return true;
1431
Douglas Gregor7201f9f2010-01-25 16:12:32 +00001432 return false;
1433}
1434
1435bool CursorVisitor::VisitForStmt(ForStmt *S) {
1436 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1437 return true;
1438 if (VarDecl *Var = S->getConditionVariable()) {
1439 if (Visit(MakeCXCursor(Var, TU)))
1440 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001441 }
1442
Douglas Gregor7201f9f2010-01-25 16:12:32 +00001443 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1444 return true;
1445 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1446 return true;
Douglas Gregore1084fa2010-01-22 01:00:11 +00001447 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1448 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001449
Douglas Gregore1084fa2010-01-22 01:00:11 +00001450 return false;
1451}
1452
Douglas Gregoraac7c812010-09-02 20:35:02 +00001453bool CursorVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
1454 // Visit nested-name-specifier, if present.
1455 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1456 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1457 return true;
1458
1459 // Visit declaration name.
1460 if (VisitDeclarationNameInfo(E->getNameInfo()))
1461 return true;
1462
1463 // Visit explicitly-specified template arguments.
1464 if (E->hasExplicitTemplateArgs()) {
1465 ExplicitTemplateArgumentList &Args = E->getExplicitTemplateArgs();
1466 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1467 *ArgEnd = Arg + Args.NumTemplateArgs;
1468 Arg != ArgEnd; ++Arg)
1469 if (VisitTemplateArgumentLoc(*Arg))
1470 return true;
1471 }
1472
1473 return false;
1474}
1475
Douglas Gregorb59d21c2010-07-29 00:26:18 +00001476bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1477 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1478 return true;
1479
1480 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1481 return true;
1482
1483 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1484 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1485 return true;
1486
1487 return false;
1488}
1489
Ted Kremenekae9e2212010-08-27 21:34:58 +00001490bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1491 if (D->isDefinition()) {
1492 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1493 E = D->bases_end(); I != E; ++I) {
1494 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1495 return true;
1496 }
1497 }
1498
1499 return VisitTagDecl(D);
1500}
1501
1502
Ted Kremenek33b9a422010-04-11 21:47:37 +00001503bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1504 return Visit(B->getBlockDecl());
1505}
1506
Douglas Gregor882211c2010-04-28 22:16:22 +00001507bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1508 // FIXME: Visit fields as well?
1509 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1510 return true;
1511
1512 return VisitExpr(E);
1513}
1514
Douglas Gregor625a5152010-01-23 00:40:08 +00001515bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1516 if (E->isArgumentType()) {
1517 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1518 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf441baf2010-02-17 00:41:40 +00001519
Douglas Gregor625a5152010-01-23 00:40:08 +00001520 return false;
1521 }
Ted Kremenekf441baf2010-02-17 00:41:40 +00001522
Douglas Gregor625a5152010-01-23 00:40:08 +00001523 return VisitExpr(E);
1524}
1525
Douglas Gregor32e4c862010-09-02 21:07:44 +00001526bool CursorVisitor::VisitMemberExpr(MemberExpr *E) {
1527 // Visit the base expression.
1528 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1529 return true;
1530
1531 // Visit the nested-name-specifier
1532 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1533 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1534 return true;
1535
1536 // Visit the declaration name.
1537 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1538 return true;
1539
1540 // Visit the explicitly-specified template arguments, if any.
1541 if (E->hasExplicitTemplateArgs()) {
1542 for (const TemplateArgumentLoc *Arg = E->getTemplateArgs(),
1543 *ArgEnd = Arg + E->getNumTemplateArgs();
1544 Arg != ArgEnd;
1545 ++Arg) {
1546 if (VisitTemplateArgumentLoc(*Arg))
1547 return true;
1548 }
1549 }
1550
1551 return false;
1552}
1553
Douglas Gregor625a5152010-01-23 00:40:08 +00001554bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1555 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1556 if (Visit(TSInfo->getTypeLoc()))
1557 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001558
Douglas Gregor625a5152010-01-23 00:40:08 +00001559 return VisitCastExpr(E);
1560}
1561
1562bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1563 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1564 if (Visit(TSInfo->getTypeLoc()))
1565 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001566
Douglas Gregor625a5152010-01-23 00:40:08 +00001567 return VisitExpr(E);
1568}
1569
Douglas Gregore68aaca2010-08-10 15:02:34 +00001570bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1571 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1572 Visit(E->getArgTInfo2()->getTypeLoc());
1573}
1574
1575bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1576 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1577 return true;
1578
1579 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1580}
1581
Douglas Gregor46af5012010-09-02 21:20:16 +00001582bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1583 if (E->isTypeOperand()) {
1584 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1585 return Visit(TSInfo->getTypeLoc());
1586
1587 return false;
1588 }
1589
1590 return VisitExpr(E);
1591}
1592
Douglas Gregor2b88c112010-09-08 00:15:04 +00001593bool CursorVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1594 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1595 return Visit(TSInfo->getTypeLoc());
1596
1597 return VisitExpr(E);
1598}
1599
1600bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1601 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1602 return Visit(TSInfo->getTypeLoc());
1603
1604 return false;
1605}
1606
Douglas Gregor0744ef62010-09-07 21:49:58 +00001607bool CursorVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1608 // Visit placement arguments.
1609 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1610 if (Visit(MakeCXCursor(E->getPlacementArg(I), StmtParent, TU)))
1611 return true;
1612
1613 // Visit the allocated type.
1614 if (TypeSourceInfo *TSInfo = E->getAllocatedTypeSourceInfo())
1615 if (Visit(TSInfo->getTypeLoc()))
1616 return true;
1617
1618 // Visit the array size, if any.
1619 if (E->isArray() && Visit(MakeCXCursor(E->getArraySize(), StmtParent, TU)))
1620 return true;
1621
1622 // Visit the initializer or constructor arguments.
1623 for (unsigned I = 0, N = E->getNumConstructorArgs(); I != N; ++I)
1624 if (Visit(MakeCXCursor(E->getConstructorArg(I), StmtParent, TU)))
1625 return true;
1626
1627 return false;
1628}
1629
Douglas Gregor4edb2ff2010-09-02 22:09:03 +00001630bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1631 // Visit base expression.
1632 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1633 return true;
1634
1635 // Visit the nested-name-specifier.
1636 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1637 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1638 return true;
1639
1640 // Visit the scope type that looks disturbingly like the nested-name-specifier
1641 // but isn't.
1642 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1643 if (Visit(TSInfo->getTypeLoc()))
1644 return true;
1645
1646 // Visit the name of the type being destroyed.
1647 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1648 if (Visit(TSInfo->getTypeLoc()))
1649 return true;
1650
1651 return false;
1652}
1653
Douglas Gregorf24eaee2010-09-02 22:29:21 +00001654bool CursorVisitor::VisitOverloadExpr(OverloadExpr *E) {
Douglas Gregor3ca46b42010-09-02 22:19:24 +00001655 // Visit the nested-name-specifier.
1656 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1657 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1658 return true;
1659
1660 // Visit the declaration name.
1661 if (VisitDeclarationNameInfo(E->getNameInfo()))
1662 return true;
1663
Douglas Gregorf24eaee2010-09-02 22:29:21 +00001664 // Visit the explicitly-specified template arguments.
1665 if (const ExplicitTemplateArgumentList *ArgList
1666 = E->getOptionalExplicitTemplateArgs()) {
1667 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1668 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1669 Arg != ArgEnd; ++Arg) {
1670 if (VisitTemplateArgumentLoc(*Arg))
1671 return true;
1672 }
1673 }
1674
Douglas Gregor3ca46b42010-09-02 22:19:24 +00001675 // FIXME: We don't have a way to visit all of the declarations referenced
1676 // here.
1677 return false;
1678}
1679
Douglas Gregor4ae34af2010-09-03 17:24:10 +00001680bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1681 DependentScopeDeclRefExpr *E) {
1682 // Visit the nested-name-specifier.
1683 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1684 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1685 return true;
1686
1687 // Visit the declaration name.
1688 if (VisitDeclarationNameInfo(E->getNameInfo()))
1689 return true;
1690
1691 // Visit the explicitly-specified template arguments.
1692 if (const ExplicitTemplateArgumentList *ArgList
1693 = E->getOptionalExplicitTemplateArgs()) {
1694 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1695 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1696 Arg != ArgEnd; ++Arg) {
1697 if (VisitTemplateArgumentLoc(*Arg))
1698 return true;
1699 }
1700 }
1701
1702 return false;
1703}
1704
Douglas Gregor2b88c112010-09-08 00:15:04 +00001705bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1706 CXXUnresolvedConstructExpr *E) {
1707 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1708 if (Visit(TSInfo->getTypeLoc()))
1709 return true;
1710
1711 return VisitExpr(E);
1712}
1713
Douglas Gregor45838272010-09-03 17:35:34 +00001714bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1715 CXXDependentScopeMemberExpr *E) {
1716 // Visit the base expression, if there is one.
1717 if (!E->isImplicitAccess() &&
1718 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1719 return true;
1720
1721 // Visit the nested-name-specifier.
1722 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1723 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1724 return true;
1725
1726 // Visit the declaration name.
1727 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1728 return true;
1729
1730 // Visit the explicitly-specified template arguments.
1731 if (const ExplicitTemplateArgumentList *ArgList
1732 = E->getOptionalExplicitTemplateArgs()) {
1733 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1734 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1735 Arg != ArgEnd; ++Arg) {
1736 if (VisitTemplateArgumentLoc(*Arg))
1737 return true;
1738 }
1739 }
1740
1741 return false;
1742}
1743
Douglas Gregor901a0fa2010-09-03 18:01:25 +00001744bool CursorVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) {
1745 // Visit the base expression, if there is one.
1746 if (!E->isImplicitAccess() &&
1747 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1748 return true;
1749
1750 return VisitOverloadExpr(E);
1751}
Douglas Gregor45838272010-09-03 17:35:34 +00001752
Douglas Gregorde4827d2010-03-08 16:40:19 +00001753bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor9a129192010-04-21 00:45:42 +00001754 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1755 if (Visit(TSInfo->getTypeLoc()))
1756 return true;
Douglas Gregorde4827d2010-03-08 16:40:19 +00001757
1758 return VisitExpr(E);
1759}
1760
Douglas Gregorabd9e962010-04-20 15:39:42 +00001761bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1762 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1763}
1764
1765
Ted Kremenek6ab9aa022010-02-18 05:46:33 +00001766bool CursorVisitor::VisitAttributes(Decl *D) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001767 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1768 i != e; ++i)
1769 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek6ab9aa022010-02-18 05:46:33 +00001770 return true;
1771
1772 return false;
1773}
1774
Benjamin Kramer61f5d0c2009-10-18 16:11:04 +00001775extern "C" {
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001776CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1777 int displayDiagnostics) {
Daniel Dunbarc91f2ff2010-08-18 18:43:14 +00001778 // We use crash recovery to make some of our APIs more reliable, implicitly
1779 // enable it.
1780 llvm::CrashRecoveryContext::Enable();
1781
Douglas Gregor87752492010-01-22 20:35:53 +00001782 CIndexer *CIdxr = new CIndexer();
Steve Naroff531e2842009-10-20 14:46:24 +00001783 if (excludeDeclarationsFromPCH)
1784 CIdxr->setOnlyLocalDecls();
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001785 if (displayDiagnostics)
1786 CIdxr->setDisplayDiagnostics();
Steve Naroff531e2842009-10-20 14:46:24 +00001787 return CIdxr;
Steve Naroffd5e8e862009-08-27 19:51:58 +00001788}
1789
Daniel Dunbar079203f2009-12-01 03:14:51 +00001790void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor69ff5dc2010-01-29 00:47:48 +00001791 if (CIdx)
1792 delete static_cast<CIndexer *>(CIdx);
Douglas Gregor8ef4c802010-08-09 21:00:09 +00001793 if (getenv("LIBCLANG_TIMING"))
1794 llvm::TimerGroup::printAll(llvm::errs());
Steve Naroff3aa2d732009-09-17 18:33:27 +00001795}
1796
Daniel Dunbar11089662009-12-03 01:54:28 +00001797void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor69ff5dc2010-01-29 00:47:48 +00001798 if (CIdx) {
1799 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1800 CXXIdx->setUseExternalASTGeneration(value);
1801 }
Daniel Dunbar11089662009-12-03 01:54:28 +00001802}
1803
Daniel Dunbar079203f2009-12-01 03:14:51 +00001804CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregor33cdd812010-02-18 18:08:43 +00001805 const char *ast_filename) {
Douglas Gregor69ff5dc2010-01-29 00:47:48 +00001806 if (!CIdx)
1807 return 0;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001808
Douglas Gregor16bef852009-10-16 20:01:17 +00001809 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001810
Douglas Gregor7f95d262010-04-05 23:52:57 +00001811 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Sebastian Redld44cd6a2010-08-18 23:57:06 +00001812 return ASTUnit::LoadFromASTFile(ast_filename, Diags,
Douglas Gregor33cdd812010-02-18 18:08:43 +00001813 CXXIdx->getOnlyLocalDecls(),
1814 0, 0, true);
Steve Naroffd5e8e862009-08-27 19:51:58 +00001815}
1816
Douglas Gregor4a47bca2010-08-09 22:28:58 +00001817unsigned clang_defaultEditingTranslationUnitOptions() {
1818 return CXTranslationUnit_PrecompiledPreamble;
1819}
1820
Daniel Dunbar079203f2009-12-01 03:14:51 +00001821CXTranslationUnit
1822clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1823 const char *source_filename,
1824 int num_command_line_args,
Douglas Gregor57879fa2010-09-01 16:43:19 +00001825 const char * const *command_line_args,
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001826 unsigned num_unsaved_files,
Douglas Gregor33cdd812010-02-18 18:08:43 +00001827 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor99d2cf42010-07-21 18:52:53 +00001828 return clang_parseTranslationUnit(CIdx, source_filename,
1829 command_line_args, num_command_line_args,
1830 unsaved_files, num_unsaved_files,
1831 CXTranslationUnit_DetailedPreprocessingRecord);
1832}
Daniel Dunbar583c3b72010-08-18 18:43:17 +00001833
1834struct ParseTranslationUnitInfo {
1835 CXIndex CIdx;
1836 const char *source_filename;
Douglas Gregor57879fa2010-09-01 16:43:19 +00001837 const char *const *command_line_args;
Daniel Dunbar583c3b72010-08-18 18:43:17 +00001838 int num_command_line_args;
1839 struct CXUnsavedFile *unsaved_files;
1840 unsigned num_unsaved_files;
1841 unsigned options;
1842 CXTranslationUnit result;
1843};
Daniel Dunbar77af1c52010-08-19 23:44:10 +00001844static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar583c3b72010-08-18 18:43:17 +00001845 ParseTranslationUnitInfo *PTUI =
1846 static_cast<ParseTranslationUnitInfo*>(UserData);
1847 CXIndex CIdx = PTUI->CIdx;
1848 const char *source_filename = PTUI->source_filename;
Douglas Gregor57879fa2010-09-01 16:43:19 +00001849 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar583c3b72010-08-18 18:43:17 +00001850 int num_command_line_args = PTUI->num_command_line_args;
1851 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
1852 unsigned num_unsaved_files = PTUI->num_unsaved_files;
1853 unsigned options = PTUI->options;
1854 PTUI->result = 0;
Douglas Gregor99d2cf42010-07-21 18:52:53 +00001855
Douglas Gregor69ff5dc2010-01-29 00:47:48 +00001856 if (!CIdx)
Daniel Dunbar583c3b72010-08-18 18:43:17 +00001857 return;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001858
Steve Naroff531e2842009-10-20 14:46:24 +00001859 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1860
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001861 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001862 bool CompleteTranslationUnit
1863 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001864 bool CacheCodeCompetionResults
1865 = options & CXTranslationUnit_CacheCompletionResults;
1866
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001867 // Configure the diagnostics.
1868 DiagnosticOptions DiagOpts;
Douglas Gregor7f95d262010-04-05 23:52:57 +00001869 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1870 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf441baf2010-02-17 00:41:40 +00001871
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001872 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1873 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner58c79342010-04-05 22:42:27 +00001874 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf441baf2010-02-17 00:41:40 +00001875 const llvm::MemoryBuffer *Buffer
Chris Lattner58c79342010-04-05 22:42:27 +00001876 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001877 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1878 Buffer));
1879 }
Ted Kremenekf441baf2010-02-17 00:41:40 +00001880
Daniel Dunbar11089662009-12-03 01:54:28 +00001881 if (!CXXIdx->getUseExternalASTGeneration()) {
1882 llvm::SmallVector<const char *, 16> Args;
1883
1884 // The 'source_filename' argument is optional. If the caller does not
1885 // specify it then it is assumed that the source file is specified
1886 // in the actual argument list.
1887 if (source_filename)
1888 Args.push_back(source_filename);
Douglas Gregor79edde82010-07-09 18:39:07 +00001889
1890 // Since the Clang C library is primarily used by batch tools dealing with
1891 // (often very broken) source code, where spell-checking can have a
1892 // significant negative impact on performance (particularly when
1893 // precompiled headers are involved), we disable it by default.
1894 // Note that we place this argument early in the list, so that it can be
1895 // overridden by the caller with "-fspell-checking".
Douglas Gregor8ed0c0b2010-07-09 17:35:33 +00001896 Args.push_back("-fno-spell-checking");
Douglas Gregor79edde82010-07-09 18:39:07 +00001897
Daniel Dunbar11089662009-12-03 01:54:28 +00001898 Args.insert(Args.end(), command_line_args,
1899 command_line_args + num_command_line_args);
Douglas Gregor99d2cf42010-07-21 18:52:53 +00001900
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001901 // Do we need the detailed preprocessing record?
Douglas Gregor99d2cf42010-07-21 18:52:53 +00001902 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1903 Args.push_back("-Xclang");
1904 Args.push_back("-detailed-preprocessing-record");
1905 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001906
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001907 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf441baf2010-02-17 00:41:40 +00001908
Ted Kremenek7a5ede22010-01-07 22:49:05 +00001909#ifdef USE_CRASHTRACER
1910 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek991eb3f2010-01-06 03:42:32 +00001911#endif
Ted Kremenekf441baf2010-02-17 00:41:40 +00001912
Daniel Dunbar72fe5b12009-12-05 02:17:18 +00001913 llvm::OwningPtr<ASTUnit> Unit(
1914 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregord03e8232010-04-05 21:10:19 +00001915 Diags,
Daniel Dunbar8d4a2022009-12-13 03:46:13 +00001916 CXXIdx->getClangResourcesPath(),
Daniel Dunbar72fe5b12009-12-05 02:17:18 +00001917 CXXIdx->getOnlyLocalDecls(),
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001918 RemappedFiles.data(),
Douglas Gregor33cdd812010-02-18 18:08:43 +00001919 RemappedFiles.size(),
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001920 /*CaptureDiagnostics=*/true,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001921 PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001922 CompleteTranslationUnit,
1923 CacheCodeCompetionResults));
Ted Kremenekf441baf2010-02-17 00:41:40 +00001924
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001925 if (NumErrors != Diags->getNumErrors()) {
Ted Kremeneka6d3ab32010-03-05 22:43:29 +00001926 // Make sure to check that 'Unit' is non-NULL.
1927 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregora2433152010-04-05 18:10:21 +00001928 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1929 DEnd = Unit->stored_diag_end();
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001930 D != DEnd; ++D) {
1931 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregord770f732010-02-22 23:17:23 +00001932 CXString Msg = clang_formatDiagnostic(&Diag,
1933 clang_defaultDiagnosticDisplayOptions());
1934 fprintf(stderr, "%s\n", clang_getCString(Msg));
1935 clang_disposeString(Msg);
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001936 }
Douglas Gregord770f732010-02-22 23:17:23 +00001937#ifdef LLVM_ON_WIN32
1938 // On Windows, force a flush, since there may be multiple copies of
1939 // stderr and stdout in the file system, all with different buffers
1940 // but writing to the same device.
1941 fflush(stderr);
Ted Kremenek014e70b2010-03-26 01:34:51 +00001942#endif
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001943 }
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001944 }
Daniel Dunbar72fe5b12009-12-05 02:17:18 +00001945
Daniel Dunbar583c3b72010-08-18 18:43:17 +00001946 PTUI->result = Unit.take();
1947 return;
Daniel Dunbar11089662009-12-03 01:54:28 +00001948 }
1949
Ted Kremenek649bf5c2009-10-22 00:03:57 +00001950 // Build up the arguments for invoking 'clang'.
Ted Kremenek51d06bb2009-10-15 23:21:22 +00001951 std::vector<const char *> argv;
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001952
Ted Kremenek649bf5c2009-10-22 00:03:57 +00001953 // First add the complete path to the 'clang' executable.
1954 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer61f5d0c2009-10-18 16:11:04 +00001955 argv.push_back(ClangPath.c_str());
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001956
Ted Kremenek649bf5c2009-10-22 00:03:57 +00001957 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek51d06bb2009-10-15 23:21:22 +00001958 argv.push_back("-emit-ast");
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001959
Ted Kremenek649bf5c2009-10-22 00:03:57 +00001960 // The 'source_filename' argument is optional. If the caller does not
1961 // specify it then it is assumed that the source file is specified
1962 // in the actual argument list.
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001963 if (source_filename)
1964 argv.push_back(source_filename);
Ted Kremenek649bf5c2009-10-22 00:03:57 +00001965
Steve Naroff1cfb96c2009-10-15 20:50:09 +00001966 // Generate a temporary name for the AST file.
Ted Kremenek649bf5c2009-10-22 00:03:57 +00001967 argv.push_back("-o");
Benjamin Kramerf156b9d2010-03-13 21:22:49 +00001968 char astTmpFile[L_tmpnam];
1969 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor79edde82010-07-09 18:39:07 +00001970
1971 // Since the Clang C library is primarily used by batch tools dealing with
1972 // (often very broken) source code, where spell-checking can have a
1973 // significant negative impact on performance (particularly when
1974 // precompiled headers are involved), we disable it by default.
1975 // Note that we place this argument early in the list, so that it can be
1976 // overridden by the caller with "-fspell-checking".
Douglas Gregor8ed0c0b2010-07-09 17:35:33 +00001977 argv.push_back("-fno-spell-checking");
Ted Kremenek649bf5c2009-10-22 00:03:57 +00001978
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001979 // Remap any unsaved files to temporary files.
1980 std::vector<llvm::sys::Path> TemporaryFiles;
1981 std::vector<std::string> RemapArgs;
1982 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
Daniel Dunbar583c3b72010-08-18 18:43:17 +00001983 return;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001984
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001985 // The pointers into the elements of RemapArgs are stable because we
1986 // won't be adding anything to RemapArgs after this point.
1987 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1988 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf441baf2010-02-17 00:41:40 +00001989
Ted Kremenek649bf5c2009-10-22 00:03:57 +00001990 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1991 for (int i = 0; i < num_command_line_args; ++i)
1992 if (const char *arg = command_line_args[i]) {
1993 if (strcmp(arg, "-o") == 0) {
1994 ++i; // Also skip the matching argument.
1995 continue;
1996 }
1997 if (strcmp(arg, "-emit-ast") == 0 ||
1998 strcmp(arg, "-c") == 0 ||
1999 strcmp(arg, "-fsyntax-only") == 0) {
2000 continue;
2001 }
2002
2003 // Keep the argument.
2004 argv.push_back(arg);
Steve Naroff531e2842009-10-20 14:46:24 +00002005 }
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00002006
Douglas Gregorac0605e2010-01-28 06:00:51 +00002007 // Generate a temporary name for the diagnostics file.
Benjamin Kramerf156b9d2010-03-13 21:22:49 +00002008 char tmpFileResults[L_tmpnam];
2009 char *tmpResultsFileName = tmpnam(tmpFileResults);
2010 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregorac0605e2010-01-28 06:00:51 +00002011 TemporaryFiles.push_back(DiagnosticsFile);
2012 argv.push_back("-fdiagnostics-binary");
2013
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00002014 // Do we need the detailed preprocessing record?
2015 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
2016 argv.push_back("-Xclang");
2017 argv.push_back("-detailed-preprocessing-record");
2018 }
2019
Ted Kremenek649bf5c2009-10-22 00:03:57 +00002020 // Add the null terminator.
Ted Kremenek51d06bb2009-10-15 23:21:22 +00002021 argv.push_back(NULL);
2022
Ted Kremenek12e678d2009-10-26 22:14:08 +00002023 // Invoke 'clang'.
2024 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
2025 // on Unix or NUL (Windows).
Ted Kremenek44886fd2009-10-22 03:24:01 +00002026 std::string ErrMsg;
Douglas Gregorac0605e2010-01-28 06:00:51 +00002027 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
2028 NULL };
Ted Kremenek44886fd2009-10-22 03:24:01 +00002029 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregorba965fb2010-01-28 00:56:43 +00002030 /* redirects */ &Redirects[0],
Ted Kremenek44886fd2009-10-22 03:24:01 +00002031 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00002032
Douglas Gregorba965fb2010-01-28 00:56:43 +00002033 if (!ErrMsg.empty()) {
2034 std::string AllArgs;
Ted Kremenek44886fd2009-10-22 03:24:01 +00002035 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregorba965fb2010-01-28 00:56:43 +00002036 I != E; ++I) {
2037 AllArgs += ' ';
Ted Kremenekbf0690c2009-10-26 22:08:39 +00002038 if (*I)
Douglas Gregorba965fb2010-01-28 00:56:43 +00002039 AllArgs += *I;
Ted Kremenekbf0690c2009-10-26 22:08:39 +00002040 }
Ted Kremenekf441baf2010-02-17 00:41:40 +00002041
Daniel Dunbar253dbad2010-02-23 20:23:45 +00002042 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek44886fd2009-10-22 03:24:01 +00002043 }
Benjamin Kramer2836c4c2009-10-18 11:19:36 +00002044
Sebastian Redld44cd6a2010-08-18 23:57:06 +00002045 ASTUnit *ATU = ASTUnit::LoadFromASTFile(astTmpFile, Diags,
Douglas Gregoraa98ed92010-01-23 00:14:00 +00002046 CXXIdx->getOnlyLocalDecls(),
Douglas Gregoraa98ed92010-01-23 00:14:00 +00002047 RemappedFiles.data(),
Douglas Gregor33cdd812010-02-18 18:08:43 +00002048 RemappedFiles.size(),
2049 /*CaptureDiagnostics=*/true);
Douglas Gregor33cdd812010-02-18 18:08:43 +00002050 if (ATU) {
2051 LoadSerializedDiagnostics(DiagnosticsFile,
2052 num_unsaved_files, unsaved_files,
2053 ATU->getFileManager(),
2054 ATU->getSourceManager(),
Douglas Gregora2433152010-04-05 18:10:21 +00002055 ATU->getStoredDiagnostics());
Douglas Gregor1e21cc72010-02-18 23:07:20 +00002056 } else if (CXXIdx->getDisplayDiagnostics()) {
2057 // We failed to load the ASTUnit, but we can still deserialize the
2058 // diagnostics and emit them.
2059 FileManager FileMgr;
Douglas Gregore0fbb832010-03-16 00:06:06 +00002060 Diagnostic Diag;
2061 SourceManager SourceMgr(Diag);
Douglas Gregor1e21cc72010-02-18 23:07:20 +00002062 // FIXME: Faked LangOpts!
2063 LangOptions LangOpts;
2064 llvm::SmallVector<StoredDiagnostic, 4> Diags;
2065 LoadSerializedDiagnostics(DiagnosticsFile,
2066 num_unsaved_files, unsaved_files,
2067 FileMgr, SourceMgr, Diags);
2068 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
2069 DEnd = Diags.end();
2070 D != DEnd; ++D) {
2071 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregord770f732010-02-22 23:17:23 +00002072 CXString Msg = clang_formatDiagnostic(&Diag,
2073 clang_defaultDiagnosticDisplayOptions());
2074 fprintf(stderr, "%s\n", clang_getCString(Msg));
2075 clang_disposeString(Msg);
Douglas Gregor1e21cc72010-02-18 23:07:20 +00002076 }
Douglas Gregord770f732010-02-22 23:17:23 +00002077
2078#ifdef LLVM_ON_WIN32
2079 // On Windows, force a flush, since there may be multiple copies of
2080 // stderr and stdout in the file system, all with different buffers
2081 // but writing to the same device.
2082 fflush(stderr);
2083#endif
Douglas Gregor33cdd812010-02-18 18:08:43 +00002084 }
Douglas Gregorac0605e2010-01-28 06:00:51 +00002085
Douglas Gregor6cb5ba42010-02-18 23:35:40 +00002086 if (ATU) {
2087 // Make the translation unit responsible for destroying all temporary files.
2088 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
2089 ATU->addTemporaryFile(TemporaryFiles[i]);
Sebastian Redld44cd6a2010-08-18 23:57:06 +00002090 ATU->addTemporaryFile(llvm::sys::Path(ATU->getASTFileName()));
Douglas Gregor6cb5ba42010-02-18 23:35:40 +00002091 } else {
2092 // Destroy all of the temporary files now; they can't be referenced any
2093 // longer.
2094 llvm::sys::Path(astTmpFile).eraseFromDisk();
2095 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
2096 TemporaryFiles[i].eraseFromDisk();
2097 }
2098
Daniel Dunbar583c3b72010-08-18 18:43:17 +00002099 PTUI->result = ATU;
2100}
2101CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2102 const char *source_filename,
Douglas Gregor57879fa2010-09-01 16:43:19 +00002103 const char * const *command_line_args,
Daniel Dunbar583c3b72010-08-18 18:43:17 +00002104 int num_command_line_args,
2105 struct CXUnsavedFile *unsaved_files,
2106 unsigned num_unsaved_files,
2107 unsigned options) {
2108 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
2109 num_command_line_args, unsaved_files, num_unsaved_files,
2110 options, 0 };
2111 llvm::CrashRecoveryContext CRC;
2112
2113 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbarf10f9be2010-08-23 22:35:34 +00002114 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2115 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2116 fprintf(stderr, " 'command_line_args' : [");
2117 for (int i = 0; i != num_command_line_args; ++i) {
2118 if (i)
2119 fprintf(stderr, ", ");
2120 fprintf(stderr, "'%s'", command_line_args[i]);
2121 }
2122 fprintf(stderr, "],\n");
2123 fprintf(stderr, " 'unsaved_files' : [");
2124 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2125 if (i)
2126 fprintf(stderr, ", ");
2127 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2128 unsaved_files[i].Length);
2129 }
2130 fprintf(stderr, "],\n");
2131 fprintf(stderr, " 'options' : %d,\n", options);
2132 fprintf(stderr, "}\n");
2133
Daniel Dunbar583c3b72010-08-18 18:43:17 +00002134 return 0;
2135 }
2136
2137 return PTUI.result;
Steve Naroff7781daa2009-10-15 20:04:39 +00002138}
2139
Douglas Gregor6bb92ec2010-08-13 15:35:05 +00002140unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2141 return CXSaveTranslationUnit_None;
2142}
2143
2144int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2145 unsigned options) {
Douglas Gregore9386682010-08-13 05:36:37 +00002146 if (!TU)
2147 return 1;
2148
2149 return static_cast<ASTUnit *>(TU)->Save(FileName);
2150}
Daniel Dunbar583c3b72010-08-18 18:43:17 +00002151
Daniel Dunbar079203f2009-12-01 03:14:51 +00002152void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbar79acdd92010-08-18 23:09:31 +00002153 if (CTUnit) {
2154 // If the translation unit has been marked as unsafe to free, just discard
2155 // it.
2156 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2157 return;
2158
Douglas Gregor69ff5dc2010-01-29 00:47:48 +00002159 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbar79acdd92010-08-18 23:09:31 +00002160 }
Steve Naroff3aa2d732009-09-17 18:33:27 +00002161}
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00002162
Douglas Gregorde051182010-08-11 15:58:42 +00002163unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2164 return CXReparse_None;
2165}
2166
Daniel Dunbar79acdd92010-08-18 23:09:31 +00002167struct ReparseTranslationUnitInfo {
2168 CXTranslationUnit TU;
2169 unsigned num_unsaved_files;
2170 struct CXUnsavedFile *unsaved_files;
2171 unsigned options;
2172 int result;
2173};
Daniel Dunbar77af1c52010-08-19 23:44:10 +00002174static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar79acdd92010-08-18 23:09:31 +00002175 ReparseTranslationUnitInfo *RTUI =
2176 static_cast<ReparseTranslationUnitInfo*>(UserData);
2177 CXTranslationUnit TU = RTUI->TU;
2178 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2179 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2180 unsigned options = RTUI->options;
2181 (void) options;
2182 RTUI->result = 1;
2183
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002184 if (!TU)
Daniel Dunbar79acdd92010-08-18 23:09:31 +00002185 return;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002186
2187 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2188 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2189 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2190 const llvm::MemoryBuffer *Buffer
Douglas Gregor8e984da2010-08-04 16:47:14 +00002191 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002192 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2193 Buffer));
2194 }
2195
Daniel Dunbar79acdd92010-08-18 23:09:31 +00002196 if (!static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(),
2197 RemappedFiles.size()))
2198 RTUI->result = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002199}
Daniel Dunbar79acdd92010-08-18 23:09:31 +00002200int clang_reparseTranslationUnit(CXTranslationUnit TU,
2201 unsigned num_unsaved_files,
2202 struct CXUnsavedFile *unsaved_files,
2203 unsigned options) {
2204 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2205 options, 0 };
2206 llvm::CrashRecoveryContext CRC;
2207
2208 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbar77af1c52010-08-19 23:44:10 +00002209 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbar79acdd92010-08-18 23:09:31 +00002210 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2211 return 1;
2212 }
2213
2214 return RTUI.result;
2215}
2216
Douglas Gregor028d3e42010-08-09 20:45:32 +00002217
Daniel Dunbar079203f2009-12-01 03:14:51 +00002218CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor69ff5dc2010-01-29 00:47:48 +00002219 if (!CTUnit)
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00002220 return createCXString("");
Ted Kremenekf441baf2010-02-17 00:41:40 +00002221
Steve Naroffc0683b92009-09-03 18:19:54 +00002222 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00002223 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroff38c1a7b2009-09-03 15:49:00 +00002224}
Daniel Dunbare58bd8b2009-08-28 16:30:07 +00002225
Douglas Gregord2fc7272010-01-20 00:23:15 +00002226CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorfed36b12010-01-20 23:57:43 +00002227 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregord2fc7272010-01-20 00:23:15 +00002228 return Result;
2229}
2230
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00002231} // end: extern "C"
Steve Naroffd5e8e862009-08-27 19:51:58 +00002232
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00002233//===----------------------------------------------------------------------===//
Douglas Gregor4f46e782010-01-19 21:36:55 +00002234// CXSourceLocation and CXSourceRange Operations.
2235//===----------------------------------------------------------------------===//
2236
Douglas Gregor816fd362010-01-22 21:44:22 +00002237extern "C" {
2238CXSourceLocation clang_getNullLocation() {
Douglas Gregor4f9c3762010-01-28 00:27:43 +00002239 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregor816fd362010-01-22 21:44:22 +00002240 return Result;
2241}
2242
2243unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar83a23542010-01-30 23:58:27 +00002244 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2245 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2246 loc1.int_data == loc2.int_data);
Douglas Gregor816fd362010-01-22 21:44:22 +00002247}
2248
2249CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2250 CXFile file,
2251 unsigned line,
2252 unsigned column) {
Douglas Gregor0925fbc2010-04-30 19:45:53 +00002253 if (!tu || !file)
Douglas Gregor816fd362010-01-22 21:44:22 +00002254 return clang_getNullLocation();
Douglas Gregor0925fbc2010-04-30 19:45:53 +00002255
Douglas Gregor816fd362010-01-22 21:44:22 +00002256 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2257 SourceLocation SLoc
2258 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf441baf2010-02-17 00:41:40 +00002259 static_cast<const FileEntry *>(file),
Douglas Gregor816fd362010-01-22 21:44:22 +00002260 line, column);
Ted Kremenekf441baf2010-02-17 00:41:40 +00002261
Ted Kremenek54140272010-06-28 23:54:17 +00002262 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregor816fd362010-01-22 21:44:22 +00002263}
2264
Douglas Gregor4f9c3762010-01-28 00:27:43 +00002265CXSourceRange clang_getNullRange() {
2266 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2267 return Result;
2268}
Daniel Dunbar02968e52010-02-14 10:02:57 +00002269
Douglas Gregor4f9c3762010-01-28 00:27:43 +00002270CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2271 if (begin.ptr_data[0] != end.ptr_data[0] ||
2272 begin.ptr_data[1] != end.ptr_data[1])
2273 return clang_getNullRange();
Ted Kremenekf441baf2010-02-17 00:41:40 +00002274
2275 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor4f9c3762010-01-28 00:27:43 +00002276 begin.int_data, end.int_data };
Douglas Gregor816fd362010-01-22 21:44:22 +00002277 return Result;
2278}
2279
Douglas Gregor9bd6db52010-01-26 19:19:08 +00002280void clang_getInstantiationLocation(CXSourceLocation location,
2281 CXFile *file,
2282 unsigned *line,
2283 unsigned *column,
2284 unsigned *offset) {
Douglas Gregor4f46e782010-01-19 21:36:55 +00002285 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2286
Daniel Dunbarc4b4d392010-02-14 01:47:36 +00002287 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor9bd6db52010-01-26 19:19:08 +00002288 if (file)
2289 *file = 0;
2290 if (line)
2291 *line = 0;
2292 if (column)
2293 *column = 0;
2294 if (offset)
2295 *offset = 0;
2296 return;
2297 }
2298
Daniel Dunbarc4b4d392010-02-14 01:47:36 +00002299 const SourceManager &SM =
2300 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor4f46e782010-01-19 21:36:55 +00002301 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor4f46e782010-01-19 21:36:55 +00002302
2303 if (file)
2304 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2305 if (line)
2306 *line = SM.getInstantiationLineNumber(InstLoc);
2307 if (column)
2308 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregor47751d62010-01-26 03:07:15 +00002309 if (offset)
Douglas Gregor9bd6db52010-01-26 19:19:08 +00002310 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregor47751d62010-01-26 03:07:15 +00002311}
2312
Douglas Gregor4f46e782010-01-19 21:36:55 +00002313CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf441baf2010-02-17 00:41:40 +00002314 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor4f9c3762010-01-28 00:27:43 +00002315 range.begin_int_data };
Douglas Gregor4f46e782010-01-19 21:36:55 +00002316 return Result;
2317}
2318
2319CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarc4b4d392010-02-14 01:47:36 +00002320 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor4f9c3762010-01-28 00:27:43 +00002321 range.end_int_data };
Douglas Gregor4f46e782010-01-19 21:36:55 +00002322 return Result;
2323}
2324
Douglas Gregor816fd362010-01-22 21:44:22 +00002325} // end: extern "C"
2326
Douglas Gregor4f46e782010-01-19 21:36:55 +00002327//===----------------------------------------------------------------------===//
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00002328// CXFile Operations.
2329//===----------------------------------------------------------------------===//
2330
2331extern "C" {
Ted Kremenekc560b682010-02-17 00:41:20 +00002332CXString clang_getFileName(CXFile SFile) {
Douglas Gregor66a58812010-01-18 22:46:11 +00002333 if (!SFile)
Ted Kremenekc560b682010-02-17 00:41:20 +00002334 return createCXString(NULL);
Ted Kremenekf441baf2010-02-17 00:41:40 +00002335
Steve Naroff6231f182009-10-27 14:35:18 +00002336 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenekc560b682010-02-17 00:41:20 +00002337 return createCXString(FEnt->getName());
Steve Naroff6231f182009-10-27 14:35:18 +00002338}
2339
2340time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor66a58812010-01-18 22:46:11 +00002341 if (!SFile)
2342 return 0;
Ted Kremenekf441baf2010-02-17 00:41:40 +00002343
Steve Naroff6231f182009-10-27 14:35:18 +00002344 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2345 return FEnt->getModificationTime();
Steve Naroff26760892009-09-25 21:45:39 +00002346}
Ted Kremenekf441baf2010-02-17 00:41:40 +00002347
Douglas Gregor816fd362010-01-22 21:44:22 +00002348CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2349 if (!tu)
2350 return 0;
Ted Kremenekf441baf2010-02-17 00:41:40 +00002351
Douglas Gregor816fd362010-01-22 21:44:22 +00002352 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf441baf2010-02-17 00:41:40 +00002353
Douglas Gregor816fd362010-01-22 21:44:22 +00002354 FileManager &FMgr = CXXUnit->getFileManager();
2355 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
2356 return const_cast<FileEntry *>(File);
2357}
Ted Kremenekf441baf2010-02-17 00:41:40 +00002358
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00002359} // end: extern "C"
Steve Naroff26760892009-09-25 21:45:39 +00002360
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00002361//===----------------------------------------------------------------------===//
2362// CXCursor Operations.
2363//===----------------------------------------------------------------------===//
2364
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00002365static Decl *getDeclFromExpr(Stmt *E) {
2366 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2367 return RefExpr->getDecl();
2368 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2369 return ME->getMemberDecl();
2370 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2371 return RE->getDecl();
Ted Kremenekf441baf2010-02-17 00:41:40 +00002372
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00002373 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2374 return getDeclFromExpr(CE->getCallee());
2375 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2376 return getDeclFromExpr(CE->getSubExpr());
2377 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2378 return OME->getMethodDecl();
Ted Kremenekf441baf2010-02-17 00:41:40 +00002379
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00002380 return 0;
2381}
2382
Daniel Dunbara4a2e5d2010-02-02 05:00:22 +00002383static SourceLocation getLocationFromExpr(Expr *E) {
2384 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2385 return /*FIXME:*/Msg->getLeftLoc();
2386 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2387 return DRE->getLocation();
2388 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2389 return Member->getMemberLoc();
2390 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2391 return Ivar->getLocation();
2392 return E->getLocStart();
2393}
2394
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00002395extern "C" {
Ted Kremenekf441baf2010-02-17 00:41:40 +00002396
2397unsigned clang_visitChildren(CXCursor parent,
Douglas Gregor71f3d942010-01-20 20:59:29 +00002398 CXCursorVisitor visitor,
2399 CXClientData client_data) {
Douglas Gregorfed36b12010-01-20 23:57:43 +00002400 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregor71f3d942010-01-20 20:59:29 +00002401
Douglas Gregore9db88f2010-08-03 19:06:41 +00002402 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2403 CXXUnit->getMaxPCHLevel());
Douglas Gregor71f3d942010-01-20 20:59:29 +00002404 return CursorVis.VisitChildren(parent);
2405}
2406
Douglas Gregordd969c82010-01-20 21:45:58 +00002407static CXString getDeclSpelling(Decl *D) {
2408 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2409 if (!ND)
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00002410 return createCXString("");
Ted Kremenekf441baf2010-02-17 00:41:40 +00002411
Douglas Gregordd969c82010-01-20 21:45:58 +00002412 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00002413 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf441baf2010-02-17 00:41:40 +00002414
Douglas Gregordd969c82010-01-20 21:45:58 +00002415 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2416 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2417 // and returns different names. NamedDecl returns the class name and
2418 // ObjCCategoryImplDecl returns the category name.
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00002419 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf441baf2010-02-17 00:41:40 +00002420
Douglas Gregor01a430132010-09-01 03:07:18 +00002421 if (isa<UsingDirectiveDecl>(D))
2422 return createCXString("");
2423
Ted Kremenek08de5c12010-05-19 21:51:10 +00002424 llvm::SmallString<1024> S;
2425 llvm::raw_svector_ostream os(S);
2426 ND->printName(os);
2427
2428 return createCXString(os.str());
Douglas Gregordd969c82010-01-20 21:45:58 +00002429}
Ted Kremenekf441baf2010-02-17 00:41:40 +00002430
Daniel Dunbar079203f2009-12-01 03:14:51 +00002431CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregord2fc7272010-01-20 00:23:15 +00002432 if (clang_isTranslationUnit(C.kind))
Douglas Gregorfed36b12010-01-20 23:57:43 +00002433 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregord2fc7272010-01-20 00:23:15 +00002434
Steve Naroff80a766b2009-09-02 18:26:48 +00002435 if (clang_isReference(C.kind)) {
2436 switch (C.kind) {
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +00002437 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor6c8959b2010-01-16 14:00:32 +00002438 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00002439 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +00002440 }
2441 case CXCursor_ObjCClassRef: {
Douglas Gregor46d66142010-01-16 17:14:40 +00002442 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00002443 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +00002444 }
2445 case CXCursor_ObjCProtocolRef: {
Douglas Gregoref6eb842010-01-16 15:44:18 +00002446 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregor7ecd0202010-01-18 23:41:10 +00002447 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00002448 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +00002449 }
Ted Kremenekae9e2212010-08-27 21:34:58 +00002450 case CXCursor_CXXBaseSpecifier: {
2451 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2452 return createCXString(B->getType().getAsString());
2453 }
Douglas Gregor93f89952010-01-21 16:28:34 +00002454 case CXCursor_TypeRef: {
2455 TypeDecl *Type = getCursorTypeRef(C).first;
2456 assert(Type && "Missing type decl");
2457
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00002458 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2459 getAsString());
Douglas Gregor93f89952010-01-21 16:28:34 +00002460 }
Douglas Gregora23e8f72010-08-31 20:37:03 +00002461 case CXCursor_TemplateRef: {
2462 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregora89314e2010-08-31 23:48:11 +00002463 assert(Template && "Missing template decl");
Douglas Gregora23e8f72010-08-31 20:37:03 +00002464
2465 return createCXString(Template->getNameAsString());
2466 }
Douglas Gregora89314e2010-08-31 23:48:11 +00002467
2468 case CXCursor_NamespaceRef: {
2469 NamedDecl *NS = getCursorNamespaceRef(C).first;
2470 assert(NS && "Missing namespace decl");
2471
2472 return createCXString(NS->getNameAsString());
2473 }
Douglas Gregor93f89952010-01-21 16:28:34 +00002474
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +00002475 default:
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00002476 return createCXString("<not implemented>");
Steve Naroff80a766b2009-09-02 18:26:48 +00002477 }
2478 }
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00002479
2480 if (clang_isExpression(C.kind)) {
2481 Decl *D = getDeclFromExpr(getCursorExpr(C));
2482 if (D)
Douglas Gregordd969c82010-01-20 21:45:58 +00002483 return getDeclSpelling(D);
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00002484 return createCXString("");
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00002485 }
2486
Douglas Gregor065f8d12010-03-18 17:52:52 +00002487 if (C.kind == CXCursor_MacroInstantiation)
2488 return createCXString(getCursorMacroInstantiation(C)->getName()
2489 ->getNameStart());
2490
Douglas Gregor06d6d322010-03-18 18:04:21 +00002491 if (C.kind == CXCursor_MacroDefinition)
2492 return createCXString(getCursorMacroDefinition(C)->getName()
2493 ->getNameStart());
2494
Douglas Gregor5bce76c2010-01-25 16:56:17 +00002495 if (clang_isDeclaration(C.kind))
2496 return getDeclSpelling(getCursorDecl(C));
Ted Kremenek29004672010-02-17 00:41:32 +00002497
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00002498 return createCXString("");
Steve Naroff80a766b2009-09-02 18:26:48 +00002499}
2500
Ted Kremenek29004672010-02-17 00:41:32 +00002501CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff1054e602009-08-31 00:59:03 +00002502 switch (Kind) {
Ted Kremenek29004672010-02-17 00:41:32 +00002503 case CXCursor_FunctionDecl:
2504 return createCXString("FunctionDecl");
2505 case CXCursor_TypedefDecl:
2506 return createCXString("TypedefDecl");
2507 case CXCursor_EnumDecl:
2508 return createCXString("EnumDecl");
2509 case CXCursor_EnumConstantDecl:
2510 return createCXString("EnumConstantDecl");
2511 case CXCursor_StructDecl:
2512 return createCXString("StructDecl");
2513 case CXCursor_UnionDecl:
2514 return createCXString("UnionDecl");
2515 case CXCursor_ClassDecl:
2516 return createCXString("ClassDecl");
2517 case CXCursor_FieldDecl:
2518 return createCXString("FieldDecl");
2519 case CXCursor_VarDecl:
2520 return createCXString("VarDecl");
2521 case CXCursor_ParmDecl:
2522 return createCXString("ParmDecl");
2523 case CXCursor_ObjCInterfaceDecl:
2524 return createCXString("ObjCInterfaceDecl");
2525 case CXCursor_ObjCCategoryDecl:
2526 return createCXString("ObjCCategoryDecl");
2527 case CXCursor_ObjCProtocolDecl:
2528 return createCXString("ObjCProtocolDecl");
2529 case CXCursor_ObjCPropertyDecl:
2530 return createCXString("ObjCPropertyDecl");
2531 case CXCursor_ObjCIvarDecl:
2532 return createCXString("ObjCIvarDecl");
2533 case CXCursor_ObjCInstanceMethodDecl:
2534 return createCXString("ObjCInstanceMethodDecl");
2535 case CXCursor_ObjCClassMethodDecl:
2536 return createCXString("ObjCClassMethodDecl");
2537 case CXCursor_ObjCImplementationDecl:
2538 return createCXString("ObjCImplementationDecl");
2539 case CXCursor_ObjCCategoryImplDecl:
2540 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek225b8e32010-04-13 23:39:06 +00002541 case CXCursor_CXXMethod:
2542 return createCXString("CXXMethod");
Ted Kremenek29004672010-02-17 00:41:32 +00002543 case CXCursor_UnexposedDecl:
2544 return createCXString("UnexposedDecl");
2545 case CXCursor_ObjCSuperClassRef:
2546 return createCXString("ObjCSuperClassRef");
2547 case CXCursor_ObjCProtocolRef:
2548 return createCXString("ObjCProtocolRef");
2549 case CXCursor_ObjCClassRef:
2550 return createCXString("ObjCClassRef");
2551 case CXCursor_TypeRef:
2552 return createCXString("TypeRef");
Douglas Gregora23e8f72010-08-31 20:37:03 +00002553 case CXCursor_TemplateRef:
2554 return createCXString("TemplateRef");
Douglas Gregora89314e2010-08-31 23:48:11 +00002555 case CXCursor_NamespaceRef:
2556 return createCXString("NamespaceRef");
Ted Kremenek29004672010-02-17 00:41:32 +00002557 case CXCursor_UnexposedExpr:
2558 return createCXString("UnexposedExpr");
Ted Kremenek33b9a422010-04-11 21:47:37 +00002559 case CXCursor_BlockExpr:
2560 return createCXString("BlockExpr");
Ted Kremenek29004672010-02-17 00:41:32 +00002561 case CXCursor_DeclRefExpr:
2562 return createCXString("DeclRefExpr");
2563 case CXCursor_MemberRefExpr:
2564 return createCXString("MemberRefExpr");
2565 case CXCursor_CallExpr:
2566 return createCXString("CallExpr");
2567 case CXCursor_ObjCMessageExpr:
2568 return createCXString("ObjCMessageExpr");
2569 case CXCursor_UnexposedStmt:
2570 return createCXString("UnexposedStmt");
2571 case CXCursor_InvalidFile:
2572 return createCXString("InvalidFile");
Ted Kremenek00da3b92010-03-19 20:39:05 +00002573 case CXCursor_InvalidCode:
2574 return createCXString("InvalidCode");
Ted Kremenek29004672010-02-17 00:41:32 +00002575 case CXCursor_NoDeclFound:
2576 return createCXString("NoDeclFound");
2577 case CXCursor_NotImplemented:
2578 return createCXString("NotImplemented");
2579 case CXCursor_TranslationUnit:
2580 return createCXString("TranslationUnit");
Ted Kremenekbff31432010-02-18 03:09:07 +00002581 case CXCursor_UnexposedAttr:
2582 return createCXString("UnexposedAttr");
2583 case CXCursor_IBActionAttr:
2584 return createCXString("attribute(ibaction)");
Douglas Gregor92a524f2010-03-18 00:42:48 +00002585 case CXCursor_IBOutletAttr:
2586 return createCXString("attribute(iboutlet)");
Ted Kremenek26bde772010-05-19 17:38:06 +00002587 case CXCursor_IBOutletCollectionAttr:
2588 return createCXString("attribute(iboutletcollection)");
Douglas Gregor92a524f2010-03-18 00:42:48 +00002589 case CXCursor_PreprocessingDirective:
2590 return createCXString("preprocessing directive");
Douglas Gregor06d6d322010-03-18 18:04:21 +00002591 case CXCursor_MacroDefinition:
2592 return createCXString("macro definition");
Douglas Gregor02ded2a2010-03-18 15:23:44 +00002593 case CXCursor_MacroInstantiation:
2594 return createCXString("macro instantiation");
Ted Kremenekbd67fb22010-05-06 23:38:21 +00002595 case CXCursor_Namespace:
2596 return createCXString("Namespace");
Ted Kremenekb80cba52010-05-07 01:04:29 +00002597 case CXCursor_LinkageSpec:
2598 return createCXString("LinkageSpec");
Ted Kremenekae9e2212010-08-27 21:34:58 +00002599 case CXCursor_CXXBaseSpecifier:
2600 return createCXString("C++ base class specifier");
Douglas Gregor12bca222010-08-31 14:41:23 +00002601 case CXCursor_Constructor:
2602 return createCXString("CXXConstructor");
2603 case CXCursor_Destructor:
2604 return createCXString("CXXDestructor");
2605 case CXCursor_ConversionFunction:
2606 return createCXString("CXXConversion");
Douglas Gregor713602b2010-08-31 17:01:39 +00002607 case CXCursor_TemplateTypeParameter:
2608 return createCXString("TemplateTypeParameter");
2609 case CXCursor_NonTypeTemplateParameter:
2610 return createCXString("NonTypeTemplateParameter");
2611 case CXCursor_TemplateTemplateParameter:
2612 return createCXString("TemplateTemplateParameter");
2613 case CXCursor_FunctionTemplate:
2614 return createCXString("FunctionTemplate");
Douglas Gregor1fbaeb12010-08-31 19:02:00 +00002615 case CXCursor_ClassTemplate:
2616 return createCXString("ClassTemplate");
Douglas Gregorf96abb22010-08-31 19:31:58 +00002617 case CXCursor_ClassTemplatePartialSpecialization:
2618 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregora89314e2010-08-31 23:48:11 +00002619 case CXCursor_NamespaceAlias:
2620 return createCXString("NamespaceAlias");
Douglas Gregor01a430132010-09-01 03:07:18 +00002621 case CXCursor_UsingDirective:
2622 return createCXString("UsingDirective");
Douglas Gregora9aa29c2010-09-01 19:52:22 +00002623 case CXCursor_UsingDeclaration:
2624 return createCXString("UsingDeclaration");
Steve Naroff1054e602009-08-31 00:59:03 +00002625 }
Ted Kremenek29004672010-02-17 00:41:32 +00002626
Ted Kremenek4ba52632010-01-16 02:02:09 +00002627 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremenek29004672010-02-17 00:41:32 +00002628 return createCXString(NULL);
Steve Naroffd5e8e862009-08-27 19:51:58 +00002629}
Steve Naroff1054e602009-08-31 00:59:03 +00002630
Ted Kremenek29004672010-02-17 00:41:32 +00002631enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
2632 CXCursor parent,
Douglas Gregor562c1f92010-01-22 19:49:59 +00002633 CXClientData client_data) {
2634 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
2635 *BestCursor = cursor;
2636 return CXChildVisit_Recurse;
2637}
Ted Kremenek29004672010-02-17 00:41:32 +00002638
Douglas Gregor816fd362010-01-22 21:44:22 +00002639CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
2640 if (!TU)
Ted Kremeneke34cbde2010-01-14 01:51:23 +00002641 return clang_getNullCursor();
Ted Kremenek29004672010-02-17 00:41:32 +00002642
Douglas Gregor816fd362010-01-22 21:44:22 +00002643 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor0c7c2f82010-03-05 21:16:25 +00002644 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2645
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00002646 // Translate the given source location to make it point at the beginning of
2647 // the token under the cursor.
Ted Kremenek97a45372010-01-25 22:34:44 +00002648 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremenek1e589f22010-07-29 00:52:07 +00002649
2650 // Guard against an invalid SourceLocation, or we may assert in one
2651 // of the following calls.
2652 if (SLoc.isInvalid())
2653 return clang_getNullCursor();
2654
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00002655 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
2656 CXXUnit->getASTContext().getLangOptions());
2657
Douglas Gregor562c1f92010-01-22 19:49:59 +00002658 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
2659 if (SLoc.isValid()) {
Douglas Gregor562c1f92010-01-22 19:49:59 +00002660 // FIXME: Would be great to have a "hint" cursor, then walk from that
2661 // hint cursor upward until we find a cursor whose source range encloses
2662 // the region of interest, rather than starting from the translation unit.
2663 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremenek29004672010-02-17 00:41:32 +00002664 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00002665 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor562c1f92010-01-22 19:49:59 +00002666 CursorVis.VisitChildren(Parent);
Steve Naroff54f22fb2009-09-15 20:25:34 +00002667 }
Ted Kremenek29004672010-02-17 00:41:32 +00002668 return Result;
Steve Naroffd5e8e862009-08-27 19:51:58 +00002669}
2670
Ted Kremeneke05d7802009-11-17 19:28:59 +00002671CXCursor clang_getNullCursor(void) {
Douglas Gregor58552bc2010-01-20 23:34:41 +00002672 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremeneke05d7802009-11-17 19:28:59 +00002673}
2674
2675unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregorc58d05b2010-01-15 21:56:13 +00002676 return X == Y;
Ted Kremeneke05d7802009-11-17 19:28:59 +00002677}
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00002678
Daniel Dunbar079203f2009-12-01 03:14:51 +00002679unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff54f22fb2009-09-15 20:25:34 +00002680 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2681}
2682
Daniel Dunbar079203f2009-12-01 03:14:51 +00002683unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff1054e602009-08-31 00:59:03 +00002684 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2685}
Steve Naroff772c1a42009-08-31 14:26:51 +00002686
Daniel Dunbar079203f2009-12-01 03:14:51 +00002687unsigned clang_isReference(enum CXCursorKind K) {
Steve Naroff80a766b2009-09-02 18:26:48 +00002688 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2689}
2690
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00002691unsigned clang_isExpression(enum CXCursorKind K) {
2692 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2693}
2694
2695unsigned clang_isStatement(enum CXCursorKind K) {
2696 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2697}
2698
Douglas Gregord2fc7272010-01-20 00:23:15 +00002699unsigned clang_isTranslationUnit(enum CXCursorKind K) {
2700 return K == CXCursor_TranslationUnit;
2701}
2702
Douglas Gregor92a524f2010-03-18 00:42:48 +00002703unsigned clang_isPreprocessing(enum CXCursorKind K) {
2704 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
2705}
2706
Ted Kremenekff9021b2010-03-08 21:17:29 +00002707unsigned clang_isUnexposed(enum CXCursorKind K) {
2708 switch (K) {
2709 case CXCursor_UnexposedDecl:
2710 case CXCursor_UnexposedExpr:
2711 case CXCursor_UnexposedStmt:
2712 case CXCursor_UnexposedAttr:
2713 return true;
2714 default:
2715 return false;
2716 }
2717}
2718
Daniel Dunbar079203f2009-12-01 03:14:51 +00002719CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroffef9618b2009-09-04 15:44:05 +00002720 return C.kind;
2721}
2722
Douglas Gregor66a58812010-01-18 22:46:11 +00002723CXSourceLocation clang_getCursorLocation(CXCursor C) {
2724 if (clang_isReference(C.kind)) {
Douglas Gregor7ecd0202010-01-18 23:41:10 +00002725 switch (C.kind) {
Ted Kremenekf441baf2010-02-17 00:41:40 +00002726 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor7ecd0202010-01-18 23:41:10 +00002727 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2728 = getCursorObjCSuperClassRef(C);
Ted Kremenek97a45372010-01-25 22:34:44 +00002729 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7ecd0202010-01-18 23:41:10 +00002730 }
2731
Ted Kremenekf441baf2010-02-17 00:41:40 +00002732 case CXCursor_ObjCProtocolRef: {
Douglas Gregor7ecd0202010-01-18 23:41:10 +00002733 std::pair<ObjCProtocolDecl *, SourceLocation> P
2734 = getCursorObjCProtocolRef(C);
Ted Kremenek97a45372010-01-25 22:34:44 +00002735 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7ecd0202010-01-18 23:41:10 +00002736 }
2737
Ted Kremenekf441baf2010-02-17 00:41:40 +00002738 case CXCursor_ObjCClassRef: {
Douglas Gregor7ecd0202010-01-18 23:41:10 +00002739 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2740 = getCursorObjCClassRef(C);
Ted Kremenek97a45372010-01-25 22:34:44 +00002741 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7ecd0202010-01-18 23:41:10 +00002742 }
Douglas Gregor93f89952010-01-21 16:28:34 +00002743
Ted Kremenekf441baf2010-02-17 00:41:40 +00002744 case CXCursor_TypeRef: {
Douglas Gregor93f89952010-01-21 16:28:34 +00002745 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremenek97a45372010-01-25 22:34:44 +00002746 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor93f89952010-01-21 16:28:34 +00002747 }
Douglas Gregora23e8f72010-08-31 20:37:03 +00002748
2749 case CXCursor_TemplateRef: {
2750 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
2751 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2752 }
2753
Douglas Gregora89314e2010-08-31 23:48:11 +00002754 case CXCursor_NamespaceRef: {
2755 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
2756 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2757 }
2758
Ted Kremenekae9e2212010-08-27 21:34:58 +00002759 case CXCursor_CXXBaseSpecifier: {
2760 // FIXME: Figure out what location to return for a CXXBaseSpecifier.
2761 return clang_getNullLocation();
2762 }
Ted Kremenekf441baf2010-02-17 00:41:40 +00002763
Douglas Gregor7ecd0202010-01-18 23:41:10 +00002764 default:
2765 // FIXME: Need a way to enumerate all non-reference cases.
2766 llvm_unreachable("Missed a reference kind");
2767 }
Douglas Gregor66a58812010-01-18 22:46:11 +00002768 }
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00002769
2770 if (clang_isExpression(C.kind))
Ted Kremenekf441baf2010-02-17 00:41:40 +00002771 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00002772 getLocationFromExpr(getCursorExpr(C)));
2773
Douglas Gregor92a524f2010-03-18 00:42:48 +00002774 if (C.kind == CXCursor_PreprocessingDirective) {
2775 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
2776 return cxloc::translateSourceLocation(getCursorContext(C), L);
2777 }
Douglas Gregor02ded2a2010-03-18 15:23:44 +00002778
2779 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor065f8d12010-03-18 17:52:52 +00002780 SourceLocation L
2781 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor02ded2a2010-03-18 15:23:44 +00002782 return cxloc::translateSourceLocation(getCursorContext(C), L);
2783 }
Douglas Gregor06d6d322010-03-18 18:04:21 +00002784
2785 if (C.kind == CXCursor_MacroDefinition) {
2786 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
2787 return cxloc::translateSourceLocation(getCursorContext(C), L);
2788 }
Douglas Gregor92a524f2010-03-18 00:42:48 +00002789
Ted Kremenek8278a322010-05-12 06:16:13 +00002790 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor4f9c3762010-01-28 00:27:43 +00002791 return clang_getNullLocation();
Douglas Gregor66a58812010-01-18 22:46:11 +00002792
Douglas Gregor7ecd0202010-01-18 23:41:10 +00002793 Decl *D = getCursorDecl(C);
Douglas Gregor7ecd0202010-01-18 23:41:10 +00002794 SourceLocation Loc = D->getLocation();
2795 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2796 Loc = Class->getClassLoc();
Douglas Gregor7bf6b8a2010-03-22 15:53:50 +00002797 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor66a58812010-01-18 22:46:11 +00002798}
Douglas Gregor33c34ac2010-01-19 00:34:46 +00002799
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00002800} // end extern "C"
2801
2802static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregor33c34ac2010-01-19 00:34:46 +00002803 if (clang_isReference(C.kind)) {
2804 switch (C.kind) {
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00002805 case CXCursor_ObjCSuperClassRef:
2806 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf441baf2010-02-17 00:41:40 +00002807
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00002808 case CXCursor_ObjCProtocolRef:
2809 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf441baf2010-02-17 00:41:40 +00002810
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00002811 case CXCursor_ObjCClassRef:
2812 return getCursorObjCClassRef(C).second;
Ted Kremenekf441baf2010-02-17 00:41:40 +00002813
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00002814 case CXCursor_TypeRef:
2815 return getCursorTypeRef(C).second;
Douglas Gregora23e8f72010-08-31 20:37:03 +00002816
2817 case CXCursor_TemplateRef:
2818 return getCursorTemplateRef(C).second;
2819
Douglas Gregora89314e2010-08-31 23:48:11 +00002820 case CXCursor_NamespaceRef:
2821 return getCursorNamespaceRef(C).second;
2822
Ted Kremenekae9e2212010-08-27 21:34:58 +00002823 case CXCursor_CXXBaseSpecifier:
2824 // FIXME: Figure out what source range to use for a CXBaseSpecifier.
2825 return SourceRange();
Douglas Gregor93f89952010-01-21 16:28:34 +00002826
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00002827 default:
2828 // FIXME: Need a way to enumerate all non-reference cases.
2829 llvm_unreachable("Missed a reference kind");
Douglas Gregor33c34ac2010-01-19 00:34:46 +00002830 }
2831 }
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00002832
2833 if (clang_isExpression(C.kind))
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00002834 return getCursorExpr(C)->getSourceRange();
Douglas Gregor562c1f92010-01-22 19:49:59 +00002835
2836 if (clang_isStatement(C.kind))
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00002837 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf441baf2010-02-17 00:41:40 +00002838
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00002839 if (C.kind == CXCursor_PreprocessingDirective)
2840 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor02ded2a2010-03-18 15:23:44 +00002841
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00002842 if (C.kind == CXCursor_MacroInstantiation)
2843 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor06d6d322010-03-18 18:04:21 +00002844
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00002845 if (C.kind == CXCursor_MacroDefinition)
2846 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregor92a524f2010-03-18 00:42:48 +00002847
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00002848 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
2849 return getCursorDecl(C)->getSourceRange();
2850
2851 return SourceRange();
2852}
2853
2854extern "C" {
2855
2856CXSourceRange clang_getCursorExtent(CXCursor C) {
2857 SourceRange R = getRawCursorExtent(C);
2858 if (R.isInvalid())
Douglas Gregor4f9c3762010-01-28 00:27:43 +00002859 return clang_getNullRange();
Ted Kremenekf441baf2010-02-17 00:41:40 +00002860
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00002861 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregor33c34ac2010-01-19 00:34:46 +00002862}
Douglas Gregorad27e8b2010-01-19 01:20:04 +00002863
2864CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorfed36b12010-01-20 23:57:43 +00002865 if (clang_isInvalid(C.kind))
2866 return clang_getNullCursor();
Ted Kremenekf441baf2010-02-17 00:41:40 +00002867
Douglas Gregorfed36b12010-01-20 23:57:43 +00002868 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002869 if (clang_isDeclaration(C.kind))
Douglas Gregorad27e8b2010-01-19 01:20:04 +00002870 return C;
Ted Kremenekf441baf2010-02-17 00:41:40 +00002871
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00002872 if (clang_isExpression(C.kind)) {
2873 Decl *D = getDeclFromExpr(getCursorExpr(C));
2874 if (D)
Douglas Gregorfed36b12010-01-20 23:57:43 +00002875 return MakeCXCursor(D, CXXUnit);
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00002876 return clang_getNullCursor();
2877 }
2878
Douglas Gregor78ae2482010-03-18 18:23:03 +00002879 if (C.kind == CXCursor_MacroInstantiation) {
2880 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
2881 return MakeMacroDefinitionCursor(Def, CXXUnit);
2882 }
2883
Douglas Gregorad27e8b2010-01-19 01:20:04 +00002884 if (!clang_isReference(C.kind))
2885 return clang_getNullCursor();
Ted Kremenekf441baf2010-02-17 00:41:40 +00002886
Douglas Gregorad27e8b2010-01-19 01:20:04 +00002887 switch (C.kind) {
2888 case CXCursor_ObjCSuperClassRef:
Douglas Gregorfed36b12010-01-20 23:57:43 +00002889 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf441baf2010-02-17 00:41:40 +00002890
2891 case CXCursor_ObjCProtocolRef: {
Douglas Gregorfed36b12010-01-20 23:57:43 +00002892 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf441baf2010-02-17 00:41:40 +00002893
2894 case CXCursor_ObjCClassRef:
Douglas Gregorfed36b12010-01-20 23:57:43 +00002895 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor93f89952010-01-21 16:28:34 +00002896
Ted Kremenekf441baf2010-02-17 00:41:40 +00002897 case CXCursor_TypeRef:
Douglas Gregor93f89952010-01-21 16:28:34 +00002898 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregora23e8f72010-08-31 20:37:03 +00002899
2900 case CXCursor_TemplateRef:
2901 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
2902
Douglas Gregora89314e2010-08-31 23:48:11 +00002903 case CXCursor_NamespaceRef:
2904 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
2905
Ted Kremenekae9e2212010-08-27 21:34:58 +00002906 case CXCursor_CXXBaseSpecifier: {
2907 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
2908 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
2909 CXXUnit));
2910 }
Ted Kremenekf441baf2010-02-17 00:41:40 +00002911
Douglas Gregorad27e8b2010-01-19 01:20:04 +00002912 default:
2913 // We would prefer to enumerate all non-reference cursor kinds here.
2914 llvm_unreachable("Unhandled reference cursor kind");
2915 break;
2916 }
2917 }
Ted Kremenekf441baf2010-02-17 00:41:40 +00002918
Douglas Gregorad27e8b2010-01-19 01:20:04 +00002919 return clang_getNullCursor();
2920}
2921
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002922CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorfed36b12010-01-20 23:57:43 +00002923 if (clang_isInvalid(C.kind))
2924 return clang_getNullCursor();
Ted Kremenekf441baf2010-02-17 00:41:40 +00002925
Douglas Gregorfed36b12010-01-20 23:57:43 +00002926 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf441baf2010-02-17 00:41:40 +00002927
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002928 bool WasReference = false;
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00002929 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002930 C = clang_getCursorReferenced(C);
2931 WasReference = true;
2932 }
2933
Douglas Gregor78ae2482010-03-18 18:23:03 +00002934 if (C.kind == CXCursor_MacroInstantiation)
2935 return clang_getCursorReferenced(C);
2936
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002937 if (!clang_isDeclaration(C.kind))
2938 return clang_getNullCursor();
2939
2940 Decl *D = getCursorDecl(C);
2941 if (!D)
2942 return clang_getNullCursor();
Ted Kremenekf441baf2010-02-17 00:41:40 +00002943
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002944 switch (D->getKind()) {
2945 // Declaration kinds that don't really separate the notions of
2946 // declaration and definition.
2947 case Decl::Namespace:
2948 case Decl::Typedef:
2949 case Decl::TemplateTypeParm:
2950 case Decl::EnumConstant:
2951 case Decl::Field:
2952 case Decl::ObjCIvar:
2953 case Decl::ObjCAtDefsField:
2954 case Decl::ImplicitParam:
2955 case Decl::ParmVar:
2956 case Decl::NonTypeTemplateParm:
2957 case Decl::TemplateTemplateParm:
2958 case Decl::ObjCCategoryImpl:
2959 case Decl::ObjCImplementation:
Abramo Bagnarad7340582010-06-05 05:09:32 +00002960 case Decl::AccessSpec:
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002961 case Decl::LinkageSpec:
2962 case Decl::ObjCPropertyImpl:
2963 case Decl::FileScopeAsm:
2964 case Decl::StaticAssert:
2965 case Decl::Block:
2966 return C;
2967
2968 // Declaration kinds that don't make any sense here, but are
2969 // nonetheless harmless.
2970 case Decl::TranslationUnit:
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002971 break;
2972
2973 // Declaration kinds for which the definition is not resolvable.
2974 case Decl::UnresolvedUsingTypename:
2975 case Decl::UnresolvedUsingValue:
2976 break;
2977
2978 case Decl::UsingDirective:
Douglas Gregorfed36b12010-01-20 23:57:43 +00002979 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2980 CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002981
2982 case Decl::NamespaceAlias:
Douglas Gregorfed36b12010-01-20 23:57:43 +00002983 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002984
2985 case Decl::Enum:
2986 case Decl::Record:
2987 case Decl::CXXRecord:
2988 case Decl::ClassTemplateSpecialization:
2989 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002990 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorfed36b12010-01-20 23:57:43 +00002991 return MakeCXCursor(Def, CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002992 return clang_getNullCursor();
2993
2994 case Decl::Function:
2995 case Decl::CXXMethod:
2996 case Decl::CXXConstructor:
2997 case Decl::CXXDestructor:
2998 case Decl::CXXConversion: {
2999 const FunctionDecl *Def = 0;
3000 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorfed36b12010-01-20 23:57:43 +00003001 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00003002 return clang_getNullCursor();
3003 }
3004
3005 case Decl::Var: {
Sebastian Redl5ca79842010-02-01 20:16:42 +00003006 // Ask the variable if it has a definition.
3007 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3008 return MakeCXCursor(Def, CXXUnit);
3009 return clang_getNullCursor();
Douglas Gregor6b8232f2010-01-19 19:34:47 +00003010 }
Ted Kremenekf441baf2010-02-17 00:41:40 +00003011
Douglas Gregor6b8232f2010-01-19 19:34:47 +00003012 case Decl::FunctionTemplate: {
3013 const FunctionDecl *Def = 0;
3014 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorfed36b12010-01-20 23:57:43 +00003015 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00003016 return clang_getNullCursor();
3017 }
Ted Kremenekf441baf2010-02-17 00:41:40 +00003018
Douglas Gregor6b8232f2010-01-19 19:34:47 +00003019 case Decl::ClassTemplate: {
3020 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor0a5a2212010-02-11 01:04:33 +00003021 ->getDefinition())
Douglas Gregora23e8f72010-08-31 20:37:03 +00003022 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorfed36b12010-01-20 23:57:43 +00003023 CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00003024 return clang_getNullCursor();
3025 }
3026
3027 case Decl::Using: {
3028 UsingDecl *Using = cast<UsingDecl>(D);
3029 CXCursor Def = clang_getNullCursor();
Ted Kremenekf441baf2010-02-17 00:41:40 +00003030 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
3031 SEnd = Using->shadow_end();
Douglas Gregor6b8232f2010-01-19 19:34:47 +00003032 S != SEnd; ++S) {
3033 if (Def != clang_getNullCursor()) {
3034 // FIXME: We have no way to return multiple results.
3035 return clang_getNullCursor();
3036 }
3037
Ted Kremenekf441baf2010-02-17 00:41:40 +00003038 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorfed36b12010-01-20 23:57:43 +00003039 CXXUnit));
Douglas Gregor6b8232f2010-01-19 19:34:47 +00003040 }
3041
3042 return Def;
3043 }
3044
3045 case Decl::UsingShadow:
3046 return clang_getCursorDefinition(
Ted Kremenekf441baf2010-02-17 00:41:40 +00003047 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorfed36b12010-01-20 23:57:43 +00003048 CXXUnit));
Douglas Gregor6b8232f2010-01-19 19:34:47 +00003049
3050 case Decl::ObjCMethod: {
3051 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3052 if (Method->isThisDeclarationADefinition())
3053 return C;
3054
3055 // Dig out the method definition in the associated
3056 // @implementation, if we have it.
3057 // FIXME: The ASTs should make finding the definition easier.
3058 if (ObjCInterfaceDecl *Class
3059 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3060 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3061 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3062 Method->isInstanceMethod()))
3063 if (Def->isThisDeclarationADefinition())
Douglas Gregorfed36b12010-01-20 23:57:43 +00003064 return MakeCXCursor(Def, CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00003065
3066 return clang_getNullCursor();
3067 }
3068
3069 case Decl::ObjCCategory:
3070 if (ObjCCategoryImplDecl *Impl
3071 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorfed36b12010-01-20 23:57:43 +00003072 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00003073 return clang_getNullCursor();
3074
3075 case Decl::ObjCProtocol:
3076 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3077 return C;
3078 return clang_getNullCursor();
3079
3080 case Decl::ObjCInterface:
3081 // There are two notions of a "definition" for an Objective-C
3082 // class: the interface and its implementation. When we resolved a
3083 // reference to an Objective-C class, produce the @interface as
3084 // the definition; when we were provided with the interface,
3085 // produce the @implementation as the definition.
3086 if (WasReference) {
3087 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3088 return C;
3089 } else if (ObjCImplementationDecl *Impl
3090 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorfed36b12010-01-20 23:57:43 +00003091 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00003092 return clang_getNullCursor();
Ted Kremenekf441baf2010-02-17 00:41:40 +00003093
Douglas Gregor6b8232f2010-01-19 19:34:47 +00003094 case Decl::ObjCProperty:
3095 // FIXME: We don't really know where to find the
3096 // ObjCPropertyImplDecls that implement this property.
3097 return clang_getNullCursor();
3098
3099 case Decl::ObjCCompatibleAlias:
3100 if (ObjCInterfaceDecl *Class
3101 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3102 if (!Class->isForwardDecl())
Douglas Gregorfed36b12010-01-20 23:57:43 +00003103 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf441baf2010-02-17 00:41:40 +00003104
Douglas Gregor6b8232f2010-01-19 19:34:47 +00003105 return clang_getNullCursor();
3106
3107 case Decl::ObjCForwardProtocol: {
3108 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
3109 if (Forward->protocol_size() == 1)
3110 return clang_getCursorDefinition(
Ted Kremenekf441baf2010-02-17 00:41:40 +00003111 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorfed36b12010-01-20 23:57:43 +00003112 CXXUnit));
Douglas Gregor6b8232f2010-01-19 19:34:47 +00003113
3114 // FIXME: Cannot return multiple definitions.
3115 return clang_getNullCursor();
3116 }
3117
3118 case Decl::ObjCClass: {
3119 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
3120 if (Class->size() == 1) {
3121 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
3122 if (!IFace->isForwardDecl())
Douglas Gregorfed36b12010-01-20 23:57:43 +00003123 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00003124 return clang_getNullCursor();
3125 }
3126
3127 // FIXME: Cannot return multiple definitions.
3128 return clang_getNullCursor();
3129 }
3130
3131 case Decl::Friend:
3132 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorfed36b12010-01-20 23:57:43 +00003133 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregor6b8232f2010-01-19 19:34:47 +00003134 return clang_getNullCursor();
3135
3136 case Decl::FriendTemplate:
3137 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorfed36b12010-01-20 23:57:43 +00003138 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregor6b8232f2010-01-19 19:34:47 +00003139 return clang_getNullCursor();
3140 }
3141
3142 return clang_getNullCursor();
3143}
3144
3145unsigned clang_isCursorDefinition(CXCursor C) {
3146 if (!clang_isDeclaration(C.kind))
3147 return 0;
3148
3149 return clang_getCursorDefinition(C) == C;
3150}
3151
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00003152void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff76b8f132009-09-23 17:52:52 +00003153 const char **startBuf,
3154 const char **endBuf,
3155 unsigned *startLine,
3156 unsigned *startColumn,
3157 unsigned *endLine,
Daniel Dunbar079203f2009-12-01 03:14:51 +00003158 unsigned *endColumn) {
Douglas Gregorc58d05b2010-01-15 21:56:13 +00003159 assert(getCursorDecl(C) && "CXCursor has null decl");
3160 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff76b8f132009-09-23 17:52:52 +00003161 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3162 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf441baf2010-02-17 00:41:40 +00003163
Steve Naroff76b8f132009-09-23 17:52:52 +00003164 SourceManager &SM = FD->getASTContext().getSourceManager();
3165 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3166 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3167 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3168 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3169 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3170 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3171}
Ted Kremenekf441baf2010-02-17 00:41:40 +00003172
Douglas Gregor1e21cc72010-02-18 23:07:20 +00003173void clang_enableStackTraces(void) {
3174 llvm::sys::PrintStackTraceOnErrorSignal();
3175}
3176
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00003177} // end: extern "C"
Steve Naroff76b8f132009-09-23 17:52:52 +00003178
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00003179//===----------------------------------------------------------------------===//
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003180// Token-based Operations.
3181//===----------------------------------------------------------------------===//
3182
3183/* CXToken layout:
3184 * int_data[0]: a CXTokenKind
3185 * int_data[1]: starting token location
3186 * int_data[2]: token length
3187 * int_data[3]: reserved
Ted Kremenekf441baf2010-02-17 00:41:40 +00003188 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003189 * otherwise unused.
3190 */
3191extern "C" {
3192
3193CXTokenKind clang_getTokenKind(CXToken CXTok) {
3194 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3195}
3196
3197CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3198 switch (clang_getTokenKind(CXTok)) {
3199 case CXToken_Identifier:
3200 case CXToken_Keyword:
3201 // We know we have an IdentifierInfo*, so use that.
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00003202 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3203 ->getNameStart());
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003204
3205 case CXToken_Literal: {
3206 // We have stashed the starting pointer in the ptr_data field. Use it.
3207 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00003208 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003209 }
Ted Kremenekf441baf2010-02-17 00:41:40 +00003210
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003211 case CXToken_Punctuation:
3212 case CXToken_Comment:
3213 break;
3214 }
Ted Kremenekf441baf2010-02-17 00:41:40 +00003215
3216 // We have to find the starting buffer pointer the hard way, by
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003217 // deconstructing the source location.
3218 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3219 if (!CXXUnit)
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00003220 return createCXString("");
Ted Kremenekf441baf2010-02-17 00:41:40 +00003221
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003222 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3223 std::pair<FileID, unsigned> LocInfo
3224 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregore0fbb832010-03-16 00:06:06 +00003225 bool Invalid = false;
Benjamin Kramereb92dc02010-03-16 14:14:31 +00003226 llvm::StringRef Buffer
Douglas Gregore0fbb832010-03-16 00:06:06 +00003227 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3228 if (Invalid)
Douglas Gregor802b7762010-03-15 22:54:52 +00003229 return createCXString("");
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003230
Benjamin Kramereb92dc02010-03-16 14:14:31 +00003231 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003232}
Ted Kremenekf441baf2010-02-17 00:41:40 +00003233
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003234CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3235 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3236 if (!CXXUnit)
3237 return clang_getNullLocation();
Ted Kremenekf441baf2010-02-17 00:41:40 +00003238
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003239 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3240 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3241}
3242
3243CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3244 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor4f9c3762010-01-28 00:27:43 +00003245 if (!CXXUnit)
3246 return clang_getNullRange();
Ted Kremenekf441baf2010-02-17 00:41:40 +00003247
3248 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003249 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3250}
Ted Kremenekf441baf2010-02-17 00:41:40 +00003251
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003252void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3253 CXToken **Tokens, unsigned *NumTokens) {
3254 if (Tokens)
3255 *Tokens = 0;
3256 if (NumTokens)
3257 *NumTokens = 0;
Ted Kremenekf441baf2010-02-17 00:41:40 +00003258
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003259 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3260 if (!CXXUnit || !Tokens || !NumTokens)
3261 return;
Ted Kremenekf441baf2010-02-17 00:41:40 +00003262
Douglas Gregor0c7c2f82010-03-05 21:16:25 +00003263 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3264
Daniel Dunbar80daf532010-02-14 08:31:57 +00003265 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003266 if (R.isInvalid())
3267 return;
Ted Kremenekf441baf2010-02-17 00:41:40 +00003268
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003269 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3270 std::pair<FileID, unsigned> BeginLocInfo
3271 = SourceMgr.getDecomposedLoc(R.getBegin());
3272 std::pair<FileID, unsigned> EndLocInfo
3273 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf441baf2010-02-17 00:41:40 +00003274
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003275 // Cannot tokenize across files.
3276 if (BeginLocInfo.first != EndLocInfo.first)
3277 return;
Ted Kremenekf441baf2010-02-17 00:41:40 +00003278
3279 // Create a lexer
Douglas Gregore0fbb832010-03-16 00:06:06 +00003280 bool Invalid = false;
Benjamin Kramereb92dc02010-03-16 14:14:31 +00003281 llvm::StringRef Buffer
Douglas Gregore0fbb832010-03-16 00:06:06 +00003282 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor554e0b12010-03-16 20:26:15 +00003283 if (Invalid)
3284 return;
Douglas Gregor802b7762010-03-15 22:54:52 +00003285
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003286 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3287 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramereb92dc02010-03-16 14:14:31 +00003288 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003289 Lex.SetCommentRetentionState(true);
Ted Kremenekf441baf2010-02-17 00:41:40 +00003290
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003291 // Lex tokens until we hit the end of the range.
Benjamin Kramereb92dc02010-03-16 14:14:31 +00003292 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003293 llvm::SmallVector<CXToken, 32> CXTokens;
3294 Token Tok;
3295 do {
3296 // Lex the next token
3297 Lex.LexFromRawLexer(Tok);
3298 if (Tok.is(tok::eof))
3299 break;
Ted Kremenekf441baf2010-02-17 00:41:40 +00003300
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003301 // Initialize the CXToken.
3302 CXToken CXTok;
Ted Kremenekf441baf2010-02-17 00:41:40 +00003303
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003304 // - Common fields
3305 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3306 CXTok.int_data[2] = Tok.getLength();
3307 CXTok.int_data[3] = 0;
Ted Kremenekf441baf2010-02-17 00:41:40 +00003308
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003309 // - Kind-specific fields
3310 if (Tok.isLiteral()) {
3311 CXTok.int_data[0] = CXToken_Literal;
3312 CXTok.ptr_data = (void *)Tok.getLiteralData();
3313 } else if (Tok.is(tok::identifier)) {
Douglas Gregor802b7762010-03-15 22:54:52 +00003314 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003315 std::pair<FileID, unsigned> LocInfo
3316 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregore0fbb832010-03-16 00:06:06 +00003317 bool Invalid = false;
Benjamin Kramereb92dc02010-03-16 14:14:31 +00003318 llvm::StringRef Buf
Douglas Gregore0fbb832010-03-16 00:06:06 +00003319 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3320 if (Invalid)
Douglas Gregor802b7762010-03-15 22:54:52 +00003321 return;
3322
Benjamin Kramereb92dc02010-03-16 14:14:31 +00003323 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003324 IdentifierInfo *II
3325 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenek15cbc3a2010-05-05 00:55:20 +00003326
3327 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
3328 CXTok.int_data[0] = CXToken_Keyword;
3329 }
3330 else {
3331 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3332 CXToken_Identifier
3333 : CXToken_Keyword;
3334 }
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003335 CXTok.ptr_data = II;
3336 } else if (Tok.is(tok::comment)) {
3337 CXTok.int_data[0] = CXToken_Comment;
3338 CXTok.ptr_data = 0;
3339 } else {
3340 CXTok.int_data[0] = CXToken_Punctuation;
3341 CXTok.ptr_data = 0;
3342 }
3343 CXTokens.push_back(CXTok);
3344 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf441baf2010-02-17 00:41:40 +00003345
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003346 if (CXTokens.empty())
3347 return;
Ted Kremenekf441baf2010-02-17 00:41:40 +00003348
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003349 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3350 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3351 *NumTokens = CXTokens.size();
3352}
Douglas Gregor61656112010-01-26 18:31:56 +00003353
Ted Kremenek63ac5992010-05-05 00:55:15 +00003354void clang_disposeTokens(CXTranslationUnit TU,
3355 CXToken *Tokens, unsigned NumTokens) {
3356 free(Tokens);
3357}
3358
3359} // end: extern "C"
3360
3361//===----------------------------------------------------------------------===//
3362// Token annotation APIs.
3363//===----------------------------------------------------------------------===//
3364
Douglas Gregor61656112010-01-26 18:31:56 +00003365typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenek680fe512010-05-05 00:55:23 +00003366static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3367 CXCursor parent,
3368 CXClientData client_data);
Ted Kremenek63ac5992010-05-05 00:55:15 +00003369namespace {
3370class AnnotateTokensWorker {
3371 AnnotateTokensData &Annotated;
Ted Kremenek458c2f12010-05-05 00:55:17 +00003372 CXToken *Tokens;
3373 CXCursor *Cursors;
3374 unsigned NumTokens;
Ted Kremenek680fe512010-05-05 00:55:23 +00003375 unsigned TokIdx;
3376 CursorVisitor AnnotateVis;
3377 SourceManager &SrcMgr;
3378
3379 bool MoreTokens() const { return TokIdx < NumTokens; }
3380 unsigned NextToken() const { return TokIdx; }
3381 void AdvanceToken() { ++TokIdx; }
3382 SourceLocation GetTokenLoc(unsigned tokI) {
3383 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3384 }
3385
Ted Kremenek63ac5992010-05-05 00:55:15 +00003386public:
Ted Kremenek458c2f12010-05-05 00:55:17 +00003387 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenek680fe512010-05-05 00:55:23 +00003388 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3389 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek458c2f12010-05-05 00:55:17 +00003390 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenek680fe512010-05-05 00:55:23 +00003391 NumTokens(numTokens), TokIdx(0),
3392 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3393 Decl::MaxPCHLevel, RegionOfInterest),
3394 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek458c2f12010-05-05 00:55:17 +00003395
Ted Kremenek680fe512010-05-05 00:55:23 +00003396 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek63ac5992010-05-05 00:55:15 +00003397 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenek680fe512010-05-05 00:55:23 +00003398 void AnnotateTokens(CXCursor parent);
Ted Kremenek63ac5992010-05-05 00:55:15 +00003399};
3400}
Douglas Gregor61656112010-01-26 18:31:56 +00003401
Ted Kremenek680fe512010-05-05 00:55:23 +00003402void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3403 // Walk the AST within the region of interest, annotating tokens
3404 // along the way.
3405 VisitChildren(parent);
Ted Kremenek458c2f12010-05-05 00:55:17 +00003406
Ted Kremenek680fe512010-05-05 00:55:23 +00003407 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3408 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3409 if (Pos != Annotated.end())
3410 Cursors[I] = Pos->second;
3411 }
3412
3413 // Finish up annotating any tokens left.
3414 if (!MoreTokens())
3415 return;
3416
3417 const CXCursor &C = clang_getNullCursor();
3418 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3419 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3420 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek458c2f12010-05-05 00:55:17 +00003421 }
3422}
3423
Ted Kremenek63ac5992010-05-05 00:55:15 +00003424enum CXChildVisitResult
3425AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenek680fe512010-05-05 00:55:23 +00003426 CXSourceLocation Loc = clang_getCursorLocation(cursor);
3427 // We can always annotate a preprocessing directive/macro instantiation.
3428 if (clang_isPreprocessing(cursor.kind)) {
3429 Annotated[Loc.int_data] = cursor;
Douglas Gregor61656112010-01-26 18:31:56 +00003430 return CXChildVisit_Recurse;
3431 }
Ted Kremenek680fe512010-05-05 00:55:23 +00003432
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00003433 SourceRange cursorRange = getRawCursorExtent(cursor);
Ted Kremenek5d616142010-05-12 05:29:33 +00003434
Ted Kremenek680fe512010-05-05 00:55:23 +00003435 if (cursorRange.isInvalid())
3436 return CXChildVisit_Continue;
Ted Kremenek5d616142010-05-12 05:29:33 +00003437
Ted Kremenek680fe512010-05-05 00:55:23 +00003438 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
3439
Ted Kremenek5d616142010-05-12 05:29:33 +00003440 // Adjust the annotated range based specific declarations.
3441 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
3442 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek49be9e02010-05-18 21:09:07 +00003443 Decl *D = cxcursor::getCursorDecl(cursor);
3444 // Don't visit synthesized ObjC methods, since they have no syntatic
3445 // representation in the source.
3446 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
3447 if (MD->isSynthesized())
3448 return CXChildVisit_Continue;
3449 }
3450 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremenek5d616142010-05-12 05:29:33 +00003451 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3452 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00003453 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenekd3214132010-05-13 15:38:38 +00003454 if (TLoc.isValid() &&
3455 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremenek5d616142010-05-12 05:29:33 +00003456 cursorRange.setBegin(TLoc);
Ted Kremenek5d616142010-05-12 05:29:33 +00003457 }
3458 }
3459 }
3460
Ted Kremenekf4ade0a2010-08-14 01:14:06 +00003461 // If the location of the cursor occurs within a macro instantiation, record
3462 // the spelling location of the cursor in our annotation map. We can then
3463 // paper over the token labelings during a post-processing step to try and
3464 // get cursor mappings for tokens that are the *arguments* of a macro
3465 // instantiation.
3466 if (L.isMacroID()) {
3467 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
3468 // Only invalidate the old annotation if it isn't part of a preprocessing
3469 // directive. Here we assume that the default construction of CXCursor
3470 // results in CXCursor.kind being an initialized value (i.e., 0). If
3471 // this isn't the case, we can fix by doing lookup + insertion.
3472
3473 CXCursor &oldC = Annotated[rawEncoding];
3474 if (!clang_isPreprocessing(oldC.kind))
3475 oldC = cursor;
3476 }
3477
Ted Kremenek680fe512010-05-05 00:55:23 +00003478 const enum CXCursorKind K = clang_getCursorKind(parent);
3479 const CXCursor updateC =
Ted Kremenek65b2cc02010-08-25 22:16:02 +00003480 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
3481 ? clang_getNullCursor() : parent;
Ted Kremenek680fe512010-05-05 00:55:23 +00003482
3483 while (MoreTokens()) {
3484 const unsigned I = NextToken();
3485 SourceLocation TokLoc = GetTokenLoc(I);
3486 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3487 case RangeBefore:
3488 Cursors[I] = updateC;
3489 AdvanceToken();
3490 continue;
3491 case RangeAfter:
Ted Kremenek680fe512010-05-05 00:55:23 +00003492 case RangeOverlap:
3493 break;
3494 }
3495 break;
3496 }
3497
3498 // Visit children to get their cursor information.
3499 const unsigned BeforeChildren = NextToken();
3500 VisitChildren(cursor);
3501 const unsigned AfterChildren = NextToken();
3502
3503 // Adjust 'Last' to the last token within the extent of the cursor.
3504 while (MoreTokens()) {
3505 const unsigned I = NextToken();
3506 SourceLocation TokLoc = GetTokenLoc(I);
3507 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3508 case RangeBefore:
3509 assert(0 && "Infeasible");
3510 case RangeAfter:
3511 break;
3512 case RangeOverlap:
3513 Cursors[I] = updateC;
3514 AdvanceToken();
3515 continue;
3516 }
3517 break;
3518 }
3519 const unsigned Last = NextToken();
Ted Kremenek63ac5992010-05-05 00:55:15 +00003520
Ted Kremenek680fe512010-05-05 00:55:23 +00003521 // Scan the tokens that are at the beginning of the cursor, but are not
3522 // capture by the child cursors.
3523
3524 // For AST elements within macros, rely on a post-annotate pass to
3525 // to correctly annotate the tokens with cursors. Otherwise we can
3526 // get confusing results of having tokens that map to cursors that really
3527 // are expanded by an instantiation.
3528 if (L.isMacroID())
3529 cursor = clang_getNullCursor();
3530
3531 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
3532 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
3533 break;
3534 Cursors[I] = cursor;
3535 }
3536 // Scan the tokens that are at the end of the cursor, but are not captured
3537 // but the child cursors.
3538 for (unsigned I = AfterChildren; I != Last; ++I)
3539 Cursors[I] = cursor;
3540
3541 TokIdx = Last;
3542 return CXChildVisit_Continue;
Douglas Gregor61656112010-01-26 18:31:56 +00003543}
3544
Ted Kremenek63ac5992010-05-05 00:55:15 +00003545static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3546 CXCursor parent,
3547 CXClientData client_data) {
3548 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
3549}
3550
3551extern "C" {
3552
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003553void clang_annotateTokens(CXTranslationUnit TU,
3554 CXToken *Tokens, unsigned NumTokens,
3555 CXCursor *Cursors) {
Ted Kremenek680fe512010-05-05 00:55:23 +00003556
3557 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor61656112010-01-26 18:31:56 +00003558 return;
Ted Kremenek680fe512010-05-05 00:55:23 +00003559
Douglas Gregor61656112010-01-26 18:31:56 +00003560 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenek680fe512010-05-05 00:55:23 +00003561 if (!CXXUnit) {
3562 // Any token we don't specifically annotate will have a NULL cursor.
3563 const CXCursor &C = clang_getNullCursor();
3564 for (unsigned I = 0; I != NumTokens; ++I)
3565 Cursors[I] = C;
Douglas Gregor61656112010-01-26 18:31:56 +00003566 return;
Ted Kremenek680fe512010-05-05 00:55:23 +00003567 }
3568
Douglas Gregor0c7c2f82010-03-05 21:16:25 +00003569 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek680fe512010-05-05 00:55:23 +00003570
Douglas Gregor5272e802010-03-19 05:22:59 +00003571 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor61656112010-01-26 18:31:56 +00003572 SourceRange RegionOfInterest;
Ted Kremenek680fe512010-05-05 00:55:23 +00003573 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
3574 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00003575 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
3576 clang_getTokenLocation(TU,
3577 Tokens[NumTokens - 1])));
Ted Kremenek680fe512010-05-05 00:55:23 +00003578
Douglas Gregor5272e802010-03-19 05:22:59 +00003579 // A mapping from the source locations found when re-lexing or traversing the
3580 // region of interest to the corresponding cursors.
3581 AnnotateTokensData Annotated;
Ted Kremenek680fe512010-05-05 00:55:23 +00003582
3583 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor5272e802010-03-19 05:22:59 +00003584 // directives.
Douglas Gregor92a524f2010-03-18 00:42:48 +00003585 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3586 std::pair<FileID, unsigned> BeginLocInfo
3587 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
3588 std::pair<FileID, unsigned> EndLocInfo
3589 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenek680fe512010-05-05 00:55:23 +00003590
Douglas Gregor92a524f2010-03-18 00:42:48 +00003591 llvm::StringRef Buffer;
Douglas Gregor5272e802010-03-19 05:22:59 +00003592 bool Invalid = false;
3593 if (BeginLocInfo.first == EndLocInfo.first &&
3594 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
3595 !Invalid) {
Douglas Gregor92a524f2010-03-18 00:42:48 +00003596 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3597 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenek680fe512010-05-05 00:55:23 +00003598 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor065f8d12010-03-18 17:52:52 +00003599 Buffer.end());
Douglas Gregor92a524f2010-03-18 00:42:48 +00003600 Lex.SetCommentRetentionState(true);
Ted Kremenek680fe512010-05-05 00:55:23 +00003601
3602 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor92a524f2010-03-18 00:42:48 +00003603 // entering #includes or expanding macros.
Douglas Gregor02ded2a2010-03-18 15:23:44 +00003604 while (true) {
Douglas Gregor92a524f2010-03-18 00:42:48 +00003605 Token Tok;
3606 Lex.LexFromRawLexer(Tok);
Ted Kremenek680fe512010-05-05 00:55:23 +00003607
Douglas Gregor92a524f2010-03-18 00:42:48 +00003608 reprocess:
3609 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
3610 // We have found a preprocessing directive. Gobble it up so that we
3611 // don't see it while preprocessing these tokens later, but keep track of
3612 // all of the token locations inside this preprocessing directive so that
3613 // we can annotate them appropriately.
3614 //
3615 // FIXME: Some simple tests here could identify macro definitions and
3616 // #undefs, to provide specific cursor kinds for those.
3617 std::vector<SourceLocation> Locations;
3618 do {
3619 Locations.push_back(Tok.getLocation());
Ted Kremenek680fe512010-05-05 00:55:23 +00003620 Lex.LexFromRawLexer(Tok);
Douglas Gregor92a524f2010-03-18 00:42:48 +00003621 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenek680fe512010-05-05 00:55:23 +00003622
Douglas Gregor92a524f2010-03-18 00:42:48 +00003623 using namespace cxcursor;
3624 CXCursor Cursor
Ted Kremenek680fe512010-05-05 00:55:23 +00003625 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
3626 Locations.back()),
Ted Kremenek63ac5992010-05-05 00:55:15 +00003627 CXXUnit);
Douglas Gregor92a524f2010-03-18 00:42:48 +00003628 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
3629 Annotated[Locations[I].getRawEncoding()] = Cursor;
3630 }
Ted Kremenek680fe512010-05-05 00:55:23 +00003631
Douglas Gregor92a524f2010-03-18 00:42:48 +00003632 if (Tok.isAtStartOfLine())
3633 goto reprocess;
Ted Kremenek680fe512010-05-05 00:55:23 +00003634
Douglas Gregor92a524f2010-03-18 00:42:48 +00003635 continue;
3636 }
Ted Kremenek680fe512010-05-05 00:55:23 +00003637
Douglas Gregor02ded2a2010-03-18 15:23:44 +00003638 if (Tok.is(tok::eof))
Douglas Gregor92a524f2010-03-18 00:42:48 +00003639 break;
3640 }
Douglas Gregor065f8d12010-03-18 17:52:52 +00003641 }
Ted Kremenek680fe512010-05-05 00:55:23 +00003642
Douglas Gregor5272e802010-03-19 05:22:59 +00003643 // Annotate all of the source locations in the region of interest that map to
Ted Kremenek680fe512010-05-05 00:55:23 +00003644 // a specific cursor.
3645 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
3646 CXXUnit, RegionOfInterest);
3647 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003648}
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003649} // end: extern "C"
3650
3651//===----------------------------------------------------------------------===//
Ted Kremenekfb4961d2010-03-03 06:36:57 +00003652// Operations for querying linkage of a cursor.
3653//===----------------------------------------------------------------------===//
3654
3655extern "C" {
3656CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor5272e802010-03-19 05:22:59 +00003657 if (!clang_isDeclaration(cursor.kind))
3658 return CXLinkage_Invalid;
3659
Ted Kremenekfb4961d2010-03-03 06:36:57 +00003660 Decl *D = cxcursor::getCursorDecl(cursor);
3661 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
3662 switch (ND->getLinkage()) {
3663 case NoLinkage: return CXLinkage_NoLinkage;
3664 case InternalLinkage: return CXLinkage_Internal;
3665 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
3666 case ExternalLinkage: return CXLinkage_External;
3667 };
3668
3669 return CXLinkage_Invalid;
3670}
3671} // end: extern "C"
3672
3673//===----------------------------------------------------------------------===//
Ted Kremenek4ed29252010-04-12 21:22:16 +00003674// Operations for querying language of a cursor.
3675//===----------------------------------------------------------------------===//
3676
3677static CXLanguageKind getDeclLanguage(const Decl *D) {
3678 switch (D->getKind()) {
3679 default:
3680 break;
3681 case Decl::ImplicitParam:
3682 case Decl::ObjCAtDefsField:
3683 case Decl::ObjCCategory:
3684 case Decl::ObjCCategoryImpl:
3685 case Decl::ObjCClass:
3686 case Decl::ObjCCompatibleAlias:
Ted Kremenek4ed29252010-04-12 21:22:16 +00003687 case Decl::ObjCForwardProtocol:
3688 case Decl::ObjCImplementation:
3689 case Decl::ObjCInterface:
3690 case Decl::ObjCIvar:
3691 case Decl::ObjCMethod:
3692 case Decl::ObjCProperty:
3693 case Decl::ObjCPropertyImpl:
3694 case Decl::ObjCProtocol:
3695 return CXLanguage_ObjC;
3696 case Decl::CXXConstructor:
3697 case Decl::CXXConversion:
3698 case Decl::CXXDestructor:
3699 case Decl::CXXMethod:
3700 case Decl::CXXRecord:
3701 case Decl::ClassTemplate:
3702 case Decl::ClassTemplatePartialSpecialization:
3703 case Decl::ClassTemplateSpecialization:
3704 case Decl::Friend:
3705 case Decl::FriendTemplate:
3706 case Decl::FunctionTemplate:
3707 case Decl::LinkageSpec:
3708 case Decl::Namespace:
3709 case Decl::NamespaceAlias:
3710 case Decl::NonTypeTemplateParm:
3711 case Decl::StaticAssert:
Ted Kremenek4ed29252010-04-12 21:22:16 +00003712 case Decl::TemplateTemplateParm:
3713 case Decl::TemplateTypeParm:
3714 case Decl::UnresolvedUsingTypename:
3715 case Decl::UnresolvedUsingValue:
3716 case Decl::Using:
3717 case Decl::UsingDirective:
3718 case Decl::UsingShadow:
3719 return CXLanguage_CPlusPlus;
3720 }
3721
3722 return CXLanguage_C;
3723}
3724
3725extern "C" {
Douglas Gregorf757a122010-08-23 23:00:57 +00003726
3727enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
3728 if (clang_isDeclaration(cursor.kind))
3729 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
3730 if (D->hasAttr<UnavailableAttr>() ||
3731 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
3732 return CXAvailability_Available;
3733
3734 if (D->hasAttr<DeprecatedAttr>())
3735 return CXAvailability_Deprecated;
3736 }
3737
3738 return CXAvailability_Available;
3739}
3740
Ted Kremenek4ed29252010-04-12 21:22:16 +00003741CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
3742 if (clang_isDeclaration(cursor.kind))
3743 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
3744
3745 return CXLanguage_Invalid;
3746}
3747} // end: extern "C"
3748
Ted Kremenek9cfe9e62010-05-17 20:06:56 +00003749
3750//===----------------------------------------------------------------------===//
3751// C++ AST instrospection.
3752//===----------------------------------------------------------------------===//
3753
3754extern "C" {
3755unsigned clang_CXXMethod_isStatic(CXCursor C) {
3756 if (!clang_isDeclaration(C.kind))
3757 return 0;
Douglas Gregorf11309e2010-08-31 22:12:17 +00003758
3759 CXXMethodDecl *Method = 0;
3760 Decl *D = cxcursor::getCursorDecl(C);
3761 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
3762 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
3763 else
3764 Method = dyn_cast_or_null<CXXMethodDecl>(D);
3765 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek0ed75492010-05-17 20:12:45 +00003766}
Ted Kremeneka10f1282010-05-18 22:32:15 +00003767
Ted Kremenek9cfe9e62010-05-17 20:06:56 +00003768} // end: extern "C"
3769
Ted Kremenek4ed29252010-04-12 21:22:16 +00003770//===----------------------------------------------------------------------===//
Ted Kremeneka5940822010-08-26 01:42:22 +00003771// Attribute introspection.
3772//===----------------------------------------------------------------------===//
3773
3774extern "C" {
3775CXType clang_getIBOutletCollectionType(CXCursor C) {
3776 if (C.kind != CXCursor_IBOutletCollectionAttr)
3777 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
3778
3779 IBOutletCollectionAttr *A =
3780 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
3781
3782 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
3783}
3784} // end: extern "C"
3785
3786//===----------------------------------------------------------------------===//
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00003787// CXString Operations.
3788//===----------------------------------------------------------------------===//
3789
3790extern "C" {
3791const char *clang_getCString(CXString string) {
3792 return string.Spelling;
3793}
3794
3795void clang_disposeString(CXString string) {
3796 if (string.MustFreeString && string.Spelling)
3797 free((void*)string.Spelling);
3798}
Ted Kremenekc0f3f722010-01-22 22:44:15 +00003799
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00003800} // end: extern "C"
Ted Kremenekc0f3f722010-01-22 22:44:15 +00003801
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00003802namespace clang { namespace cxstring {
3803CXString createCXString(const char *String, bool DupString){
3804 CXString Str;
3805 if (DupString) {
3806 Str.Spelling = strdup(String);
3807 Str.MustFreeString = 1;
3808 } else {
3809 Str.Spelling = String;
3810 Str.MustFreeString = 0;
3811 }
3812 return Str;
3813}
3814
3815CXString createCXString(llvm::StringRef String, bool DupString) {
3816 CXString Result;
3817 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
3818 char *Spelling = (char *)malloc(String.size() + 1);
3819 memmove(Spelling, String.data(), String.size());
3820 Spelling[String.size()] = 0;
3821 Result.Spelling = Spelling;
3822 Result.MustFreeString = 1;
3823 } else {
3824 Result.Spelling = String.data();
3825 Result.MustFreeString = 0;
3826 }
3827 return Result;
3828}
3829}}
3830
Ted Kremenekc0f3f722010-01-22 22:44:15 +00003831//===----------------------------------------------------------------------===//
3832// Misc. utility functions.
3833//===----------------------------------------------------------------------===//
Ted Kremenekf441baf2010-02-17 00:41:40 +00003834
Ted Kremenekc0f3f722010-01-22 22:44:15 +00003835extern "C" {
3836
Ted Kremeneka3e65702010-02-12 22:54:40 +00003837CXString clang_getClangVersion() {
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00003838 return createCXString(getClangFullVersion());
Ted Kremenekc0f3f722010-01-22 22:44:15 +00003839}
3840
3841} // end: extern "C"