blob: 9e7408375f8fcc1506694ce641e330927aea20e2 [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 Gregor98258af2010-01-18 22:46:11 +0000116/// \brief Translate a Clang source location into a CIndex source location.
117static CXSourceLocation translateSourceLocation(SourceManager &SourceMgr,
118 SourceLocation Loc) {
119 SourceLocation InstLoc = SourceMgr.getInstantiationLoc(Loc);
120 if (InstLoc.isInvalid()) {
121 CXSourceLocation Loc = { 0, 0, 0 };
122 return Loc;
123 }
124
125 CXSourceLocation Result;
126 Result.file
127 = (void*)SourceMgr.getFileEntryForID(SourceMgr.getFileID(InstLoc));
128 Result.line = SourceMgr.getInstantiationLineNumber(InstLoc);
129 Result.column = SourceMgr.getInstantiationColumnNumber(InstLoc);
130 return Result;
131}
132
Douglas Gregora7bde202010-01-19 00:34:46 +0000133/// \brief Translate a Clang source range into a CIndex source range.
134static CXSourceRange translateSourceRange(ASTContext &Context,
135 SourceRange R) {
136 if (R.isInvalid()) {
137 CXSourceRange extent = { { 0, 0, 0 }, { 0, 0, 0 } };
138 return extent;
139 }
140
141 // FIXME: This is largely copy-paste from
142 ///TextDiagnosticPrinter::HighlightRange. When it is clear that this is
143 // what we want the two routines should be refactored.
144
145 SourceManager &SM = Context.getSourceManager();
146 SourceLocation Begin = SM.getInstantiationLoc(R.getBegin());
147 SourceLocation End = SM.getInstantiationLoc(R.getEnd());
148
149 // If the End location and the start location are the same and are a macro
150 // location, then the range was something that came from a macro expansion
151 // or _Pragma. If this is an object-like macro, the best we can do is to
152 // get the range. If this is a function-like macro, we'd also like to
153 // get the arguments.
154 if (Begin == End && R.getEnd().isMacroID())
155 End = SM.getInstantiationRange(R.getEnd()).second;
156
157 unsigned StartLineNo = SM.getInstantiationLineNumber(Begin);
158 unsigned EndLineNo = SM.getInstantiationLineNumber(End);
159
160 // Compute the column number of the start. Keep the column based at 1.
161 unsigned StartColNo = SM.getInstantiationColumnNumber(Begin);
162
163 // Compute the column number of the end.
164 unsigned EndColNo = SM.getInstantiationColumnNumber(End);
165 if (EndColNo) {
166 // Offset the end column by 1 so that we point to the last character
167 // in the last token.
168 --EndColNo;
169
170 // Add in the length of the token, so that we cover multi-char tokens.
171 EndColNo += Lexer::MeasureTokenLength(End, SM, Context.getLangOptions());
172 }
173
174 // Package up the line/column data and return to the caller.
175 const FileEntry *BeginFile = SM.getFileEntryForID(SM.getFileID(Begin));
176 const FileEntry *EndFile = SM.getFileEntryForID(SM.getFileID(End));
177 CXSourceRange extent = { { (void *)BeginFile, StartLineNo, StartColNo },
178 { (void *)EndFile, EndLineNo, EndColNo } };
179 return extent;
180}
181
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000182//===----------------------------------------------------------------------===//
183// Visitors.
184//===----------------------------------------------------------------------===//
185
Steve Naroff89922f82009-08-31 00:59:03 +0000186namespace {
Ted Kremenekab188932010-01-05 19:32:54 +0000187static enum CXCursorKind TranslateDeclRefExpr(DeclRefExpr *DRE) {
Steve Naroff4ade6d62009-09-23 17:52:52 +0000188 NamedDecl *D = DRE->getDecl();
189 if (isa<VarDecl>(D))
190 return CXCursor_VarRef;
191 else if (isa<FunctionDecl>(D))
192 return CXCursor_FunctionRef;
193 else if (isa<EnumConstantDecl>(D))
194 return CXCursor_EnumConstantRef;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000195 else
Steve Naroff4ade6d62009-09-23 17:52:52 +0000196 return CXCursor_NotImplemented;
197}
198
Steve Naroff89922f82009-08-31 00:59:03 +0000199// Translation Unit Visitor.
Ted Kremenekf1286182010-01-13 00:13:47 +0000200
Steve Naroff89922f82009-08-31 00:59:03 +0000201class TUVisitor : public DeclVisitor<TUVisitor> {
Ted Kremenekf1286182010-01-13 00:13:47 +0000202public:
203 typedef void (*Iterator)(void *, CXCursor, CXClientData);
204private:
205 void *Root; // CXDecl or CXTranslationUnit
206 Iterator Callback; // CXTranslationUnitIterator or CXDeclIterator.
Steve Naroff2b8ee6c2009-09-01 15:55:40 +0000207 CXClientData CData;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000208
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000209 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
210 // to the visitor. Declarations with a PCH level greater than this value will
211 // be suppressed.
212 unsigned MaxPCHLevel;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000213
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000214 void Call(const CXCursor &C) {
Ted Kremenek70ee5422010-01-16 01:44:12 +0000215 if (clang_isInvalid(C.kind))
216 return;
217
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000218 if (const Decl *D = getCursorDecl(C)) {
219 // Filter any declarations that have a PCH level greater than what
220 // we allow.
221 if (D->getPCHLevel() > MaxPCHLevel)
222 return;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000223
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000224 // Filter any implicit declarations (since the source info will be bogus).
225 if (D->isImplicit())
226 return;
227 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000228
Ted Kremenekf1286182010-01-13 00:13:47 +0000229 Callback(Root, C, CData);
Steve Naroff2b8ee6c2009-09-01 15:55:40 +0000230 }
Ted Kremenekf1286182010-01-13 00:13:47 +0000231
Steve Naroff89922f82009-08-31 00:59:03 +0000232public:
Ted Kremenekf1286182010-01-13 00:13:47 +0000233 TUVisitor(void *root, Iterator cback, CXClientData D, unsigned MaxPCHLevel) :
234 Root(root), Callback(cback), CData(D), MaxPCHLevel(MaxPCHLevel) {}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000235
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000236 void VisitDecl(Decl *D);
Ted Kremenekf1286182010-01-13 00:13:47 +0000237 void VisitDeclContext(DeclContext *DC);
Ted Kremenekf1286182010-01-13 00:13:47 +0000238 void VisitTranslationUnitDecl(TranslationUnitDecl *D);
Ted Kremenekf1286182010-01-13 00:13:47 +0000239};
Ted Kremenekef7fdc62009-11-17 07:02:15 +0000240
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000241void TUVisitor::VisitDecl(Decl *D) {
242 Call(MakeCXCursor(D));
243}
244
Ted Kremenekf1286182010-01-13 00:13:47 +0000245void TUVisitor::VisitDeclContext(DeclContext *DC) {
246 for (DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
247 I != E; ++I)
248 Visit(*I);
249}
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000250
Ted Kremenekf1286182010-01-13 00:13:47 +0000251void TUVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
252 VisitDeclContext(dyn_cast<DeclContext>(D));
253}
Steve Naroff89922f82009-08-31 00:59:03 +0000254
Steve Naroffc857ea42009-09-02 13:28:54 +0000255// Declaration visitor.
256class CDeclVisitor : public DeclVisitor<CDeclVisitor> {
257 CXDecl CDecl;
258 CXDeclIterator Callback;
259 CXClientData CData;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000260
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000261 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
262 // to the visitor. Declarations with a PCH level greater than this value will
263 // be suppressed.
264 unsigned MaxPCHLevel;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000265
Steve Naroffc857ea42009-09-02 13:28:54 +0000266 void Call(enum CXCursorKind CK, NamedDecl *ND) {
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000267 // Disable the callback when the context is equal to the visiting decl.
268 if (CDecl == ND && !clang_isReference(CK))
269 return;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000270
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000271 // Filter any declarations that have a PCH level greater than what we allow.
272 if (ND->getPCHLevel() > MaxPCHLevel)
273 return;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000274
Douglas Gregor283cae32010-01-15 21:56:13 +0000275 CXCursor C = { CK, { ND, 0, 0 } };
Steve Naroffc857ea42009-09-02 13:28:54 +0000276 Callback(CDecl, C, CData);
277 }
Douglas Gregor2e331b92010-01-16 14:00:32 +0000278
Steve Naroff89922f82009-08-31 00:59:03 +0000279public:
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000280 CDeclVisitor(CXDecl C, CXDeclIterator cback, CXClientData D,
281 unsigned MaxPCHLevel) :
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000282 CDecl(C), Callback(cback), CData(D), MaxPCHLevel(MaxPCHLevel) {}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000283
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000284 void VisitDeclContext(DeclContext *DC);
285 void VisitEnumConstantDecl(EnumConstantDecl *ND);
286 void VisitFieldDecl(FieldDecl *ND);
287 void VisitFunctionDecl(FunctionDecl *ND);
288 void VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
289 void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
290 void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
291 void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
292 void VisitObjCIvarDecl(ObjCIvarDecl *ND);
293 void VisitObjCMethodDecl(ObjCMethodDecl *ND);
294 void VisitObjCPropertyDecl(ObjCPropertyDecl *ND);
295 void VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
296 void VisitParmVarDecl(ParmVarDecl *ND);
297 void VisitTagDecl(TagDecl *D);
298 void VisitVarDecl(VarDecl *ND);
Steve Naroff89922f82009-08-31 00:59:03 +0000299};
Ted Kremenekab188932010-01-05 19:32:54 +0000300} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000301
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000302void CDeclVisitor::VisitDeclContext(DeclContext *DC) {
303 for (DeclContext::decl_iterator
304 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I)
305 Visit(*I);
306}
307
308void CDeclVisitor::VisitEnumConstantDecl(EnumConstantDecl *ND) {
309 Call(CXCursor_EnumConstantDecl, ND);
310}
311
312void CDeclVisitor::VisitFieldDecl(FieldDecl *ND) {
313 Call(CXCursor_FieldDecl, ND);
314}
315
316void CDeclVisitor::VisitFunctionDecl(FunctionDecl *ND) {
317 if (ND->isThisDeclarationADefinition()) {
318 VisitDeclContext(dyn_cast<DeclContext>(ND));
319#if 0
320 // Not currently needed.
321 CompoundStmt *Body = dyn_cast<CompoundStmt>(ND->getBody());
322 CRefVisitor RVisit(CDecl, Callback, CData);
323 RVisit.Visit(Body);
324#endif
325 }
326}
327
328void CDeclVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
329 // Issue callbacks for the containing class.
Douglas Gregor1adb0822010-01-16 17:14:40 +0000330 Callback(CDecl,
331 MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation()),
332 CData);
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000333 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
334 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
335 E = ND->protocol_end(); I != E; ++I, ++PL)
336 Callback(CDecl, MakeCursorObjCProtocolRef(*I, *PL), CData);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000337 VisitDeclContext(dyn_cast<DeclContext>(ND));
338}
339
340void CDeclVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
341 VisitDeclContext(dyn_cast<DeclContext>(D));
342}
343
344void CDeclVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
345 VisitDeclContext(dyn_cast<DeclContext>(D));
346}
347
348void CDeclVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
349 // Issue callbacks for super class.
350 if (D->getSuperClass())
Douglas Gregor2e331b92010-01-16 14:00:32 +0000351 Callback(CDecl,
352 MakeCursorObjCSuperClassRef(D->getSuperClass(),
353 D->getSuperClassLoc()),
354 CData);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000355
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000356 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
357 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
358 E = D->protocol_end(); I != E; ++I, ++PL)
359 Callback(CDecl, MakeCursorObjCProtocolRef(*I, *PL), CData);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000360 VisitDeclContext(dyn_cast<DeclContext>(D));
361}
362
363void CDeclVisitor::VisitObjCIvarDecl(ObjCIvarDecl *ND) {
364 Call(CXCursor_ObjCIvarDecl, ND);
365}
366
367void CDeclVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
368 if (ND->getBody()) {
369 Call(ND->isInstanceMethod() ? CXCursor_ObjCInstanceMethodDefn
370 : CXCursor_ObjCClassMethodDefn, ND);
371 VisitDeclContext(dyn_cast<DeclContext>(ND));
372 } else
373 Call(ND->isInstanceMethod() ? CXCursor_ObjCInstanceMethodDecl
374 : CXCursor_ObjCClassMethodDecl, ND);
375}
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
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000568void clang_loadTranslationUnit(CXTranslationUnit CTUnit,
Steve Naroffc857ea42009-09-02 13:28:54 +0000569 CXTranslationUnitIterator callback,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000570 CXClientData CData) {
Steve Naroff50398192009-08-28 15:28:48 +0000571 assert(CTUnit && "Passed null CXTranslationUnit");
572 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
573 ASTContext &Ctx = CXXUnit->getASTContext();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000574
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000575 unsigned PCHLevel = Decl::MaxPCHLevel;
576
577 // Set the PCHLevel to filter out unwanted decls if requested.
578 if (CXXUnit->getOnlyLocalDecls()) {
579 PCHLevel = 0;
580
581 // If the main input was an AST, bump the level.
582 if (CXXUnit->isMainFileAST())
583 ++PCHLevel;
584 }
585
586 TUVisitor DVisit(CTUnit, callback, CData, PCHLevel);
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000587
588 // If using a non-AST based ASTUnit, iterate over the stored list of top-level
589 // decls.
590 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls()) {
591 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
592 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
593 ie = TLDs.end(); it != ie; ++it) {
594 DVisit.Visit(*it);
595 }
596 } else
597 DVisit.Visit(Ctx.getTranslationUnitDecl());
Steve Naroff600866c2009-08-27 19:51:58 +0000598}
599
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000600void clang_loadDeclaration(CXDecl Dcl,
601 CXDeclIterator callback,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000602 CXClientData CData) {
Steve Naroffc857ea42009-09-02 13:28:54 +0000603 assert(Dcl && "Passed null CXDecl");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000604
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000605 CDeclVisitor DVisit(Dcl, callback, CData,
606 static_cast<Decl *>(Dcl)->getPCHLevel());
Steve Naroffc857ea42009-09-02 13:28:54 +0000607 DVisit.Visit(static_cast<Decl *>(Dcl));
Steve Naroff600866c2009-08-27 19:51:58 +0000608}
Ted Kremenekfb480492010-01-13 21:46:36 +0000609} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +0000610
Ted Kremenekfb480492010-01-13 21:46:36 +0000611//===----------------------------------------------------------------------===//
Steve Naroff600866c2009-08-27 19:51:58 +0000612// CXDecl Operations.
Ted Kremenekfb480492010-01-13 21:46:36 +0000613//===----------------------------------------------------------------------===//
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000614
Ted Kremenekfb480492010-01-13 21:46:36 +0000615static const FileEntry *getFileEntryFromSourceLocation(SourceManager &SMgr,
616 SourceLocation SLoc) {
617 FileID FID;
618 if (SLoc.isFileID())
619 FID = SMgr.getFileID(SLoc);
620 else
621 FID = SMgr.getDecomposedSpellingLoc(SLoc).first;
622 return SMgr.getFileEntryForID(FID);
623}
624
625extern "C" {
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000626CXString clang_getDeclSpelling(CXDecl AnonDecl) {
Steve Naroff89922f82009-08-31 00:59:03 +0000627 assert(AnonDecl && "Passed null CXDecl");
628 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
Steve Naroffef0cef62009-11-09 17:45:52 +0000629
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000630 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenek4b333d22010-01-12 00:36:38 +0000631 return CIndexer::createCXString(OMD->getSelector().getAsString().c_str(),
632 true);
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000633
634 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Steve Naroff0d69b8c2009-10-29 21:11:04 +0000635 // No, this isn't the same as the code below. getIdentifier() is non-virtual
636 // and returns different names. NamedDecl returns the class name and
637 // ObjCCategoryImplDecl returns the category name.
Ted Kremenek4b333d22010-01-12 00:36:38 +0000638 return CIndexer::createCXString(CIMP->getIdentifier()->getNameStart());
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000639
640 if (ND->getIdentifier())
Ted Kremenek4b333d22010-01-12 00:36:38 +0000641 return CIndexer::createCXString(ND->getIdentifier()->getNameStart());
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000642
Ted Kremenek4b333d22010-01-12 00:36:38 +0000643 return CIndexer::createCXString("");
Steve Naroff600866c2009-08-27 19:51:58 +0000644}
Steve Narofff334b4e2009-09-02 18:26:48 +0000645
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000646unsigned clang_getDeclLine(CXDecl AnonDecl) {
Steve Naroff699a07d2009-09-25 21:32:34 +0000647 assert(AnonDecl && "Passed null CXDecl");
648 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
649 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
650 return SourceMgr.getSpellingLineNumber(ND->getLocation());
651}
652
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000653unsigned clang_getDeclColumn(CXDecl AnonDecl) {
Steve Naroff699a07d2009-09-25 21:32:34 +0000654 assert(AnonDecl && "Passed null CXDecl");
655 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
656 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Steve Naroff74165242009-09-25 22:15:54 +0000657 return SourceMgr.getSpellingColumnNumber(ND->getLocation());
Steve Naroff699a07d2009-09-25 21:32:34 +0000658}
Ted Kremenekfe6fd3d2010-01-05 23:18:49 +0000659
Douglas Gregor3c7313d2010-01-18 22:13:09 +0000660CXSourceRange clang_getDeclExtent(CXDecl AnonDecl) {
Douglas Gregora7bde202010-01-19 00:34:46 +0000661 return clang_getCursorExtent(clang_getCursorFromDecl(AnonDecl));
Ted Kremenekfe6fd3d2010-01-05 23:18:49 +0000662}
Steve Naroff699a07d2009-09-25 21:32:34 +0000663
Ted Kremenek6ab9db12010-01-08 17:11:32 +0000664const char *clang_getDeclSource(CXDecl AnonDecl) {
665 assert(AnonDecl && "Passed null CXDecl");
666 FileEntry *FEnt = static_cast<FileEntry *>(clang_getDeclSourceFile(AnonDecl));
667 assert(FEnt && "Cannot find FileEntry for Decl");
668 return clang_getFileName(FEnt);
669}
670
Steve Naroff88145032009-10-27 14:35:18 +0000671
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000672CXFile clang_getDeclSourceFile(CXDecl AnonDecl) {
Steve Naroff88145032009-10-27 14:35:18 +0000673 assert(AnonDecl && "Passed null CXDecl");
Steve Naroffee9405e2009-09-25 21:45:39 +0000674 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
675 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Steve Naroff88145032009-10-27 14:35:18 +0000676 return (void *)getFileEntryFromSourceLocation(SourceMgr, ND->getLocation());
677}
Ted Kremenekfb480492010-01-13 21:46:36 +0000678} // end: extern "C"
Steve Naroff88145032009-10-27 14:35:18 +0000679
Ted Kremenekfb480492010-01-13 21:46:36 +0000680//===----------------------------------------------------------------------===//
681// CXFile Operations.
682//===----------------------------------------------------------------------===//
683
684extern "C" {
Steve Naroff88145032009-10-27 14:35:18 +0000685const char *clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +0000686 if (!SFile)
687 return 0;
688
Steve Naroff88145032009-10-27 14:35:18 +0000689 assert(SFile && "Passed null CXFile");
690 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
691 return FEnt->getName();
692}
693
694time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +0000695 if (!SFile)
696 return 0;
697
Steve Naroff88145032009-10-27 14:35:18 +0000698 assert(SFile && "Passed null CXFile");
699 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
700 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +0000701}
Ted Kremenekfb480492010-01-13 21:46:36 +0000702} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +0000703
Ted Kremenekfb480492010-01-13 21:46:36 +0000704//===----------------------------------------------------------------------===//
705// CXCursor Operations.
706//===----------------------------------------------------------------------===//
707
Ted Kremenekfb480492010-01-13 21:46:36 +0000708static Decl *getDeclFromExpr(Stmt *E) {
709 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
710 return RefExpr->getDecl();
711 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
712 return ME->getMemberDecl();
713 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
714 return RE->getDecl();
715
716 if (CallExpr *CE = dyn_cast<CallExpr>(E))
717 return getDeclFromExpr(CE->getCallee());
718 if (CastExpr *CE = dyn_cast<CastExpr>(E))
719 return getDeclFromExpr(CE->getSubExpr());
720 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
721 return OME->getMethodDecl();
722
723 return 0;
724}
725
726extern "C" {
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000727CXString clang_getCursorSpelling(CXCursor C) {
Daniel Dunbarc81d7182010-01-18 17:52:42 +0000728 assert(getCursorDecl(C) && "CXCursor has null decl");
Steve Narofff334b4e2009-09-02 18:26:48 +0000729 if (clang_isReference(C.kind)) {
730 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +0000731 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +0000732 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
733 return CIndexer::createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +0000734 }
735 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +0000736 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
737 return CIndexer::createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +0000738 }
739 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000740 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +0000741 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenek4b333d22010-01-12 00:36:38 +0000742 return CIndexer::createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +0000743 }
744 case CXCursor_ObjCSelectorRef: {
Douglas Gregor283cae32010-01-15 21:56:13 +0000745 ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(getCursorStmt(C));
Douglas Gregorf46034a2010-01-18 23:41:10 +0000746 assert(OME && "getCursorSpelling(): Missing message expr");
Ted Kremenek4b333d22010-01-12 00:36:38 +0000747 return CIndexer::createCXString(OME->getSelector().getAsString().c_str(),
748 true);
Daniel Dunbaracca7252009-11-30 20:42:49 +0000749 }
750 case CXCursor_VarRef:
751 case CXCursor_FunctionRef:
752 case CXCursor_EnumConstantRef: {
Douglas Gregor283cae32010-01-15 21:56:13 +0000753 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(getCursorStmt(C));
Douglas Gregorf46034a2010-01-18 23:41:10 +0000754 assert(DRE && "getCursorSpelling(): Missing decl ref expr");
Ted Kremenek4b333d22010-01-12 00:36:38 +0000755 return CIndexer::createCXString(DRE->getDecl()->getIdentifier()
756 ->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +0000757 }
758 default:
Ted Kremenek4b333d22010-01-12 00:36:38 +0000759 return CIndexer::createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +0000760 }
761 }
Douglas Gregor283cae32010-01-15 21:56:13 +0000762 return clang_getDeclSpelling(getCursorDecl(C));
Steve Narofff334b4e2009-09-02 18:26:48 +0000763}
764
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000765const char *clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +0000766 switch (Kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +0000767 case CXCursor_FunctionDecl: return "FunctionDecl";
768 case CXCursor_TypedefDecl: return "TypedefDecl";
769 case CXCursor_EnumDecl: return "EnumDecl";
770 case CXCursor_EnumConstantDecl: return "EnumConstantDecl";
771 case CXCursor_StructDecl: return "StructDecl";
772 case CXCursor_UnionDecl: return "UnionDecl";
773 case CXCursor_ClassDecl: return "ClassDecl";
774 case CXCursor_FieldDecl: return "FieldDecl";
Ted Kremenekdeb06bd2010-01-16 02:02:09 +0000775 case CXCursor_FunctionDefn: return "FunctionDefn";
Daniel Dunbaracca7252009-11-30 20:42:49 +0000776 case CXCursor_VarDecl: return "VarDecl";
777 case CXCursor_ParmDecl: return "ParmDecl";
778 case CXCursor_ObjCInterfaceDecl: return "ObjCInterfaceDecl";
779 case CXCursor_ObjCCategoryDecl: return "ObjCCategoryDecl";
780 case CXCursor_ObjCProtocolDecl: return "ObjCProtocolDecl";
781 case CXCursor_ObjCPropertyDecl: return "ObjCPropertyDecl";
782 case CXCursor_ObjCIvarDecl: return "ObjCIvarDecl";
Ted Kremenekdeb06bd2010-01-16 02:02:09 +0000783 case CXCursor_ObjCIvarRef: return "ObjCIvarRef";
Daniel Dunbaracca7252009-11-30 20:42:49 +0000784 case CXCursor_ObjCInstanceMethodDecl: return "ObjCInstanceMethodDecl";
785 case CXCursor_ObjCClassMethodDecl: return "ObjCClassMethodDecl";
Daniel Dunbaracca7252009-11-30 20:42:49 +0000786 case CXCursor_ObjCInstanceMethodDefn: return "ObjCInstanceMethodDefn";
Ted Kremenekdeb06bd2010-01-16 02:02:09 +0000787 case CXCursor_ObjCCategoryDefn: return "ObjCCategoryDefn";
Daniel Dunbaracca7252009-11-30 20:42:49 +0000788 case CXCursor_ObjCClassMethodDefn: return "ObjCClassMethodDefn";
789 case CXCursor_ObjCClassDefn: return "ObjCClassDefn";
Daniel Dunbaracca7252009-11-30 20:42:49 +0000790 case CXCursor_ObjCSuperClassRef: return "ObjCSuperClassRef";
791 case CXCursor_ObjCProtocolRef: return "ObjCProtocolRef";
792 case CXCursor_ObjCClassRef: return "ObjCClassRef";
793 case CXCursor_ObjCSelectorRef: return "ObjCSelectorRef";
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000794
Daniel Dunbaracca7252009-11-30 20:42:49 +0000795 case CXCursor_VarRef: return "VarRef";
796 case CXCursor_FunctionRef: return "FunctionRef";
797 case CXCursor_EnumConstantRef: return "EnumConstantRef";
798 case CXCursor_MemberRef: return "MemberRef";
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000799
Daniel Dunbaracca7252009-11-30 20:42:49 +0000800 case CXCursor_InvalidFile: return "InvalidFile";
801 case CXCursor_NoDeclFound: return "NoDeclFound";
802 case CXCursor_NotImplemented: return "NotImplemented";
Steve Naroff89922f82009-08-31 00:59:03 +0000803 }
Ted Kremenekdeb06bd2010-01-16 02:02:09 +0000804
805 llvm_unreachable("Unhandled CXCursorKind");
806 return NULL;
Steve Naroff600866c2009-08-27 19:51:58 +0000807}
Steve Naroff89922f82009-08-31 00:59:03 +0000808
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000809CXCursor clang_getCursor(CXTranslationUnit CTUnit, const char *source_name,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000810 unsigned line, unsigned column) {
Steve Naroff9efa7672009-09-04 15:44:05 +0000811 assert(CTUnit && "Passed null CXTranslationUnit");
812 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000813
Steve Naroff9efa7672009-09-04 15:44:05 +0000814 FileManager &FMgr = CXXUnit->getFileManager();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000815 const FileEntry *File = FMgr.getFile(source_name,
816 source_name+strlen(source_name));
Ted Kremenekf4629892010-01-14 01:51:23 +0000817 if (!File)
818 return clang_getNullCursor();
819
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000820 SourceLocation SLoc =
Steve Naroff9efa7672009-09-04 15:44:05 +0000821 CXXUnit->getSourceManager().getLocation(File, line, column);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000822
Steve Narofff96b5242009-10-28 20:44:47 +0000823 ASTLocation LastLoc = CXXUnit->getLastASTLocation();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000824 ASTLocation ALoc = ResolveLocationInAST(CXXUnit->getASTContext(), SLoc,
Steve Narofff96b5242009-10-28 20:44:47 +0000825 &LastLoc);
Ted Kremenekf4629892010-01-14 01:51:23 +0000826
827 // FIXME: This doesn't look thread-safe.
Steve Narofff96b5242009-10-28 20:44:47 +0000828 if (ALoc.isValid())
829 CXXUnit->setLastASTLocation(ALoc);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000830
Argyrios Kyrtzidisf4526e32009-09-29 19:44:27 +0000831 Decl *Dcl = ALoc.getParentDecl();
Argyrios Kyrtzidis05a76512009-09-29 19:45:58 +0000832 if (ALoc.isNamedRef())
833 Dcl = ALoc.AsNamedRef().ND;
Argyrios Kyrtzidisf4526e32009-09-29 19:44:27 +0000834 Stmt *Stm = ALoc.dyn_AsStmt();
Steve Naroff4ade6d62009-09-23 17:52:52 +0000835 if (Dcl) {
836 if (Stm) {
Ted Kremenekfb480492010-01-13 21:46:36 +0000837 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Stm))
Douglas Gregorf46034a2010-01-18 23:41:10 +0000838 return MakeCXCursor(TranslateDeclRefExpr(DRE), Dcl, Stm,
839 CXXUnit->getASTContext());
Ted Kremenekfb480492010-01-13 21:46:36 +0000840 else if (ObjCMessageExpr *MExp = dyn_cast<ObjCMessageExpr>(Stm))
Douglas Gregorf46034a2010-01-18 23:41:10 +0000841 return MakeCXCursor(CXCursor_ObjCSelectorRef, Dcl, MExp,
842 CXXUnit->getASTContext());
Steve Naroff4ade6d62009-09-23 17:52:52 +0000843 // Fall through...treat as a decl, not a ref.
844 }
Steve Naroff85e2db72009-10-01 00:31:07 +0000845 if (ALoc.isNamedRef()) {
Douglas Gregor1adb0822010-01-16 17:14:40 +0000846 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(Dcl))
847 return MakeCursorObjCClassRef(Class, ALoc.AsNamedRef().Loc);
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000848 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(Dcl))
849 return MakeCursorObjCProtocolRef(Proto, ALoc.AsNamedRef().Loc);
Steve Naroff85e2db72009-10-01 00:31:07 +0000850 }
Ted Kremenek70ee5422010-01-16 01:44:12 +0000851 return MakeCXCursor(Dcl);
Steve Naroff77128dd2009-09-15 20:25:34 +0000852 }
Ted Kremenekfb480492010-01-13 21:46:36 +0000853 return MakeCXCursor(CXCursor_NoDeclFound, 0);
Steve Naroff600866c2009-08-27 19:51:58 +0000854}
855
Ted Kremenek73885552009-11-17 19:28:59 +0000856CXCursor clang_getNullCursor(void) {
Ted Kremenekfb480492010-01-13 21:46:36 +0000857 return MakeCXCursor(CXCursor_InvalidFile, 0);
Ted Kremenek73885552009-11-17 19:28:59 +0000858}
859
860unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +0000861 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +0000862}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000863
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000864CXCursor clang_getCursorFromDecl(CXDecl AnonDecl) {
Steve Naroff77128dd2009-09-15 20:25:34 +0000865 assert(AnonDecl && "Passed null CXDecl");
Ted Kremenekdeb06bd2010-01-16 02:02:09 +0000866 return MakeCXCursor(static_cast<NamedDecl *>(AnonDecl));
Steve Naroff77128dd2009-09-15 20:25:34 +0000867}
868
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000869unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +0000870 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
871}
872
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000873unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +0000874 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
875}
Steve Naroff2d4d6292009-08-31 14:26:51 +0000876
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000877unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +0000878 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
879}
880
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000881unsigned clang_isDefinition(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +0000882 return K >= CXCursor_FirstDefn && K <= CXCursor_LastDefn;
883}
884
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000885CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +0000886 return C.kind;
887}
888
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000889CXDecl clang_getCursorDecl(CXCursor C) {
Ted Kremenek70ee5422010-01-16 01:44:12 +0000890 if (clang_isDeclaration(C.kind) || clang_isDefinition(C.kind))
Douglas Gregor283cae32010-01-15 21:56:13 +0000891 return getCursorDecl(C);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000892
Steve Naroff699a07d2009-09-25 21:32:34 +0000893 if (clang_isReference(C.kind)) {
Douglas Gregor1adb0822010-01-16 17:14:40 +0000894 if (getCursorStmt(C))
895 return getDeclFromExpr(getCursorStmt(C));
896
897 return getCursorDecl(C);
Steve Naroff699a07d2009-09-25 21:32:34 +0000898 }
899 return 0;
Steve Naroff9efa7672009-09-04 15:44:05 +0000900}
901
Douglas Gregor98258af2010-01-18 22:46:11 +0000902CXSourceLocation clang_getCursorLocation(CXCursor C) {
903 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +0000904 switch (C.kind) {
905 case CXCursor_ObjCSuperClassRef: {
906 std::pair<ObjCInterfaceDecl *, SourceLocation> P
907 = getCursorObjCSuperClassRef(C);
908 SourceManager &SM = P.first->getASTContext().getSourceManager();
909 return translateSourceLocation(SM, P.second);
910 }
911
912 case CXCursor_ObjCProtocolRef: {
913 std::pair<ObjCProtocolDecl *, SourceLocation> P
914 = getCursorObjCProtocolRef(C);
915 SourceManager &SM = P.first->getASTContext().getSourceManager();
916 return translateSourceLocation(SM, P.second);
917 }
918
919 case CXCursor_ObjCClassRef: {
920 std::pair<ObjCInterfaceDecl *, SourceLocation> P
921 = getCursorObjCClassRef(C);
922 SourceManager &SM = P.first->getASTContext().getSourceManager();
923 return translateSourceLocation(SM, P.second);
924 }
925
926 case CXCursor_ObjCSelectorRef:
927 case CXCursor_ObjCIvarRef:
928 case CXCursor_VarRef:
929 case CXCursor_FunctionRef:
930 case CXCursor_EnumConstantRef:
931 case CXCursor_MemberRef: {
932 Expr *E = getCursorExpr(C);
933 SourceManager &SM = getCursorContext(C).getSourceManager();
934 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
935 return translateSourceLocation(SM, /*FIXME:*/Msg->getLeftLoc());
936 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
937 return translateSourceLocation(SM, DRE->getLocation());
938 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
939 return translateSourceLocation(SM, Member->getMemberLoc());
940 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
941 return translateSourceLocation(SM, Ivar->getLocation());
942 return translateSourceLocation(SM, E->getLocStart());
943 }
944
945 default:
946 // FIXME: Need a way to enumerate all non-reference cases.
947 llvm_unreachable("Missed a reference kind");
948 }
Douglas Gregor98258af2010-01-18 22:46:11 +0000949 }
950
951 if (!getCursorDecl(C)) {
952 CXSourceLocation empty = { 0, 0, 0 };
953 return empty;
954 }
955
Douglas Gregorf46034a2010-01-18 23:41:10 +0000956 Decl *D = getCursorDecl(C);
957 SourceManager &SM = D->getASTContext().getSourceManager();
958 SourceLocation Loc = D->getLocation();
959 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
960 Loc = Class->getClassLoc();
961 return translateSourceLocation(SM, Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +0000962}
Douglas Gregora7bde202010-01-19 00:34:46 +0000963
964CXSourceRange clang_getCursorExtent(CXCursor C) {
965 if (clang_isReference(C.kind)) {
966 switch (C.kind) {
967 case CXCursor_ObjCSuperClassRef: {
968 std::pair<ObjCInterfaceDecl *, SourceLocation> P
969 = getCursorObjCSuperClassRef(C);
970 return translateSourceRange(P.first->getASTContext(), P.second);
971 }
972
973 case CXCursor_ObjCProtocolRef: {
974 std::pair<ObjCProtocolDecl *, SourceLocation> P
975 = getCursorObjCProtocolRef(C);
976 return translateSourceRange(P.first->getASTContext(), P.second);
977 }
978
979 case CXCursor_ObjCClassRef: {
980 std::pair<ObjCInterfaceDecl *, SourceLocation> P
981 = getCursorObjCClassRef(C);
982
983 return translateSourceRange(P.first->getASTContext(), P.second);
984 }
985
986 case CXCursor_ObjCSelectorRef:
987 case CXCursor_ObjCIvarRef:
988 case CXCursor_VarRef:
989 case CXCursor_FunctionRef:
990 case CXCursor_EnumConstantRef:
991 case CXCursor_MemberRef:
992 return translateSourceRange(getCursorContext(C),
993 getCursorExpr(C)->getSourceRange());
994
995 default:
996 // FIXME: Need a way to enumerate all non-reference cases.
997 llvm_unreachable("Missed a reference kind");
998 }
999 }
1000
1001 if (!getCursorDecl(C)) {
1002 CXSourceRange empty = { { 0, 0, 0 }, { 0, 0, 0 } };
1003 return empty;
1004 }
1005
1006 Decl *D = getCursorDecl(C);
1007 return translateSourceRange(D->getASTContext(), D->getSourceRange());
1008}
Douglas Gregor98258af2010-01-18 22:46:11 +00001009
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001010void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00001011 const char **startBuf,
1012 const char **endBuf,
1013 unsigned *startLine,
1014 unsigned *startColumn,
1015 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001016 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001017 assert(getCursorDecl(C) && "CXCursor has null decl");
1018 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00001019 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
1020 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekfb480492010-01-13 21:46:36 +00001021
Steve Naroff4ade6d62009-09-23 17:52:52 +00001022 SourceManager &SM = FD->getASTContext().getSourceManager();
1023 *startBuf = SM.getCharacterData(Body->getLBracLoc());
1024 *endBuf = SM.getCharacterData(Body->getRBracLoc());
1025 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
1026 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
1027 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
1028 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
1029}
Ted Kremenekfb480492010-01-13 21:46:36 +00001030
1031} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00001032
Ted Kremenekfb480492010-01-13 21:46:36 +00001033//===----------------------------------------------------------------------===//
1034// CXString Operations.
1035//===----------------------------------------------------------------------===//
1036
1037extern "C" {
1038const char *clang_getCString(CXString string) {
1039 return string.Spelling;
1040}
1041
1042void clang_disposeString(CXString string) {
1043 if (string.MustFreeString && string.Spelling)
1044 free((void*)string.Spelling);
1045}
1046} // end: extern "C"