blob: 8dfaa4cbe1230cf105196481ce9f91c69b65c3e4 [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 {
Steve Naroff89922f82009-08-31 00:59:03 +0000202// Translation Unit Visitor.
203class TUVisitor : public DeclVisitor<TUVisitor> {
Ted Kremenekf1286182010-01-13 00:13:47 +0000204public:
205 typedef void (*Iterator)(void *, CXCursor, CXClientData);
206private:
207 void *Root; // CXDecl or CXTranslationUnit
208 Iterator Callback; // CXTranslationUnitIterator or CXDeclIterator.
Steve Naroff2b8ee6c2009-09-01 15:55:40 +0000209 CXClientData CData;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000210
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000211 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
212 // to the visitor. Declarations with a PCH level greater than this value will
213 // be suppressed.
214 unsigned MaxPCHLevel;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000215
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000216 void Call(const CXCursor &C) {
Ted Kremenek70ee5422010-01-16 01:44:12 +0000217 if (clang_isInvalid(C.kind))
218 return;
219
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000220 if (const Decl *D = getCursorDecl(C)) {
221 // Filter any declarations that have a PCH level greater than what
222 // we allow.
223 if (D->getPCHLevel() > MaxPCHLevel)
224 return;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000225
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000226 // Filter any implicit declarations (since the source info will be bogus).
227 if (D->isImplicit())
228 return;
229 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000230
Ted Kremenekf1286182010-01-13 00:13:47 +0000231 Callback(Root, C, CData);
Steve Naroff2b8ee6c2009-09-01 15:55:40 +0000232 }
Ted Kremenekf1286182010-01-13 00:13:47 +0000233
Steve Naroff89922f82009-08-31 00:59:03 +0000234public:
Ted Kremenekf1286182010-01-13 00:13:47 +0000235 TUVisitor(void *root, Iterator cback, CXClientData D, unsigned MaxPCHLevel) :
236 Root(root), Callback(cback), CData(D), MaxPCHLevel(MaxPCHLevel) {}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000237
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000238 void VisitDecl(Decl *D);
Ted Kremenekf1286182010-01-13 00:13:47 +0000239 void VisitDeclContext(DeclContext *DC);
Ted Kremenekf1286182010-01-13 00:13:47 +0000240 void VisitTranslationUnitDecl(TranslationUnitDecl *D);
Ted Kremenekf1286182010-01-13 00:13:47 +0000241};
Ted Kremenekef7fdc62009-11-17 07:02:15 +0000242
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000243void TUVisitor::VisitDecl(Decl *D) {
244 Call(MakeCXCursor(D));
245}
246
Ted Kremenekf1286182010-01-13 00:13:47 +0000247void TUVisitor::VisitDeclContext(DeclContext *DC) {
248 for (DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
249 I != E; ++I)
250 Visit(*I);
251}
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000252
Ted Kremenekf1286182010-01-13 00:13:47 +0000253void TUVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
254 VisitDeclContext(dyn_cast<DeclContext>(D));
255}
Steve Naroff89922f82009-08-31 00:59:03 +0000256
Steve Naroffc857ea42009-09-02 13:28:54 +0000257// Declaration visitor.
258class CDeclVisitor : public DeclVisitor<CDeclVisitor> {
259 CXDecl CDecl;
260 CXDeclIterator Callback;
261 CXClientData CData;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000262
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000263 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
264 // to the visitor. Declarations with a PCH level greater than this value will
265 // be suppressed.
266 unsigned MaxPCHLevel;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000267
Steve Naroffc857ea42009-09-02 13:28:54 +0000268 void Call(enum CXCursorKind CK, NamedDecl *ND) {
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000269 // Disable the callback when the context is equal to the visiting decl.
270 if (CDecl == ND && !clang_isReference(CK))
271 return;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000272
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000273 // Filter any declarations that have a PCH level greater than what we allow.
274 if (ND->getPCHLevel() > MaxPCHLevel)
275 return;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000276
Douglas Gregor283cae32010-01-15 21:56:13 +0000277 CXCursor C = { CK, { ND, 0, 0 } };
Steve Naroffc857ea42009-09-02 13:28:54 +0000278 Callback(CDecl, C, CData);
279 }
Douglas Gregor2e331b92010-01-16 14:00:32 +0000280
Steve Naroff89922f82009-08-31 00:59:03 +0000281public:
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000282 CDeclVisitor(CXDecl C, CXDeclIterator cback, CXClientData D,
283 unsigned MaxPCHLevel) :
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000284 CDecl(C), Callback(cback), CData(D), MaxPCHLevel(MaxPCHLevel) {}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000285
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000286 void VisitDeclContext(DeclContext *DC);
287 void VisitEnumConstantDecl(EnumConstantDecl *ND);
288 void VisitFieldDecl(FieldDecl *ND);
289 void VisitFunctionDecl(FunctionDecl *ND);
290 void VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
291 void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
292 void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
293 void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
294 void VisitObjCIvarDecl(ObjCIvarDecl *ND);
295 void VisitObjCMethodDecl(ObjCMethodDecl *ND);
296 void VisitObjCPropertyDecl(ObjCPropertyDecl *ND);
297 void VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
298 void VisitParmVarDecl(ParmVarDecl *ND);
299 void VisitTagDecl(TagDecl *D);
300 void VisitVarDecl(VarDecl *ND);
Steve Naroff89922f82009-08-31 00:59:03 +0000301};
Ted Kremenekab188932010-01-05 19:32:54 +0000302} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000303
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000304void CDeclVisitor::VisitDeclContext(DeclContext *DC) {
305 for (DeclContext::decl_iterator
306 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I)
307 Visit(*I);
308}
309
310void CDeclVisitor::VisitEnumConstantDecl(EnumConstantDecl *ND) {
311 Call(CXCursor_EnumConstantDecl, ND);
312}
313
314void CDeclVisitor::VisitFieldDecl(FieldDecl *ND) {
315 Call(CXCursor_FieldDecl, ND);
316}
317
318void CDeclVisitor::VisitFunctionDecl(FunctionDecl *ND) {
319 if (ND->isThisDeclarationADefinition()) {
320 VisitDeclContext(dyn_cast<DeclContext>(ND));
321#if 0
322 // Not currently needed.
323 CompoundStmt *Body = dyn_cast<CompoundStmt>(ND->getBody());
324 CRefVisitor RVisit(CDecl, Callback, CData);
325 RVisit.Visit(Body);
326#endif
327 }
328}
329
330void CDeclVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
331 // Issue callbacks for the containing class.
Douglas Gregor1adb0822010-01-16 17:14:40 +0000332 Callback(CDecl,
333 MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation()),
334 CData);
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000335 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
336 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
337 E = ND->protocol_end(); I != E; ++I, ++PL)
338 Callback(CDecl, MakeCursorObjCProtocolRef(*I, *PL), CData);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000339 VisitDeclContext(dyn_cast<DeclContext>(ND));
340}
341
342void CDeclVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
343 VisitDeclContext(dyn_cast<DeclContext>(D));
344}
345
346void CDeclVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
347 VisitDeclContext(dyn_cast<DeclContext>(D));
348}
349
350void CDeclVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
351 // Issue callbacks for super class.
352 if (D->getSuperClass())
Douglas Gregor2e331b92010-01-16 14:00:32 +0000353 Callback(CDecl,
354 MakeCursorObjCSuperClassRef(D->getSuperClass(),
355 D->getSuperClassLoc()),
356 CData);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000357
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000358 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
359 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
360 E = D->protocol_end(); I != E; ++I, ++PL)
361 Callback(CDecl, MakeCursorObjCProtocolRef(*I, *PL), CData);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000362 VisitDeclContext(dyn_cast<DeclContext>(D));
363}
364
365void CDeclVisitor::VisitObjCIvarDecl(ObjCIvarDecl *ND) {
366 Call(CXCursor_ObjCIvarDecl, ND);
367}
368
369void CDeclVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregorb6998662010-01-19 19:34:47 +0000370 Call(ND->isInstanceMethod() ? CXCursor_ObjCInstanceMethodDecl
371 : CXCursor_ObjCClassMethodDecl, ND);
372
373 if (ND->getBody())
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000374 VisitDeclContext(dyn_cast<DeclContext>(ND));
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000375}
376
377void CDeclVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *ND) {
378 Call(CXCursor_ObjCPropertyDecl, ND);
379}
380
381void CDeclVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000382 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000383 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000384 E = PID->protocol_end(); I != E; ++I, ++PL)
385 Callback(CDecl, MakeCursorObjCProtocolRef(*I, *PL), CData);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000386
387 VisitDeclContext(dyn_cast<DeclContext>(PID));
388}
389
390void CDeclVisitor::VisitParmVarDecl(ParmVarDecl *ND) {
391 Call(CXCursor_ParmDecl, ND);
392}
393
394void CDeclVisitor::VisitTagDecl(TagDecl *D) {
395 VisitDeclContext(dyn_cast<DeclContext>(D));
396}
397
398void CDeclVisitor::VisitVarDecl(VarDecl *ND) {
399 Call(CXCursor_VarDecl, ND);
400}
401
Daniel Dunbar140fce22010-01-12 02:34:07 +0000402CXString CIndexer::createCXString(const char *String, bool DupString){
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000403 CXString Str;
404 if (DupString) {
405 Str.Spelling = strdup(String);
406 Str.MustFreeString = 1;
407 } else {
408 Str.Spelling = String;
409 Str.MustFreeString = 0;
410 }
411 return Str;
412}
413
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000414extern "C" {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000415CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000416 int displayDiagnostics) {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000417 CIndexer *CIdxr = new CIndexer(new Program());
418 if (excludeDeclarationsFromPCH)
419 CIdxr->setOnlyLocalDecls();
420 if (displayDiagnostics)
421 CIdxr->setDisplayDiagnostics();
422 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +0000423}
424
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000425void clang_disposeIndex(CXIndex CIdx) {
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000426 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000427 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000428}
429
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000430void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
431 assert(CIdx && "Passed null CXIndex");
432 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
433 CXXIdx->setUseExternalASTGeneration(value);
434}
435
Steve Naroff50398192009-08-28 15:28:48 +0000436// FIXME: need to pass back error info.
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000437CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
438 const char *ast_filename) {
Steve Naroff50398192009-08-28 15:28:48 +0000439 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000440 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000441
Daniel Dunbar5262fda2009-12-03 01:45:44 +0000442 return ASTUnit::LoadFromPCHFile(ast_filename, CXXIdx->getDiags(),
443 CXXIdx->getOnlyLocalDecls(),
444 /* UseBumpAllocator = */ true);
Steve Naroff600866c2009-08-27 19:51:58 +0000445}
446
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000447CXTranslationUnit
448clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
449 const char *source_filename,
450 int num_command_line_args,
451 const char **command_line_args) {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000452 assert(CIdx && "Passed null CXIndex");
453 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
454
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000455 if (!CXXIdx->getUseExternalASTGeneration()) {
456 llvm::SmallVector<const char *, 16> Args;
457
458 // The 'source_filename' argument is optional. If the caller does not
459 // specify it then it is assumed that the source file is specified
460 // in the actual argument list.
461 if (source_filename)
462 Args.push_back(source_filename);
463 Args.insert(Args.end(), command_line_args,
464 command_line_args + num_command_line_args);
465
Daniel Dunbar94220972009-12-05 02:17:18 +0000466 unsigned NumErrors = CXXIdx->getDiags().getNumErrors();
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000467
Ted Kremenek29b72842010-01-07 22:49:05 +0000468#ifdef USE_CRASHTRACER
469 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000470#endif
471
Daniel Dunbar94220972009-12-05 02:17:18 +0000472 llvm::OwningPtr<ASTUnit> Unit(
473 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Daniel Dunbar869824e2009-12-13 03:46:13 +0000474 CXXIdx->getDiags(),
475 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +0000476 CXXIdx->getOnlyLocalDecls(),
477 /* UseBumpAllocator = */ true));
Ted Kremenek29b72842010-01-07 22:49:05 +0000478
Daniel Dunbar94220972009-12-05 02:17:18 +0000479 // FIXME: Until we have broader testing, just drop the entire AST if we
480 // encountered an error.
481 if (NumErrors != CXXIdx->getDiags().getNumErrors())
482 return 0;
483
484 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000485 }
486
Ted Kremenek139ba862009-10-22 00:03:57 +0000487 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000488 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000489
Ted Kremenek139ba862009-10-22 00:03:57 +0000490 // First add the complete path to the 'clang' executable.
491 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000492 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000493
Ted Kremenek139ba862009-10-22 00:03:57 +0000494 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000495 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000496
Ted Kremenek139ba862009-10-22 00:03:57 +0000497 // The 'source_filename' argument is optional. If the caller does not
498 // specify it then it is assumed that the source file is specified
499 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000500 if (source_filename)
501 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +0000502
Steve Naroff37b5ac22009-10-15 20:50:09 +0000503 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +0000504 argv.push_back("-o");
Steve Naroff37b5ac22009-10-15 20:50:09 +0000505 char astTmpFile[L_tmpnam];
Ted Kremenek74cd0692009-10-15 23:21:22 +0000506 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +0000507
508 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
509 for (int i = 0; i < num_command_line_args; ++i)
510 if (const char *arg = command_line_args[i]) {
511 if (strcmp(arg, "-o") == 0) {
512 ++i; // Also skip the matching argument.
513 continue;
514 }
515 if (strcmp(arg, "-emit-ast") == 0 ||
516 strcmp(arg, "-c") == 0 ||
517 strcmp(arg, "-fsyntax-only") == 0) {
518 continue;
519 }
520
521 // Keep the argument.
522 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000523 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000524
Ted Kremenek139ba862009-10-22 00:03:57 +0000525 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000526 argv.push_back(NULL);
527
Ted Kremenekfeb15e32009-10-26 22:14:08 +0000528 // Invoke 'clang'.
529 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
530 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +0000531 std::string ErrMsg;
Ted Kremenekc46e4632009-10-19 22:27:32 +0000532 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DevNull, NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +0000533 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
534 /* redirects */ !CXXIdx->getDisplayDiagnostics() ? &Redirects[0] : NULL,
535 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000536
Ted Kremenek0854d702009-11-10 19:18:52 +0000537 if (CXXIdx->getDisplayDiagnostics() && !ErrMsg.empty()) {
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000538 llvm::errs() << "clang_createTranslationUnitFromSourceFile: " << ErrMsg
Daniel Dunbaracca7252009-11-30 20:42:49 +0000539 << '\n' << "Arguments: \n";
Ted Kremenek379afec2009-10-22 03:24:01 +0000540 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Ted Kremenek779e5f42009-10-26 22:08:39 +0000541 I!=E; ++I) {
542 if (*I)
543 llvm::errs() << ' ' << *I << '\n';
544 }
545 llvm::errs() << '\n';
Ted Kremenek379afec2009-10-22 03:24:01 +0000546 }
Benjamin Kramer0829a832009-10-18 11:19:36 +0000547
Steve Naroff37b5ac22009-10-15 20:50:09 +0000548 // Finally, we create the translation unit from the ast file.
Steve Naroffe19944c2009-10-15 22:23:48 +0000549 ASTUnit *ATU = static_cast<ASTUnit *>(
Daniel Dunbaracca7252009-11-30 20:42:49 +0000550 clang_createTranslationUnit(CIdx, astTmpFile));
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000551 if (ATU)
552 ATU->unlinkTemporaryFile();
Steve Naroffe19944c2009-10-15 22:23:48 +0000553 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +0000554}
555
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000556void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000557 assert(CTUnit && "Passed null CXTranslationUnit");
558 delete static_cast<ASTUnit *>(CTUnit);
559}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000560
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000561CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000562 assert(CTUnit && "Passed null CXTranslationUnit");
Steve Naroff77accc12009-09-03 18:19:54 +0000563 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenek4b333d22010-01-12 00:36:38 +0000564 return CIndexer::createCXString(CXXUnit->getOriginalSourceFileName().c_str(),
565 true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000566}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +0000567
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +0000568CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
569 CXCursor Result = { CXCursor_TranslationUnit, { TU, 0, 0 } };
570 return Result;
571}
572
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000573void clang_loadTranslationUnit(CXTranslationUnit CTUnit,
Steve Naroffc857ea42009-09-02 13:28:54 +0000574 CXTranslationUnitIterator callback,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000575 CXClientData CData) {
Steve Naroff50398192009-08-28 15:28:48 +0000576 assert(CTUnit && "Passed null CXTranslationUnit");
577 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
578 ASTContext &Ctx = CXXUnit->getASTContext();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000579
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000580 unsigned PCHLevel = Decl::MaxPCHLevel;
581
582 // Set the PCHLevel to filter out unwanted decls if requested.
583 if (CXXUnit->getOnlyLocalDecls()) {
584 PCHLevel = 0;
585
586 // If the main input was an AST, bump the level.
587 if (CXXUnit->isMainFileAST())
588 ++PCHLevel;
589 }
590
591 TUVisitor DVisit(CTUnit, callback, CData, PCHLevel);
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000592
593 // If using a non-AST based ASTUnit, iterate over the stored list of top-level
594 // decls.
595 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls()) {
596 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
597 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
598 ie = TLDs.end(); it != ie; ++it) {
599 DVisit.Visit(*it);
600 }
601 } else
602 DVisit.Visit(Ctx.getTranslationUnitDecl());
Steve Naroff600866c2009-08-27 19:51:58 +0000603}
604
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000605void clang_loadDeclaration(CXDecl Dcl,
606 CXDeclIterator callback,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000607 CXClientData CData) {
Steve Naroffc857ea42009-09-02 13:28:54 +0000608 assert(Dcl && "Passed null CXDecl");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000609
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000610 CDeclVisitor DVisit(Dcl, callback, CData,
611 static_cast<Decl *>(Dcl)->getPCHLevel());
Steve Naroffc857ea42009-09-02 13:28:54 +0000612 DVisit.Visit(static_cast<Decl *>(Dcl));
Steve Naroff600866c2009-08-27 19:51:58 +0000613}
Ted Kremenekfb480492010-01-13 21:46:36 +0000614} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +0000615
Ted Kremenekfb480492010-01-13 21:46:36 +0000616//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +0000617// CXSourceLocation and CXSourceRange Operations.
618//===----------------------------------------------------------------------===//
619
620void clang_getInstantiationLocation(CXSourceLocation location,
621 CXFile *file,
622 unsigned *line,
623 unsigned *column) {
624 CXSourceLocationPtr Ptr
625 = CXSourceLocationPtr::getFromOpaqueValue(location.ptr_data);
626 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
627
628 if (!Ptr.getPointer() || Loc.isInvalid()) {
629 if (file)
630 *file = 0;
631 if (line)
632 *line = 0;
633 if (column)
634 *column = 0;
635 return;
636 }
637
638 // FIXME: This is largely copy-paste from
639 ///TextDiagnosticPrinter::HighlightRange. When it is clear that this is
640 // what we want the two routines should be refactored.
641 ASTContext &Context = *Ptr.getPointer();
642 SourceManager &SM = Context.getSourceManager();
643 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
644
645 if (Ptr.getInt()) {
646 // We want the last character in this location, so we will adjust
647 // the instantiation location accordingly.
648
649 // If the location is from a macro instantiation, get the end of
650 // the instantiation range.
651 if (Loc.isMacroID())
652 InstLoc = SM.getInstantiationRange(Loc).second;
653
654 // Measure the length token we're pointing at, so we can adjust
655 // the physical location in the file to point at the last
656 // character.
657 // FIXME: This won't cope with trigraphs or escaped newlines
658 // well. For that, we actually need a preprocessor, which isn't
659 // currently available here. Eventually, we'll switch the pointer
660 // data of CXSourceLocation/CXSourceRange to a translation unit
661 // (CXXUnit), so that the preprocessor will be available here. At
662 // that point, we can use Preprocessor::getLocForEndOfToken().
663 unsigned Length = Lexer::MeasureTokenLength(InstLoc, SM,
664 Context.getLangOptions());
665 if (Length > 0)
666 InstLoc = InstLoc.getFileLocWithOffset(Length - 1);
667 }
668
669 if (file)
670 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
671 if (line)
672 *line = SM.getInstantiationLineNumber(InstLoc);
673 if (column)
674 *column = SM.getInstantiationColumnNumber(InstLoc);
675}
676
677CXSourceLocation clang_getRangeStart(CXSourceRange range) {
678 CXSourceLocation Result = { range.ptr_data, range.begin_int_data };
679 return Result;
680}
681
682CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
683 llvm::PointerIntPair<ASTContext *, 1, bool> Ptr;
684 Ptr.setPointer(static_cast<ASTContext *>(range.ptr_data));
685 Ptr.setInt(true);
686 CXSourceLocation Result = { Ptr.getOpaqueValue(), range.end_int_data };
687 return Result;
688}
689
690//===----------------------------------------------------------------------===//
Steve Naroff600866c2009-08-27 19:51:58 +0000691// CXDecl Operations.
Ted Kremenekfb480492010-01-13 21:46:36 +0000692//===----------------------------------------------------------------------===//
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000693
Ted Kremenekfb480492010-01-13 21:46:36 +0000694static const FileEntry *getFileEntryFromSourceLocation(SourceManager &SMgr,
695 SourceLocation SLoc) {
696 FileID FID;
697 if (SLoc.isFileID())
698 FID = SMgr.getFileID(SLoc);
699 else
700 FID = SMgr.getDecomposedSpellingLoc(SLoc).first;
701 return SMgr.getFileEntryForID(FID);
702}
703
704extern "C" {
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000705CXString clang_getDeclSpelling(CXDecl AnonDecl) {
Steve Naroff89922f82009-08-31 00:59:03 +0000706 assert(AnonDecl && "Passed null CXDecl");
Douglas Gregor30122132010-01-19 22:07:56 +0000707 Decl *D = static_cast<Decl *>(AnonDecl);
708 NamedDecl *ND = dyn_cast<NamedDecl>(D);
709 if (!ND)
710 return CIndexer::createCXString("");
Steve Naroffef0cef62009-11-09 17:45:52 +0000711
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000712 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenek4b333d22010-01-12 00:36:38 +0000713 return CIndexer::createCXString(OMD->getSelector().getAsString().c_str(),
714 true);
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000715
716 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Steve Naroff0d69b8c2009-10-29 21:11:04 +0000717 // No, this isn't the same as the code below. getIdentifier() is non-virtual
718 // and returns different names. NamedDecl returns the class name and
719 // ObjCCategoryImplDecl returns the category name.
Ted Kremenek4b333d22010-01-12 00:36:38 +0000720 return CIndexer::createCXString(CIMP->getIdentifier()->getNameStart());
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000721
722 if (ND->getIdentifier())
Ted Kremenek4b333d22010-01-12 00:36:38 +0000723 return CIndexer::createCXString(ND->getIdentifier()->getNameStart());
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000724
Ted Kremenek4b333d22010-01-12 00:36:38 +0000725 return CIndexer::createCXString("");
Steve Naroff600866c2009-08-27 19:51:58 +0000726}
Steve Narofff334b4e2009-09-02 18:26:48 +0000727
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000728unsigned clang_getDeclLine(CXDecl AnonDecl) {
Steve Naroff699a07d2009-09-25 21:32:34 +0000729 assert(AnonDecl && "Passed null CXDecl");
730 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
731 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
732 return SourceMgr.getSpellingLineNumber(ND->getLocation());
733}
734
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000735unsigned clang_getDeclColumn(CXDecl AnonDecl) {
Steve Naroff699a07d2009-09-25 21:32:34 +0000736 assert(AnonDecl && "Passed null CXDecl");
737 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
738 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Steve Naroff74165242009-09-25 22:15:54 +0000739 return SourceMgr.getSpellingColumnNumber(ND->getLocation());
Steve Naroff699a07d2009-09-25 21:32:34 +0000740}
Ted Kremenekfe6fd3d2010-01-05 23:18:49 +0000741
Douglas Gregor3c7313d2010-01-18 22:13:09 +0000742CXSourceRange clang_getDeclExtent(CXDecl AnonDecl) {
Douglas Gregora7bde202010-01-19 00:34:46 +0000743 return clang_getCursorExtent(clang_getCursorFromDecl(AnonDecl));
Ted Kremenekfe6fd3d2010-01-05 23:18:49 +0000744}
Steve Naroff699a07d2009-09-25 21:32:34 +0000745
Ted Kremenek6ab9db12010-01-08 17:11:32 +0000746const char *clang_getDeclSource(CXDecl AnonDecl) {
747 assert(AnonDecl && "Passed null CXDecl");
748 FileEntry *FEnt = static_cast<FileEntry *>(clang_getDeclSourceFile(AnonDecl));
749 assert(FEnt && "Cannot find FileEntry for Decl");
750 return clang_getFileName(FEnt);
751}
752
Steve Naroff88145032009-10-27 14:35:18 +0000753
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000754CXFile clang_getDeclSourceFile(CXDecl AnonDecl) {
Steve Naroff88145032009-10-27 14:35:18 +0000755 assert(AnonDecl && "Passed null CXDecl");
Steve Naroffee9405e2009-09-25 21:45:39 +0000756 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
757 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Steve Naroff88145032009-10-27 14:35:18 +0000758 return (void *)getFileEntryFromSourceLocation(SourceMgr, ND->getLocation());
759}
Ted Kremenekfb480492010-01-13 21:46:36 +0000760} // end: extern "C"
Steve Naroff88145032009-10-27 14:35:18 +0000761
Ted Kremenekfb480492010-01-13 21:46:36 +0000762//===----------------------------------------------------------------------===//
763// CXFile Operations.
764//===----------------------------------------------------------------------===//
765
766extern "C" {
Steve Naroff88145032009-10-27 14:35:18 +0000767const char *clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +0000768 if (!SFile)
769 return 0;
770
Steve Naroff88145032009-10-27 14:35:18 +0000771 assert(SFile && "Passed null CXFile");
772 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
773 return FEnt->getName();
774}
775
776time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +0000777 if (!SFile)
778 return 0;
779
Steve Naroff88145032009-10-27 14:35:18 +0000780 assert(SFile && "Passed null CXFile");
781 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
782 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +0000783}
Ted Kremenekfb480492010-01-13 21:46:36 +0000784} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +0000785
Ted Kremenekfb480492010-01-13 21:46:36 +0000786//===----------------------------------------------------------------------===//
787// CXCursor Operations.
788//===----------------------------------------------------------------------===//
789
Ted Kremenekfb480492010-01-13 21:46:36 +0000790static Decl *getDeclFromExpr(Stmt *E) {
791 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
792 return RefExpr->getDecl();
793 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
794 return ME->getMemberDecl();
795 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
796 return RE->getDecl();
797
798 if (CallExpr *CE = dyn_cast<CallExpr>(E))
799 return getDeclFromExpr(CE->getCallee());
800 if (CastExpr *CE = dyn_cast<CastExpr>(E))
801 return getDeclFromExpr(CE->getSubExpr());
802 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
803 return OME->getMethodDecl();
804
805 return 0;
806}
807
808extern "C" {
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000809CXString clang_getCursorSpelling(CXCursor C) {
Daniel Dunbarc81d7182010-01-18 17:52:42 +0000810 assert(getCursorDecl(C) && "CXCursor has null decl");
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +0000811 if (clang_isTranslationUnit(C.kind))
812 return clang_getTranslationUnitSpelling(C.data[0]);
813
Steve Narofff334b4e2009-09-02 18:26:48 +0000814 if (clang_isReference(C.kind)) {
815 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +0000816 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +0000817 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
818 return CIndexer::createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +0000819 }
820 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +0000821 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
822 return CIndexer::createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +0000823 }
824 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000825 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +0000826 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenek4b333d22010-01-12 00:36:38 +0000827 return CIndexer::createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +0000828 }
Daniel Dunbaracca7252009-11-30 20:42:49 +0000829 default:
Ted Kremenek4b333d22010-01-12 00:36:38 +0000830 return CIndexer::createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +0000831 }
832 }
Douglas Gregor97b98722010-01-19 23:20:36 +0000833
834 if (clang_isExpression(C.kind)) {
835 Decl *D = getDeclFromExpr(getCursorExpr(C));
836 if (D)
837 return clang_getDeclSpelling(D);
838 return CIndexer::createCXString("");
839 }
840
Douglas Gregor283cae32010-01-15 21:56:13 +0000841 return clang_getDeclSpelling(getCursorDecl(C));
Steve Narofff334b4e2009-09-02 18:26:48 +0000842}
843
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000844const char *clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +0000845 switch (Kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +0000846 case CXCursor_FunctionDecl: return "FunctionDecl";
847 case CXCursor_TypedefDecl: return "TypedefDecl";
848 case CXCursor_EnumDecl: return "EnumDecl";
849 case CXCursor_EnumConstantDecl: return "EnumConstantDecl";
850 case CXCursor_StructDecl: return "StructDecl";
851 case CXCursor_UnionDecl: return "UnionDecl";
852 case CXCursor_ClassDecl: return "ClassDecl";
853 case CXCursor_FieldDecl: return "FieldDecl";
854 case CXCursor_VarDecl: return "VarDecl";
855 case CXCursor_ParmDecl: return "ParmDecl";
856 case CXCursor_ObjCInterfaceDecl: return "ObjCInterfaceDecl";
857 case CXCursor_ObjCCategoryDecl: return "ObjCCategoryDecl";
858 case CXCursor_ObjCProtocolDecl: return "ObjCProtocolDecl";
859 case CXCursor_ObjCPropertyDecl: return "ObjCPropertyDecl";
860 case CXCursor_ObjCIvarDecl: return "ObjCIvarDecl";
861 case CXCursor_ObjCInstanceMethodDecl: return "ObjCInstanceMethodDecl";
862 case CXCursor_ObjCClassMethodDecl: return "ObjCClassMethodDecl";
Douglas Gregorb6998662010-01-19 19:34:47 +0000863 case CXCursor_ObjCImplementationDecl: return "ObjCImplementationDecl";
864 case CXCursor_ObjCCategoryImplDecl: return "ObjCCategoryImplDecl";
Douglas Gregor30122132010-01-19 22:07:56 +0000865 case CXCursor_UnexposedDecl: return "UnexposedDecl";
Daniel Dunbaracca7252009-11-30 20:42:49 +0000866 case CXCursor_ObjCSuperClassRef: return "ObjCSuperClassRef";
867 case CXCursor_ObjCProtocolRef: return "ObjCProtocolRef";
868 case CXCursor_ObjCClassRef: return "ObjCClassRef";
Douglas Gregor97b98722010-01-19 23:20:36 +0000869 case CXCursor_UnexposedExpr: return "UnexposedExpr";
870 case CXCursor_DeclRefExpr: return "DeclRefExpr";
871 case CXCursor_MemberRefExpr: return "MemberRefExpr";
872 case CXCursor_CallExpr: return "CallExpr";
873 case CXCursor_ObjCMessageExpr: return "ObjCMessageExpr";
874 case CXCursor_UnexposedStmt: return "UnexposedStmt";
Daniel Dunbaracca7252009-11-30 20:42:49 +0000875 case CXCursor_InvalidFile: return "InvalidFile";
876 case CXCursor_NoDeclFound: return "NoDeclFound";
877 case CXCursor_NotImplemented: return "NotImplemented";
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +0000878 case CXCursor_TranslationUnit: return "TranslationUnit";
Steve Naroff89922f82009-08-31 00:59:03 +0000879 }
Ted Kremenekdeb06bd2010-01-16 02:02:09 +0000880
881 llvm_unreachable("Unhandled CXCursorKind");
882 return NULL;
Steve Naroff600866c2009-08-27 19:51:58 +0000883}
Steve Naroff89922f82009-08-31 00:59:03 +0000884
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000885CXCursor clang_getCursor(CXTranslationUnit CTUnit, const char *source_name,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000886 unsigned line, unsigned column) {
Steve Naroff9efa7672009-09-04 15:44:05 +0000887 assert(CTUnit && "Passed null CXTranslationUnit");
888 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000889
Steve Naroff9efa7672009-09-04 15:44:05 +0000890 FileManager &FMgr = CXXUnit->getFileManager();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000891 const FileEntry *File = FMgr.getFile(source_name,
892 source_name+strlen(source_name));
Ted Kremenekf4629892010-01-14 01:51:23 +0000893 if (!File)
894 return clang_getNullCursor();
895
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000896 SourceLocation SLoc =
Steve Naroff9efa7672009-09-04 15:44:05 +0000897 CXXUnit->getSourceManager().getLocation(File, line, column);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000898
Steve Narofff96b5242009-10-28 20:44:47 +0000899 ASTLocation LastLoc = CXXUnit->getLastASTLocation();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000900 ASTLocation ALoc = ResolveLocationInAST(CXXUnit->getASTContext(), SLoc,
Steve Narofff96b5242009-10-28 20:44:47 +0000901 &LastLoc);
Ted Kremenekf4629892010-01-14 01:51:23 +0000902
903 // FIXME: This doesn't look thread-safe.
Steve Narofff96b5242009-10-28 20:44:47 +0000904 if (ALoc.isValid())
905 CXXUnit->setLastASTLocation(ALoc);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000906
Argyrios Kyrtzidisf4526e32009-09-29 19:44:27 +0000907 Decl *Dcl = ALoc.getParentDecl();
Argyrios Kyrtzidis05a76512009-09-29 19:45:58 +0000908 if (ALoc.isNamedRef())
909 Dcl = ALoc.AsNamedRef().ND;
Argyrios Kyrtzidisf4526e32009-09-29 19:44:27 +0000910 Stmt *Stm = ALoc.dyn_AsStmt();
Steve Naroff4ade6d62009-09-23 17:52:52 +0000911 if (Dcl) {
Douglas Gregor97b98722010-01-19 23:20:36 +0000912 if (Stm)
913 return MakeCXCursor(Stm, Dcl);
914
Steve Naroff85e2db72009-10-01 00:31:07 +0000915 if (ALoc.isNamedRef()) {
Douglas Gregor1adb0822010-01-16 17:14:40 +0000916 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(Dcl))
917 return MakeCursorObjCClassRef(Class, ALoc.AsNamedRef().Loc);
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000918 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(Dcl))
919 return MakeCursorObjCProtocolRef(Proto, ALoc.AsNamedRef().Loc);
Steve Naroff85e2db72009-10-01 00:31:07 +0000920 }
Ted Kremenek70ee5422010-01-16 01:44:12 +0000921 return MakeCXCursor(Dcl);
Steve Naroff77128dd2009-09-15 20:25:34 +0000922 }
Ted Kremenekfb480492010-01-13 21:46:36 +0000923 return MakeCXCursor(CXCursor_NoDeclFound, 0);
Steve Naroff600866c2009-08-27 19:51:58 +0000924}
925
Ted Kremenek73885552009-11-17 19:28:59 +0000926CXCursor clang_getNullCursor(void) {
Ted Kremenekfb480492010-01-13 21:46:36 +0000927 return MakeCXCursor(CXCursor_InvalidFile, 0);
Ted Kremenek73885552009-11-17 19:28:59 +0000928}
929
930unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +0000931 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +0000932}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000933
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000934CXCursor clang_getCursorFromDecl(CXDecl AnonDecl) {
Steve Naroff77128dd2009-09-15 20:25:34 +0000935 assert(AnonDecl && "Passed null CXDecl");
Ted Kremenekdeb06bd2010-01-16 02:02:09 +0000936 return MakeCXCursor(static_cast<NamedDecl *>(AnonDecl));
Steve Naroff77128dd2009-09-15 20:25:34 +0000937}
938
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000939unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +0000940 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
941}
942
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000943unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +0000944 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
945}
Steve Naroff2d4d6292009-08-31 14:26:51 +0000946
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000947unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +0000948 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
949}
950
Douglas Gregor97b98722010-01-19 23:20:36 +0000951unsigned clang_isExpression(enum CXCursorKind K) {
952 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
953}
954
955unsigned clang_isStatement(enum CXCursorKind K) {
956 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
957}
958
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +0000959unsigned clang_isTranslationUnit(enum CXCursorKind K) {
960 return K == CXCursor_TranslationUnit;
961}
962
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000963CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +0000964 return C.kind;
965}
966
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000967CXDecl clang_getCursorDecl(CXCursor C) {
Douglas Gregorb6998662010-01-19 19:34:47 +0000968 if (clang_isDeclaration(C.kind))
Douglas Gregor283cae32010-01-15 21:56:13 +0000969 return getCursorDecl(C);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000970
Steve Naroff699a07d2009-09-25 21:32:34 +0000971 if (clang_isReference(C.kind)) {
Douglas Gregor1adb0822010-01-16 17:14:40 +0000972 if (getCursorStmt(C))
973 return getDeclFromExpr(getCursorStmt(C));
974
975 return getCursorDecl(C);
Steve Naroff699a07d2009-09-25 21:32:34 +0000976 }
Douglas Gregor97b98722010-01-19 23:20:36 +0000977
978 if (clang_isExpression(C.kind))
979 return getDeclFromExpr(getCursorStmt(C));
980
Steve Naroff699a07d2009-09-25 21:32:34 +0000981 return 0;
Steve Naroff9efa7672009-09-04 15:44:05 +0000982}
983
Douglas Gregor97b98722010-01-19 23:20:36 +0000984static SourceLocation getLocationFromExpr(Expr *E) {
985 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
986 return /*FIXME:*/Msg->getLeftLoc();
987 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
988 return DRE->getLocation();
989 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
990 return Member->getMemberLoc();
991 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
992 return Ivar->getLocation();
993 return E->getLocStart();
994}
995
Douglas Gregor98258af2010-01-18 22:46:11 +0000996CXSourceLocation clang_getCursorLocation(CXCursor C) {
997 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +0000998 switch (C.kind) {
999 case CXCursor_ObjCSuperClassRef: {
1000 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1001 = getCursorObjCSuperClassRef(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_ObjCProtocolRef: {
1006 std::pair<ObjCProtocolDecl *, SourceLocation> P
1007 = getCursorObjCProtocolRef(C);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001008 return translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001009 }
1010
1011 case CXCursor_ObjCClassRef: {
1012 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1013 = getCursorObjCClassRef(C);
Douglas Gregor1db19de2010-01-19 21:36:55 +00001014 return translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001015 }
1016
Douglas Gregorf46034a2010-01-18 23:41:10 +00001017 default:
1018 // FIXME: Need a way to enumerate all non-reference cases.
1019 llvm_unreachable("Missed a reference kind");
1020 }
Douglas Gregor98258af2010-01-18 22:46:11 +00001021 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001022
1023 if (clang_isExpression(C.kind))
1024 return translateSourceLocation(getCursorContext(C),
1025 getLocationFromExpr(getCursorExpr(C)));
1026
Douglas Gregor98258af2010-01-18 22:46:11 +00001027 if (!getCursorDecl(C)) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001028 CXSourceLocation empty = { 0, 0 };
Douglas Gregor98258af2010-01-18 22:46:11 +00001029 return empty;
1030 }
1031
Douglas Gregorf46034a2010-01-18 23:41:10 +00001032 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00001033 SourceLocation Loc = D->getLocation();
1034 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1035 Loc = Class->getClassLoc();
Douglas Gregor1db19de2010-01-19 21:36:55 +00001036 return translateSourceLocation(D->getASTContext(), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001037}
Douglas Gregora7bde202010-01-19 00:34:46 +00001038
1039CXSourceRange clang_getCursorExtent(CXCursor C) {
1040 if (clang_isReference(C.kind)) {
1041 switch (C.kind) {
1042 case CXCursor_ObjCSuperClassRef: {
1043 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1044 = getCursorObjCSuperClassRef(C);
1045 return translateSourceRange(P.first->getASTContext(), P.second);
1046 }
1047
1048 case CXCursor_ObjCProtocolRef: {
1049 std::pair<ObjCProtocolDecl *, SourceLocation> P
1050 = getCursorObjCProtocolRef(C);
1051 return translateSourceRange(P.first->getASTContext(), P.second);
1052 }
1053
1054 case CXCursor_ObjCClassRef: {
1055 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1056 = getCursorObjCClassRef(C);
1057
1058 return translateSourceRange(P.first->getASTContext(), P.second);
1059 }
1060
Douglas Gregora7bde202010-01-19 00:34:46 +00001061 default:
1062 // FIXME: Need a way to enumerate all non-reference cases.
1063 llvm_unreachable("Missed a reference kind");
1064 }
1065 }
Douglas Gregor97b98722010-01-19 23:20:36 +00001066
1067 if (clang_isExpression(C.kind))
1068 return translateSourceRange(getCursorContext(C),
1069 getCursorExpr(C)->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +00001070
1071 if (!getCursorDecl(C)) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00001072 CXSourceRange empty = { 0, 0, 0 };
Douglas Gregora7bde202010-01-19 00:34:46 +00001073 return empty;
1074 }
1075
1076 Decl *D = getCursorDecl(C);
1077 return translateSourceRange(D->getASTContext(), D->getSourceRange());
1078}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001079
1080CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001081 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001082 return C;
Douglas Gregor98258af2010-01-18 22:46:11 +00001083
Douglas Gregor97b98722010-01-19 23:20:36 +00001084 if (clang_isExpression(C.kind)) {
1085 Decl *D = getDeclFromExpr(getCursorExpr(C));
1086 if (D)
1087 return MakeCXCursor(D);
1088 return clang_getNullCursor();
1089 }
1090
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001091 if (!clang_isReference(C.kind))
1092 return clang_getNullCursor();
1093
1094 switch (C.kind) {
1095 case CXCursor_ObjCSuperClassRef:
1096 return MakeCXCursor(getCursorObjCSuperClassRef(C).first);
1097
1098 case CXCursor_ObjCProtocolRef: {
1099 return MakeCXCursor(getCursorObjCProtocolRef(C).first);
1100
1101 case CXCursor_ObjCClassRef:
1102 return MakeCXCursor(getCursorObjCClassRef(C).first);
1103
Douglas Gregorc5d1e932010-01-19 01:20:04 +00001104 default:
1105 // We would prefer to enumerate all non-reference cursor kinds here.
1106 llvm_unreachable("Unhandled reference cursor kind");
1107 break;
1108 }
1109 }
1110
1111 return clang_getNullCursor();
1112}
1113
Douglas Gregorb6998662010-01-19 19:34:47 +00001114CXCursor clang_getCursorDefinition(CXCursor C) {
1115 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001116 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001117 C = clang_getCursorReferenced(C);
1118 WasReference = true;
1119 }
1120
1121 if (!clang_isDeclaration(C.kind))
1122 return clang_getNullCursor();
1123
1124 Decl *D = getCursorDecl(C);
1125 if (!D)
1126 return clang_getNullCursor();
1127
1128 switch (D->getKind()) {
1129 // Declaration kinds that don't really separate the notions of
1130 // declaration and definition.
1131 case Decl::Namespace:
1132 case Decl::Typedef:
1133 case Decl::TemplateTypeParm:
1134 case Decl::EnumConstant:
1135 case Decl::Field:
1136 case Decl::ObjCIvar:
1137 case Decl::ObjCAtDefsField:
1138 case Decl::ImplicitParam:
1139 case Decl::ParmVar:
1140 case Decl::NonTypeTemplateParm:
1141 case Decl::TemplateTemplateParm:
1142 case Decl::ObjCCategoryImpl:
1143 case Decl::ObjCImplementation:
1144 case Decl::LinkageSpec:
1145 case Decl::ObjCPropertyImpl:
1146 case Decl::FileScopeAsm:
1147 case Decl::StaticAssert:
1148 case Decl::Block:
1149 return C;
1150
1151 // Declaration kinds that don't make any sense here, but are
1152 // nonetheless harmless.
1153 case Decl::TranslationUnit:
1154 case Decl::Template:
1155 case Decl::ObjCContainer:
1156 break;
1157
1158 // Declaration kinds for which the definition is not resolvable.
1159 case Decl::UnresolvedUsingTypename:
1160 case Decl::UnresolvedUsingValue:
1161 break;
1162
1163 case Decl::UsingDirective:
1164 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace());
1165
1166 case Decl::NamespaceAlias:
1167 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace());
1168
1169 case Decl::Enum:
1170 case Decl::Record:
1171 case Decl::CXXRecord:
1172 case Decl::ClassTemplateSpecialization:
1173 case Decl::ClassTemplatePartialSpecialization:
1174 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition(D->getASTContext()))
1175 return MakeCXCursor(Def);
1176 return clang_getNullCursor();
1177
1178 case Decl::Function:
1179 case Decl::CXXMethod:
1180 case Decl::CXXConstructor:
1181 case Decl::CXXDestructor:
1182 case Decl::CXXConversion: {
1183 const FunctionDecl *Def = 0;
1184 if (cast<FunctionDecl>(D)->getBody(Def))
1185 return MakeCXCursor(const_cast<FunctionDecl *>(Def));
1186 return clang_getNullCursor();
1187 }
1188
1189 case Decl::Var: {
1190 VarDecl *Var = cast<VarDecl>(D);
1191
1192 // Variables with initializers have definitions.
1193 const VarDecl *Def = 0;
1194 if (Var->getDefinition(Def))
1195 return MakeCXCursor(const_cast<VarDecl *>(Def));
1196
1197 // extern and private_extern variables are not definitions.
1198 if (Var->hasExternalStorage())
1199 return clang_getNullCursor();
1200
1201 // In-line static data members do not have definitions.
1202 if (Var->isStaticDataMember() && !Var->isOutOfLine())
1203 return clang_getNullCursor();
1204
1205 // All other variables are themselves definitions.
1206 return C;
1207 }
1208
1209 case Decl::FunctionTemplate: {
1210 const FunctionDecl *Def = 0;
1211 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
1212 return MakeCXCursor(Def->getDescribedFunctionTemplate());
1213 return clang_getNullCursor();
1214 }
1215
1216 case Decl::ClassTemplate: {
1217 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
1218 ->getDefinition(D->getASTContext()))
1219 return MakeCXCursor(
1220 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate());
1221 return clang_getNullCursor();
1222 }
1223
1224 case Decl::Using: {
1225 UsingDecl *Using = cast<UsingDecl>(D);
1226 CXCursor Def = clang_getNullCursor();
1227 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1228 SEnd = Using->shadow_end();
1229 S != SEnd; ++S) {
1230 if (Def != clang_getNullCursor()) {
1231 // FIXME: We have no way to return multiple results.
1232 return clang_getNullCursor();
1233 }
1234
1235 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl()));
1236 }
1237
1238 return Def;
1239 }
1240
1241 case Decl::UsingShadow:
1242 return clang_getCursorDefinition(
1243 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl()));
1244
1245 case Decl::ObjCMethod: {
1246 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1247 if (Method->isThisDeclarationADefinition())
1248 return C;
1249
1250 // Dig out the method definition in the associated
1251 // @implementation, if we have it.
1252 // FIXME: The ASTs should make finding the definition easier.
1253 if (ObjCInterfaceDecl *Class
1254 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
1255 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
1256 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
1257 Method->isInstanceMethod()))
1258 if (Def->isThisDeclarationADefinition())
1259 return MakeCXCursor(Def);
1260
1261 return clang_getNullCursor();
1262 }
1263
1264 case Decl::ObjCCategory:
1265 if (ObjCCategoryImplDecl *Impl
1266 = cast<ObjCCategoryDecl>(D)->getImplementation())
1267 return MakeCXCursor(Impl);
1268 return clang_getNullCursor();
1269
1270 case Decl::ObjCProtocol:
1271 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
1272 return C;
1273 return clang_getNullCursor();
1274
1275 case Decl::ObjCInterface:
1276 // There are two notions of a "definition" for an Objective-C
1277 // class: the interface and its implementation. When we resolved a
1278 // reference to an Objective-C class, produce the @interface as
1279 // the definition; when we were provided with the interface,
1280 // produce the @implementation as the definition.
1281 if (WasReference) {
1282 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
1283 return C;
1284 } else if (ObjCImplementationDecl *Impl
1285 = cast<ObjCInterfaceDecl>(D)->getImplementation())
1286 return MakeCXCursor(Impl);
1287 return clang_getNullCursor();
1288
1289 case Decl::ObjCProperty:
1290 // FIXME: We don't really know where to find the
1291 // ObjCPropertyImplDecls that implement this property.
1292 return clang_getNullCursor();
1293
1294 case Decl::ObjCCompatibleAlias:
1295 if (ObjCInterfaceDecl *Class
1296 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
1297 if (!Class->isForwardDecl())
1298 return MakeCXCursor(Class);
1299
1300 return clang_getNullCursor();
1301
1302 case Decl::ObjCForwardProtocol: {
1303 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
1304 if (Forward->protocol_size() == 1)
1305 return clang_getCursorDefinition(
1306 MakeCXCursor(*Forward->protocol_begin()));
1307
1308 // FIXME: Cannot return multiple definitions.
1309 return clang_getNullCursor();
1310 }
1311
1312 case Decl::ObjCClass: {
1313 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
1314 if (Class->size() == 1) {
1315 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
1316 if (!IFace->isForwardDecl())
1317 return MakeCXCursor(IFace);
1318 return clang_getNullCursor();
1319 }
1320
1321 // FIXME: Cannot return multiple definitions.
1322 return clang_getNullCursor();
1323 }
1324
1325 case Decl::Friend:
1326 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
1327 return clang_getCursorDefinition(MakeCXCursor(Friend));
1328 return clang_getNullCursor();
1329
1330 case Decl::FriendTemplate:
1331 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
1332 return clang_getCursorDefinition(MakeCXCursor(Friend));
1333 return clang_getNullCursor();
1334 }
1335
1336 return clang_getNullCursor();
1337}
1338
1339unsigned clang_isCursorDefinition(CXCursor C) {
1340 if (!clang_isDeclaration(C.kind))
1341 return 0;
1342
1343 return clang_getCursorDefinition(C) == C;
1344}
1345
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001346void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00001347 const char **startBuf,
1348 const char **endBuf,
1349 unsigned *startLine,
1350 unsigned *startColumn,
1351 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001352 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001353 assert(getCursorDecl(C) && "CXCursor has null decl");
1354 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00001355 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
1356 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekfb480492010-01-13 21:46:36 +00001357
Steve Naroff4ade6d62009-09-23 17:52:52 +00001358 SourceManager &SM = FD->getASTContext().getSourceManager();
1359 *startBuf = SM.getCharacterData(Body->getLBracLoc());
1360 *endBuf = SM.getCharacterData(Body->getRBracLoc());
1361 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
1362 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
1363 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
1364 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
1365}
Ted Kremenekfb480492010-01-13 21:46:36 +00001366
1367} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00001368
Ted Kremenekfb480492010-01-13 21:46:36 +00001369//===----------------------------------------------------------------------===//
1370// CXString Operations.
1371//===----------------------------------------------------------------------===//
1372
1373extern "C" {
1374const char *clang_getCString(CXString string) {
1375 return string.Spelling;
1376}
1377
1378void clang_disposeString(CXString string) {
1379 if (string.MustFreeString && string.Spelling)
1380 free((void*)string.Spelling);
1381}
1382} // end: extern "C"