blob: 267fcf7336386deec6950959760955941046865e [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//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +0000597// CXFile Operations.
598//===----------------------------------------------------------------------===//
599
600extern "C" {
Steve Naroff88145032009-10-27 14:35:18 +0000601const char *clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +0000602 if (!SFile)
603 return 0;
604
Steve Naroff88145032009-10-27 14:35:18 +0000605 assert(SFile && "Passed null CXFile");
606 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
607 return FEnt->getName();
608}
609
610time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +0000611 if (!SFile)
612 return 0;
613
Steve Naroff88145032009-10-27 14:35:18 +0000614 assert(SFile && "Passed null CXFile");
615 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
616 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +0000617}
Ted Kremenekfb480492010-01-13 21:46:36 +0000618} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +0000619
Ted Kremenekfb480492010-01-13 21:46:36 +0000620//===----------------------------------------------------------------------===//
621// CXCursor Operations.
622//===----------------------------------------------------------------------===//
623
Ted Kremenekfb480492010-01-13 21:46:36 +0000624static Decl *getDeclFromExpr(Stmt *E) {
625 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
626 return RefExpr->getDecl();
627 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
628 return ME->getMemberDecl();
629 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
630 return RE->getDecl();
631
632 if (CallExpr *CE = dyn_cast<CallExpr>(E))
633 return getDeclFromExpr(CE->getCallee());
634 if (CastExpr *CE = dyn_cast<CastExpr>(E))
635 return getDeclFromExpr(CE->getSubExpr());
636 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
637 return OME->getMethodDecl();
638
639 return 0;
640}
641
642extern "C" {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000643
644unsigned clang_visitChildren(CXTranslationUnit tu,
645 CXCursor parent,
646 CXCursorVisitor visitor,
647 CXClientData client_data) {
648 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
649
650 unsigned PCHLevel = Decl::MaxPCHLevel;
651
652 // Set the PCHLevel to filter out unwanted decls if requested.
653 if (CXXUnit->getOnlyLocalDecls()) {
654 PCHLevel = 0;
655
656 // If the main input was an AST, bump the level.
657 if (CXXUnit->isMainFileAST())
658 ++PCHLevel;
659 }
660
661 CursorVisitor CursorVis(visitor, client_data, PCHLevel);
662 return CursorVis.VisitChildren(parent);
663}
664
Douglas Gregor78205d42010-01-20 21:45:58 +0000665static CXString getDeclSpelling(Decl *D) {
666 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
667 if (!ND)
668 return CIndexer::createCXString("");
669
670 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
671 return CIndexer::createCXString(OMD->getSelector().getAsString().c_str(),
672 true);
673
674 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
675 // No, this isn't the same as the code below. getIdentifier() is non-virtual
676 // and returns different names. NamedDecl returns the class name and
677 // ObjCCategoryImplDecl returns the category name.
678 return CIndexer::createCXString(CIMP->getIdentifier()->getNameStart());
679
680 if (ND->getIdentifier())
681 return CIndexer::createCXString(ND->getIdentifier()->getNameStart());
682
683 return CIndexer::createCXString("");
684}
685
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000686CXString clang_getCursorSpelling(CXCursor C) {
Daniel Dunbarc81d7182010-01-18 17:52:42 +0000687 assert(getCursorDecl(C) && "CXCursor has null decl");
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +0000688 if (clang_isTranslationUnit(C.kind))
689 return clang_getTranslationUnitSpelling(C.data[0]);
690
Steve Narofff334b4e2009-09-02 18:26:48 +0000691 if (clang_isReference(C.kind)) {
692 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +0000693 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +0000694 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
695 return CIndexer::createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +0000696 }
697 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +0000698 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
699 return CIndexer::createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +0000700 }
701 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000702 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +0000703 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenek4b333d22010-01-12 00:36:38 +0000704 return CIndexer::createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +0000705 }
Daniel Dunbaracca7252009-11-30 20:42:49 +0000706 default:
Ted Kremenek4b333d22010-01-12 00:36:38 +0000707 return CIndexer::createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +0000708 }
709 }
Douglas Gregor97b98722010-01-19 23:20:36 +0000710
711 if (clang_isExpression(C.kind)) {
712 Decl *D = getDeclFromExpr(getCursorExpr(C));
713 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +0000714 return getDeclSpelling(D);
Douglas Gregor97b98722010-01-19 23:20:36 +0000715 return CIndexer::createCXString("");
716 }
717
Douglas Gregor78205d42010-01-20 21:45:58 +0000718 return getDeclSpelling(getCursorDecl(C));
Steve Narofff334b4e2009-09-02 18:26:48 +0000719}
720
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000721const char *clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +0000722 switch (Kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +0000723 case CXCursor_FunctionDecl: return "FunctionDecl";
724 case CXCursor_TypedefDecl: return "TypedefDecl";
725 case CXCursor_EnumDecl: return "EnumDecl";
726 case CXCursor_EnumConstantDecl: return "EnumConstantDecl";
727 case CXCursor_StructDecl: return "StructDecl";
728 case CXCursor_UnionDecl: return "UnionDecl";
729 case CXCursor_ClassDecl: return "ClassDecl";
730 case CXCursor_FieldDecl: return "FieldDecl";
731 case CXCursor_VarDecl: return "VarDecl";
732 case CXCursor_ParmDecl: return "ParmDecl";
733 case CXCursor_ObjCInterfaceDecl: return "ObjCInterfaceDecl";
734 case CXCursor_ObjCCategoryDecl: return "ObjCCategoryDecl";
735 case CXCursor_ObjCProtocolDecl: return "ObjCProtocolDecl";
736 case CXCursor_ObjCPropertyDecl: return "ObjCPropertyDecl";
737 case CXCursor_ObjCIvarDecl: return "ObjCIvarDecl";
738 case CXCursor_ObjCInstanceMethodDecl: return "ObjCInstanceMethodDecl";
739 case CXCursor_ObjCClassMethodDecl: return "ObjCClassMethodDecl";
Douglas Gregorb6998662010-01-19 19:34:47 +0000740 case CXCursor_ObjCImplementationDecl: return "ObjCImplementationDecl";
741 case CXCursor_ObjCCategoryImplDecl: return "ObjCCategoryImplDecl";
Douglas Gregor30122132010-01-19 22:07:56 +0000742 case CXCursor_UnexposedDecl: return "UnexposedDecl";
Daniel Dunbaracca7252009-11-30 20:42:49 +0000743 case CXCursor_ObjCSuperClassRef: return "ObjCSuperClassRef";
744 case CXCursor_ObjCProtocolRef: return "ObjCProtocolRef";
745 case CXCursor_ObjCClassRef: return "ObjCClassRef";
Douglas Gregor97b98722010-01-19 23:20:36 +0000746 case CXCursor_UnexposedExpr: return "UnexposedExpr";
747 case CXCursor_DeclRefExpr: return "DeclRefExpr";
748 case CXCursor_MemberRefExpr: return "MemberRefExpr";
749 case CXCursor_CallExpr: return "CallExpr";
750 case CXCursor_ObjCMessageExpr: return "ObjCMessageExpr";
751 case CXCursor_UnexposedStmt: return "UnexposedStmt";
Daniel Dunbaracca7252009-11-30 20:42:49 +0000752 case CXCursor_InvalidFile: return "InvalidFile";
753 case CXCursor_NoDeclFound: return "NoDeclFound";
754 case CXCursor_NotImplemented: return "NotImplemented";
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +0000755 case CXCursor_TranslationUnit: return "TranslationUnit";
Steve Naroff89922f82009-08-31 00:59:03 +0000756 }
Ted Kremenekdeb06bd2010-01-16 02:02:09 +0000757
758 llvm_unreachable("Unhandled CXCursorKind");
759 return NULL;
Steve Naroff600866c2009-08-27 19:51:58 +0000760}
Steve Naroff89922f82009-08-31 00:59:03 +0000761
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000762CXCursor clang_getCursor(CXTranslationUnit CTUnit, const char *source_name,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000763 unsigned line, unsigned column) {
Steve Naroff9efa7672009-09-04 15:44:05 +0000764 assert(CTUnit && "Passed null CXTranslationUnit");
765 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000766
Steve Naroff9efa7672009-09-04 15:44:05 +0000767 FileManager &FMgr = CXXUnit->getFileManager();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000768 const FileEntry *File = FMgr.getFile(source_name,
769 source_name+strlen(source_name));
Ted Kremenekf4629892010-01-14 01:51:23 +0000770 if (!File)
771 return clang_getNullCursor();
772
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000773 SourceLocation SLoc =
Steve Naroff9efa7672009-09-04 15:44:05 +0000774 CXXUnit->getSourceManager().getLocation(File, line, column);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000775
Steve Narofff96b5242009-10-28 20:44:47 +0000776 ASTLocation LastLoc = CXXUnit->getLastASTLocation();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000777 ASTLocation ALoc = ResolveLocationInAST(CXXUnit->getASTContext(), SLoc,
Steve Narofff96b5242009-10-28 20:44:47 +0000778 &LastLoc);
Ted Kremenekf4629892010-01-14 01:51:23 +0000779
780 // FIXME: This doesn't look thread-safe.
Steve Narofff96b5242009-10-28 20:44:47 +0000781 if (ALoc.isValid())
782 CXXUnit->setLastASTLocation(ALoc);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000783
Argyrios Kyrtzidisf4526e32009-09-29 19:44:27 +0000784 Decl *Dcl = ALoc.getParentDecl();
Argyrios Kyrtzidis05a76512009-09-29 19:45:58 +0000785 if (ALoc.isNamedRef())
786 Dcl = ALoc.AsNamedRef().ND;
Argyrios Kyrtzidisf4526e32009-09-29 19:44:27 +0000787 Stmt *Stm = ALoc.dyn_AsStmt();
Steve Naroff4ade6d62009-09-23 17:52:52 +0000788 if (Dcl) {
Douglas Gregor97b98722010-01-19 23:20:36 +0000789 if (Stm)
790 return MakeCXCursor(Stm, Dcl);
791
Steve Naroff85e2db72009-10-01 00:31:07 +0000792 if (ALoc.isNamedRef()) {
Douglas Gregor1adb0822010-01-16 17:14:40 +0000793 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(Dcl))
794 return MakeCursorObjCClassRef(Class, ALoc.AsNamedRef().Loc);
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000795 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(Dcl))
796 return MakeCursorObjCProtocolRef(Proto, ALoc.AsNamedRef().Loc);
Steve Naroff85e2db72009-10-01 00:31:07 +0000797 }
Ted Kremenek70ee5422010-01-16 01:44:12 +0000798 return MakeCXCursor(Dcl);
Steve Naroff77128dd2009-09-15 20:25:34 +0000799 }
Douglas Gregor5bfb8c12010-01-20 23:34:41 +0000800 return MakeCXCursorInvalid(CXCursor_NoDeclFound);
Steve Naroff600866c2009-08-27 19:51:58 +0000801}
802
Ted Kremenek73885552009-11-17 19:28:59 +0000803CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +0000804 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +0000805}
806
807unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +0000808 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +0000809}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000810
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000811unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +0000812 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
813}
814
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000815unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +0000816 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
817}
Steve Naroff2d4d6292009-08-31 14:26:51 +0000818
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000819unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +0000820 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
821}
822
Douglas Gregor97b98722010-01-19 23:20:36 +0000823unsigned clang_isExpression(enum CXCursorKind K) {
824 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
825}
826
827unsigned clang_isStatement(enum CXCursorKind K) {
828 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
829}
830
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +0000831unsigned clang_isTranslationUnit(enum CXCursorKind K) {
832 return K == CXCursor_TranslationUnit;
833}
834
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000835CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +0000836 return C.kind;
837}
838
Douglas Gregor97b98722010-01-19 23:20:36 +0000839static SourceLocation getLocationFromExpr(Expr *E) {
840 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
841 return /*FIXME:*/Msg->getLeftLoc();
842 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
843 return DRE->getLocation();
844 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
845 return Member->getMemberLoc();
846 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
847 return Ivar->getLocation();
848 return E->getLocStart();
849}
850
Douglas Gregor98258af2010-01-18 22:46:11 +0000851CXSourceLocation clang_getCursorLocation(CXCursor C) {
852 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +0000853 switch (C.kind) {
854 case CXCursor_ObjCSuperClassRef: {
855 std::pair<ObjCInterfaceDecl *, SourceLocation> P
856 = getCursorObjCSuperClassRef(C);
Douglas Gregor1db19de2010-01-19 21:36:55 +0000857 return translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +0000858 }
859
860 case CXCursor_ObjCProtocolRef: {
861 std::pair<ObjCProtocolDecl *, SourceLocation> P
862 = getCursorObjCProtocolRef(C);
Douglas Gregor1db19de2010-01-19 21:36:55 +0000863 return translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +0000864 }
865
866 case CXCursor_ObjCClassRef: {
867 std::pair<ObjCInterfaceDecl *, SourceLocation> P
868 = getCursorObjCClassRef(C);
Douglas Gregor1db19de2010-01-19 21:36:55 +0000869 return translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +0000870 }
871
Douglas Gregorf46034a2010-01-18 23:41:10 +0000872 default:
873 // FIXME: Need a way to enumerate all non-reference cases.
874 llvm_unreachable("Missed a reference kind");
875 }
Douglas Gregor98258af2010-01-18 22:46:11 +0000876 }
Douglas Gregor97b98722010-01-19 23:20:36 +0000877
878 if (clang_isExpression(C.kind))
879 return translateSourceLocation(getCursorContext(C),
880 getLocationFromExpr(getCursorExpr(C)));
881
Douglas Gregor98258af2010-01-18 22:46:11 +0000882 if (!getCursorDecl(C)) {
Douglas Gregor1db19de2010-01-19 21:36:55 +0000883 CXSourceLocation empty = { 0, 0 };
Douglas Gregor98258af2010-01-18 22:46:11 +0000884 return empty;
885 }
886
Douglas Gregorf46034a2010-01-18 23:41:10 +0000887 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +0000888 SourceLocation Loc = D->getLocation();
889 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
890 Loc = Class->getClassLoc();
Douglas Gregor1db19de2010-01-19 21:36:55 +0000891 return translateSourceLocation(D->getASTContext(), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +0000892}
Douglas Gregora7bde202010-01-19 00:34:46 +0000893
894CXSourceRange clang_getCursorExtent(CXCursor C) {
895 if (clang_isReference(C.kind)) {
896 switch (C.kind) {
897 case CXCursor_ObjCSuperClassRef: {
898 std::pair<ObjCInterfaceDecl *, SourceLocation> P
899 = getCursorObjCSuperClassRef(C);
900 return translateSourceRange(P.first->getASTContext(), P.second);
901 }
902
903 case CXCursor_ObjCProtocolRef: {
904 std::pair<ObjCProtocolDecl *, SourceLocation> P
905 = getCursorObjCProtocolRef(C);
906 return translateSourceRange(P.first->getASTContext(), P.second);
907 }
908
909 case CXCursor_ObjCClassRef: {
910 std::pair<ObjCInterfaceDecl *, SourceLocation> P
911 = getCursorObjCClassRef(C);
912
913 return translateSourceRange(P.first->getASTContext(), P.second);
914 }
915
Douglas Gregora7bde202010-01-19 00:34:46 +0000916 default:
917 // FIXME: Need a way to enumerate all non-reference cases.
918 llvm_unreachable("Missed a reference kind");
919 }
920 }
Douglas Gregor97b98722010-01-19 23:20:36 +0000921
922 if (clang_isExpression(C.kind))
923 return translateSourceRange(getCursorContext(C),
924 getCursorExpr(C)->getSourceRange());
Douglas Gregora7bde202010-01-19 00:34:46 +0000925
926 if (!getCursorDecl(C)) {
Douglas Gregor1db19de2010-01-19 21:36:55 +0000927 CXSourceRange empty = { 0, 0, 0 };
Douglas Gregora7bde202010-01-19 00:34:46 +0000928 return empty;
929 }
930
931 Decl *D = getCursorDecl(C);
932 return translateSourceRange(D->getASTContext(), D->getSourceRange());
933}
Douglas Gregorc5d1e932010-01-19 01:20:04 +0000934
935CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb6998662010-01-19 19:34:47 +0000936 if (clang_isDeclaration(C.kind))
Douglas Gregorc5d1e932010-01-19 01:20:04 +0000937 return C;
Douglas Gregor98258af2010-01-18 22:46:11 +0000938
Douglas Gregor97b98722010-01-19 23:20:36 +0000939 if (clang_isExpression(C.kind)) {
940 Decl *D = getDeclFromExpr(getCursorExpr(C));
941 if (D)
942 return MakeCXCursor(D);
943 return clang_getNullCursor();
944 }
945
Douglas Gregorc5d1e932010-01-19 01:20:04 +0000946 if (!clang_isReference(C.kind))
947 return clang_getNullCursor();
948
949 switch (C.kind) {
950 case CXCursor_ObjCSuperClassRef:
951 return MakeCXCursor(getCursorObjCSuperClassRef(C).first);
952
953 case CXCursor_ObjCProtocolRef: {
954 return MakeCXCursor(getCursorObjCProtocolRef(C).first);
955
956 case CXCursor_ObjCClassRef:
957 return MakeCXCursor(getCursorObjCClassRef(C).first);
958
Douglas Gregorc5d1e932010-01-19 01:20:04 +0000959 default:
960 // We would prefer to enumerate all non-reference cursor kinds here.
961 llvm_unreachable("Unhandled reference cursor kind");
962 break;
963 }
964 }
965
966 return clang_getNullCursor();
967}
968
Douglas Gregorb6998662010-01-19 19:34:47 +0000969CXCursor clang_getCursorDefinition(CXCursor C) {
970 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +0000971 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +0000972 C = clang_getCursorReferenced(C);
973 WasReference = true;
974 }
975
976 if (!clang_isDeclaration(C.kind))
977 return clang_getNullCursor();
978
979 Decl *D = getCursorDecl(C);
980 if (!D)
981 return clang_getNullCursor();
982
983 switch (D->getKind()) {
984 // Declaration kinds that don't really separate the notions of
985 // declaration and definition.
986 case Decl::Namespace:
987 case Decl::Typedef:
988 case Decl::TemplateTypeParm:
989 case Decl::EnumConstant:
990 case Decl::Field:
991 case Decl::ObjCIvar:
992 case Decl::ObjCAtDefsField:
993 case Decl::ImplicitParam:
994 case Decl::ParmVar:
995 case Decl::NonTypeTemplateParm:
996 case Decl::TemplateTemplateParm:
997 case Decl::ObjCCategoryImpl:
998 case Decl::ObjCImplementation:
999 case Decl::LinkageSpec:
1000 case Decl::ObjCPropertyImpl:
1001 case Decl::FileScopeAsm:
1002 case Decl::StaticAssert:
1003 case Decl::Block:
1004 return C;
1005
1006 // Declaration kinds that don't make any sense here, but are
1007 // nonetheless harmless.
1008 case Decl::TranslationUnit:
1009 case Decl::Template:
1010 case Decl::ObjCContainer:
1011 break;
1012
1013 // Declaration kinds for which the definition is not resolvable.
1014 case Decl::UnresolvedUsingTypename:
1015 case Decl::UnresolvedUsingValue:
1016 break;
1017
1018 case Decl::UsingDirective:
1019 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace());
1020
1021 case Decl::NamespaceAlias:
1022 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace());
1023
1024 case Decl::Enum:
1025 case Decl::Record:
1026 case Decl::CXXRecord:
1027 case Decl::ClassTemplateSpecialization:
1028 case Decl::ClassTemplatePartialSpecialization:
1029 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition(D->getASTContext()))
1030 return MakeCXCursor(Def);
1031 return clang_getNullCursor();
1032
1033 case Decl::Function:
1034 case Decl::CXXMethod:
1035 case Decl::CXXConstructor:
1036 case Decl::CXXDestructor:
1037 case Decl::CXXConversion: {
1038 const FunctionDecl *Def = 0;
1039 if (cast<FunctionDecl>(D)->getBody(Def))
1040 return MakeCXCursor(const_cast<FunctionDecl *>(Def));
1041 return clang_getNullCursor();
1042 }
1043
1044 case Decl::Var: {
1045 VarDecl *Var = cast<VarDecl>(D);
1046
1047 // Variables with initializers have definitions.
1048 const VarDecl *Def = 0;
1049 if (Var->getDefinition(Def))
1050 return MakeCXCursor(const_cast<VarDecl *>(Def));
1051
1052 // extern and private_extern variables are not definitions.
1053 if (Var->hasExternalStorage())
1054 return clang_getNullCursor();
1055
1056 // In-line static data members do not have definitions.
1057 if (Var->isStaticDataMember() && !Var->isOutOfLine())
1058 return clang_getNullCursor();
1059
1060 // All other variables are themselves definitions.
1061 return C;
1062 }
1063
1064 case Decl::FunctionTemplate: {
1065 const FunctionDecl *Def = 0;
1066 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
1067 return MakeCXCursor(Def->getDescribedFunctionTemplate());
1068 return clang_getNullCursor();
1069 }
1070
1071 case Decl::ClassTemplate: {
1072 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
1073 ->getDefinition(D->getASTContext()))
1074 return MakeCXCursor(
1075 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate());
1076 return clang_getNullCursor();
1077 }
1078
1079 case Decl::Using: {
1080 UsingDecl *Using = cast<UsingDecl>(D);
1081 CXCursor Def = clang_getNullCursor();
1082 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
1083 SEnd = Using->shadow_end();
1084 S != SEnd; ++S) {
1085 if (Def != clang_getNullCursor()) {
1086 // FIXME: We have no way to return multiple results.
1087 return clang_getNullCursor();
1088 }
1089
1090 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl()));
1091 }
1092
1093 return Def;
1094 }
1095
1096 case Decl::UsingShadow:
1097 return clang_getCursorDefinition(
1098 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl()));
1099
1100 case Decl::ObjCMethod: {
1101 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
1102 if (Method->isThisDeclarationADefinition())
1103 return C;
1104
1105 // Dig out the method definition in the associated
1106 // @implementation, if we have it.
1107 // FIXME: The ASTs should make finding the definition easier.
1108 if (ObjCInterfaceDecl *Class
1109 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
1110 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
1111 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
1112 Method->isInstanceMethod()))
1113 if (Def->isThisDeclarationADefinition())
1114 return MakeCXCursor(Def);
1115
1116 return clang_getNullCursor();
1117 }
1118
1119 case Decl::ObjCCategory:
1120 if (ObjCCategoryImplDecl *Impl
1121 = cast<ObjCCategoryDecl>(D)->getImplementation())
1122 return MakeCXCursor(Impl);
1123 return clang_getNullCursor();
1124
1125 case Decl::ObjCProtocol:
1126 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
1127 return C;
1128 return clang_getNullCursor();
1129
1130 case Decl::ObjCInterface:
1131 // There are two notions of a "definition" for an Objective-C
1132 // class: the interface and its implementation. When we resolved a
1133 // reference to an Objective-C class, produce the @interface as
1134 // the definition; when we were provided with the interface,
1135 // produce the @implementation as the definition.
1136 if (WasReference) {
1137 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
1138 return C;
1139 } else if (ObjCImplementationDecl *Impl
1140 = cast<ObjCInterfaceDecl>(D)->getImplementation())
1141 return MakeCXCursor(Impl);
1142 return clang_getNullCursor();
1143
1144 case Decl::ObjCProperty:
1145 // FIXME: We don't really know where to find the
1146 // ObjCPropertyImplDecls that implement this property.
1147 return clang_getNullCursor();
1148
1149 case Decl::ObjCCompatibleAlias:
1150 if (ObjCInterfaceDecl *Class
1151 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
1152 if (!Class->isForwardDecl())
1153 return MakeCXCursor(Class);
1154
1155 return clang_getNullCursor();
1156
1157 case Decl::ObjCForwardProtocol: {
1158 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
1159 if (Forward->protocol_size() == 1)
1160 return clang_getCursorDefinition(
1161 MakeCXCursor(*Forward->protocol_begin()));
1162
1163 // FIXME: Cannot return multiple definitions.
1164 return clang_getNullCursor();
1165 }
1166
1167 case Decl::ObjCClass: {
1168 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
1169 if (Class->size() == 1) {
1170 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
1171 if (!IFace->isForwardDecl())
1172 return MakeCXCursor(IFace);
1173 return clang_getNullCursor();
1174 }
1175
1176 // FIXME: Cannot return multiple definitions.
1177 return clang_getNullCursor();
1178 }
1179
1180 case Decl::Friend:
1181 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
1182 return clang_getCursorDefinition(MakeCXCursor(Friend));
1183 return clang_getNullCursor();
1184
1185 case Decl::FriendTemplate:
1186 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
1187 return clang_getCursorDefinition(MakeCXCursor(Friend));
1188 return clang_getNullCursor();
1189 }
1190
1191 return clang_getNullCursor();
1192}
1193
1194unsigned clang_isCursorDefinition(CXCursor C) {
1195 if (!clang_isDeclaration(C.kind))
1196 return 0;
1197
1198 return clang_getCursorDefinition(C) == C;
1199}
1200
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001201void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00001202 const char **startBuf,
1203 const char **endBuf,
1204 unsigned *startLine,
1205 unsigned *startColumn,
1206 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001207 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00001208 assert(getCursorDecl(C) && "CXCursor has null decl");
1209 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00001210 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
1211 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekfb480492010-01-13 21:46:36 +00001212
Steve Naroff4ade6d62009-09-23 17:52:52 +00001213 SourceManager &SM = FD->getASTContext().getSourceManager();
1214 *startBuf = SM.getCharacterData(Body->getLBracLoc());
1215 *endBuf = SM.getCharacterData(Body->getRBracLoc());
1216 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
1217 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
1218 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
1219 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
1220}
Ted Kremenekfb480492010-01-13 21:46:36 +00001221
1222} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00001223
Ted Kremenekfb480492010-01-13 21:46:36 +00001224//===----------------------------------------------------------------------===//
1225// CXString Operations.
1226//===----------------------------------------------------------------------===//
1227
1228extern "C" {
1229const char *clang_getCString(CXString string) {
1230 return string.Spelling;
1231}
1232
1233void clang_disposeString(CXString string) {
1234 if (string.MustFreeString && string.Spelling)
1235 free((void*)string.Spelling);
1236}
1237} // end: extern "C"