blob: 1bda65f8e69c0b637d252029e6c77a3585944a65 [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"
16
Steve Naroff50398192009-08-28 15:28:48 +000017#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000018#include "clang/AST/StmtVisitor.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000019#include "clang/Lex/Lexer.h"
Douglas Gregor02465752009-10-16 21:24:31 +000020#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000021#include "llvm/System/Program.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000022
Ted Kremenekdb3d0da2010-01-05 20:55:39 +000023// Needed to define L_TMPNAM on some systems.
24#include <cstdio>
25
Steve Naroff50398192009-08-28 15:28:48 +000026using namespace clang;
27using namespace idx;
28
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000029//===----------------------------------------------------------------------===//
30// Crash Reporting.
31//===----------------------------------------------------------------------===//
32
33#ifdef __APPLE__
Ted Kremenek29b72842010-01-07 22:49:05 +000034#ifndef NDEBUG
35#define USE_CRASHTRACER
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000036#include "clang/Analysis/Support/SaveAndRestore.h"
37// Integrate with crash reporter.
38extern "C" const char *__crashreporter_info__;
Ted Kremenek29b72842010-01-07 22:49:05 +000039#define NUM_CRASH_STRINGS 16
40static unsigned crashtracer_counter = 0;
41static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
42static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
43
44static unsigned SetCrashTracerInfo(const char *str,
45 llvm::SmallString<1024> &AggStr) {
46
47 unsigned slot = crashtracer_counter;
48 while (crashtracer_strings[slot]) {
49 if (++slot == NUM_CRASH_STRINGS)
50 slot = 0;
51 }
52 crashtracer_strings[slot] = str;
53 crashtracer_counter = slot;
54
55 // We need to create an aggregate string because multiple threads
56 // may be in this method at one time. The crash reporter string
57 // will attempt to overapproximate the set of in-flight invocations
58 // of this function. Race conditions can still cause this goal
59 // to not be achieved.
60 {
61 llvm::raw_svector_ostream Out(AggStr);
62 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
63 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
64 }
65 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
66 return slot;
67}
68
69static void ResetCrashTracerInfo(unsigned slot) {
70 agg_crashtracer_strings[slot] = crashtracer_strings[slot] = 0;
71 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i) {
72 if (agg_crashtracer_strings[i]) {
73 __crashreporter_info__ = agg_crashtracer_strings[i];
74 return;
75 }
76 }
77 __crashreporter_info__ = 0;
78}
79
80namespace {
81class ArgsCrashTracerInfo {
82 llvm::SmallString<1024> CrashString;
83 llvm::SmallString<1024> AggregateString;
84 unsigned crashtracerSlot;
85public:
86 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
87 : crashtracerSlot(0)
88 {
89 {
90 llvm::raw_svector_ostream Out(CrashString);
91 Out << "ClangCIndex [createTranslationUnitFromSourceFile]: clang";
92 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
93 E=Args.end(); I!=E; ++I)
94 Out << ' ' << *I;
95 }
96 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
97 AggregateString);
98 }
99
100 ~ArgsCrashTracerInfo() {
101 ResetCrashTracerInfo(crashtracerSlot);
102 }
103};
104}
105#endif
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000106#endif
107
108//===----------------------------------------------------------------------===//
109// Visitors.
110//===----------------------------------------------------------------------===//
111
Steve Naroff89922f82009-08-31 00:59:03 +0000112namespace {
Ted Kremenekab188932010-01-05 19:32:54 +0000113static enum CXCursorKind TranslateDeclRefExpr(DeclRefExpr *DRE) {
Steve Naroff4ade6d62009-09-23 17:52:52 +0000114 NamedDecl *D = DRE->getDecl();
115 if (isa<VarDecl>(D))
116 return CXCursor_VarRef;
117 else if (isa<FunctionDecl>(D))
118 return CXCursor_FunctionRef;
119 else if (isa<EnumConstantDecl>(D))
120 return CXCursor_EnumConstantRef;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000121 else
Steve Naroff4ade6d62009-09-23 17:52:52 +0000122 return CXCursor_NotImplemented;
123}
124
125#if 0
126// Will be useful one day.
Steve Narofffb570422009-09-22 19:25:29 +0000127class CRefVisitor : public StmtVisitor<CRefVisitor> {
128 CXDecl CDecl;
129 CXDeclIterator Callback;
130 CXClientData CData;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000131
Steve Narofffb570422009-09-22 19:25:29 +0000132 void Call(enum CXCursorKind CK, Stmt *SRef) {
133 CXCursor C = { CK, CDecl, SRef };
134 Callback(CDecl, C, CData);
135 }
136
137public:
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000138 CRefVisitor(CXDecl C, CXDeclIterator cback, CXClientData D) :
Steve Narofffb570422009-09-22 19:25:29 +0000139 CDecl(C), Callback(cback), CData(D) {}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000140
Steve Narofffb570422009-09-22 19:25:29 +0000141 void VisitStmt(Stmt *S) {
142 for (Stmt::child_iterator C = S->child_begin(), CEnd = S->child_end();
143 C != CEnd; ++C)
144 Visit(*C);
145 }
146 void VisitDeclRefExpr(DeclRefExpr *Node) {
Steve Naroff4ade6d62009-09-23 17:52:52 +0000147 Call(TranslateDeclRefExpr(Node), Node);
Steve Narofffb570422009-09-22 19:25:29 +0000148 }
149 void VisitMemberExpr(MemberExpr *Node) {
150 Call(CXCursor_MemberRef, Node);
151 }
152 void VisitObjCMessageExpr(ObjCMessageExpr *Node) {
153 Call(CXCursor_ObjCSelectorRef, Node);
154 }
155 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *Node) {
156 Call(CXCursor_ObjCIvarRef, Node);
157 }
158};
Steve Naroff4ade6d62009-09-23 17:52:52 +0000159#endif
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000160
Steve Naroff89922f82009-08-31 00:59:03 +0000161// Translation Unit Visitor.
162class TUVisitor : public DeclVisitor<TUVisitor> {
163 CXTranslationUnit TUnit;
164 CXTranslationUnitIterator Callback;
Steve Naroff2b8ee6c2009-09-01 15:55:40 +0000165 CXClientData CData;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000166
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000167 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
168 // to the visitor. Declarations with a PCH level greater than this value will
169 // be suppressed.
170 unsigned MaxPCHLevel;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000171
Steve Naroff2b8ee6c2009-09-01 15:55:40 +0000172 void Call(enum CXCursorKind CK, NamedDecl *ND) {
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000173 // Filter any declarations that have a PCH level greater than what we allow.
174 if (ND->getPCHLevel() > MaxPCHLevel)
175 return;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000176
Steve Narofff96b5242009-10-28 20:44:47 +0000177 // Filter any implicit declarations (since the source info will be bogus).
178 if (ND->isImplicit())
179 return;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000180
Steve Narofffb570422009-09-22 19:25:29 +0000181 CXCursor C = { CK, ND, 0 };
Steve Naroff2b8ee6c2009-09-01 15:55:40 +0000182 Callback(TUnit, C, CData);
183 }
Steve Naroff89922f82009-08-31 00:59:03 +0000184public:
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000185 TUVisitor(CXTranslationUnit CTU,
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000186 CXTranslationUnitIterator cback, CXClientData D,
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000187 unsigned MaxPCHLevel) :
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000188 TUnit(CTU), Callback(cback), CData(D), MaxPCHLevel(MaxPCHLevel) {}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000189
Steve Naroff89922f82009-08-31 00:59:03 +0000190 void VisitTranslationUnitDecl(TranslationUnitDecl *D) {
191 VisitDeclContext(dyn_cast<DeclContext>(D));
192 }
193 void VisitDeclContext(DeclContext *DC) {
194 for (DeclContext::decl_iterator
195 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I)
196 Visit(*I);
197 }
Ted Kremenekef7fdc62009-11-17 07:02:15 +0000198
199 void VisitFunctionDecl(FunctionDecl *ND) {
200 Call(ND->isThisDeclarationADefinition() ? CXCursor_FunctionDefn
201 : CXCursor_FunctionDecl, ND);
202 }
203 void VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
204 Call(CXCursor_ObjCCategoryDecl, ND);
205 }
206 void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *ND) {
207 Call(CXCursor_ObjCCategoryDefn, ND);
208 }
209 void VisitObjCImplementationDecl(ObjCImplementationDecl *ND) {
210 Call(CXCursor_ObjCClassDefn, ND);
211 }
212 void VisitObjCInterfaceDecl(ObjCInterfaceDecl *ND) {
213 Call(CXCursor_ObjCInterfaceDecl, ND);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000214 }
Ted Kremenekef7fdc62009-11-17 07:02:15 +0000215 void VisitObjCProtocolDecl(ObjCProtocolDecl *ND) {
216 Call(CXCursor_ObjCProtocolDecl, ND);
Steve Naroff89922f82009-08-31 00:59:03 +0000217 }
218 void VisitTagDecl(TagDecl *ND) {
Steve Naroffc857ea42009-09-02 13:28:54 +0000219 switch (ND->getTagKind()) {
Daniel Dunbaracca7252009-11-30 20:42:49 +0000220 case TagDecl::TK_struct:
221 Call(CXCursor_StructDecl, ND);
222 break;
223 case TagDecl::TK_class:
224 Call(CXCursor_ClassDecl, ND);
225 break;
226 case TagDecl::TK_union:
227 Call(CXCursor_UnionDecl, ND);
228 break;
229 case TagDecl::TK_enum:
230 Call(CXCursor_EnumDecl, ND);
231 break;
Steve Naroffc857ea42009-09-02 13:28:54 +0000232 }
Steve Naroff89922f82009-08-31 00:59:03 +0000233 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000234 void VisitTypedefDecl(TypedefDecl *ND) {
235 Call(CXCursor_TypedefDecl, ND);
236 }
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000237 void VisitVarDecl(VarDecl *ND) {
238 Call(CXCursor_VarDecl, ND);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000239 }
Steve Naroff89922f82009-08-31 00:59:03 +0000240};
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000241
Steve Naroff89922f82009-08-31 00:59:03 +0000242
Steve Naroffc857ea42009-09-02 13:28:54 +0000243// Declaration visitor.
244class CDeclVisitor : public DeclVisitor<CDeclVisitor> {
245 CXDecl CDecl;
246 CXDeclIterator Callback;
247 CXClientData CData;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000248
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000249 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
250 // to the visitor. Declarations with a PCH level greater than this value will
251 // be suppressed.
252 unsigned MaxPCHLevel;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000253
Steve Naroffc857ea42009-09-02 13:28:54 +0000254 void Call(enum CXCursorKind CK, NamedDecl *ND) {
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000255 // Disable the callback when the context is equal to the visiting decl.
256 if (CDecl == ND && !clang_isReference(CK))
257 return;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000258
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000259 // Filter any declarations that have a PCH level greater than what we allow.
260 if (ND->getPCHLevel() > MaxPCHLevel)
261 return;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000262
Steve Narofffb570422009-09-22 19:25:29 +0000263 CXCursor C = { CK, ND, 0 };
Steve Naroffc857ea42009-09-02 13:28:54 +0000264 Callback(CDecl, C, CData);
265 }
Steve Naroff89922f82009-08-31 00:59:03 +0000266public:
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000267 CDeclVisitor(CXDecl C, CXDeclIterator cback, CXClientData D,
268 unsigned MaxPCHLevel) :
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000269 CDecl(C), Callback(cback), CData(D), MaxPCHLevel(MaxPCHLevel) {}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000270
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000271 void VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
272 // Issue callbacks for the containing class.
273 Call(CXCursor_ObjCClassRef, ND);
274 // FIXME: Issue callbacks for protocol refs.
275 VisitDeclContext(dyn_cast<DeclContext>(ND));
276 }
Steve Naroffc857ea42009-09-02 13:28:54 +0000277 void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000278 // Issue callbacks for super class.
Steve Narofff334b4e2009-09-02 18:26:48 +0000279 if (D->getSuperClass())
280 Call(CXCursor_ObjCSuperClassRef, D);
281
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000282 for (ObjCProtocolDecl::protocol_iterator I = D->protocol_begin(),
Daniel Dunbaracca7252009-11-30 20:42:49 +0000283 E = D->protocol_end(); I != E; ++I)
Steve Naroff9efa7672009-09-04 15:44:05 +0000284 Call(CXCursor_ObjCProtocolRef, *I);
Steve Naroffc857ea42009-09-02 13:28:54 +0000285 VisitDeclContext(dyn_cast<DeclContext>(D));
286 }
Steve Naroff9efa7672009-09-04 15:44:05 +0000287 void VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000288 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
Daniel Dunbaracca7252009-11-30 20:42:49 +0000289 E = PID->protocol_end(); I != E; ++I)
Steve Naroff9efa7672009-09-04 15:44:05 +0000290 Call(CXCursor_ObjCProtocolRef, *I);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000291
Steve Naroff9efa7672009-09-04 15:44:05 +0000292 VisitDeclContext(dyn_cast<DeclContext>(PID));
293 }
Steve Naroffc857ea42009-09-02 13:28:54 +0000294 void VisitTagDecl(TagDecl *D) {
295 VisitDeclContext(dyn_cast<DeclContext>(D));
296 }
297 void VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
298 VisitDeclContext(dyn_cast<DeclContext>(D));
299 }
300 void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
301 VisitDeclContext(dyn_cast<DeclContext>(D));
302 }
Steve Naroff89922f82009-08-31 00:59:03 +0000303 void VisitDeclContext(DeclContext *DC) {
304 for (DeclContext::decl_iterator
305 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I)
306 Visit(*I);
307 }
308 void VisitEnumConstantDecl(EnumConstantDecl *ND) {
Steve Naroffc857ea42009-09-02 13:28:54 +0000309 Call(CXCursor_EnumConstantDecl, ND);
Steve Naroff89922f82009-08-31 00:59:03 +0000310 }
311 void VisitFieldDecl(FieldDecl *ND) {
Steve Naroffc857ea42009-09-02 13:28:54 +0000312 Call(CXCursor_FieldDecl, ND);
313 }
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000314 void VisitVarDecl(VarDecl *ND) {
315 Call(CXCursor_VarDecl, ND);
316 }
317 void VisitParmVarDecl(ParmVarDecl *ND) {
318 Call(CXCursor_ParmDecl, ND);
319 }
Steve Naroffc857ea42009-09-02 13:28:54 +0000320 void VisitObjCPropertyDecl(ObjCPropertyDecl *ND) {
321 Call(CXCursor_ObjCPropertyDecl, ND);
Steve Naroff89922f82009-08-31 00:59:03 +0000322 }
323 void VisitObjCIvarDecl(ObjCIvarDecl *ND) {
Steve Naroffc857ea42009-09-02 13:28:54 +0000324 Call(CXCursor_ObjCIvarDecl, ND);
325 }
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000326 void VisitFunctionDecl(FunctionDecl *ND) {
327 if (ND->isThisDeclarationADefinition()) {
328 VisitDeclContext(dyn_cast<DeclContext>(ND));
Steve Naroff4ade6d62009-09-23 17:52:52 +0000329#if 0
330 // Not currently needed.
331 CompoundStmt *Body = dyn_cast<CompoundStmt>(ND->getBody());
Steve Narofffb570422009-09-22 19:25:29 +0000332 CRefVisitor RVisit(CDecl, Callback, CData);
Steve Naroff4ade6d62009-09-23 17:52:52 +0000333 RVisit.Visit(Body);
334#endif
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000335 }
336 }
Steve Naroffc857ea42009-09-02 13:28:54 +0000337 void VisitObjCMethodDecl(ObjCMethodDecl *ND) {
338 if (ND->getBody()) {
339 Call(ND->isInstanceMethod() ? CXCursor_ObjCInstanceMethodDefn
340 : CXCursor_ObjCClassMethodDefn, ND);
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000341 VisitDeclContext(dyn_cast<DeclContext>(ND));
Steve Naroffc857ea42009-09-02 13:28:54 +0000342 } else
343 Call(ND->isInstanceMethod() ? CXCursor_ObjCInstanceMethodDecl
344 : CXCursor_ObjCClassMethodDecl, ND);
Steve Naroff89922f82009-08-31 00:59:03 +0000345 }
346};
Ted Kremenekab188932010-01-05 19:32:54 +0000347} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000348
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000349static SourceLocation getLocationFromCursor(CXCursor C,
Daniel Dunbarc6190332009-11-08 04:13:53 +0000350 SourceManager &SourceMgr,
351 NamedDecl *ND) {
352 if (clang_isReference(C.kind)) {
353 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +0000354 case CXCursor_ObjCClassRef: {
355 if (isa<ObjCInterfaceDecl>(ND)) {
356 // FIXME: This is a hack (storing the parent decl in the stmt slot).
357 NamedDecl *parentDecl = static_cast<NamedDecl *>(C.stmt);
358 return parentDecl->getLocation();
Daniel Dunbarc6190332009-11-08 04:13:53 +0000359 }
Daniel Dunbaracca7252009-11-30 20:42:49 +0000360 ObjCCategoryDecl *OID = dyn_cast<ObjCCategoryDecl>(ND);
361 assert(OID && "clang_getCursorLine(): Missing category decl");
362 return OID->getClassInterface()->getLocation();
363 }
364 case CXCursor_ObjCSuperClassRef: {
365 ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ND);
366 assert(OID && "clang_getCursorLine(): Missing interface decl");
367 return OID->getSuperClassLoc();
368 }
369 case CXCursor_ObjCProtocolRef: {
370 ObjCProtocolDecl *OID = dyn_cast<ObjCProtocolDecl>(ND);
371 assert(OID && "clang_getCursorLine(): Missing protocol decl");
372 return OID->getLocation();
373 }
374 case CXCursor_ObjCSelectorRef: {
375 ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(
376 static_cast<Stmt *>(C.stmt));
377 assert(OME && "clang_getCursorLine(): Missing message expr");
378 return OME->getLeftLoc(); /* FIXME: should be a range */
379 }
380 case CXCursor_VarRef:
381 case CXCursor_FunctionRef:
382 case CXCursor_EnumConstantRef: {
383 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(
384 static_cast<Stmt *>(C.stmt));
385 assert(DRE && "clang_getCursorLine(): Missing decl ref expr");
386 return DRE->getLocation();
387 }
388 default:
389 return SourceLocation();
Daniel Dunbarc6190332009-11-08 04:13:53 +0000390 }
391 } else { // We have a declaration or a definition.
392 SourceLocation SLoc;
393 switch (ND->getKind()) {
Daniel Dunbaracca7252009-11-30 20:42:49 +0000394 case Decl::ObjCInterface: {
395 SLoc = dyn_cast<ObjCInterfaceDecl>(ND)->getClassLoc();
396 break;
397 }
398 case Decl::ObjCProtocol: {
399 SLoc = ND->getLocation(); /* FIXME: need to get the name location. */
400 break;
401 }
402 default: {
403 SLoc = ND->getLocation();
404 break;
405 }
Daniel Dunbarc6190332009-11-08 04:13:53 +0000406 }
407 if (SLoc.isInvalid())
408 return SourceLocation();
409 return SourceMgr.getSpellingLoc(SLoc); // handles macro instantiations.
410 }
411}
412
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000413static CXString createCXString(const char *String, bool DupString = false) {
414 CXString Str;
415 if (DupString) {
416 Str.Spelling = strdup(String);
417 Str.MustFreeString = 1;
418 } else {
419 Str.Spelling = String;
420 Str.MustFreeString = 0;
421 }
422 return Str;
423}
424
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000425extern "C" {
426
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000427CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000428 int displayDiagnostics) {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000429 CIndexer *CIdxr = new CIndexer(new Program());
430 if (excludeDeclarationsFromPCH)
431 CIdxr->setOnlyLocalDecls();
432 if (displayDiagnostics)
433 CIdxr->setDisplayDiagnostics();
434 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +0000435}
436
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000437void clang_disposeIndex(CXIndex CIdx) {
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000438 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000439 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000440}
441
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000442void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
443 assert(CIdx && "Passed null CXIndex");
444 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
445 CXXIdx->setUseExternalASTGeneration(value);
446}
447
Steve Naroff50398192009-08-28 15:28:48 +0000448// FIXME: need to pass back error info.
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000449CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
450 const char *ast_filename) {
Steve Naroff50398192009-08-28 15:28:48 +0000451 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000452 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000453
Daniel Dunbar5262fda2009-12-03 01:45:44 +0000454 return ASTUnit::LoadFromPCHFile(ast_filename, CXXIdx->getDiags(),
455 CXXIdx->getOnlyLocalDecls(),
456 /* UseBumpAllocator = */ true);
Steve Naroff600866c2009-08-27 19:51:58 +0000457}
458
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000459CXTranslationUnit
460clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
461 const char *source_filename,
462 int num_command_line_args,
463 const char **command_line_args) {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000464 assert(CIdx && "Passed null CXIndex");
465 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
466
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000467 if (!CXXIdx->getUseExternalASTGeneration()) {
468 llvm::SmallVector<const char *, 16> Args;
469
470 // The 'source_filename' argument is optional. If the caller does not
471 // specify it then it is assumed that the source file is specified
472 // in the actual argument list.
473 if (source_filename)
474 Args.push_back(source_filename);
475 Args.insert(Args.end(), command_line_args,
476 command_line_args + num_command_line_args);
477
Daniel Dunbar94220972009-12-05 02:17:18 +0000478 unsigned NumErrors = CXXIdx->getDiags().getNumErrors();
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000479
Ted Kremenek29b72842010-01-07 22:49:05 +0000480#ifdef USE_CRASHTRACER
481 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000482#endif
483
Daniel Dunbar94220972009-12-05 02:17:18 +0000484 llvm::OwningPtr<ASTUnit> Unit(
485 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Daniel Dunbar869824e2009-12-13 03:46:13 +0000486 CXXIdx->getDiags(),
487 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +0000488 CXXIdx->getOnlyLocalDecls(),
489 /* UseBumpAllocator = */ true));
Ted Kremenek29b72842010-01-07 22:49:05 +0000490
Daniel Dunbar94220972009-12-05 02:17:18 +0000491 // FIXME: Until we have broader testing, just drop the entire AST if we
492 // encountered an error.
493 if (NumErrors != CXXIdx->getDiags().getNumErrors())
494 return 0;
495
496 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000497 }
498
Ted Kremenek139ba862009-10-22 00:03:57 +0000499 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000500 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000501
Ted Kremenek139ba862009-10-22 00:03:57 +0000502 // First add the complete path to the 'clang' executable.
503 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000504 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000505
Ted Kremenek139ba862009-10-22 00:03:57 +0000506 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000507 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000508
Ted Kremenek139ba862009-10-22 00:03:57 +0000509 // The 'source_filename' argument is optional. If the caller does not
510 // specify it then it is assumed that the source file is specified
511 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000512 if (source_filename)
513 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +0000514
Steve Naroff37b5ac22009-10-15 20:50:09 +0000515 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +0000516 argv.push_back("-o");
Steve Naroff37b5ac22009-10-15 20:50:09 +0000517 char astTmpFile[L_tmpnam];
Ted Kremenek74cd0692009-10-15 23:21:22 +0000518 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +0000519
520 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
521 for (int i = 0; i < num_command_line_args; ++i)
522 if (const char *arg = command_line_args[i]) {
523 if (strcmp(arg, "-o") == 0) {
524 ++i; // Also skip the matching argument.
525 continue;
526 }
527 if (strcmp(arg, "-emit-ast") == 0 ||
528 strcmp(arg, "-c") == 0 ||
529 strcmp(arg, "-fsyntax-only") == 0) {
530 continue;
531 }
532
533 // Keep the argument.
534 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000535 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000536
Ted Kremenek139ba862009-10-22 00:03:57 +0000537 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000538 argv.push_back(NULL);
539
Ted Kremenekfeb15e32009-10-26 22:14:08 +0000540 // Invoke 'clang'.
541 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
542 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +0000543 std::string ErrMsg;
Ted Kremenekc46e4632009-10-19 22:27:32 +0000544 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DevNull, NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +0000545 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
546 /* redirects */ !CXXIdx->getDisplayDiagnostics() ? &Redirects[0] : NULL,
547 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000548
Ted Kremenek0854d702009-11-10 19:18:52 +0000549 if (CXXIdx->getDisplayDiagnostics() && !ErrMsg.empty()) {
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000550 llvm::errs() << "clang_createTranslationUnitFromSourceFile: " << ErrMsg
Daniel Dunbaracca7252009-11-30 20:42:49 +0000551 << '\n' << "Arguments: \n";
Ted Kremenek379afec2009-10-22 03:24:01 +0000552 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Ted Kremenek779e5f42009-10-26 22:08:39 +0000553 I!=E; ++I) {
554 if (*I)
555 llvm::errs() << ' ' << *I << '\n';
556 }
557 llvm::errs() << '\n';
Ted Kremenek379afec2009-10-22 03:24:01 +0000558 }
Benjamin Kramer0829a832009-10-18 11:19:36 +0000559
Steve Naroff37b5ac22009-10-15 20:50:09 +0000560 // Finally, we create the translation unit from the ast file.
Steve Naroffe19944c2009-10-15 22:23:48 +0000561 ASTUnit *ATU = static_cast<ASTUnit *>(
Daniel Dunbaracca7252009-11-30 20:42:49 +0000562 clang_createTranslationUnit(CIdx, astTmpFile));
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000563 if (ATU)
564 ATU->unlinkTemporaryFile();
Steve Naroffe19944c2009-10-15 22:23:48 +0000565 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +0000566}
567
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000568void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000569 assert(CTUnit && "Passed null CXTranslationUnit");
570 delete static_cast<ASTUnit *>(CTUnit);
571}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000572
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000573CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000574 assert(CTUnit && "Passed null CXTranslationUnit");
Steve Naroff77accc12009-09-03 18:19:54 +0000575 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000576 return createCXString(CXXUnit->getOriginalSourceFileName().c_str(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000577}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +0000578
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000579void clang_loadTranslationUnit(CXTranslationUnit CTUnit,
Steve Naroffc857ea42009-09-02 13:28:54 +0000580 CXTranslationUnitIterator callback,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000581 CXClientData CData) {
Steve Naroff50398192009-08-28 15:28:48 +0000582 assert(CTUnit && "Passed null CXTranslationUnit");
583 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
584 ASTContext &Ctx = CXXUnit->getASTContext();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000585
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000586 unsigned PCHLevel = Decl::MaxPCHLevel;
587
588 // Set the PCHLevel to filter out unwanted decls if requested.
589 if (CXXUnit->getOnlyLocalDecls()) {
590 PCHLevel = 0;
591
592 // If the main input was an AST, bump the level.
593 if (CXXUnit->isMainFileAST())
594 ++PCHLevel;
595 }
596
597 TUVisitor DVisit(CTUnit, callback, CData, PCHLevel);
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000598
599 // If using a non-AST based ASTUnit, iterate over the stored list of top-level
600 // decls.
601 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls()) {
602 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
603 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
604 ie = TLDs.end(); it != ie; ++it) {
605 DVisit.Visit(*it);
606 }
607 } else
608 DVisit.Visit(Ctx.getTranslationUnitDecl());
Steve Naroff600866c2009-08-27 19:51:58 +0000609}
610
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000611void clang_loadDeclaration(CXDecl Dcl,
612 CXDeclIterator callback,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000613 CXClientData CData) {
Steve Naroffc857ea42009-09-02 13:28:54 +0000614 assert(Dcl && "Passed null CXDecl");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000615
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000616 CDeclVisitor DVisit(Dcl, callback, CData,
617 static_cast<Decl *>(Dcl)->getPCHLevel());
Steve Naroffc857ea42009-09-02 13:28:54 +0000618 DVisit.Visit(static_cast<Decl *>(Dcl));
Steve Naroff600866c2009-08-27 19:51:58 +0000619}
620
Steve Naroff600866c2009-08-27 19:51:58 +0000621//
622// CXDecl Operations.
623//
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000624
625CXEntity clang_getEntityFromDecl(CXDecl) {
Steve Naroff600866c2009-08-27 19:51:58 +0000626 return 0;
627}
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000628
629CXString clang_getDeclSpelling(CXDecl AnonDecl) {
Steve Naroff89922f82009-08-31 00:59:03 +0000630 assert(AnonDecl && "Passed null CXDecl");
631 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
Steve Naroffef0cef62009-11-09 17:45:52 +0000632
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000633 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
634 return createCXString(OMD->getSelector().getAsString().c_str(), true);
635
636 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Steve Naroff0d69b8c2009-10-29 21:11:04 +0000637 // No, this isn't the same as the code below. getIdentifier() is non-virtual
638 // and returns different names. NamedDecl returns the class name and
639 // ObjCCategoryImplDecl returns the category name.
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000640 return createCXString(CIMP->getIdentifier()->getNameStart());
641
642 if (ND->getIdentifier())
643 return createCXString(ND->getIdentifier()->getNameStart());
644
645 return createCXString("");
Steve Naroff600866c2009-08-27 19:51:58 +0000646}
Steve Narofff334b4e2009-09-02 18:26:48 +0000647
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000648unsigned clang_getDeclLine(CXDecl AnonDecl) {
Steve Naroff699a07d2009-09-25 21:32:34 +0000649 assert(AnonDecl && "Passed null CXDecl");
650 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
651 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
652 return SourceMgr.getSpellingLineNumber(ND->getLocation());
653}
654
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000655unsigned clang_getDeclColumn(CXDecl AnonDecl) {
Steve Naroff699a07d2009-09-25 21:32:34 +0000656 assert(AnonDecl && "Passed null CXDecl");
657 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
658 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Steve Naroff74165242009-09-25 22:15:54 +0000659 return SourceMgr.getSpellingColumnNumber(ND->getLocation());
Steve Naroff699a07d2009-09-25 21:32:34 +0000660}
Ted Kremenekfe6fd3d2010-01-05 23:18:49 +0000661
662CXDeclExtent clang_getDeclExtent(CXDecl AnonDecl) {
663 assert(AnonDecl && "Passed null CXDecl");
664 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
Ted Kremenekd8210652010-01-06 23:43:31 +0000665 SourceManager &SM = ND->getASTContext().getSourceManager();
Ted Kremenekfe6fd3d2010-01-05 23:18:49 +0000666 SourceRange R = ND->getSourceRange();
667
Ted Kremenekd8210652010-01-06 23:43:31 +0000668 SourceLocation Begin = SM.getInstantiationLoc(R.getBegin());
669 SourceLocation End = SM.getInstantiationLoc(R.getEnd());
670
671 if (!Begin.isValid()) {
672 CXDeclExtent extent = { { 0, 0 }, { 0, 0 } };
673 return extent;
674 }
Ted Kremenekfe6fd3d2010-01-05 23:18:49 +0000675
Ted Kremenekd8210652010-01-06 23:43:31 +0000676 // FIXME: This is largely copy-paste from
677 ///TextDiagnosticPrinter::HighlightRange. When it is clear that this is
678 // what we want the two routines should be refactored.
Ted Kremenekfe6fd3d2010-01-05 23:18:49 +0000679
Ted Kremenekd8210652010-01-06 23:43:31 +0000680 // If the End location and the start location are the same and are a macro
681 // location, then the range was something that came from a macro expansion
682 // or _Pragma. If this is an object-like macro, the best we can do is to
683 // get the range. If this is a function-like macro, we'd also like to
684 // get the arguments.
685 if (Begin == End && R.getEnd().isMacroID())
686 End = SM.getInstantiationRange(R.getEnd()).second;
687
688 assert(SM.getFileID(Begin) == SM.getFileID(End));
689 unsigned StartLineNo = SM.getInstantiationLineNumber(Begin);
690 unsigned EndLineNo = SM.getInstantiationLineNumber(End);
Ted Kremenekfe6fd3d2010-01-05 23:18:49 +0000691
Ted Kremenekd8210652010-01-06 23:43:31 +0000692 // Compute the column number of the start. Keep the column based at 1.
693 unsigned StartColNo = SM.getInstantiationColumnNumber(Begin);
694
695 // Compute the column number of the end.
696 unsigned EndColNo = SM.getInstantiationColumnNumber(End);
697 if (EndColNo) {
698 // Offset the end column by 1 so that we point to the last character
699 // in the last token.
700 --EndColNo;
701
702 // Add in the length of the token, so that we cover multi-char tokens.
703 ASTContext &Ctx = ND->getTranslationUnitDecl()->getASTContext();
704 const LangOptions &LOpts = Ctx.getLangOptions();
705
706 EndColNo += Lexer::MeasureTokenLength(End, SM, LOpts);
707 }
708
709 // Package up the line/column data and return to the caller.
710 CXDeclExtent extent = { { StartLineNo, StartColNo },
711 { EndLineNo, EndColNo } };
Ted Kremenekfe6fd3d2010-01-05 23:18:49 +0000712 return extent;
713}
Steve Naroff699a07d2009-09-25 21:32:34 +0000714
Steve Naroff88145032009-10-27 14:35:18 +0000715static const FileEntry *getFileEntryFromSourceLocation(SourceManager &SMgr,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000716 SourceLocation SLoc) {
Steve Naroff88145032009-10-27 14:35:18 +0000717 FileID FID;
718 if (SLoc.isFileID())
719 FID = SMgr.getFileID(SLoc);
720 else
721 FID = SMgr.getDecomposedSpellingLoc(SLoc).first;
722 return SMgr.getFileEntryForID(FID);
723}
724
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000725CXFile clang_getDeclSourceFile(CXDecl AnonDecl) {
Steve Naroff88145032009-10-27 14:35:18 +0000726 assert(AnonDecl && "Passed null CXDecl");
Steve Naroffee9405e2009-09-25 21:45:39 +0000727 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
728 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Steve Naroff88145032009-10-27 14:35:18 +0000729 return (void *)getFileEntryFromSourceLocation(SourceMgr, ND->getLocation());
730}
731
732const char *clang_getFileName(CXFile SFile) {
733 assert(SFile && "Passed null CXFile");
734 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
735 return FEnt->getName();
736}
737
738time_t clang_getFileTime(CXFile SFile) {
739 assert(SFile && "Passed null CXFile");
740 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
741 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +0000742}
743
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000744CXString clang_getCursorSpelling(CXCursor C) {
Steve Narofff334b4e2009-09-02 18:26:48 +0000745 assert(C.decl && "CXCursor has null decl");
746 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
Steve Naroffef0cef62009-11-09 17:45:52 +0000747
Steve Narofff334b4e2009-09-02 18:26:48 +0000748 if (clang_isReference(C.kind)) {
749 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +0000750 case CXCursor_ObjCSuperClassRef: {
751 ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ND);
752 assert(OID && "clang_getCursorLine(): Missing interface decl");
753 return createCXString(OID->getSuperClass()->getIdentifier()
754 ->getNameStart());
755 }
756 case CXCursor_ObjCClassRef: {
757 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ND))
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000758 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +0000759
760 ObjCCategoryDecl *OCD = dyn_cast<ObjCCategoryDecl>(ND);
761 assert(OCD && "clang_getCursorLine(): Missing category decl");
762 return createCXString(OCD->getClassInterface()->getIdentifier()
763 ->getNameStart());
764 }
765 case CXCursor_ObjCProtocolRef: {
766 ObjCProtocolDecl *OID = dyn_cast<ObjCProtocolDecl>(ND);
767 assert(OID && "clang_getCursorLine(): Missing protocol decl");
768 return createCXString(OID->getIdentifier()->getNameStart());
769 }
770 case CXCursor_ObjCSelectorRef: {
771 ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(
772 static_cast<Stmt *>(C.stmt));
773 assert(OME && "clang_getCursorLine(): Missing message expr");
774 return createCXString(OME->getSelector().getAsString().c_str(), true);
775 }
776 case CXCursor_VarRef:
777 case CXCursor_FunctionRef:
778 case CXCursor_EnumConstantRef: {
779 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(
780 static_cast<Stmt *>(C.stmt));
781 assert(DRE && "clang_getCursorLine(): Missing decl ref expr");
782 return createCXString(DRE->getDecl()->getIdentifier()->getNameStart());
783 }
784 default:
785 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +0000786 }
787 }
788 return clang_getDeclSpelling(C.decl);
789}
790
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000791const char *clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +0000792 switch (Kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +0000793 case CXCursor_FunctionDecl: return "FunctionDecl";
794 case CXCursor_TypedefDecl: return "TypedefDecl";
795 case CXCursor_EnumDecl: return "EnumDecl";
796 case CXCursor_EnumConstantDecl: return "EnumConstantDecl";
797 case CXCursor_StructDecl: return "StructDecl";
798 case CXCursor_UnionDecl: return "UnionDecl";
799 case CXCursor_ClassDecl: return "ClassDecl";
800 case CXCursor_FieldDecl: return "FieldDecl";
801 case CXCursor_VarDecl: return "VarDecl";
802 case CXCursor_ParmDecl: return "ParmDecl";
803 case CXCursor_ObjCInterfaceDecl: return "ObjCInterfaceDecl";
804 case CXCursor_ObjCCategoryDecl: return "ObjCCategoryDecl";
805 case CXCursor_ObjCProtocolDecl: return "ObjCProtocolDecl";
806 case CXCursor_ObjCPropertyDecl: return "ObjCPropertyDecl";
807 case CXCursor_ObjCIvarDecl: return "ObjCIvarDecl";
808 case CXCursor_ObjCInstanceMethodDecl: return "ObjCInstanceMethodDecl";
809 case CXCursor_ObjCClassMethodDecl: return "ObjCClassMethodDecl";
810 case CXCursor_FunctionDefn: return "FunctionDefn";
811 case CXCursor_ObjCInstanceMethodDefn: return "ObjCInstanceMethodDefn";
812 case CXCursor_ObjCClassMethodDefn: return "ObjCClassMethodDefn";
813 case CXCursor_ObjCClassDefn: return "ObjCClassDefn";
814 case CXCursor_ObjCCategoryDefn: return "ObjCCategoryDefn";
815 case CXCursor_ObjCSuperClassRef: return "ObjCSuperClassRef";
816 case CXCursor_ObjCProtocolRef: return "ObjCProtocolRef";
817 case CXCursor_ObjCClassRef: return "ObjCClassRef";
818 case CXCursor_ObjCSelectorRef: return "ObjCSelectorRef";
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000819
Daniel Dunbaracca7252009-11-30 20:42:49 +0000820 case CXCursor_VarRef: return "VarRef";
821 case CXCursor_FunctionRef: return "FunctionRef";
822 case CXCursor_EnumConstantRef: return "EnumConstantRef";
823 case CXCursor_MemberRef: return "MemberRef";
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000824
Daniel Dunbaracca7252009-11-30 20:42:49 +0000825 case CXCursor_InvalidFile: return "InvalidFile";
826 case CXCursor_NoDeclFound: return "NoDeclFound";
827 case CXCursor_NotImplemented: return "NotImplemented";
828 default: return "<not implemented>";
Steve Naroff89922f82009-08-31 00:59:03 +0000829 }
Steve Naroff600866c2009-08-27 19:51:58 +0000830}
Steve Naroff89922f82009-08-31 00:59:03 +0000831
Steve Naroff9efa7672009-09-04 15:44:05 +0000832static enum CXCursorKind TranslateKind(Decl *D) {
833 switch (D->getKind()) {
Daniel Dunbaracca7252009-11-30 20:42:49 +0000834 case Decl::Function: return CXCursor_FunctionDecl;
835 case Decl::Typedef: return CXCursor_TypedefDecl;
836 case Decl::Enum: return CXCursor_EnumDecl;
837 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
838 case Decl::Record: return CXCursor_StructDecl; // FIXME: union/class
839 case Decl::Field: return CXCursor_FieldDecl;
840 case Decl::Var: return CXCursor_VarDecl;
841 case Decl::ParmVar: return CXCursor_ParmDecl;
842 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
843 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
844 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
845 case Decl::ObjCMethod: {
846 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D);
847 if (MD->isInstanceMethod())
848 return CXCursor_ObjCInstanceMethodDecl;
849 return CXCursor_ObjCClassMethodDecl;
850 }
851 default: break;
Steve Naroff9efa7672009-09-04 15:44:05 +0000852 }
Steve Naroff77128dd2009-09-15 20:25:34 +0000853 return CXCursor_NotImplemented;
Steve Naroff9efa7672009-09-04 15:44:05 +0000854}
Steve Naroff600866c2009-08-27 19:51:58 +0000855//
856// CXCursor Operations.
857//
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000858
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000859CXCursor clang_getCursor(CXTranslationUnit CTUnit, const char *source_name,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000860 unsigned line, unsigned column) {
Steve Naroff9efa7672009-09-04 15:44:05 +0000861 assert(CTUnit && "Passed null CXTranslationUnit");
862 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000863
Steve Naroff9efa7672009-09-04 15:44:05 +0000864 FileManager &FMgr = CXXUnit->getFileManager();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000865 const FileEntry *File = FMgr.getFile(source_name,
866 source_name+strlen(source_name));
Steve Naroff77128dd2009-09-15 20:25:34 +0000867 if (!File) {
Steve Narofffb570422009-09-22 19:25:29 +0000868 CXCursor C = { CXCursor_InvalidFile, 0, 0 };
Steve Naroff77128dd2009-09-15 20:25:34 +0000869 return C;
870 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000871 SourceLocation SLoc =
Steve Naroff9efa7672009-09-04 15:44:05 +0000872 CXXUnit->getSourceManager().getLocation(File, line, column);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000873
Steve Narofff96b5242009-10-28 20:44:47 +0000874 ASTLocation LastLoc = CXXUnit->getLastASTLocation();
875
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000876 ASTLocation ALoc = ResolveLocationInAST(CXXUnit->getASTContext(), SLoc,
Steve Narofff96b5242009-10-28 20:44:47 +0000877 &LastLoc);
878 if (ALoc.isValid())
879 CXXUnit->setLastASTLocation(ALoc);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000880
Argyrios Kyrtzidisf4526e32009-09-29 19:44:27 +0000881 Decl *Dcl = ALoc.getParentDecl();
Argyrios Kyrtzidis05a76512009-09-29 19:45:58 +0000882 if (ALoc.isNamedRef())
883 Dcl = ALoc.AsNamedRef().ND;
Argyrios Kyrtzidisf4526e32009-09-29 19:44:27 +0000884 Stmt *Stm = ALoc.dyn_AsStmt();
Steve Naroff4ade6d62009-09-23 17:52:52 +0000885 if (Dcl) {
886 if (Stm) {
887 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Stm)) {
888 CXCursor C = { TranslateDeclRefExpr(DRE), Dcl, Stm };
889 return C;
890 } else if (ObjCMessageExpr *MExp = dyn_cast<ObjCMessageExpr>(Stm)) {
891 CXCursor C = { CXCursor_ObjCSelectorRef, Dcl, MExp };
892 return C;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000893 }
Steve Naroff4ade6d62009-09-23 17:52:52 +0000894 // Fall through...treat as a decl, not a ref.
895 }
Steve Naroff85e2db72009-10-01 00:31:07 +0000896 if (ALoc.isNamedRef()) {
897 if (isa<ObjCInterfaceDecl>(Dcl)) {
898 CXCursor C = { CXCursor_ObjCClassRef, Dcl, ALoc.getParentDecl() };
899 return C;
900 }
901 if (isa<ObjCProtocolDecl>(Dcl)) {
902 CXCursor C = { CXCursor_ObjCProtocolRef, Dcl, ALoc.getParentDecl() };
903 return C;
904 }
905 }
Daniel Dunbaracca7252009-11-30 20:42:49 +0000906 CXCursor C = { TranslateKind(Dcl), Dcl, 0 };
Steve Naroff77128dd2009-09-15 20:25:34 +0000907 return C;
908 }
Steve Narofffb570422009-09-22 19:25:29 +0000909 CXCursor C = { CXCursor_NoDeclFound, 0, 0 };
Steve Naroff9efa7672009-09-04 15:44:05 +0000910 return C;
Steve Naroff600866c2009-08-27 19:51:58 +0000911}
912
Ted Kremenek73885552009-11-17 19:28:59 +0000913CXCursor clang_getNullCursor(void) {
914 CXCursor C;
915 C.kind = CXCursor_InvalidFile;
916 C.decl = NULL;
917 C.stmt = NULL;
918 return C;
919}
920
921unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
922 return X.kind == Y.kind && X.decl == Y.decl && X.stmt == Y.stmt;
923}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000924
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000925CXCursor clang_getCursorFromDecl(CXDecl AnonDecl) {
Steve Naroff77128dd2009-09-15 20:25:34 +0000926 assert(AnonDecl && "Passed null CXDecl");
927 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000928
Steve Narofffb570422009-09-22 19:25:29 +0000929 CXCursor C = { TranslateKind(ND), ND, 0 };
Steve Naroff77128dd2009-09-15 20:25:34 +0000930 return C;
931}
932
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000933unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +0000934 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
935}
936
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000937unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +0000938 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
939}
Steve Naroff2d4d6292009-08-31 14:26:51 +0000940
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000941unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +0000942 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
943}
944
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000945unsigned clang_isDefinition(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +0000946 return K >= CXCursor_FirstDefn && K <= CXCursor_LastDefn;
947}
948
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000949CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +0000950 return C.kind;
951}
952
Steve Naroff699a07d2009-09-25 21:32:34 +0000953static Decl *getDeclFromExpr(Stmt *E) {
954 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
955 return RefExpr->getDecl();
956 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
957 return ME->getMemberDecl();
958 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
959 return RE->getDecl();
960
961 if (CallExpr *CE = dyn_cast<CallExpr>(E))
962 return getDeclFromExpr(CE->getCallee());
963 if (CastExpr *CE = dyn_cast<CastExpr>(E))
964 return getDeclFromExpr(CE->getSubExpr());
965 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
966 return OME->getMethodDecl();
967
968 return 0;
969}
970
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000971CXDecl clang_getCursorDecl(CXCursor C) {
Steve Naroff699a07d2009-09-25 21:32:34 +0000972 if (clang_isDeclaration(C.kind))
973 return C.decl;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000974
Steve Naroff699a07d2009-09-25 21:32:34 +0000975 if (clang_isReference(C.kind)) {
Steve Naroff85e2db72009-10-01 00:31:07 +0000976 if (C.stmt) {
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000977 if (C.kind == CXCursor_ObjCClassRef ||
Steve Narofff9adf8f2009-10-05 17:58:19 +0000978 C.kind == CXCursor_ObjCProtocolRef)
Steve Naroff85e2db72009-10-01 00:31:07 +0000979 return static_cast<Stmt *>(C.stmt);
980 else
981 return getDeclFromExpr(static_cast<Stmt *>(C.stmt));
982 } else
Steve Naroff699a07d2009-09-25 21:32:34 +0000983 return C.decl;
984 }
985 return 0;
Steve Naroff9efa7672009-09-04 15:44:05 +0000986}
987
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000988unsigned clang_getCursorLine(CXCursor C) {
Steve Naroff2d4d6292009-08-31 14:26:51 +0000989 assert(C.decl && "CXCursor has null decl");
990 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
Steve Naroff2d4d6292009-08-31 14:26:51 +0000991 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000992
Steve Narofff334b4e2009-09-02 18:26:48 +0000993 SourceLocation SLoc = getLocationFromCursor(C, SourceMgr, ND);
Steve Naroff2d4d6292009-08-31 14:26:51 +0000994 return SourceMgr.getSpellingLineNumber(SLoc);
Steve Naroff600866c2009-08-27 19:51:58 +0000995}
Steve Narofff334b4e2009-09-02 18:26:48 +0000996
Steve Naroffef0cef62009-11-09 17:45:52 +0000997const char *clang_getCString(CXString string) {
998 return string.Spelling;
999}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001000
Steve Naroffef0cef62009-11-09 17:45:52 +00001001void clang_disposeString(CXString string) {
Benjamin Kramer858e5de2009-11-09 18:24:53 +00001002 if (string.MustFreeString)
1003 free((void*)string.Spelling);
Steve Naroffef0cef62009-11-09 17:45:52 +00001004}
1005
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001006unsigned clang_getCursorColumn(CXCursor C) {
Steve Naroff2d4d6292009-08-31 14:26:51 +00001007 assert(C.decl && "CXCursor has null decl");
1008 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
Steve Naroff2d4d6292009-08-31 14:26:51 +00001009 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001010
Steve Narofff334b4e2009-09-02 18:26:48 +00001011 SourceLocation SLoc = getLocationFromCursor(C, SourceMgr, ND);
Steve Naroff2d4d6292009-08-31 14:26:51 +00001012 return SourceMgr.getSpellingColumnNumber(SLoc);
Steve Naroff600866c2009-08-27 19:51:58 +00001013}
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001014
1015const char *clang_getCursorSource(CXCursor C) {
Steve Naroff2d4d6292009-08-31 14:26:51 +00001016 assert(C.decl && "CXCursor has null decl");
1017 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
Steve Naroff2d4d6292009-08-31 14:26:51 +00001018 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001019
Steve Narofff334b4e2009-09-02 18:26:48 +00001020 SourceLocation SLoc = getLocationFromCursor(C, SourceMgr, ND);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001021
Ted Kremenek9298cfc2009-11-17 05:31:58 +00001022 if (SLoc.isFileID()) {
1023 const char *bufferName = SourceMgr.getBufferName(SLoc);
1024 return bufferName[0] == '<' ? NULL : bufferName;
1025 }
Douglas Gregor02465752009-10-16 21:24:31 +00001026
1027 // Retrieve the file in which the macro was instantiated, then provide that
1028 // buffer name.
1029 // FIXME: Do we want to give specific macro-instantiation information?
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001030 const llvm::MemoryBuffer *Buffer
Douglas Gregor02465752009-10-16 21:24:31 +00001031 = SourceMgr.getBuffer(SourceMgr.getDecomposedSpellingLoc(SLoc).first);
1032 if (!Buffer)
1033 return 0;
1034
1035 return Buffer->getBufferIdentifier();
Steve Naroff600866c2009-08-27 19:51:58 +00001036}
1037
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001038CXFile clang_getCursorSourceFile(CXCursor C) {
Steve Naroff88145032009-10-27 14:35:18 +00001039 assert(C.decl && "CXCursor has null decl");
1040 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
1041 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001042
Steve Naroff88145032009-10-27 14:35:18 +00001043 return (void *)getFileEntryFromSourceLocation(SourceMgr,
Daniel Dunbaracca7252009-11-30 20:42:49 +00001044 getLocationFromCursor(C,SourceMgr, ND));
Steve Naroff88145032009-10-27 14:35:18 +00001045}
1046
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001047void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00001048 const char **startBuf,
1049 const char **endBuf,
1050 unsigned *startLine,
1051 unsigned *startColumn,
1052 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001053 unsigned *endColumn) {
Steve Naroff4ade6d62009-09-23 17:52:52 +00001054 assert(C.decl && "CXCursor has null decl");
1055 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
1056 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
1057 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001058
Steve Naroff4ade6d62009-09-23 17:52:52 +00001059 SourceManager &SM = FD->getASTContext().getSourceManager();
1060 *startBuf = SM.getCharacterData(Body->getLBracLoc());
1061 *endBuf = SM.getCharacterData(Body->getRBracLoc());
1062 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
1063 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
1064 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
1065 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
1066}
1067
Steve Naroff600866c2009-08-27 19:51:58 +00001068} // end extern "C"