blob: 8fba3cf6b5cd0f74428900c4617c284e26a443f0 [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.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Clang-C Source Indexing library.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang-c/Index.h"
Steve Naroff50398192009-08-28 15:28:48 +000015#include "clang/Index/Program.h"
16#include "clang/Index/Indexer.h"
Steve Naroff9efa7672009-09-04 15:44:05 +000017#include "clang/Index/ASTLocation.h"
18#include "clang/Index/Utils.h"
Douglas Gregor0c8296d2009-11-07 00:00:49 +000019#include "clang/Sema/CodeCompleteConsumer.h"
Steve Naroff50398192009-08-28 15:28:48 +000020#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000021#include "clang/AST/StmtVisitor.h"
Steve Naroffc857ea42009-09-02 13:28:54 +000022#include "clang/AST/Decl.h"
Benjamin Kramerd01a0bc2009-08-29 12:56:35 +000023#include "clang/Basic/FileManager.h"
Steve Naroff2d4d6292009-08-31 14:26:51 +000024#include "clang/Basic/SourceManager.h"
Benjamin Kramerd01a0bc2009-08-29 12:56:35 +000025#include "clang/Frontend/ASTUnit.h"
Douglas Gregor0c8296d2009-11-07 00:00:49 +000026#include "llvm/ADT/StringExtras.h"
27#include "llvm/ADT/StringSwitch.h"
Benjamin Kramer20d75812009-10-18 16:13:48 +000028#include "llvm/Config/config.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000029#include "llvm/Support/Compiler.h"
Douglas Gregor02465752009-10-16 21:24:31 +000030#include "llvm/Support/MemoryBuffer.h"
31#include "llvm/System/Path.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000032#include "llvm/System/Program.h"
Ted Kremenek379afec2009-10-22 03:24:01 +000033#include "llvm/Support/raw_ostream.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000034
Benjamin Kramerd01a0bc2009-08-29 12:56:35 +000035#include <cstdio>
Ted Kremenek49358d82009-10-19 21:17:25 +000036#include <vector>
Douglas Gregor0c8296d2009-11-07 00:00:49 +000037#include <sstream>
Ted Kremenek49358d82009-10-19 21:17:25 +000038
Benjamin Kramer20d75812009-10-18 16:13:48 +000039#ifdef LLVM_ON_WIN32
40#define WIN32_LEAN_AND_MEAN
41#include <windows.h>
42#else
Steve Naroff5b7d8e22009-10-15 20:04:39 +000043#include <dlfcn.h>
Daniel Dunbara47dd192009-10-17 23:53:11 +000044#endif
Steve Naroff5b7d8e22009-10-15 20:04:39 +000045
Steve Naroff50398192009-08-28 15:28:48 +000046using namespace clang;
47using namespace idx;
48
Steve Naroff89922f82009-08-31 00:59:03 +000049namespace {
Steve Naroff4ade6d62009-09-23 17:52:52 +000050static enum CXCursorKind TranslateDeclRefExpr(DeclRefExpr *DRE)
51{
52 NamedDecl *D = DRE->getDecl();
53 if (isa<VarDecl>(D))
54 return CXCursor_VarRef;
55 else if (isa<FunctionDecl>(D))
56 return CXCursor_FunctionRef;
57 else if (isa<EnumConstantDecl>(D))
58 return CXCursor_EnumConstantRef;
59 else
60 return CXCursor_NotImplemented;
61}
62
63#if 0
64// Will be useful one day.
Steve Narofffb570422009-09-22 19:25:29 +000065class CRefVisitor : public StmtVisitor<CRefVisitor> {
66 CXDecl CDecl;
67 CXDeclIterator Callback;
68 CXClientData CData;
69
70 void Call(enum CXCursorKind CK, Stmt *SRef) {
71 CXCursor C = { CK, CDecl, SRef };
72 Callback(CDecl, C, CData);
73 }
74
75public:
76 CRefVisitor(CXDecl C, CXDeclIterator cback, CXClientData D) :
77 CDecl(C), Callback(cback), CData(D) {}
78
79 void VisitStmt(Stmt *S) {
80 for (Stmt::child_iterator C = S->child_begin(), CEnd = S->child_end();
81 C != CEnd; ++C)
82 Visit(*C);
83 }
84 void VisitDeclRefExpr(DeclRefExpr *Node) {
Steve Naroff4ade6d62009-09-23 17:52:52 +000085 Call(TranslateDeclRefExpr(Node), Node);
Steve Narofffb570422009-09-22 19:25:29 +000086 }
87 void VisitMemberExpr(MemberExpr *Node) {
88 Call(CXCursor_MemberRef, Node);
89 }
90 void VisitObjCMessageExpr(ObjCMessageExpr *Node) {
91 Call(CXCursor_ObjCSelectorRef, Node);
92 }
93 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *Node) {
94 Call(CXCursor_ObjCIvarRef, Node);
95 }
96};
Steve Naroff4ade6d62009-09-23 17:52:52 +000097#endif
Ted Kremenekfc062212009-10-19 21:44:57 +000098
99/// IgnoreDiagnosticsClient - A DiagnosticsClient that just ignores emitted
100/// warnings and errors.
101class VISIBILITY_HIDDEN IgnoreDiagnosticsClient : public DiagnosticClient {
102public:
103 virtual ~IgnoreDiagnosticsClient() {}
104 virtual void HandleDiagnostic(Diagnostic::Level, const DiagnosticInfo &) {}
105};
Steve Narofffb570422009-09-22 19:25:29 +0000106
Steve Naroff89922f82009-08-31 00:59:03 +0000107// Translation Unit Visitor.
108class TUVisitor : public DeclVisitor<TUVisitor> {
109 CXTranslationUnit TUnit;
110 CXTranslationUnitIterator Callback;
Steve Naroff2b8ee6c2009-09-01 15:55:40 +0000111 CXClientData CData;
112
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000113 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
114 // to the visitor. Declarations with a PCH level greater than this value will
115 // be suppressed.
116 unsigned MaxPCHLevel;
117
Steve Naroff2b8ee6c2009-09-01 15:55:40 +0000118 void Call(enum CXCursorKind CK, NamedDecl *ND) {
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000119 // Filter any declarations that have a PCH level greater than what we allow.
120 if (ND->getPCHLevel() > MaxPCHLevel)
121 return;
122
Steve Narofff96b5242009-10-28 20:44:47 +0000123 // Filter any implicit declarations (since the source info will be bogus).
124 if (ND->isImplicit())
125 return;
126
Steve Narofffb570422009-09-22 19:25:29 +0000127 CXCursor C = { CK, ND, 0 };
Steve Naroff2b8ee6c2009-09-01 15:55:40 +0000128 Callback(TUnit, C, CData);
129 }
Steve Naroff89922f82009-08-31 00:59:03 +0000130public:
Steve Naroff2b8ee6c2009-09-01 15:55:40 +0000131 TUVisitor(CXTranslationUnit CTU,
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000132 CXTranslationUnitIterator cback, CXClientData D,
133 unsigned MaxPCHLevel) :
134 TUnit(CTU), Callback(cback), CData(D), MaxPCHLevel(MaxPCHLevel) {}
Steve Naroff89922f82009-08-31 00:59:03 +0000135
136 void VisitTranslationUnitDecl(TranslationUnitDecl *D) {
137 VisitDeclContext(dyn_cast<DeclContext>(D));
138 }
139 void VisitDeclContext(DeclContext *DC) {
140 for (DeclContext::decl_iterator
141 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I)
142 Visit(*I);
143 }
Steve Naroff2b8ee6c2009-09-01 15:55:40 +0000144 void VisitTypedefDecl(TypedefDecl *ND) {
145 Call(CXCursor_TypedefDecl, ND);
Steve Naroff89922f82009-08-31 00:59:03 +0000146 }
147 void VisitTagDecl(TagDecl *ND) {
Steve Naroffc857ea42009-09-02 13:28:54 +0000148 switch (ND->getTagKind()) {
149 case TagDecl::TK_struct:
150 Call(CXCursor_StructDecl, ND);
151 break;
152 case TagDecl::TK_class:
153 Call(CXCursor_ClassDecl, ND);
154 break;
155 case TagDecl::TK_union:
156 Call(CXCursor_UnionDecl, ND);
157 break;
158 case TagDecl::TK_enum:
159 Call(CXCursor_EnumDecl, ND);
160 break;
161 }
Steve Naroff89922f82009-08-31 00:59:03 +0000162 }
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000163 void VisitVarDecl(VarDecl *ND) {
164 Call(CXCursor_VarDecl, ND);
165 }
Steve Naroff89922f82009-08-31 00:59:03 +0000166 void VisitFunctionDecl(FunctionDecl *ND) {
Steve Naroffc857ea42009-09-02 13:28:54 +0000167 Call(ND->isThisDeclarationADefinition() ? CXCursor_FunctionDefn
168 : CXCursor_FunctionDecl, ND);
Steve Naroff89922f82009-08-31 00:59:03 +0000169 }
170 void VisitObjCInterfaceDecl(ObjCInterfaceDecl *ND) {
Steve Naroff2b8ee6c2009-09-01 15:55:40 +0000171 Call(CXCursor_ObjCInterfaceDecl, ND);
Steve Naroff89922f82009-08-31 00:59:03 +0000172 }
173 void VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Steve Naroff2b8ee6c2009-09-01 15:55:40 +0000174 Call(CXCursor_ObjCCategoryDecl, ND);
Steve Naroff89922f82009-08-31 00:59:03 +0000175 }
176 void VisitObjCProtocolDecl(ObjCProtocolDecl *ND) {
Steve Naroff2b8ee6c2009-09-01 15:55:40 +0000177 Call(CXCursor_ObjCProtocolDecl, ND);
Steve Naroff89922f82009-08-31 00:59:03 +0000178 }
Steve Naroffc857ea42009-09-02 13:28:54 +0000179 void VisitObjCImplementationDecl(ObjCImplementationDecl *ND) {
180 Call(CXCursor_ObjCClassDefn, ND);
181 }
182 void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *ND) {
183 Call(CXCursor_ObjCCategoryDefn, ND);
184 }
Steve Naroff89922f82009-08-31 00:59:03 +0000185};
186
Steve Naroffc857ea42009-09-02 13:28:54 +0000187// Declaration visitor.
188class CDeclVisitor : public DeclVisitor<CDeclVisitor> {
189 CXDecl CDecl;
190 CXDeclIterator Callback;
191 CXClientData CData;
192
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000193 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
194 // to the visitor. Declarations with a PCH level greater than this value will
195 // be suppressed.
196 unsigned MaxPCHLevel;
197
Steve Naroffc857ea42009-09-02 13:28:54 +0000198 void Call(enum CXCursorKind CK, NamedDecl *ND) {
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000199 // Disable the callback when the context is equal to the visiting decl.
200 if (CDecl == ND && !clang_isReference(CK))
201 return;
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000202
203 // Filter any declarations that have a PCH level greater than what we allow.
204 if (ND->getPCHLevel() > MaxPCHLevel)
205 return;
206
Steve Narofffb570422009-09-22 19:25:29 +0000207 CXCursor C = { CK, ND, 0 };
Steve Naroffc857ea42009-09-02 13:28:54 +0000208 Callback(CDecl, C, CData);
209 }
Steve Naroff89922f82009-08-31 00:59:03 +0000210public:
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000211 CDeclVisitor(CXDecl C, CXDeclIterator cback, CXClientData D,
212 unsigned MaxPCHLevel) :
213 CDecl(C), Callback(cback), CData(D), MaxPCHLevel(MaxPCHLevel) {}
Steve Naroffc857ea42009-09-02 13:28:54 +0000214
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000215 void VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
216 // Issue callbacks for the containing class.
217 Call(CXCursor_ObjCClassRef, ND);
218 // FIXME: Issue callbacks for protocol refs.
219 VisitDeclContext(dyn_cast<DeclContext>(ND));
220 }
Steve Naroffc857ea42009-09-02 13:28:54 +0000221 void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000222 // Issue callbacks for super class.
Steve Narofff334b4e2009-09-02 18:26:48 +0000223 if (D->getSuperClass())
224 Call(CXCursor_ObjCSuperClassRef, D);
225
Steve Naroff9efa7672009-09-04 15:44:05 +0000226 for (ObjCProtocolDecl::protocol_iterator I = D->protocol_begin(),
227 E = D->protocol_end(); I != E; ++I)
228 Call(CXCursor_ObjCProtocolRef, *I);
Steve Naroffc857ea42009-09-02 13:28:54 +0000229 VisitDeclContext(dyn_cast<DeclContext>(D));
230 }
Steve Naroff9efa7672009-09-04 15:44:05 +0000231 void VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
232 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
233 E = PID->protocol_end(); I != E; ++I)
234 Call(CXCursor_ObjCProtocolRef, *I);
235
236 VisitDeclContext(dyn_cast<DeclContext>(PID));
237 }
Steve Naroffc857ea42009-09-02 13:28:54 +0000238 void VisitTagDecl(TagDecl *D) {
239 VisitDeclContext(dyn_cast<DeclContext>(D));
240 }
241 void VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
242 VisitDeclContext(dyn_cast<DeclContext>(D));
243 }
244 void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
245 VisitDeclContext(dyn_cast<DeclContext>(D));
246 }
Steve Naroff89922f82009-08-31 00:59:03 +0000247 void VisitDeclContext(DeclContext *DC) {
248 for (DeclContext::decl_iterator
249 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I)
250 Visit(*I);
251 }
252 void VisitEnumConstantDecl(EnumConstantDecl *ND) {
Steve Naroffc857ea42009-09-02 13:28:54 +0000253 Call(CXCursor_EnumConstantDecl, ND);
Steve Naroff89922f82009-08-31 00:59:03 +0000254 }
255 void VisitFieldDecl(FieldDecl *ND) {
Steve Naroffc857ea42009-09-02 13:28:54 +0000256 Call(CXCursor_FieldDecl, ND);
257 }
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000258 void VisitVarDecl(VarDecl *ND) {
259 Call(CXCursor_VarDecl, ND);
260 }
261 void VisitParmVarDecl(ParmVarDecl *ND) {
262 Call(CXCursor_ParmDecl, ND);
263 }
Steve Naroffc857ea42009-09-02 13:28:54 +0000264 void VisitObjCPropertyDecl(ObjCPropertyDecl *ND) {
265 Call(CXCursor_ObjCPropertyDecl, ND);
Steve Naroff89922f82009-08-31 00:59:03 +0000266 }
267 void VisitObjCIvarDecl(ObjCIvarDecl *ND) {
Steve Naroffc857ea42009-09-02 13:28:54 +0000268 Call(CXCursor_ObjCIvarDecl, ND);
269 }
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000270 void VisitFunctionDecl(FunctionDecl *ND) {
271 if (ND->isThisDeclarationADefinition()) {
272 VisitDeclContext(dyn_cast<DeclContext>(ND));
Steve Naroff4ade6d62009-09-23 17:52:52 +0000273#if 0
274 // Not currently needed.
275 CompoundStmt *Body = dyn_cast<CompoundStmt>(ND->getBody());
Steve Narofffb570422009-09-22 19:25:29 +0000276 CRefVisitor RVisit(CDecl, Callback, CData);
Steve Naroff4ade6d62009-09-23 17:52:52 +0000277 RVisit.Visit(Body);
278#endif
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000279 }
280 }
Steve Naroffc857ea42009-09-02 13:28:54 +0000281 void VisitObjCMethodDecl(ObjCMethodDecl *ND) {
282 if (ND->getBody()) {
283 Call(ND->isInstanceMethod() ? CXCursor_ObjCInstanceMethodDefn
284 : CXCursor_ObjCClassMethodDefn, ND);
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000285 VisitDeclContext(dyn_cast<DeclContext>(ND));
Steve Naroffc857ea42009-09-02 13:28:54 +0000286 } else
287 Call(ND->isInstanceMethod() ? CXCursor_ObjCInstanceMethodDecl
288 : CXCursor_ObjCClassMethodDecl, ND);
Steve Naroff89922f82009-08-31 00:59:03 +0000289 }
290};
291
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000292class CIndexer : public Indexer {
293public:
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000294 explicit CIndexer(Program *prog) : Indexer(*prog),
295 OnlyLocalDecls(false),
296 DisplayDiagnostics(false) {}
Ted Kremenekdff76892009-10-17 06:21:47 +0000297
298 virtual ~CIndexer() { delete &getProgram(); }
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000299
300 /// \brief Whether we only want to see "local" declarations (that did not
301 /// come from a previous precompiled header). If false, we want to see all
302 /// declarations.
303 bool getOnlyLocalDecls() const { return OnlyLocalDecls; }
304 void setOnlyLocalDecls(bool Local = true) { OnlyLocalDecls = Local; }
Benjamin Kramer96707622009-10-18 11:10:55 +0000305
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000306 void setDisplayDiagnostics(bool Display = true) {
307 DisplayDiagnostics = Display;
308 }
309 bool getDisplayDiagnostics() const { return DisplayDiagnostics; }
310
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000311 /// \brief Get the path of the clang binary.
Benjamin Kramerc5a9e952009-10-19 10:20:24 +0000312 const llvm::sys::Path& getClangPath();
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000313private:
314 bool OnlyLocalDecls;
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000315 bool DisplayDiagnostics;
316
Benjamin Kramerc5a9e952009-10-19 10:20:24 +0000317 llvm::sys::Path ClangPath;
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000318};
Steve Naroff89922f82009-08-31 00:59:03 +0000319
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000320const llvm::sys::Path& CIndexer::getClangPath() {
321 // Did we already compute the path?
322 if (!ClangPath.empty())
323 return ClangPath;
324
Steve Naroff5b7d8e22009-10-15 20:04:39 +0000325 // Find the location where this library lives (libCIndex.dylib).
Benjamin Kramer20d75812009-10-18 16:13:48 +0000326#ifdef LLVM_ON_WIN32
327 MEMORY_BASIC_INFORMATION mbi;
328 char path[MAX_PATH];
Benjamin Krameredcd8282009-10-18 16:20:58 +0000329 VirtualQuery((void *)(uintptr_t)clang_createTranslationUnit, &mbi,
Benjamin Kramer20d75812009-10-18 16:13:48 +0000330 sizeof(mbi));
331 GetModuleFileNameA((HINSTANCE)mbi.AllocationBase, path, MAX_PATH);
332
333 llvm::sys::Path CIndexPath(path);
334#else
Steve Naroff5b7d8e22009-10-15 20:04:39 +0000335 // This silly cast below avoids a C++ warning.
336 Dl_info info;
337 if (dladdr((void *)(uintptr_t)clang_createTranslationUnit, &info) == 0)
338 assert(0 && "Call to dladdr() failed");
339
340 llvm::sys::Path CIndexPath(info.dli_fname);
Daniel Dunbara47dd192009-10-17 23:53:11 +0000341#endif
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000342
Steve Naroff5b7d8e22009-10-15 20:04:39 +0000343 // We now have the CIndex directory, locate clang relative to it.
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000344 CIndexPath.eraseComponent();
345 CIndexPath.eraseComponent();
346 CIndexPath.appendComponent("bin");
347 CIndexPath.appendComponent("clang");
348
349 // Cache our result.
350 ClangPath = CIndexPath;
351 return ClangPath;
352}
353
354}
355
Daniel Dunbarc6190332009-11-08 04:13:53 +0000356static SourceLocation getLocationFromCursor(CXCursor C,
357 SourceManager &SourceMgr,
358 NamedDecl *ND) {
359 if (clang_isReference(C.kind)) {
360 switch (C.kind) {
361 case CXCursor_ObjCClassRef: {
362 if (isa<ObjCInterfaceDecl>(ND)) {
363 // FIXME: This is a hack (storing the parent decl in the stmt slot).
364 NamedDecl *parentDecl = static_cast<NamedDecl *>(C.stmt);
365 return parentDecl->getLocation();
366 }
367 ObjCCategoryDecl *OID = dyn_cast<ObjCCategoryDecl>(ND);
368 assert(OID && "clang_getCursorLine(): Missing category decl");
369 return OID->getClassInterface()->getLocation();
370 }
371 case CXCursor_ObjCSuperClassRef: {
372 ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ND);
373 assert(OID && "clang_getCursorLine(): Missing interface decl");
374 return OID->getSuperClassLoc();
375 }
376 case CXCursor_ObjCProtocolRef: {
377 ObjCProtocolDecl *OID = dyn_cast<ObjCProtocolDecl>(ND);
378 assert(OID && "clang_getCursorLine(): Missing protocol decl");
379 return OID->getLocation();
380 }
381 case CXCursor_ObjCSelectorRef: {
382 ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(
383 static_cast<Stmt *>(C.stmt));
384 assert(OME && "clang_getCursorLine(): Missing message expr");
385 return OME->getLeftLoc(); /* FIXME: should be a range */
386 }
387 case CXCursor_VarRef:
388 case CXCursor_FunctionRef:
389 case CXCursor_EnumConstantRef: {
390 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(
391 static_cast<Stmt *>(C.stmt));
392 assert(DRE && "clang_getCursorLine(): Missing decl ref expr");
393 return DRE->getLocation();
394 }
395 default:
396 return SourceLocation();
397 }
398 } else { // We have a declaration or a definition.
399 SourceLocation SLoc;
400 switch (ND->getKind()) {
401 case Decl::ObjCInterface: {
402 SLoc = dyn_cast<ObjCInterfaceDecl>(ND)->getClassLoc();
403 break;
404 }
405 case Decl::ObjCProtocol: {
406 SLoc = ND->getLocation(); /* FIXME: need to get the name location. */
407 break;
408 }
409 default: {
410 SLoc = ND->getLocation();
411 break;
412 }
413 }
414 if (SLoc.isInvalid())
415 return SourceLocation();
416 return SourceMgr.getSpellingLoc(SLoc); // handles macro instantiations.
417 }
418}
419
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000420extern "C" {
421
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000422CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
423 int displayDiagnostics)
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000424{
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000425 CIndexer *CIdxr = new CIndexer(new Program());
426 if (excludeDeclarationsFromPCH)
427 CIdxr->setOnlyLocalDecls();
428 if (displayDiagnostics)
429 CIdxr->setDisplayDiagnostics();
430 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +0000431}
432
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000433void clang_disposeIndex(CXIndex CIdx)
434{
435 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000436 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000437}
438
Steve Naroff50398192009-08-28 15:28:48 +0000439// FIXME: need to pass back error info.
440CXTranslationUnit clang_createTranslationUnit(
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000441 CXIndex CIdx, const char *ast_filename)
Steve Naroff600866c2009-08-27 19:51:58 +0000442{
Steve Naroff50398192009-08-28 15:28:48 +0000443 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000444 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Steve Naroff50398192009-08-28 15:28:48 +0000445 std::string astName(ast_filename);
446 std::string ErrMsg;
447
Ted Kremenek379afec2009-10-22 03:24:01 +0000448 CXTranslationUnit TU =
449 ASTUnit::LoadFromPCHFile(astName, &ErrMsg,
450 CXXIdx->getDisplayDiagnostics() ?
451 NULL : new IgnoreDiagnosticsClient(),
452 CXXIdx->getOnlyLocalDecls(),
453 /* UseBumpAllocator = */ true);
454
Ted Kremenek779e5f42009-10-26 22:08:39 +0000455 if (!ErrMsg.empty())
456 llvm::errs() << "clang_createTranslationUnit: " << ErrMsg << '\n';
Ted Kremenek379afec2009-10-22 03:24:01 +0000457
458 return TU;
Steve Naroff600866c2009-08-27 19:51:58 +0000459}
460
Steve Naroff5b7d8e22009-10-15 20:04:39 +0000461CXTranslationUnit clang_createTranslationUnitFromSourceFile(
462 CXIndex CIdx,
463 const char *source_filename,
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000464 int num_command_line_args, const char **command_line_args) {
465 assert(CIdx && "Passed null CXIndex");
466 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
467
Ted Kremenek139ba862009-10-22 00:03:57 +0000468 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000469 std::vector<const char *> argv;
Ted Kremenek139ba862009-10-22 00:03:57 +0000470
471 // First add the complete path to the 'clang' executable.
472 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000473 argv.push_back(ClangPath.c_str());
Ted Kremenek139ba862009-10-22 00:03:57 +0000474
475 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000476 argv.push_back("-emit-ast");
Ted Kremenek139ba862009-10-22 00:03:57 +0000477
478 // The 'source_filename' argument is optional. If the caller does not
479 // specify it then it is assumed that the source file is specified
480 // in the actual argument list.
481 if (source_filename)
482 argv.push_back(source_filename);
483
Steve Naroff37b5ac22009-10-15 20:50:09 +0000484 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +0000485 argv.push_back("-o");
Steve Naroff37b5ac22009-10-15 20:50:09 +0000486 char astTmpFile[L_tmpnam];
Ted Kremenek74cd0692009-10-15 23:21:22 +0000487 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +0000488
489 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
490 for (int i = 0; i < num_command_line_args; ++i)
491 if (const char *arg = command_line_args[i]) {
492 if (strcmp(arg, "-o") == 0) {
493 ++i; // Also skip the matching argument.
494 continue;
495 }
496 if (strcmp(arg, "-emit-ast") == 0 ||
497 strcmp(arg, "-c") == 0 ||
498 strcmp(arg, "-fsyntax-only") == 0) {
499 continue;
500 }
501
502 // Keep the argument.
503 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000504 }
Ted Kremenek139ba862009-10-22 00:03:57 +0000505
506 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000507 argv.push_back(NULL);
508
Ted Kremenekfeb15e32009-10-26 22:14:08 +0000509 // Invoke 'clang'.
510 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
511 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +0000512 std::string ErrMsg;
Ted Kremenekc46e4632009-10-19 22:27:32 +0000513 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DevNull, NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +0000514 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
515 /* redirects */ !CXXIdx->getDisplayDiagnostics() ? &Redirects[0] : NULL,
516 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
517
Ted Kremenek8ee1f3f2009-10-22 22:19:00 +0000518 if (!ErrMsg.empty()) {
Ted Kremenek379afec2009-10-22 03:24:01 +0000519 llvm::errs() << "clang_createTranslationUnitFromSourceFile: " << ErrMsg
520 << '\n' << "Arguments: \n";
521 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Ted Kremenek779e5f42009-10-26 22:08:39 +0000522 I!=E; ++I) {
523 if (*I)
524 llvm::errs() << ' ' << *I << '\n';
525 }
526 llvm::errs() << '\n';
Ted Kremenek379afec2009-10-22 03:24:01 +0000527 }
Benjamin Kramer0829a832009-10-18 11:19:36 +0000528
Steve Naroff37b5ac22009-10-15 20:50:09 +0000529 // Finally, we create the translation unit from the ast file.
Steve Naroffe19944c2009-10-15 22:23:48 +0000530 ASTUnit *ATU = static_cast<ASTUnit *>(
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000531 clang_createTranslationUnit(CIdx, astTmpFile));
532 if (ATU)
533 ATU->unlinkTemporaryFile();
Steve Naroffe19944c2009-10-15 22:23:48 +0000534 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +0000535}
536
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000537void clang_disposeTranslationUnit(
538 CXTranslationUnit CTUnit)
539{
540 assert(CTUnit && "Passed null CXTranslationUnit");
541 delete static_cast<ASTUnit *>(CTUnit);
542}
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000543
Steve Naroffef0cef62009-11-09 17:45:52 +0000544CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit)
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000545{
546 assert(CTUnit && "Passed null CXTranslationUnit");
Steve Naroff77accc12009-09-03 18:19:54 +0000547 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Steve Naroffef0cef62009-11-09 17:45:52 +0000548 CXString string;
549 string.Spelling = strdup(CXXUnit->getOriginalSourceFileName().c_str());
550 string.MustFreeString = 1;
551 return string;
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000552}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +0000553
Steve Naroffc857ea42009-09-02 13:28:54 +0000554void clang_loadTranslationUnit(CXTranslationUnit CTUnit,
555 CXTranslationUnitIterator callback,
556 CXClientData CData)
Steve Naroff600866c2009-08-27 19:51:58 +0000557{
Steve Naroff50398192009-08-28 15:28:48 +0000558 assert(CTUnit && "Passed null CXTranslationUnit");
559 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
560 ASTContext &Ctx = CXXUnit->getASTContext();
561
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000562 TUVisitor DVisit(CTUnit, callback, CData,
563 CXXUnit->getOnlyLocalDecls()? 1 : Decl::MaxPCHLevel);
Steve Naroff50398192009-08-28 15:28:48 +0000564 DVisit.Visit(Ctx.getTranslationUnitDecl());
Steve Naroff600866c2009-08-27 19:51:58 +0000565}
566
Steve Naroffc857ea42009-09-02 13:28:54 +0000567void clang_loadDeclaration(CXDecl Dcl,
568 CXDeclIterator callback,
569 CXClientData CData)
Steve Naroff600866c2009-08-27 19:51:58 +0000570{
Steve Naroffc857ea42009-09-02 13:28:54 +0000571 assert(Dcl && "Passed null CXDecl");
572
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000573 CDeclVisitor DVisit(Dcl, callback, CData,
574 static_cast<Decl *>(Dcl)->getPCHLevel());
Steve Naroffc857ea42009-09-02 13:28:54 +0000575 DVisit.Visit(static_cast<Decl *>(Dcl));
Steve Naroff600866c2009-08-27 19:51:58 +0000576}
577
Steve Naroff7e8f8182009-08-28 12:07:44 +0000578// Some notes on CXEntity:
579//
580// - Since the 'ordinary' namespace includes functions, data, typedefs,
581// ObjC interfaces, thecurrent algorithm is a bit naive (resulting in one
582// entity for 2 different types). For example:
583//
584// module1.m: @interface Foo @end Foo *x;
585// module2.m: void Foo(int);
586//
587// - Since the unique name spans translation units, static data/functions
588// within a CXTranslationUnit are *not* currently represented by entities.
589// As a result, there will be no entity for the following:
590//
591// module.m: static void Foo() { }
592//
593
594
Steve Naroff600866c2009-08-27 19:51:58 +0000595const char *clang_getDeclarationName(CXEntity)
596{
597 return "";
598}
599const char *clang_getURI(CXEntity)
600{
601 return "";
602}
603
604CXEntity clang_getEntity(const char *URI)
605{
606 return 0;
607}
608
609//
610// CXDecl Operations.
611//
Steve Naroff600866c2009-08-27 19:51:58 +0000612CXEntity clang_getEntityFromDecl(CXDecl)
613{
614 return 0;
615}
Steve Naroffef0cef62009-11-09 17:45:52 +0000616CXString clang_getDeclSpelling(CXDecl AnonDecl)
Steve Naroff600866c2009-08-27 19:51:58 +0000617{
Steve Naroff89922f82009-08-31 00:59:03 +0000618 assert(AnonDecl && "Passed null CXDecl");
619 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
Steve Naroffef0cef62009-11-09 17:45:52 +0000620 CXString string;
621
622 string.MustFreeString = 0;
Steve Naroffc857ea42009-09-02 13:28:54 +0000623 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND)) {
Steve Naroffef0cef62009-11-09 17:45:52 +0000624 string.Spelling = strdup(OMD->getSelector().getAsString().c_str());
625 string.MustFreeString = 1;
Steve Narofff9f61962009-10-29 18:55:50 +0000626 }
Steve Naroffef0cef62009-11-09 17:45:52 +0000627 else if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Steve Naroff0d69b8c2009-10-29 21:11:04 +0000628 // No, this isn't the same as the code below. getIdentifier() is non-virtual
629 // and returns different names. NamedDecl returns the class name and
630 // ObjCCategoryImplDecl returns the category name.
Steve Naroffef0cef62009-11-09 17:45:52 +0000631 string.Spelling = CIMP->getIdentifier()->getNameStart();
632 else if (ND->getIdentifier())
633 string.Spelling = ND->getIdentifier()->getNameStart();
Steve Naroffc857ea42009-09-02 13:28:54 +0000634 else
Steve Naroffef0cef62009-11-09 17:45:52 +0000635 string.Spelling = "";
636 return string;
Steve Naroff600866c2009-08-27 19:51:58 +0000637}
Steve Narofff334b4e2009-09-02 18:26:48 +0000638
Steve Naroff699a07d2009-09-25 21:32:34 +0000639unsigned clang_getDeclLine(CXDecl AnonDecl)
640{
641 assert(AnonDecl && "Passed null CXDecl");
642 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
643 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
644 return SourceMgr.getSpellingLineNumber(ND->getLocation());
645}
646
647unsigned clang_getDeclColumn(CXDecl AnonDecl)
648{
649 assert(AnonDecl && "Passed null CXDecl");
650 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
651 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Steve Naroff74165242009-09-25 22:15:54 +0000652 return SourceMgr.getSpellingColumnNumber(ND->getLocation());
Steve Naroff699a07d2009-09-25 21:32:34 +0000653}
654
Steve Naroffee9405e2009-09-25 21:45:39 +0000655const char *clang_getDeclSource(CXDecl AnonDecl)
656{
657 assert(AnonDecl && "Passed null CXDecl");
Steve Naroff88145032009-10-27 14:35:18 +0000658 FileEntry *FEnt = static_cast<FileEntry *>(clang_getDeclSourceFile(AnonDecl));
659 assert (FEnt && "Cannot find FileEntry for Decl");
660 return clang_getFileName(FEnt);
661}
662
663static const FileEntry *getFileEntryFromSourceLocation(SourceManager &SMgr,
664 SourceLocation SLoc)
665{
666 FileID FID;
667 if (SLoc.isFileID())
668 FID = SMgr.getFileID(SLoc);
669 else
670 FID = SMgr.getDecomposedSpellingLoc(SLoc).first;
671 return SMgr.getFileEntryForID(FID);
672}
673
674CXFile clang_getDeclSourceFile(CXDecl AnonDecl)
675{
676 assert(AnonDecl && "Passed null CXDecl");
Steve Naroffee9405e2009-09-25 21:45:39 +0000677 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
678 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Steve Naroff88145032009-10-27 14:35:18 +0000679 return (void *)getFileEntryFromSourceLocation(SourceMgr, ND->getLocation());
680}
681
682const char *clang_getFileName(CXFile SFile) {
683 assert(SFile && "Passed null CXFile");
684 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
685 return FEnt->getName();
686}
687
688time_t clang_getFileTime(CXFile SFile) {
689 assert(SFile && "Passed null CXFile");
690 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
691 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +0000692}
693
Steve Naroffef0cef62009-11-09 17:45:52 +0000694CXString clang_getCursorSpelling(CXCursor C)
Steve Narofff334b4e2009-09-02 18:26:48 +0000695{
696 assert(C.decl && "CXCursor has null decl");
697 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
Steve Naroffef0cef62009-11-09 17:45:52 +0000698
Steve Narofff334b4e2009-09-02 18:26:48 +0000699 if (clang_isReference(C.kind)) {
Steve Naroffef0cef62009-11-09 17:45:52 +0000700 CXString string;
701 string.MustFreeString = 0;
Steve Narofff334b4e2009-09-02 18:26:48 +0000702 switch (C.kind) {
Steve Naroffbade7de2009-10-19 13:41:39 +0000703 case CXCursor_ObjCSuperClassRef: {
Steve Narofff334b4e2009-09-02 18:26:48 +0000704 ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ND);
705 assert(OID && "clang_getCursorLine(): Missing interface decl");
Steve Naroffef0cef62009-11-09 17:45:52 +0000706 string.Spelling = OID->getSuperClass()->getIdentifier()->getNameStart();
707 break;
Steve Naroffbade7de2009-10-19 13:41:39 +0000708 }
709 case CXCursor_ObjCClassRef: {
Steve Naroff85e2db72009-10-01 00:31:07 +0000710 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ND)) {
Steve Naroffef0cef62009-11-09 17:45:52 +0000711 string.Spelling = OID->getIdentifier()->getNameStart();
712 } else {
713 ObjCCategoryDecl *OCD = dyn_cast<ObjCCategoryDecl>(ND);
714 assert(OCD && "clang_getCursorLine(): Missing category decl");
715 string.Spelling = OCD->getClassInterface()->getIdentifier()->getNameStart();
Steve Naroff85e2db72009-10-01 00:31:07 +0000716 }
Steve Naroffef0cef62009-11-09 17:45:52 +0000717 break;
Steve Naroffbade7de2009-10-19 13:41:39 +0000718 }
719 case CXCursor_ObjCProtocolRef: {
Steve Naroff9efa7672009-09-04 15:44:05 +0000720 ObjCProtocolDecl *OID = dyn_cast<ObjCProtocolDecl>(ND);
721 assert(OID && "clang_getCursorLine(): Missing protocol decl");
Steve Naroffef0cef62009-11-09 17:45:52 +0000722 string.Spelling = OID->getIdentifier()->getNameStart();
723 break;
Steve Naroffbade7de2009-10-19 13:41:39 +0000724 }
725 case CXCursor_ObjCSelectorRef: {
Steve Narofffb570422009-09-22 19:25:29 +0000726 ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(
727 static_cast<Stmt *>(C.stmt));
728 assert(OME && "clang_getCursorLine(): Missing message expr");
Steve Naroffef0cef62009-11-09 17:45:52 +0000729 string.Spelling = strdup(OME->getSelector().getAsString().c_str());
730 string.MustFreeString = 1;
731 break;
Steve Naroffbade7de2009-10-19 13:41:39 +0000732 }
Steve Narofffb570422009-09-22 19:25:29 +0000733 case CXCursor_VarRef:
734 case CXCursor_FunctionRef:
Steve Naroffbade7de2009-10-19 13:41:39 +0000735 case CXCursor_EnumConstantRef: {
Steve Narofffb570422009-09-22 19:25:29 +0000736 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(
737 static_cast<Stmt *>(C.stmt));
738 assert(DRE && "clang_getCursorLine(): Missing decl ref expr");
Steve Naroffef0cef62009-11-09 17:45:52 +0000739 string.Spelling = DRE->getDecl()->getIdentifier()->getNameStart();
740 break;
Steve Naroffbade7de2009-10-19 13:41:39 +0000741 }
Steve Narofff334b4e2009-09-02 18:26:48 +0000742 default:
Steve Naroffef0cef62009-11-09 17:45:52 +0000743 string.Spelling = "<not implemented>";
744 break;
Steve Narofff334b4e2009-09-02 18:26:48 +0000745 }
Steve Naroffef0cef62009-11-09 17:45:52 +0000746 return string;
Steve Narofff334b4e2009-09-02 18:26:48 +0000747 }
748 return clang_getDeclSpelling(C.decl);
749}
750
751const char *clang_getCursorKindSpelling(enum CXCursorKind Kind)
Steve Naroff600866c2009-08-27 19:51:58 +0000752{
Steve Naroff89922f82009-08-31 00:59:03 +0000753 switch (Kind) {
754 case CXCursor_FunctionDecl: return "FunctionDecl";
755 case CXCursor_TypedefDecl: return "TypedefDecl";
756 case CXCursor_EnumDecl: return "EnumDecl";
757 case CXCursor_EnumConstantDecl: return "EnumConstantDecl";
Steve Naroffc857ea42009-09-02 13:28:54 +0000758 case CXCursor_StructDecl: return "StructDecl";
759 case CXCursor_UnionDecl: return "UnionDecl";
760 case CXCursor_ClassDecl: return "ClassDecl";
Steve Naroff89922f82009-08-31 00:59:03 +0000761 case CXCursor_FieldDecl: return "FieldDecl";
762 case CXCursor_VarDecl: return "VarDecl";
763 case CXCursor_ParmDecl: return "ParmDecl";
764 case CXCursor_ObjCInterfaceDecl: return "ObjCInterfaceDecl";
765 case CXCursor_ObjCCategoryDecl: return "ObjCCategoryDecl";
766 case CXCursor_ObjCProtocolDecl: return "ObjCProtocolDecl";
767 case CXCursor_ObjCPropertyDecl: return "ObjCPropertyDecl";
768 case CXCursor_ObjCIvarDecl: return "ObjCIvarDecl";
Steve Naroffc857ea42009-09-02 13:28:54 +0000769 case CXCursor_ObjCInstanceMethodDecl: return "ObjCInstanceMethodDecl";
770 case CXCursor_ObjCClassMethodDecl: return "ObjCClassMethodDecl";
771 case CXCursor_FunctionDefn: return "FunctionDefn";
772 case CXCursor_ObjCInstanceMethodDefn: return "ObjCInstanceMethodDefn";
773 case CXCursor_ObjCClassMethodDefn: return "ObjCClassMethodDefn";
774 case CXCursor_ObjCClassDefn: return "ObjCClassDefn";
775 case CXCursor_ObjCCategoryDefn: return "ObjCCategoryDefn";
Steve Narofff334b4e2009-09-02 18:26:48 +0000776 case CXCursor_ObjCSuperClassRef: return "ObjCSuperClassRef";
Steve Naroff9efa7672009-09-04 15:44:05 +0000777 case CXCursor_ObjCProtocolRef: return "ObjCProtocolRef";
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000778 case CXCursor_ObjCClassRef: return "ObjCClassRef";
Steve Narofffb570422009-09-22 19:25:29 +0000779 case CXCursor_ObjCSelectorRef: return "ObjCSelectorRef";
780
781 case CXCursor_VarRef: return "VarRef";
782 case CXCursor_FunctionRef: return "FunctionRef";
783 case CXCursor_EnumConstantRef: return "EnumConstantRef";
784 case CXCursor_MemberRef: return "MemberRef";
785
Steve Naroff77128dd2009-09-15 20:25:34 +0000786 case CXCursor_InvalidFile: return "InvalidFile";
787 case CXCursor_NoDeclFound: return "NoDeclFound";
788 case CXCursor_NotImplemented: return "NotImplemented";
Steve Naroff89922f82009-08-31 00:59:03 +0000789 default: return "<not implemented>";
790 }
Steve Naroff600866c2009-08-27 19:51:58 +0000791}
Steve Naroff89922f82009-08-31 00:59:03 +0000792
Steve Naroff9efa7672009-09-04 15:44:05 +0000793static enum CXCursorKind TranslateKind(Decl *D) {
794 switch (D->getKind()) {
795 case Decl::Function: return CXCursor_FunctionDecl;
796 case Decl::Typedef: return CXCursor_TypedefDecl;
797 case Decl::Enum: return CXCursor_EnumDecl;
798 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
799 case Decl::Record: return CXCursor_StructDecl; // FIXME: union/class
800 case Decl::Field: return CXCursor_FieldDecl;
801 case Decl::Var: return CXCursor_VarDecl;
802 case Decl::ParmVar: return CXCursor_ParmDecl;
803 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
Steve Narofffb570422009-09-22 19:25:29 +0000804 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
805 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
Steve Naroff9efa7672009-09-04 15:44:05 +0000806 case Decl::ObjCMethod: {
807 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D);
808 if (MD->isInstanceMethod())
809 return CXCursor_ObjCInstanceMethodDecl;
810 return CXCursor_ObjCClassMethodDecl;
811 }
812 default: break;
813 }
Steve Naroff77128dd2009-09-15 20:25:34 +0000814 return CXCursor_NotImplemented;
Steve Naroff9efa7672009-09-04 15:44:05 +0000815}
Steve Naroff600866c2009-08-27 19:51:58 +0000816//
817// CXCursor Operations.
818//
Steve Naroff9efa7672009-09-04 15:44:05 +0000819CXCursor clang_getCursor(CXTranslationUnit CTUnit, const char *source_name,
Steve Narofff96b5242009-10-28 20:44:47 +0000820 unsigned line, unsigned column)
Steve Naroff600866c2009-08-27 19:51:58 +0000821{
Steve Naroff9efa7672009-09-04 15:44:05 +0000822 assert(CTUnit && "Passed null CXTranslationUnit");
823 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
824
825 FileManager &FMgr = CXXUnit->getFileManager();
826 const FileEntry *File = FMgr.getFile(source_name,
Steve Naroff77128dd2009-09-15 20:25:34 +0000827 source_name+strlen(source_name));
828 if (!File) {
Steve Narofffb570422009-09-22 19:25:29 +0000829 CXCursor C = { CXCursor_InvalidFile, 0, 0 };
Steve Naroff77128dd2009-09-15 20:25:34 +0000830 return C;
831 }
Steve Naroff9efa7672009-09-04 15:44:05 +0000832 SourceLocation SLoc =
833 CXXUnit->getSourceManager().getLocation(File, line, column);
834
Steve Narofff96b5242009-10-28 20:44:47 +0000835 ASTLocation LastLoc = CXXUnit->getLastASTLocation();
836
837 ASTLocation ALoc = ResolveLocationInAST(CXXUnit->getASTContext(), SLoc,
838 &LastLoc);
839 if (ALoc.isValid())
840 CXXUnit->setLastASTLocation(ALoc);
841
Argyrios Kyrtzidisf4526e32009-09-29 19:44:27 +0000842 Decl *Dcl = ALoc.getParentDecl();
Argyrios Kyrtzidis05a76512009-09-29 19:45:58 +0000843 if (ALoc.isNamedRef())
844 Dcl = ALoc.AsNamedRef().ND;
Argyrios Kyrtzidisf4526e32009-09-29 19:44:27 +0000845 Stmt *Stm = ALoc.dyn_AsStmt();
Steve Naroff4ade6d62009-09-23 17:52:52 +0000846 if (Dcl) {
847 if (Stm) {
848 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Stm)) {
849 CXCursor C = { TranslateDeclRefExpr(DRE), Dcl, Stm };
850 return C;
851 } else if (ObjCMessageExpr *MExp = dyn_cast<ObjCMessageExpr>(Stm)) {
852 CXCursor C = { CXCursor_ObjCSelectorRef, Dcl, MExp };
853 return C;
Steve Naroff85e2db72009-10-01 00:31:07 +0000854 }
Steve Naroff4ade6d62009-09-23 17:52:52 +0000855 // Fall through...treat as a decl, not a ref.
856 }
Steve Naroff85e2db72009-10-01 00:31:07 +0000857 if (ALoc.isNamedRef()) {
858 if (isa<ObjCInterfaceDecl>(Dcl)) {
859 CXCursor C = { CXCursor_ObjCClassRef, Dcl, ALoc.getParentDecl() };
860 return C;
861 }
862 if (isa<ObjCProtocolDecl>(Dcl)) {
863 CXCursor C = { CXCursor_ObjCProtocolRef, Dcl, ALoc.getParentDecl() };
864 return C;
865 }
866 }
867 CXCursor C = { TranslateKind(Dcl), Dcl, 0 };
Steve Naroff77128dd2009-09-15 20:25:34 +0000868 return C;
869 }
Steve Narofffb570422009-09-22 19:25:29 +0000870 CXCursor C = { CXCursor_NoDeclFound, 0, 0 };
Steve Naroff9efa7672009-09-04 15:44:05 +0000871 return C;
Steve Naroff600866c2009-08-27 19:51:58 +0000872}
873
Steve Naroff77128dd2009-09-15 20:25:34 +0000874CXCursor clang_getCursorFromDecl(CXDecl AnonDecl)
875{
876 assert(AnonDecl && "Passed null CXDecl");
877 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
878
Steve Narofffb570422009-09-22 19:25:29 +0000879 CXCursor C = { TranslateKind(ND), ND, 0 };
Steve Naroff77128dd2009-09-15 20:25:34 +0000880 return C;
881}
882
883unsigned clang_isInvalid(enum CXCursorKind K)
884{
885 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
886}
887
Steve Naroff89922f82009-08-31 00:59:03 +0000888unsigned clang_isDeclaration(enum CXCursorKind K)
889{
890 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
891}
Steve Naroff2d4d6292009-08-31 14:26:51 +0000892
Steve Narofff334b4e2009-09-02 18:26:48 +0000893unsigned clang_isReference(enum CXCursorKind K)
894{
895 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
896}
897
898unsigned clang_isDefinition(enum CXCursorKind K)
899{
900 return K >= CXCursor_FirstDefn && K <= CXCursor_LastDefn;
901}
902
Steve Naroff9efa7672009-09-04 15:44:05 +0000903CXCursorKind clang_getCursorKind(CXCursor C)
904{
905 return C.kind;
906}
907
Steve Naroff699a07d2009-09-25 21:32:34 +0000908static Decl *getDeclFromExpr(Stmt *E) {
909 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
910 return RefExpr->getDecl();
911 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
912 return ME->getMemberDecl();
913 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
914 return RE->getDecl();
915
916 if (CallExpr *CE = dyn_cast<CallExpr>(E))
917 return getDeclFromExpr(CE->getCallee());
918 if (CastExpr *CE = dyn_cast<CastExpr>(E))
919 return getDeclFromExpr(CE->getSubExpr());
920 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
921 return OME->getMethodDecl();
922
923 return 0;
924}
925
Steve Naroff9efa7672009-09-04 15:44:05 +0000926CXDecl clang_getCursorDecl(CXCursor C)
927{
Steve Naroff699a07d2009-09-25 21:32:34 +0000928 if (clang_isDeclaration(C.kind))
929 return C.decl;
930
931 if (clang_isReference(C.kind)) {
Steve Naroff85e2db72009-10-01 00:31:07 +0000932 if (C.stmt) {
Steve Narofff9adf8f2009-10-05 17:58:19 +0000933 if (C.kind == CXCursor_ObjCClassRef ||
934 C.kind == CXCursor_ObjCProtocolRef)
Steve Naroff85e2db72009-10-01 00:31:07 +0000935 return static_cast<Stmt *>(C.stmt);
936 else
937 return getDeclFromExpr(static_cast<Stmt *>(C.stmt));
938 } else
Steve Naroff699a07d2009-09-25 21:32:34 +0000939 return C.decl;
940 }
941 return 0;
Steve Naroff9efa7672009-09-04 15:44:05 +0000942}
943
Steve Naroff2d4d6292009-08-31 14:26:51 +0000944unsigned clang_getCursorLine(CXCursor C)
Steve Naroff600866c2009-08-27 19:51:58 +0000945{
Steve Naroff2d4d6292009-08-31 14:26:51 +0000946 assert(C.decl && "CXCursor has null decl");
947 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
Steve Naroff2d4d6292009-08-31 14:26:51 +0000948 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Steve Narofff334b4e2009-09-02 18:26:48 +0000949
950 SourceLocation SLoc = getLocationFromCursor(C, SourceMgr, ND);
Steve Naroff2d4d6292009-08-31 14:26:51 +0000951 return SourceMgr.getSpellingLineNumber(SLoc);
Steve Naroff600866c2009-08-27 19:51:58 +0000952}
Steve Narofff334b4e2009-09-02 18:26:48 +0000953
Steve Naroffef0cef62009-11-09 17:45:52 +0000954// Access string.
955const char *clang_getCString(CXString string) {
956 return string.Spelling;
957}
958
959// Free CXString.
960void clang_disposeString(CXString string) {
961 if (string.MustFreeString) {
962 if (string.Spelling) {
963 free((void *)string.Spelling);
964 string.Spelling = NULL;
965 }
966 string.MustFreeString = 0;
967 }
968}
969
Steve Naroff2d4d6292009-08-31 14:26:51 +0000970unsigned clang_getCursorColumn(CXCursor C)
Steve Naroff600866c2009-08-27 19:51:58 +0000971{
Steve Naroff2d4d6292009-08-31 14:26:51 +0000972 assert(C.decl && "CXCursor has null decl");
973 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
Steve Naroff2d4d6292009-08-31 14:26:51 +0000974 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Steve Narofff334b4e2009-09-02 18:26:48 +0000975
976 SourceLocation SLoc = getLocationFromCursor(C, SourceMgr, ND);
Steve Naroff2d4d6292009-08-31 14:26:51 +0000977 return SourceMgr.getSpellingColumnNumber(SLoc);
Steve Naroff600866c2009-08-27 19:51:58 +0000978}
Steve Naroff2d4d6292009-08-31 14:26:51 +0000979const char *clang_getCursorSource(CXCursor C)
Steve Naroff600866c2009-08-27 19:51:58 +0000980{
Steve Naroff2d4d6292009-08-31 14:26:51 +0000981 assert(C.decl && "CXCursor has null decl");
982 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
Steve Naroff2d4d6292009-08-31 14:26:51 +0000983 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Steve Narofff334b4e2009-09-02 18:26:48 +0000984
985 SourceLocation SLoc = getLocationFromCursor(C, SourceMgr, ND);
Douglas Gregor02465752009-10-16 21:24:31 +0000986 if (SLoc.isFileID())
987 return SourceMgr.getBufferName(SLoc);
988
989 // Retrieve the file in which the macro was instantiated, then provide that
990 // buffer name.
991 // FIXME: Do we want to give specific macro-instantiation information?
992 const llvm::MemoryBuffer *Buffer
993 = SourceMgr.getBuffer(SourceMgr.getDecomposedSpellingLoc(SLoc).first);
994 if (!Buffer)
995 return 0;
996
997 return Buffer->getBufferIdentifier();
Steve Naroff600866c2009-08-27 19:51:58 +0000998}
999
Steve Naroff88145032009-10-27 14:35:18 +00001000CXFile clang_getCursorSourceFile(CXCursor C)
1001{
1002 assert(C.decl && "CXCursor has null decl");
1003 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
1004 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
1005
1006 return (void *)getFileEntryFromSourceLocation(SourceMgr,
1007 getLocationFromCursor(C,SourceMgr, ND));
1008}
1009
Steve Naroff4ade6d62009-09-23 17:52:52 +00001010void clang_getDefinitionSpellingAndExtent(CXCursor C,
1011 const char **startBuf,
1012 const char **endBuf,
1013 unsigned *startLine,
1014 unsigned *startColumn,
1015 unsigned *endLine,
1016 unsigned *endColumn)
1017{
1018 assert(C.decl && "CXCursor has null decl");
1019 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
1020 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
1021 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
1022
1023 SourceManager &SM = FD->getASTContext().getSourceManager();
1024 *startBuf = SM.getCharacterData(Body->getLBracLoc());
1025 *endBuf = SM.getCharacterData(Body->getRBracLoc());
1026 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
1027 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
1028 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
1029 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
1030}
1031
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001032enum CXCompletionChunkKind
1033clang_getCompletionChunkKind(CXCompletionString completion_string,
1034 unsigned chunk_number) {
1035 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
1036 if (!CCStr || chunk_number >= CCStr->size())
1037 return CXCompletionChunk_Text;
1038
1039 switch ((*CCStr)[chunk_number].Kind) {
1040 case CodeCompletionString::CK_TypedText:
1041 return CXCompletionChunk_TypedText;
1042 case CodeCompletionString::CK_Text:
1043 return CXCompletionChunk_Text;
1044 case CodeCompletionString::CK_Optional:
1045 return CXCompletionChunk_Optional;
1046 case CodeCompletionString::CK_Placeholder:
1047 return CXCompletionChunk_Placeholder;
1048 case CodeCompletionString::CK_Informative:
1049 return CXCompletionChunk_Informative;
1050 case CodeCompletionString::CK_CurrentParameter:
1051 return CXCompletionChunk_CurrentParameter;
1052 case CodeCompletionString::CK_LeftParen:
1053 return CXCompletionChunk_LeftParen;
1054 case CodeCompletionString::CK_RightParen:
1055 return CXCompletionChunk_RightParen;
1056 case CodeCompletionString::CK_LeftBracket:
1057 return CXCompletionChunk_LeftBracket;
1058 case CodeCompletionString::CK_RightBracket:
1059 return CXCompletionChunk_RightBracket;
1060 case CodeCompletionString::CK_LeftBrace:
1061 return CXCompletionChunk_LeftBrace;
1062 case CodeCompletionString::CK_RightBrace:
1063 return CXCompletionChunk_RightBrace;
1064 case CodeCompletionString::CK_LeftAngle:
1065 return CXCompletionChunk_LeftAngle;
1066 case CodeCompletionString::CK_RightAngle:
1067 return CXCompletionChunk_RightAngle;
1068 case CodeCompletionString::CK_Comma:
1069 return CXCompletionChunk_Comma;
1070 }
1071
1072 // Should be unreachable, but let's be careful.
1073 return CXCompletionChunk_Text;
1074}
1075
1076const char *clang_getCompletionChunkText(CXCompletionString completion_string,
1077 unsigned chunk_number) {
1078 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
1079 if (!CCStr || chunk_number >= CCStr->size())
1080 return 0;
1081
1082 switch ((*CCStr)[chunk_number].Kind) {
1083 case CodeCompletionString::CK_TypedText:
1084 case CodeCompletionString::CK_Text:
1085 case CodeCompletionString::CK_Placeholder:
1086 case CodeCompletionString::CK_CurrentParameter:
1087 case CodeCompletionString::CK_Informative:
1088 case CodeCompletionString::CK_LeftParen:
1089 case CodeCompletionString::CK_RightParen:
1090 case CodeCompletionString::CK_LeftBracket:
1091 case CodeCompletionString::CK_RightBracket:
1092 case CodeCompletionString::CK_LeftBrace:
1093 case CodeCompletionString::CK_RightBrace:
1094 case CodeCompletionString::CK_LeftAngle:
1095 case CodeCompletionString::CK_RightAngle:
1096 case CodeCompletionString::CK_Comma:
1097 return (*CCStr)[chunk_number].Text;
1098
1099 case CodeCompletionString::CK_Optional:
1100 // Note: treated as an empty text block.
1101 return 0;
1102 }
1103
1104 // Should be unreachable, but let's be careful.
1105 return 0;
1106}
1107
1108CXCompletionString
1109clang_getCompletionChunkCompletionString(CXCompletionString completion_string,
1110 unsigned chunk_number) {
1111 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
1112 if (!CCStr || chunk_number >= CCStr->size())
1113 return 0;
1114
1115 switch ((*CCStr)[chunk_number].Kind) {
1116 case CodeCompletionString::CK_TypedText:
1117 case CodeCompletionString::CK_Text:
1118 case CodeCompletionString::CK_Placeholder:
1119 case CodeCompletionString::CK_CurrentParameter:
1120 case CodeCompletionString::CK_Informative:
1121 case CodeCompletionString::CK_LeftParen:
1122 case CodeCompletionString::CK_RightParen:
1123 case CodeCompletionString::CK_LeftBracket:
1124 case CodeCompletionString::CK_RightBracket:
1125 case CodeCompletionString::CK_LeftBrace:
1126 case CodeCompletionString::CK_RightBrace:
1127 case CodeCompletionString::CK_LeftAngle:
1128 case CodeCompletionString::CK_RightAngle:
1129 case CodeCompletionString::CK_Comma:
1130 return 0;
1131
1132 case CodeCompletionString::CK_Optional:
1133 // Note: treated as an empty text block.
1134 return (*CCStr)[chunk_number].Optional;
1135 }
1136
1137 // Should be unreachable, but let's be careful.
1138 return 0;
1139}
1140
1141unsigned clang_getNumCompletionChunks(CXCompletionString completion_string) {
1142 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
1143 return CCStr? CCStr->size() : 0;
1144}
Steve Naroff4ade6d62009-09-23 17:52:52 +00001145
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001146static CXCursorKind parseResultKind(llvm::StringRef Str) {
1147 return llvm::StringSwitch<CXCursorKind>(Str)
1148 .Case("Typedef", CXCursor_TypedefDecl)
1149 .Case("Struct", CXCursor_StructDecl)
1150 .Case("Union", CXCursor_UnionDecl)
1151 .Case("Class", CXCursor_ClassDecl)
1152 .Case("Field", CXCursor_FieldDecl)
1153 .Case("EnumConstant", CXCursor_EnumConstantDecl)
1154 .Case("Function", CXCursor_FunctionDecl)
1155 // FIXME: Hacks here to make C++ member functions look like C functions
1156 .Case("CXXMethod", CXCursor_FunctionDecl)
1157 .Case("CXXConstructor", CXCursor_FunctionDecl)
1158 .Case("CXXDestructor", CXCursor_FunctionDecl)
1159 .Case("CXXConversion", CXCursor_FunctionDecl)
1160 .Case("Var", CXCursor_VarDecl)
1161 .Case("ParmVar", CXCursor_ParmDecl)
1162 .Case("ObjCInterface", CXCursor_ObjCInterfaceDecl)
1163 .Case("ObjCCategory", CXCursor_ObjCCategoryDecl)
1164 .Case("ObjCProtocol", CXCursor_ObjCProtocolDecl)
1165 .Case("ObjCProperty", CXCursor_ObjCPropertyDecl)
1166 .Case("ObjCIvar", CXCursor_ObjCIvarDecl)
1167 .Case("ObjCInstanceMethod", CXCursor_ObjCInstanceMethodDecl)
1168 .Case("ObjCClassMethod", CXCursor_ObjCClassMethodDecl)
1169 .Default(CXCursor_NotImplemented);
1170}
1171
1172void clang_codeComplete(CXIndex CIdx,
1173 const char *source_filename,
1174 int num_command_line_args,
1175 const char **command_line_args,
1176 const char *complete_filename,
1177 unsigned complete_line,
1178 unsigned complete_column,
1179 CXCompletionIterator completion_iterator,
1180 CXClientData client_data) {
1181 // The indexer, which is mainly used to determine where diagnostics go.
1182 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1183
1184 // Build up the arguments for invoking 'clang'.
1185 std::vector<const char *> argv;
1186
1187 // First add the complete path to the 'clang' executable.
1188 llvm::sys::Path ClangPath = CXXIdx->getClangPath();
1189 argv.push_back(ClangPath.c_str());
1190
1191 // Add the '-fsyntax-only' argument so that we only perform a basic
1192 // syntax check of the code.
1193 argv.push_back("-fsyntax-only");
1194
1195 // Add the appropriate '-code-completion-at=file:line:column' argument
1196 // to perform code completion, with an "-Xclang" preceding it.
1197 std::string code_complete_at;
1198 code_complete_at += "-code-completion-at=";
1199 code_complete_at += complete_filename;
1200 code_complete_at += ":";
1201 code_complete_at += llvm::utostr(complete_line);
1202 code_complete_at += ":";
1203 code_complete_at += llvm::utostr(complete_column);
1204 argv.push_back("-Xclang");
1205 argv.push_back(code_complete_at.c_str());
1206 argv.push_back("-Xclang");
1207 argv.push_back("-code-completion-printer=cindex");
1208
1209 // Add the source file name (FIXME: later, we'll want to build temporary
1210 // file from the buffer, or just feed the source text via standard input).
1211 argv.push_back(source_filename);
1212
1213 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1214 for (int i = 0; i < num_command_line_args; ++i)
1215 if (const char *arg = command_line_args[i]) {
1216 if (strcmp(arg, "-o") == 0) {
1217 ++i; // Also skip the matching argument.
1218 continue;
1219 }
1220 if (strcmp(arg, "-emit-ast") == 0 ||
1221 strcmp(arg, "-c") == 0 ||
1222 strcmp(arg, "-fsyntax-only") == 0) {
1223 continue;
1224 }
1225
1226 // Keep the argument.
1227 argv.push_back(arg);
1228 }
1229
1230 // Add the null terminator.
1231 argv.push_back(NULL);
1232
1233 // Generate a temporary name for the AST file.
1234 char tmpFile[L_tmpnam];
1235 char *tmpFileName = tmpnam(tmpFile);
1236 llvm::sys::Path ResultsFile(tmpFileName);
1237
1238 // Invoke 'clang'.
1239 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1240 // on Unix or NUL (Windows).
1241 std::string ErrMsg;
1242 const llvm::sys::Path *Redirects[] = { &DevNull, &ResultsFile, &DevNull, 0 };
1243 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
1244 /* redirects */ &Redirects[0],
1245 /* secondsToWait */ 0,
1246 /* memoryLimits */ 0, &ErrMsg);
1247
1248 if (!ErrMsg.empty()) {
1249 llvm::errs() << "clang_codeComplete: " << ErrMsg
1250 << '\n' << "Arguments: \n";
1251 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
1252 I!=E; ++I) {
1253 if (*I)
1254 llvm::errs() << ' ' << *I << '\n';
1255 }
1256 llvm::errs() << '\n';
1257 }
1258
1259 // Parse the resulting source file to find code-completion results.
1260 using llvm::MemoryBuffer;
1261 using llvm::StringRef;
1262 if (MemoryBuffer *F = MemoryBuffer::getFile(ResultsFile.c_str())) {
1263 StringRef Buffer = F->getBuffer();
1264 do {
1265 StringRef::size_type CompletionIdx = Buffer.find("COMPLETION:");
1266 StringRef::size_type OverloadIdx = Buffer.find("OVERLOAD:");
1267 if (CompletionIdx == StringRef::npos && OverloadIdx == StringRef::npos)
1268 break;
1269
1270 if (OverloadIdx < CompletionIdx) {
1271 // Parse an overload result.
1272 Buffer = Buffer.substr(OverloadIdx);
1273
1274 // Skip past the OVERLOAD:
1275 Buffer = Buffer.substr(Buffer.find(':') + 1);
1276
1277 // Find the entire completion string.
1278 StringRef::size_type EOL = Buffer.find_first_of("\n\r");
1279 if (EOL == StringRef::npos)
1280 continue;
1281
1282 StringRef Line = Buffer.substr(0, EOL);
1283 Buffer = Buffer.substr(EOL + 1);
1284 CodeCompletionString *CCStr = CodeCompletionString::Deserialize(Line);
1285 if (!CCStr || CCStr->empty())
1286 continue;
1287
1288 // Vend the code-completion result to the caller.
1289 CXCompletionResult Result;
1290 Result.CursorKind = CXCursor_NotImplemented;
1291 Result.CompletionString = CCStr;
1292 if (completion_iterator)
1293 completion_iterator(&Result, client_data);
1294 delete CCStr;
1295
1296 continue;
1297 }
1298
1299 // Parse a completion result.
1300 Buffer = Buffer.substr(CompletionIdx);
1301
1302 // Skip past the COMPLETION:
1303 Buffer = Buffer.substr(Buffer.find(':') + 1);
1304
1305 // Get the rank
1306 unsigned Rank = 0;
1307 StringRef::size_type AfterRank = Buffer.find(':');
1308 Buffer.substr(0, AfterRank).getAsInteger(10, Rank);
1309 Buffer = Buffer.substr(AfterRank + 1);
1310
1311 // Get the kind of result.
1312 StringRef::size_type AfterKind = Buffer.find(':');
1313 StringRef Kind = Buffer.substr(0, AfterKind);
1314 Buffer = Buffer.substr(AfterKind + 1);
1315
1316 // Skip over any whitespace.
1317 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
1318
1319 // Find the entire completion string.
1320 StringRef::size_type EOL = Buffer.find_first_of("\n\r");
1321 if (EOL == StringRef::npos)
1322 continue;
1323
1324 StringRef Line = Buffer.substr(0, EOL);
1325 Buffer = Buffer.substr(EOL + 1);
1326 CodeCompletionString *CCStr = CodeCompletionString::Deserialize(Line);
1327 if (!CCStr || CCStr->empty())
1328 continue;
1329
1330 // Vend the code-completion result to the caller.
1331 CXCompletionResult Result;
1332 Result.CursorKind = parseResultKind(Kind);
1333 Result.CompletionString = CCStr;
1334 if (completion_iterator)
1335 completion_iterator(&Result, client_data);
1336 delete CCStr;
1337 } while (true);
1338 delete F;
1339 }
1340
1341 ResultsFile.eraseFromDisk();
1342}
1343
Steve Naroff600866c2009-08-27 19:51:58 +00001344} // end extern "C"