blob: c93adaff73f210becd4b433b6013d938b4fe489d [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 Kremenek97a45372010-01-25 22:34:44 +000017#include "CXSourceLocation.h"
Douglas Gregor4f9c3762010-01-28 00:27:43 +000018#include "CIndexDiagnostic.h"
Ted Kremenek0ec2cca2010-01-05 19:32:54 +000019
Ted Kremenekc0f3f722010-01-22 22:44:15 +000020#include "clang/Basic/Version.h"
Douglas Gregorba965fb2010-01-28 00:56:43 +000021
Steve Naroffa1c72842009-08-28 15:28:48 +000022#include "clang/AST/DeclVisitor.h"
Steve Naroff66af1ae2009-09-22 19:25:29 +000023#include "clang/AST/StmtVisitor.h"
Douglas Gregor93f89952010-01-21 16:28:34 +000024#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramer064414532010-04-12 19:45:50 +000025#include "clang/Basic/Diagnostic.h"
26#include "clang/Frontend/ASTUnit.h"
27#include "clang/Frontend/CompilerInstance.h"
Douglas Gregorba965fb2010-01-28 00:56:43 +000028#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenek2a43fd52010-01-06 23:43:31 +000029#include "clang/Lex/Lexer.h"
Benjamin Kramer064414532010-04-12 19:45:50 +000030#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor562c1f92010-01-22 19:49:59 +000031#include "clang/Lex/Preprocessor.h"
Douglas Gregord3d923a2009-10-16 21:24:31 +000032#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer2836c4c2009-10-18 11:19:36 +000033#include "llvm/System/Program.h"
Douglas Gregor1e21cc72010-02-18 23:07:20 +000034#include "llvm/System/Signals.h"
Ted Kremenek428c6372009-10-19 21:44:57 +000035
Benjamin Kramerf156b9d2010-03-13 21:22:49 +000036// Needed to define L_TMPNAM on some systems.
37#include <cstdio>
38
Steve Naroffa1c72842009-08-28 15:28:48 +000039using namespace clang;
Ted Kremenek87553c42010-01-15 20:35:54 +000040using namespace clang::cxcursor;
Ted Kremenek5cca6eb2010-02-17 00:41:08 +000041using namespace clang::cxstring;
Steve Naroffa1c72842009-08-28 15:28:48 +000042
Ted Kremenek991eb3f2010-01-06 03:42:32 +000043//===----------------------------------------------------------------------===//
44// Crash Reporting.
45//===----------------------------------------------------------------------===//
46
47#ifdef __APPLE__
Ted Kremenek7a5ede22010-01-07 22:49:05 +000048#define USE_CRASHTRACER
Ted Kremenek991eb3f2010-01-06 03:42:32 +000049#include "clang/Analysis/Support/SaveAndRestore.h"
50// Integrate with crash reporter.
Daniel Dunbar6ac7d7d2010-05-20 23:50:23 +000051static const char *__crashreporter_info__ = 0;
52asm(".desc ___crashreporter_info__, 0x10");
Ted Kremenek896e1642010-02-17 21:12:23 +000053#define NUM_CRASH_STRINGS 32
Ted Kremenek7a5ede22010-01-07 22:49:05 +000054static unsigned crashtracer_counter = 0;
Ted Kremenek32b79312010-01-07 23:13:53 +000055static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek7a5ede22010-01-07 22:49:05 +000056static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
57static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
58
59static unsigned SetCrashTracerInfo(const char *str,
60 llvm::SmallString<1024> &AggStr) {
Ted Kremenekf441baf2010-02-17 00:41:40 +000061
Ted Kremenek32b79312010-01-07 23:13:53 +000062 unsigned slot = 0;
Ted Kremenek7a5ede22010-01-07 22:49:05 +000063 while (crashtracer_strings[slot]) {
64 if (++slot == NUM_CRASH_STRINGS)
65 slot = 0;
66 }
67 crashtracer_strings[slot] = str;
Ted Kremenek32b79312010-01-07 23:13:53 +000068 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek7a5ede22010-01-07 22:49:05 +000069
70 // We need to create an aggregate string because multiple threads
71 // may be in this method at one time. The crash reporter string
72 // will attempt to overapproximate the set of in-flight invocations
73 // of this function. Race conditions can still cause this goal
74 // to not be achieved.
75 {
Ted Kremenekf441baf2010-02-17 00:41:40 +000076 llvm::raw_svector_ostream Out(AggStr);
Ted Kremenek7a5ede22010-01-07 22:49:05 +000077 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
78 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
79 }
80 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
81 return slot;
82}
83
84static void ResetCrashTracerInfo(unsigned slot) {
Ted Kremenek32b79312010-01-07 23:13:53 +000085 unsigned max_slot = 0;
86 unsigned max_value = 0;
Ted Kremenekf441baf2010-02-17 00:41:40 +000087
Ted Kremenek32b79312010-01-07 23:13:53 +000088 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
89
90 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
91 if (agg_crashtracer_strings[i] &&
92 crashtracer_counter_id[i] > max_value) {
93 max_slot = i;
94 max_value = crashtracer_counter_id[i];
Ted Kremenek7a5ede22010-01-07 22:49:05 +000095 }
Ted Kremenek32b79312010-01-07 23:13:53 +000096
97 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek7a5ede22010-01-07 22:49:05 +000098}
99
100namespace {
101class ArgsCrashTracerInfo {
102 llvm::SmallString<1024> CrashString;
103 llvm::SmallString<1024> AggregateString;
104 unsigned crashtracerSlot;
105public:
106 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
107 : crashtracerSlot(0)
108 {
109 {
110 llvm::raw_svector_ostream Out(CrashString);
Ted Kremenekb3908402010-03-05 22:43:25 +0000111 Out << "ClangCIndex [" << getClangFullVersion() << "]"
112 << "[createTranslationUnitFromSourceFile]: clang";
Ted Kremenek7a5ede22010-01-07 22:49:05 +0000113 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
114 E=Args.end(); I!=E; ++I)
115 Out << ' ' << *I;
116 }
117 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
118 AggregateString);
119 }
Ted Kremenekf441baf2010-02-17 00:41:40 +0000120
Ted Kremenek7a5ede22010-01-07 22:49:05 +0000121 ~ArgsCrashTracerInfo() {
122 ResetCrashTracerInfo(crashtracerSlot);
123 }
124};
125}
126#endif
Ted Kremenek991eb3f2010-01-06 03:42:32 +0000127
Douglas Gregor562c1f92010-01-22 19:49:59 +0000128/// \brief The result of comparing two source ranges.
129enum RangeComparisonResult {
130 /// \brief Either the ranges overlap or one of the ranges is invalid.
131 RangeOverlap,
Ted Kremenekf441baf2010-02-17 00:41:40 +0000132
Douglas Gregor562c1f92010-01-22 19:49:59 +0000133 /// \brief The first range ends before the second range starts.
134 RangeBefore,
Ted Kremenekf441baf2010-02-17 00:41:40 +0000135
Douglas Gregor562c1f92010-01-22 19:49:59 +0000136 /// \brief The first range starts after the second range ends.
137 RangeAfter
138};
139
Ted Kremenekf441baf2010-02-17 00:41:40 +0000140/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor562c1f92010-01-22 19:49:59 +0000141/// the translation unit.
Ted Kremenekf441baf2010-02-17 00:41:40 +0000142static RangeComparisonResult RangeCompare(SourceManager &SM,
143 SourceRange R1,
Douglas Gregor562c1f92010-01-22 19:49:59 +0000144 SourceRange R2) {
145 assert(R1.isValid() && "First range is invalid?");
146 assert(R2.isValid() && "Second range is invalid?");
Daniel Dunbar02968e52010-02-14 10:02:57 +0000147 if (R1.getEnd() == R2.getBegin() ||
148 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor562c1f92010-01-22 19:49:59 +0000149 return RangeBefore;
Daniel Dunbar02968e52010-02-14 10:02:57 +0000150 if (R2.getEnd() == R1.getBegin() ||
151 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor562c1f92010-01-22 19:49:59 +0000152 return RangeAfter;
153 return RangeOverlap;
154}
155
Ted Kremenek680fe512010-05-05 00:55:23 +0000156/// \brief Determine if a source location falls within, before, or after a
157/// a given source range.
158static RangeComparisonResult LocationCompare(SourceManager &SM,
159 SourceLocation L, SourceRange R) {
160 assert(R.isValid() && "First range is invalid?");
161 assert(L.isValid() && "Second range is invalid?");
162 if (L == R.getBegin())
163 return RangeOverlap;
164 if (L == R.getEnd())
165 return RangeAfter;
166 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,
181 SourceRange 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();
Douglas Gregoraae92242010-03-19 21:51:54 +0000186 if (!EndLoc.isInvalid() && EndLoc.isFileID()) {
187 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);
Douglas Gregor71f3d942010-01-20 20:59:29 +0000288 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek7dff4162010-02-18 18:47:08 +0000289 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
290 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremeneke2110252010-02-18 22:36:18 +0000291 bool VisitTagDecl(TagDecl *D);
292 bool VisitEnumConstantDecl(EnumConstantDecl *D);
293 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
294 bool VisitFunctionDecl(FunctionDecl *ND);
295 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek7dff4162010-02-18 18:47:08 +0000296 bool VisitVarDecl(VarDecl *);
Ted Kremeneke2110252010-02-18 22:36:18 +0000297 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
298 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
299 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
300 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek49be9e02010-05-18 21:09:07 +0000301 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremeneke2110252010-02-18 22:36:18 +0000302 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
303 bool VisitObjCImplDecl(ObjCImplDecl *D);
304 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
305 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
306 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
307 // etc.
308 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
309 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
310 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremenekb80cba52010-05-07 01:04:29 +0000311 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenekbd67fb22010-05-06 23:38:21 +0000312 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor93f89952010-01-21 16:28:34 +0000313
314 // Type visitors
Douglas Gregord1824312010-01-21 17:29:07 +0000315 // FIXME: QualifiedTypeLoc doesn't provide any location information
316 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor93f89952010-01-21 16:28:34 +0000317 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregord1824312010-01-21 17:29:07 +0000318 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
319 bool VisitTagTypeLoc(TagTypeLoc TL);
320 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
321 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCall8b07ec22010-05-15 11:32:37 +0000322 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregord1824312010-01-21 17:29:07 +0000323 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
324 bool VisitPointerTypeLoc(PointerTypeLoc TL);
325 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
326 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
327 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
328 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
329 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
330 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor6479fc42010-01-21 20:48:56 +0000331 // FIXME: Implement for TemplateSpecializationTypeLoc
332 // FIXME: Implement visitors here when the unimplemented TypeLocs get
333 // implemented
334 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
335 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf441baf2010-02-17 00:41:40 +0000336
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000337 // Statement visitors
338 bool VisitStmt(Stmt *S);
339 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregore1084fa2010-01-22 01:00:11 +0000340 // FIXME: LabelStmt label?
341 bool VisitIfStmt(IfStmt *S);
342 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek12e0f292010-05-13 00:25:00 +0000343 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor7201f9f2010-01-25 16:12:32 +0000344 bool VisitWhileStmt(WhileStmt *S);
345 bool VisitForStmt(ForStmt *S);
Ted Kremenek12e0f292010-05-13 00:25:00 +0000346// bool VisitSwitchCase(SwitchCase *S);
Ted Kremenekf441baf2010-02-17 00:41:40 +0000347
Douglas Gregor625a5152010-01-23 00:40:08 +0000348 // Expression visitors
Ted Kremenek33b9a422010-04-11 21:47:37 +0000349 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor625a5152010-01-23 00:40:08 +0000350 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek33b9a422010-04-11 21:47:37 +0000351 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorde4827d2010-03-08 16:40:19 +0000352 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregorabd9e962010-04-20 15:39:42 +0000353 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor882211c2010-04-28 22:16:22 +0000354 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek33b9a422010-04-11 21:47:37 +0000355 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Steve Naroff1054e602009-08-31 00:59:03 +0000356};
Ted Kremenekf441baf2010-02-17 00:41:40 +0000357
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000358} // end anonymous namespace
Benjamin Kramer61f5d0c2009-10-18 16:11:04 +0000359
Douglas Gregor562c1f92010-01-22 19:49:59 +0000360RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor562c1f92010-01-22 19:49:59 +0000361 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
362}
363
Douglas Gregor71f3d942010-01-20 20:59:29 +0000364/// \brief Visit the given cursor and, if requested by the visitor,
365/// its children.
366///
Douglas Gregor562c1f92010-01-22 19:49:59 +0000367/// \param Cursor the cursor to visit.
368///
369/// \param CheckRegionOfInterest if true, then the caller already checked that
370/// this cursor is within the region of interest.
371///
Douglas Gregor71f3d942010-01-20 20:59:29 +0000372/// \returns true if the visitation should be aborted, false if it
373/// should continue.
Douglas Gregor562c1f92010-01-22 19:49:59 +0000374bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregor71f3d942010-01-20 20:59:29 +0000375 if (clang_isInvalid(Cursor.kind))
376 return false;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000377
Douglas Gregor71f3d942010-01-20 20:59:29 +0000378 if (clang_isDeclaration(Cursor.kind)) {
379 Decl *D = getCursorDecl(Cursor);
380 assert(D && "Invalid declaration cursor");
381 if (D->getPCHLevel() > MaxPCHLevel)
382 return false;
383
384 if (D->isImplicit())
385 return false;
386 }
387
Douglas Gregor562c1f92010-01-22 19:49:59 +0000388 // If we have a range of interest, and this cursor doesn't intersect with it,
389 // we're done.
390 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Daniel Dunbar2f4ba172010-02-14 08:32:05 +0000391 SourceRange Range =
392 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
393 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor562c1f92010-01-22 19:49:59 +0000394 return false;
395 }
Ted Kremenekf441baf2010-02-17 00:41:40 +0000396
Douglas Gregor71f3d942010-01-20 20:59:29 +0000397 switch (Visitor(Cursor, Parent, ClientData)) {
398 case CXChildVisit_Break:
399 return true;
400
401 case CXChildVisit_Continue:
402 return false;
403
404 case CXChildVisit_Recurse:
405 return VisitChildren(Cursor);
406 }
407
Douglas Gregor33f16852010-01-25 16:45:46 +0000408 return false;
Douglas Gregor71f3d942010-01-20 20:59:29 +0000409}
410
Douglas Gregor3dc10b52010-03-20 00:41:21 +0000411std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
412CursorVisitor::getPreprocessedEntities() {
413 PreprocessingRecord &PPRec
414 = *TU->getPreprocessor().getPreprocessingRecord();
415
416 bool OnlyLocalDecls
417 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
418
419 // There is no region of interest; we have to walk everything.
420 if (RegionOfInterest.isInvalid())
421 return std::make_pair(PPRec.begin(OnlyLocalDecls),
422 PPRec.end(OnlyLocalDecls));
423
424 // Find the file in which the region of interest lands.
425 SourceManager &SM = TU->getSourceManager();
426 std::pair<FileID, unsigned> Begin
427 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
428 std::pair<FileID, unsigned> End
429 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
430
431 // The region of interest spans files; we have to walk everything.
432 if (Begin.first != End.first)
433 return std::make_pair(PPRec.begin(OnlyLocalDecls),
434 PPRec.end(OnlyLocalDecls));
435
436 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
437 = TU->getPreprocessedEntitiesByFile();
438 if (ByFileMap.empty()) {
439 // Build the mapping from files to sets of preprocessed entities.
440 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
441 EEnd = PPRec.end(OnlyLocalDecls);
442 E != EEnd; ++E) {
443 std::pair<FileID, unsigned> P
444 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
445 ByFileMap[P.first].push_back(*E);
446 }
447 }
448
449 return std::make_pair(ByFileMap[Begin.first].begin(),
450 ByFileMap[Begin.first].end());
451}
452
Douglas Gregor71f3d942010-01-20 20:59:29 +0000453/// \brief Visit the children of the given cursor.
454///
455/// \returns true if the visitation should be aborted, false if it
456/// should continue.
Ted Kremenekf441baf2010-02-17 00:41:40 +0000457bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000458 if (clang_isReference(Cursor.kind)) {
459 // By definition, references have no children.
460 return false;
461 }
Ted Kremenekf441baf2010-02-17 00:41:40 +0000462
463 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregor71f3d942010-01-20 20:59:29 +0000464 // done.
Ted Kremenek12e0f292010-05-13 00:25:00 +0000465 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf441baf2010-02-17 00:41:40 +0000466
Douglas Gregor71f3d942010-01-20 20:59:29 +0000467 if (clang_isDeclaration(Cursor.kind)) {
468 Decl *D = getCursorDecl(Cursor);
469 assert(D && "Invalid declaration cursor");
Ted Kremenek0e293092010-02-18 18:47:01 +0000470 return VisitAttributes(D) || Visit(D);
Douglas Gregor71f3d942010-01-20 20:59:29 +0000471 }
Ted Kremenekf441baf2010-02-17 00:41:40 +0000472
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000473 if (clang_isStatement(Cursor.kind))
474 return Visit(getCursorStmt(Cursor));
475 if (clang_isExpression(Cursor.kind))
476 return Visit(getCursorExpr(Cursor));
Ted Kremenekf441baf2010-02-17 00:41:40 +0000477
Douglas Gregor71f3d942010-01-20 20:59:29 +0000478 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorfed36b12010-01-20 23:57:43 +0000479 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor562c1f92010-01-22 19:49:59 +0000480 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
481 RegionOfInterest.isInvalid()) {
Douglas Gregorbefc4a12010-01-20 21:13:59 +0000482 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
483 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
484 ie = TLDs.end(); it != ie; ++it) {
Douglas Gregor562c1f92010-01-22 19:49:59 +0000485 if (Visit(MakeCXCursor(*it, CXXUnit), true))
Douglas Gregorbefc4a12010-01-20 21:13:59 +0000486 return true;
487 }
Douglas Gregor5272e802010-03-19 05:22:59 +0000488 } else if (VisitDeclContext(
489 CXXUnit->getASTContext().getTranslationUnitDecl()))
490 return true;
Bob Wilson4f559a32010-03-19 03:57:57 +0000491
Douglas Gregor5272e802010-03-19 05:22:59 +0000492 // Walk the preprocessing record.
Daniel Dunbaraef1db12010-03-20 01:11:56 +0000493 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor5272e802010-03-19 05:22:59 +0000494 // FIXME: Once we have the ability to deserialize a preprocessing record,
495 // do so.
Douglas Gregor3dc10b52010-03-20 00:41:21 +0000496 PreprocessingRecord::iterator E, EEnd;
497 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor5272e802010-03-19 05:22:59 +0000498 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
499 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
500 return true;
Douglas Gregor3dc10b52010-03-20 00:41:21 +0000501
Douglas Gregor5272e802010-03-19 05:22:59 +0000502 continue;
503 }
504
505 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
506 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
507 return true;
508
509 continue;
510 }
511 }
512 }
Douglas Gregorbefc4a12010-01-20 21:13:59 +0000513 return false;
Douglas Gregor71f3d942010-01-20 20:59:29 +0000514 }
Ted Kremenekf441baf2010-02-17 00:41:40 +0000515
Douglas Gregor71f3d942010-01-20 20:59:29 +0000516 // Nothing to visit at the moment.
Douglas Gregor71f3d942010-01-20 20:59:29 +0000517 return false;
518}
519
Ted Kremenek33b9a422010-04-11 21:47:37 +0000520bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
521 for (BlockDecl::param_iterator I=B->param_begin(), E=B->param_end(); I!=E;++I)
522 if (Decl *D = *I)
523 if (Visit(D))
524 return true;
525
526 return Visit(MakeCXCursor(B->getBody(), StmtParent, TU));
527}
528
Douglas Gregor71f3d942010-01-20 20:59:29 +0000529bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenek78668fd2010-01-13 00:22:49 +0000530 for (DeclContext::decl_iterator
Douglas Gregor71f3d942010-01-20 20:59:29 +0000531 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek6ab9aa022010-02-18 05:46:33 +0000532
Ted Kremenek49be9e02010-05-18 21:09:07 +0000533 Decl *D = *I;
534 if (D->getLexicalDeclContext() != DC)
535 continue;
536
537 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbar02968e52010-02-14 10:02:57 +0000538
Douglas Gregor562c1f92010-01-22 19:49:59 +0000539 if (RegionOfInterest.isValid()) {
Daniel Dunbar02968e52010-02-14 10:02:57 +0000540 SourceRange Range =
541 cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor));
542 if (Range.isInvalid())
Douglas Gregor562c1f92010-01-22 19:49:59 +0000543 continue;
Daniel Dunbar02968e52010-02-14 10:02:57 +0000544
545 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor562c1f92010-01-22 19:49:59 +0000546 case RangeBefore:
547 // This declaration comes before the region of interest; skip it.
548 continue;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000549
Douglas Gregor562c1f92010-01-22 19:49:59 +0000550 case RangeAfter:
551 // This declaration comes after the region of interest; we're done.
552 return false;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000553
Douglas Gregor562c1f92010-01-22 19:49:59 +0000554 case RangeOverlap:
555 // This declaration overlaps the region of interest; visit it.
556 break;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000557 }
Douglas Gregor562c1f92010-01-22 19:49:59 +0000558 }
Ted Kremenekf441baf2010-02-17 00:41:40 +0000559
Daniel Dunbar02968e52010-02-14 10:02:57 +0000560 if (Visit(Cursor, true))
Douglas Gregor71f3d942010-01-20 20:59:29 +0000561 return true;
562 }
Ted Kremenekf441baf2010-02-17 00:41:40 +0000563
Douglas Gregor71f3d942010-01-20 20:59:29 +0000564 return false;
Ted Kremenek78668fd2010-01-13 00:22:49 +0000565}
566
Douglas Gregord824f882010-01-22 00:50:27 +0000567bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
568 llvm_unreachable("Translation units are visited directly by Visit()");
569 return false;
570}
571
572bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
573 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
574 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf441baf2010-02-17 00:41:40 +0000575
Douglas Gregord824f882010-01-22 00:50:27 +0000576 return false;
577}
578
579bool CursorVisitor::VisitTagDecl(TagDecl *D) {
580 return VisitDeclContext(D);
581}
582
583bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
584 if (Expr *Init = D->getInitExpr())
585 return Visit(MakeCXCursor(Init, StmtParent, TU));
586 return false;
587}
588
Douglas Gregor93f89952010-01-21 16:28:34 +0000589bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
590 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
591 if (Visit(TSInfo->getTypeLoc()))
592 return true;
593
594 return false;
595}
596
Douglas Gregor71f3d942010-01-20 20:59:29 +0000597bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregord1824312010-01-21 17:29:07 +0000598 if (VisitDeclaratorDecl(ND))
599 return true;
600
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000601 if (ND->isThisDeclarationADefinition() &&
602 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
603 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000604
Douglas Gregor71f3d942010-01-20 20:59:29 +0000605 return false;
606}
Ted Kremenek78668fd2010-01-13 00:22:49 +0000607
Douglas Gregord824f882010-01-22 00:50:27 +0000608bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
609 if (VisitDeclaratorDecl(D))
610 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000611
Douglas Gregord824f882010-01-22 00:50:27 +0000612 if (Expr *BitWidth = D->getBitWidth())
613 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf441baf2010-02-17 00:41:40 +0000614
Douglas Gregord824f882010-01-22 00:50:27 +0000615 return false;
616}
617
618bool CursorVisitor::VisitVarDecl(VarDecl *D) {
619 if (VisitDeclaratorDecl(D))
620 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000621
Douglas Gregord824f882010-01-22 00:50:27 +0000622 if (Expr *Init = D->getInit())
623 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf441baf2010-02-17 00:41:40 +0000624
Douglas Gregord824f882010-01-22 00:50:27 +0000625 return false;
626}
627
628bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor12852d92010-03-08 14:59:44 +0000629 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
630 if (Visit(TSInfo->getTypeLoc()))
631 return true;
632
Ted Kremenekf441baf2010-02-17 00:41:40 +0000633 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregord824f882010-01-22 00:50:27 +0000634 PEnd = ND->param_end();
635 P != PEnd; ++P) {
636 if (Visit(MakeCXCursor(*P, TU)))
637 return true;
638 }
Ted Kremenekf441baf2010-02-17 00:41:40 +0000639
Douglas Gregord824f882010-01-22 00:50:27 +0000640 if (ND->isThisDeclarationADefinition() &&
641 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
642 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000643
Douglas Gregord824f882010-01-22 00:50:27 +0000644 return false;
645}
646
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000647bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
648 return VisitDeclContext(D);
649}
650
Douglas Gregor71f3d942010-01-20 20:59:29 +0000651bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorfed36b12010-01-20 23:57:43 +0000652 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
653 TU)))
Douglas Gregor71f3d942010-01-20 20:59:29 +0000654 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000655
Douglas Gregoref6eb842010-01-16 15:44:18 +0000656 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
657 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
658 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorfed36b12010-01-20 23:57:43 +0000659 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregor71f3d942010-01-20 20:59:29 +0000660 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000661
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000662 return VisitObjCContainerDecl(ND);
Ted Kremenek78668fd2010-01-13 00:22:49 +0000663}
664
Douglas Gregord824f882010-01-22 00:50:27 +0000665bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
666 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
667 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
668 E = PID->protocol_end(); I != E; ++I, ++PL)
669 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
670 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000671
Douglas Gregord824f882010-01-22 00:50:27 +0000672 return VisitObjCContainerDecl(PID);
673}
674
Ted Kremenek49be9e02010-05-18 21:09:07 +0000675bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
676 // FIXME: This implements a workaround with @property declarations also being
677 // installed in the DeclContext for the @interface. Eventually this code
678 // should be removed.
679 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
680 if (!CDecl || !CDecl->IsClassExtension())
681 return false;
682
683 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
684 if (!ID)
685 return false;
686
687 IdentifierInfo *PropertyId = PD->getIdentifier();
688 ObjCPropertyDecl *prevDecl =
689 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
690
691 if (!prevDecl)
692 return false;
693
694 // Visit synthesized methods since they will be skipped when visiting
695 // the @interface.
696 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
697 if (MD->isSynthesized())
698 if (Visit(MakeCXCursor(MD, TU)))
699 return true;
700
701 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
702 if (MD->isSynthesized())
703 if (Visit(MakeCXCursor(MD, TU)))
704 return true;
705
706 return false;
707}
708
Douglas Gregor71f3d942010-01-20 20:59:29 +0000709bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenek78668fd2010-01-13 00:22:49 +0000710 // Issue callbacks for super class.
Douglas Gregor71f3d942010-01-20 20:59:29 +0000711 if (D->getSuperClass() &&
712 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf441baf2010-02-17 00:41:40 +0000713 D->getSuperClassLoc(),
Douglas Gregorfed36b12010-01-20 23:57:43 +0000714 TU)))
Douglas Gregor71f3d942010-01-20 20:59:29 +0000715 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000716
Douglas Gregoref6eb842010-01-16 15:44:18 +0000717 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
718 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
719 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorfed36b12010-01-20 23:57:43 +0000720 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregor71f3d942010-01-20 20:59:29 +0000721 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000722
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000723 return VisitObjCContainerDecl(D);
Ted Kremenek78668fd2010-01-13 00:22:49 +0000724}
725
Douglas Gregord824f882010-01-22 00:50:27 +0000726bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
727 return VisitObjCContainerDecl(D);
Ted Kremenek78668fd2010-01-13 00:22:49 +0000728}
729
Douglas Gregord824f882010-01-22 00:50:27 +0000730bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremeneke184ac52010-03-19 20:39:03 +0000731 // 'ID' could be null when dealing with invalid code.
732 if (ObjCInterfaceDecl *ID = D->getClassInterface())
733 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
734 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000735
Douglas Gregord824f882010-01-22 00:50:27 +0000736 return VisitObjCImplDecl(D);
737}
738
739bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
740#if 0
741 // Issue callbacks for super class.
742 // FIXME: No source location information!
743 if (D->getSuperClass() &&
744 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf441baf2010-02-17 00:41:40 +0000745 D->getSuperClassLoc(),
Douglas Gregord824f882010-01-22 00:50:27 +0000746 TU)))
747 return true;
748#endif
Ted Kremenekf441baf2010-02-17 00:41:40 +0000749
Douglas Gregord824f882010-01-22 00:50:27 +0000750 return VisitObjCImplDecl(D);
751}
752
753bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
754 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
755 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
756 E = D->protocol_end();
757 I != E; ++I, ++PL)
Douglas Gregorfed36b12010-01-20 23:57:43 +0000758 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregor71f3d942010-01-20 20:59:29 +0000759 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000760
761 return false;
Ted Kremenek78668fd2010-01-13 00:22:49 +0000762}
763
Douglas Gregord824f882010-01-22 00:50:27 +0000764bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
765 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
766 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
767 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000768
Douglas Gregord824f882010-01-22 00:50:27 +0000769 return false;
Ted Kremenek78668fd2010-01-13 00:22:49 +0000770}
771
Ted Kremenekbd67fb22010-05-06 23:38:21 +0000772bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
773 return VisitDeclContext(D);
774}
775
Ted Kremenekb80cba52010-05-07 01:04:29 +0000776bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
777 return VisitDeclContext(D);
778}
779
Douglas Gregord1824312010-01-21 17:29:07 +0000780bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
781 ASTContext &Context = TU->getASTContext();
782
783 // Some builtin types (such as Objective-C's "id", "sel", and
784 // "Class") have associated declarations. Create cursors for those.
785 QualType VisitType;
786 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenekaaaf2bf2010-02-18 22:32:43 +0000787 case BuiltinType::Void:
Douglas Gregord1824312010-01-21 17:29:07 +0000788 case BuiltinType::Bool:
Ted Kremenekaaaf2bf2010-02-18 22:32:43 +0000789 case BuiltinType::Char_U:
790 case BuiltinType::UChar:
Douglas Gregord1824312010-01-21 17:29:07 +0000791 case BuiltinType::Char16:
792 case BuiltinType::Char32:
Ted Kremenekaaaf2bf2010-02-18 22:32:43 +0000793 case BuiltinType::UShort:
Douglas Gregord1824312010-01-21 17:29:07 +0000794 case BuiltinType::UInt:
795 case BuiltinType::ULong:
796 case BuiltinType::ULongLong:
Ted Kremenekaaaf2bf2010-02-18 22:32:43 +0000797 case BuiltinType::UInt128:
798 case BuiltinType::Char_S:
799 case BuiltinType::SChar:
Douglas Gregord1824312010-01-21 17:29:07 +0000800 case BuiltinType::WChar:
Ted Kremenekaaaf2bf2010-02-18 22:32:43 +0000801 case BuiltinType::Short:
802 case BuiltinType::Int:
803 case BuiltinType::Long:
804 case BuiltinType::LongLong:
805 case BuiltinType::Int128:
806 case BuiltinType::Float:
807 case BuiltinType::Double:
808 case BuiltinType::LongDouble:
809 case BuiltinType::NullPtr:
810 case BuiltinType::Overload:
811 case BuiltinType::Dependent:
Douglas Gregord1824312010-01-21 17:29:07 +0000812 break;
Ted Kremenekaaaf2bf2010-02-18 22:32:43 +0000813
814 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregord1824312010-01-21 17:29:07 +0000815 break;
Ted Kremenekaaaf2bf2010-02-18 22:32:43 +0000816
Ted Kremenekfcb3db72010-02-18 18:52:18 +0000817 case BuiltinType::ObjCId:
818 VisitType = Context.getObjCIdType();
819 break;
Ted Kremenekaaaf2bf2010-02-18 22:32:43 +0000820
821 case BuiltinType::ObjCClass:
822 VisitType = Context.getObjCClassType();
823 break;
824
Douglas Gregord1824312010-01-21 17:29:07 +0000825 case BuiltinType::ObjCSel:
826 VisitType = Context.getObjCSelType();
827 break;
828 }
829
830 if (!VisitType.isNull()) {
831 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf441baf2010-02-17 00:41:40 +0000832 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregord1824312010-01-21 17:29:07 +0000833 TU));
834 }
835
836 return false;
837}
838
Douglas Gregor93f89952010-01-21 16:28:34 +0000839bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
840 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
841}
842
Douglas Gregord1824312010-01-21 17:29:07 +0000843bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
844 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
845}
846
847bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
848 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
849}
850
851bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
852 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
853 return true;
854
John McCall8b07ec22010-05-15 11:32:37 +0000855 return false;
856}
857
858bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
859 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
860 return true;
861
Douglas Gregord1824312010-01-21 17:29:07 +0000862 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
863 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
864 TU)))
865 return true;
866 }
867
868 return false;
869}
870
871bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCall8b07ec22010-05-15 11:32:37 +0000872 return Visit(TL.getPointeeLoc());
Douglas Gregord1824312010-01-21 17:29:07 +0000873}
874
875bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
876 return Visit(TL.getPointeeLoc());
877}
878
879bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
880 return Visit(TL.getPointeeLoc());
881}
882
883bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
884 return Visit(TL.getPointeeLoc());
885}
886
887bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf441baf2010-02-17 00:41:40 +0000888 return Visit(TL.getPointeeLoc());
Douglas Gregord1824312010-01-21 17:29:07 +0000889}
890
891bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf441baf2010-02-17 00:41:40 +0000892 return Visit(TL.getPointeeLoc());
Douglas Gregord1824312010-01-21 17:29:07 +0000893}
894
895bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
896 if (Visit(TL.getResultLoc()))
897 return true;
898
Douglas Gregord1824312010-01-21 17:29:07 +0000899 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek6ca136a2010-04-07 00:27:13 +0000900 if (Decl *D = TL.getArg(I))
901 if (Visit(MakeCXCursor(D, TU)))
902 return true;
Douglas Gregord1824312010-01-21 17:29:07 +0000903
904 return false;
905}
906
907bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
908 if (Visit(TL.getElementLoc()))
909 return true;
910
911 if (Expr *Size = TL.getSizeExpr())
912 return Visit(MakeCXCursor(Size, StmtParent, TU));
913
914 return false;
915}
916
Douglas Gregor6479fc42010-01-21 20:48:56 +0000917bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
918 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
919}
920
921bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
922 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
923 return Visit(TSInfo->getTypeLoc());
924
925 return false;
926}
927
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000928bool CursorVisitor::VisitStmt(Stmt *S) {
929 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
930 Child != ChildEnd; ++Child) {
Ted Kremenek12e0f292010-05-13 00:25:00 +0000931 if (Stmt *C = *Child)
932 if (Visit(MakeCXCursor(C, StmtParent, TU)))
933 return true;
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000934 }
Ted Kremenekf441baf2010-02-17 00:41:40 +0000935
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000936 return false;
937}
938
Ted Kremenek12e0f292010-05-13 00:25:00 +0000939bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
940 // Specially handle CaseStmts because they can be nested, e.g.:
941 //
942 // case 1:
943 // case 2:
944 //
945 // In this case the second CaseStmt is the child of the first. Walking
946 // these recursively can blow out the stack.
947 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
948 while (true) {
949 // Set the Parent field to Cursor, then back to its old value once we're
950 // done.
951 SetParentRAII SetParent(Parent, StmtParent, Cursor);
952
953 if (Stmt *LHS = S->getLHS())
954 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
955 return true;
956 if (Stmt *RHS = S->getRHS())
957 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
958 return true;
959 if (Stmt *SubStmt = S->getSubStmt()) {
960 if (!isa<CaseStmt>(SubStmt))
961 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
962
963 // Specially handle 'CaseStmt' so that we don't blow out the stack.
964 CaseStmt *CS = cast<CaseStmt>(SubStmt);
965 Cursor = MakeCXCursor(CS, StmtParent, TU);
966 if (RegionOfInterest.isValid()) {
967 SourceRange Range = CS->getSourceRange();
968 if (Range.isInvalid() || CompareRegionOfInterest(Range))
969 return false;
970 }
971
972 switch (Visitor(Cursor, Parent, ClientData)) {
973 case CXChildVisit_Break: return true;
974 case CXChildVisit_Continue: return false;
975 case CXChildVisit_Recurse:
976 // Perform tail-recursion manually.
977 S = CS;
978 continue;
979 }
980 }
981 return false;
982 }
983}
984
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000985bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
986 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
987 D != DEnd; ++D) {
Douglas Gregor7201f9f2010-01-25 16:12:32 +0000988 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000989 return true;
990 }
Ted Kremenekf441baf2010-02-17 00:41:40 +0000991
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000992 return false;
993}
994
Douglas Gregore1084fa2010-01-22 01:00:11 +0000995bool CursorVisitor::VisitIfStmt(IfStmt *S) {
996 if (VarDecl *Var = S->getConditionVariable()) {
997 if (Visit(MakeCXCursor(Var, TU)))
998 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000999 }
1000
Douglas Gregor7201f9f2010-01-25 16:12:32 +00001001 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1002 return true;
Douglas Gregore1084fa2010-01-22 01:00:11 +00001003 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1004 return true;
Douglas Gregore1084fa2010-01-22 01:00:11 +00001005 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1006 return true;
1007
1008 return false;
1009}
1010
1011bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1012 if (VarDecl *Var = S->getConditionVariable()) {
1013 if (Visit(MakeCXCursor(Var, TU)))
1014 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001015 }
1016
Douglas Gregor7201f9f2010-01-25 16:12:32 +00001017 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1018 return true;
1019 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1020 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001021
Douglas Gregor7201f9f2010-01-25 16:12:32 +00001022 return false;
1023}
1024
1025bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1026 if (VarDecl *Var = S->getConditionVariable()) {
1027 if (Visit(MakeCXCursor(Var, TU)))
1028 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001029 }
1030
Douglas Gregor7201f9f2010-01-25 16:12:32 +00001031 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1032 return true;
1033 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregore1084fa2010-01-22 01:00:11 +00001034 return true;
1035
Douglas Gregor7201f9f2010-01-25 16:12:32 +00001036 return false;
1037}
1038
1039bool CursorVisitor::VisitForStmt(ForStmt *S) {
1040 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1041 return true;
1042 if (VarDecl *Var = S->getConditionVariable()) {
1043 if (Visit(MakeCXCursor(Var, TU)))
1044 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001045 }
1046
Douglas Gregor7201f9f2010-01-25 16:12:32 +00001047 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1048 return true;
1049 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1050 return true;
Douglas Gregore1084fa2010-01-22 01:00:11 +00001051 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1052 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001053
Douglas Gregore1084fa2010-01-22 01:00:11 +00001054 return false;
1055}
1056
Ted Kremenek33b9a422010-04-11 21:47:37 +00001057bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1058 return Visit(B->getBlockDecl());
1059}
1060
Douglas Gregor882211c2010-04-28 22:16:22 +00001061bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1062 // FIXME: Visit fields as well?
1063 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1064 return true;
1065
1066 return VisitExpr(E);
1067}
1068
Douglas Gregor625a5152010-01-23 00:40:08 +00001069bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1070 if (E->isArgumentType()) {
1071 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1072 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf441baf2010-02-17 00:41:40 +00001073
Douglas Gregor625a5152010-01-23 00:40:08 +00001074 return false;
1075 }
Ted Kremenekf441baf2010-02-17 00:41:40 +00001076
Douglas Gregor625a5152010-01-23 00:40:08 +00001077 return VisitExpr(E);
1078}
1079
1080bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1081 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1082 if (Visit(TSInfo->getTypeLoc()))
1083 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001084
Douglas Gregor625a5152010-01-23 00:40:08 +00001085 return VisitCastExpr(E);
1086}
1087
1088bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1089 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1090 if (Visit(TSInfo->getTypeLoc()))
1091 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001092
Douglas Gregor625a5152010-01-23 00:40:08 +00001093 return VisitExpr(E);
1094}
1095
Douglas Gregorde4827d2010-03-08 16:40:19 +00001096bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor9a129192010-04-21 00:45:42 +00001097 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1098 if (Visit(TSInfo->getTypeLoc()))
1099 return true;
Douglas Gregorde4827d2010-03-08 16:40:19 +00001100
1101 return VisitExpr(E);
1102}
1103
Douglas Gregorabd9e962010-04-20 15:39:42 +00001104bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1105 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1106}
1107
1108
Ted Kremenek6ab9aa022010-02-18 05:46:33 +00001109bool CursorVisitor::VisitAttributes(Decl *D) {
1110 for (const Attr *A = D->getAttrs(); A; A = A->getNext())
1111 if (Visit(MakeCXCursor(A, D, TU)))
1112 return true;
1113
1114 return false;
1115}
1116
Benjamin Kramer61f5d0c2009-10-18 16:11:04 +00001117extern "C" {
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001118CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1119 int displayDiagnostics) {
Douglas Gregor87752492010-01-22 20:35:53 +00001120 CIndexer *CIdxr = new CIndexer();
Steve Naroff531e2842009-10-20 14:46:24 +00001121 if (excludeDeclarationsFromPCH)
1122 CIdxr->setOnlyLocalDecls();
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001123 if (displayDiagnostics)
1124 CIdxr->setDisplayDiagnostics();
Steve Naroff531e2842009-10-20 14:46:24 +00001125 return CIdxr;
Steve Naroffd5e8e862009-08-27 19:51:58 +00001126}
1127
Daniel Dunbar079203f2009-12-01 03:14:51 +00001128void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor69ff5dc2010-01-29 00:47:48 +00001129 if (CIdx)
1130 delete static_cast<CIndexer *>(CIdx);
Steve Naroff3aa2d732009-09-17 18:33:27 +00001131}
1132
Daniel Dunbar11089662009-12-03 01:54:28 +00001133void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor69ff5dc2010-01-29 00:47:48 +00001134 if (CIdx) {
1135 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1136 CXXIdx->setUseExternalASTGeneration(value);
1137 }
Daniel Dunbar11089662009-12-03 01:54:28 +00001138}
1139
Daniel Dunbar079203f2009-12-01 03:14:51 +00001140CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregor33cdd812010-02-18 18:08:43 +00001141 const char *ast_filename) {
Douglas Gregor69ff5dc2010-01-29 00:47:48 +00001142 if (!CIdx)
1143 return 0;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001144
Douglas Gregor16bef852009-10-16 20:01:17 +00001145 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001146
Douglas Gregor7f95d262010-04-05 23:52:57 +00001147 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1148 return ASTUnit::LoadFromPCHFile(ast_filename, Diags,
Douglas Gregor33cdd812010-02-18 18:08:43 +00001149 CXXIdx->getOnlyLocalDecls(),
1150 0, 0, true);
Steve Naroffd5e8e862009-08-27 19:51:58 +00001151}
1152
Daniel Dunbar079203f2009-12-01 03:14:51 +00001153CXTranslationUnit
1154clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1155 const char *source_filename,
1156 int num_command_line_args,
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001157 const char **command_line_args,
1158 unsigned num_unsaved_files,
Douglas Gregor33cdd812010-02-18 18:08:43 +00001159 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor69ff5dc2010-01-29 00:47:48 +00001160 if (!CIdx)
1161 return 0;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001162
Steve Naroff531e2842009-10-20 14:46:24 +00001163 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1164
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001165 // Configure the diagnostics.
1166 DiagnosticOptions DiagOpts;
Douglas Gregor7f95d262010-04-05 23:52:57 +00001167 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1168 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf441baf2010-02-17 00:41:40 +00001169
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001170 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1171 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner58c79342010-04-05 22:42:27 +00001172 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf441baf2010-02-17 00:41:40 +00001173 const llvm::MemoryBuffer *Buffer
Chris Lattner58c79342010-04-05 22:42:27 +00001174 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001175 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1176 Buffer));
1177 }
Ted Kremenekf441baf2010-02-17 00:41:40 +00001178
Daniel Dunbar11089662009-12-03 01:54:28 +00001179 if (!CXXIdx->getUseExternalASTGeneration()) {
1180 llvm::SmallVector<const char *, 16> Args;
1181
1182 // The 'source_filename' argument is optional. If the caller does not
1183 // specify it then it is assumed that the source file is specified
1184 // in the actual argument list.
1185 if (source_filename)
1186 Args.push_back(source_filename);
1187 Args.insert(Args.end(), command_line_args,
1188 command_line_args + num_command_line_args);
Douglas Gregor7f6d60d2010-03-19 16:15:56 +00001189 Args.push_back("-Xclang");
1190 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001191 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf441baf2010-02-17 00:41:40 +00001192
Ted Kremenek7a5ede22010-01-07 22:49:05 +00001193#ifdef USE_CRASHTRACER
1194 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek991eb3f2010-01-06 03:42:32 +00001195#endif
Ted Kremenekf441baf2010-02-17 00:41:40 +00001196
Daniel Dunbar72fe5b12009-12-05 02:17:18 +00001197 llvm::OwningPtr<ASTUnit> Unit(
1198 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregord03e8232010-04-05 21:10:19 +00001199 Diags,
Daniel Dunbar8d4a2022009-12-13 03:46:13 +00001200 CXXIdx->getClangResourcesPath(),
Daniel Dunbar72fe5b12009-12-05 02:17:18 +00001201 CXXIdx->getOnlyLocalDecls(),
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001202 RemappedFiles.data(),
Douglas Gregor33cdd812010-02-18 18:08:43 +00001203 RemappedFiles.size(),
Douglas Gregor7f6d60d2010-03-19 16:15:56 +00001204 /*CaptureDiagnostics=*/true));
Ted Kremenekf441baf2010-02-17 00:41:40 +00001205
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001206 if (NumErrors != Diags->getNumErrors()) {
Ted Kremeneka6d3ab32010-03-05 22:43:29 +00001207 // Make sure to check that 'Unit' is non-NULL.
1208 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregora2433152010-04-05 18:10:21 +00001209 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1210 DEnd = Unit->stored_diag_end();
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001211 D != DEnd; ++D) {
1212 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregord770f732010-02-22 23:17:23 +00001213 CXString Msg = clang_formatDiagnostic(&Diag,
1214 clang_defaultDiagnosticDisplayOptions());
1215 fprintf(stderr, "%s\n", clang_getCString(Msg));
1216 clang_disposeString(Msg);
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001217 }
Douglas Gregord770f732010-02-22 23:17:23 +00001218#ifdef LLVM_ON_WIN32
1219 // On Windows, force a flush, since there may be multiple copies of
1220 // stderr and stdout in the file system, all with different buffers
1221 // but writing to the same device.
1222 fflush(stderr);
Ted Kremenek014e70b2010-03-26 01:34:51 +00001223#endif
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001224 }
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001225 }
Daniel Dunbar72fe5b12009-12-05 02:17:18 +00001226
1227 return Unit.take();
Daniel Dunbar11089662009-12-03 01:54:28 +00001228 }
1229
Ted Kremenek649bf5c2009-10-22 00:03:57 +00001230 // Build up the arguments for invoking 'clang'.
Ted Kremenek51d06bb2009-10-15 23:21:22 +00001231 std::vector<const char *> argv;
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001232
Ted Kremenek649bf5c2009-10-22 00:03:57 +00001233 // First add the complete path to the 'clang' executable.
1234 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer61f5d0c2009-10-18 16:11:04 +00001235 argv.push_back(ClangPath.c_str());
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001236
Ted Kremenek649bf5c2009-10-22 00:03:57 +00001237 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek51d06bb2009-10-15 23:21:22 +00001238 argv.push_back("-emit-ast");
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001239
Ted Kremenek649bf5c2009-10-22 00:03:57 +00001240 // The 'source_filename' argument is optional. If the caller does not
1241 // specify it then it is assumed that the source file is specified
1242 // in the actual argument list.
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001243 if (source_filename)
1244 argv.push_back(source_filename);
Ted Kremenek649bf5c2009-10-22 00:03:57 +00001245
Steve Naroff1cfb96c2009-10-15 20:50:09 +00001246 // Generate a temporary name for the AST file.
Ted Kremenek649bf5c2009-10-22 00:03:57 +00001247 argv.push_back("-o");
Benjamin Kramerf156b9d2010-03-13 21:22:49 +00001248 char astTmpFile[L_tmpnam];
1249 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek649bf5c2009-10-22 00:03:57 +00001250
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001251 // Remap any unsaved files to temporary files.
1252 std::vector<llvm::sys::Path> TemporaryFiles;
1253 std::vector<std::string> RemapArgs;
1254 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1255 return 0;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001256
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001257 // The pointers into the elements of RemapArgs are stable because we
1258 // won't be adding anything to RemapArgs after this point.
1259 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1260 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf441baf2010-02-17 00:41:40 +00001261
Ted Kremenek649bf5c2009-10-22 00:03:57 +00001262 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1263 for (int i = 0; i < num_command_line_args; ++i)
1264 if (const char *arg = command_line_args[i]) {
1265 if (strcmp(arg, "-o") == 0) {
1266 ++i; // Also skip the matching argument.
1267 continue;
1268 }
1269 if (strcmp(arg, "-emit-ast") == 0 ||
1270 strcmp(arg, "-c") == 0 ||
1271 strcmp(arg, "-fsyntax-only") == 0) {
1272 continue;
1273 }
1274
1275 // Keep the argument.
1276 argv.push_back(arg);
Steve Naroff531e2842009-10-20 14:46:24 +00001277 }
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001278
Douglas Gregorac0605e2010-01-28 06:00:51 +00001279 // Generate a temporary name for the diagnostics file.
Benjamin Kramerf156b9d2010-03-13 21:22:49 +00001280 char tmpFileResults[L_tmpnam];
1281 char *tmpResultsFileName = tmpnam(tmpFileResults);
1282 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregorac0605e2010-01-28 06:00:51 +00001283 TemporaryFiles.push_back(DiagnosticsFile);
1284 argv.push_back("-fdiagnostics-binary");
1285
Douglas Gregor7f6d60d2010-03-19 16:15:56 +00001286 argv.push_back("-Xclang");
1287 argv.push_back("-detailed-preprocessing-record");
1288
Ted Kremenek649bf5c2009-10-22 00:03:57 +00001289 // Add the null terminator.
Ted Kremenek51d06bb2009-10-15 23:21:22 +00001290 argv.push_back(NULL);
1291
Ted Kremenek12e678d2009-10-26 22:14:08 +00001292 // Invoke 'clang'.
1293 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1294 // on Unix or NUL (Windows).
Ted Kremenek44886fd2009-10-22 03:24:01 +00001295 std::string ErrMsg;
Douglas Gregorac0605e2010-01-28 06:00:51 +00001296 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1297 NULL };
Ted Kremenek44886fd2009-10-22 03:24:01 +00001298 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregorba965fb2010-01-28 00:56:43 +00001299 /* redirects */ &Redirects[0],
Ted Kremenek44886fd2009-10-22 03:24:01 +00001300 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001301
Douglas Gregorba965fb2010-01-28 00:56:43 +00001302 if (!ErrMsg.empty()) {
1303 std::string AllArgs;
Ted Kremenek44886fd2009-10-22 03:24:01 +00001304 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregorba965fb2010-01-28 00:56:43 +00001305 I != E; ++I) {
1306 AllArgs += ' ';
Ted Kremenekbf0690c2009-10-26 22:08:39 +00001307 if (*I)
Douglas Gregorba965fb2010-01-28 00:56:43 +00001308 AllArgs += *I;
Ted Kremenekbf0690c2009-10-26 22:08:39 +00001309 }
Ted Kremenekf441baf2010-02-17 00:41:40 +00001310
Daniel Dunbar253dbad2010-02-23 20:23:45 +00001311 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek44886fd2009-10-22 03:24:01 +00001312 }
Benjamin Kramer2836c4c2009-10-18 11:19:36 +00001313
Douglas Gregord03e8232010-04-05 21:10:19 +00001314 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, Diags,
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001315 CXXIdx->getOnlyLocalDecls(),
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001316 RemappedFiles.data(),
Douglas Gregor33cdd812010-02-18 18:08:43 +00001317 RemappedFiles.size(),
1318 /*CaptureDiagnostics=*/true);
Douglas Gregor33cdd812010-02-18 18:08:43 +00001319 if (ATU) {
1320 LoadSerializedDiagnostics(DiagnosticsFile,
1321 num_unsaved_files, unsaved_files,
1322 ATU->getFileManager(),
1323 ATU->getSourceManager(),
Douglas Gregora2433152010-04-05 18:10:21 +00001324 ATU->getStoredDiagnostics());
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001325 } else if (CXXIdx->getDisplayDiagnostics()) {
1326 // We failed to load the ASTUnit, but we can still deserialize the
1327 // diagnostics and emit them.
1328 FileManager FileMgr;
Douglas Gregore0fbb832010-03-16 00:06:06 +00001329 Diagnostic Diag;
1330 SourceManager SourceMgr(Diag);
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001331 // FIXME: Faked LangOpts!
1332 LangOptions LangOpts;
1333 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1334 LoadSerializedDiagnostics(DiagnosticsFile,
1335 num_unsaved_files, unsaved_files,
1336 FileMgr, SourceMgr, Diags);
1337 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1338 DEnd = Diags.end();
1339 D != DEnd; ++D) {
1340 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregord770f732010-02-22 23:17:23 +00001341 CXString Msg = clang_formatDiagnostic(&Diag,
1342 clang_defaultDiagnosticDisplayOptions());
1343 fprintf(stderr, "%s\n", clang_getCString(Msg));
1344 clang_disposeString(Msg);
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001345 }
Douglas Gregord770f732010-02-22 23:17:23 +00001346
1347#ifdef LLVM_ON_WIN32
1348 // On Windows, force a flush, since there may be multiple copies of
1349 // stderr and stdout in the file system, all with different buffers
1350 // but writing to the same device.
1351 fflush(stderr);
1352#endif
Douglas Gregor33cdd812010-02-18 18:08:43 +00001353 }
Douglas Gregorac0605e2010-01-28 06:00:51 +00001354
Douglas Gregor6cb5ba42010-02-18 23:35:40 +00001355 if (ATU) {
1356 // Make the translation unit responsible for destroying all temporary files.
1357 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1358 ATU->addTemporaryFile(TemporaryFiles[i]);
1359 ATU->addTemporaryFile(llvm::sys::Path(ATU->getPCHFileName()));
1360 } else {
1361 // Destroy all of the temporary files now; they can't be referenced any
1362 // longer.
1363 llvm::sys::Path(astTmpFile).eraseFromDisk();
1364 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1365 TemporaryFiles[i].eraseFromDisk();
1366 }
1367
Steve Naroff44cd60e2009-10-15 22:23:48 +00001368 return ATU;
Steve Naroff7781daa2009-10-15 20:04:39 +00001369}
1370
Daniel Dunbar079203f2009-12-01 03:14:51 +00001371void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor69ff5dc2010-01-29 00:47:48 +00001372 if (CTUnit)
1373 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff3aa2d732009-09-17 18:33:27 +00001374}
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001375
Daniel Dunbar079203f2009-12-01 03:14:51 +00001376CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor69ff5dc2010-01-29 00:47:48 +00001377 if (!CTUnit)
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00001378 return createCXString("");
Ted Kremenekf441baf2010-02-17 00:41:40 +00001379
Steve Naroffc0683b92009-09-03 18:19:54 +00001380 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00001381 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroff38c1a7b2009-09-03 15:49:00 +00001382}
Daniel Dunbare58bd8b2009-08-28 16:30:07 +00001383
Douglas Gregord2fc7272010-01-20 00:23:15 +00001384CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorfed36b12010-01-20 23:57:43 +00001385 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregord2fc7272010-01-20 00:23:15 +00001386 return Result;
1387}
1388
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00001389} // end: extern "C"
Steve Naroffd5e8e862009-08-27 19:51:58 +00001390
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00001391//===----------------------------------------------------------------------===//
Douglas Gregor4f46e782010-01-19 21:36:55 +00001392// CXSourceLocation and CXSourceRange Operations.
1393//===----------------------------------------------------------------------===//
1394
Douglas Gregor816fd362010-01-22 21:44:22 +00001395extern "C" {
1396CXSourceLocation clang_getNullLocation() {
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001397 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregor816fd362010-01-22 21:44:22 +00001398 return Result;
1399}
1400
1401unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar83a23542010-01-30 23:58:27 +00001402 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1403 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1404 loc1.int_data == loc2.int_data);
Douglas Gregor816fd362010-01-22 21:44:22 +00001405}
1406
1407CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1408 CXFile file,
1409 unsigned line,
1410 unsigned column) {
Douglas Gregor0925fbc2010-04-30 19:45:53 +00001411 if (!tu || !file)
Douglas Gregor816fd362010-01-22 21:44:22 +00001412 return clang_getNullLocation();
Douglas Gregor0925fbc2010-04-30 19:45:53 +00001413
Douglas Gregor816fd362010-01-22 21:44:22 +00001414 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1415 SourceLocation SLoc
1416 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf441baf2010-02-17 00:41:40 +00001417 static_cast<const FileEntry *>(file),
Douglas Gregor816fd362010-01-22 21:44:22 +00001418 line, column);
Ted Kremenekf441baf2010-02-17 00:41:40 +00001419
Daniel Dunbarc4b4d392010-02-14 01:47:36 +00001420 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregor816fd362010-01-22 21:44:22 +00001421}
1422
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001423CXSourceRange clang_getNullRange() {
1424 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1425 return Result;
1426}
Daniel Dunbar02968e52010-02-14 10:02:57 +00001427
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001428CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1429 if (begin.ptr_data[0] != end.ptr_data[0] ||
1430 begin.ptr_data[1] != end.ptr_data[1])
1431 return clang_getNullRange();
Ted Kremenekf441baf2010-02-17 00:41:40 +00001432
1433 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001434 begin.int_data, end.int_data };
Douglas Gregor816fd362010-01-22 21:44:22 +00001435 return Result;
1436}
1437
Douglas Gregor9bd6db52010-01-26 19:19:08 +00001438void clang_getInstantiationLocation(CXSourceLocation location,
1439 CXFile *file,
1440 unsigned *line,
1441 unsigned *column,
1442 unsigned *offset) {
Douglas Gregor4f46e782010-01-19 21:36:55 +00001443 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1444
Daniel Dunbarc4b4d392010-02-14 01:47:36 +00001445 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor9bd6db52010-01-26 19:19:08 +00001446 if (file)
1447 *file = 0;
1448 if (line)
1449 *line = 0;
1450 if (column)
1451 *column = 0;
1452 if (offset)
1453 *offset = 0;
1454 return;
1455 }
1456
Daniel Dunbarc4b4d392010-02-14 01:47:36 +00001457 const SourceManager &SM =
1458 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor4f46e782010-01-19 21:36:55 +00001459 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor4f46e782010-01-19 21:36:55 +00001460
1461 if (file)
1462 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1463 if (line)
1464 *line = SM.getInstantiationLineNumber(InstLoc);
1465 if (column)
1466 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregor47751d62010-01-26 03:07:15 +00001467 if (offset)
Douglas Gregor9bd6db52010-01-26 19:19:08 +00001468 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregor47751d62010-01-26 03:07:15 +00001469}
1470
Douglas Gregor4f46e782010-01-19 21:36:55 +00001471CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf441baf2010-02-17 00:41:40 +00001472 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001473 range.begin_int_data };
Douglas Gregor4f46e782010-01-19 21:36:55 +00001474 return Result;
1475}
1476
1477CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarc4b4d392010-02-14 01:47:36 +00001478 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001479 range.end_int_data };
Douglas Gregor4f46e782010-01-19 21:36:55 +00001480 return Result;
1481}
1482
Ted Kremenek76a43482010-05-20 02:59:19 +00001483unsigned clang_isFromMainFile(CXSourceLocation loc) {
1484 SourceLocation Loc = SourceLocation::getFromRawEncoding(loc.int_data);
1485 const SourceManager &SM =
1486 *static_cast<const SourceManager*>(loc.ptr_data[0]);
1487 return SM.isFromMainFile(Loc) ? 1 : 0;
1488}
1489
Douglas Gregor816fd362010-01-22 21:44:22 +00001490} // end: extern "C"
1491
Douglas Gregor4f46e782010-01-19 21:36:55 +00001492//===----------------------------------------------------------------------===//
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00001493// CXFile Operations.
1494//===----------------------------------------------------------------------===//
1495
1496extern "C" {
Ted Kremenekc560b682010-02-17 00:41:20 +00001497CXString clang_getFileName(CXFile SFile) {
Douglas Gregor66a58812010-01-18 22:46:11 +00001498 if (!SFile)
Ted Kremenekc560b682010-02-17 00:41:20 +00001499 return createCXString(NULL);
Ted Kremenekf441baf2010-02-17 00:41:40 +00001500
Steve Naroff6231f182009-10-27 14:35:18 +00001501 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenekc560b682010-02-17 00:41:20 +00001502 return createCXString(FEnt->getName());
Steve Naroff6231f182009-10-27 14:35:18 +00001503}
1504
1505time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor66a58812010-01-18 22:46:11 +00001506 if (!SFile)
1507 return 0;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001508
Steve Naroff6231f182009-10-27 14:35:18 +00001509 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1510 return FEnt->getModificationTime();
Steve Naroff26760892009-09-25 21:45:39 +00001511}
Ted Kremenekf441baf2010-02-17 00:41:40 +00001512
Douglas Gregor816fd362010-01-22 21:44:22 +00001513CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1514 if (!tu)
1515 return 0;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001516
Douglas Gregor816fd362010-01-22 21:44:22 +00001517 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf441baf2010-02-17 00:41:40 +00001518
Douglas Gregor816fd362010-01-22 21:44:22 +00001519 FileManager &FMgr = CXXUnit->getFileManager();
1520 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1521 return const_cast<FileEntry *>(File);
1522}
Ted Kremenekf441baf2010-02-17 00:41:40 +00001523
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00001524} // end: extern "C"
Steve Naroff26760892009-09-25 21:45:39 +00001525
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00001526//===----------------------------------------------------------------------===//
1527// CXCursor Operations.
1528//===----------------------------------------------------------------------===//
1529
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00001530static Decl *getDeclFromExpr(Stmt *E) {
1531 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1532 return RefExpr->getDecl();
1533 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1534 return ME->getMemberDecl();
1535 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1536 return RE->getDecl();
Ted Kremenekf441baf2010-02-17 00:41:40 +00001537
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00001538 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1539 return getDeclFromExpr(CE->getCallee());
1540 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1541 return getDeclFromExpr(CE->getSubExpr());
1542 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1543 return OME->getMethodDecl();
Ted Kremenekf441baf2010-02-17 00:41:40 +00001544
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00001545 return 0;
1546}
1547
Daniel Dunbara4a2e5d2010-02-02 05:00:22 +00001548static SourceLocation getLocationFromExpr(Expr *E) {
1549 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1550 return /*FIXME:*/Msg->getLeftLoc();
1551 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1552 return DRE->getLocation();
1553 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1554 return Member->getMemberLoc();
1555 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1556 return Ivar->getLocation();
1557 return E->getLocStart();
1558}
1559
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00001560extern "C" {
Ted Kremenekf441baf2010-02-17 00:41:40 +00001561
1562unsigned clang_visitChildren(CXCursor parent,
Douglas Gregor71f3d942010-01-20 20:59:29 +00001563 CXCursorVisitor visitor,
1564 CXClientData client_data) {
Douglas Gregorfed36b12010-01-20 23:57:43 +00001565 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregor71f3d942010-01-20 20:59:29 +00001566
1567 unsigned PCHLevel = Decl::MaxPCHLevel;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001568
Douglas Gregor71f3d942010-01-20 20:59:29 +00001569 // Set the PCHLevel to filter out unwanted decls if requested.
1570 if (CXXUnit->getOnlyLocalDecls()) {
1571 PCHLevel = 0;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001572
Douglas Gregor71f3d942010-01-20 20:59:29 +00001573 // If the main input was an AST, bump the level.
1574 if (CXXUnit->isMainFileAST())
1575 ++PCHLevel;
1576 }
Ted Kremenekf441baf2010-02-17 00:41:40 +00001577
Douglas Gregorfed36b12010-01-20 23:57:43 +00001578 CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel);
Douglas Gregor71f3d942010-01-20 20:59:29 +00001579 return CursorVis.VisitChildren(parent);
1580}
1581
Douglas Gregordd969c82010-01-20 21:45:58 +00001582static CXString getDeclSpelling(Decl *D) {
1583 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1584 if (!ND)
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00001585 return createCXString("");
Ted Kremenekf441baf2010-02-17 00:41:40 +00001586
Douglas Gregordd969c82010-01-20 21:45:58 +00001587 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00001588 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf441baf2010-02-17 00:41:40 +00001589
Douglas Gregordd969c82010-01-20 21:45:58 +00001590 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1591 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1592 // and returns different names. NamedDecl returns the class name and
1593 // ObjCCategoryImplDecl returns the category name.
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00001594 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf441baf2010-02-17 00:41:40 +00001595
Ted Kremenek08de5c12010-05-19 21:51:10 +00001596 llvm::SmallString<1024> S;
1597 llvm::raw_svector_ostream os(S);
1598 ND->printName(os);
1599
1600 return createCXString(os.str());
Douglas Gregordd969c82010-01-20 21:45:58 +00001601}
Ted Kremenekf441baf2010-02-17 00:41:40 +00001602
Daniel Dunbar079203f2009-12-01 03:14:51 +00001603CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregord2fc7272010-01-20 00:23:15 +00001604 if (clang_isTranslationUnit(C.kind))
Douglas Gregorfed36b12010-01-20 23:57:43 +00001605 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregord2fc7272010-01-20 00:23:15 +00001606
Steve Naroff80a766b2009-09-02 18:26:48 +00001607 if (clang_isReference(C.kind)) {
1608 switch (C.kind) {
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +00001609 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor6c8959b2010-01-16 14:00:32 +00001610 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00001611 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +00001612 }
1613 case CXCursor_ObjCClassRef: {
Douglas Gregor46d66142010-01-16 17:14:40 +00001614 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00001615 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +00001616 }
1617 case CXCursor_ObjCProtocolRef: {
Douglas Gregoref6eb842010-01-16 15:44:18 +00001618 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregor7ecd0202010-01-18 23:41:10 +00001619 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00001620 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +00001621 }
Douglas Gregor93f89952010-01-21 16:28:34 +00001622 case CXCursor_TypeRef: {
1623 TypeDecl *Type = getCursorTypeRef(C).first;
1624 assert(Type && "Missing type decl");
1625
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00001626 return createCXString(getCursorContext(C).getTypeDeclType(Type).
1627 getAsString());
Douglas Gregor93f89952010-01-21 16:28:34 +00001628 }
1629
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +00001630 default:
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00001631 return createCXString("<not implemented>");
Steve Naroff80a766b2009-09-02 18:26:48 +00001632 }
1633 }
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00001634
1635 if (clang_isExpression(C.kind)) {
1636 Decl *D = getDeclFromExpr(getCursorExpr(C));
1637 if (D)
Douglas Gregordd969c82010-01-20 21:45:58 +00001638 return getDeclSpelling(D);
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00001639 return createCXString("");
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00001640 }
1641
Douglas Gregor065f8d12010-03-18 17:52:52 +00001642 if (C.kind == CXCursor_MacroInstantiation)
1643 return createCXString(getCursorMacroInstantiation(C)->getName()
1644 ->getNameStart());
1645
Douglas Gregor06d6d322010-03-18 18:04:21 +00001646 if (C.kind == CXCursor_MacroDefinition)
1647 return createCXString(getCursorMacroDefinition(C)->getName()
1648 ->getNameStart());
1649
Douglas Gregor5bce76c2010-01-25 16:56:17 +00001650 if (clang_isDeclaration(C.kind))
1651 return getDeclSpelling(getCursorDecl(C));
Ted Kremenek29004672010-02-17 00:41:32 +00001652
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00001653 return createCXString("");
Steve Naroff80a766b2009-09-02 18:26:48 +00001654}
1655
Ted Kremenek29004672010-02-17 00:41:32 +00001656CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff1054e602009-08-31 00:59:03 +00001657 switch (Kind) {
Ted Kremenek29004672010-02-17 00:41:32 +00001658 case CXCursor_FunctionDecl:
1659 return createCXString("FunctionDecl");
1660 case CXCursor_TypedefDecl:
1661 return createCXString("TypedefDecl");
1662 case CXCursor_EnumDecl:
1663 return createCXString("EnumDecl");
1664 case CXCursor_EnumConstantDecl:
1665 return createCXString("EnumConstantDecl");
1666 case CXCursor_StructDecl:
1667 return createCXString("StructDecl");
1668 case CXCursor_UnionDecl:
1669 return createCXString("UnionDecl");
1670 case CXCursor_ClassDecl:
1671 return createCXString("ClassDecl");
1672 case CXCursor_FieldDecl:
1673 return createCXString("FieldDecl");
1674 case CXCursor_VarDecl:
1675 return createCXString("VarDecl");
1676 case CXCursor_ParmDecl:
1677 return createCXString("ParmDecl");
1678 case CXCursor_ObjCInterfaceDecl:
1679 return createCXString("ObjCInterfaceDecl");
1680 case CXCursor_ObjCCategoryDecl:
1681 return createCXString("ObjCCategoryDecl");
1682 case CXCursor_ObjCProtocolDecl:
1683 return createCXString("ObjCProtocolDecl");
1684 case CXCursor_ObjCPropertyDecl:
1685 return createCXString("ObjCPropertyDecl");
1686 case CXCursor_ObjCIvarDecl:
1687 return createCXString("ObjCIvarDecl");
1688 case CXCursor_ObjCInstanceMethodDecl:
1689 return createCXString("ObjCInstanceMethodDecl");
1690 case CXCursor_ObjCClassMethodDecl:
1691 return createCXString("ObjCClassMethodDecl");
1692 case CXCursor_ObjCImplementationDecl:
1693 return createCXString("ObjCImplementationDecl");
1694 case CXCursor_ObjCCategoryImplDecl:
1695 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek225b8e32010-04-13 23:39:06 +00001696 case CXCursor_CXXMethod:
1697 return createCXString("CXXMethod");
Ted Kremenek29004672010-02-17 00:41:32 +00001698 case CXCursor_UnexposedDecl:
1699 return createCXString("UnexposedDecl");
1700 case CXCursor_ObjCSuperClassRef:
1701 return createCXString("ObjCSuperClassRef");
1702 case CXCursor_ObjCProtocolRef:
1703 return createCXString("ObjCProtocolRef");
1704 case CXCursor_ObjCClassRef:
1705 return createCXString("ObjCClassRef");
1706 case CXCursor_TypeRef:
1707 return createCXString("TypeRef");
1708 case CXCursor_UnexposedExpr:
1709 return createCXString("UnexposedExpr");
Ted Kremenek33b9a422010-04-11 21:47:37 +00001710 case CXCursor_BlockExpr:
1711 return createCXString("BlockExpr");
Ted Kremenek29004672010-02-17 00:41:32 +00001712 case CXCursor_DeclRefExpr:
1713 return createCXString("DeclRefExpr");
1714 case CXCursor_MemberRefExpr:
1715 return createCXString("MemberRefExpr");
1716 case CXCursor_CallExpr:
1717 return createCXString("CallExpr");
1718 case CXCursor_ObjCMessageExpr:
1719 return createCXString("ObjCMessageExpr");
1720 case CXCursor_UnexposedStmt:
1721 return createCXString("UnexposedStmt");
1722 case CXCursor_InvalidFile:
1723 return createCXString("InvalidFile");
Ted Kremenek00da3b92010-03-19 20:39:05 +00001724 case CXCursor_InvalidCode:
1725 return createCXString("InvalidCode");
Ted Kremenek29004672010-02-17 00:41:32 +00001726 case CXCursor_NoDeclFound:
1727 return createCXString("NoDeclFound");
1728 case CXCursor_NotImplemented:
1729 return createCXString("NotImplemented");
1730 case CXCursor_TranslationUnit:
1731 return createCXString("TranslationUnit");
Ted Kremenekbff31432010-02-18 03:09:07 +00001732 case CXCursor_UnexposedAttr:
1733 return createCXString("UnexposedAttr");
1734 case CXCursor_IBActionAttr:
1735 return createCXString("attribute(ibaction)");
Douglas Gregor92a524f2010-03-18 00:42:48 +00001736 case CXCursor_IBOutletAttr:
1737 return createCXString("attribute(iboutlet)");
Ted Kremenek26bde772010-05-19 17:38:06 +00001738 case CXCursor_IBOutletCollectionAttr:
1739 return createCXString("attribute(iboutletcollection)");
Douglas Gregor92a524f2010-03-18 00:42:48 +00001740 case CXCursor_PreprocessingDirective:
1741 return createCXString("preprocessing directive");
Douglas Gregor06d6d322010-03-18 18:04:21 +00001742 case CXCursor_MacroDefinition:
1743 return createCXString("macro definition");
Douglas Gregor02ded2a2010-03-18 15:23:44 +00001744 case CXCursor_MacroInstantiation:
1745 return createCXString("macro instantiation");
Ted Kremenekbd67fb22010-05-06 23:38:21 +00001746 case CXCursor_Namespace:
1747 return createCXString("Namespace");
Ted Kremenekb80cba52010-05-07 01:04:29 +00001748 case CXCursor_LinkageSpec:
1749 return createCXString("LinkageSpec");
Steve Naroff1054e602009-08-31 00:59:03 +00001750 }
Ted Kremenek29004672010-02-17 00:41:32 +00001751
Ted Kremenek4ba52632010-01-16 02:02:09 +00001752 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremenek29004672010-02-17 00:41:32 +00001753 return createCXString(NULL);
Steve Naroffd5e8e862009-08-27 19:51:58 +00001754}
Steve Naroff1054e602009-08-31 00:59:03 +00001755
Ted Kremenek29004672010-02-17 00:41:32 +00001756enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1757 CXCursor parent,
Douglas Gregor562c1f92010-01-22 19:49:59 +00001758 CXClientData client_data) {
1759 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1760 *BestCursor = cursor;
1761 return CXChildVisit_Recurse;
1762}
Ted Kremenek29004672010-02-17 00:41:32 +00001763
Douglas Gregor816fd362010-01-22 21:44:22 +00001764CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1765 if (!TU)
Ted Kremeneke34cbde2010-01-14 01:51:23 +00001766 return clang_getNullCursor();
Ted Kremenek29004672010-02-17 00:41:32 +00001767
Douglas Gregor816fd362010-01-22 21:44:22 +00001768 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
1769
Douglas Gregor0c7c2f82010-03-05 21:16:25 +00001770 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
1771
Ted Kremenek97a45372010-01-25 22:34:44 +00001772 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Douglas Gregor562c1f92010-01-22 19:49:59 +00001773 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1774 if (SLoc.isValid()) {
Daniel Dunbar02968e52010-02-14 10:02:57 +00001775 SourceRange RegionOfInterest(SLoc, SLoc.getFileLocWithOffset(1));
Ted Kremenek29004672010-02-17 00:41:32 +00001776
Douglas Gregor562c1f92010-01-22 19:49:59 +00001777 // FIXME: Would be great to have a "hint" cursor, then walk from that
1778 // hint cursor upward until we find a cursor whose source range encloses
1779 // the region of interest, rather than starting from the translation unit.
1780 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremenek29004672010-02-17 00:41:32 +00001781 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregor562c1f92010-01-22 19:49:59 +00001782 Decl::MaxPCHLevel, RegionOfInterest);
1783 CursorVis.VisitChildren(Parent);
Steve Naroff54f22fb2009-09-15 20:25:34 +00001784 }
Ted Kremenek29004672010-02-17 00:41:32 +00001785 return Result;
Steve Naroffd5e8e862009-08-27 19:51:58 +00001786}
1787
Ted Kremeneke05d7802009-11-17 19:28:59 +00001788CXCursor clang_getNullCursor(void) {
Douglas Gregor58552bc2010-01-20 23:34:41 +00001789 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremeneke05d7802009-11-17 19:28:59 +00001790}
1791
1792unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregorc58d05b2010-01-15 21:56:13 +00001793 return X == Y;
Ted Kremeneke05d7802009-11-17 19:28:59 +00001794}
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001795
Daniel Dunbar079203f2009-12-01 03:14:51 +00001796unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff54f22fb2009-09-15 20:25:34 +00001797 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1798}
1799
Daniel Dunbar079203f2009-12-01 03:14:51 +00001800unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff1054e602009-08-31 00:59:03 +00001801 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1802}
Steve Naroff772c1a42009-08-31 14:26:51 +00001803
Daniel Dunbar079203f2009-12-01 03:14:51 +00001804unsigned clang_isReference(enum CXCursorKind K) {
Steve Naroff80a766b2009-09-02 18:26:48 +00001805 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1806}
1807
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00001808unsigned clang_isExpression(enum CXCursorKind K) {
1809 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1810}
1811
1812unsigned clang_isStatement(enum CXCursorKind K) {
1813 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1814}
1815
Douglas Gregord2fc7272010-01-20 00:23:15 +00001816unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1817 return K == CXCursor_TranslationUnit;
1818}
1819
Douglas Gregor92a524f2010-03-18 00:42:48 +00001820unsigned clang_isPreprocessing(enum CXCursorKind K) {
1821 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
1822}
1823
Ted Kremenekff9021b2010-03-08 21:17:29 +00001824unsigned clang_isUnexposed(enum CXCursorKind K) {
1825 switch (K) {
1826 case CXCursor_UnexposedDecl:
1827 case CXCursor_UnexposedExpr:
1828 case CXCursor_UnexposedStmt:
1829 case CXCursor_UnexposedAttr:
1830 return true;
1831 default:
1832 return false;
1833 }
1834}
1835
Daniel Dunbar079203f2009-12-01 03:14:51 +00001836CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroffef9618b2009-09-04 15:44:05 +00001837 return C.kind;
1838}
1839
Douglas Gregor66a58812010-01-18 22:46:11 +00001840CXSourceLocation clang_getCursorLocation(CXCursor C) {
1841 if (clang_isReference(C.kind)) {
Douglas Gregor7ecd0202010-01-18 23:41:10 +00001842 switch (C.kind) {
Ted Kremenekf441baf2010-02-17 00:41:40 +00001843 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor7ecd0202010-01-18 23:41:10 +00001844 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1845 = getCursorObjCSuperClassRef(C);
Ted Kremenek97a45372010-01-25 22:34:44 +00001846 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7ecd0202010-01-18 23:41:10 +00001847 }
1848
Ted Kremenekf441baf2010-02-17 00:41:40 +00001849 case CXCursor_ObjCProtocolRef: {
Douglas Gregor7ecd0202010-01-18 23:41:10 +00001850 std::pair<ObjCProtocolDecl *, SourceLocation> P
1851 = getCursorObjCProtocolRef(C);
Ted Kremenek97a45372010-01-25 22:34:44 +00001852 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7ecd0202010-01-18 23:41:10 +00001853 }
1854
Ted Kremenekf441baf2010-02-17 00:41:40 +00001855 case CXCursor_ObjCClassRef: {
Douglas Gregor7ecd0202010-01-18 23:41:10 +00001856 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1857 = getCursorObjCClassRef(C);
Ted Kremenek97a45372010-01-25 22:34:44 +00001858 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7ecd0202010-01-18 23:41:10 +00001859 }
Douglas Gregor93f89952010-01-21 16:28:34 +00001860
Ted Kremenekf441baf2010-02-17 00:41:40 +00001861 case CXCursor_TypeRef: {
Douglas Gregor93f89952010-01-21 16:28:34 +00001862 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremenek97a45372010-01-25 22:34:44 +00001863 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor93f89952010-01-21 16:28:34 +00001864 }
Ted Kremenekf441baf2010-02-17 00:41:40 +00001865
Douglas Gregor7ecd0202010-01-18 23:41:10 +00001866 default:
1867 // FIXME: Need a way to enumerate all non-reference cases.
1868 llvm_unreachable("Missed a reference kind");
1869 }
Douglas Gregor66a58812010-01-18 22:46:11 +00001870 }
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00001871
1872 if (clang_isExpression(C.kind))
Ted Kremenekf441baf2010-02-17 00:41:40 +00001873 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00001874 getLocationFromExpr(getCursorExpr(C)));
1875
Douglas Gregor92a524f2010-03-18 00:42:48 +00001876 if (C.kind == CXCursor_PreprocessingDirective) {
1877 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
1878 return cxloc::translateSourceLocation(getCursorContext(C), L);
1879 }
Douglas Gregor02ded2a2010-03-18 15:23:44 +00001880
1881 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor065f8d12010-03-18 17:52:52 +00001882 SourceLocation L
1883 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor02ded2a2010-03-18 15:23:44 +00001884 return cxloc::translateSourceLocation(getCursorContext(C), L);
1885 }
Douglas Gregor06d6d322010-03-18 18:04:21 +00001886
1887 if (C.kind == CXCursor_MacroDefinition) {
1888 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
1889 return cxloc::translateSourceLocation(getCursorContext(C), L);
1890 }
Douglas Gregor92a524f2010-03-18 00:42:48 +00001891
Ted Kremenek8278a322010-05-12 06:16:13 +00001892 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001893 return clang_getNullLocation();
Douglas Gregor66a58812010-01-18 22:46:11 +00001894
Douglas Gregor7ecd0202010-01-18 23:41:10 +00001895 Decl *D = getCursorDecl(C);
Douglas Gregor7ecd0202010-01-18 23:41:10 +00001896 SourceLocation Loc = D->getLocation();
1897 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1898 Loc = Class->getClassLoc();
Douglas Gregor7bf6b8a2010-03-22 15:53:50 +00001899 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor66a58812010-01-18 22:46:11 +00001900}
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001901
1902CXSourceRange clang_getCursorExtent(CXCursor C) {
1903 if (clang_isReference(C.kind)) {
1904 switch (C.kind) {
Ted Kremenekf441baf2010-02-17 00:41:40 +00001905 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001906 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1907 = getCursorObjCSuperClassRef(C);
Ted Kremenek97a45372010-01-25 22:34:44 +00001908 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001909 }
Ted Kremenekf441baf2010-02-17 00:41:40 +00001910
1911 case CXCursor_ObjCProtocolRef: {
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001912 std::pair<ObjCProtocolDecl *, SourceLocation> P
1913 = getCursorObjCProtocolRef(C);
Ted Kremenek97a45372010-01-25 22:34:44 +00001914 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001915 }
Ted Kremenekf441baf2010-02-17 00:41:40 +00001916
1917 case CXCursor_ObjCClassRef: {
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001918 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1919 = getCursorObjCClassRef(C);
Ted Kremenekf441baf2010-02-17 00:41:40 +00001920
Ted Kremenek97a45372010-01-25 22:34:44 +00001921 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001922 }
Douglas Gregor93f89952010-01-21 16:28:34 +00001923
Ted Kremenekf441baf2010-02-17 00:41:40 +00001924 case CXCursor_TypeRef: {
Douglas Gregor93f89952010-01-21 16:28:34 +00001925 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremenek97a45372010-01-25 22:34:44 +00001926 return cxloc::translateSourceRange(P.first->getASTContext(), P.second);
Douglas Gregor93f89952010-01-21 16:28:34 +00001927 }
Ted Kremenekf441baf2010-02-17 00:41:40 +00001928
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001929 default:
1930 // FIXME: Need a way to enumerate all non-reference cases.
1931 llvm_unreachable("Missed a reference kind");
1932 }
1933 }
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00001934
1935 if (clang_isExpression(C.kind))
Ted Kremenekf441baf2010-02-17 00:41:40 +00001936 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00001937 getCursorExpr(C)->getSourceRange());
Douglas Gregor562c1f92010-01-22 19:49:59 +00001938
1939 if (clang_isStatement(C.kind))
Ted Kremenekf441baf2010-02-17 00:41:40 +00001940 return cxloc::translateSourceRange(getCursorContext(C),
Douglas Gregor562c1f92010-01-22 19:49:59 +00001941 getCursorStmt(C)->getSourceRange());
Ted Kremenekf441baf2010-02-17 00:41:40 +00001942
Douglas Gregor92a524f2010-03-18 00:42:48 +00001943 if (C.kind == CXCursor_PreprocessingDirective) {
1944 SourceRange R = cxcursor::getCursorPreprocessingDirective(C);
1945 return cxloc::translateSourceRange(getCursorContext(C), R);
1946 }
Douglas Gregor02ded2a2010-03-18 15:23:44 +00001947
1948 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor065f8d12010-03-18 17:52:52 +00001949 SourceRange R = cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor02ded2a2010-03-18 15:23:44 +00001950 return cxloc::translateSourceRange(getCursorContext(C), R);
1951 }
Douglas Gregor06d6d322010-03-18 18:04:21 +00001952
1953 if (C.kind == CXCursor_MacroDefinition) {
1954 SourceRange R = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
1955 return cxloc::translateSourceRange(getCursorContext(C), R);
1956 }
Douglas Gregor92a524f2010-03-18 00:42:48 +00001957
Ted Kremenek8278a322010-05-12 06:16:13 +00001958 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001959 return clang_getNullRange();
Ted Kremenekf441baf2010-02-17 00:41:40 +00001960
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001961 Decl *D = getCursorDecl(C);
Douglas Gregor7bf6b8a2010-03-22 15:53:50 +00001962 return cxloc::translateSourceRange(getCursorContext(C), D->getSourceRange());
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001963}
Douglas Gregorad27e8b2010-01-19 01:20:04 +00001964
1965CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorfed36b12010-01-20 23:57:43 +00001966 if (clang_isInvalid(C.kind))
1967 return clang_getNullCursor();
Ted Kremenekf441baf2010-02-17 00:41:40 +00001968
Douglas Gregorfed36b12010-01-20 23:57:43 +00001969 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00001970 if (clang_isDeclaration(C.kind))
Douglas Gregorad27e8b2010-01-19 01:20:04 +00001971 return C;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001972
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00001973 if (clang_isExpression(C.kind)) {
1974 Decl *D = getDeclFromExpr(getCursorExpr(C));
1975 if (D)
Douglas Gregorfed36b12010-01-20 23:57:43 +00001976 return MakeCXCursor(D, CXXUnit);
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00001977 return clang_getNullCursor();
1978 }
1979
Douglas Gregor78ae2482010-03-18 18:23:03 +00001980 if (C.kind == CXCursor_MacroInstantiation) {
1981 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
1982 return MakeMacroDefinitionCursor(Def, CXXUnit);
1983 }
1984
Douglas Gregorad27e8b2010-01-19 01:20:04 +00001985 if (!clang_isReference(C.kind))
1986 return clang_getNullCursor();
Ted Kremenekf441baf2010-02-17 00:41:40 +00001987
Douglas Gregorad27e8b2010-01-19 01:20:04 +00001988 switch (C.kind) {
1989 case CXCursor_ObjCSuperClassRef:
Douglas Gregorfed36b12010-01-20 23:57:43 +00001990 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf441baf2010-02-17 00:41:40 +00001991
1992 case CXCursor_ObjCProtocolRef: {
Douglas Gregorfed36b12010-01-20 23:57:43 +00001993 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf441baf2010-02-17 00:41:40 +00001994
1995 case CXCursor_ObjCClassRef:
Douglas Gregorfed36b12010-01-20 23:57:43 +00001996 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor93f89952010-01-21 16:28:34 +00001997
Ted Kremenekf441baf2010-02-17 00:41:40 +00001998 case CXCursor_TypeRef:
Douglas Gregor93f89952010-01-21 16:28:34 +00001999 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenekf441baf2010-02-17 00:41:40 +00002000
Douglas Gregorad27e8b2010-01-19 01:20:04 +00002001 default:
2002 // We would prefer to enumerate all non-reference cursor kinds here.
2003 llvm_unreachable("Unhandled reference cursor kind");
2004 break;
2005 }
2006 }
Ted Kremenekf441baf2010-02-17 00:41:40 +00002007
Douglas Gregorad27e8b2010-01-19 01:20:04 +00002008 return clang_getNullCursor();
2009}
2010
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002011CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorfed36b12010-01-20 23:57:43 +00002012 if (clang_isInvalid(C.kind))
2013 return clang_getNullCursor();
Ted Kremenekf441baf2010-02-17 00:41:40 +00002014
Douglas Gregorfed36b12010-01-20 23:57:43 +00002015 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf441baf2010-02-17 00:41:40 +00002016
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002017 bool WasReference = false;
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00002018 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002019 C = clang_getCursorReferenced(C);
2020 WasReference = true;
2021 }
2022
Douglas Gregor78ae2482010-03-18 18:23:03 +00002023 if (C.kind == CXCursor_MacroInstantiation)
2024 return clang_getCursorReferenced(C);
2025
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002026 if (!clang_isDeclaration(C.kind))
2027 return clang_getNullCursor();
2028
2029 Decl *D = getCursorDecl(C);
2030 if (!D)
2031 return clang_getNullCursor();
Ted Kremenekf441baf2010-02-17 00:41:40 +00002032
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002033 switch (D->getKind()) {
2034 // Declaration kinds that don't really separate the notions of
2035 // declaration and definition.
2036 case Decl::Namespace:
2037 case Decl::Typedef:
2038 case Decl::TemplateTypeParm:
2039 case Decl::EnumConstant:
2040 case Decl::Field:
2041 case Decl::ObjCIvar:
2042 case Decl::ObjCAtDefsField:
2043 case Decl::ImplicitParam:
2044 case Decl::ParmVar:
2045 case Decl::NonTypeTemplateParm:
2046 case Decl::TemplateTemplateParm:
2047 case Decl::ObjCCategoryImpl:
2048 case Decl::ObjCImplementation:
2049 case Decl::LinkageSpec:
2050 case Decl::ObjCPropertyImpl:
2051 case Decl::FileScopeAsm:
2052 case Decl::StaticAssert:
2053 case Decl::Block:
2054 return C;
2055
2056 // Declaration kinds that don't make any sense here, but are
2057 // nonetheless harmless.
2058 case Decl::TranslationUnit:
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002059 break;
2060
2061 // Declaration kinds for which the definition is not resolvable.
2062 case Decl::UnresolvedUsingTypename:
2063 case Decl::UnresolvedUsingValue:
2064 break;
2065
2066 case Decl::UsingDirective:
Douglas Gregorfed36b12010-01-20 23:57:43 +00002067 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2068 CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002069
2070 case Decl::NamespaceAlias:
Douglas Gregorfed36b12010-01-20 23:57:43 +00002071 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002072
2073 case Decl::Enum:
2074 case Decl::Record:
2075 case Decl::CXXRecord:
2076 case Decl::ClassTemplateSpecialization:
2077 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002078 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorfed36b12010-01-20 23:57:43 +00002079 return MakeCXCursor(Def, CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002080 return clang_getNullCursor();
2081
2082 case Decl::Function:
2083 case Decl::CXXMethod:
2084 case Decl::CXXConstructor:
2085 case Decl::CXXDestructor:
2086 case Decl::CXXConversion: {
2087 const FunctionDecl *Def = 0;
2088 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorfed36b12010-01-20 23:57:43 +00002089 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002090 return clang_getNullCursor();
2091 }
2092
2093 case Decl::Var: {
Sebastian Redl5ca79842010-02-01 20:16:42 +00002094 // Ask the variable if it has a definition.
2095 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2096 return MakeCXCursor(Def, CXXUnit);
2097 return clang_getNullCursor();
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002098 }
Ted Kremenekf441baf2010-02-17 00:41:40 +00002099
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002100 case Decl::FunctionTemplate: {
2101 const FunctionDecl *Def = 0;
2102 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorfed36b12010-01-20 23:57:43 +00002103 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002104 return clang_getNullCursor();
2105 }
Ted Kremenekf441baf2010-02-17 00:41:40 +00002106
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002107 case Decl::ClassTemplate: {
2108 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002109 ->getDefinition())
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002110 return MakeCXCursor(
Ted Kremenekf441baf2010-02-17 00:41:40 +00002111 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorfed36b12010-01-20 23:57:43 +00002112 CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002113 return clang_getNullCursor();
2114 }
2115
2116 case Decl::Using: {
2117 UsingDecl *Using = cast<UsingDecl>(D);
2118 CXCursor Def = clang_getNullCursor();
Ted Kremenekf441baf2010-02-17 00:41:40 +00002119 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2120 SEnd = Using->shadow_end();
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002121 S != SEnd; ++S) {
2122 if (Def != clang_getNullCursor()) {
2123 // FIXME: We have no way to return multiple results.
2124 return clang_getNullCursor();
2125 }
2126
Ted Kremenekf441baf2010-02-17 00:41:40 +00002127 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorfed36b12010-01-20 23:57:43 +00002128 CXXUnit));
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002129 }
2130
2131 return Def;
2132 }
2133
2134 case Decl::UsingShadow:
2135 return clang_getCursorDefinition(
Ted Kremenekf441baf2010-02-17 00:41:40 +00002136 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorfed36b12010-01-20 23:57:43 +00002137 CXXUnit));
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002138
2139 case Decl::ObjCMethod: {
2140 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2141 if (Method->isThisDeclarationADefinition())
2142 return C;
2143
2144 // Dig out the method definition in the associated
2145 // @implementation, if we have it.
2146 // FIXME: The ASTs should make finding the definition easier.
2147 if (ObjCInterfaceDecl *Class
2148 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2149 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2150 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2151 Method->isInstanceMethod()))
2152 if (Def->isThisDeclarationADefinition())
Douglas Gregorfed36b12010-01-20 23:57:43 +00002153 return MakeCXCursor(Def, CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002154
2155 return clang_getNullCursor();
2156 }
2157
2158 case Decl::ObjCCategory:
2159 if (ObjCCategoryImplDecl *Impl
2160 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorfed36b12010-01-20 23:57:43 +00002161 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002162 return clang_getNullCursor();
2163
2164 case Decl::ObjCProtocol:
2165 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2166 return C;
2167 return clang_getNullCursor();
2168
2169 case Decl::ObjCInterface:
2170 // There are two notions of a "definition" for an Objective-C
2171 // class: the interface and its implementation. When we resolved a
2172 // reference to an Objective-C class, produce the @interface as
2173 // the definition; when we were provided with the interface,
2174 // produce the @implementation as the definition.
2175 if (WasReference) {
2176 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2177 return C;
2178 } else if (ObjCImplementationDecl *Impl
2179 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorfed36b12010-01-20 23:57:43 +00002180 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002181 return clang_getNullCursor();
Ted Kremenekf441baf2010-02-17 00:41:40 +00002182
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002183 case Decl::ObjCProperty:
2184 // FIXME: We don't really know where to find the
2185 // ObjCPropertyImplDecls that implement this property.
2186 return clang_getNullCursor();
2187
2188 case Decl::ObjCCompatibleAlias:
2189 if (ObjCInterfaceDecl *Class
2190 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2191 if (!Class->isForwardDecl())
Douglas Gregorfed36b12010-01-20 23:57:43 +00002192 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf441baf2010-02-17 00:41:40 +00002193
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002194 return clang_getNullCursor();
2195
2196 case Decl::ObjCForwardProtocol: {
2197 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2198 if (Forward->protocol_size() == 1)
2199 return clang_getCursorDefinition(
Ted Kremenekf441baf2010-02-17 00:41:40 +00002200 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorfed36b12010-01-20 23:57:43 +00002201 CXXUnit));
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002202
2203 // FIXME: Cannot return multiple definitions.
2204 return clang_getNullCursor();
2205 }
2206
2207 case Decl::ObjCClass: {
2208 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2209 if (Class->size() == 1) {
2210 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2211 if (!IFace->isForwardDecl())
Douglas Gregorfed36b12010-01-20 23:57:43 +00002212 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002213 return clang_getNullCursor();
2214 }
2215
2216 // FIXME: Cannot return multiple definitions.
2217 return clang_getNullCursor();
2218 }
2219
2220 case Decl::Friend:
2221 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorfed36b12010-01-20 23:57:43 +00002222 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002223 return clang_getNullCursor();
2224
2225 case Decl::FriendTemplate:
2226 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorfed36b12010-01-20 23:57:43 +00002227 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002228 return clang_getNullCursor();
2229 }
2230
2231 return clang_getNullCursor();
2232}
2233
2234unsigned clang_isCursorDefinition(CXCursor C) {
2235 if (!clang_isDeclaration(C.kind))
2236 return 0;
2237
2238 return clang_getCursorDefinition(C) == C;
2239}
2240
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00002241void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff76b8f132009-09-23 17:52:52 +00002242 const char **startBuf,
2243 const char **endBuf,
2244 unsigned *startLine,
2245 unsigned *startColumn,
2246 unsigned *endLine,
Daniel Dunbar079203f2009-12-01 03:14:51 +00002247 unsigned *endColumn) {
Douglas Gregorc58d05b2010-01-15 21:56:13 +00002248 assert(getCursorDecl(C) && "CXCursor has null decl");
2249 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff76b8f132009-09-23 17:52:52 +00002250 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2251 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf441baf2010-02-17 00:41:40 +00002252
Steve Naroff76b8f132009-09-23 17:52:52 +00002253 SourceManager &SM = FD->getASTContext().getSourceManager();
2254 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2255 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2256 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2257 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2258 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2259 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2260}
Ted Kremenekf441baf2010-02-17 00:41:40 +00002261
Douglas Gregor1e21cc72010-02-18 23:07:20 +00002262void clang_enableStackTraces(void) {
2263 llvm::sys::PrintStackTraceOnErrorSignal();
2264}
2265
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00002266} // end: extern "C"
Steve Naroff76b8f132009-09-23 17:52:52 +00002267
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00002268//===----------------------------------------------------------------------===//
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002269// Token-based Operations.
2270//===----------------------------------------------------------------------===//
2271
2272/* CXToken layout:
2273 * int_data[0]: a CXTokenKind
2274 * int_data[1]: starting token location
2275 * int_data[2]: token length
2276 * int_data[3]: reserved
Ted Kremenekf441baf2010-02-17 00:41:40 +00002277 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002278 * otherwise unused.
2279 */
2280extern "C" {
2281
2282CXTokenKind clang_getTokenKind(CXToken CXTok) {
2283 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2284}
2285
2286CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2287 switch (clang_getTokenKind(CXTok)) {
2288 case CXToken_Identifier:
2289 case CXToken_Keyword:
2290 // We know we have an IdentifierInfo*, so use that.
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00002291 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2292 ->getNameStart());
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002293
2294 case CXToken_Literal: {
2295 // We have stashed the starting pointer in the ptr_data field. Use it.
2296 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00002297 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002298 }
Ted Kremenekf441baf2010-02-17 00:41:40 +00002299
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002300 case CXToken_Punctuation:
2301 case CXToken_Comment:
2302 break;
2303 }
Ted Kremenekf441baf2010-02-17 00:41:40 +00002304
2305 // We have to find the starting buffer pointer the hard way, by
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002306 // deconstructing the source location.
2307 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2308 if (!CXXUnit)
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00002309 return createCXString("");
Ted Kremenekf441baf2010-02-17 00:41:40 +00002310
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002311 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2312 std::pair<FileID, unsigned> LocInfo
2313 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregore0fbb832010-03-16 00:06:06 +00002314 bool Invalid = false;
Benjamin Kramereb92dc02010-03-16 14:14:31 +00002315 llvm::StringRef Buffer
Douglas Gregore0fbb832010-03-16 00:06:06 +00002316 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2317 if (Invalid)
Douglas Gregor802b7762010-03-15 22:54:52 +00002318 return createCXString("");
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002319
Benjamin Kramereb92dc02010-03-16 14:14:31 +00002320 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002321}
Ted Kremenekf441baf2010-02-17 00:41:40 +00002322
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002323CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2324 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2325 if (!CXXUnit)
2326 return clang_getNullLocation();
Ted Kremenekf441baf2010-02-17 00:41:40 +00002327
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002328 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2329 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2330}
2331
2332CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2333 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor4f9c3762010-01-28 00:27:43 +00002334 if (!CXXUnit)
2335 return clang_getNullRange();
Ted Kremenekf441baf2010-02-17 00:41:40 +00002336
2337 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002338 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2339}
Ted Kremenekf441baf2010-02-17 00:41:40 +00002340
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002341void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2342 CXToken **Tokens, unsigned *NumTokens) {
2343 if (Tokens)
2344 *Tokens = 0;
2345 if (NumTokens)
2346 *NumTokens = 0;
Ted Kremenekf441baf2010-02-17 00:41:40 +00002347
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002348 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2349 if (!CXXUnit || !Tokens || !NumTokens)
2350 return;
Ted Kremenekf441baf2010-02-17 00:41:40 +00002351
Douglas Gregor0c7c2f82010-03-05 21:16:25 +00002352 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2353
Daniel Dunbar80daf532010-02-14 08:31:57 +00002354 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002355 if (R.isInvalid())
2356 return;
Ted Kremenekf441baf2010-02-17 00:41:40 +00002357
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002358 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2359 std::pair<FileID, unsigned> BeginLocInfo
2360 = SourceMgr.getDecomposedLoc(R.getBegin());
2361 std::pair<FileID, unsigned> EndLocInfo
2362 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf441baf2010-02-17 00:41:40 +00002363
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002364 // Cannot tokenize across files.
2365 if (BeginLocInfo.first != EndLocInfo.first)
2366 return;
Ted Kremenekf441baf2010-02-17 00:41:40 +00002367
2368 // Create a lexer
Douglas Gregore0fbb832010-03-16 00:06:06 +00002369 bool Invalid = false;
Benjamin Kramereb92dc02010-03-16 14:14:31 +00002370 llvm::StringRef Buffer
Douglas Gregore0fbb832010-03-16 00:06:06 +00002371 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor554e0b12010-03-16 20:26:15 +00002372 if (Invalid)
2373 return;
Douglas Gregor802b7762010-03-15 22:54:52 +00002374
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002375 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2376 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramereb92dc02010-03-16 14:14:31 +00002377 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002378 Lex.SetCommentRetentionState(true);
Ted Kremenekf441baf2010-02-17 00:41:40 +00002379
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002380 // Lex tokens until we hit the end of the range.
Benjamin Kramereb92dc02010-03-16 14:14:31 +00002381 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002382 llvm::SmallVector<CXToken, 32> CXTokens;
2383 Token Tok;
2384 do {
2385 // Lex the next token
2386 Lex.LexFromRawLexer(Tok);
2387 if (Tok.is(tok::eof))
2388 break;
Ted Kremenekf441baf2010-02-17 00:41:40 +00002389
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002390 // Initialize the CXToken.
2391 CXToken CXTok;
Ted Kremenekf441baf2010-02-17 00:41:40 +00002392
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002393 // - Common fields
2394 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2395 CXTok.int_data[2] = Tok.getLength();
2396 CXTok.int_data[3] = 0;
Ted Kremenekf441baf2010-02-17 00:41:40 +00002397
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002398 // - Kind-specific fields
2399 if (Tok.isLiteral()) {
2400 CXTok.int_data[0] = CXToken_Literal;
2401 CXTok.ptr_data = (void *)Tok.getLiteralData();
2402 } else if (Tok.is(tok::identifier)) {
Douglas Gregor802b7762010-03-15 22:54:52 +00002403 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002404 std::pair<FileID, unsigned> LocInfo
2405 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregore0fbb832010-03-16 00:06:06 +00002406 bool Invalid = false;
Benjamin Kramereb92dc02010-03-16 14:14:31 +00002407 llvm::StringRef Buf
Douglas Gregore0fbb832010-03-16 00:06:06 +00002408 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2409 if (Invalid)
Douglas Gregor802b7762010-03-15 22:54:52 +00002410 return;
2411
Benjamin Kramereb92dc02010-03-16 14:14:31 +00002412 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002413 IdentifierInfo *II
2414 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenek15cbc3a2010-05-05 00:55:20 +00002415
2416 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
2417 CXTok.int_data[0] = CXToken_Keyword;
2418 }
2419 else {
2420 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2421 CXToken_Identifier
2422 : CXToken_Keyword;
2423 }
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002424 CXTok.ptr_data = II;
2425 } else if (Tok.is(tok::comment)) {
2426 CXTok.int_data[0] = CXToken_Comment;
2427 CXTok.ptr_data = 0;
2428 } else {
2429 CXTok.int_data[0] = CXToken_Punctuation;
2430 CXTok.ptr_data = 0;
2431 }
2432 CXTokens.push_back(CXTok);
2433 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf441baf2010-02-17 00:41:40 +00002434
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002435 if (CXTokens.empty())
2436 return;
Ted Kremenekf441baf2010-02-17 00:41:40 +00002437
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002438 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2439 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2440 *NumTokens = CXTokens.size();
2441}
Douglas Gregor61656112010-01-26 18:31:56 +00002442
Ted Kremenek63ac5992010-05-05 00:55:15 +00002443void clang_disposeTokens(CXTranslationUnit TU,
2444 CXToken *Tokens, unsigned NumTokens) {
2445 free(Tokens);
2446}
2447
2448} // end: extern "C"
2449
2450//===----------------------------------------------------------------------===//
2451// Token annotation APIs.
2452//===----------------------------------------------------------------------===//
2453
Douglas Gregor61656112010-01-26 18:31:56 +00002454typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenek680fe512010-05-05 00:55:23 +00002455static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2456 CXCursor parent,
2457 CXClientData client_data);
Ted Kremenek63ac5992010-05-05 00:55:15 +00002458namespace {
2459class AnnotateTokensWorker {
2460 AnnotateTokensData &Annotated;
Ted Kremenek458c2f12010-05-05 00:55:17 +00002461 CXToken *Tokens;
2462 CXCursor *Cursors;
2463 unsigned NumTokens;
Ted Kremenek680fe512010-05-05 00:55:23 +00002464 unsigned TokIdx;
2465 CursorVisitor AnnotateVis;
2466 SourceManager &SrcMgr;
2467
2468 bool MoreTokens() const { return TokIdx < NumTokens; }
2469 unsigned NextToken() const { return TokIdx; }
2470 void AdvanceToken() { ++TokIdx; }
2471 SourceLocation GetTokenLoc(unsigned tokI) {
2472 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
2473 }
2474
Ted Kremenek63ac5992010-05-05 00:55:15 +00002475public:
Ted Kremenek458c2f12010-05-05 00:55:17 +00002476 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenek680fe512010-05-05 00:55:23 +00002477 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
2478 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek458c2f12010-05-05 00:55:17 +00002479 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenek680fe512010-05-05 00:55:23 +00002480 NumTokens(numTokens), TokIdx(0),
2481 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
2482 Decl::MaxPCHLevel, RegionOfInterest),
2483 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek458c2f12010-05-05 00:55:17 +00002484
Ted Kremenek680fe512010-05-05 00:55:23 +00002485 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek63ac5992010-05-05 00:55:15 +00002486 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenek680fe512010-05-05 00:55:23 +00002487 void AnnotateTokens(CXCursor parent);
Ted Kremenek63ac5992010-05-05 00:55:15 +00002488};
2489}
Douglas Gregor61656112010-01-26 18:31:56 +00002490
Ted Kremenek680fe512010-05-05 00:55:23 +00002491void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
2492 // Walk the AST within the region of interest, annotating tokens
2493 // along the way.
2494 VisitChildren(parent);
Ted Kremenek458c2f12010-05-05 00:55:17 +00002495
Ted Kremenek680fe512010-05-05 00:55:23 +00002496 for (unsigned I = 0 ; I < TokIdx ; ++I) {
2497 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2498 if (Pos != Annotated.end())
2499 Cursors[I] = Pos->second;
2500 }
2501
2502 // Finish up annotating any tokens left.
2503 if (!MoreTokens())
2504 return;
2505
2506 const CXCursor &C = clang_getNullCursor();
2507 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
2508 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2509 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek458c2f12010-05-05 00:55:17 +00002510 }
2511}
2512
Ted Kremenek63ac5992010-05-05 00:55:15 +00002513enum CXChildVisitResult
2514AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenek680fe512010-05-05 00:55:23 +00002515 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2516 // We can always annotate a preprocessing directive/macro instantiation.
2517 if (clang_isPreprocessing(cursor.kind)) {
2518 Annotated[Loc.int_data] = cursor;
Douglas Gregor61656112010-01-26 18:31:56 +00002519 return CXChildVisit_Recurse;
2520 }
Ted Kremenek680fe512010-05-05 00:55:23 +00002521
2522 CXSourceRange cursorExtent = clang_getCursorExtent(cursor);
2523 SourceRange cursorRange = cxloc::translateCXSourceRange(cursorExtent);
Ted Kremenek5d616142010-05-12 05:29:33 +00002524
Ted Kremenek680fe512010-05-05 00:55:23 +00002525 if (cursorRange.isInvalid())
2526 return CXChildVisit_Continue;
Ted Kremenek5d616142010-05-12 05:29:33 +00002527
Ted Kremenek680fe512010-05-05 00:55:23 +00002528 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
2529
Ted Kremenek5d616142010-05-12 05:29:33 +00002530 // Adjust the annotated range based specific declarations.
2531 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
2532 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek49be9e02010-05-18 21:09:07 +00002533 Decl *D = cxcursor::getCursorDecl(cursor);
2534 // Don't visit synthesized ObjC methods, since they have no syntatic
2535 // representation in the source.
2536 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2537 if (MD->isSynthesized())
2538 return CXChildVisit_Continue;
2539 }
2540 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremenek5d616142010-05-12 05:29:33 +00002541 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
2542 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002543 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenekd3214132010-05-13 15:38:38 +00002544 if (TLoc.isValid() &&
2545 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremenek5d616142010-05-12 05:29:33 +00002546 cursorRange.setBegin(TLoc);
Ted Kremenek5d616142010-05-12 05:29:33 +00002547 }
2548 }
2549 }
2550
Ted Kremenek680fe512010-05-05 00:55:23 +00002551 const enum CXCursorKind K = clang_getCursorKind(parent);
2552 const CXCursor updateC =
2553 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
2554 L.isMacroID())
2555 ? clang_getNullCursor() : parent;
2556
2557 while (MoreTokens()) {
2558 const unsigned I = NextToken();
2559 SourceLocation TokLoc = GetTokenLoc(I);
2560 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2561 case RangeBefore:
2562 Cursors[I] = updateC;
2563 AdvanceToken();
2564 continue;
2565 case RangeAfter:
2566 return CXChildVisit_Continue;
2567 case RangeOverlap:
2568 break;
2569 }
2570 break;
2571 }
2572
2573 // Visit children to get their cursor information.
2574 const unsigned BeforeChildren = NextToken();
2575 VisitChildren(cursor);
2576 const unsigned AfterChildren = NextToken();
2577
2578 // Adjust 'Last' to the last token within the extent of the cursor.
2579 while (MoreTokens()) {
2580 const unsigned I = NextToken();
2581 SourceLocation TokLoc = GetTokenLoc(I);
2582 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2583 case RangeBefore:
2584 assert(0 && "Infeasible");
2585 case RangeAfter:
2586 break;
2587 case RangeOverlap:
2588 Cursors[I] = updateC;
2589 AdvanceToken();
2590 continue;
2591 }
2592 break;
2593 }
2594 const unsigned Last = NextToken();
Ted Kremenek63ac5992010-05-05 00:55:15 +00002595
Ted Kremenek680fe512010-05-05 00:55:23 +00002596 // Scan the tokens that are at the beginning of the cursor, but are not
2597 // capture by the child cursors.
2598
2599 // For AST elements within macros, rely on a post-annotate pass to
2600 // to correctly annotate the tokens with cursors. Otherwise we can
2601 // get confusing results of having tokens that map to cursors that really
2602 // are expanded by an instantiation.
2603 if (L.isMacroID())
2604 cursor = clang_getNullCursor();
2605
2606 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
2607 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
2608 break;
2609 Cursors[I] = cursor;
2610 }
2611 // Scan the tokens that are at the end of the cursor, but are not captured
2612 // but the child cursors.
2613 for (unsigned I = AfterChildren; I != Last; ++I)
2614 Cursors[I] = cursor;
2615
2616 TokIdx = Last;
2617 return CXChildVisit_Continue;
Douglas Gregor61656112010-01-26 18:31:56 +00002618}
2619
Ted Kremenek63ac5992010-05-05 00:55:15 +00002620static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2621 CXCursor parent,
2622 CXClientData client_data) {
2623 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
2624}
2625
2626extern "C" {
2627
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002628void clang_annotateTokens(CXTranslationUnit TU,
2629 CXToken *Tokens, unsigned NumTokens,
2630 CXCursor *Cursors) {
Ted Kremenek680fe512010-05-05 00:55:23 +00002631
2632 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor61656112010-01-26 18:31:56 +00002633 return;
Ted Kremenek680fe512010-05-05 00:55:23 +00002634
Douglas Gregor61656112010-01-26 18:31:56 +00002635 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenek680fe512010-05-05 00:55:23 +00002636 if (!CXXUnit) {
2637 // Any token we don't specifically annotate will have a NULL cursor.
2638 const CXCursor &C = clang_getNullCursor();
2639 for (unsigned I = 0; I != NumTokens; ++I)
2640 Cursors[I] = C;
Douglas Gregor61656112010-01-26 18:31:56 +00002641 return;
Ted Kremenek680fe512010-05-05 00:55:23 +00002642 }
2643
Douglas Gregor0c7c2f82010-03-05 21:16:25 +00002644 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek680fe512010-05-05 00:55:23 +00002645
Douglas Gregor5272e802010-03-19 05:22:59 +00002646 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor61656112010-01-26 18:31:56 +00002647 SourceRange RegionOfInterest;
Ted Kremenek680fe512010-05-05 00:55:23 +00002648 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
2649 clang_getTokenLocation(TU, Tokens[0])));
2650
Douglas Gregor61656112010-01-26 18:31:56 +00002651 SourceLocation End
Ted Kremenek680fe512010-05-05 00:55:23 +00002652 = cxloc::translateSourceLocation(clang_getTokenLocation(TU,
2653 Tokens[NumTokens - 1]));
Daniel Dunbar02968e52010-02-14 10:02:57 +00002654 RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End));
Ted Kremenek680fe512010-05-05 00:55:23 +00002655
Douglas Gregor5272e802010-03-19 05:22:59 +00002656 // A mapping from the source locations found when re-lexing or traversing the
2657 // region of interest to the corresponding cursors.
2658 AnnotateTokensData Annotated;
Ted Kremenek680fe512010-05-05 00:55:23 +00002659
2660 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor5272e802010-03-19 05:22:59 +00002661 // directives.
Douglas Gregor92a524f2010-03-18 00:42:48 +00002662 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2663 std::pair<FileID, unsigned> BeginLocInfo
2664 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
2665 std::pair<FileID, unsigned> EndLocInfo
2666 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenek680fe512010-05-05 00:55:23 +00002667
Douglas Gregor92a524f2010-03-18 00:42:48 +00002668 llvm::StringRef Buffer;
Douglas Gregor5272e802010-03-19 05:22:59 +00002669 bool Invalid = false;
2670 if (BeginLocInfo.first == EndLocInfo.first &&
2671 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
2672 !Invalid) {
Douglas Gregor92a524f2010-03-18 00:42:48 +00002673 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2674 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenek680fe512010-05-05 00:55:23 +00002675 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor065f8d12010-03-18 17:52:52 +00002676 Buffer.end());
Douglas Gregor92a524f2010-03-18 00:42:48 +00002677 Lex.SetCommentRetentionState(true);
Ted Kremenek680fe512010-05-05 00:55:23 +00002678
2679 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor92a524f2010-03-18 00:42:48 +00002680 // entering #includes or expanding macros.
Douglas Gregor02ded2a2010-03-18 15:23:44 +00002681 while (true) {
Douglas Gregor92a524f2010-03-18 00:42:48 +00002682 Token Tok;
2683 Lex.LexFromRawLexer(Tok);
Ted Kremenek680fe512010-05-05 00:55:23 +00002684
Douglas Gregor92a524f2010-03-18 00:42:48 +00002685 reprocess:
2686 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
2687 // We have found a preprocessing directive. Gobble it up so that we
2688 // don't see it while preprocessing these tokens later, but keep track of
2689 // all of the token locations inside this preprocessing directive so that
2690 // we can annotate them appropriately.
2691 //
2692 // FIXME: Some simple tests here could identify macro definitions and
2693 // #undefs, to provide specific cursor kinds for those.
2694 std::vector<SourceLocation> Locations;
2695 do {
2696 Locations.push_back(Tok.getLocation());
Ted Kremenek680fe512010-05-05 00:55:23 +00002697 Lex.LexFromRawLexer(Tok);
Douglas Gregor92a524f2010-03-18 00:42:48 +00002698 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenek680fe512010-05-05 00:55:23 +00002699
Douglas Gregor92a524f2010-03-18 00:42:48 +00002700 using namespace cxcursor;
2701 CXCursor Cursor
Ted Kremenek680fe512010-05-05 00:55:23 +00002702 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
2703 Locations.back()),
Ted Kremenek63ac5992010-05-05 00:55:15 +00002704 CXXUnit);
Douglas Gregor92a524f2010-03-18 00:42:48 +00002705 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
2706 Annotated[Locations[I].getRawEncoding()] = Cursor;
2707 }
Ted Kremenek680fe512010-05-05 00:55:23 +00002708
Douglas Gregor92a524f2010-03-18 00:42:48 +00002709 if (Tok.isAtStartOfLine())
2710 goto reprocess;
Ted Kremenek680fe512010-05-05 00:55:23 +00002711
Douglas Gregor92a524f2010-03-18 00:42:48 +00002712 continue;
2713 }
Ted Kremenek680fe512010-05-05 00:55:23 +00002714
Douglas Gregor02ded2a2010-03-18 15:23:44 +00002715 if (Tok.is(tok::eof))
Douglas Gregor92a524f2010-03-18 00:42:48 +00002716 break;
2717 }
Douglas Gregor065f8d12010-03-18 17:52:52 +00002718 }
Ted Kremenek680fe512010-05-05 00:55:23 +00002719
Douglas Gregor5272e802010-03-19 05:22:59 +00002720 // Annotate all of the source locations in the region of interest that map to
Ted Kremenek680fe512010-05-05 00:55:23 +00002721 // a specific cursor.
2722 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
2723 CXXUnit, RegionOfInterest);
2724 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002725}
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002726} // end: extern "C"
2727
2728//===----------------------------------------------------------------------===//
Ted Kremenekfb4961d2010-03-03 06:36:57 +00002729// Operations for querying linkage of a cursor.
2730//===----------------------------------------------------------------------===//
2731
2732extern "C" {
2733CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor5272e802010-03-19 05:22:59 +00002734 if (!clang_isDeclaration(cursor.kind))
2735 return CXLinkage_Invalid;
2736
Ted Kremenekfb4961d2010-03-03 06:36:57 +00002737 Decl *D = cxcursor::getCursorDecl(cursor);
2738 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
2739 switch (ND->getLinkage()) {
2740 case NoLinkage: return CXLinkage_NoLinkage;
2741 case InternalLinkage: return CXLinkage_Internal;
2742 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
2743 case ExternalLinkage: return CXLinkage_External;
2744 };
2745
2746 return CXLinkage_Invalid;
2747}
2748} // end: extern "C"
2749
2750//===----------------------------------------------------------------------===//
Ted Kremenek4ed29252010-04-12 21:22:16 +00002751// Operations for querying language of a cursor.
2752//===----------------------------------------------------------------------===//
2753
2754static CXLanguageKind getDeclLanguage(const Decl *D) {
2755 switch (D->getKind()) {
2756 default:
2757 break;
2758 case Decl::ImplicitParam:
2759 case Decl::ObjCAtDefsField:
2760 case Decl::ObjCCategory:
2761 case Decl::ObjCCategoryImpl:
2762 case Decl::ObjCClass:
2763 case Decl::ObjCCompatibleAlias:
Ted Kremenek4ed29252010-04-12 21:22:16 +00002764 case Decl::ObjCForwardProtocol:
2765 case Decl::ObjCImplementation:
2766 case Decl::ObjCInterface:
2767 case Decl::ObjCIvar:
2768 case Decl::ObjCMethod:
2769 case Decl::ObjCProperty:
2770 case Decl::ObjCPropertyImpl:
2771 case Decl::ObjCProtocol:
2772 return CXLanguage_ObjC;
2773 case Decl::CXXConstructor:
2774 case Decl::CXXConversion:
2775 case Decl::CXXDestructor:
2776 case Decl::CXXMethod:
2777 case Decl::CXXRecord:
2778 case Decl::ClassTemplate:
2779 case Decl::ClassTemplatePartialSpecialization:
2780 case Decl::ClassTemplateSpecialization:
2781 case Decl::Friend:
2782 case Decl::FriendTemplate:
2783 case Decl::FunctionTemplate:
2784 case Decl::LinkageSpec:
2785 case Decl::Namespace:
2786 case Decl::NamespaceAlias:
2787 case Decl::NonTypeTemplateParm:
2788 case Decl::StaticAssert:
Ted Kremenek4ed29252010-04-12 21:22:16 +00002789 case Decl::TemplateTemplateParm:
2790 case Decl::TemplateTypeParm:
2791 case Decl::UnresolvedUsingTypename:
2792 case Decl::UnresolvedUsingValue:
2793 case Decl::Using:
2794 case Decl::UsingDirective:
2795 case Decl::UsingShadow:
2796 return CXLanguage_CPlusPlus;
2797 }
2798
2799 return CXLanguage_C;
2800}
2801
2802extern "C" {
2803CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
2804 if (clang_isDeclaration(cursor.kind))
2805 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
2806
2807 return CXLanguage_Invalid;
2808}
2809} // end: extern "C"
2810
Ted Kremenek9cfe9e62010-05-17 20:06:56 +00002811
2812//===----------------------------------------------------------------------===//
2813// C++ AST instrospection.
2814//===----------------------------------------------------------------------===//
2815
2816extern "C" {
2817unsigned clang_CXXMethod_isStatic(CXCursor C) {
2818 if (!clang_isDeclaration(C.kind))
2819 return 0;
2820 CXXMethodDecl *D = dyn_cast<CXXMethodDecl>(cxcursor::getCursorDecl(C));
2821 return (D && D->isStatic()) ? 1 : 0;
Ted Kremenek0ed75492010-05-17 20:12:45 +00002822}
Ted Kremeneka10f1282010-05-18 22:32:15 +00002823
Ted Kremenek9cfe9e62010-05-17 20:06:56 +00002824} // end: extern "C"
2825
Ted Kremenek4ed29252010-04-12 21:22:16 +00002826//===----------------------------------------------------------------------===//
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00002827// CXString Operations.
2828//===----------------------------------------------------------------------===//
2829
2830extern "C" {
2831const char *clang_getCString(CXString string) {
2832 return string.Spelling;
2833}
2834
2835void clang_disposeString(CXString string) {
2836 if (string.MustFreeString && string.Spelling)
2837 free((void*)string.Spelling);
2838}
Ted Kremenekc0f3f722010-01-22 22:44:15 +00002839
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00002840} // end: extern "C"
Ted Kremenekc0f3f722010-01-22 22:44:15 +00002841
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00002842namespace clang { namespace cxstring {
2843CXString createCXString(const char *String, bool DupString){
2844 CXString Str;
2845 if (DupString) {
2846 Str.Spelling = strdup(String);
2847 Str.MustFreeString = 1;
2848 } else {
2849 Str.Spelling = String;
2850 Str.MustFreeString = 0;
2851 }
2852 return Str;
2853}
2854
2855CXString createCXString(llvm::StringRef String, bool DupString) {
2856 CXString Result;
2857 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
2858 char *Spelling = (char *)malloc(String.size() + 1);
2859 memmove(Spelling, String.data(), String.size());
2860 Spelling[String.size()] = 0;
2861 Result.Spelling = Spelling;
2862 Result.MustFreeString = 1;
2863 } else {
2864 Result.Spelling = String.data();
2865 Result.MustFreeString = 0;
2866 }
2867 return Result;
2868}
2869}}
2870
Ted Kremenekc0f3f722010-01-22 22:44:15 +00002871//===----------------------------------------------------------------------===//
2872// Misc. utility functions.
2873//===----------------------------------------------------------------------===//
Ted Kremenekf441baf2010-02-17 00:41:40 +00002874
Ted Kremenekc0f3f722010-01-22 22:44:15 +00002875extern "C" {
2876
Ted Kremeneka3e65702010-02-12 22:54:40 +00002877CXString clang_getClangVersion() {
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00002878 return createCXString(getClangFullVersion());
Ted Kremenekc0f3f722010-01-22 22:44:15 +00002879}
2880
2881} // end: extern "C"