blob: 485e6c9980f969e50fb4c2fb19891f5892fdf0e0 [file] [log] [blame]
Ted Kremenekd2fa5662009-08-26 22:36:44 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00007//
Ted Kremenekd2fa5662009-08-26 22:36:44 +00008//===----------------------------------------------------------------------===//
9//
Ted Kremenekab188932010-01-05 19:32:54 +000010// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
Ted Kremenekd2fa5662009-08-26 22:36:44 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenekab188932010-01-05 19:32:54 +000015#include "CIndexer.h"
Ted Kremenek16c440a2010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremenekab188932010-01-05 19:32:54 +000017
Steve Naroff50398192009-08-28 15:28:48 +000018#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000019#include "clang/AST/StmtVisitor.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000020#include "clang/Lex/Lexer.h"
Douglas Gregor02465752009-10-16 21:24:31 +000021#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000022#include "llvm/System/Program.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000023
Ted Kremenekdb3d0da2010-01-05 20:55:39 +000024// Needed to define L_TMPNAM on some systems.
25#include <cstdio>
26
Steve Naroff50398192009-08-28 15:28:48 +000027using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000028using namespace clang::cxcursor;
Steve Naroff50398192009-08-28 15:28:48 +000029using namespace idx;
30
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000031//===----------------------------------------------------------------------===//
32// Crash Reporting.
33//===----------------------------------------------------------------------===//
34
35#ifdef __APPLE__
Ted Kremenek29b72842010-01-07 22:49:05 +000036#ifndef NDEBUG
37#define USE_CRASHTRACER
Ted Kremenek8a8da7d2010-01-06 03:42:32 +000038#include "clang/Analysis/Support/SaveAndRestore.h"
39// Integrate with crash reporter.
40extern "C" const char *__crashreporter_info__;
Ted Kremenek29b72842010-01-07 22:49:05 +000041#define NUM_CRASH_STRINGS 16
42static unsigned crashtracer_counter = 0;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000043static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek29b72842010-01-07 22:49:05 +000044static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
45static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
46
47static unsigned SetCrashTracerInfo(const char *str,
48 llvm::SmallString<1024> &AggStr) {
49
Ted Kremenek254ba7c2010-01-07 23:13:53 +000050 unsigned slot = 0;
Ted Kremenek29b72842010-01-07 22:49:05 +000051 while (crashtracer_strings[slot]) {
52 if (++slot == NUM_CRASH_STRINGS)
53 slot = 0;
54 }
55 crashtracer_strings[slot] = str;
Ted Kremenek254ba7c2010-01-07 23:13:53 +000056 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek29b72842010-01-07 22:49:05 +000057
58 // We need to create an aggregate string because multiple threads
59 // may be in this method at one time. The crash reporter string
60 // will attempt to overapproximate the set of in-flight invocations
61 // of this function. Race conditions can still cause this goal
62 // to not be achieved.
63 {
64 llvm::raw_svector_ostream Out(AggStr);
65 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
66 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
67 }
68 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
69 return slot;
70}
71
72static void ResetCrashTracerInfo(unsigned slot) {
Ted Kremenek254ba7c2010-01-07 23:13:53 +000073 unsigned max_slot = 0;
74 unsigned max_value = 0;
75
76 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
77
78 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
79 if (agg_crashtracer_strings[i] &&
80 crashtracer_counter_id[i] > max_value) {
81 max_slot = i;
82 max_value = crashtracer_counter_id[i];
Ted Kremenek29b72842010-01-07 22:49:05 +000083 }
Ted Kremenek254ba7c2010-01-07 23:13:53 +000084
85 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek29b72842010-01-07 22:49:05 +000086}
87
88namespace {
89class ArgsCrashTracerInfo {
90 llvm::SmallString<1024> CrashString;
91 llvm::SmallString<1024> AggregateString;
92 unsigned crashtracerSlot;
93public:
94 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
95 : crashtracerSlot(0)
96 {
97 {
98 llvm::raw_svector_ostream Out(CrashString);
99 Out << "ClangCIndex [createTranslationUnitFromSourceFile]: clang";
100 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
101 E=Args.end(); I!=E; ++I)
102 Out << ' ' << *I;
103 }
104 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
105 AggregateString);
106 }
107
108 ~ArgsCrashTracerInfo() {
109 ResetCrashTracerInfo(crashtracerSlot);
110 }
111};
112}
113#endif
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000114#endif
115
Douglas Gregor1db19de2010-01-19 21:36:55 +0000116typedef llvm::PointerIntPair<ASTContext *, 1, bool> CXSourceLocationPtr;
117
Douglas Gregor98258af2010-01-18 22:46:11 +0000118/// \brief Translate a Clang source location into a CIndex source location.
Douglas Gregor1db19de2010-01-19 21:36:55 +0000119static CXSourceLocation translateSourceLocation(ASTContext &Context,
120 SourceLocation Loc,
121 bool AtEnd = false) {
122 CXSourceLocationPtr Ptr(&Context, AtEnd);
123 CXSourceLocation Result = { Ptr.getOpaqueValue(), Loc.getRawEncoding() };
124 return Result;
Douglas Gregor98258af2010-01-18 22:46:11 +0000125}
126
Douglas Gregora7bde202010-01-19 00:34:46 +0000127/// \brief Translate a Clang source range into a CIndex source range.
Douglas Gregor1db19de2010-01-19 21:36:55 +0000128static CXSourceRange translateSourceRange(ASTContext &Context, SourceRange R) {
129 CXSourceRange Result = { &Context,
130 R.getBegin().getRawEncoding(),
131 R.getEnd().getRawEncoding() };
132 return Result;
Douglas Gregora7bde202010-01-19 00:34:46 +0000133}
134
Douglas Gregor1db19de2010-01-19 21:36:55 +0000135
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000136//===----------------------------------------------------------------------===//
137// Visitors.
138//===----------------------------------------------------------------------===//
139
Steve Naroff89922f82009-08-31 00:59:03 +0000140namespace {
Ted Kremenekedc8aa62010-01-16 00:36:30 +0000141
Douglas Gregorb1373d02010-01-20 20:59:29 +0000142// Cursor visitor.
143class CursorVisitor : public DeclVisitor<CursorVisitor, bool> {
144 CXCursor Parent;
145 CXCursorVisitor Visitor;
146 CXClientData ClientData;
147
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000148 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
149 // to the visitor. Declarations with a PCH level greater than this value will
150 // be suppressed.
151 unsigned MaxPCHLevel;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000152
153 using DeclVisitor<CursorVisitor, bool>::Visit;
154
Steve Naroff89922f82009-08-31 00:59:03 +0000155public:
Douglas Gregorb1373d02010-01-20 20:59:29 +0000156 CursorVisitor(CXCursorVisitor Visitor, CXClientData ClientData,
157 unsigned MaxPCHLevel)
158 : Visitor(Visitor), ClientData(ClientData), MaxPCHLevel(MaxPCHLevel)
159 {
160 Parent.kind = CXCursor_NoDeclFound;
161 Parent.data[0] = 0;
162 Parent.data[1] = 0;
163 Parent.data[2] = 0;
164 }
165
166 bool Visit(CXCursor Cursor);
167 bool VisitChildren(CXCursor Parent);
168
169 bool VisitDeclContext(DeclContext *DC);
170
171 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
172 bool VisitFunctionDecl(FunctionDecl *ND);
173 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
174 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
175 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
176 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
177 bool VisitTagDecl(TagDecl *D);
Steve Naroff89922f82009-08-31 00:59:03 +0000178};
Douglas Gregorb1373d02010-01-20 20:59:29 +0000179
Ted Kremenekab188932010-01-05 19:32:54 +0000180} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000181
Douglas Gregorb1373d02010-01-20 20:59:29 +0000182/// \brief Visit the given cursor and, if requested by the visitor,
183/// its children.
184///
185/// \returns true if the visitation should be aborted, false if it
186/// should continue.
187bool CursorVisitor::Visit(CXCursor Cursor) {
188 if (clang_isInvalid(Cursor.kind))
189 return false;
190
191 if (clang_isDeclaration(Cursor.kind)) {
192 Decl *D = getCursorDecl(Cursor);
193 assert(D && "Invalid declaration cursor");
194 if (D->getPCHLevel() > MaxPCHLevel)
195 return false;
196
197 if (D->isImplicit())
198 return false;
199 }
200
201 switch (Visitor(Cursor, Parent, ClientData)) {
202 case CXChildVisit_Break:
203 return true;
204
205 case CXChildVisit_Continue:
206 return false;
207
208 case CXChildVisit_Recurse:
209 return VisitChildren(Cursor);
210 }
211
212 llvm_unreachable("Silly GCC, we can't get here");
213}
214
215/// \brief Visit the children of the given cursor.
216///
217/// \returns true if the visitation should be aborted, false if it
218/// should continue.
219bool CursorVisitor::VisitChildren(CXCursor Cursor) {
220 // Set the Parent field to Cursor, then back to its old value once we're
221 // done.
222 class SetParentRAII {
223 CXCursor &Parent;
224 CXCursor OldParent;
225
226 public:
227 SetParentRAII(CXCursor &Parent, CXCursor NewParent)
228 : Parent(Parent), OldParent(Parent)
229 {
230 Parent = NewParent;
231 }
232
233 ~SetParentRAII() {
234 Parent = OldParent;
235 }
236 } SetParent(Parent, Cursor);
237
238 if (clang_isDeclaration(Cursor.kind)) {
239 Decl *D = getCursorDecl(Cursor);
240 assert(D && "Invalid declaration cursor");
241 return Visit(D);
242 }
243
244 if (clang_isTranslationUnit(Cursor.kind)) {
245 ASTUnit *CXXUnit = static_cast<ASTUnit *>(Cursor.data[0]);
Douglas Gregor7b691f332010-01-20 21:13:59 +0000246 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls()) {
247 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
248 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
249 ie = TLDs.end(); it != ie; ++it) {
250 if (Visit(MakeCXCursor(*it)))
251 return true;
252 }
253 } else {
254 return VisitDeclContext(
Douglas Gregorb1373d02010-01-20 20:59:29 +0000255 CXXUnit->getASTContext().getTranslationUnitDecl());
Douglas Gregor7b691f332010-01-20 21:13:59 +0000256 }
257
258 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000259 }
260
261 // Nothing to visit at the moment.
262 // FIXME: Traverse statements, declarations, etc. here.
263 return false;
264}
265
266bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
Douglas Gregor7b691f332010-01-20 21:13:59 +0000267 llvm_unreachable("Translation units are visited directly by Visit()");
268 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000269}
270
271bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000272 for (DeclContext::decl_iterator
Douglas Gregorb1373d02010-01-20 20:59:29 +0000273 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
274 if (Visit(MakeCXCursor(*I)))
275 return true;
276 }
277
278 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000279}
280
Douglas Gregorb1373d02010-01-20 20:59:29 +0000281bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
282 // FIXME: This is wrong. We always want to visit the parameters and
283 // the body, if available.
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000284 if (ND->isThisDeclarationADefinition()) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000285 return VisitDeclContext(ND);
286
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000287#if 0
288 // Not currently needed.
289 CompoundStmt *Body = dyn_cast<CompoundStmt>(ND->getBody());
290 CRefVisitor RVisit(CDecl, Callback, CData);
291 RVisit.Visit(Body);
292#endif
293 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000294
295 return false;
296}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000297
Douglas Gregorb1373d02010-01-20 20:59:29 +0000298bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
299 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation())))
300 return true;
301
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000302 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
303 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
304 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000305 if (Visit(MakeCursorObjCProtocolRef(*I, *PL)))
306 return true;
307
308 return VisitDeclContext(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000309}
310
Douglas Gregorb1373d02010-01-20 20:59:29 +0000311bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000312 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000313 if (D->getSuperClass() &&
314 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
315 D->getSuperClassLoc())))
316 return true;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000317
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000318 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
319 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
320 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000321 if (Visit(MakeCursorObjCProtocolRef(*I, *PL)))
322 return true;
323
324 return VisitDeclContext(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000325}
326
Douglas Gregorb1373d02010-01-20 20:59:29 +0000327bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
328 // FIXME: Wrong in the same way that VisitFunctionDecl is wrong.
Douglas Gregorb6998662010-01-19 19:34:47 +0000329 if (ND->getBody())
Douglas Gregorb1373d02010-01-20 20:59:29 +0000330 return VisitDeclContext(ND);
331
332 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000333}
334
Douglas Gregorb1373d02010-01-20 20:59:29 +0000335bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000336 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000337 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000338 E = PID->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000339 if (Visit(MakeCursorObjCProtocolRef(*I, *PL)))
340 return true;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000341
Douglas Gregorb1373d02010-01-20 20:59:29 +0000342 return VisitDeclContext(PID);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000343}
344
Douglas Gregorb1373d02010-01-20 20:59:29 +0000345bool CursorVisitor::VisitTagDecl(TagDecl *D) {
346 return VisitDeclContext(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000347}
348
Daniel Dunbar140fce22010-01-12 02:34:07 +0000349CXString CIndexer::createCXString(const char *String, bool DupString){
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000350 CXString Str;
351 if (DupString) {
352 Str.Spelling = strdup(String);
353 Str.MustFreeString = 1;
354 } else {
355 Str.Spelling = String;
356 Str.MustFreeString = 0;
357 }
358 return Str;
359}
360
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000361extern "C" {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000362CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000363 int displayDiagnostics) {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000364 CIndexer *CIdxr = new CIndexer(new Program());
365 if (excludeDeclarationsFromPCH)
366 CIdxr->setOnlyLocalDecls();
367 if (displayDiagnostics)
368 CIdxr->setDisplayDiagnostics();
369 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +0000370}
371
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000372void clang_disposeIndex(CXIndex CIdx) {
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000373 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000374 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000375}
376
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000377void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
378 assert(CIdx && "Passed null CXIndex");
379 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
380 CXXIdx->setUseExternalASTGeneration(value);
381}
382
Steve Naroff50398192009-08-28 15:28:48 +0000383// FIXME: need to pass back error info.
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000384CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
385 const char *ast_filename) {
Steve Naroff50398192009-08-28 15:28:48 +0000386 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000387 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000388
Daniel Dunbar5262fda2009-12-03 01:45:44 +0000389 return ASTUnit::LoadFromPCHFile(ast_filename, CXXIdx->getDiags(),
390 CXXIdx->getOnlyLocalDecls(),
391 /* UseBumpAllocator = */ true);
Steve Naroff600866c2009-08-27 19:51:58 +0000392}
393
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000394CXTranslationUnit
395clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
396 const char *source_filename,
397 int num_command_line_args,
398 const char **command_line_args) {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000399 assert(CIdx && "Passed null CXIndex");
400 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
401
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000402 if (!CXXIdx->getUseExternalASTGeneration()) {
403 llvm::SmallVector<const char *, 16> Args;
404
405 // The 'source_filename' argument is optional. If the caller does not
406 // specify it then it is assumed that the source file is specified
407 // in the actual argument list.
408 if (source_filename)
409 Args.push_back(source_filename);
410 Args.insert(Args.end(), command_line_args,
411 command_line_args + num_command_line_args);
412
Daniel Dunbar94220972009-12-05 02:17:18 +0000413 unsigned NumErrors = CXXIdx->getDiags().getNumErrors();
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000414
Ted Kremenek29b72842010-01-07 22:49:05 +0000415#ifdef USE_CRASHTRACER
416 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000417#endif
418
Daniel Dunbar94220972009-12-05 02:17:18 +0000419 llvm::OwningPtr<ASTUnit> Unit(
420 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Daniel Dunbar869824e2009-12-13 03:46:13 +0000421 CXXIdx->getDiags(),
422 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +0000423 CXXIdx->getOnlyLocalDecls(),
424 /* UseBumpAllocator = */ true));
Ted Kremenek29b72842010-01-07 22:49:05 +0000425
Daniel Dunbar94220972009-12-05 02:17:18 +0000426 // FIXME: Until we have broader testing, just drop the entire AST if we
427 // encountered an error.
428 if (NumErrors != CXXIdx->getDiags().getNumErrors())
429 return 0;
430
431 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000432 }
433
Ted Kremenek139ba862009-10-22 00:03:57 +0000434 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000435 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000436
Ted Kremenek139ba862009-10-22 00:03:57 +0000437 // First add the complete path to the 'clang' executable.
438 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000439 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000440
Ted Kremenek139ba862009-10-22 00:03:57 +0000441 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000442 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000443
Ted Kremenek139ba862009-10-22 00:03:57 +0000444 // The 'source_filename' argument is optional. If the caller does not
445 // specify it then it is assumed that the source file is specified
446 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000447 if (source_filename)
448 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +0000449
Steve Naroff37b5ac22009-10-15 20:50:09 +0000450 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +0000451 argv.push_back("-o");
Steve Naroff37b5ac22009-10-15 20:50:09 +0000452 char astTmpFile[L_tmpnam];
Ted Kremenek74cd0692009-10-15 23:21:22 +0000453 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +0000454
455 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
456 for (int i = 0; i < num_command_line_args; ++i)
457 if (const char *arg = command_line_args[i]) {
458 if (strcmp(arg, "-o") == 0) {
459 ++i; // Also skip the matching argument.
460 continue;
461 }
462 if (strcmp(arg, "-emit-ast") == 0 ||
463 strcmp(arg, "-c") == 0 ||
464 strcmp(arg, "-fsyntax-only") == 0) {
465 continue;
466 }
467
468 // Keep the argument.
469 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000470 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000471
Ted Kremenek139ba862009-10-22 00:03:57 +0000472 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000473 argv.push_back(NULL);
474
Ted Kremenekfeb15e32009-10-26 22:14:08 +0000475 // Invoke 'clang'.
476 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
477 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +0000478 std::string ErrMsg;
Ted Kremenekc46e4632009-10-19 22:27:32 +0000479 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DevNull, NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +0000480 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
481 /* redirects */ !CXXIdx->getDisplayDiagnostics() ? &Redirects[0] : NULL,
482 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000483
Ted Kremenek0854d702009-11-10 19:18:52 +0000484 if (CXXIdx->getDisplayDiagnostics() && !ErrMsg.empty()) {
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000485 llvm::errs() << "clang_createTranslationUnitFromSourceFile: " << ErrMsg
Daniel Dunbaracca7252009-11-30 20:42:49 +0000486 << '\n' << "Arguments: \n";
Ted Kremenek379afec2009-10-22 03:24:01 +0000487 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Ted Kremenek779e5f42009-10-26 22:08:39 +0000488 I!=E; ++I) {
489 if (*I)
490 llvm::errs() << ' ' << *I << '\n';
491 }
492 llvm::errs() << '\n';
Ted Kremenek379afec2009-10-22 03:24:01 +0000493 }
Benjamin Kramer0829a832009-10-18 11:19:36 +0000494
Steve Naroff37b5ac22009-10-15 20:50:09 +0000495 // Finally, we create the translation unit from the ast file.
Steve Naroffe19944c2009-10-15 22:23:48 +0000496 ASTUnit *ATU = static_cast<ASTUnit *>(
Daniel Dunbaracca7252009-11-30 20:42:49 +0000497 clang_createTranslationUnit(CIdx, astTmpFile));
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000498 if (ATU)
499 ATU->unlinkTemporaryFile();
Steve Naroffe19944c2009-10-15 22:23:48 +0000500 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +0000501}
502
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000503void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000504 assert(CTUnit && "Passed null CXTranslationUnit");
505 delete static_cast<ASTUnit *>(CTUnit);
506}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000507
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000508CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000509 assert(CTUnit && "Passed null CXTranslationUnit");
Steve Naroff77accc12009-09-03 18:19:54 +0000510 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenek4b333d22010-01-12 00:36:38 +0000511 return CIndexer::createCXString(CXXUnit->getOriginalSourceFileName().c_str(),
512 true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000513}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +0000514
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +0000515CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
516 CXCursor Result = { CXCursor_TranslationUnit, { TU, 0, 0 } };
517 return Result;
518}
519
Ted Kremenekfb480492010-01-13 21:46:36 +0000520} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +0000521
Ted Kremenekfb480492010-01-13 21:46:36 +0000522//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +0000523// CXSourceLocation and CXSourceRange Operations.
524//===----------------------------------------------------------------------===//
525
526void clang_getInstantiationLocation(CXSourceLocation location,
527 CXFile *file,
528 unsigned *line,
529 unsigned *column) {
530 CXSourceLocationPtr Ptr
531 = CXSourceLocationPtr::getFromOpaqueValue(location.ptr_data);
532 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
533
534 if (!Ptr.getPointer() || Loc.isInvalid()) {
535 if (file)
536 *file = 0;
537 if (line)
538 *line = 0;
539 if (column)
540 *column = 0;
541 return;
542 }
543
544 // FIXME: This is largely copy-paste from
545 ///TextDiagnosticPrinter::HighlightRange. When it is clear that this is
546 // what we want the two routines should be refactored.
547 ASTContext &Context = *Ptr.getPointer();
548 SourceManager &SM = Context.getSourceManager();
549 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
550
551 if (Ptr.getInt()) {
552 // We want the last character in this location, so we will adjust
553 // the instantiation location accordingly.
554
555 // If the location is from a macro instantiation, get the end of
556 // the instantiation range.
557 if (Loc.isMacroID())
558 InstLoc = SM.getInstantiationRange(Loc).second;
559
560 // Measure the length token we're pointing at, so we can adjust
561 // the physical location in the file to point at the last
562 // character.
563 // FIXME: This won't cope with trigraphs or escaped newlines
564 // well. For that, we actually need a preprocessor, which isn't
565 // currently available here. Eventually, we'll switch the pointer
566 // data of CXSourceLocation/CXSourceRange to a translation unit
567 // (CXXUnit), so that the preprocessor will be available here. At
568 // that point, we can use Preprocessor::getLocForEndOfToken().
569 unsigned Length = Lexer::MeasureTokenLength(InstLoc, SM,
570 Context.getLangOptions());
571 if (Length > 0)
572 InstLoc = InstLoc.getFileLocWithOffset(Length - 1);
573 }
574
575 if (file)
576 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
577 if (line)
578 *line = SM.getInstantiationLineNumber(InstLoc);
579 if (column)
580 *column = SM.getInstantiationColumnNumber(InstLoc);
581}
582
583CXSourceLocation clang_getRangeStart(CXSourceRange range) {
584 CXSourceLocation Result = { range.ptr_data, range.begin_int_data };
585 return Result;
586}
587
588CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
589 llvm::PointerIntPair<ASTContext *, 1, bool> Ptr;
590 Ptr.setPointer(static_cast<ASTContext *>(range.ptr_data));
591 Ptr.setInt(true);
592 CXSourceLocation Result = { Ptr.getOpaqueValue(), range.end_int_data };
593 return Result;
594}
595
596//===----------------------------------------------------------------------===//
Steve Naroff600866c2009-08-27 19:51:58 +0000597// CXDecl Operations.
Ted Kremenekfb480492010-01-13 21:46:36 +0000598//===----------------------------------------------------------------------===//
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000599
Ted Kremenekfb480492010-01-13 21:46:36 +0000600extern "C" {
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000601CXString clang_getDeclSpelling(CXDecl AnonDecl) {
Steve Naroff89922f82009-08-31 00:59:03 +0000602 assert(AnonDecl && "Passed null CXDecl");
Douglas Gregor30122132010-01-19 22:07:56 +0000603 Decl *D = static_cast<Decl *>(AnonDecl);
604 NamedDecl *ND = dyn_cast<NamedDecl>(D);
605 if (!ND)
606 return CIndexer::createCXString("");
Steve Naroffef0cef62009-11-09 17:45:52 +0000607
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000608 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenek4b333d22010-01-12 00:36:38 +0000609 return CIndexer::createCXString(OMD->getSelector().getAsString().c_str(),
610 true);
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000611
612 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Steve Naroff0d69b8c2009-10-29 21:11:04 +0000613 // No, this isn't the same as the code below. getIdentifier() is non-virtual
614 // and returns different names. NamedDecl returns the class name and
615 // ObjCCategoryImplDecl returns the category name.
Ted Kremenek4b333d22010-01-12 00:36:38 +0000616 return CIndexer::createCXString(CIMP->getIdentifier()->getNameStart());
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000617
618 if (ND->getIdentifier())
Ted Kremenek4b333d22010-01-12 00:36:38 +0000619 return CIndexer::createCXString(ND->getIdentifier()->getNameStart());
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000620
Ted Kremenek4b333d22010-01-12 00:36:38 +0000621 return CIndexer::createCXString("");
Steve Naroff600866c2009-08-27 19:51:58 +0000622}
Steve Narofff334b4e2009-09-02 18:26:48 +0000623
Ted Kremenekfb480492010-01-13 21:46:36 +0000624} // end: extern "C"
Steve Naroff88145032009-10-27 14:35:18 +0000625
Ted Kremenekfb480492010-01-13 21:46:36 +0000626//===----------------------------------------------------------------------===//
627// CXFile Operations.
628//===----------------------------------------------------------------------===//
629
630extern "C" {
Steve Naroff88145032009-10-27 14:35:18 +0000631const char *clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +0000632 if (!SFile)
633 return 0;
634
Steve Naroff88145032009-10-27 14:35:18 +0000635 assert(SFile && "Passed null CXFile");
636 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
637 return FEnt->getName();
638}
639
640time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +0000641 if (!SFile)
642 return 0;
643
Steve Naroff88145032009-10-27 14:35:18 +0000644 assert(SFile && "Passed null CXFile");
645 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
646 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +0000647}
Ted Kremenekfb480492010-01-13 21:46:36 +0000648} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +0000649
Ted Kremenekfb480492010-01-13 21:46:36 +0000650//===----------------------------------------------------------------------===//
651// CXCursor Operations.
652//===----------------------------------------------------------------------===//
653
Ted Kremenekfb480492010-01-13 21:46:36 +0000654static Decl *getDeclFromExpr(Stmt *E) {
655 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
656 return RefExpr->getDecl();
657 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
658 return ME->getMemberDecl();
659 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
660 return RE->getDecl();
661
662 if (CallExpr *CE = dyn_cast<CallExpr>(E))
663 return getDeclFromExpr(CE->getCallee());
664 if (CastExpr *CE = dyn_cast<CastExpr>(E))
665 return getDeclFromExpr(CE->getSubExpr());
666 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
667 return OME->getMethodDecl();
668
669 return 0;
670}
671
672extern "C" {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000673
674unsigned clang_visitChildren(CXTranslationUnit tu,
675 CXCursor parent,
676 CXCursorVisitor visitor,
677 CXClientData client_data) {
678 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
679
680 unsigned PCHLevel = Decl::MaxPCHLevel;
681
682 // Set the PCHLevel to filter out unwanted decls if requested.
683 if (CXXUnit->getOnlyLocalDecls()) {
684 PCHLevel = 0;
685
686 // If the main input was an AST, bump the level.
687 if (CXXUnit->isMainFileAST())
688 ++PCHLevel;
689 }
690
691 CursorVisitor CursorVis(visitor, client_data, PCHLevel);
692 return CursorVis.VisitChildren(parent);
693}
694
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000695CXString clang_getCursorSpelling(CXCursor C) {
Daniel Dunbarc81d7182010-01-18 17:52:42 +0000696 assert(getCursorDecl(C) && "CXCursor has null decl");
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +0000697 if (clang_isTranslationUnit(C.kind))
698 return clang_getTranslationUnitSpelling(C.data[0]);
699
Steve Narofff334b4e2009-09-02 18:26:48 +0000700 if (clang_isReference(C.kind)) {
701 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +0000702 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +0000703 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
704 return CIndexer::createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +0000705 }
706 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +0000707 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
708 return CIndexer::createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +0000709 }
710 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000711 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +0000712 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenek4b333d22010-01-12 00:36:38 +0000713 return CIndexer::createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +0000714 }
Daniel Dunbaracca7252009-11-30 20:42:49 +0000715 default:
Ted Kremenek4b333d22010-01-12 00:36:38 +0000716 return CIndexer::createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +0000717 }
718 }
Douglas Gregor97b98722010-01-19 23:20:36 +0000719
720 if (clang_isExpression(C.kind)) {
721 Decl *D = getDeclFromExpr(getCursorExpr(C));
722 if (D)
723 return clang_getDeclSpelling(D);
724 return CIndexer::createCXString("");
725 }
726
Douglas Gregor283cae32010-01-15 21:56:13 +0000727 return clang_getDeclSpelling(getCursorDecl(C));
Steve Narofff334b4e2009-09-02 18:26:48 +0000728}
729
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000730const char *clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +0000731 switch (Kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +0000732 case CXCursor_FunctionDecl: return "FunctionDecl";
733 case CXCursor_TypedefDecl: return "TypedefDecl";
734 case CXCursor_EnumDecl: return "EnumDecl";
735 case CXCursor_EnumConstantDecl: return "EnumConstantDecl";
736 case CXCursor_StructDecl: return "StructDecl";
737 case CXCursor_UnionDecl: return "UnionDecl";
738 case CXCursor_ClassDecl: return "ClassDecl";
739 case CXCursor_FieldDecl: return "FieldDecl";
740 case CXCursor_VarDecl: return "VarDecl";
741 case CXCursor_ParmDecl: return "ParmDecl";
742 case CXCursor_ObjCInterfaceDecl: return "ObjCInterfaceDecl";
743 case CXCursor_ObjCCategoryDecl: return "ObjCCategoryDecl";
744 case CXCursor_ObjCProtocolDecl: return "ObjCProtocolDecl";
745 case CXCursor_ObjCPropertyDecl: return "ObjCPropertyDecl";
746 case CXCursor_ObjCIvarDecl: return "ObjCIvarDecl";
747 case CXCursor_ObjCInstanceMethodDecl: return "ObjCInstanceMethodDecl";
748 case CXCursor_ObjCClassMethodDecl: return "ObjCClassMethodDecl";
Douglas Gregorb6998662010-01-19 19:34:47 +0000749 case CXCursor_ObjCImplementationDecl: return "ObjCImplementationDecl";
750 case CXCursor_ObjCCategoryImplDecl: return "ObjCCategoryImplDecl";
Douglas Gregor30122132010-01-19 22:07:56 +0000751 case CXCursor_UnexposedDecl: return "UnexposedDecl";
Daniel Dunbaracca7252009-11-30 20:42:49 +0000752 case CXCursor_ObjCSuperClassRef: return "ObjCSuperClassRef";
753 case CXCursor_ObjCProtocolRef: return "ObjCProtocolRef";
754 case CXCursor_ObjCClassRef: return "ObjCClassRef";
Douglas Gregor97b98722010-01-19 23:20:36 +0000755 case CXCursor_UnexposedExpr: return "UnexposedExpr";
756 case CXCursor_DeclRefExpr: return "DeclRefExpr";
757 case CXCursor_MemberRefExpr: return "MemberRefExpr";
758 case CXCursor_CallExpr: return "CallExpr";
759 case CXCursor_ObjCMessageExpr: return "ObjCMessageExpr";
760 case CXCursor_UnexposedStmt: return "UnexposedStmt";
Daniel Dunbaracca7252009-11-30 20:42:49 +0000761 case CXCursor_InvalidFile: return "InvalidFile";
762 case CXCursor_NoDeclFound: return "NoDeclFound";
763 case CXCursor_NotImplemented: return "NotImplemented";
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +0000764 case CXCursor_TranslationUnit: return "TranslationUnit";
Steve Naroff89922f82009-08-31 00:59:03 +0000765 }
Ted Kremenekdeb06bd2010-01-16 02:02:09 +0000766
767 llvm_unreachable("Unhandled CXCursorKind");
768 return NULL;
Steve Naroff600866c2009-08-27 19:51:58 +0000769}
Steve Naroff89922f82009-08-31 00:59:03 +0000770
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000771CXCursor clang_getCursor(CXTranslationUnit CTUnit, const char *source_name,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000772 unsigned line, unsigned column) {
Steve Naroff9efa7672009-09-04 15:44:05 +0000773 assert(CTUnit && "Passed null CXTranslationUnit");
774 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000775
Steve Naroff9efa7672009-09-04 15:44:05 +0000776 FileManager &FMgr = CXXUnit->getFileManager();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000777 const FileEntry *File = FMgr.getFile(source_name,
778 source_name+strlen(source_name));
Ted Kremenekf4629892010-01-14 01:51:23 +0000779 if (!File)
780 return clang_getNullCursor();
781
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000782 SourceLocation SLoc =
Steve Naroff9efa7672009-09-04 15:44:05 +0000783 CXXUnit->getSourceManager().getLocation(File, line, column);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000784
Steve Narofff96b5242009-10-28 20:44:47 +0000785 ASTLocation LastLoc = CXXUnit->getLastASTLocation();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000786 ASTLocation ALoc = ResolveLocationInAST(CXXUnit->getASTContext(), SLoc,
Steve Narofff96b5242009-10-28 20:44:47 +0000787 &LastLoc);
Ted Kremenekf4629892010-01-14 01:51:23 +0000788
789 // FIXME: This doesn't look thread-safe.
Steve Narofff96b5242009-10-28 20:44:47 +0000790 if (ALoc.isValid())
791 CXXUnit->setLastASTLocation(ALoc);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000792
Argyrios Kyrtzidisf4526e32009-09-29 19:44:27 +0000793 Decl *Dcl = ALoc.getParentDecl();
Argyrios Kyrtzidis05a76512009-09-29 19:45:58 +0000794 if (ALoc.isNamedRef())
795 Dcl = ALoc.AsNamedRef().ND;
Argyrios Kyrtzidisf4526e32009-09-29 19:44:27 +0000796 Stmt *Stm = ALoc.dyn_AsStmt();
Steve Naroff4ade6d62009-09-23 17:52:52 +0000797 if (Dcl) {
Douglas Gregor97b98722010-01-19 23:20:36 +0000798 if (Stm)
799 return MakeCXCursor(Stm, Dcl);
800
Steve Naroff85e2db72009-10-01 00:31:07 +0000801 if (ALoc.isNamedRef()) {
Douglas Gregor1adb0822010-01-16 17:14:40 +0000802 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(Dcl))
803 return MakeCursorObjCClassRef(Class, ALoc.AsNamedRef().Loc);
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000804 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(Dcl))
805 return MakeCursorObjCProtocolRef(Proto, ALoc.AsNamedRef().Loc);
Steve Naroff85e2db72009-10-01 00:31:07 +0000806 }
Ted Kremenek70ee5422010-01-16 01:44:12 +0000807 return MakeCXCursor(Dcl);
Steve Naroff77128dd2009-09-15 20:25:34 +0000808 }
Ted Kremenekfb480492010-01-13 21:46:36 +0000809 return MakeCXCursor(CXCursor_NoDeclFound, 0);
Steve Naroff600866c2009-08-27 19:51:58 +0000810}
811
Ted Kremenek73885552009-11-17 19:28:59 +0000812CXCursor clang_getNullCursor(void) {
Ted Kremenekfb480492010-01-13 21:46:36 +0000813 return MakeCXCursor(CXCursor_InvalidFile, 0);
Ted Kremenek73885552009-11-17 19:28:59 +0000814}
815
816unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +0000817 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +0000818}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000819
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000820CXCursor clang_getCursorFromDecl(CXDecl AnonDecl) {
Steve Naroff77128dd2009-09-15 20:25:34 +0000821 assert(AnonDecl && "Passed null CXDecl");
Ted Kremenekdeb06bd2010-01-16 02:02:09 +0000822 return MakeCXCursor(static_cast<NamedDecl *>(AnonDecl));
Steve Naroff77128dd2009-09-15 20:25:34 +0000823}
824
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000825unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +0000826 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
827}
828
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000829unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +0000830 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
831}
Steve Naroff2d4d6292009-08-31 14:26:51 +0000832
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000833unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +0000834 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
835}
836
Douglas Gregor97b98722010-01-19 23:20:36 +0000837unsigned clang_isExpression(enum CXCursorKind K) {
838 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
839}
840
841unsigned clang_isStatement(enum CXCursorKind K) {
842 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
843}
844
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +0000845unsigned clang_isTranslationUnit(enum CXCursorKind K) {
846 return K == CXCursor_TranslationUnit;
847}
848
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000849CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +0000850 return C.kind;
851}
852
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000853CXDecl clang_getCursorDecl(CXCursor C) {
Douglas Gregorb6998662010-01-19 19:34:47 +0000854 if (clang_isDeclaration(C.kind))
Douglas Gregor283cae32010-01-15 21:56:13 +0000855 return getCursorDecl(C);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000856
Steve Naroff699a07d2009-09-25 21:32:34 +0000857 if (clang_isReference(C.kind)) {
Douglas Gregor1adb0822010-01-16 17:14:40 +0000858 if (getCursorStmt(C))
859 return getDeclFromExpr(getCursorStmt(C));
860
861 return getCursorDecl(C);
Steve Naroff699a07d2009-09-25 21:32:34 +0000862 }
Douglas Gregor97b98722010-01-19 23:20:36 +0000863
864 if (clang_isExpression(C.kind))
865 return getDeclFromExpr(getCursorStmt(C));
866
Steve Naroff699a07d2009-09-25 21:32:34 +0000867 return 0;
Steve Naroff9efa7672009-09-04 15:44:05 +0000868}
869
Douglas Gregor97b98722010-01-19 23:20:36 +0000870static SourceLocation getLocationFromExpr(Expr *E) {
871 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
872 return /*FIXME:*/Msg->getLeftLoc();
873 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
874 return DRE->getLocation();
875 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
876 return Member->getMemberLoc();
877 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
878 return Ivar->getLocation();
879 return E->getLocStart();
880}
881
Douglas Gregor98258af2010-01-18 22:46:11 +0000882CXSourceLocation clang_getCursorLocation(CXCursor C) {
883 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +0000884 switch (C.kind) {
885 case CXCursor_ObjCSuperClassRef: {
886 std::pair<ObjCInterfaceDecl *, SourceLocation> P
887 = getCursorObjCSuperClassRef(C);
Douglas Gregor1db19de2010-01-19 21:36:55 +0000888 return translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +0000889 }
890
891 case CXCursor_ObjCProtocolRef: {
892 std::pair<ObjCProtocolDecl *, SourceLocation> P
893 = getCursorObjCProtocolRef(C);
Douglas Gregor1db19de2010-01-19 21:36:55 +0000894 return translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +0000895 }
896
897 case CXCursor_ObjCClassRef: {
898 std::pair<ObjCInterfaceDecl *, SourceLocation> P
899 = getCursorObjCClassRef(C);
Douglas Gregor1db19de2010-01-19 21:36:55 +0000900 return translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +0000901 }
902
Douglas Gregorf46034a2010-01-18 23:41:10 +0000903 default:
904 // FIXME: Need a way to enumerate all non-reference cases.
905 llvm_unreachable("Missed a reference kind");
906 }
Douglas Gregor98258af2010-01-18 22:46:11 +0000907 }
Douglas Gregor97b98722010-01-19 23:20:36 +0000908
909 if (clang_isExpression(C.kind))
910 return translateSourceLocation(getCursorContext(C),
911 getLocationFromExpr(getCursorExpr(C)));
912
Douglas Gregor98258af2010-01-18 22:46:11 +0000913 if (!getCursorDecl(C)) {
Douglas Gregor1db19de2010-01-19 21:36:55 +0000914 CXSourceLocation empty = { 0, 0 };
Douglas Gregor98258af2010-01-18 22:46:11 +0000915 return empty;
916 }
917
Douglas Gregorf46034a2010-01-18 23:41:10 +0000918 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +0000919 SourceLocation Loc = D->getLocation();
920 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
921 Loc = Class->getClassLoc();
Douglas Gregor1db19de2010-01-19 21:36:55 +0000922 return translateSourceLocation(D->getASTContext(), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +0000923}
Douglas Gregora7bde202010-01-19 00:34:46 +0000924
925CXSourceRange clang_getCursorExtent(CXCursor C) {
926 if (clang_isReference(C.kind)) {
927 switch (C.kind) {
928 case CXCursor_ObjCSuperClassRef: {
929 std::pair<ObjCInterfaceDecl *, SourceLocation> P
930 = getCursorObjCSuperClassRef(C);
931 return translateSourceRange(P.first->getASTContext(), P.second);
932 }
933
934 case CXCursor_ObjCProtocolRef: {
935 std::pair<ObjCProtocolDecl *, SourceLocation> P
936 = getCursorObjCProtocolRef(C);
937 return translateSourceRange(P.first->getASTContext(), P.second);
938 }
939
940 case CXCursor_ObjCClassRef: {
941 std::pair<ObjCInterfaceDecl *, SourceLocation> P
942 = getCursorObjCClassRef(C);
943
944 return translateSourceRange(P.first->getASTContext(), P.second);
945 }
946
Douglas Gregora7bde202010-01-19 00:34:46 +0000947 default:
948 // FIXME: Need a way to enumerate all non-reference cases.
949 llvm_unreachable("Missed a reference kind");
950 }
951 }
Douglas Gregor97b98722010-01-19 23:20:36 +0000952
953 if (clang_isExpression(C.kind))
954 return translateSourceRange(getCursorContext(C),
955 getCursorExpr(C)->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +0000956
957 if (!getCursorDecl(C)) {
Douglas Gregor1db19de2010-01-19 21:36:55 +0000958 CXSourceRange empty = { 0, 0, 0 };
Douglas Gregora7bde202010-01-19 00:34:46 +0000959 return empty;
960 }
961
962 Decl *D = getCursorDecl(C);
963 return translateSourceRange(D->getASTContext(), D->getSourceRange());
964}
Douglas Gregorc5d1e932010-01-19 01:20:04 +0000965
966CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb6998662010-01-19 19:34:47 +0000967 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +0000968 return C;
Douglas Gregor98258af2010-01-18 22:46:11 +0000969
Douglas Gregor97b98722010-01-19 23:20:36 +0000970 if (clang_isExpression(C.kind)) {
971 Decl *D = getDeclFromExpr(getCursorExpr(C));
972 if (D)
973 return MakeCXCursor(D);
974 return clang_getNullCursor();
975 }
976
Douglas Gregorc5d1e932010-01-19 01:20:04 +0000977 if (!clang_isReference(C.kind))
978 return clang_getNullCursor();
979
980 switch (C.kind) {
981 case CXCursor_ObjCSuperClassRef:
982 return MakeCXCursor(getCursorObjCSuperClassRef(C).first);
983
984 case CXCursor_ObjCProtocolRef: {
985 return MakeCXCursor(getCursorObjCProtocolRef(C).first);
986
987 case CXCursor_ObjCClassRef:
988 return MakeCXCursor(getCursorObjCClassRef(C).first);
989
Douglas Gregorc5d1e932010-01-19 01:20:04 +0000990 default:
991 // We would prefer to enumerate all non-reference cursor kinds here.
992 llvm_unreachable("Unhandled reference cursor kind");
993 break;
994 }
995 }
996
997 return clang_getNullCursor();
998}
999
Douglas Gregorb6998662010-01-19 19:34:47 +00001000CXCursor clang_getCursorDefinition(CXCursor C) {
1001 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00001002 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00001003 C = clang_getCursorReferenced(C);
1004 WasReference = true;
1005 }
1006
1007 if (!clang_isDeclaration(C.kind))
1008 return clang_getNullCursor();
1009
1010 Decl *D = getCursorDecl(C);
1011 if (!D)
1012 return clang_getNullCursor();
1013
1014 switch (D->getKind()) {
1015 // Declaration kinds that don't really separate the notions of
1016 // declaration and definition.
1017 case Decl::Namespace:
1018 case Decl::Typedef:
1019 case Decl::TemplateTypeParm:
1020 case Decl::EnumConstant:
1021 case Decl::Field:
1022 case Decl::ObjCIvar:
1023 case Decl::ObjCAtDefsField:
1024 case Decl::ImplicitParam:
1025 case Decl::ParmVar:
1026 case Decl::NonTypeTemplateParm:
1027 case Decl::TemplateTemplateParm:
1028 case Decl::ObjCCategoryImpl:
1029 case Decl::ObjCImplementation:
1030 case Decl::LinkageSpec:
1031 case Decl::ObjCPropertyImpl:
1032 case Decl::FileScopeAsm:
1033 case Decl::StaticAssert:
1034 case Decl::Block:
1035 return C;
1036
1037 // Declaration kinds that don't make any sense here, but are
1038 // nonetheless harmless.
1039 case Decl::TranslationUnit:
1040 case Decl::Template:
1041 case Decl::ObjCContainer:
1042 break;
1043
1044 // Declaration kinds for which the definition is not resolvable.
1045 case Decl::UnresolvedUsingTypename:
1046 case Decl::UnresolvedUsingValue:
1047 break;
1048
1049 case Decl::UsingDirective:
1050 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace());
1051
1052 case Decl::NamespaceAlias:
1053 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace());
1054
1055 case Decl::Enum:
1056 case Decl::Record:
1057 case Decl::CXXRecord:
1058 case Decl::ClassTemplateSpecialization:
1059 case Decl::ClassTemplatePartialSpecialization:
1060 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition(D->getASTContext()))
1061 return MakeCXCursor(Def);
1062 return clang_getNullCursor();
1063
1064 case Decl::Function:
1065 case Decl::CXXMethod:
1066 case Decl::CXXConstructor:
1067 case Decl::CXXDestructor:
1068 case Decl::CXXConversion: {
1069 const FunctionDecl *Def = 0;
1070 if (cast<FunctionDecl>(D)->getBody(Def))
1071 return MakeCXCursor(const_cast<FunctionDecl *>(Def));
1072 return clang_getNullCursor();
1073 }
1074
1075 case Decl::Var: {
1076 VarDecl *Var = cast<VarDecl>(D);
1077
1078 // Variables with initializers have definitions.
1079 const VarDecl *Def = 0;
1080 if (Var->getDefinition(Def))
1081 return MakeCXCursor(const_cast<VarDecl *>(Def));
1082
1083 // extern and private_extern variables are not definitions.
1084 if (Var->hasExternalStorage())
1085 return clang_getNullCursor();
1086
1087 // In-line static data members do not have definitions.
1088 if (Var->isStaticDataMember() && !Var->isOutOfLine())
1089 return clang_getNullCursor();
1090
1091 // All other variables are themselves definitions.
1092 return C;
1093 }
1094
1095 case Decl::FunctionTemplate: {
1096 const FunctionDecl *Def = 0;
1097 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
1098 return MakeCXCursor(Def->getDescribedFunctionTemplate());
1099 return clang_getNullCursor();
1100 }
1101
1102 case Decl::ClassTemplate: {
1103 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
1104 ->getDefinition(D->getASTContext()))
1105 return MakeCXCursor(
1106 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate());
1107 return clang_getNullCursor();
1108 }
1109
1110 case Decl::Using: {
1111 UsingDecl *Using = cast<UsingDecl>(D);
1112 CXCursor Def = clang_getNullCursor();
1113 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1114 SEnd = Using->shadow_end();
1115 S != SEnd; ++S) {
1116 if (Def != clang_getNullCursor()) {
1117 // FIXME: We have no way to return multiple results.
1118 return clang_getNullCursor();
1119 }
1120
1121 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl()));
1122 }
1123
1124 return Def;
1125 }
1126
1127 case Decl::UsingShadow:
1128 return clang_getCursorDefinition(
1129 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl()));
1130
1131 case Decl::ObjCMethod: {
1132 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1133 if (Method->isThisDeclarationADefinition())
1134 return C;
1135
1136 // Dig out the method definition in the associated
1137 // @implementation, if we have it.
1138 // FIXME: The ASTs should make finding the definition easier.
1139 if (ObjCInterfaceDecl *Class
1140 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
1141 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
1142 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
1143 Method->isInstanceMethod()))
1144 if (Def->isThisDeclarationADefinition())
1145 return MakeCXCursor(Def);
1146
1147 return clang_getNullCursor();
1148 }
1149
1150 case Decl::ObjCCategory:
1151 if (ObjCCategoryImplDecl *Impl
1152 = cast<ObjCCategoryDecl>(D)->getImplementation())
1153 return MakeCXCursor(Impl);
1154 return clang_getNullCursor();
1155
1156 case Decl::ObjCProtocol:
1157 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
1158 return C;
1159 return clang_getNullCursor();
1160
1161 case Decl::ObjCInterface:
1162 // There are two notions of a "definition" for an Objective-C
1163 // class: the interface and its implementation. When we resolved a
1164 // reference to an Objective-C class, produce the @interface as
1165 // the definition; when we were provided with the interface,
1166 // produce the @implementation as the definition.
1167 if (WasReference) {
1168 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
1169 return C;
1170 } else if (ObjCImplementationDecl *Impl
1171 = cast<ObjCInterfaceDecl>(D)->getImplementation())
1172 return MakeCXCursor(Impl);
1173 return clang_getNullCursor();
1174
1175 case Decl::ObjCProperty:
1176 // FIXME: We don't really know where to find the
1177 // ObjCPropertyImplDecls that implement this property.
1178 return clang_getNullCursor();
1179
1180 case Decl::ObjCCompatibleAlias:
1181 if (ObjCInterfaceDecl *Class
1182 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
1183 if (!Class->isForwardDecl())
1184 return MakeCXCursor(Class);
1185
1186 return clang_getNullCursor();
1187
1188 case Decl::ObjCForwardProtocol: {
1189 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
1190 if (Forward->protocol_size() == 1)
1191 return clang_getCursorDefinition(
1192 MakeCXCursor(*Forward->protocol_begin()));
1193
1194 // FIXME: Cannot return multiple definitions.
1195 return clang_getNullCursor();
1196 }
1197
1198 case Decl::ObjCClass: {
1199 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
1200 if (Class->size() == 1) {
1201 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
1202 if (!IFace->isForwardDecl())
1203 return MakeCXCursor(IFace);
1204 return clang_getNullCursor();
1205 }
1206
1207 // FIXME: Cannot return multiple definitions.
1208 return clang_getNullCursor();
1209 }
1210
1211 case Decl::Friend:
1212 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
1213 return clang_getCursorDefinition(MakeCXCursor(Friend));
1214 return clang_getNullCursor();
1215
1216 case Decl::FriendTemplate:
1217 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
1218 return clang_getCursorDefinition(MakeCXCursor(Friend));
1219 return clang_getNullCursor();
1220 }
1221
1222 return clang_getNullCursor();
1223}
1224
1225unsigned clang_isCursorDefinition(CXCursor C) {
1226 if (!clang_isDeclaration(C.kind))
1227 return 0;
1228
1229 return clang_getCursorDefinition(C) == C;
1230}
1231
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001232void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00001233 const char **startBuf,
1234 const char **endBuf,
1235 unsigned *startLine,
1236 unsigned *startColumn,
1237 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001238 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001239 assert(getCursorDecl(C) && "CXCursor has null decl");
1240 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00001241 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
1242 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekfb480492010-01-13 21:46:36 +00001243
Steve Naroff4ade6d62009-09-23 17:52:52 +00001244 SourceManager &SM = FD->getASTContext().getSourceManager();
1245 *startBuf = SM.getCharacterData(Body->getLBracLoc());
1246 *endBuf = SM.getCharacterData(Body->getRBracLoc());
1247 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
1248 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
1249 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
1250 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
1251}
Ted Kremenekfb480492010-01-13 21:46:36 +00001252
1253} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00001254
Ted Kremenekfb480492010-01-13 21:46:36 +00001255//===----------------------------------------------------------------------===//
1256// CXString Operations.
1257//===----------------------------------------------------------------------===//
1258
1259extern "C" {
1260const char *clang_getCString(CXString string) {
1261 return string.Spelling;
1262}
1263
1264void clang_disposeString(CXString string) {
1265 if (string.MustFreeString && string.Spelling)
1266 free((void*)string.Spelling);
1267}
1268} // end: extern "C"