blob: 10a57ae235d84a42bea8feef210063dbcedd7e5f [file] [log] [blame]
Ted Kremenekd2fa5662009-08-26 22:36:44 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00007//
Ted Kremenekd2fa5662009-08-26 22:36:44 +00008//===----------------------------------------------------------------------===//
9//
Ted Kremenekab188932010-01-05 19:32:54 +000010// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
Ted Kremenekd2fa5662009-08-26 22:36:44 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenekab188932010-01-05 19:32:54 +000015#include "CIndexer.h"
Ted Kremenek16c440a2010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremenekab188932010-01-05 19:32:54 +000017
Steve Naroff50398192009-08-28 15:28:48 +000018#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000019#include "clang/AST/StmtVisitor.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000020#include "clang/Lex/Lexer.h"
Douglas Gregor02465752009-10-16 21:24:31 +000021#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000022#include "llvm/System/Program.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000023
Ted Kremenekdb3d0da2010-01-05 20:55:39 +000024// Needed to define L_TMPNAM on some systems.
25#include <cstdio>
26
Steve Naroff50398192009-08-28 15:28:48 +000027using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000028using namespace clang::cxcursor;
Steve Naroff50398192009-08-28 15:28:48 +000029using namespace idx;
30
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000031//===----------------------------------------------------------------------===//
32// Crash Reporting.
33//===----------------------------------------------------------------------===//
34
35#ifdef __APPLE__
Ted Kremenek29b72842010-01-07 22:49:05 +000036#ifndef NDEBUG
37#define USE_CRASHTRACER
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000038#include "clang/Analysis/Support/SaveAndRestore.h"
39// Integrate with crash reporter.
40extern "C" const char *__crashreporter_info__;
Ted Kremenek29b72842010-01-07 22:49:05 +000041#define NUM_CRASH_STRINGS 16
42static unsigned crashtracer_counter = 0;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000043static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek29b72842010-01-07 22:49:05 +000044static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
45static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
46
47static unsigned SetCrashTracerInfo(const char *str,
48 llvm::SmallString<1024> &AggStr) {
49
Ted Kremenek254ba7c2010-01-07 23:13:53 +000050 unsigned slot = 0;
Ted Kremenek29b72842010-01-07 22:49:05 +000051 while (crashtracer_strings[slot]) {
52 if (++slot == NUM_CRASH_STRINGS)
53 slot = 0;
54 }
55 crashtracer_strings[slot] = str;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000056 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek29b72842010-01-07 22:49:05 +000057
58 // We need to create an aggregate string because multiple threads
59 // may be in this method at one time. The crash reporter string
60 // will attempt to overapproximate the set of in-flight invocations
61 // of this function. Race conditions can still cause this goal
62 // to not be achieved.
63 {
64 llvm::raw_svector_ostream Out(AggStr);
65 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
66 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
67 }
68 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
69 return slot;
70}
71
72static void ResetCrashTracerInfo(unsigned slot) {
Ted Kremenek254ba7c2010-01-07 23:13:53 +000073 unsigned max_slot = 0;
74 unsigned max_value = 0;
75
76 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
77
78 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
79 if (agg_crashtracer_strings[i] &&
80 crashtracer_counter_id[i] > max_value) {
81 max_slot = i;
82 max_value = crashtracer_counter_id[i];
Ted Kremenek29b72842010-01-07 22:49:05 +000083 }
Ted Kremenek254ba7c2010-01-07 23:13:53 +000084
85 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek29b72842010-01-07 22:49:05 +000086}
87
88namespace {
89class ArgsCrashTracerInfo {
90 llvm::SmallString<1024> CrashString;
91 llvm::SmallString<1024> AggregateString;
92 unsigned crashtracerSlot;
93public:
94 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
95 : crashtracerSlot(0)
96 {
97 {
98 llvm::raw_svector_ostream Out(CrashString);
99 Out << "ClangCIndex [createTranslationUnitFromSourceFile]: clang";
100 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
101 E=Args.end(); I!=E; ++I)
102 Out << ' ' << *I;
103 }
104 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
105 AggregateString);
106 }
107
108 ~ArgsCrashTracerInfo() {
109 ResetCrashTracerInfo(crashtracerSlot);
110 }
111};
112}
113#endif
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000114#endif
115
Douglas Gregor1db19de2010-01-19 21:36:55 +0000116typedef llvm::PointerIntPair<ASTContext *, 1, bool> CXSourceLocationPtr;
117
Douglas Gregor98258af2010-01-18 22:46:11 +0000118/// \brief Translate a Clang source location into a CIndex source location.
Douglas Gregor1db19de2010-01-19 21:36:55 +0000119static CXSourceLocation translateSourceLocation(ASTContext &Context,
120 SourceLocation Loc,
121 bool AtEnd = false) {
122 CXSourceLocationPtr Ptr(&Context, AtEnd);
123 CXSourceLocation Result = { Ptr.getOpaqueValue(), Loc.getRawEncoding() };
124 return Result;
125
126#if 0
Douglas Gregor98258af2010-01-18 22:46:11 +0000127 SourceLocation InstLoc = SourceMgr.getInstantiationLoc(Loc);
128 if (InstLoc.isInvalid()) {
129 CXSourceLocation Loc = { 0, 0, 0 };
130 return Loc;
131 }
132
133 CXSourceLocation Result;
134 Result.file
135 = (void*)SourceMgr.getFileEntryForID(SourceMgr.getFileID(InstLoc));
136 Result.line = SourceMgr.getInstantiationLineNumber(InstLoc);
137 Result.column = SourceMgr.getInstantiationColumnNumber(InstLoc);
138 return Result;
Douglas Gregor1db19de2010-01-19 21:36:55 +0000139#endif
Douglas Gregor98258af2010-01-18 22:46:11 +0000140}
141
Douglas Gregora7bde202010-01-19 00:34:46 +0000142/// \brief Translate a Clang source range into a CIndex source range.
Douglas Gregor1db19de2010-01-19 21:36:55 +0000143static CXSourceRange translateSourceRange(ASTContext &Context, SourceRange R) {
144 CXSourceRange Result = { &Context,
145 R.getBegin().getRawEncoding(),
146 R.getEnd().getRawEncoding() };
147 return Result;
148#if 0
Douglas Gregora7bde202010-01-19 00:34:46 +0000149 if (R.isInvalid()) {
150 CXSourceRange extent = { { 0, 0, 0 }, { 0, 0, 0 } };
151 return extent;
152 }
153
154 // FIXME: This is largely copy-paste from
155 ///TextDiagnosticPrinter::HighlightRange. When it is clear that this is
156 // what we want the two routines should be refactored.
157
158 SourceManager &SM = Context.getSourceManager();
159 SourceLocation Begin = SM.getInstantiationLoc(R.getBegin());
160 SourceLocation End = SM.getInstantiationLoc(R.getEnd());
161
162 // If the End location and the start location are the same and are a macro
163 // location, then the range was something that came from a macro expansion
164 // or _Pragma. If this is an object-like macro, the best we can do is to
165 // get the range. If this is a function-like macro, we'd also like to
166 // get the arguments.
167 if (Begin == End && R.getEnd().isMacroID())
168 End = SM.getInstantiationRange(R.getEnd()).second;
169
170 unsigned StartLineNo = SM.getInstantiationLineNumber(Begin);
171 unsigned EndLineNo = SM.getInstantiationLineNumber(End);
172
173 // Compute the column number of the start. Keep the column based at 1.
174 unsigned StartColNo = SM.getInstantiationColumnNumber(Begin);
175
176 // Compute the column number of the end.
177 unsigned EndColNo = SM.getInstantiationColumnNumber(End);
178 if (EndColNo) {
179 // Offset the end column by 1 so that we point to the last character
180 // in the last token.
181 --EndColNo;
182
183 // Add in the length of the token, so that we cover multi-char tokens.
184 EndColNo += Lexer::MeasureTokenLength(End, SM, Context.getLangOptions());
185 }
186
187 // Package up the line/column data and return to the caller.
188 const FileEntry *BeginFile = SM.getFileEntryForID(SM.getFileID(Begin));
189 const FileEntry *EndFile = SM.getFileEntryForID(SM.getFileID(End));
190 CXSourceRange extent = { { (void *)BeginFile, StartLineNo, StartColNo },
191 { (void *)EndFile, EndLineNo, EndColNo } };
192 return extent;
Douglas Gregor1db19de2010-01-19 21:36:55 +0000193#endif
Douglas Gregora7bde202010-01-19 00:34:46 +0000194}
195
Douglas Gregor1db19de2010-01-19 21:36:55 +0000196
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000197//===----------------------------------------------------------------------===//
198// Visitors.
199//===----------------------------------------------------------------------===//
200
Steve Naroff89922f82009-08-31 00:59:03 +0000201namespace {
Ted Kremenekab188932010-01-05 19:32:54 +0000202static enum CXCursorKind TranslateDeclRefExpr(DeclRefExpr *DRE) {
Steve Naroff4ade6d62009-09-23 17:52:52 +0000203 NamedDecl *D = DRE->getDecl();
204 if (isa<VarDecl>(D))
205 return CXCursor_VarRef;
206 else if (isa<FunctionDecl>(D))
207 return CXCursor_FunctionRef;
208 else if (isa<EnumConstantDecl>(D))
209 return CXCursor_EnumConstantRef;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000210 else
Douglas Gregor30122132010-01-19 22:07:56 +0000211 return CXCursor_UnexposedDecl;
Steve Naroff4ade6d62009-09-23 17:52:52 +0000212}
213
Steve Naroff89922f82009-08-31 00:59:03 +0000214// Translation Unit Visitor.
Ted Kremenekf1286182010-01-13 00:13:47 +0000215
Steve Naroff89922f82009-08-31 00:59:03 +0000216class TUVisitor : public DeclVisitor<TUVisitor> {
Ted Kremenekf1286182010-01-13 00:13:47 +0000217public:
218 typedef void (*Iterator)(void *, CXCursor, CXClientData);
219private:
220 void *Root; // CXDecl or CXTranslationUnit
221 Iterator Callback; // CXTranslationUnitIterator or CXDeclIterator.
Steve Naroff2b8ee6c2009-09-01 15:55:40 +0000222 CXClientData CData;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000223
Douglas Gregor7d1d49d2009-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;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000228
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000229 void Call(const CXCursor &C) {
Ted Kremenek70ee5422010-01-16 01:44:12 +0000230 if (clang_isInvalid(C.kind))
231 return;
232
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000233 if (const Decl *D = getCursorDecl(C)) {
234 // Filter any declarations that have a PCH level greater than what
235 // we allow.
236 if (D->getPCHLevel() > MaxPCHLevel)
237 return;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000238
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000239 // Filter any implicit declarations (since the source info will be bogus).
240 if (D->isImplicit())
241 return;
242 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000243
Ted Kremenekf1286182010-01-13 00:13:47 +0000244 Callback(Root, C, CData);
Steve Naroff2b8ee6c2009-09-01 15:55:40 +0000245 }
Ted Kremenekf1286182010-01-13 00:13:47 +0000246
Steve Naroff89922f82009-08-31 00:59:03 +0000247public:
Ted Kremenekf1286182010-01-13 00:13:47 +0000248 TUVisitor(void *root, Iterator cback, CXClientData D, unsigned MaxPCHLevel) :
249 Root(root), Callback(cback), CData(D), MaxPCHLevel(MaxPCHLevel) {}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000250
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000251 void VisitDecl(Decl *D);
Ted Kremenekf1286182010-01-13 00:13:47 +0000252 void VisitDeclContext(DeclContext *DC);
Ted Kremenekf1286182010-01-13 00:13:47 +0000253 void VisitTranslationUnitDecl(TranslationUnitDecl *D);
Ted Kremenekf1286182010-01-13 00:13:47 +0000254};
Ted Kremenekef7fdc62009-11-17 07:02:15 +0000255
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000256void TUVisitor::VisitDecl(Decl *D) {
257 Call(MakeCXCursor(D));
258}
259
Ted Kremenekf1286182010-01-13 00:13:47 +0000260void TUVisitor::VisitDeclContext(DeclContext *DC) {
261 for (DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
262 I != E; ++I)
263 Visit(*I);
264}
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000265
Ted Kremenekf1286182010-01-13 00:13:47 +0000266void TUVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
267 VisitDeclContext(dyn_cast<DeclContext>(D));
268}
Steve Naroff89922f82009-08-31 00:59:03 +0000269
Steve Naroffc857ea42009-09-02 13:28:54 +0000270// Declaration visitor.
271class CDeclVisitor : public DeclVisitor<CDeclVisitor> {
272 CXDecl CDecl;
273 CXDeclIterator Callback;
274 CXClientData CData;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000275
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000276 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
277 // to the visitor. Declarations with a PCH level greater than this value will
278 // be suppressed.
279 unsigned MaxPCHLevel;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000280
Steve Naroffc857ea42009-09-02 13:28:54 +0000281 void Call(enum CXCursorKind CK, NamedDecl *ND) {
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000282 // Disable the callback when the context is equal to the visiting decl.
283 if (CDecl == ND && !clang_isReference(CK))
284 return;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000285
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000286 // Filter any declarations that have a PCH level greater than what we allow.
287 if (ND->getPCHLevel() > MaxPCHLevel)
288 return;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000289
Douglas Gregor283cae32010-01-15 21:56:13 +0000290 CXCursor C = { CK, { ND, 0, 0 } };
Steve Naroffc857ea42009-09-02 13:28:54 +0000291 Callback(CDecl, C, CData);
292 }
Douglas Gregor2e331b92010-01-16 14:00:32 +0000293
Steve Naroff89922f82009-08-31 00:59:03 +0000294public:
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000295 CDeclVisitor(CXDecl C, CXDeclIterator cback, CXClientData D,
296 unsigned MaxPCHLevel) :
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000297 CDecl(C), Callback(cback), CData(D), MaxPCHLevel(MaxPCHLevel) {}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000298
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000299 void VisitDeclContext(DeclContext *DC);
300 void VisitEnumConstantDecl(EnumConstantDecl *ND);
301 void VisitFieldDecl(FieldDecl *ND);
302 void VisitFunctionDecl(FunctionDecl *ND);
303 void VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
304 void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
305 void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
306 void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
307 void VisitObjCIvarDecl(ObjCIvarDecl *ND);
308 void VisitObjCMethodDecl(ObjCMethodDecl *ND);
309 void VisitObjCPropertyDecl(ObjCPropertyDecl *ND);
310 void VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
311 void VisitParmVarDecl(ParmVarDecl *ND);
312 void VisitTagDecl(TagDecl *D);
313 void VisitVarDecl(VarDecl *ND);
Steve Naroff89922f82009-08-31 00:59:03 +0000314};
Ted Kremenekab188932010-01-05 19:32:54 +0000315} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000316
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000317void CDeclVisitor::VisitDeclContext(DeclContext *DC) {
318 for (DeclContext::decl_iterator
319 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I)
320 Visit(*I);
321}
322
323void CDeclVisitor::VisitEnumConstantDecl(EnumConstantDecl *ND) {
324 Call(CXCursor_EnumConstantDecl, ND);
325}
326
327void CDeclVisitor::VisitFieldDecl(FieldDecl *ND) {
328 Call(CXCursor_FieldDecl, ND);
329}
330
331void CDeclVisitor::VisitFunctionDecl(FunctionDecl *ND) {
332 if (ND->isThisDeclarationADefinition()) {
333 VisitDeclContext(dyn_cast<DeclContext>(ND));
334#if 0
335 // Not currently needed.
336 CompoundStmt *Body = dyn_cast<CompoundStmt>(ND->getBody());
337 CRefVisitor RVisit(CDecl, Callback, CData);
338 RVisit.Visit(Body);
339#endif
340 }
341}
342
343void CDeclVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
344 // Issue callbacks for the containing class.
Douglas Gregor1adb0822010-01-16 17:14:40 +0000345 Callback(CDecl,
346 MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation()),
347 CData);
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000348 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
349 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
350 E = ND->protocol_end(); I != E; ++I, ++PL)
351 Callback(CDecl, MakeCursorObjCProtocolRef(*I, *PL), CData);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000352 VisitDeclContext(dyn_cast<DeclContext>(ND));
353}
354
355void CDeclVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
356 VisitDeclContext(dyn_cast<DeclContext>(D));
357}
358
359void CDeclVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
360 VisitDeclContext(dyn_cast<DeclContext>(D));
361}
362
363void CDeclVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
364 // Issue callbacks for super class.
365 if (D->getSuperClass())
Douglas Gregor2e331b92010-01-16 14:00:32 +0000366 Callback(CDecl,
367 MakeCursorObjCSuperClassRef(D->getSuperClass(),
368 D->getSuperClassLoc()),
369 CData);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000370
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000371 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
372 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
373 E = D->protocol_end(); I != E; ++I, ++PL)
374 Callback(CDecl, MakeCursorObjCProtocolRef(*I, *PL), CData);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000375 VisitDeclContext(dyn_cast<DeclContext>(D));
376}
377
378void CDeclVisitor::VisitObjCIvarDecl(ObjCIvarDecl *ND) {
379 Call(CXCursor_ObjCIvarDecl, ND);
380}
381
382void CDeclVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregorb6998662010-01-19 19:34:47 +0000383 Call(ND->isInstanceMethod() ? CXCursor_ObjCInstanceMethodDecl
384 : CXCursor_ObjCClassMethodDecl, ND);
385
386 if (ND->getBody())
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000387 VisitDeclContext(dyn_cast<DeclContext>(ND));
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000388}
389
390void CDeclVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *ND) {
391 Call(CXCursor_ObjCPropertyDecl, ND);
392}
393
394void CDeclVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000395 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000396 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000397 E = PID->protocol_end(); I != E; ++I, ++PL)
398 Callback(CDecl, MakeCursorObjCProtocolRef(*I, *PL), CData);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000399
400 VisitDeclContext(dyn_cast<DeclContext>(PID));
401}
402
403void CDeclVisitor::VisitParmVarDecl(ParmVarDecl *ND) {
404 Call(CXCursor_ParmDecl, ND);
405}
406
407void CDeclVisitor::VisitTagDecl(TagDecl *D) {
408 VisitDeclContext(dyn_cast<DeclContext>(D));
409}
410
411void CDeclVisitor::VisitVarDecl(VarDecl *ND) {
412 Call(CXCursor_VarDecl, ND);
413}
414
Daniel Dunbar140fce22010-01-12 02:34:07 +0000415CXString CIndexer::createCXString(const char *String, bool DupString){
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000416 CXString Str;
417 if (DupString) {
418 Str.Spelling = strdup(String);
419 Str.MustFreeString = 1;
420 } else {
421 Str.Spelling = String;
422 Str.MustFreeString = 0;
423 }
424 return Str;
425}
426
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000427extern "C" {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000428CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000429 int displayDiagnostics) {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000430 CIndexer *CIdxr = new CIndexer(new Program());
431 if (excludeDeclarationsFromPCH)
432 CIdxr->setOnlyLocalDecls();
433 if (displayDiagnostics)
434 CIdxr->setDisplayDiagnostics();
435 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +0000436}
437
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000438void clang_disposeIndex(CXIndex CIdx) {
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000439 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000440 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000441}
442
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000443void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
444 assert(CIdx && "Passed null CXIndex");
445 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
446 CXXIdx->setUseExternalASTGeneration(value);
447}
448
Steve Naroff50398192009-08-28 15:28:48 +0000449// FIXME: need to pass back error info.
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000450CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
451 const char *ast_filename) {
Steve Naroff50398192009-08-28 15:28:48 +0000452 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000453 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000454
Daniel Dunbar5262fda2009-12-03 01:45:44 +0000455 return ASTUnit::LoadFromPCHFile(ast_filename, CXXIdx->getDiags(),
456 CXXIdx->getOnlyLocalDecls(),
457 /* UseBumpAllocator = */ true);
Steve Naroff600866c2009-08-27 19:51:58 +0000458}
459
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000460CXTranslationUnit
461clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
462 const char *source_filename,
463 int num_command_line_args,
464 const char **command_line_args) {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000465 assert(CIdx && "Passed null CXIndex");
466 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
467
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000468 if (!CXXIdx->getUseExternalASTGeneration()) {
469 llvm::SmallVector<const char *, 16> Args;
470
471 // The 'source_filename' argument is optional. If the caller does not
472 // specify it then it is assumed that the source file is specified
473 // in the actual argument list.
474 if (source_filename)
475 Args.push_back(source_filename);
476 Args.insert(Args.end(), command_line_args,
477 command_line_args + num_command_line_args);
478
Daniel Dunbar94220972009-12-05 02:17:18 +0000479 unsigned NumErrors = CXXIdx->getDiags().getNumErrors();
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000480
Ted Kremenek29b72842010-01-07 22:49:05 +0000481#ifdef USE_CRASHTRACER
482 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000483#endif
484
Daniel Dunbar94220972009-12-05 02:17:18 +0000485 llvm::OwningPtr<ASTUnit> Unit(
486 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Daniel Dunbar869824e2009-12-13 03:46:13 +0000487 CXXIdx->getDiags(),
488 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +0000489 CXXIdx->getOnlyLocalDecls(),
490 /* UseBumpAllocator = */ true));
Ted Kremenek29b72842010-01-07 22:49:05 +0000491
Daniel Dunbar94220972009-12-05 02:17:18 +0000492 // FIXME: Until we have broader testing, just drop the entire AST if we
493 // encountered an error.
494 if (NumErrors != CXXIdx->getDiags().getNumErrors())
495 return 0;
496
497 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000498 }
499
Ted Kremenek139ba862009-10-22 00:03:57 +0000500 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000501 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000502
Ted Kremenek139ba862009-10-22 00:03:57 +0000503 // First add the complete path to the 'clang' executable.
504 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000505 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000506
Ted Kremenek139ba862009-10-22 00:03:57 +0000507 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000508 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000509
Ted Kremenek139ba862009-10-22 00:03:57 +0000510 // The 'source_filename' argument is optional. If the caller does not
511 // specify it then it is assumed that the source file is specified
512 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000513 if (source_filename)
514 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +0000515
Steve Naroff37b5ac22009-10-15 20:50:09 +0000516 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +0000517 argv.push_back("-o");
Steve Naroff37b5ac22009-10-15 20:50:09 +0000518 char astTmpFile[L_tmpnam];
Ted Kremenek74cd0692009-10-15 23:21:22 +0000519 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +0000520
521 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
522 for (int i = 0; i < num_command_line_args; ++i)
523 if (const char *arg = command_line_args[i]) {
524 if (strcmp(arg, "-o") == 0) {
525 ++i; // Also skip the matching argument.
526 continue;
527 }
528 if (strcmp(arg, "-emit-ast") == 0 ||
529 strcmp(arg, "-c") == 0 ||
530 strcmp(arg, "-fsyntax-only") == 0) {
531 continue;
532 }
533
534 // Keep the argument.
535 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000536 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000537
Ted Kremenek139ba862009-10-22 00:03:57 +0000538 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000539 argv.push_back(NULL);
540
Ted Kremenekfeb15e32009-10-26 22:14:08 +0000541 // Invoke 'clang'.
542 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
543 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +0000544 std::string ErrMsg;
Ted Kremenekc46e4632009-10-19 22:27:32 +0000545 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DevNull, NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +0000546 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
547 /* redirects */ !CXXIdx->getDisplayDiagnostics() ? &Redirects[0] : NULL,
548 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000549
Ted Kremenek0854d702009-11-10 19:18:52 +0000550 if (CXXIdx->getDisplayDiagnostics() && !ErrMsg.empty()) {
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000551 llvm::errs() << "clang_createTranslationUnitFromSourceFile: " << ErrMsg
Daniel Dunbaracca7252009-11-30 20:42:49 +0000552 << '\n' << "Arguments: \n";
Ted Kremenek379afec2009-10-22 03:24:01 +0000553 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Ted Kremenek779e5f42009-10-26 22:08:39 +0000554 I!=E; ++I) {
555 if (*I)
556 llvm::errs() << ' ' << *I << '\n';
557 }
558 llvm::errs() << '\n';
Ted Kremenek379afec2009-10-22 03:24:01 +0000559 }
Benjamin Kramer0829a832009-10-18 11:19:36 +0000560
Steve Naroff37b5ac22009-10-15 20:50:09 +0000561 // Finally, we create the translation unit from the ast file.
Steve Naroffe19944c2009-10-15 22:23:48 +0000562 ASTUnit *ATU = static_cast<ASTUnit *>(
Daniel Dunbaracca7252009-11-30 20:42:49 +0000563 clang_createTranslationUnit(CIdx, astTmpFile));
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000564 if (ATU)
565 ATU->unlinkTemporaryFile();
Steve Naroffe19944c2009-10-15 22:23:48 +0000566 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +0000567}
568
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000569void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000570 assert(CTUnit && "Passed null CXTranslationUnit");
571 delete static_cast<ASTUnit *>(CTUnit);
572}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000573
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000574CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000575 assert(CTUnit && "Passed null CXTranslationUnit");
Steve Naroff77accc12009-09-03 18:19:54 +0000576 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenek4b333d22010-01-12 00:36:38 +0000577 return CIndexer::createCXString(CXXUnit->getOriginalSourceFileName().c_str(),
578 true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000579}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +0000580
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000581void clang_loadTranslationUnit(CXTranslationUnit CTUnit,
Steve Naroffc857ea42009-09-02 13:28:54 +0000582 CXTranslationUnitIterator callback,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000583 CXClientData CData) {
Steve Naroff50398192009-08-28 15:28:48 +0000584 assert(CTUnit && "Passed null CXTranslationUnit");
585 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
586 ASTContext &Ctx = CXXUnit->getASTContext();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000587
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000588 unsigned PCHLevel = Decl::MaxPCHLevel;
589
590 // Set the PCHLevel to filter out unwanted decls if requested.
591 if (CXXUnit->getOnlyLocalDecls()) {
592 PCHLevel = 0;
593
594 // If the main input was an AST, bump the level.
595 if (CXXUnit->isMainFileAST())
596 ++PCHLevel;
597 }
598
599 TUVisitor DVisit(CTUnit, callback, CData, PCHLevel);
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000600
601 // If using a non-AST based ASTUnit, iterate over the stored list of top-level
602 // decls.
603 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls()) {
604 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
605 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
606 ie = TLDs.end(); it != ie; ++it) {
607 DVisit.Visit(*it);
608 }
609 } else
610 DVisit.Visit(Ctx.getTranslationUnitDecl());
Steve Naroff600866c2009-08-27 19:51:58 +0000611}
612
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000613void clang_loadDeclaration(CXDecl Dcl,
614 CXDeclIterator callback,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000615 CXClientData CData) {
Steve Naroffc857ea42009-09-02 13:28:54 +0000616 assert(Dcl && "Passed null CXDecl");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000617
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000618 CDeclVisitor DVisit(Dcl, callback, CData,
619 static_cast<Decl *>(Dcl)->getPCHLevel());
Steve Naroffc857ea42009-09-02 13:28:54 +0000620 DVisit.Visit(static_cast<Decl *>(Dcl));
Steve Naroff600866c2009-08-27 19:51:58 +0000621}
Ted Kremenekfb480492010-01-13 21:46:36 +0000622} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +0000623
Ted Kremenekfb480492010-01-13 21:46:36 +0000624//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +0000625// CXSourceLocation and CXSourceRange Operations.
626//===----------------------------------------------------------------------===//
627
628void clang_getInstantiationLocation(CXSourceLocation location,
629 CXFile *file,
630 unsigned *line,
631 unsigned *column) {
632 CXSourceLocationPtr Ptr
633 = CXSourceLocationPtr::getFromOpaqueValue(location.ptr_data);
634 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
635
636 if (!Ptr.getPointer() || Loc.isInvalid()) {
637 if (file)
638 *file = 0;
639 if (line)
640 *line = 0;
641 if (column)
642 *column = 0;
643 return;
644 }
645
646 // FIXME: This is largely copy-paste from
647 ///TextDiagnosticPrinter::HighlightRange. When it is clear that this is
648 // what we want the two routines should be refactored.
649 ASTContext &Context = *Ptr.getPointer();
650 SourceManager &SM = Context.getSourceManager();
651 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
652
653 if (Ptr.getInt()) {
654 // We want the last character in this location, so we will adjust
655 // the instantiation location accordingly.
656
657 // If the location is from a macro instantiation, get the end of
658 // the instantiation range.
659 if (Loc.isMacroID())
660 InstLoc = SM.getInstantiationRange(Loc).second;
661
662 // Measure the length token we're pointing at, so we can adjust
663 // the physical location in the file to point at the last
664 // character.
665 // FIXME: This won't cope with trigraphs or escaped newlines
666 // well. For that, we actually need a preprocessor, which isn't
667 // currently available here. Eventually, we'll switch the pointer
668 // data of CXSourceLocation/CXSourceRange to a translation unit
669 // (CXXUnit), so that the preprocessor will be available here. At
670 // that point, we can use Preprocessor::getLocForEndOfToken().
671 unsigned Length = Lexer::MeasureTokenLength(InstLoc, SM,
672 Context.getLangOptions());
673 if (Length > 0)
674 InstLoc = InstLoc.getFileLocWithOffset(Length - 1);
675 }
676
677 if (file)
678 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
679 if (line)
680 *line = SM.getInstantiationLineNumber(InstLoc);
681 if (column)
682 *column = SM.getInstantiationColumnNumber(InstLoc);
683}
684
685CXSourceLocation clang_getRangeStart(CXSourceRange range) {
686 CXSourceLocation Result = { range.ptr_data, range.begin_int_data };
687 return Result;
688}
689
690CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
691 llvm::PointerIntPair<ASTContext *, 1, bool> Ptr;
692 Ptr.setPointer(static_cast<ASTContext *>(range.ptr_data));
693 Ptr.setInt(true);
694 CXSourceLocation Result = { Ptr.getOpaqueValue(), range.end_int_data };
695 return Result;
696}
697
698//===----------------------------------------------------------------------===//
Steve Naroff600866c2009-08-27 19:51:58 +0000699// CXDecl Operations.
Ted Kremenekfb480492010-01-13 21:46:36 +0000700//===----------------------------------------------------------------------===//
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000701
Ted Kremenekfb480492010-01-13 21:46:36 +0000702static const FileEntry *getFileEntryFromSourceLocation(SourceManager &SMgr,
703 SourceLocation SLoc) {
704 FileID FID;
705 if (SLoc.isFileID())
706 FID = SMgr.getFileID(SLoc);
707 else
708 FID = SMgr.getDecomposedSpellingLoc(SLoc).first;
709 return SMgr.getFileEntryForID(FID);
710}
711
712extern "C" {
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000713CXString clang_getDeclSpelling(CXDecl AnonDecl) {
Steve Naroff89922f82009-08-31 00:59:03 +0000714 assert(AnonDecl && "Passed null CXDecl");
Douglas Gregor30122132010-01-19 22:07:56 +0000715 Decl *D = static_cast<Decl *>(AnonDecl);
716 NamedDecl *ND = dyn_cast<NamedDecl>(D);
717 if (!ND)
718 return CIndexer::createCXString("");
Steve Naroffef0cef62009-11-09 17:45:52 +0000719
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000720 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenek4b333d22010-01-12 00:36:38 +0000721 return CIndexer::createCXString(OMD->getSelector().getAsString().c_str(),
722 true);
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000723
724 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Steve Naroff0d69b8c2009-10-29 21:11:04 +0000725 // No, this isn't the same as the code below. getIdentifier() is non-virtual
726 // and returns different names. NamedDecl returns the class name and
727 // ObjCCategoryImplDecl returns the category name.
Ted Kremenek4b333d22010-01-12 00:36:38 +0000728 return CIndexer::createCXString(CIMP->getIdentifier()->getNameStart());
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000729
730 if (ND->getIdentifier())
Ted Kremenek4b333d22010-01-12 00:36:38 +0000731 return CIndexer::createCXString(ND->getIdentifier()->getNameStart());
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000732
Ted Kremenek4b333d22010-01-12 00:36:38 +0000733 return CIndexer::createCXString("");
Steve Naroff600866c2009-08-27 19:51:58 +0000734}
Steve Narofff334b4e2009-09-02 18:26:48 +0000735
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000736unsigned clang_getDeclLine(CXDecl AnonDecl) {
Steve Naroff699a07d2009-09-25 21:32:34 +0000737 assert(AnonDecl && "Passed null CXDecl");
738 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
739 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
740 return SourceMgr.getSpellingLineNumber(ND->getLocation());
741}
742
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000743unsigned clang_getDeclColumn(CXDecl AnonDecl) {
Steve Naroff699a07d2009-09-25 21:32:34 +0000744 assert(AnonDecl && "Passed null CXDecl");
745 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
746 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Steve Naroff74165242009-09-25 22:15:54 +0000747 return SourceMgr.getSpellingColumnNumber(ND->getLocation());
Steve Naroff699a07d2009-09-25 21:32:34 +0000748}
Ted Kremenekfe6fd3d2010-01-05 23:18:49 +0000749
Douglas Gregor3c7313d2010-01-18 22:13:09 +0000750CXSourceRange clang_getDeclExtent(CXDecl AnonDecl) {
Douglas Gregora7bde202010-01-19 00:34:46 +0000751 return clang_getCursorExtent(clang_getCursorFromDecl(AnonDecl));
Ted Kremenekfe6fd3d2010-01-05 23:18:49 +0000752}
Steve Naroff699a07d2009-09-25 21:32:34 +0000753
Ted Kremenek6ab9db12010-01-08 17:11:32 +0000754const char *clang_getDeclSource(CXDecl AnonDecl) {
755 assert(AnonDecl && "Passed null CXDecl");
756 FileEntry *FEnt = static_cast<FileEntry *>(clang_getDeclSourceFile(AnonDecl));
757 assert(FEnt && "Cannot find FileEntry for Decl");
758 return clang_getFileName(FEnt);
759}
760
Steve Naroff88145032009-10-27 14:35:18 +0000761
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000762CXFile clang_getDeclSourceFile(CXDecl AnonDecl) {
Steve Naroff88145032009-10-27 14:35:18 +0000763 assert(AnonDecl && "Passed null CXDecl");
Steve Naroffee9405e2009-09-25 21:45:39 +0000764 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
765 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Steve Naroff88145032009-10-27 14:35:18 +0000766 return (void *)getFileEntryFromSourceLocation(SourceMgr, ND->getLocation());
767}
Ted Kremenekfb480492010-01-13 21:46:36 +0000768} // end: extern "C"
Steve Naroff88145032009-10-27 14:35:18 +0000769
Ted Kremenekfb480492010-01-13 21:46:36 +0000770//===----------------------------------------------------------------------===//
771// CXFile Operations.
772//===----------------------------------------------------------------------===//
773
774extern "C" {
Steve Naroff88145032009-10-27 14:35:18 +0000775const char *clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +0000776 if (!SFile)
777 return 0;
778
Steve Naroff88145032009-10-27 14:35:18 +0000779 assert(SFile && "Passed null CXFile");
780 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
781 return FEnt->getName();
782}
783
784time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +0000785 if (!SFile)
786 return 0;
787
Steve Naroff88145032009-10-27 14:35:18 +0000788 assert(SFile && "Passed null CXFile");
789 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
790 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +0000791}
Ted Kremenekfb480492010-01-13 21:46:36 +0000792} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +0000793
Ted Kremenekfb480492010-01-13 21:46:36 +0000794//===----------------------------------------------------------------------===//
795// CXCursor Operations.
796//===----------------------------------------------------------------------===//
797
Ted Kremenekfb480492010-01-13 21:46:36 +0000798static Decl *getDeclFromExpr(Stmt *E) {
799 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
800 return RefExpr->getDecl();
801 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
802 return ME->getMemberDecl();
803 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
804 return RE->getDecl();
805
806 if (CallExpr *CE = dyn_cast<CallExpr>(E))
807 return getDeclFromExpr(CE->getCallee());
808 if (CastExpr *CE = dyn_cast<CastExpr>(E))
809 return getDeclFromExpr(CE->getSubExpr());
810 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
811 return OME->getMethodDecl();
812
813 return 0;
814}
815
816extern "C" {
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000817CXString clang_getCursorSpelling(CXCursor C) {
Daniel Dunbarc81d7182010-01-18 17:52:42 +0000818 assert(getCursorDecl(C) && "CXCursor has null decl");
Steve Narofff334b4e2009-09-02 18:26:48 +0000819 if (clang_isReference(C.kind)) {
820 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +0000821 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +0000822 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
823 return CIndexer::createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +0000824 }
825 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +0000826 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
827 return CIndexer::createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +0000828 }
829 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000830 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +0000831 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenek4b333d22010-01-12 00:36:38 +0000832 return CIndexer::createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +0000833 }
834 case CXCursor_ObjCSelectorRef: {
Douglas Gregor283cae32010-01-15 21:56:13 +0000835 ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(getCursorStmt(C));
Douglas Gregorf46034a2010-01-18 23:41:10 +0000836 assert(OME && "getCursorSpelling(): Missing message expr");
Ted Kremenek4b333d22010-01-12 00:36:38 +0000837 return CIndexer::createCXString(OME->getSelector().getAsString().c_str(),
838 true);
Daniel Dunbaracca7252009-11-30 20:42:49 +0000839 }
840 case CXCursor_VarRef:
841 case CXCursor_FunctionRef:
842 case CXCursor_EnumConstantRef: {
Douglas Gregor283cae32010-01-15 21:56:13 +0000843 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(getCursorStmt(C));
Douglas Gregorf46034a2010-01-18 23:41:10 +0000844 assert(DRE && "getCursorSpelling(): Missing decl ref expr");
Ted Kremenek4b333d22010-01-12 00:36:38 +0000845 return CIndexer::createCXString(DRE->getDecl()->getIdentifier()
846 ->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +0000847 }
848 default:
Ted Kremenek4b333d22010-01-12 00:36:38 +0000849 return CIndexer::createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +0000850 }
851 }
Douglas Gregor283cae32010-01-15 21:56:13 +0000852 return clang_getDeclSpelling(getCursorDecl(C));
Steve Narofff334b4e2009-09-02 18:26:48 +0000853}
854
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000855const char *clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +0000856 switch (Kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +0000857 case CXCursor_FunctionDecl: return "FunctionDecl";
858 case CXCursor_TypedefDecl: return "TypedefDecl";
859 case CXCursor_EnumDecl: return "EnumDecl";
860 case CXCursor_EnumConstantDecl: return "EnumConstantDecl";
861 case CXCursor_StructDecl: return "StructDecl";
862 case CXCursor_UnionDecl: return "UnionDecl";
863 case CXCursor_ClassDecl: return "ClassDecl";
864 case CXCursor_FieldDecl: return "FieldDecl";
865 case CXCursor_VarDecl: return "VarDecl";
866 case CXCursor_ParmDecl: return "ParmDecl";
867 case CXCursor_ObjCInterfaceDecl: return "ObjCInterfaceDecl";
868 case CXCursor_ObjCCategoryDecl: return "ObjCCategoryDecl";
869 case CXCursor_ObjCProtocolDecl: return "ObjCProtocolDecl";
870 case CXCursor_ObjCPropertyDecl: return "ObjCPropertyDecl";
871 case CXCursor_ObjCIvarDecl: return "ObjCIvarDecl";
872 case CXCursor_ObjCInstanceMethodDecl: return "ObjCInstanceMethodDecl";
873 case CXCursor_ObjCClassMethodDecl: return "ObjCClassMethodDecl";
Douglas Gregorb6998662010-01-19 19:34:47 +0000874 case CXCursor_ObjCImplementationDecl: return "ObjCImplementationDecl";
875 case CXCursor_ObjCCategoryImplDecl: return "ObjCCategoryImplDecl";
Douglas Gregor30122132010-01-19 22:07:56 +0000876 case CXCursor_UnexposedDecl: return "UnexposedDecl";
Daniel Dunbaracca7252009-11-30 20:42:49 +0000877 case CXCursor_ObjCSuperClassRef: return "ObjCSuperClassRef";
878 case CXCursor_ObjCProtocolRef: return "ObjCProtocolRef";
879 case CXCursor_ObjCClassRef: return "ObjCClassRef";
880 case CXCursor_ObjCSelectorRef: return "ObjCSelectorRef";
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000881
Daniel Dunbaracca7252009-11-30 20:42:49 +0000882 case CXCursor_VarRef: return "VarRef";
883 case CXCursor_FunctionRef: return "FunctionRef";
884 case CXCursor_EnumConstantRef: return "EnumConstantRef";
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000885
Daniel Dunbaracca7252009-11-30 20:42:49 +0000886 case CXCursor_InvalidFile: return "InvalidFile";
887 case CXCursor_NoDeclFound: return "NoDeclFound";
888 case CXCursor_NotImplemented: return "NotImplemented";
Steve Naroff89922f82009-08-31 00:59:03 +0000889 }
Ted Kremenekdeb06bd2010-01-16 02:02:09 +0000890
891 llvm_unreachable("Unhandled CXCursorKind");
892 return NULL;
Steve Naroff600866c2009-08-27 19:51:58 +0000893}
Steve Naroff89922f82009-08-31 00:59:03 +0000894
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000895CXCursor clang_getCursor(CXTranslationUnit CTUnit, const char *source_name,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000896 unsigned line, unsigned column) {
Steve Naroff9efa7672009-09-04 15:44:05 +0000897 assert(CTUnit && "Passed null CXTranslationUnit");
898 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000899
Steve Naroff9efa7672009-09-04 15:44:05 +0000900 FileManager &FMgr = CXXUnit->getFileManager();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000901 const FileEntry *File = FMgr.getFile(source_name,
902 source_name+strlen(source_name));
Ted Kremenekf4629892010-01-14 01:51:23 +0000903 if (!File)
904 return clang_getNullCursor();
905
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000906 SourceLocation SLoc =
Steve Naroff9efa7672009-09-04 15:44:05 +0000907 CXXUnit->getSourceManager().getLocation(File, line, column);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000908
Steve Narofff96b5242009-10-28 20:44:47 +0000909 ASTLocation LastLoc = CXXUnit->getLastASTLocation();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000910 ASTLocation ALoc = ResolveLocationInAST(CXXUnit->getASTContext(), SLoc,
Steve Narofff96b5242009-10-28 20:44:47 +0000911 &LastLoc);
Ted Kremenekf4629892010-01-14 01:51:23 +0000912
913 // FIXME: This doesn't look thread-safe.
Steve Narofff96b5242009-10-28 20:44:47 +0000914 if (ALoc.isValid())
915 CXXUnit->setLastASTLocation(ALoc);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000916
Argyrios Kyrtzidisf4526e32009-09-29 19:44:27 +0000917 Decl *Dcl = ALoc.getParentDecl();
Argyrios Kyrtzidis05a76512009-09-29 19:45:58 +0000918 if (ALoc.isNamedRef())
919 Dcl = ALoc.AsNamedRef().ND;
Argyrios Kyrtzidisf4526e32009-09-29 19:44:27 +0000920 Stmt *Stm = ALoc.dyn_AsStmt();
Steve Naroff4ade6d62009-09-23 17:52:52 +0000921 if (Dcl) {
922 if (Stm) {
Ted Kremenekfb480492010-01-13 21:46:36 +0000923 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Stm))
Douglas Gregorf46034a2010-01-18 23:41:10 +0000924 return MakeCXCursor(TranslateDeclRefExpr(DRE), Dcl, Stm,
925 CXXUnit->getASTContext());
Ted Kremenekfb480492010-01-13 21:46:36 +0000926 else if (ObjCMessageExpr *MExp = dyn_cast<ObjCMessageExpr>(Stm))
Douglas Gregorf46034a2010-01-18 23:41:10 +0000927 return MakeCXCursor(CXCursor_ObjCSelectorRef, Dcl, MExp,
928 CXXUnit->getASTContext());
Steve Naroff4ade6d62009-09-23 17:52:52 +0000929 // Fall through...treat as a decl, not a ref.
930 }
Steve Naroff85e2db72009-10-01 00:31:07 +0000931 if (ALoc.isNamedRef()) {
Douglas Gregor1adb0822010-01-16 17:14:40 +0000932 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(Dcl))
933 return MakeCursorObjCClassRef(Class, ALoc.AsNamedRef().Loc);
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000934 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(Dcl))
935 return MakeCursorObjCProtocolRef(Proto, ALoc.AsNamedRef().Loc);
Steve Naroff85e2db72009-10-01 00:31:07 +0000936 }
Ted Kremenek70ee5422010-01-16 01:44:12 +0000937 return MakeCXCursor(Dcl);
Steve Naroff77128dd2009-09-15 20:25:34 +0000938 }
Ted Kremenekfb480492010-01-13 21:46:36 +0000939 return MakeCXCursor(CXCursor_NoDeclFound, 0);
Steve Naroff600866c2009-08-27 19:51:58 +0000940}
941
Ted Kremenek73885552009-11-17 19:28:59 +0000942CXCursor clang_getNullCursor(void) {
Ted Kremenekfb480492010-01-13 21:46:36 +0000943 return MakeCXCursor(CXCursor_InvalidFile, 0);
Ted Kremenek73885552009-11-17 19:28:59 +0000944}
945
946unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +0000947 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +0000948}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000949
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000950CXCursor clang_getCursorFromDecl(CXDecl AnonDecl) {
Steve Naroff77128dd2009-09-15 20:25:34 +0000951 assert(AnonDecl && "Passed null CXDecl");
Ted Kremenekdeb06bd2010-01-16 02:02:09 +0000952 return MakeCXCursor(static_cast<NamedDecl *>(AnonDecl));
Steve Naroff77128dd2009-09-15 20:25:34 +0000953}
954
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000955unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +0000956 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
957}
958
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000959unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +0000960 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
961}
Steve Naroff2d4d6292009-08-31 14:26:51 +0000962
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000963unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +0000964 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
965}
966
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000967CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +0000968 return C.kind;
969}
970
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000971CXDecl clang_getCursorDecl(CXCursor C) {
Douglas Gregorb6998662010-01-19 19:34:47 +0000972 if (clang_isDeclaration(C.kind))
Douglas Gregor283cae32010-01-15 21:56:13 +0000973 return getCursorDecl(C);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000974
Steve Naroff699a07d2009-09-25 21:32:34 +0000975 if (clang_isReference(C.kind)) {
Douglas Gregor1adb0822010-01-16 17:14:40 +0000976 if (getCursorStmt(C))
977 return getDeclFromExpr(getCursorStmt(C));
978
979 return getCursorDecl(C);
Steve Naroff699a07d2009-09-25 21:32:34 +0000980 }
981 return 0;
Steve Naroff9efa7672009-09-04 15:44:05 +0000982}
983
Douglas Gregor98258af2010-01-18 22:46:11 +0000984CXSourceLocation clang_getCursorLocation(CXCursor C) {
985 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +0000986 switch (C.kind) {
987 case CXCursor_ObjCSuperClassRef: {
988 std::pair<ObjCInterfaceDecl *, SourceLocation> P
989 = getCursorObjCSuperClassRef(C);
Douglas Gregor1db19de2010-01-19 21:36:55 +0000990 return translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +0000991 }
992
993 case CXCursor_ObjCProtocolRef: {
994 std::pair<ObjCProtocolDecl *, SourceLocation> P
995 = getCursorObjCProtocolRef(C);
Douglas Gregor1db19de2010-01-19 21:36:55 +0000996 return translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +0000997 }
998
999 case CXCursor_ObjCClassRef: {
1000 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1001 = getCursorObjCClassRef(C);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001002 return translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001003 }
1004
1005 case CXCursor_ObjCSelectorRef:
Douglas Gregorf46034a2010-01-18 23:41:10 +00001006 case CXCursor_VarRef:
1007 case CXCursor_FunctionRef:
Douglas Gregore8c70432010-01-19 22:15:34 +00001008 case CXCursor_EnumConstantRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00001009 Expr *E = getCursorExpr(C);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001010 ASTContext &Context = getCursorContext(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001011 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Douglas Gregor1db19de2010-01-19 21:36:55 +00001012 return translateSourceLocation(Context, /*FIXME:*/Msg->getLeftLoc());
Douglas Gregorf46034a2010-01-18 23:41:10 +00001013 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Douglas Gregor1db19de2010-01-19 21:36:55 +00001014 return translateSourceLocation(Context, DRE->getLocation());
Douglas Gregorf46034a2010-01-18 23:41:10 +00001015 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
Douglas Gregor1db19de2010-01-19 21:36:55 +00001016 return translateSourceLocation(Context, Member->getMemberLoc());
Douglas Gregorf46034a2010-01-18 23:41:10 +00001017 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Douglas Gregor1db19de2010-01-19 21:36:55 +00001018 return translateSourceLocation(Context, Ivar->getLocation());
1019 return translateSourceLocation(Context, E->getLocStart());
Douglas Gregorf46034a2010-01-18 23:41:10 +00001020 }
1021
1022 default:
1023 // FIXME: Need a way to enumerate all non-reference cases.
1024 llvm_unreachable("Missed a reference kind");
1025 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001026 }
1027
1028 if (!getCursorDecl(C)) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001029 CXSourceLocation empty = { 0, 0 };
Douglas Gregor98258af2010-01-18 22:46:11 +00001030 return empty;
1031 }
1032
Douglas Gregorf46034a2010-01-18 23:41:10 +00001033 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001034 SourceLocation Loc = D->getLocation();
1035 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1036 Loc = Class->getClassLoc();
Douglas Gregor1db19de2010-01-19 21:36:55 +00001037 return translateSourceLocation(D->getASTContext(), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001038}
Douglas Gregora7bde202010-01-19 00:34:46 +00001039
1040CXSourceRange clang_getCursorExtent(CXCursor C) {
1041 if (clang_isReference(C.kind)) {
1042 switch (C.kind) {
1043 case CXCursor_ObjCSuperClassRef: {
1044 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1045 = getCursorObjCSuperClassRef(C);
1046 return translateSourceRange(P.first->getASTContext(), P.second);
1047 }
1048
1049 case CXCursor_ObjCProtocolRef: {
1050 std::pair<ObjCProtocolDecl *, SourceLocation> P
1051 = getCursorObjCProtocolRef(C);
1052 return translateSourceRange(P.first->getASTContext(), P.second);
1053 }
1054
1055 case CXCursor_ObjCClassRef: {
1056 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1057 = getCursorObjCClassRef(C);
1058
1059 return translateSourceRange(P.first->getASTContext(), P.second);
1060 }
1061
1062 case CXCursor_ObjCSelectorRef:
Douglas Gregora7bde202010-01-19 00:34:46 +00001063 case CXCursor_VarRef:
1064 case CXCursor_FunctionRef:
1065 case CXCursor_EnumConstantRef:
Douglas Gregora7bde202010-01-19 00:34:46 +00001066 return translateSourceRange(getCursorContext(C),
1067 getCursorExpr(C)->getSourceRange());
1068
1069 default:
1070 // FIXME: Need a way to enumerate all non-reference cases.
1071 llvm_unreachable("Missed a reference kind");
1072 }
1073 }
1074
1075 if (!getCursorDecl(C)) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001076 CXSourceRange empty = { 0, 0, 0 };
Douglas Gregora7bde202010-01-19 00:34:46 +00001077 return empty;
1078 }
1079
1080 Decl *D = getCursorDecl(C);
1081 return translateSourceRange(D->getASTContext(), D->getSourceRange());
1082}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001083
1084CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001085 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001086 return C;
Douglas Gregor98258af2010-01-18 22:46:11 +00001087
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001088 if (!clang_isReference(C.kind))
1089 return clang_getNullCursor();
1090
1091 switch (C.kind) {
1092 case CXCursor_ObjCSuperClassRef:
1093 return MakeCXCursor(getCursorObjCSuperClassRef(C).first);
1094
1095 case CXCursor_ObjCProtocolRef: {
1096 return MakeCXCursor(getCursorObjCProtocolRef(C).first);
1097
1098 case CXCursor_ObjCClassRef:
1099 return MakeCXCursor(getCursorObjCClassRef(C).first);
1100
1101 case CXCursor_ObjCSelectorRef:
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001102 case CXCursor_VarRef:
1103 case CXCursor_FunctionRef:
Douglas Gregore8c70432010-01-19 22:15:34 +00001104 case CXCursor_EnumConstantRef: {
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001105 Decl *D = getDeclFromExpr(getCursorExpr(C));
1106 if (D)
1107 return MakeCXCursor(D);
1108 break;
1109 }
1110
1111 default:
1112 // We would prefer to enumerate all non-reference cursor kinds here.
1113 llvm_unreachable("Unhandled reference cursor kind");
1114 break;
1115 }
1116 }
1117
1118 return clang_getNullCursor();
1119}
1120
Douglas Gregorb6998662010-01-19 19:34:47 +00001121CXCursor clang_getCursorDefinition(CXCursor C) {
1122 bool WasReference = false;
1123 if (clang_isReference(C.kind)) {
1124 C = clang_getCursorReferenced(C);
1125 WasReference = true;
1126 }
1127
1128 if (!clang_isDeclaration(C.kind))
1129 return clang_getNullCursor();
1130
1131 Decl *D = getCursorDecl(C);
1132 if (!D)
1133 return clang_getNullCursor();
1134
1135 switch (D->getKind()) {
1136 // Declaration kinds that don't really separate the notions of
1137 // declaration and definition.
1138 case Decl::Namespace:
1139 case Decl::Typedef:
1140 case Decl::TemplateTypeParm:
1141 case Decl::EnumConstant:
1142 case Decl::Field:
1143 case Decl::ObjCIvar:
1144 case Decl::ObjCAtDefsField:
1145 case Decl::ImplicitParam:
1146 case Decl::ParmVar:
1147 case Decl::NonTypeTemplateParm:
1148 case Decl::TemplateTemplateParm:
1149 case Decl::ObjCCategoryImpl:
1150 case Decl::ObjCImplementation:
1151 case Decl::LinkageSpec:
1152 case Decl::ObjCPropertyImpl:
1153 case Decl::FileScopeAsm:
1154 case Decl::StaticAssert:
1155 case Decl::Block:
1156 return C;
1157
1158 // Declaration kinds that don't make any sense here, but are
1159 // nonetheless harmless.
1160 case Decl::TranslationUnit:
1161 case Decl::Template:
1162 case Decl::ObjCContainer:
1163 break;
1164
1165 // Declaration kinds for which the definition is not resolvable.
1166 case Decl::UnresolvedUsingTypename:
1167 case Decl::UnresolvedUsingValue:
1168 break;
1169
1170 case Decl::UsingDirective:
1171 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace());
1172
1173 case Decl::NamespaceAlias:
1174 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace());
1175
1176 case Decl::Enum:
1177 case Decl::Record:
1178 case Decl::CXXRecord:
1179 case Decl::ClassTemplateSpecialization:
1180 case Decl::ClassTemplatePartialSpecialization:
1181 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition(D->getASTContext()))
1182 return MakeCXCursor(Def);
1183 return clang_getNullCursor();
1184
1185 case Decl::Function:
1186 case Decl::CXXMethod:
1187 case Decl::CXXConstructor:
1188 case Decl::CXXDestructor:
1189 case Decl::CXXConversion: {
1190 const FunctionDecl *Def = 0;
1191 if (cast<FunctionDecl>(D)->getBody(Def))
1192 return MakeCXCursor(const_cast<FunctionDecl *>(Def));
1193 return clang_getNullCursor();
1194 }
1195
1196 case Decl::Var: {
1197 VarDecl *Var = cast<VarDecl>(D);
1198
1199 // Variables with initializers have definitions.
1200 const VarDecl *Def = 0;
1201 if (Var->getDefinition(Def))
1202 return MakeCXCursor(const_cast<VarDecl *>(Def));
1203
1204 // extern and private_extern variables are not definitions.
1205 if (Var->hasExternalStorage())
1206 return clang_getNullCursor();
1207
1208 // In-line static data members do not have definitions.
1209 if (Var->isStaticDataMember() && !Var->isOutOfLine())
1210 return clang_getNullCursor();
1211
1212 // All other variables are themselves definitions.
1213 return C;
1214 }
1215
1216 case Decl::FunctionTemplate: {
1217 const FunctionDecl *Def = 0;
1218 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
1219 return MakeCXCursor(Def->getDescribedFunctionTemplate());
1220 return clang_getNullCursor();
1221 }
1222
1223 case Decl::ClassTemplate: {
1224 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
1225 ->getDefinition(D->getASTContext()))
1226 return MakeCXCursor(
1227 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate());
1228 return clang_getNullCursor();
1229 }
1230
1231 case Decl::Using: {
1232 UsingDecl *Using = cast<UsingDecl>(D);
1233 CXCursor Def = clang_getNullCursor();
1234 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1235 SEnd = Using->shadow_end();
1236 S != SEnd; ++S) {
1237 if (Def != clang_getNullCursor()) {
1238 // FIXME: We have no way to return multiple results.
1239 return clang_getNullCursor();
1240 }
1241
1242 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl()));
1243 }
1244
1245 return Def;
1246 }
1247
1248 case Decl::UsingShadow:
1249 return clang_getCursorDefinition(
1250 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl()));
1251
1252 case Decl::ObjCMethod: {
1253 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1254 if (Method->isThisDeclarationADefinition())
1255 return C;
1256
1257 // Dig out the method definition in the associated
1258 // @implementation, if we have it.
1259 // FIXME: The ASTs should make finding the definition easier.
1260 if (ObjCInterfaceDecl *Class
1261 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
1262 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
1263 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
1264 Method->isInstanceMethod()))
1265 if (Def->isThisDeclarationADefinition())
1266 return MakeCXCursor(Def);
1267
1268 return clang_getNullCursor();
1269 }
1270
1271 case Decl::ObjCCategory:
1272 if (ObjCCategoryImplDecl *Impl
1273 = cast<ObjCCategoryDecl>(D)->getImplementation())
1274 return MakeCXCursor(Impl);
1275 return clang_getNullCursor();
1276
1277 case Decl::ObjCProtocol:
1278 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
1279 return C;
1280 return clang_getNullCursor();
1281
1282 case Decl::ObjCInterface:
1283 // There are two notions of a "definition" for an Objective-C
1284 // class: the interface and its implementation. When we resolved a
1285 // reference to an Objective-C class, produce the @interface as
1286 // the definition; when we were provided with the interface,
1287 // produce the @implementation as the definition.
1288 if (WasReference) {
1289 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
1290 return C;
1291 } else if (ObjCImplementationDecl *Impl
1292 = cast<ObjCInterfaceDecl>(D)->getImplementation())
1293 return MakeCXCursor(Impl);
1294 return clang_getNullCursor();
1295
1296 case Decl::ObjCProperty:
1297 // FIXME: We don't really know where to find the
1298 // ObjCPropertyImplDecls that implement this property.
1299 return clang_getNullCursor();
1300
1301 case Decl::ObjCCompatibleAlias:
1302 if (ObjCInterfaceDecl *Class
1303 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
1304 if (!Class->isForwardDecl())
1305 return MakeCXCursor(Class);
1306
1307 return clang_getNullCursor();
1308
1309 case Decl::ObjCForwardProtocol: {
1310 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
1311 if (Forward->protocol_size() == 1)
1312 return clang_getCursorDefinition(
1313 MakeCXCursor(*Forward->protocol_begin()));
1314
1315 // FIXME: Cannot return multiple definitions.
1316 return clang_getNullCursor();
1317 }
1318
1319 case Decl::ObjCClass: {
1320 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
1321 if (Class->size() == 1) {
1322 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
1323 if (!IFace->isForwardDecl())
1324 return MakeCXCursor(IFace);
1325 return clang_getNullCursor();
1326 }
1327
1328 // FIXME: Cannot return multiple definitions.
1329 return clang_getNullCursor();
1330 }
1331
1332 case Decl::Friend:
1333 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
1334 return clang_getCursorDefinition(MakeCXCursor(Friend));
1335 return clang_getNullCursor();
1336
1337 case Decl::FriendTemplate:
1338 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
1339 return clang_getCursorDefinition(MakeCXCursor(Friend));
1340 return clang_getNullCursor();
1341 }
1342
1343 return clang_getNullCursor();
1344}
1345
1346unsigned clang_isCursorDefinition(CXCursor C) {
1347 if (!clang_isDeclaration(C.kind))
1348 return 0;
1349
1350 return clang_getCursorDefinition(C) == C;
1351}
1352
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001353void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00001354 const char **startBuf,
1355 const char **endBuf,
1356 unsigned *startLine,
1357 unsigned *startColumn,
1358 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001359 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001360 assert(getCursorDecl(C) && "CXCursor has null decl");
1361 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00001362 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
1363 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekfb480492010-01-13 21:46:36 +00001364
Steve Naroff4ade6d62009-09-23 17:52:52 +00001365 SourceManager &SM = FD->getASTContext().getSourceManager();
1366 *startBuf = SM.getCharacterData(Body->getLBracLoc());
1367 *endBuf = SM.getCharacterData(Body->getRBracLoc());
1368 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
1369 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
1370 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
1371 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
1372}
Ted Kremenekfb480492010-01-13 21:46:36 +00001373
1374} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00001375
Ted Kremenekfb480492010-01-13 21:46:36 +00001376//===----------------------------------------------------------------------===//
1377// CXString Operations.
1378//===----------------------------------------------------------------------===//
1379
1380extern "C" {
1381const char *clang_getCString(CXString string) {
1382 return string.Spelling;
1383}
1384
1385void clang_disposeString(CXString string) {
1386 if (string.MustFreeString && string.Spelling)
1387 free((void*)string.Spelling);
1388}
1389} // end: extern "C"