blob: 1f456eb24f396128068ca2c7cd8fd05ea4cf40ee [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//
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 {
Daniel Dunbar0d7dd222009-11-30 20:42:43 +000050static enum CXCursorKind TranslateDeclRefExpr(DeclRefExpr *DRE)
Steve Naroff4ade6d62009-09-23 17:52:52 +000051{
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;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +000059 else
Steve Naroff4ade6d62009-09-23 17:52:52 +000060 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;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +000069
Steve Narofffb570422009-09-22 19:25:29 +000070 void Call(enum CXCursorKind CK, Stmt *SRef) {
71 CXCursor C = { CK, CDecl, SRef };
72 Callback(CDecl, C, CData);
73 }
74
75public:
Daniel Dunbar0d7dd222009-11-30 20:42:43 +000076 CRefVisitor(CXDecl C, CXDeclIterator cback, CXClientData D) :
Steve Narofffb570422009-09-22 19:25:29 +000077 CDecl(C), Callback(cback), CData(D) {}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +000078
Steve Narofffb570422009-09-22 19:25:29 +000079 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
Daniel Dunbar0d7dd222009-11-30 20:42:43 +000098
Ted Kremenekfc062212009-10-19 21:44:57 +000099/// IgnoreDiagnosticsClient - A DiagnosticsClient that just ignores emitted
100/// warnings and errors.
101class VISIBILITY_HIDDEN IgnoreDiagnosticsClient : public DiagnosticClient {
102public:
103 virtual ~IgnoreDiagnosticsClient() {}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000104 virtual void HandleDiagnostic(Diagnostic::Level, const DiagnosticInfo &) {}
Ted Kremenekfc062212009-10-19 21:44:57 +0000105};
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;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000112
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;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000117
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;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000122
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;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000126
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:
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000131 TUVisitor(CXTranslationUnit CTU,
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000132 CXTranslationUnitIterator cback, CXClientData D,
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000133 unsigned MaxPCHLevel) :
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000134 TUnit(CTU), Callback(cback), CData(D), MaxPCHLevel(MaxPCHLevel) {}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000135
Steve Naroff89922f82009-08-31 00:59:03 +0000136 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 }
Ted Kremenekef7fdc62009-11-17 07:02:15 +0000144
145 void VisitFunctionDecl(FunctionDecl *ND) {
146 Call(ND->isThisDeclarationADefinition() ? CXCursor_FunctionDefn
147 : CXCursor_FunctionDecl, ND);
148 }
149 void VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
150 Call(CXCursor_ObjCCategoryDecl, ND);
151 }
152 void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *ND) {
153 Call(CXCursor_ObjCCategoryDefn, ND);
154 }
155 void VisitObjCImplementationDecl(ObjCImplementationDecl *ND) {
156 Call(CXCursor_ObjCClassDefn, ND);
157 }
158 void VisitObjCInterfaceDecl(ObjCInterfaceDecl *ND) {
159 Call(CXCursor_ObjCInterfaceDecl, ND);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000160 }
Ted Kremenekef7fdc62009-11-17 07:02:15 +0000161 void VisitObjCProtocolDecl(ObjCProtocolDecl *ND) {
162 Call(CXCursor_ObjCProtocolDecl, ND);
Steve Naroff89922f82009-08-31 00:59:03 +0000163 }
164 void VisitTagDecl(TagDecl *ND) {
Steve Naroffc857ea42009-09-02 13:28:54 +0000165 switch (ND->getTagKind()) {
Daniel Dunbaracca7252009-11-30 20:42:49 +0000166 case TagDecl::TK_struct:
167 Call(CXCursor_StructDecl, ND);
168 break;
169 case TagDecl::TK_class:
170 Call(CXCursor_ClassDecl, ND);
171 break;
172 case TagDecl::TK_union:
173 Call(CXCursor_UnionDecl, ND);
174 break;
175 case TagDecl::TK_enum:
176 Call(CXCursor_EnumDecl, ND);
177 break;
Steve Naroffc857ea42009-09-02 13:28:54 +0000178 }
Steve Naroff89922f82009-08-31 00:59:03 +0000179 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000180 void VisitTypedefDecl(TypedefDecl *ND) {
181 Call(CXCursor_TypedefDecl, ND);
182 }
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000183 void VisitVarDecl(VarDecl *ND) {
184 Call(CXCursor_VarDecl, ND);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000185 }
Steve Naroff89922f82009-08-31 00:59:03 +0000186};
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000187
Steve Naroff89922f82009-08-31 00:59:03 +0000188
Steve Naroffc857ea42009-09-02 13:28:54 +0000189// Declaration visitor.
190class CDeclVisitor : public DeclVisitor<CDeclVisitor> {
191 CXDecl CDecl;
192 CXDeclIterator Callback;
193 CXClientData CData;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000194
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000195 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
196 // to the visitor. Declarations with a PCH level greater than this value will
197 // be suppressed.
198 unsigned MaxPCHLevel;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000199
Steve Naroffc857ea42009-09-02 13:28:54 +0000200 void Call(enum CXCursorKind CK, NamedDecl *ND) {
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000201 // Disable the callback when the context is equal to the visiting decl.
202 if (CDecl == ND && !clang_isReference(CK))
203 return;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000204
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000205 // Filter any declarations that have a PCH level greater than what we allow.
206 if (ND->getPCHLevel() > MaxPCHLevel)
207 return;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000208
Steve Narofffb570422009-09-22 19:25:29 +0000209 CXCursor C = { CK, ND, 0 };
Steve Naroffc857ea42009-09-02 13:28:54 +0000210 Callback(CDecl, C, CData);
211 }
Steve Naroff89922f82009-08-31 00:59:03 +0000212public:
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000213 CDeclVisitor(CXDecl C, CXDeclIterator cback, CXClientData D,
214 unsigned MaxPCHLevel) :
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000215 CDecl(C), Callback(cback), CData(D), MaxPCHLevel(MaxPCHLevel) {}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000216
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000217 void VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
218 // Issue callbacks for the containing class.
219 Call(CXCursor_ObjCClassRef, ND);
220 // FIXME: Issue callbacks for protocol refs.
221 VisitDeclContext(dyn_cast<DeclContext>(ND));
222 }
Steve Naroffc857ea42009-09-02 13:28:54 +0000223 void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000224 // Issue callbacks for super class.
Steve Narofff334b4e2009-09-02 18:26:48 +0000225 if (D->getSuperClass())
226 Call(CXCursor_ObjCSuperClassRef, D);
227
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000228 for (ObjCProtocolDecl::protocol_iterator I = D->protocol_begin(),
Daniel Dunbaracca7252009-11-30 20:42:49 +0000229 E = D->protocol_end(); I != E; ++I)
Steve Naroff9efa7672009-09-04 15:44:05 +0000230 Call(CXCursor_ObjCProtocolRef, *I);
Steve Naroffc857ea42009-09-02 13:28:54 +0000231 VisitDeclContext(dyn_cast<DeclContext>(D));
232 }
Steve Naroff9efa7672009-09-04 15:44:05 +0000233 void VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000234 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
Daniel Dunbaracca7252009-11-30 20:42:49 +0000235 E = PID->protocol_end(); I != E; ++I)
Steve Naroff9efa7672009-09-04 15:44:05 +0000236 Call(CXCursor_ObjCProtocolRef, *I);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000237
Steve Naroff9efa7672009-09-04 15:44:05 +0000238 VisitDeclContext(dyn_cast<DeclContext>(PID));
239 }
Steve Naroffc857ea42009-09-02 13:28:54 +0000240 void VisitTagDecl(TagDecl *D) {
241 VisitDeclContext(dyn_cast<DeclContext>(D));
242 }
243 void VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
244 VisitDeclContext(dyn_cast<DeclContext>(D));
245 }
246 void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
247 VisitDeclContext(dyn_cast<DeclContext>(D));
248 }
Steve Naroff89922f82009-08-31 00:59:03 +0000249 void VisitDeclContext(DeclContext *DC) {
250 for (DeclContext::decl_iterator
251 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I)
252 Visit(*I);
253 }
254 void VisitEnumConstantDecl(EnumConstantDecl *ND) {
Steve Naroffc857ea42009-09-02 13:28:54 +0000255 Call(CXCursor_EnumConstantDecl, ND);
Steve Naroff89922f82009-08-31 00:59:03 +0000256 }
257 void VisitFieldDecl(FieldDecl *ND) {
Steve Naroffc857ea42009-09-02 13:28:54 +0000258 Call(CXCursor_FieldDecl, ND);
259 }
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000260 void VisitVarDecl(VarDecl *ND) {
261 Call(CXCursor_VarDecl, ND);
262 }
263 void VisitParmVarDecl(ParmVarDecl *ND) {
264 Call(CXCursor_ParmDecl, ND);
265 }
Steve Naroffc857ea42009-09-02 13:28:54 +0000266 void VisitObjCPropertyDecl(ObjCPropertyDecl *ND) {
267 Call(CXCursor_ObjCPropertyDecl, ND);
Steve Naroff89922f82009-08-31 00:59:03 +0000268 }
269 void VisitObjCIvarDecl(ObjCIvarDecl *ND) {
Steve Naroffc857ea42009-09-02 13:28:54 +0000270 Call(CXCursor_ObjCIvarDecl, ND);
271 }
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000272 void VisitFunctionDecl(FunctionDecl *ND) {
273 if (ND->isThisDeclarationADefinition()) {
274 VisitDeclContext(dyn_cast<DeclContext>(ND));
Steve Naroff4ade6d62009-09-23 17:52:52 +0000275#if 0
276 // Not currently needed.
277 CompoundStmt *Body = dyn_cast<CompoundStmt>(ND->getBody());
Steve Narofffb570422009-09-22 19:25:29 +0000278 CRefVisitor RVisit(CDecl, Callback, CData);
Steve Naroff4ade6d62009-09-23 17:52:52 +0000279 RVisit.Visit(Body);
280#endif
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000281 }
282 }
Steve Naroffc857ea42009-09-02 13:28:54 +0000283 void VisitObjCMethodDecl(ObjCMethodDecl *ND) {
284 if (ND->getBody()) {
285 Call(ND->isInstanceMethod() ? CXCursor_ObjCInstanceMethodDefn
286 : CXCursor_ObjCClassMethodDefn, ND);
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000287 VisitDeclContext(dyn_cast<DeclContext>(ND));
Steve Naroffc857ea42009-09-02 13:28:54 +0000288 } else
289 Call(ND->isInstanceMethod() ? CXCursor_ObjCInstanceMethodDecl
290 : CXCursor_ObjCClassMethodDecl, ND);
Steve Naroff89922f82009-08-31 00:59:03 +0000291 }
292};
293
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000294class CIndexer : public Indexer {
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000295public:
296 explicit CIndexer(Program *prog) : Indexer(*prog),
297 OnlyLocalDecls(false),
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000298 DisplayDiagnostics(false) {}
Ted Kremenekdff76892009-10-17 06:21:47 +0000299
300 virtual ~CIndexer() { delete &getProgram(); }
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000301
302 /// \brief Whether we only want to see "local" declarations (that did not
303 /// come from a previous precompiled header). If false, we want to see all
304 /// declarations.
305 bool getOnlyLocalDecls() const { return OnlyLocalDecls; }
306 void setOnlyLocalDecls(bool Local = true) { OnlyLocalDecls = Local; }
Benjamin Kramer96707622009-10-18 11:10:55 +0000307
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000308 void setDisplayDiagnostics(bool Display = true) {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000309 DisplayDiagnostics = Display;
310 }
311 bool getDisplayDiagnostics() const { return DisplayDiagnostics; }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000312
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000313 /// \brief Get the path of the clang binary.
Benjamin Kramerc5a9e952009-10-19 10:20:24 +0000314 const llvm::sys::Path& getClangPath();
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000315private:
316 bool OnlyLocalDecls;
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000317 bool DisplayDiagnostics;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000318
Benjamin Kramerc5a9e952009-10-19 10:20:24 +0000319 llvm::sys::Path ClangPath;
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000320};
Steve Naroff89922f82009-08-31 00:59:03 +0000321
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000322const llvm::sys::Path& CIndexer::getClangPath() {
323 // Did we already compute the path?
324 if (!ClangPath.empty())
325 return ClangPath;
326
Steve Naroff5b7d8e22009-10-15 20:04:39 +0000327 // Find the location where this library lives (libCIndex.dylib).
Benjamin Kramer20d75812009-10-18 16:13:48 +0000328#ifdef LLVM_ON_WIN32
329 MEMORY_BASIC_INFORMATION mbi;
330 char path[MAX_PATH];
Benjamin Krameredcd8282009-10-18 16:20:58 +0000331 VirtualQuery((void *)(uintptr_t)clang_createTranslationUnit, &mbi,
Benjamin Kramer20d75812009-10-18 16:13:48 +0000332 sizeof(mbi));
333 GetModuleFileNameA((HINSTANCE)mbi.AllocationBase, path, MAX_PATH);
334
335 llvm::sys::Path CIndexPath(path);
John Thompson6a6742a2009-11-11 23:11:14 +0000336
337 CIndexPath.eraseComponent();
338 CIndexPath.appendComponent("clang");
339 CIndexPath.appendSuffix("exe");
340 CIndexPath.makeAbsolute();
Benjamin Kramer20d75812009-10-18 16:13:48 +0000341#else
Steve Naroff5b7d8e22009-10-15 20:04:39 +0000342 // This silly cast below avoids a C++ warning.
343 Dl_info info;
344 if (dladdr((void *)(uintptr_t)clang_createTranslationUnit, &info) == 0)
345 assert(0 && "Call to dladdr() failed");
346
347 llvm::sys::Path CIndexPath(info.dli_fname);
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000348
Steve Naroff5b7d8e22009-10-15 20:04:39 +0000349 // We now have the CIndex directory, locate clang relative to it.
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000350 CIndexPath.eraseComponent();
351 CIndexPath.eraseComponent();
352 CIndexPath.appendComponent("bin");
353 CIndexPath.appendComponent("clang");
John Thompson6a6742a2009-11-11 23:11:14 +0000354#endif
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000355
356 // Cache our result.
357 ClangPath = CIndexPath;
358 return ClangPath;
359}
360
361}
362
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000363static SourceLocation getLocationFromCursor(CXCursor C,
Daniel Dunbarc6190332009-11-08 04:13:53 +0000364 SourceManager &SourceMgr,
365 NamedDecl *ND) {
366 if (clang_isReference(C.kind)) {
367 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +0000368 case CXCursor_ObjCClassRef: {
369 if (isa<ObjCInterfaceDecl>(ND)) {
370 // FIXME: This is a hack (storing the parent decl in the stmt slot).
371 NamedDecl *parentDecl = static_cast<NamedDecl *>(C.stmt);
372 return parentDecl->getLocation();
Daniel Dunbarc6190332009-11-08 04:13:53 +0000373 }
Daniel Dunbaracca7252009-11-30 20:42:49 +0000374 ObjCCategoryDecl *OID = dyn_cast<ObjCCategoryDecl>(ND);
375 assert(OID && "clang_getCursorLine(): Missing category decl");
376 return OID->getClassInterface()->getLocation();
377 }
378 case CXCursor_ObjCSuperClassRef: {
379 ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ND);
380 assert(OID && "clang_getCursorLine(): Missing interface decl");
381 return OID->getSuperClassLoc();
382 }
383 case CXCursor_ObjCProtocolRef: {
384 ObjCProtocolDecl *OID = dyn_cast<ObjCProtocolDecl>(ND);
385 assert(OID && "clang_getCursorLine(): Missing protocol decl");
386 return OID->getLocation();
387 }
388 case CXCursor_ObjCSelectorRef: {
389 ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(
390 static_cast<Stmt *>(C.stmt));
391 assert(OME && "clang_getCursorLine(): Missing message expr");
392 return OME->getLeftLoc(); /* FIXME: should be a range */
393 }
394 case CXCursor_VarRef:
395 case CXCursor_FunctionRef:
396 case CXCursor_EnumConstantRef: {
397 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(
398 static_cast<Stmt *>(C.stmt));
399 assert(DRE && "clang_getCursorLine(): Missing decl ref expr");
400 return DRE->getLocation();
401 }
402 default:
403 return SourceLocation();
Daniel Dunbarc6190332009-11-08 04:13:53 +0000404 }
405 } else { // We have a declaration or a definition.
406 SourceLocation SLoc;
407 switch (ND->getKind()) {
Daniel Dunbaracca7252009-11-30 20:42:49 +0000408 case Decl::ObjCInterface: {
409 SLoc = dyn_cast<ObjCInterfaceDecl>(ND)->getClassLoc();
410 break;
411 }
412 case Decl::ObjCProtocol: {
413 SLoc = ND->getLocation(); /* FIXME: need to get the name location. */
414 break;
415 }
416 default: {
417 SLoc = ND->getLocation();
418 break;
419 }
Daniel Dunbarc6190332009-11-08 04:13:53 +0000420 }
421 if (SLoc.isInvalid())
422 return SourceLocation();
423 return SourceMgr.getSpellingLoc(SLoc); // handles macro instantiations.
424 }
425}
426
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000427static CXString createCXString(const char *String, bool DupString = false) {
428 CXString Str;
429 if (DupString) {
430 Str.Spelling = strdup(String);
431 Str.MustFreeString = 1;
432 } else {
433 Str.Spelling = String;
434 Str.MustFreeString = 0;
435 }
436 return Str;
437}
438
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000439extern "C" {
440
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000441CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000442 int displayDiagnostics) {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000443 CIndexer *CIdxr = new CIndexer(new Program());
444 if (excludeDeclarationsFromPCH)
445 CIdxr->setOnlyLocalDecls();
446 if (displayDiagnostics)
447 CIdxr->setDisplayDiagnostics();
448 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +0000449}
450
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000451void clang_disposeIndex(CXIndex CIdx) {
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000452 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000453 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000454}
455
Steve Naroff50398192009-08-28 15:28:48 +0000456// FIXME: need to pass back error info.
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000457CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
458 const char *ast_filename) {
Steve Naroff50398192009-08-28 15:28:48 +0000459 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000460 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Steve Naroff50398192009-08-28 15:28:48 +0000461 std::string astName(ast_filename);
462 std::string ErrMsg;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000463
Ted Kremenek379afec2009-10-22 03:24:01 +0000464 CXTranslationUnit TU =
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000465 ASTUnit::LoadFromPCHFile(astName, &ErrMsg,
Daniel Dunbaracca7252009-11-30 20:42:49 +0000466 CXXIdx->getDisplayDiagnostics() ?
467 NULL : new IgnoreDiagnosticsClient(),
468 CXXIdx->getOnlyLocalDecls(),
469 /* UseBumpAllocator = */ true);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000470
Ted Kremenek0854d702009-11-10 19:18:52 +0000471 if (CXXIdx->getDisplayDiagnostics() && !ErrMsg.empty())
Ted Kremenek779e5f42009-10-26 22:08:39 +0000472 llvm::errs() << "clang_createTranslationUnit: " << ErrMsg << '\n';
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000473
Ted Kremenek379afec2009-10-22 03:24:01 +0000474 return TU;
Steve Naroff600866c2009-08-27 19:51:58 +0000475}
476
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000477CXTranslationUnit
478clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
479 const char *source_filename,
480 int num_command_line_args,
481 const char **command_line_args) {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000482 assert(CIdx && "Passed null CXIndex");
483 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
484
Ted Kremenek139ba862009-10-22 00:03:57 +0000485 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000486 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000487
Ted Kremenek139ba862009-10-22 00:03:57 +0000488 // First add the complete path to the 'clang' executable.
489 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000490 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000491
Ted Kremenek139ba862009-10-22 00:03:57 +0000492 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000493 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000494
Ted Kremenek139ba862009-10-22 00:03:57 +0000495 // The 'source_filename' argument is optional. If the caller does not
496 // specify it then it is assumed that the source file is specified
497 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000498 if (source_filename)
499 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +0000500
Steve Naroff37b5ac22009-10-15 20:50:09 +0000501 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +0000502 argv.push_back("-o");
Steve Naroff37b5ac22009-10-15 20:50:09 +0000503 char astTmpFile[L_tmpnam];
Ted Kremenek74cd0692009-10-15 23:21:22 +0000504 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +0000505
506 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
507 for (int i = 0; i < num_command_line_args; ++i)
508 if (const char *arg = command_line_args[i]) {
509 if (strcmp(arg, "-o") == 0) {
510 ++i; // Also skip the matching argument.
511 continue;
512 }
513 if (strcmp(arg, "-emit-ast") == 0 ||
514 strcmp(arg, "-c") == 0 ||
515 strcmp(arg, "-fsyntax-only") == 0) {
516 continue;
517 }
518
519 // Keep the argument.
520 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000521 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000522
Ted Kremenek139ba862009-10-22 00:03:57 +0000523 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000524 argv.push_back(NULL);
525
Ted Kremenekfeb15e32009-10-26 22:14:08 +0000526 // Invoke 'clang'.
527 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
528 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +0000529 std::string ErrMsg;
Ted Kremenekc46e4632009-10-19 22:27:32 +0000530 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DevNull, NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +0000531 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
532 /* redirects */ !CXXIdx->getDisplayDiagnostics() ? &Redirects[0] : NULL,
533 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000534
Ted Kremenek0854d702009-11-10 19:18:52 +0000535 if (CXXIdx->getDisplayDiagnostics() && !ErrMsg.empty()) {
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000536 llvm::errs() << "clang_createTranslationUnitFromSourceFile: " << ErrMsg
Daniel Dunbaracca7252009-11-30 20:42:49 +0000537 << '\n' << "Arguments: \n";
Ted Kremenek379afec2009-10-22 03:24:01 +0000538 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Ted Kremenek779e5f42009-10-26 22:08:39 +0000539 I!=E; ++I) {
540 if (*I)
541 llvm::errs() << ' ' << *I << '\n';
542 }
543 llvm::errs() << '\n';
Ted Kremenek379afec2009-10-22 03:24:01 +0000544 }
Benjamin Kramer0829a832009-10-18 11:19:36 +0000545
Steve Naroff37b5ac22009-10-15 20:50:09 +0000546 // Finally, we create the translation unit from the ast file.
Steve Naroffe19944c2009-10-15 22:23:48 +0000547 ASTUnit *ATU = static_cast<ASTUnit *>(
Daniel Dunbaracca7252009-11-30 20:42:49 +0000548 clang_createTranslationUnit(CIdx, astTmpFile));
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000549 if (ATU)
550 ATU->unlinkTemporaryFile();
Steve Naroffe19944c2009-10-15 22:23:48 +0000551 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +0000552}
553
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000554void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000555 assert(CTUnit && "Passed null CXTranslationUnit");
556 delete static_cast<ASTUnit *>(CTUnit);
557}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000558
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000559CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000560 assert(CTUnit && "Passed null CXTranslationUnit");
Steve Naroff77accc12009-09-03 18:19:54 +0000561 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000562 return createCXString(CXXUnit->getOriginalSourceFileName().c_str(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000563}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +0000564
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000565void clang_loadTranslationUnit(CXTranslationUnit CTUnit,
Steve Naroffc857ea42009-09-02 13:28:54 +0000566 CXTranslationUnitIterator callback,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000567 CXClientData CData) {
Steve Naroff50398192009-08-28 15:28:48 +0000568 assert(CTUnit && "Passed null CXTranslationUnit");
569 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
570 ASTContext &Ctx = CXXUnit->getASTContext();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000571
572 TUVisitor DVisit(CTUnit, callback, CData,
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000573 CXXUnit->getOnlyLocalDecls()? 1 : Decl::MaxPCHLevel);
Steve Naroff50398192009-08-28 15:28:48 +0000574 DVisit.Visit(Ctx.getTranslationUnitDecl());
Steve Naroff600866c2009-08-27 19:51:58 +0000575}
576
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000577void clang_loadDeclaration(CXDecl Dcl,
578 CXDeclIterator callback,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000579 CXClientData CData) {
Steve Naroffc857ea42009-09-02 13:28:54 +0000580 assert(Dcl && "Passed null CXDecl");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000581
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000582 CDeclVisitor DVisit(Dcl, callback, CData,
583 static_cast<Decl *>(Dcl)->getPCHLevel());
Steve Naroffc857ea42009-09-02 13:28:54 +0000584 DVisit.Visit(static_cast<Decl *>(Dcl));
Steve Naroff600866c2009-08-27 19:51:58 +0000585}
586
Steve Naroff7e8f8182009-08-28 12:07:44 +0000587// Some notes on CXEntity:
588//
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000589// - Since the 'ordinary' namespace includes functions, data, typedefs,
590// ObjC interfaces, thecurrent algorithm is a bit naive (resulting in one
Steve Naroff7e8f8182009-08-28 12:07:44 +0000591// entity for 2 different types). For example:
592//
593// module1.m: @interface Foo @end Foo *x;
594// module2.m: void Foo(int);
595//
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000596// - Since the unique name spans translation units, static data/functions
Steve Naroff7e8f8182009-08-28 12:07:44 +0000597// within a CXTranslationUnit are *not* currently represented by entities.
598// As a result, there will be no entity for the following:
599//
600// module.m: static void Foo() { }
601//
602
603
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000604const char *clang_getDeclarationName(CXEntity) {
Steve Naroff600866c2009-08-27 19:51:58 +0000605 return "";
606}
607
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000608const char *clang_getURI(CXEntity) {
609 return "";
610}
611
612CXEntity clang_getEntity(const char *URI) {
Steve Naroff600866c2009-08-27 19:51:58 +0000613 return 0;
614}
615
616//
617// CXDecl Operations.
618//
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000619
620CXEntity clang_getEntityFromDecl(CXDecl) {
Steve Naroff600866c2009-08-27 19:51:58 +0000621 return 0;
622}
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000623
624CXString clang_getDeclSpelling(CXDecl AnonDecl) {
Steve Naroff89922f82009-08-31 00:59:03 +0000625 assert(AnonDecl && "Passed null CXDecl");
626 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
Steve Naroffef0cef62009-11-09 17:45:52 +0000627
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000628 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
629 return createCXString(OMD->getSelector().getAsString().c_str(), true);
630
631 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Steve Naroff0d69b8c2009-10-29 21:11:04 +0000632 // No, this isn't the same as the code below. getIdentifier() is non-virtual
633 // and returns different names. NamedDecl returns the class name and
634 // ObjCCategoryImplDecl returns the category name.
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000635 return createCXString(CIMP->getIdentifier()->getNameStart());
636
637 if (ND->getIdentifier())
638 return createCXString(ND->getIdentifier()->getNameStart());
639
640 return createCXString("");
Steve Naroff600866c2009-08-27 19:51:58 +0000641}
Steve Narofff334b4e2009-09-02 18:26:48 +0000642
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000643unsigned clang_getDeclLine(CXDecl AnonDecl) {
Steve Naroff699a07d2009-09-25 21:32:34 +0000644 assert(AnonDecl && "Passed null CXDecl");
645 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
646 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
647 return SourceMgr.getSpellingLineNumber(ND->getLocation());
648}
649
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000650unsigned clang_getDeclColumn(CXDecl AnonDecl) {
Steve Naroff699a07d2009-09-25 21:32:34 +0000651 assert(AnonDecl && "Passed null CXDecl");
652 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
653 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Steve Naroff74165242009-09-25 22:15:54 +0000654 return SourceMgr.getSpellingColumnNumber(ND->getLocation());
Steve Naroff699a07d2009-09-25 21:32:34 +0000655}
656
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000657const char *clang_getDeclSource(CXDecl AnonDecl) {
Steve Naroffee9405e2009-09-25 21:45:39 +0000658 assert(AnonDecl && "Passed null CXDecl");
Steve Naroff88145032009-10-27 14:35:18 +0000659 FileEntry *FEnt = static_cast<FileEntry *>(clang_getDeclSourceFile(AnonDecl));
660 assert (FEnt && "Cannot find FileEntry for Decl");
661 return clang_getFileName(FEnt);
662}
663
664static const FileEntry *getFileEntryFromSourceLocation(SourceManager &SMgr,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000665 SourceLocation SLoc) {
Steve Naroff88145032009-10-27 14:35:18 +0000666 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
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000674CXFile clang_getDeclSourceFile(CXDecl AnonDecl) {
Steve Naroff88145032009-10-27 14:35:18 +0000675 assert(AnonDecl && "Passed null CXDecl");
Steve Naroffee9405e2009-09-25 21:45:39 +0000676 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
677 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Steve Naroff88145032009-10-27 14:35:18 +0000678 return (void *)getFileEntryFromSourceLocation(SourceMgr, ND->getLocation());
679}
680
681const char *clang_getFileName(CXFile SFile) {
682 assert(SFile && "Passed null CXFile");
683 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
684 return FEnt->getName();
685}
686
687time_t clang_getFileTime(CXFile SFile) {
688 assert(SFile && "Passed null CXFile");
689 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
690 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +0000691}
692
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000693CXString clang_getCursorSpelling(CXCursor C) {
Steve Narofff334b4e2009-09-02 18:26:48 +0000694 assert(C.decl && "CXCursor has null decl");
695 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
Steve Naroffef0cef62009-11-09 17:45:52 +0000696
Steve Narofff334b4e2009-09-02 18:26:48 +0000697 if (clang_isReference(C.kind)) {
698 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +0000699 case CXCursor_ObjCSuperClassRef: {
700 ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ND);
701 assert(OID && "clang_getCursorLine(): Missing interface decl");
702 return createCXString(OID->getSuperClass()->getIdentifier()
703 ->getNameStart());
704 }
705 case CXCursor_ObjCClassRef: {
706 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ND))
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000707 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +0000708
709 ObjCCategoryDecl *OCD = dyn_cast<ObjCCategoryDecl>(ND);
710 assert(OCD && "clang_getCursorLine(): Missing category decl");
711 return createCXString(OCD->getClassInterface()->getIdentifier()
712 ->getNameStart());
713 }
714 case CXCursor_ObjCProtocolRef: {
715 ObjCProtocolDecl *OID = dyn_cast<ObjCProtocolDecl>(ND);
716 assert(OID && "clang_getCursorLine(): Missing protocol decl");
717 return createCXString(OID->getIdentifier()->getNameStart());
718 }
719 case CXCursor_ObjCSelectorRef: {
720 ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(
721 static_cast<Stmt *>(C.stmt));
722 assert(OME && "clang_getCursorLine(): Missing message expr");
723 return createCXString(OME->getSelector().getAsString().c_str(), true);
724 }
725 case CXCursor_VarRef:
726 case CXCursor_FunctionRef:
727 case CXCursor_EnumConstantRef: {
728 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(
729 static_cast<Stmt *>(C.stmt));
730 assert(DRE && "clang_getCursorLine(): Missing decl ref expr");
731 return createCXString(DRE->getDecl()->getIdentifier()->getNameStart());
732 }
733 default:
734 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +0000735 }
736 }
737 return clang_getDeclSpelling(C.decl);
738}
739
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000740const char *clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +0000741 switch (Kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +0000742 case CXCursor_FunctionDecl: return "FunctionDecl";
743 case CXCursor_TypedefDecl: return "TypedefDecl";
744 case CXCursor_EnumDecl: return "EnumDecl";
745 case CXCursor_EnumConstantDecl: return "EnumConstantDecl";
746 case CXCursor_StructDecl: return "StructDecl";
747 case CXCursor_UnionDecl: return "UnionDecl";
748 case CXCursor_ClassDecl: return "ClassDecl";
749 case CXCursor_FieldDecl: return "FieldDecl";
750 case CXCursor_VarDecl: return "VarDecl";
751 case CXCursor_ParmDecl: return "ParmDecl";
752 case CXCursor_ObjCInterfaceDecl: return "ObjCInterfaceDecl";
753 case CXCursor_ObjCCategoryDecl: return "ObjCCategoryDecl";
754 case CXCursor_ObjCProtocolDecl: return "ObjCProtocolDecl";
755 case CXCursor_ObjCPropertyDecl: return "ObjCPropertyDecl";
756 case CXCursor_ObjCIvarDecl: return "ObjCIvarDecl";
757 case CXCursor_ObjCInstanceMethodDecl: return "ObjCInstanceMethodDecl";
758 case CXCursor_ObjCClassMethodDecl: return "ObjCClassMethodDecl";
759 case CXCursor_FunctionDefn: return "FunctionDefn";
760 case CXCursor_ObjCInstanceMethodDefn: return "ObjCInstanceMethodDefn";
761 case CXCursor_ObjCClassMethodDefn: return "ObjCClassMethodDefn";
762 case CXCursor_ObjCClassDefn: return "ObjCClassDefn";
763 case CXCursor_ObjCCategoryDefn: return "ObjCCategoryDefn";
764 case CXCursor_ObjCSuperClassRef: return "ObjCSuperClassRef";
765 case CXCursor_ObjCProtocolRef: return "ObjCProtocolRef";
766 case CXCursor_ObjCClassRef: return "ObjCClassRef";
767 case CXCursor_ObjCSelectorRef: return "ObjCSelectorRef";
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000768
Daniel Dunbaracca7252009-11-30 20:42:49 +0000769 case CXCursor_VarRef: return "VarRef";
770 case CXCursor_FunctionRef: return "FunctionRef";
771 case CXCursor_EnumConstantRef: return "EnumConstantRef";
772 case CXCursor_MemberRef: return "MemberRef";
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000773
Daniel Dunbaracca7252009-11-30 20:42:49 +0000774 case CXCursor_InvalidFile: return "InvalidFile";
775 case CXCursor_NoDeclFound: return "NoDeclFound";
776 case CXCursor_NotImplemented: return "NotImplemented";
777 default: return "<not implemented>";
Steve Naroff89922f82009-08-31 00:59:03 +0000778 }
Steve Naroff600866c2009-08-27 19:51:58 +0000779}
Steve Naroff89922f82009-08-31 00:59:03 +0000780
Steve Naroff9efa7672009-09-04 15:44:05 +0000781static enum CXCursorKind TranslateKind(Decl *D) {
782 switch (D->getKind()) {
Daniel Dunbaracca7252009-11-30 20:42:49 +0000783 case Decl::Function: return CXCursor_FunctionDecl;
784 case Decl::Typedef: return CXCursor_TypedefDecl;
785 case Decl::Enum: return CXCursor_EnumDecl;
786 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
787 case Decl::Record: return CXCursor_StructDecl; // FIXME: union/class
788 case Decl::Field: return CXCursor_FieldDecl;
789 case Decl::Var: return CXCursor_VarDecl;
790 case Decl::ParmVar: return CXCursor_ParmDecl;
791 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
792 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
793 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
794 case Decl::ObjCMethod: {
795 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D);
796 if (MD->isInstanceMethod())
797 return CXCursor_ObjCInstanceMethodDecl;
798 return CXCursor_ObjCClassMethodDecl;
799 }
800 default: break;
Steve Naroff9efa7672009-09-04 15:44:05 +0000801 }
Steve Naroff77128dd2009-09-15 20:25:34 +0000802 return CXCursor_NotImplemented;
Steve Naroff9efa7672009-09-04 15:44:05 +0000803}
Steve Naroff600866c2009-08-27 19:51:58 +0000804//
805// CXCursor Operations.
806//
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000807
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000808CXCursor clang_getCursor(CXTranslationUnit CTUnit, const char *source_name,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000809 unsigned line, unsigned column) {
Steve Naroff9efa7672009-09-04 15:44:05 +0000810 assert(CTUnit && "Passed null CXTranslationUnit");
811 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000812
Steve Naroff9efa7672009-09-04 15:44:05 +0000813 FileManager &FMgr = CXXUnit->getFileManager();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000814 const FileEntry *File = FMgr.getFile(source_name,
815 source_name+strlen(source_name));
Steve Naroff77128dd2009-09-15 20:25:34 +0000816 if (!File) {
Steve Narofffb570422009-09-22 19:25:29 +0000817 CXCursor C = { CXCursor_InvalidFile, 0, 0 };
Steve Naroff77128dd2009-09-15 20:25:34 +0000818 return C;
819 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000820 SourceLocation SLoc =
Steve Naroff9efa7672009-09-04 15:44:05 +0000821 CXXUnit->getSourceManager().getLocation(File, line, column);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000822
Steve Narofff96b5242009-10-28 20:44:47 +0000823 ASTLocation LastLoc = CXXUnit->getLastASTLocation();
824
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000825 ASTLocation ALoc = ResolveLocationInAST(CXXUnit->getASTContext(), SLoc,
Steve Narofff96b5242009-10-28 20:44:47 +0000826 &LastLoc);
827 if (ALoc.isValid())
828 CXXUnit->setLastASTLocation(ALoc);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000829
Argyrios Kyrtzidisf4526e32009-09-29 19:44:27 +0000830 Decl *Dcl = ALoc.getParentDecl();
Argyrios Kyrtzidis05a76512009-09-29 19:45:58 +0000831 if (ALoc.isNamedRef())
832 Dcl = ALoc.AsNamedRef().ND;
Argyrios Kyrtzidisf4526e32009-09-29 19:44:27 +0000833 Stmt *Stm = ALoc.dyn_AsStmt();
Steve Naroff4ade6d62009-09-23 17:52:52 +0000834 if (Dcl) {
835 if (Stm) {
836 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Stm)) {
837 CXCursor C = { TranslateDeclRefExpr(DRE), Dcl, Stm };
838 return C;
839 } else if (ObjCMessageExpr *MExp = dyn_cast<ObjCMessageExpr>(Stm)) {
840 CXCursor C = { CXCursor_ObjCSelectorRef, Dcl, MExp };
841 return C;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000842 }
Steve Naroff4ade6d62009-09-23 17:52:52 +0000843 // Fall through...treat as a decl, not a ref.
844 }
Steve Naroff85e2db72009-10-01 00:31:07 +0000845 if (ALoc.isNamedRef()) {
846 if (isa<ObjCInterfaceDecl>(Dcl)) {
847 CXCursor C = { CXCursor_ObjCClassRef, Dcl, ALoc.getParentDecl() };
848 return C;
849 }
850 if (isa<ObjCProtocolDecl>(Dcl)) {
851 CXCursor C = { CXCursor_ObjCProtocolRef, Dcl, ALoc.getParentDecl() };
852 return C;
853 }
854 }
Daniel Dunbaracca7252009-11-30 20:42:49 +0000855 CXCursor C = { TranslateKind(Dcl), Dcl, 0 };
Steve Naroff77128dd2009-09-15 20:25:34 +0000856 return C;
857 }
Steve Narofffb570422009-09-22 19:25:29 +0000858 CXCursor C = { CXCursor_NoDeclFound, 0, 0 };
Steve Naroff9efa7672009-09-04 15:44:05 +0000859 return C;
Steve Naroff600866c2009-08-27 19:51:58 +0000860}
861
Ted Kremenek73885552009-11-17 19:28:59 +0000862CXCursor clang_getNullCursor(void) {
863 CXCursor C;
864 C.kind = CXCursor_InvalidFile;
865 C.decl = NULL;
866 C.stmt = NULL;
867 return C;
868}
869
870unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
871 return X.kind == Y.kind && X.decl == Y.decl && X.stmt == Y.stmt;
872}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000873
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000874CXCursor clang_getCursorFromDecl(CXDecl AnonDecl) {
Steve Naroff77128dd2009-09-15 20:25:34 +0000875 assert(AnonDecl && "Passed null CXDecl");
876 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000877
Steve Narofffb570422009-09-22 19:25:29 +0000878 CXCursor C = { TranslateKind(ND), ND, 0 };
Steve Naroff77128dd2009-09-15 20:25:34 +0000879 return C;
880}
881
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000882unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +0000883 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
884}
885
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000886unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +0000887 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
888}
Steve Naroff2d4d6292009-08-31 14:26:51 +0000889
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000890unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +0000891 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
892}
893
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000894unsigned clang_isDefinition(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +0000895 return K >= CXCursor_FirstDefn && K <= CXCursor_LastDefn;
896}
897
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000898CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +0000899 return C.kind;
900}
901
Steve Naroff699a07d2009-09-25 21:32:34 +0000902static Decl *getDeclFromExpr(Stmt *E) {
903 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
904 return RefExpr->getDecl();
905 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
906 return ME->getMemberDecl();
907 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
908 return RE->getDecl();
909
910 if (CallExpr *CE = dyn_cast<CallExpr>(E))
911 return getDeclFromExpr(CE->getCallee());
912 if (CastExpr *CE = dyn_cast<CastExpr>(E))
913 return getDeclFromExpr(CE->getSubExpr());
914 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
915 return OME->getMethodDecl();
916
917 return 0;
918}
919
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000920CXDecl clang_getCursorDecl(CXCursor C) {
Steve Naroff699a07d2009-09-25 21:32:34 +0000921 if (clang_isDeclaration(C.kind))
922 return C.decl;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000923
Steve Naroff699a07d2009-09-25 21:32:34 +0000924 if (clang_isReference(C.kind)) {
Steve Naroff85e2db72009-10-01 00:31:07 +0000925 if (C.stmt) {
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000926 if (C.kind == CXCursor_ObjCClassRef ||
Steve Narofff9adf8f2009-10-05 17:58:19 +0000927 C.kind == CXCursor_ObjCProtocolRef)
Steve Naroff85e2db72009-10-01 00:31:07 +0000928 return static_cast<Stmt *>(C.stmt);
929 else
930 return getDeclFromExpr(static_cast<Stmt *>(C.stmt));
931 } else
Steve Naroff699a07d2009-09-25 21:32:34 +0000932 return C.decl;
933 }
934 return 0;
Steve Naroff9efa7672009-09-04 15:44:05 +0000935}
936
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000937unsigned clang_getCursorLine(CXCursor C) {
Steve Naroff2d4d6292009-08-31 14:26:51 +0000938 assert(C.decl && "CXCursor has null decl");
939 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
Steve Naroff2d4d6292009-08-31 14:26:51 +0000940 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000941
Steve Narofff334b4e2009-09-02 18:26:48 +0000942 SourceLocation SLoc = getLocationFromCursor(C, SourceMgr, ND);
Steve Naroff2d4d6292009-08-31 14:26:51 +0000943 return SourceMgr.getSpellingLineNumber(SLoc);
Steve Naroff600866c2009-08-27 19:51:58 +0000944}
Steve Narofff334b4e2009-09-02 18:26:48 +0000945
Steve Naroffef0cef62009-11-09 17:45:52 +0000946const char *clang_getCString(CXString string) {
947 return string.Spelling;
948}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000949
Steve Naroffef0cef62009-11-09 17:45:52 +0000950void clang_disposeString(CXString string) {
Benjamin Kramer858e5de2009-11-09 18:24:53 +0000951 if (string.MustFreeString)
952 free((void*)string.Spelling);
Steve Naroffef0cef62009-11-09 17:45:52 +0000953}
954
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000955unsigned clang_getCursorColumn(CXCursor C) {
Steve Naroff2d4d6292009-08-31 14:26:51 +0000956 assert(C.decl && "CXCursor has null decl");
957 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
Steve Naroff2d4d6292009-08-31 14:26:51 +0000958 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000959
Steve Narofff334b4e2009-09-02 18:26:48 +0000960 SourceLocation SLoc = getLocationFromCursor(C, SourceMgr, ND);
Steve Naroff2d4d6292009-08-31 14:26:51 +0000961 return SourceMgr.getSpellingColumnNumber(SLoc);
Steve Naroff600866c2009-08-27 19:51:58 +0000962}
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000963
964const char *clang_getCursorSource(CXCursor C) {
Steve Naroff2d4d6292009-08-31 14:26:51 +0000965 assert(C.decl && "CXCursor has null decl");
966 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
Steve Naroff2d4d6292009-08-31 14:26:51 +0000967 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000968
Steve Narofff334b4e2009-09-02 18:26:48 +0000969 SourceLocation SLoc = getLocationFromCursor(C, SourceMgr, ND);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000970
Ted Kremenek9298cfc2009-11-17 05:31:58 +0000971 if (SLoc.isFileID()) {
972 const char *bufferName = SourceMgr.getBufferName(SLoc);
973 return bufferName[0] == '<' ? NULL : bufferName;
974 }
Douglas Gregor02465752009-10-16 21:24:31 +0000975
976 // Retrieve the file in which the macro was instantiated, then provide that
977 // buffer name.
978 // FIXME: Do we want to give specific macro-instantiation information?
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000979 const llvm::MemoryBuffer *Buffer
Douglas Gregor02465752009-10-16 21:24:31 +0000980 = SourceMgr.getBuffer(SourceMgr.getDecomposedSpellingLoc(SLoc).first);
981 if (!Buffer)
982 return 0;
983
984 return Buffer->getBufferIdentifier();
Steve Naroff600866c2009-08-27 19:51:58 +0000985}
986
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000987CXFile clang_getCursorSourceFile(CXCursor C) {
Steve Naroff88145032009-10-27 14:35:18 +0000988 assert(C.decl && "CXCursor has null decl");
989 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
990 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000991
Steve Naroff88145032009-10-27 14:35:18 +0000992 return (void *)getFileEntryFromSourceLocation(SourceMgr,
Daniel Dunbaracca7252009-11-30 20:42:49 +0000993 getLocationFromCursor(C,SourceMgr, ND));
Steve Naroff88145032009-10-27 14:35:18 +0000994}
995
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000996void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +0000997 const char **startBuf,
998 const char **endBuf,
999 unsigned *startLine,
1000 unsigned *startColumn,
1001 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001002 unsigned *endColumn) {
Steve Naroff4ade6d62009-09-23 17:52:52 +00001003 assert(C.decl && "CXCursor has null decl");
1004 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
1005 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
1006 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001007
Steve Naroff4ade6d62009-09-23 17:52:52 +00001008 SourceManager &SM = FD->getASTContext().getSourceManager();
1009 *startBuf = SM.getCharacterData(Body->getLBracLoc());
1010 *endBuf = SM.getCharacterData(Body->getRBracLoc());
1011 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
1012 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
1013 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
1014 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
1015}
1016
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001017enum CXCompletionChunkKind
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001018clang_getCompletionChunkKind(CXCompletionString completion_string,
1019 unsigned chunk_number) {
1020 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
1021 if (!CCStr || chunk_number >= CCStr->size())
1022 return CXCompletionChunk_Text;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001023
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001024 switch ((*CCStr)[chunk_number].Kind) {
1025 case CodeCompletionString::CK_TypedText:
1026 return CXCompletionChunk_TypedText;
1027 case CodeCompletionString::CK_Text:
1028 return CXCompletionChunk_Text;
1029 case CodeCompletionString::CK_Optional:
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001030 return CXCompletionChunk_Optional;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001031 case CodeCompletionString::CK_Placeholder:
1032 return CXCompletionChunk_Placeholder;
1033 case CodeCompletionString::CK_Informative:
1034 return CXCompletionChunk_Informative;
1035 case CodeCompletionString::CK_CurrentParameter:
1036 return CXCompletionChunk_CurrentParameter;
1037 case CodeCompletionString::CK_LeftParen:
1038 return CXCompletionChunk_LeftParen;
1039 case CodeCompletionString::CK_RightParen:
1040 return CXCompletionChunk_RightParen;
1041 case CodeCompletionString::CK_LeftBracket:
1042 return CXCompletionChunk_LeftBracket;
1043 case CodeCompletionString::CK_RightBracket:
1044 return CXCompletionChunk_RightBracket;
1045 case CodeCompletionString::CK_LeftBrace:
1046 return CXCompletionChunk_LeftBrace;
1047 case CodeCompletionString::CK_RightBrace:
1048 return CXCompletionChunk_RightBrace;
1049 case CodeCompletionString::CK_LeftAngle:
1050 return CXCompletionChunk_LeftAngle;
1051 case CodeCompletionString::CK_RightAngle:
1052 return CXCompletionChunk_RightAngle;
1053 case CodeCompletionString::CK_Comma:
1054 return CXCompletionChunk_Comma;
1055 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001056
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001057 // Should be unreachable, but let's be careful.
1058 return CXCompletionChunk_Text;
1059}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001060
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001061const char *clang_getCompletionChunkText(CXCompletionString completion_string,
1062 unsigned chunk_number) {
1063 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
1064 if (!CCStr || chunk_number >= CCStr->size())
1065 return 0;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001066
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001067 switch ((*CCStr)[chunk_number].Kind) {
1068 case CodeCompletionString::CK_TypedText:
1069 case CodeCompletionString::CK_Text:
1070 case CodeCompletionString::CK_Placeholder:
1071 case CodeCompletionString::CK_CurrentParameter:
1072 case CodeCompletionString::CK_Informative:
1073 case CodeCompletionString::CK_LeftParen:
1074 case CodeCompletionString::CK_RightParen:
1075 case CodeCompletionString::CK_LeftBracket:
1076 case CodeCompletionString::CK_RightBracket:
1077 case CodeCompletionString::CK_LeftBrace:
1078 case CodeCompletionString::CK_RightBrace:
1079 case CodeCompletionString::CK_LeftAngle:
1080 case CodeCompletionString::CK_RightAngle:
1081 case CodeCompletionString::CK_Comma:
1082 return (*CCStr)[chunk_number].Text;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001083
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001084 case CodeCompletionString::CK_Optional:
1085 // Note: treated as an empty text block.
1086 return 0;
1087 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001088
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001089 // Should be unreachable, but let's be careful.
1090 return 0;
1091}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001092
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001093CXCompletionString
1094clang_getCompletionChunkCompletionString(CXCompletionString completion_string,
1095 unsigned chunk_number) {
1096 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
1097 if (!CCStr || chunk_number >= CCStr->size())
1098 return 0;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001099
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001100 switch ((*CCStr)[chunk_number].Kind) {
1101 case CodeCompletionString::CK_TypedText:
1102 case CodeCompletionString::CK_Text:
1103 case CodeCompletionString::CK_Placeholder:
1104 case CodeCompletionString::CK_CurrentParameter:
1105 case CodeCompletionString::CK_Informative:
1106 case CodeCompletionString::CK_LeftParen:
1107 case CodeCompletionString::CK_RightParen:
1108 case CodeCompletionString::CK_LeftBracket:
1109 case CodeCompletionString::CK_RightBracket:
1110 case CodeCompletionString::CK_LeftBrace:
1111 case CodeCompletionString::CK_RightBrace:
1112 case CodeCompletionString::CK_LeftAngle:
1113 case CodeCompletionString::CK_RightAngle:
1114 case CodeCompletionString::CK_Comma:
1115 return 0;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001116
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001117 case CodeCompletionString::CK_Optional:
1118 // Note: treated as an empty text block.
1119 return (*CCStr)[chunk_number].Optional;
1120 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001121
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001122 // Should be unreachable, but let's be careful.
1123 return 0;
1124}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001125
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001126unsigned clang_getNumCompletionChunks(CXCompletionString completion_string) {
1127 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
1128 return CCStr? CCStr->size() : 0;
1129}
Steve Naroff4ade6d62009-09-23 17:52:52 +00001130
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001131static CXCursorKind parseResultKind(llvm::StringRef Str) {
1132 return llvm::StringSwitch<CXCursorKind>(Str)
1133 .Case("Typedef", CXCursor_TypedefDecl)
1134 .Case("Struct", CXCursor_StructDecl)
1135 .Case("Union", CXCursor_UnionDecl)
1136 .Case("Class", CXCursor_ClassDecl)
Douglas Gregorff4393c2009-11-09 21:35:27 +00001137 .Case("Enum", CXCursor_EnumDecl)
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001138 .Case("Field", CXCursor_FieldDecl)
1139 .Case("EnumConstant", CXCursor_EnumConstantDecl)
1140 .Case("Function", CXCursor_FunctionDecl)
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001141 // FIXME: Hacks here to make C++ member functions look like C functions
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001142 .Case("CXXMethod", CXCursor_FunctionDecl)
1143 .Case("CXXConstructor", CXCursor_FunctionDecl)
1144 .Case("CXXDestructor", CXCursor_FunctionDecl)
1145 .Case("CXXConversion", CXCursor_FunctionDecl)
1146 .Case("Var", CXCursor_VarDecl)
1147 .Case("ParmVar", CXCursor_ParmDecl)
1148 .Case("ObjCInterface", CXCursor_ObjCInterfaceDecl)
1149 .Case("ObjCCategory", CXCursor_ObjCCategoryDecl)
1150 .Case("ObjCProtocol", CXCursor_ObjCProtocolDecl)
1151 .Case("ObjCProperty", CXCursor_ObjCPropertyDecl)
1152 .Case("ObjCIvar", CXCursor_ObjCIvarDecl)
1153 .Case("ObjCInstanceMethod", CXCursor_ObjCInstanceMethodDecl)
1154 .Case("ObjCClassMethod", CXCursor_ObjCClassMethodDecl)
1155 .Default(CXCursor_NotImplemented);
1156}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001157
1158void clang_codeComplete(CXIndex CIdx,
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001159 const char *source_filename,
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001160 int num_command_line_args,
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001161 const char **command_line_args,
1162 const char *complete_filename,
1163 unsigned complete_line,
1164 unsigned complete_column,
1165 CXCompletionIterator completion_iterator,
1166 CXClientData client_data) {
1167 // The indexer, which is mainly used to determine where diagnostics go.
1168 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001169
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001170 // Build up the arguments for invoking 'clang'.
1171 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001172
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001173 // First add the complete path to the 'clang' executable.
1174 llvm::sys::Path ClangPath = CXXIdx->getClangPath();
1175 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001176
1177 // Add the '-fsyntax-only' argument so that we only perform a basic
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001178 // syntax check of the code.
1179 argv.push_back("-fsyntax-only");
1180
1181 // Add the appropriate '-code-completion-at=file:line:column' argument
1182 // to perform code completion, with an "-Xclang" preceding it.
1183 std::string code_complete_at;
1184 code_complete_at += "-code-completion-at=";
1185 code_complete_at += complete_filename;
1186 code_complete_at += ":";
1187 code_complete_at += llvm::utostr(complete_line);
1188 code_complete_at += ":";
1189 code_complete_at += llvm::utostr(complete_column);
1190 argv.push_back("-Xclang");
1191 argv.push_back(code_complete_at.c_str());
1192 argv.push_back("-Xclang");
Daniel Dunbar4db166b2009-11-19 05:32:09 +00001193 argv.push_back("-no-code-completion-debug-printer");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001194
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001195 // Add the source file name (FIXME: later, we'll want to build temporary
1196 // file from the buffer, or just feed the source text via standard input).
Ted Kremenek4633d1b2009-11-17 18:18:02 +00001197 if (source_filename)
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001198 argv.push_back(source_filename);
1199
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001200 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1201 for (int i = 0; i < num_command_line_args; ++i)
1202 if (const char *arg = command_line_args[i]) {
1203 if (strcmp(arg, "-o") == 0) {
1204 ++i; // Also skip the matching argument.
1205 continue;
1206 }
1207 if (strcmp(arg, "-emit-ast") == 0 ||
1208 strcmp(arg, "-c") == 0 ||
1209 strcmp(arg, "-fsyntax-only") == 0) {
1210 continue;
1211 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001212
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001213 // Keep the argument.
1214 argv.push_back(arg);
1215 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001216
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001217 // Add the null terminator.
1218 argv.push_back(NULL);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001219
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001220 // Generate a temporary name for the AST file.
1221 char tmpFile[L_tmpnam];
1222 char *tmpFileName = tmpnam(tmpFile);
1223 llvm::sys::Path ResultsFile(tmpFileName);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001224
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001225 // Invoke 'clang'.
1226 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1227 // on Unix or NUL (Windows).
1228 std::string ErrMsg;
1229 const llvm::sys::Path *Redirects[] = { &DevNull, &ResultsFile, &DevNull, 0 };
1230 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
1231 /* redirects */ &Redirects[0],
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001232 /* secondsToWait */ 0,
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001233 /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001234
Ted Kremenek0854d702009-11-10 19:18:52 +00001235 if (CXXIdx->getDisplayDiagnostics() && !ErrMsg.empty()) {
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001236 llvm::errs() << "clang_codeComplete: " << ErrMsg
Daniel Dunbaracca7252009-11-30 20:42:49 +00001237 << '\n' << "Arguments: \n";
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001238 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
1239 I!=E; ++I) {
1240 if (*I)
1241 llvm::errs() << ' ' << *I << '\n';
1242 }
1243 llvm::errs() << '\n';
1244 }
1245
1246 // Parse the resulting source file to find code-completion results.
1247 using llvm::MemoryBuffer;
1248 using llvm::StringRef;
1249 if (MemoryBuffer *F = MemoryBuffer::getFile(ResultsFile.c_str())) {
1250 StringRef Buffer = F->getBuffer();
1251 do {
1252 StringRef::size_type CompletionIdx = Buffer.find("COMPLETION:");
1253 StringRef::size_type OverloadIdx = Buffer.find("OVERLOAD:");
1254 if (CompletionIdx == StringRef::npos && OverloadIdx == StringRef::npos)
1255 break;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001256
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001257 if (OverloadIdx < CompletionIdx) {
1258 // Parse an overload result.
1259 Buffer = Buffer.substr(OverloadIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001260
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001261 // Skip past the OVERLOAD:
1262 Buffer = Buffer.substr(Buffer.find(':') + 1);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001263
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001264 // Find the entire completion string.
1265 StringRef::size_type EOL = Buffer.find_first_of("\n\r");
1266 if (EOL == StringRef::npos)
1267 continue;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001268
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001269 StringRef Line = Buffer.substr(0, EOL);
1270 Buffer = Buffer.substr(EOL + 1);
1271 CodeCompletionString *CCStr = CodeCompletionString::Deserialize(Line);
1272 if (!CCStr || CCStr->empty())
1273 continue;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001274
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001275 // Vend the code-completion result to the caller.
1276 CXCompletionResult Result;
1277 Result.CursorKind = CXCursor_NotImplemented;
1278 Result.CompletionString = CCStr;
1279 if (completion_iterator)
1280 completion_iterator(&Result, client_data);
1281 delete CCStr;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001282
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001283 continue;
1284 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001285
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001286 // Parse a completion result.
1287 Buffer = Buffer.substr(CompletionIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001288
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001289 // Skip past the COMPLETION:
1290 Buffer = Buffer.substr(Buffer.find(':') + 1);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001291
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001292 // Get the rank
1293 unsigned Rank = 0;
1294 StringRef::size_type AfterRank = Buffer.find(':');
1295 Buffer.substr(0, AfterRank).getAsInteger(10, Rank);
1296 Buffer = Buffer.substr(AfterRank + 1);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001297
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001298 // Get the kind of result.
1299 StringRef::size_type AfterKind = Buffer.find(':');
1300 StringRef Kind = Buffer.substr(0, AfterKind);
1301 Buffer = Buffer.substr(AfterKind + 1);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001302
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001303 // Skip over any whitespace.
1304 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001305
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001306 // Find the entire completion string.
1307 StringRef::size_type EOL = Buffer.find_first_of("\n\r");
1308 if (EOL == StringRef::npos)
1309 continue;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001310
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001311 StringRef Line = Buffer.substr(0, EOL);
1312 Buffer = Buffer.substr(EOL + 1);
1313 CodeCompletionString *CCStr = CodeCompletionString::Deserialize(Line);
1314 if (!CCStr || CCStr->empty())
1315 continue;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001316
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001317 // Vend the code-completion result to the caller.
1318 CXCompletionResult Result;
1319 Result.CursorKind = parseResultKind(Kind);
1320 Result.CompletionString = CCStr;
1321 if (completion_iterator)
1322 completion_iterator(&Result, client_data);
1323 delete CCStr;
1324 } while (true);
1325 delete F;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001326 }
1327
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001328 ResultsFile.eraseFromDisk();
1329}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001330
Steve Naroff600866c2009-08-27 19:51:58 +00001331} // end extern "C"