blob: 3cc32c375b9ce82ff52d3e2bc2c58678c1fa3ed0 [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;
Douglas Gregor98258af2010-01-18 22:46:11 +0000125}
126
Douglas Gregora7bde202010-01-19 00:34:46 +0000127/// \brief Translate a Clang source range into a CIndex source range.
Douglas Gregor1db19de2010-01-19 21:36:55 +0000128static CXSourceRange translateSourceRange(ASTContext &Context, SourceRange R) {
129 CXSourceRange Result = { &Context,
130 R.getBegin().getRawEncoding(),
131 R.getEnd().getRawEncoding() };
132 return Result;
Douglas Gregora7bde202010-01-19 00:34:46 +0000133}
134
Douglas Gregor1db19de2010-01-19 21:36:55 +0000135
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000136//===----------------------------------------------------------------------===//
137// Visitors.
138//===----------------------------------------------------------------------===//
139
Steve Naroff89922f82009-08-31 00:59:03 +0000140namespace {
Steve Naroff89922f82009-08-31 00:59:03 +0000141// Translation Unit Visitor.
142class TUVisitor : public DeclVisitor<TUVisitor> {
Ted Kremenekf1286182010-01-13 00:13:47 +0000143public:
144 typedef void (*Iterator)(void *, CXCursor, CXClientData);
145private:
146 void *Root; // CXDecl or CXTranslationUnit
147 Iterator Callback; // CXTranslationUnitIterator or CXDeclIterator.
Steve Naroff2b8ee6c2009-09-01 15:55:40 +0000148 CXClientData CData;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000149
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000150 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
151 // to the visitor. Declarations with a PCH level greater than this value will
152 // be suppressed.
153 unsigned MaxPCHLevel;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000154
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000155 void Call(const CXCursor &C) {
Ted Kremenek70ee5422010-01-16 01:44:12 +0000156 if (clang_isInvalid(C.kind))
157 return;
158
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000159 if (const Decl *D = getCursorDecl(C)) {
160 // Filter any declarations that have a PCH level greater than what
161 // we allow.
162 if (D->getPCHLevel() > MaxPCHLevel)
163 return;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000164
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000165 // Filter any implicit declarations (since the source info will be bogus).
166 if (D->isImplicit())
167 return;
168 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000169
Ted Kremenekf1286182010-01-13 00:13:47 +0000170 Callback(Root, C, CData);
Steve Naroff2b8ee6c2009-09-01 15:55:40 +0000171 }
Ted Kremenekf1286182010-01-13 00:13:47 +0000172
Steve Naroff89922f82009-08-31 00:59:03 +0000173public:
Ted Kremenekf1286182010-01-13 00:13:47 +0000174 TUVisitor(void *root, Iterator cback, CXClientData D, unsigned MaxPCHLevel) :
175 Root(root), Callback(cback), CData(D), MaxPCHLevel(MaxPCHLevel) {}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000176
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000177 void VisitDecl(Decl *D);
Ted Kremenekf1286182010-01-13 00:13:47 +0000178 void VisitDeclContext(DeclContext *DC);
Ted Kremenekf1286182010-01-13 00:13:47 +0000179 void VisitTranslationUnitDecl(TranslationUnitDecl *D);
Ted Kremenekf1286182010-01-13 00:13:47 +0000180};
Ted Kremenekef7fdc62009-11-17 07:02:15 +0000181
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000182void TUVisitor::VisitDecl(Decl *D) {
183 Call(MakeCXCursor(D));
184}
185
Ted Kremenekf1286182010-01-13 00:13:47 +0000186void TUVisitor::VisitDeclContext(DeclContext *DC) {
187 for (DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
188 I != E; ++I)
189 Visit(*I);
190}
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000191
Ted Kremenekf1286182010-01-13 00:13:47 +0000192void TUVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
193 VisitDeclContext(dyn_cast<DeclContext>(D));
194}
Steve Naroff89922f82009-08-31 00:59:03 +0000195
Douglas Gregorb1373d02010-01-20 20:59:29 +0000196// Cursor visitor.
197class CursorVisitor : public DeclVisitor<CursorVisitor, bool> {
198 CXCursor Parent;
199 CXCursorVisitor Visitor;
200 CXClientData ClientData;
201
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000202 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
203 // to the visitor. Declarations with a PCH level greater than this value will
204 // be suppressed.
205 unsigned MaxPCHLevel;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000206
207 using DeclVisitor<CursorVisitor, bool>::Visit;
208
Steve Naroff89922f82009-08-31 00:59:03 +0000209public:
Douglas Gregorb1373d02010-01-20 20:59:29 +0000210 CursorVisitor(CXCursorVisitor Visitor, CXClientData ClientData,
211 unsigned MaxPCHLevel)
212 : Visitor(Visitor), ClientData(ClientData), MaxPCHLevel(MaxPCHLevel)
213 {
214 Parent.kind = CXCursor_NoDeclFound;
215 Parent.data[0] = 0;
216 Parent.data[1] = 0;
217 Parent.data[2] = 0;
218 }
219
220 bool Visit(CXCursor Cursor);
221 bool VisitChildren(CXCursor Parent);
222
223 bool VisitDeclContext(DeclContext *DC);
224
225 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
226 bool VisitFunctionDecl(FunctionDecl *ND);
227 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
228 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
229 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
230 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
231 bool VisitTagDecl(TagDecl *D);
Steve Naroff89922f82009-08-31 00:59:03 +0000232};
Douglas Gregorb1373d02010-01-20 20:59:29 +0000233
Ted Kremenekab188932010-01-05 19:32:54 +0000234} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000235
Douglas Gregorb1373d02010-01-20 20:59:29 +0000236/// \brief Visit the given cursor and, if requested by the visitor,
237/// its children.
238///
239/// \returns true if the visitation should be aborted, false if it
240/// should continue.
241bool CursorVisitor::Visit(CXCursor Cursor) {
242 if (clang_isInvalid(Cursor.kind))
243 return false;
244
245 if (clang_isDeclaration(Cursor.kind)) {
246 Decl *D = getCursorDecl(Cursor);
247 assert(D && "Invalid declaration cursor");
248 if (D->getPCHLevel() > MaxPCHLevel)
249 return false;
250
251 if (D->isImplicit())
252 return false;
253 }
254
255 switch (Visitor(Cursor, Parent, ClientData)) {
256 case CXChildVisit_Break:
257 return true;
258
259 case CXChildVisit_Continue:
260 return false;
261
262 case CXChildVisit_Recurse:
263 return VisitChildren(Cursor);
264 }
265
266 llvm_unreachable("Silly GCC, we can't get here");
267}
268
269/// \brief Visit the children of the given cursor.
270///
271/// \returns true if the visitation should be aborted, false if it
272/// should continue.
273bool CursorVisitor::VisitChildren(CXCursor Cursor) {
274 // Set the Parent field to Cursor, then back to its old value once we're
275 // done.
276 class SetParentRAII {
277 CXCursor &Parent;
278 CXCursor OldParent;
279
280 public:
281 SetParentRAII(CXCursor &Parent, CXCursor NewParent)
282 : Parent(Parent), OldParent(Parent)
283 {
284 Parent = NewParent;
285 }
286
287 ~SetParentRAII() {
288 Parent = OldParent;
289 }
290 } SetParent(Parent, Cursor);
291
292 if (clang_isDeclaration(Cursor.kind)) {
293 Decl *D = getCursorDecl(Cursor);
294 assert(D && "Invalid declaration cursor");
295 return Visit(D);
296 }
297
298 if (clang_isTranslationUnit(Cursor.kind)) {
299 ASTUnit *CXXUnit = static_cast<ASTUnit *>(Cursor.data[0]);
300 return VisitTranslationUnitDecl(
301 CXXUnit->getASTContext().getTranslationUnitDecl());
302 }
303
304 // Nothing to visit at the moment.
305 // FIXME: Traverse statements, declarations, etc. here.
306 return false;
307}
308
309bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
310 return VisitDeclContext(D);
311}
312
313bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000314 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000315 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
316 if (Visit(MakeCXCursor(*I)))
317 return true;
318 }
319
320 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000321}
322
Douglas Gregorb1373d02010-01-20 20:59:29 +0000323bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
324 // FIXME: This is wrong. We always want to visit the parameters and
325 // the body, if available.
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000326 if (ND->isThisDeclarationADefinition()) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000327 return VisitDeclContext(ND);
328
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000329#if 0
330 // Not currently needed.
331 CompoundStmt *Body = dyn_cast<CompoundStmt>(ND->getBody());
332 CRefVisitor RVisit(CDecl, Callback, CData);
333 RVisit.Visit(Body);
334#endif
335 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000336
337 return false;
338}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000339
Douglas Gregorb1373d02010-01-20 20:59:29 +0000340bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
341 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation())))
342 return true;
343
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000344 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
345 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
346 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000347 if (Visit(MakeCursorObjCProtocolRef(*I, *PL)))
348 return true;
349
350 return VisitDeclContext(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000351}
352
Douglas Gregorb1373d02010-01-20 20:59:29 +0000353bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000354 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000355 if (D->getSuperClass() &&
356 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
357 D->getSuperClassLoc())))
358 return true;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000359
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000360 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
361 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
362 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000363 if (Visit(MakeCursorObjCProtocolRef(*I, *PL)))
364 return true;
365
366 return VisitDeclContext(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000367}
368
Douglas Gregorb1373d02010-01-20 20:59:29 +0000369bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
370 // FIXME: Wrong in the same way that VisitFunctionDecl is wrong.
Douglas Gregorb6998662010-01-19 19:34:47 +0000371 if (ND->getBody())
Douglas Gregorb1373d02010-01-20 20:59:29 +0000372 return VisitDeclContext(ND);
373
374 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000375}
376
Douglas Gregorb1373d02010-01-20 20:59:29 +0000377bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000378 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000379 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000380 E = PID->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000381 if (Visit(MakeCursorObjCProtocolRef(*I, *PL)))
382 return true;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000383
Douglas Gregorb1373d02010-01-20 20:59:29 +0000384 return VisitDeclContext(PID);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000385}
386
Douglas Gregorb1373d02010-01-20 20:59:29 +0000387bool CursorVisitor::VisitTagDecl(TagDecl *D) {
388 return VisitDeclContext(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000389}
390
Daniel Dunbar140fce22010-01-12 02:34:07 +0000391CXString CIndexer::createCXString(const char *String, bool DupString){
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000392 CXString Str;
393 if (DupString) {
394 Str.Spelling = strdup(String);
395 Str.MustFreeString = 1;
396 } else {
397 Str.Spelling = String;
398 Str.MustFreeString = 0;
399 }
400 return Str;
401}
402
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000403extern "C" {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000404CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000405 int displayDiagnostics) {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000406 CIndexer *CIdxr = new CIndexer(new Program());
407 if (excludeDeclarationsFromPCH)
408 CIdxr->setOnlyLocalDecls();
409 if (displayDiagnostics)
410 CIdxr->setDisplayDiagnostics();
411 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +0000412}
413
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000414void clang_disposeIndex(CXIndex CIdx) {
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000415 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000416 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000417}
418
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000419void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
420 assert(CIdx && "Passed null CXIndex");
421 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
422 CXXIdx->setUseExternalASTGeneration(value);
423}
424
Steve Naroff50398192009-08-28 15:28:48 +0000425// FIXME: need to pass back error info.
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000426CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
427 const char *ast_filename) {
Steve Naroff50398192009-08-28 15:28:48 +0000428 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000429 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000430
Daniel Dunbar5262fda2009-12-03 01:45:44 +0000431 return ASTUnit::LoadFromPCHFile(ast_filename, CXXIdx->getDiags(),
432 CXXIdx->getOnlyLocalDecls(),
433 /* UseBumpAllocator = */ true);
Steve Naroff600866c2009-08-27 19:51:58 +0000434}
435
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000436CXTranslationUnit
437clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
438 const char *source_filename,
439 int num_command_line_args,
440 const char **command_line_args) {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000441 assert(CIdx && "Passed null CXIndex");
442 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
443
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000444 if (!CXXIdx->getUseExternalASTGeneration()) {
445 llvm::SmallVector<const char *, 16> Args;
446
447 // The 'source_filename' argument is optional. If the caller does not
448 // specify it then it is assumed that the source file is specified
449 // in the actual argument list.
450 if (source_filename)
451 Args.push_back(source_filename);
452 Args.insert(Args.end(), command_line_args,
453 command_line_args + num_command_line_args);
454
Daniel Dunbar94220972009-12-05 02:17:18 +0000455 unsigned NumErrors = CXXIdx->getDiags().getNumErrors();
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000456
Ted Kremenek29b72842010-01-07 22:49:05 +0000457#ifdef USE_CRASHTRACER
458 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000459#endif
460
Daniel Dunbar94220972009-12-05 02:17:18 +0000461 llvm::OwningPtr<ASTUnit> Unit(
462 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Daniel Dunbar869824e2009-12-13 03:46:13 +0000463 CXXIdx->getDiags(),
464 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +0000465 CXXIdx->getOnlyLocalDecls(),
466 /* UseBumpAllocator = */ true));
Ted Kremenek29b72842010-01-07 22:49:05 +0000467
Daniel Dunbar94220972009-12-05 02:17:18 +0000468 // FIXME: Until we have broader testing, just drop the entire AST if we
469 // encountered an error.
470 if (NumErrors != CXXIdx->getDiags().getNumErrors())
471 return 0;
472
473 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000474 }
475
Ted Kremenek139ba862009-10-22 00:03:57 +0000476 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000477 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000478
Ted Kremenek139ba862009-10-22 00:03:57 +0000479 // First add the complete path to the 'clang' executable.
480 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000481 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000482
Ted Kremenek139ba862009-10-22 00:03:57 +0000483 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000484 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000485
Ted Kremenek139ba862009-10-22 00:03:57 +0000486 // The 'source_filename' argument is optional. If the caller does not
487 // specify it then it is assumed that the source file is specified
488 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000489 if (source_filename)
490 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +0000491
Steve Naroff37b5ac22009-10-15 20:50:09 +0000492 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +0000493 argv.push_back("-o");
Steve Naroff37b5ac22009-10-15 20:50:09 +0000494 char astTmpFile[L_tmpnam];
Ted Kremenek74cd0692009-10-15 23:21:22 +0000495 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +0000496
497 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
498 for (int i = 0; i < num_command_line_args; ++i)
499 if (const char *arg = command_line_args[i]) {
500 if (strcmp(arg, "-o") == 0) {
501 ++i; // Also skip the matching argument.
502 continue;
503 }
504 if (strcmp(arg, "-emit-ast") == 0 ||
505 strcmp(arg, "-c") == 0 ||
506 strcmp(arg, "-fsyntax-only") == 0) {
507 continue;
508 }
509
510 // Keep the argument.
511 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000512 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000513
Ted Kremenek139ba862009-10-22 00:03:57 +0000514 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000515 argv.push_back(NULL);
516
Ted Kremenekfeb15e32009-10-26 22:14:08 +0000517 // Invoke 'clang'.
518 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
519 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +0000520 std::string ErrMsg;
Ted Kremenekc46e4632009-10-19 22:27:32 +0000521 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DevNull, NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +0000522 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
523 /* redirects */ !CXXIdx->getDisplayDiagnostics() ? &Redirects[0] : NULL,
524 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000525
Ted Kremenek0854d702009-11-10 19:18:52 +0000526 if (CXXIdx->getDisplayDiagnostics() && !ErrMsg.empty()) {
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000527 llvm::errs() << "clang_createTranslationUnitFromSourceFile: " << ErrMsg
Daniel Dunbaracca7252009-11-30 20:42:49 +0000528 << '\n' << "Arguments: \n";
Ted Kremenek379afec2009-10-22 03:24:01 +0000529 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Ted Kremenek779e5f42009-10-26 22:08:39 +0000530 I!=E; ++I) {
531 if (*I)
532 llvm::errs() << ' ' << *I << '\n';
533 }
534 llvm::errs() << '\n';
Ted Kremenek379afec2009-10-22 03:24:01 +0000535 }
Benjamin Kramer0829a832009-10-18 11:19:36 +0000536
Steve Naroff37b5ac22009-10-15 20:50:09 +0000537 // Finally, we create the translation unit from the ast file.
Steve Naroffe19944c2009-10-15 22:23:48 +0000538 ASTUnit *ATU = static_cast<ASTUnit *>(
Daniel Dunbaracca7252009-11-30 20:42:49 +0000539 clang_createTranslationUnit(CIdx, astTmpFile));
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000540 if (ATU)
541 ATU->unlinkTemporaryFile();
Steve Naroffe19944c2009-10-15 22:23:48 +0000542 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +0000543}
544
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000545void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000546 assert(CTUnit && "Passed null CXTranslationUnit");
547 delete static_cast<ASTUnit *>(CTUnit);
548}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000549
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000550CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000551 assert(CTUnit && "Passed null CXTranslationUnit");
Steve Naroff77accc12009-09-03 18:19:54 +0000552 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenek4b333d22010-01-12 00:36:38 +0000553 return CIndexer::createCXString(CXXUnit->getOriginalSourceFileName().c_str(),
554 true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000555}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +0000556
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +0000557CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
558 CXCursor Result = { CXCursor_TranslationUnit, { TU, 0, 0 } };
559 return Result;
560}
561
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000562void clang_loadTranslationUnit(CXTranslationUnit CTUnit,
Steve Naroffc857ea42009-09-02 13:28:54 +0000563 CXTranslationUnitIterator callback,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000564 CXClientData CData) {
Steve Naroff50398192009-08-28 15:28:48 +0000565 assert(CTUnit && "Passed null CXTranslationUnit");
566 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
567 ASTContext &Ctx = CXXUnit->getASTContext();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000568
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000569 unsigned PCHLevel = Decl::MaxPCHLevel;
570
571 // Set the PCHLevel to filter out unwanted decls if requested.
572 if (CXXUnit->getOnlyLocalDecls()) {
573 PCHLevel = 0;
574
575 // If the main input was an AST, bump the level.
576 if (CXXUnit->isMainFileAST())
577 ++PCHLevel;
578 }
579
580 TUVisitor DVisit(CTUnit, callback, CData, PCHLevel);
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000581
582 // If using a non-AST based ASTUnit, iterate over the stored list of top-level
583 // decls.
584 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls()) {
585 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
586 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
587 ie = TLDs.end(); it != ie; ++it) {
588 DVisit.Visit(*it);
589 }
590 } else
591 DVisit.Visit(Ctx.getTranslationUnitDecl());
Steve Naroff600866c2009-08-27 19:51:58 +0000592}
593
Douglas Gregorb1373d02010-01-20 20:59:29 +0000594struct LoadDeclarationData {
595 CXDeclIterator Callback;
596 CXClientData ClientData;
597};
598
599CXChildVisitResult LoadDeclarationVisitor(CXCursor cursor,
600 CXCursor parent,
601 CXClientData client_data) {
602 LoadDeclarationData *Data = static_cast<LoadDeclarationData *>(client_data);
603 Data->Callback(clang_getCursorDecl(cursor), cursor, Data->ClientData);
604 return CXChildVisit_Recurse;
605}
606
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000607void clang_loadDeclaration(CXDecl Dcl,
608 CXDeclIterator callback,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000609 CXClientData CData) {
Steve Naroffc857ea42009-09-02 13:28:54 +0000610 assert(Dcl && "Passed null CXDecl");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000611
Douglas Gregorb1373d02010-01-20 20:59:29 +0000612 LoadDeclarationData Data = { callback, CData };
613 CursorVisitor CurVisit(&LoadDeclarationVisitor, &Data,
614 static_cast<Decl *>(Dcl)->getPCHLevel());
615 CurVisit.VisitChildren(clang_getCursorFromDecl(Dcl));
Steve Naroff600866c2009-08-27 19:51:58 +0000616}
Ted Kremenekfb480492010-01-13 21:46:36 +0000617} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +0000618
Ted Kremenekfb480492010-01-13 21:46:36 +0000619//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +0000620// CXSourceLocation and CXSourceRange Operations.
621//===----------------------------------------------------------------------===//
622
623void clang_getInstantiationLocation(CXSourceLocation location,
624 CXFile *file,
625 unsigned *line,
626 unsigned *column) {
627 CXSourceLocationPtr Ptr
628 = CXSourceLocationPtr::getFromOpaqueValue(location.ptr_data);
629 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
630
631 if (!Ptr.getPointer() || Loc.isInvalid()) {
632 if (file)
633 *file = 0;
634 if (line)
635 *line = 0;
636 if (column)
637 *column = 0;
638 return;
639 }
640
641 // FIXME: This is largely copy-paste from
642 ///TextDiagnosticPrinter::HighlightRange. When it is clear that this is
643 // what we want the two routines should be refactored.
644 ASTContext &Context = *Ptr.getPointer();
645 SourceManager &SM = Context.getSourceManager();
646 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
647
648 if (Ptr.getInt()) {
649 // We want the last character in this location, so we will adjust
650 // the instantiation location accordingly.
651
652 // If the location is from a macro instantiation, get the end of
653 // the instantiation range.
654 if (Loc.isMacroID())
655 InstLoc = SM.getInstantiationRange(Loc).second;
656
657 // Measure the length token we're pointing at, so we can adjust
658 // the physical location in the file to point at the last
659 // character.
660 // FIXME: This won't cope with trigraphs or escaped newlines
661 // well. For that, we actually need a preprocessor, which isn't
662 // currently available here. Eventually, we'll switch the pointer
663 // data of CXSourceLocation/CXSourceRange to a translation unit
664 // (CXXUnit), so that the preprocessor will be available here. At
665 // that point, we can use Preprocessor::getLocForEndOfToken().
666 unsigned Length = Lexer::MeasureTokenLength(InstLoc, SM,
667 Context.getLangOptions());
668 if (Length > 0)
669 InstLoc = InstLoc.getFileLocWithOffset(Length - 1);
670 }
671
672 if (file)
673 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
674 if (line)
675 *line = SM.getInstantiationLineNumber(InstLoc);
676 if (column)
677 *column = SM.getInstantiationColumnNumber(InstLoc);
678}
679
680CXSourceLocation clang_getRangeStart(CXSourceRange range) {
681 CXSourceLocation Result = { range.ptr_data, range.begin_int_data };
682 return Result;
683}
684
685CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
686 llvm::PointerIntPair<ASTContext *, 1, bool> Ptr;
687 Ptr.setPointer(static_cast<ASTContext *>(range.ptr_data));
688 Ptr.setInt(true);
689 CXSourceLocation Result = { Ptr.getOpaqueValue(), range.end_int_data };
690 return Result;
691}
692
693//===----------------------------------------------------------------------===//
Steve Naroff600866c2009-08-27 19:51:58 +0000694// CXDecl Operations.
Ted Kremenekfb480492010-01-13 21:46:36 +0000695//===----------------------------------------------------------------------===//
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000696
Ted Kremenekfb480492010-01-13 21:46:36 +0000697extern "C" {
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000698CXString clang_getDeclSpelling(CXDecl AnonDecl) {
Steve Naroff89922f82009-08-31 00:59:03 +0000699 assert(AnonDecl && "Passed null CXDecl");
Douglas Gregor30122132010-01-19 22:07:56 +0000700 Decl *D = static_cast<Decl *>(AnonDecl);
701 NamedDecl *ND = dyn_cast<NamedDecl>(D);
702 if (!ND)
703 return CIndexer::createCXString("");
Steve Naroffef0cef62009-11-09 17:45:52 +0000704
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000705 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenek4b333d22010-01-12 00:36:38 +0000706 return CIndexer::createCXString(OMD->getSelector().getAsString().c_str(),
707 true);
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000708
709 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Steve Naroff0d69b8c2009-10-29 21:11:04 +0000710 // No, this isn't the same as the code below. getIdentifier() is non-virtual
711 // and returns different names. NamedDecl returns the class name and
712 // ObjCCategoryImplDecl returns the category name.
Ted Kremenek4b333d22010-01-12 00:36:38 +0000713 return CIndexer::createCXString(CIMP->getIdentifier()->getNameStart());
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000714
715 if (ND->getIdentifier())
Ted Kremenek4b333d22010-01-12 00:36:38 +0000716 return CIndexer::createCXString(ND->getIdentifier()->getNameStart());
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000717
Ted Kremenek4b333d22010-01-12 00:36:38 +0000718 return CIndexer::createCXString("");
Steve Naroff600866c2009-08-27 19:51:58 +0000719}
Steve Narofff334b4e2009-09-02 18:26:48 +0000720
Ted Kremenekfb480492010-01-13 21:46:36 +0000721} // end: extern "C"
Steve Naroff88145032009-10-27 14:35:18 +0000722
Ted Kremenekfb480492010-01-13 21:46:36 +0000723//===----------------------------------------------------------------------===//
724// CXFile Operations.
725//===----------------------------------------------------------------------===//
726
727extern "C" {
Steve Naroff88145032009-10-27 14:35:18 +0000728const char *clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +0000729 if (!SFile)
730 return 0;
731
Steve Naroff88145032009-10-27 14:35:18 +0000732 assert(SFile && "Passed null CXFile");
733 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
734 return FEnt->getName();
735}
736
737time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +0000738 if (!SFile)
739 return 0;
740
Steve Naroff88145032009-10-27 14:35:18 +0000741 assert(SFile && "Passed null CXFile");
742 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
743 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +0000744}
Ted Kremenekfb480492010-01-13 21:46:36 +0000745} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +0000746
Ted Kremenekfb480492010-01-13 21:46:36 +0000747//===----------------------------------------------------------------------===//
748// CXCursor Operations.
749//===----------------------------------------------------------------------===//
750
Ted Kremenekfb480492010-01-13 21:46:36 +0000751static Decl *getDeclFromExpr(Stmt *E) {
752 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
753 return RefExpr->getDecl();
754 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
755 return ME->getMemberDecl();
756 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
757 return RE->getDecl();
758
759 if (CallExpr *CE = dyn_cast<CallExpr>(E))
760 return getDeclFromExpr(CE->getCallee());
761 if (CastExpr *CE = dyn_cast<CastExpr>(E))
762 return getDeclFromExpr(CE->getSubExpr());
763 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
764 return OME->getMethodDecl();
765
766 return 0;
767}
768
769extern "C" {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000770
771unsigned clang_visitChildren(CXTranslationUnit tu,
772 CXCursor parent,
773 CXCursorVisitor visitor,
774 CXClientData client_data) {
775 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
776
777 unsigned PCHLevel = Decl::MaxPCHLevel;
778
779 // Set the PCHLevel to filter out unwanted decls if requested.
780 if (CXXUnit->getOnlyLocalDecls()) {
781 PCHLevel = 0;
782
783 // If the main input was an AST, bump the level.
784 if (CXXUnit->isMainFileAST())
785 ++PCHLevel;
786 }
787
788 CursorVisitor CursorVis(visitor, client_data, PCHLevel);
789 return CursorVis.VisitChildren(parent);
790}
791
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000792CXString clang_getCursorSpelling(CXCursor C) {
Daniel Dunbarc81d7182010-01-18 17:52:42 +0000793 assert(getCursorDecl(C) && "CXCursor has null decl");
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +0000794 if (clang_isTranslationUnit(C.kind))
795 return clang_getTranslationUnitSpelling(C.data[0]);
796
Steve Narofff334b4e2009-09-02 18:26:48 +0000797 if (clang_isReference(C.kind)) {
798 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +0000799 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +0000800 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
801 return CIndexer::createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +0000802 }
803 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +0000804 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
805 return CIndexer::createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +0000806 }
807 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000808 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +0000809 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenek4b333d22010-01-12 00:36:38 +0000810 return CIndexer::createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +0000811 }
Daniel Dunbaracca7252009-11-30 20:42:49 +0000812 default:
Ted Kremenek4b333d22010-01-12 00:36:38 +0000813 return CIndexer::createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +0000814 }
815 }
Douglas Gregor97b98722010-01-19 23:20:36 +0000816
817 if (clang_isExpression(C.kind)) {
818 Decl *D = getDeclFromExpr(getCursorExpr(C));
819 if (D)
820 return clang_getDeclSpelling(D);
821 return CIndexer::createCXString("");
822 }
823
Douglas Gregor283cae32010-01-15 21:56:13 +0000824 return clang_getDeclSpelling(getCursorDecl(C));
Steve Narofff334b4e2009-09-02 18:26:48 +0000825}
826
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000827const char *clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +0000828 switch (Kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +0000829 case CXCursor_FunctionDecl: return "FunctionDecl";
830 case CXCursor_TypedefDecl: return "TypedefDecl";
831 case CXCursor_EnumDecl: return "EnumDecl";
832 case CXCursor_EnumConstantDecl: return "EnumConstantDecl";
833 case CXCursor_StructDecl: return "StructDecl";
834 case CXCursor_UnionDecl: return "UnionDecl";
835 case CXCursor_ClassDecl: return "ClassDecl";
836 case CXCursor_FieldDecl: return "FieldDecl";
837 case CXCursor_VarDecl: return "VarDecl";
838 case CXCursor_ParmDecl: return "ParmDecl";
839 case CXCursor_ObjCInterfaceDecl: return "ObjCInterfaceDecl";
840 case CXCursor_ObjCCategoryDecl: return "ObjCCategoryDecl";
841 case CXCursor_ObjCProtocolDecl: return "ObjCProtocolDecl";
842 case CXCursor_ObjCPropertyDecl: return "ObjCPropertyDecl";
843 case CXCursor_ObjCIvarDecl: return "ObjCIvarDecl";
844 case CXCursor_ObjCInstanceMethodDecl: return "ObjCInstanceMethodDecl";
845 case CXCursor_ObjCClassMethodDecl: return "ObjCClassMethodDecl";
Douglas Gregorb6998662010-01-19 19:34:47 +0000846 case CXCursor_ObjCImplementationDecl: return "ObjCImplementationDecl";
847 case CXCursor_ObjCCategoryImplDecl: return "ObjCCategoryImplDecl";
Douglas Gregor30122132010-01-19 22:07:56 +0000848 case CXCursor_UnexposedDecl: return "UnexposedDecl";
Daniel Dunbaracca7252009-11-30 20:42:49 +0000849 case CXCursor_ObjCSuperClassRef: return "ObjCSuperClassRef";
850 case CXCursor_ObjCProtocolRef: return "ObjCProtocolRef";
851 case CXCursor_ObjCClassRef: return "ObjCClassRef";
Douglas Gregor97b98722010-01-19 23:20:36 +0000852 case CXCursor_UnexposedExpr: return "UnexposedExpr";
853 case CXCursor_DeclRefExpr: return "DeclRefExpr";
854 case CXCursor_MemberRefExpr: return "MemberRefExpr";
855 case CXCursor_CallExpr: return "CallExpr";
856 case CXCursor_ObjCMessageExpr: return "ObjCMessageExpr";
857 case CXCursor_UnexposedStmt: return "UnexposedStmt";
Daniel Dunbaracca7252009-11-30 20:42:49 +0000858 case CXCursor_InvalidFile: return "InvalidFile";
859 case CXCursor_NoDeclFound: return "NoDeclFound";
860 case CXCursor_NotImplemented: return "NotImplemented";
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +0000861 case CXCursor_TranslationUnit: return "TranslationUnit";
Steve Naroff89922f82009-08-31 00:59:03 +0000862 }
Ted Kremenekdeb06bd2010-01-16 02:02:09 +0000863
864 llvm_unreachable("Unhandled CXCursorKind");
865 return NULL;
Steve Naroff600866c2009-08-27 19:51:58 +0000866}
Steve Naroff89922f82009-08-31 00:59:03 +0000867
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000868CXCursor clang_getCursor(CXTranslationUnit CTUnit, const char *source_name,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000869 unsigned line, unsigned column) {
Steve Naroff9efa7672009-09-04 15:44:05 +0000870 assert(CTUnit && "Passed null CXTranslationUnit");
871 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000872
Steve Naroff9efa7672009-09-04 15:44:05 +0000873 FileManager &FMgr = CXXUnit->getFileManager();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000874 const FileEntry *File = FMgr.getFile(source_name,
875 source_name+strlen(source_name));
Ted Kremenekf4629892010-01-14 01:51:23 +0000876 if (!File)
877 return clang_getNullCursor();
878
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000879 SourceLocation SLoc =
Steve Naroff9efa7672009-09-04 15:44:05 +0000880 CXXUnit->getSourceManager().getLocation(File, line, column);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000881
Steve Narofff96b5242009-10-28 20:44:47 +0000882 ASTLocation LastLoc = CXXUnit->getLastASTLocation();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000883 ASTLocation ALoc = ResolveLocationInAST(CXXUnit->getASTContext(), SLoc,
Steve Narofff96b5242009-10-28 20:44:47 +0000884 &LastLoc);
Ted Kremenekf4629892010-01-14 01:51:23 +0000885
886 // FIXME: This doesn't look thread-safe.
Steve Narofff96b5242009-10-28 20:44:47 +0000887 if (ALoc.isValid())
888 CXXUnit->setLastASTLocation(ALoc);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000889
Argyrios Kyrtzidisf4526e32009-09-29 19:44:27 +0000890 Decl *Dcl = ALoc.getParentDecl();
Argyrios Kyrtzidis05a76512009-09-29 19:45:58 +0000891 if (ALoc.isNamedRef())
892 Dcl = ALoc.AsNamedRef().ND;
Argyrios Kyrtzidisf4526e32009-09-29 19:44:27 +0000893 Stmt *Stm = ALoc.dyn_AsStmt();
Steve Naroff4ade6d62009-09-23 17:52:52 +0000894 if (Dcl) {
Douglas Gregor97b98722010-01-19 23:20:36 +0000895 if (Stm)
896 return MakeCXCursor(Stm, Dcl);
897
Steve Naroff85e2db72009-10-01 00:31:07 +0000898 if (ALoc.isNamedRef()) {
Douglas Gregor1adb0822010-01-16 17:14:40 +0000899 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(Dcl))
900 return MakeCursorObjCClassRef(Class, ALoc.AsNamedRef().Loc);
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000901 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(Dcl))
902 return MakeCursorObjCProtocolRef(Proto, ALoc.AsNamedRef().Loc);
Steve Naroff85e2db72009-10-01 00:31:07 +0000903 }
Ted Kremenek70ee5422010-01-16 01:44:12 +0000904 return MakeCXCursor(Dcl);
Steve Naroff77128dd2009-09-15 20:25:34 +0000905 }
Ted Kremenekfb480492010-01-13 21:46:36 +0000906 return MakeCXCursor(CXCursor_NoDeclFound, 0);
Steve Naroff600866c2009-08-27 19:51:58 +0000907}
908
Ted Kremenek73885552009-11-17 19:28:59 +0000909CXCursor clang_getNullCursor(void) {
Ted Kremenekfb480492010-01-13 21:46:36 +0000910 return MakeCXCursor(CXCursor_InvalidFile, 0);
Ted Kremenek73885552009-11-17 19:28:59 +0000911}
912
913unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +0000914 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +0000915}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000916
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000917CXCursor clang_getCursorFromDecl(CXDecl AnonDecl) {
Steve Naroff77128dd2009-09-15 20:25:34 +0000918 assert(AnonDecl && "Passed null CXDecl");
Ted Kremenekdeb06bd2010-01-16 02:02:09 +0000919 return MakeCXCursor(static_cast<NamedDecl *>(AnonDecl));
Steve Naroff77128dd2009-09-15 20:25:34 +0000920}
921
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000922unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +0000923 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
924}
925
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000926unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +0000927 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
928}
Steve Naroff2d4d6292009-08-31 14:26:51 +0000929
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000930unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +0000931 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
932}
933
Douglas Gregor97b98722010-01-19 23:20:36 +0000934unsigned clang_isExpression(enum CXCursorKind K) {
935 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
936}
937
938unsigned clang_isStatement(enum CXCursorKind K) {
939 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
940}
941
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +0000942unsigned clang_isTranslationUnit(enum CXCursorKind K) {
943 return K == CXCursor_TranslationUnit;
944}
945
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000946CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +0000947 return C.kind;
948}
949
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000950CXDecl clang_getCursorDecl(CXCursor C) {
Douglas Gregorb6998662010-01-19 19:34:47 +0000951 if (clang_isDeclaration(C.kind))
Douglas Gregor283cae32010-01-15 21:56:13 +0000952 return getCursorDecl(C);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000953
Steve Naroff699a07d2009-09-25 21:32:34 +0000954 if (clang_isReference(C.kind)) {
Douglas Gregor1adb0822010-01-16 17:14:40 +0000955 if (getCursorStmt(C))
956 return getDeclFromExpr(getCursorStmt(C));
957
958 return getCursorDecl(C);
Steve Naroff699a07d2009-09-25 21:32:34 +0000959 }
Douglas Gregor97b98722010-01-19 23:20:36 +0000960
961 if (clang_isExpression(C.kind))
962 return getDeclFromExpr(getCursorStmt(C));
963
Steve Naroff699a07d2009-09-25 21:32:34 +0000964 return 0;
Steve Naroff9efa7672009-09-04 15:44:05 +0000965}
966
Douglas Gregor97b98722010-01-19 23:20:36 +0000967static SourceLocation getLocationFromExpr(Expr *E) {
968 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
969 return /*FIXME:*/Msg->getLeftLoc();
970 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
971 return DRE->getLocation();
972 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
973 return Member->getMemberLoc();
974 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
975 return Ivar->getLocation();
976 return E->getLocStart();
977}
978
Douglas Gregor98258af2010-01-18 22:46:11 +0000979CXSourceLocation clang_getCursorLocation(CXCursor C) {
980 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +0000981 switch (C.kind) {
982 case CXCursor_ObjCSuperClassRef: {
983 std::pair<ObjCInterfaceDecl *, SourceLocation> P
984 = getCursorObjCSuperClassRef(C);
Douglas Gregor1db19de2010-01-19 21:36:55 +0000985 return translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +0000986 }
987
988 case CXCursor_ObjCProtocolRef: {
989 std::pair<ObjCProtocolDecl *, SourceLocation> P
990 = getCursorObjCProtocolRef(C);
Douglas Gregor1db19de2010-01-19 21:36:55 +0000991 return translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +0000992 }
993
994 case CXCursor_ObjCClassRef: {
995 std::pair<ObjCInterfaceDecl *, SourceLocation> P
996 = getCursorObjCClassRef(C);
Douglas Gregor1db19de2010-01-19 21:36:55 +0000997 return translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +0000998 }
999
Douglas Gregorf46034a2010-01-18 23:41:10 +00001000 default:
1001 // FIXME: Need a way to enumerate all non-reference cases.
1002 llvm_unreachable("Missed a reference kind");
1003 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001004 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001005
1006 if (clang_isExpression(C.kind))
1007 return translateSourceLocation(getCursorContext(C),
1008 getLocationFromExpr(getCursorExpr(C)));
1009
Douglas Gregor98258af2010-01-18 22:46:11 +00001010 if (!getCursorDecl(C)) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001011 CXSourceLocation empty = { 0, 0 };
Douglas Gregor98258af2010-01-18 22:46:11 +00001012 return empty;
1013 }
1014
Douglas Gregorf46034a2010-01-18 23:41:10 +00001015 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001016 SourceLocation Loc = D->getLocation();
1017 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1018 Loc = Class->getClassLoc();
Douglas Gregor1db19de2010-01-19 21:36:55 +00001019 return translateSourceLocation(D->getASTContext(), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001020}
Douglas Gregora7bde202010-01-19 00:34:46 +00001021
1022CXSourceRange clang_getCursorExtent(CXCursor C) {
1023 if (clang_isReference(C.kind)) {
1024 switch (C.kind) {
1025 case CXCursor_ObjCSuperClassRef: {
1026 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1027 = getCursorObjCSuperClassRef(C);
1028 return translateSourceRange(P.first->getASTContext(), P.second);
1029 }
1030
1031 case CXCursor_ObjCProtocolRef: {
1032 std::pair<ObjCProtocolDecl *, SourceLocation> P
1033 = getCursorObjCProtocolRef(C);
1034 return translateSourceRange(P.first->getASTContext(), P.second);
1035 }
1036
1037 case CXCursor_ObjCClassRef: {
1038 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1039 = getCursorObjCClassRef(C);
1040
1041 return translateSourceRange(P.first->getASTContext(), P.second);
1042 }
1043
Douglas Gregora7bde202010-01-19 00:34:46 +00001044 default:
1045 // FIXME: Need a way to enumerate all non-reference cases.
1046 llvm_unreachable("Missed a reference kind");
1047 }
1048 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001049
1050 if (clang_isExpression(C.kind))
1051 return translateSourceRange(getCursorContext(C),
1052 getCursorExpr(C)->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001053
1054 if (!getCursorDecl(C)) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001055 CXSourceRange empty = { 0, 0, 0 };
Douglas Gregora7bde202010-01-19 00:34:46 +00001056 return empty;
1057 }
1058
1059 Decl *D = getCursorDecl(C);
1060 return translateSourceRange(D->getASTContext(), D->getSourceRange());
1061}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001062
1063CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001064 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001065 return C;
Douglas Gregor98258af2010-01-18 22:46:11 +00001066
Douglas Gregor97b98722010-01-19 23:20:36 +00001067 if (clang_isExpression(C.kind)) {
1068 Decl *D = getDeclFromExpr(getCursorExpr(C));
1069 if (D)
1070 return MakeCXCursor(D);
1071 return clang_getNullCursor();
1072 }
1073
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001074 if (!clang_isReference(C.kind))
1075 return clang_getNullCursor();
1076
1077 switch (C.kind) {
1078 case CXCursor_ObjCSuperClassRef:
1079 return MakeCXCursor(getCursorObjCSuperClassRef(C).first);
1080
1081 case CXCursor_ObjCProtocolRef: {
1082 return MakeCXCursor(getCursorObjCProtocolRef(C).first);
1083
1084 case CXCursor_ObjCClassRef:
1085 return MakeCXCursor(getCursorObjCClassRef(C).first);
1086
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001087 default:
1088 // We would prefer to enumerate all non-reference cursor kinds here.
1089 llvm_unreachable("Unhandled reference cursor kind");
1090 break;
1091 }
1092 }
1093
1094 return clang_getNullCursor();
1095}
1096
Douglas Gregorb6998662010-01-19 19:34:47 +00001097CXCursor clang_getCursorDefinition(CXCursor C) {
1098 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001099 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001100 C = clang_getCursorReferenced(C);
1101 WasReference = true;
1102 }
1103
1104 if (!clang_isDeclaration(C.kind))
1105 return clang_getNullCursor();
1106
1107 Decl *D = getCursorDecl(C);
1108 if (!D)
1109 return clang_getNullCursor();
1110
1111 switch (D->getKind()) {
1112 // Declaration kinds that don't really separate the notions of
1113 // declaration and definition.
1114 case Decl::Namespace:
1115 case Decl::Typedef:
1116 case Decl::TemplateTypeParm:
1117 case Decl::EnumConstant:
1118 case Decl::Field:
1119 case Decl::ObjCIvar:
1120 case Decl::ObjCAtDefsField:
1121 case Decl::ImplicitParam:
1122 case Decl::ParmVar:
1123 case Decl::NonTypeTemplateParm:
1124 case Decl::TemplateTemplateParm:
1125 case Decl::ObjCCategoryImpl:
1126 case Decl::ObjCImplementation:
1127 case Decl::LinkageSpec:
1128 case Decl::ObjCPropertyImpl:
1129 case Decl::FileScopeAsm:
1130 case Decl::StaticAssert:
1131 case Decl::Block:
1132 return C;
1133
1134 // Declaration kinds that don't make any sense here, but are
1135 // nonetheless harmless.
1136 case Decl::TranslationUnit:
1137 case Decl::Template:
1138 case Decl::ObjCContainer:
1139 break;
1140
1141 // Declaration kinds for which the definition is not resolvable.
1142 case Decl::UnresolvedUsingTypename:
1143 case Decl::UnresolvedUsingValue:
1144 break;
1145
1146 case Decl::UsingDirective:
1147 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace());
1148
1149 case Decl::NamespaceAlias:
1150 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace());
1151
1152 case Decl::Enum:
1153 case Decl::Record:
1154 case Decl::CXXRecord:
1155 case Decl::ClassTemplateSpecialization:
1156 case Decl::ClassTemplatePartialSpecialization:
1157 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition(D->getASTContext()))
1158 return MakeCXCursor(Def);
1159 return clang_getNullCursor();
1160
1161 case Decl::Function:
1162 case Decl::CXXMethod:
1163 case Decl::CXXConstructor:
1164 case Decl::CXXDestructor:
1165 case Decl::CXXConversion: {
1166 const FunctionDecl *Def = 0;
1167 if (cast<FunctionDecl>(D)->getBody(Def))
1168 return MakeCXCursor(const_cast<FunctionDecl *>(Def));
1169 return clang_getNullCursor();
1170 }
1171
1172 case Decl::Var: {
1173 VarDecl *Var = cast<VarDecl>(D);
1174
1175 // Variables with initializers have definitions.
1176 const VarDecl *Def = 0;
1177 if (Var->getDefinition(Def))
1178 return MakeCXCursor(const_cast<VarDecl *>(Def));
1179
1180 // extern and private_extern variables are not definitions.
1181 if (Var->hasExternalStorage())
1182 return clang_getNullCursor();
1183
1184 // In-line static data members do not have definitions.
1185 if (Var->isStaticDataMember() && !Var->isOutOfLine())
1186 return clang_getNullCursor();
1187
1188 // All other variables are themselves definitions.
1189 return C;
1190 }
1191
1192 case Decl::FunctionTemplate: {
1193 const FunctionDecl *Def = 0;
1194 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
1195 return MakeCXCursor(Def->getDescribedFunctionTemplate());
1196 return clang_getNullCursor();
1197 }
1198
1199 case Decl::ClassTemplate: {
1200 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
1201 ->getDefinition(D->getASTContext()))
1202 return MakeCXCursor(
1203 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate());
1204 return clang_getNullCursor();
1205 }
1206
1207 case Decl::Using: {
1208 UsingDecl *Using = cast<UsingDecl>(D);
1209 CXCursor Def = clang_getNullCursor();
1210 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1211 SEnd = Using->shadow_end();
1212 S != SEnd; ++S) {
1213 if (Def != clang_getNullCursor()) {
1214 // FIXME: We have no way to return multiple results.
1215 return clang_getNullCursor();
1216 }
1217
1218 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl()));
1219 }
1220
1221 return Def;
1222 }
1223
1224 case Decl::UsingShadow:
1225 return clang_getCursorDefinition(
1226 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl()));
1227
1228 case Decl::ObjCMethod: {
1229 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1230 if (Method->isThisDeclarationADefinition())
1231 return C;
1232
1233 // Dig out the method definition in the associated
1234 // @implementation, if we have it.
1235 // FIXME: The ASTs should make finding the definition easier.
1236 if (ObjCInterfaceDecl *Class
1237 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
1238 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
1239 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
1240 Method->isInstanceMethod()))
1241 if (Def->isThisDeclarationADefinition())
1242 return MakeCXCursor(Def);
1243
1244 return clang_getNullCursor();
1245 }
1246
1247 case Decl::ObjCCategory:
1248 if (ObjCCategoryImplDecl *Impl
1249 = cast<ObjCCategoryDecl>(D)->getImplementation())
1250 return MakeCXCursor(Impl);
1251 return clang_getNullCursor();
1252
1253 case Decl::ObjCProtocol:
1254 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
1255 return C;
1256 return clang_getNullCursor();
1257
1258 case Decl::ObjCInterface:
1259 // There are two notions of a "definition" for an Objective-C
1260 // class: the interface and its implementation. When we resolved a
1261 // reference to an Objective-C class, produce the @interface as
1262 // the definition; when we were provided with the interface,
1263 // produce the @implementation as the definition.
1264 if (WasReference) {
1265 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
1266 return C;
1267 } else if (ObjCImplementationDecl *Impl
1268 = cast<ObjCInterfaceDecl>(D)->getImplementation())
1269 return MakeCXCursor(Impl);
1270 return clang_getNullCursor();
1271
1272 case Decl::ObjCProperty:
1273 // FIXME: We don't really know where to find the
1274 // ObjCPropertyImplDecls that implement this property.
1275 return clang_getNullCursor();
1276
1277 case Decl::ObjCCompatibleAlias:
1278 if (ObjCInterfaceDecl *Class
1279 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
1280 if (!Class->isForwardDecl())
1281 return MakeCXCursor(Class);
1282
1283 return clang_getNullCursor();
1284
1285 case Decl::ObjCForwardProtocol: {
1286 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
1287 if (Forward->protocol_size() == 1)
1288 return clang_getCursorDefinition(
1289 MakeCXCursor(*Forward->protocol_begin()));
1290
1291 // FIXME: Cannot return multiple definitions.
1292 return clang_getNullCursor();
1293 }
1294
1295 case Decl::ObjCClass: {
1296 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
1297 if (Class->size() == 1) {
1298 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
1299 if (!IFace->isForwardDecl())
1300 return MakeCXCursor(IFace);
1301 return clang_getNullCursor();
1302 }
1303
1304 // FIXME: Cannot return multiple definitions.
1305 return clang_getNullCursor();
1306 }
1307
1308 case Decl::Friend:
1309 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
1310 return clang_getCursorDefinition(MakeCXCursor(Friend));
1311 return clang_getNullCursor();
1312
1313 case Decl::FriendTemplate:
1314 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
1315 return clang_getCursorDefinition(MakeCXCursor(Friend));
1316 return clang_getNullCursor();
1317 }
1318
1319 return clang_getNullCursor();
1320}
1321
1322unsigned clang_isCursorDefinition(CXCursor C) {
1323 if (!clang_isDeclaration(C.kind))
1324 return 0;
1325
1326 return clang_getCursorDefinition(C) == C;
1327}
1328
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001329void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00001330 const char **startBuf,
1331 const char **endBuf,
1332 unsigned *startLine,
1333 unsigned *startColumn,
1334 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001335 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001336 assert(getCursorDecl(C) && "CXCursor has null decl");
1337 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00001338 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
1339 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekfb480492010-01-13 21:46:36 +00001340
Steve Naroff4ade6d62009-09-23 17:52:52 +00001341 SourceManager &SM = FD->getASTContext().getSourceManager();
1342 *startBuf = SM.getCharacterData(Body->getLBracLoc());
1343 *endBuf = SM.getCharacterData(Body->getRBracLoc());
1344 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
1345 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
1346 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
1347 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
1348}
Ted Kremenekfb480492010-01-13 21:46:36 +00001349
1350} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00001351
Ted Kremenekfb480492010-01-13 21:46:36 +00001352//===----------------------------------------------------------------------===//
1353// CXString Operations.
1354//===----------------------------------------------------------------------===//
1355
1356extern "C" {
1357const char *clang_getCString(CXString string) {
1358 return string.Spelling;
1359}
1360
1361void clang_disposeString(CXString string) {
1362 if (string.MustFreeString && string.Spelling)
1363 free((void*)string.Spelling);
1364}
1365} // end: extern "C"