blob: 9259818e0ecaf6027d6dd3040898fc1d92c90c3d [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"
Daniel Dunbar5262fda2009-12-03 01:45:44 +000026#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor0c8296d2009-11-07 00:00:49 +000027#include "llvm/ADT/StringExtras.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 Dunbar5262fda2009-12-03 01:45:44 +0000295 IgnoreDiagnosticsClient IgnoreDiagClient;
296 llvm::OwningPtr<Diagnostic> TextDiags;
297 Diagnostic IgnoreDiags;
298 bool UseExternalASTGeneration;
299 bool OnlyLocalDecls;
300 bool DisplayDiagnostics;
301
302 llvm::sys::Path ClangPath;
303
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000304public:
305 explicit CIndexer(Program *prog) : Indexer(*prog),
Daniel Dunbar5262fda2009-12-03 01:45:44 +0000306 IgnoreDiags(&IgnoreDiagClient),
307 UseExternalASTGeneration(false),
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000308 OnlyLocalDecls(false),
Daniel Dunbar5262fda2009-12-03 01:45:44 +0000309 DisplayDiagnostics(false) {
310 TextDiags.reset(
311 CompilerInstance::createDiagnostics(DiagnosticOptions(), 0, 0));
312 }
Ted Kremenekdff76892009-10-17 06:21:47 +0000313
314 virtual ~CIndexer() { delete &getProgram(); }
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000315
316 /// \brief Whether we only want to see "local" declarations (that did not
317 /// come from a previous precompiled header). If false, we want to see all
318 /// declarations.
319 bool getOnlyLocalDecls() const { return OnlyLocalDecls; }
320 void setOnlyLocalDecls(bool Local = true) { OnlyLocalDecls = Local; }
Benjamin Kramer96707622009-10-18 11:10:55 +0000321
Daniel Dunbar5262fda2009-12-03 01:45:44 +0000322 bool getDisplayDiagnostics() const { return DisplayDiagnostics; }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000323 void setDisplayDiagnostics(bool Display = true) {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000324 DisplayDiagnostics = Display;
325 }
Daniel Dunbar5262fda2009-12-03 01:45:44 +0000326
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000327 bool getUseExternalASTGeneration() const { return UseExternalASTGeneration; }
328 void setUseExternalASTGeneration(bool Value) {
329 UseExternalASTGeneration = Value;
330 }
331
Daniel Dunbar5262fda2009-12-03 01:45:44 +0000332 Diagnostic &getDiags() {
333 return DisplayDiagnostics ? *TextDiags : IgnoreDiags;
334 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000335
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000336 /// \brief Get the path of the clang binary.
Benjamin Kramerc5a9e952009-10-19 10:20:24 +0000337 const llvm::sys::Path& getClangPath();
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000338};
Steve Naroff89922f82009-08-31 00:59:03 +0000339
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000340const llvm::sys::Path& CIndexer::getClangPath() {
341 // Did we already compute the path?
342 if (!ClangPath.empty())
343 return ClangPath;
344
Steve Naroff5b7d8e22009-10-15 20:04:39 +0000345 // Find the location where this library lives (libCIndex.dylib).
Benjamin Kramer20d75812009-10-18 16:13:48 +0000346#ifdef LLVM_ON_WIN32
347 MEMORY_BASIC_INFORMATION mbi;
348 char path[MAX_PATH];
Benjamin Krameredcd8282009-10-18 16:20:58 +0000349 VirtualQuery((void *)(uintptr_t)clang_createTranslationUnit, &mbi,
Benjamin Kramer20d75812009-10-18 16:13:48 +0000350 sizeof(mbi));
351 GetModuleFileNameA((HINSTANCE)mbi.AllocationBase, path, MAX_PATH);
352
353 llvm::sys::Path CIndexPath(path);
John Thompson6a6742a2009-11-11 23:11:14 +0000354
355 CIndexPath.eraseComponent();
356 CIndexPath.appendComponent("clang");
357 CIndexPath.appendSuffix("exe");
358 CIndexPath.makeAbsolute();
Benjamin Kramer20d75812009-10-18 16:13:48 +0000359#else
Steve Naroff5b7d8e22009-10-15 20:04:39 +0000360 // This silly cast below avoids a C++ warning.
361 Dl_info info;
362 if (dladdr((void *)(uintptr_t)clang_createTranslationUnit, &info) == 0)
363 assert(0 && "Call to dladdr() failed");
364
365 llvm::sys::Path CIndexPath(info.dli_fname);
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000366
Steve Naroff5b7d8e22009-10-15 20:04:39 +0000367 // We now have the CIndex directory, locate clang relative to it.
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000368 CIndexPath.eraseComponent();
369 CIndexPath.eraseComponent();
370 CIndexPath.appendComponent("bin");
371 CIndexPath.appendComponent("clang");
John Thompson6a6742a2009-11-11 23:11:14 +0000372#endif
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000373
374 // Cache our result.
375 ClangPath = CIndexPath;
376 return ClangPath;
377}
378
379}
380
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000381static SourceLocation getLocationFromCursor(CXCursor C,
Daniel Dunbarc6190332009-11-08 04:13:53 +0000382 SourceManager &SourceMgr,
383 NamedDecl *ND) {
384 if (clang_isReference(C.kind)) {
385 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +0000386 case CXCursor_ObjCClassRef: {
387 if (isa<ObjCInterfaceDecl>(ND)) {
388 // FIXME: This is a hack (storing the parent decl in the stmt slot).
389 NamedDecl *parentDecl = static_cast<NamedDecl *>(C.stmt);
390 return parentDecl->getLocation();
Daniel Dunbarc6190332009-11-08 04:13:53 +0000391 }
Daniel Dunbaracca7252009-11-30 20:42:49 +0000392 ObjCCategoryDecl *OID = dyn_cast<ObjCCategoryDecl>(ND);
393 assert(OID && "clang_getCursorLine(): Missing category decl");
394 return OID->getClassInterface()->getLocation();
395 }
396 case CXCursor_ObjCSuperClassRef: {
397 ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ND);
398 assert(OID && "clang_getCursorLine(): Missing interface decl");
399 return OID->getSuperClassLoc();
400 }
401 case CXCursor_ObjCProtocolRef: {
402 ObjCProtocolDecl *OID = dyn_cast<ObjCProtocolDecl>(ND);
403 assert(OID && "clang_getCursorLine(): Missing protocol decl");
404 return OID->getLocation();
405 }
406 case CXCursor_ObjCSelectorRef: {
407 ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(
408 static_cast<Stmt *>(C.stmt));
409 assert(OME && "clang_getCursorLine(): Missing message expr");
410 return OME->getLeftLoc(); /* FIXME: should be a range */
411 }
412 case CXCursor_VarRef:
413 case CXCursor_FunctionRef:
414 case CXCursor_EnumConstantRef: {
415 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(
416 static_cast<Stmt *>(C.stmt));
417 assert(DRE && "clang_getCursorLine(): Missing decl ref expr");
418 return DRE->getLocation();
419 }
420 default:
421 return SourceLocation();
Daniel Dunbarc6190332009-11-08 04:13:53 +0000422 }
423 } else { // We have a declaration or a definition.
424 SourceLocation SLoc;
425 switch (ND->getKind()) {
Daniel Dunbaracca7252009-11-30 20:42:49 +0000426 case Decl::ObjCInterface: {
427 SLoc = dyn_cast<ObjCInterfaceDecl>(ND)->getClassLoc();
428 break;
429 }
430 case Decl::ObjCProtocol: {
431 SLoc = ND->getLocation(); /* FIXME: need to get the name location. */
432 break;
433 }
434 default: {
435 SLoc = ND->getLocation();
436 break;
437 }
Daniel Dunbarc6190332009-11-08 04:13:53 +0000438 }
439 if (SLoc.isInvalid())
440 return SourceLocation();
441 return SourceMgr.getSpellingLoc(SLoc); // handles macro instantiations.
442 }
443}
444
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000445static CXString createCXString(const char *String, bool DupString = false) {
446 CXString Str;
447 if (DupString) {
448 Str.Spelling = strdup(String);
449 Str.MustFreeString = 1;
450 } else {
451 Str.Spelling = String;
452 Str.MustFreeString = 0;
453 }
454 return Str;
455}
456
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000457extern "C" {
458
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000459CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000460 int displayDiagnostics) {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000461 CIndexer *CIdxr = new CIndexer(new Program());
462 if (excludeDeclarationsFromPCH)
463 CIdxr->setOnlyLocalDecls();
464 if (displayDiagnostics)
465 CIdxr->setDisplayDiagnostics();
466 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +0000467}
468
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000469void clang_disposeIndex(CXIndex CIdx) {
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000470 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000471 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000472}
473
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000474void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
475 assert(CIdx && "Passed null CXIndex");
476 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
477 CXXIdx->setUseExternalASTGeneration(value);
478}
479
Steve Naroff50398192009-08-28 15:28:48 +0000480// FIXME: need to pass back error info.
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000481CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
482 const char *ast_filename) {
Steve Naroff50398192009-08-28 15:28:48 +0000483 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000484 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000485
Daniel Dunbar5262fda2009-12-03 01:45:44 +0000486 return ASTUnit::LoadFromPCHFile(ast_filename, CXXIdx->getDiags(),
487 CXXIdx->getOnlyLocalDecls(),
488 /* UseBumpAllocator = */ true);
Steve Naroff600866c2009-08-27 19:51:58 +0000489}
490
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000491CXTranslationUnit
492clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
493 const char *source_filename,
494 int num_command_line_args,
495 const char **command_line_args) {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000496 assert(CIdx && "Passed null CXIndex");
497 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
498
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000499 if (!CXXIdx->getUseExternalASTGeneration()) {
500 llvm::SmallVector<const char *, 16> Args;
501
502 // The 'source_filename' argument is optional. If the caller does not
503 // specify it then it is assumed that the source file is specified
504 // in the actual argument list.
505 if (source_filename)
506 Args.push_back(source_filename);
507 Args.insert(Args.end(), command_line_args,
508 command_line_args + num_command_line_args);
509
510 void *MainAddr = (void *)(uintptr_t)clang_createTranslationUnit;
Daniel Dunbar94220972009-12-05 02:17:18 +0000511
512 unsigned NumErrors = CXXIdx->getDiags().getNumErrors();
513 llvm::OwningPtr<ASTUnit> Unit(
514 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
515 CXXIdx->getDiags(), "<clang>", MainAddr,
516 CXXIdx->getOnlyLocalDecls(),
517 /* UseBumpAllocator = */ true));
518
519 // FIXME: Until we have broader testing, just drop the entire AST if we
520 // encountered an error.
521 if (NumErrors != CXXIdx->getDiags().getNumErrors())
522 return 0;
523
524 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000525 }
526
Ted Kremenek139ba862009-10-22 00:03:57 +0000527 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000528 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000529
Ted Kremenek139ba862009-10-22 00:03:57 +0000530 // First add the complete path to the 'clang' executable.
531 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000532 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000533
Ted Kremenek139ba862009-10-22 00:03:57 +0000534 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000535 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000536
Ted Kremenek139ba862009-10-22 00:03:57 +0000537 // The 'source_filename' argument is optional. If the caller does not
538 // specify it then it is assumed that the source file is specified
539 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000540 if (source_filename)
541 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +0000542
Steve Naroff37b5ac22009-10-15 20:50:09 +0000543 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +0000544 argv.push_back("-o");
Steve Naroff37b5ac22009-10-15 20:50:09 +0000545 char astTmpFile[L_tmpnam];
Ted Kremenek74cd0692009-10-15 23:21:22 +0000546 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +0000547
548 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
549 for (int i = 0; i < num_command_line_args; ++i)
550 if (const char *arg = command_line_args[i]) {
551 if (strcmp(arg, "-o") == 0) {
552 ++i; // Also skip the matching argument.
553 continue;
554 }
555 if (strcmp(arg, "-emit-ast") == 0 ||
556 strcmp(arg, "-c") == 0 ||
557 strcmp(arg, "-fsyntax-only") == 0) {
558 continue;
559 }
560
561 // Keep the argument.
562 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000563 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000564
Ted Kremenek139ba862009-10-22 00:03:57 +0000565 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000566 argv.push_back(NULL);
567
Ted Kremenekfeb15e32009-10-26 22:14:08 +0000568 // Invoke 'clang'.
569 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
570 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +0000571 std::string ErrMsg;
Ted Kremenekc46e4632009-10-19 22:27:32 +0000572 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DevNull, NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +0000573 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
574 /* redirects */ !CXXIdx->getDisplayDiagnostics() ? &Redirects[0] : NULL,
575 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000576
Ted Kremenek0854d702009-11-10 19:18:52 +0000577 if (CXXIdx->getDisplayDiagnostics() && !ErrMsg.empty()) {
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000578 llvm::errs() << "clang_createTranslationUnitFromSourceFile: " << ErrMsg
Daniel Dunbaracca7252009-11-30 20:42:49 +0000579 << '\n' << "Arguments: \n";
Ted Kremenek379afec2009-10-22 03:24:01 +0000580 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Ted Kremenek779e5f42009-10-26 22:08:39 +0000581 I!=E; ++I) {
582 if (*I)
583 llvm::errs() << ' ' << *I << '\n';
584 }
585 llvm::errs() << '\n';
Ted Kremenek379afec2009-10-22 03:24:01 +0000586 }
Benjamin Kramer0829a832009-10-18 11:19:36 +0000587
Steve Naroff37b5ac22009-10-15 20:50:09 +0000588 // Finally, we create the translation unit from the ast file.
Steve Naroffe19944c2009-10-15 22:23:48 +0000589 ASTUnit *ATU = static_cast<ASTUnit *>(
Daniel Dunbaracca7252009-11-30 20:42:49 +0000590 clang_createTranslationUnit(CIdx, astTmpFile));
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000591 if (ATU)
592 ATU->unlinkTemporaryFile();
Steve Naroffe19944c2009-10-15 22:23:48 +0000593 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +0000594}
595
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000596void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000597 assert(CTUnit && "Passed null CXTranslationUnit");
598 delete static_cast<ASTUnit *>(CTUnit);
599}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000600
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000601CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000602 assert(CTUnit && "Passed null CXTranslationUnit");
Steve Naroff77accc12009-09-03 18:19:54 +0000603 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000604 return createCXString(CXXUnit->getOriginalSourceFileName().c_str(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000605}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +0000606
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000607void clang_loadTranslationUnit(CXTranslationUnit CTUnit,
Steve Naroffc857ea42009-09-02 13:28:54 +0000608 CXTranslationUnitIterator callback,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000609 CXClientData CData) {
Steve Naroff50398192009-08-28 15:28:48 +0000610 assert(CTUnit && "Passed null CXTranslationUnit");
611 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
612 ASTContext &Ctx = CXXUnit->getASTContext();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000613
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000614 unsigned PCHLevel = Decl::MaxPCHLevel;
615
616 // Set the PCHLevel to filter out unwanted decls if requested.
617 if (CXXUnit->getOnlyLocalDecls()) {
618 PCHLevel = 0;
619
620 // If the main input was an AST, bump the level.
621 if (CXXUnit->isMainFileAST())
622 ++PCHLevel;
623 }
624
625 TUVisitor DVisit(CTUnit, callback, CData, PCHLevel);
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000626
627 // If using a non-AST based ASTUnit, iterate over the stored list of top-level
628 // decls.
629 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls()) {
630 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
631 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
632 ie = TLDs.end(); it != ie; ++it) {
633 DVisit.Visit(*it);
634 }
635 } else
636 DVisit.Visit(Ctx.getTranslationUnitDecl());
Steve Naroff600866c2009-08-27 19:51:58 +0000637}
638
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000639void clang_loadDeclaration(CXDecl Dcl,
640 CXDeclIterator callback,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000641 CXClientData CData) {
Steve Naroffc857ea42009-09-02 13:28:54 +0000642 assert(Dcl && "Passed null CXDecl");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000643
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000644 CDeclVisitor DVisit(Dcl, callback, CData,
645 static_cast<Decl *>(Dcl)->getPCHLevel());
Steve Naroffc857ea42009-09-02 13:28:54 +0000646 DVisit.Visit(static_cast<Decl *>(Dcl));
Steve Naroff600866c2009-08-27 19:51:58 +0000647}
648
Steve Naroff7e8f8182009-08-28 12:07:44 +0000649// Some notes on CXEntity:
650//
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000651// - Since the 'ordinary' namespace includes functions, data, typedefs,
652// ObjC interfaces, thecurrent algorithm is a bit naive (resulting in one
Steve Naroff7e8f8182009-08-28 12:07:44 +0000653// entity for 2 different types). For example:
654//
655// module1.m: @interface Foo @end Foo *x;
656// module2.m: void Foo(int);
657//
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000658// - Since the unique name spans translation units, static data/functions
Steve Naroff7e8f8182009-08-28 12:07:44 +0000659// within a CXTranslationUnit are *not* currently represented by entities.
660// As a result, there will be no entity for the following:
661//
662// module.m: static void Foo() { }
663//
664
665
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000666const char *clang_getDeclarationName(CXEntity) {
Steve Naroff600866c2009-08-27 19:51:58 +0000667 return "";
668}
669
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000670const char *clang_getURI(CXEntity) {
671 return "";
672}
673
674CXEntity clang_getEntity(const char *URI) {
Steve Naroff600866c2009-08-27 19:51:58 +0000675 return 0;
676}
677
678//
679// CXDecl Operations.
680//
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000681
682CXEntity clang_getEntityFromDecl(CXDecl) {
Steve Naroff600866c2009-08-27 19:51:58 +0000683 return 0;
684}
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000685
686CXString clang_getDeclSpelling(CXDecl AnonDecl) {
Steve Naroff89922f82009-08-31 00:59:03 +0000687 assert(AnonDecl && "Passed null CXDecl");
688 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
Steve Naroffef0cef62009-11-09 17:45:52 +0000689
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000690 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
691 return createCXString(OMD->getSelector().getAsString().c_str(), true);
692
693 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Steve Naroff0d69b8c2009-10-29 21:11:04 +0000694 // No, this isn't the same as the code below. getIdentifier() is non-virtual
695 // and returns different names. NamedDecl returns the class name and
696 // ObjCCategoryImplDecl returns the category name.
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000697 return createCXString(CIMP->getIdentifier()->getNameStart());
698
699 if (ND->getIdentifier())
700 return createCXString(ND->getIdentifier()->getNameStart());
701
702 return createCXString("");
Steve Naroff600866c2009-08-27 19:51:58 +0000703}
Steve Narofff334b4e2009-09-02 18:26:48 +0000704
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000705unsigned clang_getDeclLine(CXDecl AnonDecl) {
Steve Naroff699a07d2009-09-25 21:32:34 +0000706 assert(AnonDecl && "Passed null CXDecl");
707 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
708 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
709 return SourceMgr.getSpellingLineNumber(ND->getLocation());
710}
711
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000712unsigned clang_getDeclColumn(CXDecl AnonDecl) {
Steve Naroff699a07d2009-09-25 21:32:34 +0000713 assert(AnonDecl && "Passed null CXDecl");
714 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
715 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Steve Naroff74165242009-09-25 22:15:54 +0000716 return SourceMgr.getSpellingColumnNumber(ND->getLocation());
Steve Naroff699a07d2009-09-25 21:32:34 +0000717}
718
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000719const char *clang_getDeclSource(CXDecl AnonDecl) {
Steve Naroffee9405e2009-09-25 21:45:39 +0000720 assert(AnonDecl && "Passed null CXDecl");
Steve Naroff88145032009-10-27 14:35:18 +0000721 FileEntry *FEnt = static_cast<FileEntry *>(clang_getDeclSourceFile(AnonDecl));
722 assert (FEnt && "Cannot find FileEntry for Decl");
723 return clang_getFileName(FEnt);
724}
725
726static const FileEntry *getFileEntryFromSourceLocation(SourceManager &SMgr,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000727 SourceLocation SLoc) {
Steve Naroff88145032009-10-27 14:35:18 +0000728 FileID FID;
729 if (SLoc.isFileID())
730 FID = SMgr.getFileID(SLoc);
731 else
732 FID = SMgr.getDecomposedSpellingLoc(SLoc).first;
733 return SMgr.getFileEntryForID(FID);
734}
735
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000736CXFile clang_getDeclSourceFile(CXDecl AnonDecl) {
Steve Naroff88145032009-10-27 14:35:18 +0000737 assert(AnonDecl && "Passed null CXDecl");
Steve Naroffee9405e2009-09-25 21:45:39 +0000738 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
739 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Steve Naroff88145032009-10-27 14:35:18 +0000740 return (void *)getFileEntryFromSourceLocation(SourceMgr, ND->getLocation());
741}
742
743const char *clang_getFileName(CXFile SFile) {
744 assert(SFile && "Passed null CXFile");
745 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
746 return FEnt->getName();
747}
748
749time_t clang_getFileTime(CXFile SFile) {
750 assert(SFile && "Passed null CXFile");
751 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
752 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +0000753}
754
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000755CXString clang_getCursorSpelling(CXCursor C) {
Steve Narofff334b4e2009-09-02 18:26:48 +0000756 assert(C.decl && "CXCursor has null decl");
757 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
Steve Naroffef0cef62009-11-09 17:45:52 +0000758
Steve Narofff334b4e2009-09-02 18:26:48 +0000759 if (clang_isReference(C.kind)) {
760 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +0000761 case CXCursor_ObjCSuperClassRef: {
762 ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ND);
763 assert(OID && "clang_getCursorLine(): Missing interface decl");
764 return createCXString(OID->getSuperClass()->getIdentifier()
765 ->getNameStart());
766 }
767 case CXCursor_ObjCClassRef: {
768 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ND))
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000769 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +0000770
771 ObjCCategoryDecl *OCD = dyn_cast<ObjCCategoryDecl>(ND);
772 assert(OCD && "clang_getCursorLine(): Missing category decl");
773 return createCXString(OCD->getClassInterface()->getIdentifier()
774 ->getNameStart());
775 }
776 case CXCursor_ObjCProtocolRef: {
777 ObjCProtocolDecl *OID = dyn_cast<ObjCProtocolDecl>(ND);
778 assert(OID && "clang_getCursorLine(): Missing protocol decl");
779 return createCXString(OID->getIdentifier()->getNameStart());
780 }
781 case CXCursor_ObjCSelectorRef: {
782 ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(
783 static_cast<Stmt *>(C.stmt));
784 assert(OME && "clang_getCursorLine(): Missing message expr");
785 return createCXString(OME->getSelector().getAsString().c_str(), true);
786 }
787 case CXCursor_VarRef:
788 case CXCursor_FunctionRef:
789 case CXCursor_EnumConstantRef: {
790 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(
791 static_cast<Stmt *>(C.stmt));
792 assert(DRE && "clang_getCursorLine(): Missing decl ref expr");
793 return createCXString(DRE->getDecl()->getIdentifier()->getNameStart());
794 }
795 default:
796 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +0000797 }
798 }
799 return clang_getDeclSpelling(C.decl);
800}
801
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000802const char *clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +0000803 switch (Kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +0000804 case CXCursor_FunctionDecl: return "FunctionDecl";
805 case CXCursor_TypedefDecl: return "TypedefDecl";
806 case CXCursor_EnumDecl: return "EnumDecl";
807 case CXCursor_EnumConstantDecl: return "EnumConstantDecl";
808 case CXCursor_StructDecl: return "StructDecl";
809 case CXCursor_UnionDecl: return "UnionDecl";
810 case CXCursor_ClassDecl: return "ClassDecl";
811 case CXCursor_FieldDecl: return "FieldDecl";
812 case CXCursor_VarDecl: return "VarDecl";
813 case CXCursor_ParmDecl: return "ParmDecl";
814 case CXCursor_ObjCInterfaceDecl: return "ObjCInterfaceDecl";
815 case CXCursor_ObjCCategoryDecl: return "ObjCCategoryDecl";
816 case CXCursor_ObjCProtocolDecl: return "ObjCProtocolDecl";
817 case CXCursor_ObjCPropertyDecl: return "ObjCPropertyDecl";
818 case CXCursor_ObjCIvarDecl: return "ObjCIvarDecl";
819 case CXCursor_ObjCInstanceMethodDecl: return "ObjCInstanceMethodDecl";
820 case CXCursor_ObjCClassMethodDecl: return "ObjCClassMethodDecl";
821 case CXCursor_FunctionDefn: return "FunctionDefn";
822 case CXCursor_ObjCInstanceMethodDefn: return "ObjCInstanceMethodDefn";
823 case CXCursor_ObjCClassMethodDefn: return "ObjCClassMethodDefn";
824 case CXCursor_ObjCClassDefn: return "ObjCClassDefn";
825 case CXCursor_ObjCCategoryDefn: return "ObjCCategoryDefn";
826 case CXCursor_ObjCSuperClassRef: return "ObjCSuperClassRef";
827 case CXCursor_ObjCProtocolRef: return "ObjCProtocolRef";
828 case CXCursor_ObjCClassRef: return "ObjCClassRef";
829 case CXCursor_ObjCSelectorRef: return "ObjCSelectorRef";
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000830
Daniel Dunbaracca7252009-11-30 20:42:49 +0000831 case CXCursor_VarRef: return "VarRef";
832 case CXCursor_FunctionRef: return "FunctionRef";
833 case CXCursor_EnumConstantRef: return "EnumConstantRef";
834 case CXCursor_MemberRef: return "MemberRef";
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000835
Daniel Dunbaracca7252009-11-30 20:42:49 +0000836 case CXCursor_InvalidFile: return "InvalidFile";
837 case CXCursor_NoDeclFound: return "NoDeclFound";
838 case CXCursor_NotImplemented: return "NotImplemented";
839 default: return "<not implemented>";
Steve Naroff89922f82009-08-31 00:59:03 +0000840 }
Steve Naroff600866c2009-08-27 19:51:58 +0000841}
Steve Naroff89922f82009-08-31 00:59:03 +0000842
Steve Naroff9efa7672009-09-04 15:44:05 +0000843static enum CXCursorKind TranslateKind(Decl *D) {
844 switch (D->getKind()) {
Daniel Dunbaracca7252009-11-30 20:42:49 +0000845 case Decl::Function: return CXCursor_FunctionDecl;
846 case Decl::Typedef: return CXCursor_TypedefDecl;
847 case Decl::Enum: return CXCursor_EnumDecl;
848 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
849 case Decl::Record: return CXCursor_StructDecl; // FIXME: union/class
850 case Decl::Field: return CXCursor_FieldDecl;
851 case Decl::Var: return CXCursor_VarDecl;
852 case Decl::ParmVar: return CXCursor_ParmDecl;
853 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
854 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
855 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
856 case Decl::ObjCMethod: {
857 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D);
858 if (MD->isInstanceMethod())
859 return CXCursor_ObjCInstanceMethodDecl;
860 return CXCursor_ObjCClassMethodDecl;
861 }
862 default: break;
Steve Naroff9efa7672009-09-04 15:44:05 +0000863 }
Steve Naroff77128dd2009-09-15 20:25:34 +0000864 return CXCursor_NotImplemented;
Steve Naroff9efa7672009-09-04 15:44:05 +0000865}
Steve Naroff600866c2009-08-27 19:51:58 +0000866//
867// CXCursor Operations.
868//
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000869
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000870CXCursor clang_getCursor(CXTranslationUnit CTUnit, const char *source_name,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000871 unsigned line, unsigned column) {
Steve Naroff9efa7672009-09-04 15:44:05 +0000872 assert(CTUnit && "Passed null CXTranslationUnit");
873 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000874
Steve Naroff9efa7672009-09-04 15:44:05 +0000875 FileManager &FMgr = CXXUnit->getFileManager();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000876 const FileEntry *File = FMgr.getFile(source_name,
877 source_name+strlen(source_name));
Steve Naroff77128dd2009-09-15 20:25:34 +0000878 if (!File) {
Steve Narofffb570422009-09-22 19:25:29 +0000879 CXCursor C = { CXCursor_InvalidFile, 0, 0 };
Steve Naroff77128dd2009-09-15 20:25:34 +0000880 return C;
881 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000882 SourceLocation SLoc =
Steve Naroff9efa7672009-09-04 15:44:05 +0000883 CXXUnit->getSourceManager().getLocation(File, line, column);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000884
Steve Narofff96b5242009-10-28 20:44:47 +0000885 ASTLocation LastLoc = CXXUnit->getLastASTLocation();
886
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000887 ASTLocation ALoc = ResolveLocationInAST(CXXUnit->getASTContext(), SLoc,
Steve Narofff96b5242009-10-28 20:44:47 +0000888 &LastLoc);
889 if (ALoc.isValid())
890 CXXUnit->setLastASTLocation(ALoc);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000891
Argyrios Kyrtzidisf4526e32009-09-29 19:44:27 +0000892 Decl *Dcl = ALoc.getParentDecl();
Argyrios Kyrtzidis05a76512009-09-29 19:45:58 +0000893 if (ALoc.isNamedRef())
894 Dcl = ALoc.AsNamedRef().ND;
Argyrios Kyrtzidisf4526e32009-09-29 19:44:27 +0000895 Stmt *Stm = ALoc.dyn_AsStmt();
Steve Naroff4ade6d62009-09-23 17:52:52 +0000896 if (Dcl) {
897 if (Stm) {
898 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Stm)) {
899 CXCursor C = { TranslateDeclRefExpr(DRE), Dcl, Stm };
900 return C;
901 } else if (ObjCMessageExpr *MExp = dyn_cast<ObjCMessageExpr>(Stm)) {
902 CXCursor C = { CXCursor_ObjCSelectorRef, Dcl, MExp };
903 return C;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000904 }
Steve Naroff4ade6d62009-09-23 17:52:52 +0000905 // Fall through...treat as a decl, not a ref.
906 }
Steve Naroff85e2db72009-10-01 00:31:07 +0000907 if (ALoc.isNamedRef()) {
908 if (isa<ObjCInterfaceDecl>(Dcl)) {
909 CXCursor C = { CXCursor_ObjCClassRef, Dcl, ALoc.getParentDecl() };
910 return C;
911 }
912 if (isa<ObjCProtocolDecl>(Dcl)) {
913 CXCursor C = { CXCursor_ObjCProtocolRef, Dcl, ALoc.getParentDecl() };
914 return C;
915 }
916 }
Daniel Dunbaracca7252009-11-30 20:42:49 +0000917 CXCursor C = { TranslateKind(Dcl), Dcl, 0 };
Steve Naroff77128dd2009-09-15 20:25:34 +0000918 return C;
919 }
Steve Narofffb570422009-09-22 19:25:29 +0000920 CXCursor C = { CXCursor_NoDeclFound, 0, 0 };
Steve Naroff9efa7672009-09-04 15:44:05 +0000921 return C;
Steve Naroff600866c2009-08-27 19:51:58 +0000922}
923
Ted Kremenek73885552009-11-17 19:28:59 +0000924CXCursor clang_getNullCursor(void) {
925 CXCursor C;
926 C.kind = CXCursor_InvalidFile;
927 C.decl = NULL;
928 C.stmt = NULL;
929 return C;
930}
931
932unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
933 return X.kind == Y.kind && X.decl == Y.decl && X.stmt == Y.stmt;
934}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000935
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000936CXCursor clang_getCursorFromDecl(CXDecl AnonDecl) {
Steve Naroff77128dd2009-09-15 20:25:34 +0000937 assert(AnonDecl && "Passed null CXDecl");
938 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000939
Steve Narofffb570422009-09-22 19:25:29 +0000940 CXCursor C = { TranslateKind(ND), ND, 0 };
Steve Naroff77128dd2009-09-15 20:25:34 +0000941 return C;
942}
943
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000944unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +0000945 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
946}
947
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000948unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +0000949 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
950}
Steve Naroff2d4d6292009-08-31 14:26:51 +0000951
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000952unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +0000953 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
954}
955
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000956unsigned clang_isDefinition(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +0000957 return K >= CXCursor_FirstDefn && K <= CXCursor_LastDefn;
958}
959
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000960CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +0000961 return C.kind;
962}
963
Steve Naroff699a07d2009-09-25 21:32:34 +0000964static Decl *getDeclFromExpr(Stmt *E) {
965 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
966 return RefExpr->getDecl();
967 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
968 return ME->getMemberDecl();
969 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
970 return RE->getDecl();
971
972 if (CallExpr *CE = dyn_cast<CallExpr>(E))
973 return getDeclFromExpr(CE->getCallee());
974 if (CastExpr *CE = dyn_cast<CastExpr>(E))
975 return getDeclFromExpr(CE->getSubExpr());
976 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
977 return OME->getMethodDecl();
978
979 return 0;
980}
981
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000982CXDecl clang_getCursorDecl(CXCursor C) {
Steve Naroff699a07d2009-09-25 21:32:34 +0000983 if (clang_isDeclaration(C.kind))
984 return C.decl;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000985
Steve Naroff699a07d2009-09-25 21:32:34 +0000986 if (clang_isReference(C.kind)) {
Steve Naroff85e2db72009-10-01 00:31:07 +0000987 if (C.stmt) {
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000988 if (C.kind == CXCursor_ObjCClassRef ||
Steve Narofff9adf8f2009-10-05 17:58:19 +0000989 C.kind == CXCursor_ObjCProtocolRef)
Steve Naroff85e2db72009-10-01 00:31:07 +0000990 return static_cast<Stmt *>(C.stmt);
991 else
992 return getDeclFromExpr(static_cast<Stmt *>(C.stmt));
993 } else
Steve Naroff699a07d2009-09-25 21:32:34 +0000994 return C.decl;
995 }
996 return 0;
Steve Naroff9efa7672009-09-04 15:44:05 +0000997}
998
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000999unsigned clang_getCursorLine(CXCursor C) {
Steve Naroff2d4d6292009-08-31 14:26:51 +00001000 assert(C.decl && "CXCursor has null decl");
1001 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
Steve Naroff2d4d6292009-08-31 14:26:51 +00001002 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001003
Steve Narofff334b4e2009-09-02 18:26:48 +00001004 SourceLocation SLoc = getLocationFromCursor(C, SourceMgr, ND);
Steve Naroff2d4d6292009-08-31 14:26:51 +00001005 return SourceMgr.getSpellingLineNumber(SLoc);
Steve Naroff600866c2009-08-27 19:51:58 +00001006}
Steve Narofff334b4e2009-09-02 18:26:48 +00001007
Steve Naroffef0cef62009-11-09 17:45:52 +00001008const char *clang_getCString(CXString string) {
1009 return string.Spelling;
1010}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001011
Steve Naroffef0cef62009-11-09 17:45:52 +00001012void clang_disposeString(CXString string) {
Benjamin Kramer858e5de2009-11-09 18:24:53 +00001013 if (string.MustFreeString)
1014 free((void*)string.Spelling);
Steve Naroffef0cef62009-11-09 17:45:52 +00001015}
1016
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001017unsigned clang_getCursorColumn(CXCursor C) {
Steve Naroff2d4d6292009-08-31 14:26:51 +00001018 assert(C.decl && "CXCursor has null decl");
1019 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
Steve Naroff2d4d6292009-08-31 14:26:51 +00001020 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001021
Steve Narofff334b4e2009-09-02 18:26:48 +00001022 SourceLocation SLoc = getLocationFromCursor(C, SourceMgr, ND);
Steve Naroff2d4d6292009-08-31 14:26:51 +00001023 return SourceMgr.getSpellingColumnNumber(SLoc);
Steve Naroff600866c2009-08-27 19:51:58 +00001024}
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001025
1026const char *clang_getCursorSource(CXCursor C) {
Steve Naroff2d4d6292009-08-31 14:26:51 +00001027 assert(C.decl && "CXCursor has null decl");
1028 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
Steve Naroff2d4d6292009-08-31 14:26:51 +00001029 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001030
Steve Narofff334b4e2009-09-02 18:26:48 +00001031 SourceLocation SLoc = getLocationFromCursor(C, SourceMgr, ND);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001032
Ted Kremenek9298cfc2009-11-17 05:31:58 +00001033 if (SLoc.isFileID()) {
1034 const char *bufferName = SourceMgr.getBufferName(SLoc);
1035 return bufferName[0] == '<' ? NULL : bufferName;
1036 }
Douglas Gregor02465752009-10-16 21:24:31 +00001037
1038 // Retrieve the file in which the macro was instantiated, then provide that
1039 // buffer name.
1040 // FIXME: Do we want to give specific macro-instantiation information?
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001041 const llvm::MemoryBuffer *Buffer
Douglas Gregor02465752009-10-16 21:24:31 +00001042 = SourceMgr.getBuffer(SourceMgr.getDecomposedSpellingLoc(SLoc).first);
1043 if (!Buffer)
1044 return 0;
1045
1046 return Buffer->getBufferIdentifier();
Steve Naroff600866c2009-08-27 19:51:58 +00001047}
1048
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001049CXFile clang_getCursorSourceFile(CXCursor C) {
Steve Naroff88145032009-10-27 14:35:18 +00001050 assert(C.decl && "CXCursor has null decl");
1051 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
1052 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001053
Steve Naroff88145032009-10-27 14:35:18 +00001054 return (void *)getFileEntryFromSourceLocation(SourceMgr,
Daniel Dunbaracca7252009-11-30 20:42:49 +00001055 getLocationFromCursor(C,SourceMgr, ND));
Steve Naroff88145032009-10-27 14:35:18 +00001056}
1057
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001058void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00001059 const char **startBuf,
1060 const char **endBuf,
1061 unsigned *startLine,
1062 unsigned *startColumn,
1063 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001064 unsigned *endColumn) {
Steve Naroff4ade6d62009-09-23 17:52:52 +00001065 assert(C.decl && "CXCursor has null decl");
1066 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
1067 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
1068 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001069
Steve Naroff4ade6d62009-09-23 17:52:52 +00001070 SourceManager &SM = FD->getASTContext().getSourceManager();
1071 *startBuf = SM.getCharacterData(Body->getLBracLoc());
1072 *endBuf = SM.getCharacterData(Body->getRBracLoc());
1073 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
1074 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
1075 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
1076 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
1077}
1078
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001079enum CXCompletionChunkKind
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001080clang_getCompletionChunkKind(CXCompletionString completion_string,
1081 unsigned chunk_number) {
1082 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
1083 if (!CCStr || chunk_number >= CCStr->size())
1084 return CXCompletionChunk_Text;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001085
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001086 switch ((*CCStr)[chunk_number].Kind) {
1087 case CodeCompletionString::CK_TypedText:
1088 return CXCompletionChunk_TypedText;
1089 case CodeCompletionString::CK_Text:
1090 return CXCompletionChunk_Text;
1091 case CodeCompletionString::CK_Optional:
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001092 return CXCompletionChunk_Optional;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001093 case CodeCompletionString::CK_Placeholder:
1094 return CXCompletionChunk_Placeholder;
1095 case CodeCompletionString::CK_Informative:
1096 return CXCompletionChunk_Informative;
1097 case CodeCompletionString::CK_CurrentParameter:
1098 return CXCompletionChunk_CurrentParameter;
1099 case CodeCompletionString::CK_LeftParen:
1100 return CXCompletionChunk_LeftParen;
1101 case CodeCompletionString::CK_RightParen:
1102 return CXCompletionChunk_RightParen;
1103 case CodeCompletionString::CK_LeftBracket:
1104 return CXCompletionChunk_LeftBracket;
1105 case CodeCompletionString::CK_RightBracket:
1106 return CXCompletionChunk_RightBracket;
1107 case CodeCompletionString::CK_LeftBrace:
1108 return CXCompletionChunk_LeftBrace;
1109 case CodeCompletionString::CK_RightBrace:
1110 return CXCompletionChunk_RightBrace;
1111 case CodeCompletionString::CK_LeftAngle:
1112 return CXCompletionChunk_LeftAngle;
1113 case CodeCompletionString::CK_RightAngle:
1114 return CXCompletionChunk_RightAngle;
1115 case CodeCompletionString::CK_Comma:
1116 return CXCompletionChunk_Comma;
1117 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001118
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001119 // Should be unreachable, but let's be careful.
1120 return CXCompletionChunk_Text;
1121}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001122
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001123const char *clang_getCompletionChunkText(CXCompletionString completion_string,
1124 unsigned chunk_number) {
1125 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
1126 if (!CCStr || chunk_number >= CCStr->size())
1127 return 0;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001128
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001129 switch ((*CCStr)[chunk_number].Kind) {
1130 case CodeCompletionString::CK_TypedText:
1131 case CodeCompletionString::CK_Text:
1132 case CodeCompletionString::CK_Placeholder:
1133 case CodeCompletionString::CK_CurrentParameter:
1134 case CodeCompletionString::CK_Informative:
1135 case CodeCompletionString::CK_LeftParen:
1136 case CodeCompletionString::CK_RightParen:
1137 case CodeCompletionString::CK_LeftBracket:
1138 case CodeCompletionString::CK_RightBracket:
1139 case CodeCompletionString::CK_LeftBrace:
1140 case CodeCompletionString::CK_RightBrace:
1141 case CodeCompletionString::CK_LeftAngle:
1142 case CodeCompletionString::CK_RightAngle:
1143 case CodeCompletionString::CK_Comma:
1144 return (*CCStr)[chunk_number].Text;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001145
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001146 case CodeCompletionString::CK_Optional:
1147 // Note: treated as an empty text block.
1148 return 0;
1149 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001150
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001151 // Should be unreachable, but let's be careful.
1152 return 0;
1153}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001154
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001155CXCompletionString
1156clang_getCompletionChunkCompletionString(CXCompletionString completion_string,
1157 unsigned chunk_number) {
1158 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
1159 if (!CCStr || chunk_number >= CCStr->size())
1160 return 0;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001161
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001162 switch ((*CCStr)[chunk_number].Kind) {
1163 case CodeCompletionString::CK_TypedText:
1164 case CodeCompletionString::CK_Text:
1165 case CodeCompletionString::CK_Placeholder:
1166 case CodeCompletionString::CK_CurrentParameter:
1167 case CodeCompletionString::CK_Informative:
1168 case CodeCompletionString::CK_LeftParen:
1169 case CodeCompletionString::CK_RightParen:
1170 case CodeCompletionString::CK_LeftBracket:
1171 case CodeCompletionString::CK_RightBracket:
1172 case CodeCompletionString::CK_LeftBrace:
1173 case CodeCompletionString::CK_RightBrace:
1174 case CodeCompletionString::CK_LeftAngle:
1175 case CodeCompletionString::CK_RightAngle:
1176 case CodeCompletionString::CK_Comma:
1177 return 0;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001178
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001179 case CodeCompletionString::CK_Optional:
1180 // Note: treated as an empty text block.
1181 return (*CCStr)[chunk_number].Optional;
1182 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001183
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001184 // Should be unreachable, but let's be careful.
1185 return 0;
1186}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001187
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001188unsigned clang_getNumCompletionChunks(CXCompletionString completion_string) {
1189 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
1190 return CCStr? CCStr->size() : 0;
1191}
Steve Naroff4ade6d62009-09-23 17:52:52 +00001192
Douglas Gregor2b4074f2009-12-01 05:55:20 +00001193static bool ReadUnsigned(const char *&Memory, const char *MemoryEnd,
1194 unsigned &Value) {
1195 if (Memory + sizeof(unsigned) > MemoryEnd)
1196 return true;
1197
1198 memmove(&Value, Memory, sizeof(unsigned));
1199 Memory += sizeof(unsigned);
1200 return false;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001201}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001202
1203void clang_codeComplete(CXIndex CIdx,
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001204 const char *source_filename,
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001205 int num_command_line_args,
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001206 const char **command_line_args,
Douglas Gregor735df882009-12-02 09:21:34 +00001207 unsigned num_unsaved_files,
1208 struct CXUnsavedFile *unsaved_files,
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001209 const char *complete_filename,
1210 unsigned complete_line,
1211 unsigned complete_column,
1212 CXCompletionIterator completion_iterator,
1213 CXClientData client_data) {
1214 // The indexer, which is mainly used to determine where diagnostics go.
1215 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001216
Douglas Gregor735df882009-12-02 09:21:34 +00001217 // The set of temporary files that we've built.
1218 std::vector<llvm::sys::Path> TemporaryFiles;
1219
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001220 // Build up the arguments for invoking 'clang'.
1221 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001222
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001223 // First add the complete path to the 'clang' executable.
1224 llvm::sys::Path ClangPath = CXXIdx->getClangPath();
1225 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001226
1227 // Add the '-fsyntax-only' argument so that we only perform a basic
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001228 // syntax check of the code.
1229 argv.push_back("-fsyntax-only");
1230
1231 // Add the appropriate '-code-completion-at=file:line:column' argument
1232 // to perform code completion, with an "-Xclang" preceding it.
1233 std::string code_complete_at;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001234 code_complete_at += complete_filename;
1235 code_complete_at += ":";
1236 code_complete_at += llvm::utostr(complete_line);
1237 code_complete_at += ":";
1238 code_complete_at += llvm::utostr(complete_column);
1239 argv.push_back("-Xclang");
Daniel Dunbar7bd71652009-12-03 05:32:40 +00001240 argv.push_back("-code-completion-at");
1241 argv.push_back("-Xclang");
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001242 argv.push_back(code_complete_at.c_str());
1243 argv.push_back("-Xclang");
Daniel Dunbar4db166b2009-11-19 05:32:09 +00001244 argv.push_back("-no-code-completion-debug-printer");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001245
Douglas Gregor735df882009-12-02 09:21:34 +00001246 std::vector<std::string> RemapArgs;
1247 for (unsigned i = 0; i != num_unsaved_files; ++i) {
1248 char tmpFile[L_tmpnam];
1249 char *tmpFileName = tmpnam(tmpFile);
1250
1251 // Write the contents of this unsaved file into the temporary file.
1252 llvm::sys::Path SavedFile(tmpFileName);
1253 std::string ErrorInfo;
1254 llvm::raw_fd_ostream OS(SavedFile.c_str(), ErrorInfo);
1255 if (!ErrorInfo.empty())
1256 continue;
1257
1258 OS.write(unsaved_files[i].Contents, unsaved_files[i].Length);
1259 OS.close();
1260 if (OS.has_error()) {
1261 SavedFile.eraseFromDisk();
1262 continue;
1263 }
1264
1265 // Remap the file.
Daniel Dunbar7bd71652009-12-03 05:32:40 +00001266 std::string RemapArg = unsaved_files[i].Filename;
Douglas Gregor735df882009-12-02 09:21:34 +00001267 RemapArg += ';';
1268 RemapArg += tmpFileName;
1269 RemapArgs.push_back("-Xclang");
Daniel Dunbar7bd71652009-12-03 05:32:40 +00001270 RemapArgs.push_back("-remap-file");
1271 RemapArgs.push_back("-Xclang");
Douglas Gregor735df882009-12-02 09:21:34 +00001272 RemapArgs.push_back(RemapArg);
1273 TemporaryFiles.push_back(SavedFile);
1274 }
1275
1276 // The pointers into the elements of RemapArgs are stable because we
1277 // won't be adding anything to RemapArgs after this point.
1278 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1279 argv.push_back(RemapArgs[i].c_str());
1280
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001281 // Add the source file name (FIXME: later, we'll want to build temporary
1282 // file from the buffer, or just feed the source text via standard input).
Ted Kremenek4633d1b2009-11-17 18:18:02 +00001283 if (source_filename)
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001284 argv.push_back(source_filename);
1285
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001286 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1287 for (int i = 0; i < num_command_line_args; ++i)
1288 if (const char *arg = command_line_args[i]) {
1289 if (strcmp(arg, "-o") == 0) {
1290 ++i; // Also skip the matching argument.
1291 continue;
1292 }
1293 if (strcmp(arg, "-emit-ast") == 0 ||
1294 strcmp(arg, "-c") == 0 ||
1295 strcmp(arg, "-fsyntax-only") == 0) {
1296 continue;
1297 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001298
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001299 // Keep the argument.
1300 argv.push_back(arg);
1301 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001302
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001303 // Add the null terminator.
1304 argv.push_back(NULL);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001305
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001306 // Generate a temporary name for the AST file.
1307 char tmpFile[L_tmpnam];
1308 char *tmpFileName = tmpnam(tmpFile);
1309 llvm::sys::Path ResultsFile(tmpFileName);
Douglas Gregor735df882009-12-02 09:21:34 +00001310 TemporaryFiles.push_back(ResultsFile);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001311
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001312 // Invoke 'clang'.
1313 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1314 // on Unix or NUL (Windows).
1315 std::string ErrMsg;
1316 const llvm::sys::Path *Redirects[] = { &DevNull, &ResultsFile, &DevNull, 0 };
1317 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
1318 /* redirects */ &Redirects[0],
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001319 /* secondsToWait */ 0,
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001320 /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001321
Ted Kremenek0854d702009-11-10 19:18:52 +00001322 if (CXXIdx->getDisplayDiagnostics() && !ErrMsg.empty()) {
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001323 llvm::errs() << "clang_codeComplete: " << ErrMsg
Daniel Dunbaracca7252009-11-30 20:42:49 +00001324 << '\n' << "Arguments: \n";
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001325 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
1326 I!=E; ++I) {
1327 if (*I)
1328 llvm::errs() << ' ' << *I << '\n';
1329 }
1330 llvm::errs() << '\n';
1331 }
1332
1333 // Parse the resulting source file to find code-completion results.
1334 using llvm::MemoryBuffer;
1335 using llvm::StringRef;
1336 if (MemoryBuffer *F = MemoryBuffer::getFile(ResultsFile.c_str())) {
1337 StringRef Buffer = F->getBuffer();
Douglas Gregor2b4074f2009-12-01 05:55:20 +00001338 for (const char *Str = Buffer.data(), *StrEnd = Str + Buffer.size();
1339 Str < StrEnd;) {
1340 unsigned KindValue;
1341 if (ReadUnsigned(Str, StrEnd, KindValue))
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001342 break;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001343
Douglas Gregor2b4074f2009-12-01 05:55:20 +00001344 CodeCompletionString *CCStr
1345 = CodeCompletionString::Deserialize(Str, StrEnd);
1346 if (!CCStr)
1347 continue;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001348
Douglas Gregor2b4074f2009-12-01 05:55:20 +00001349 if (!CCStr->empty()) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001350 // Vend the code-completion result to the caller.
1351 CXCompletionResult Result;
Douglas Gregor2b4074f2009-12-01 05:55:20 +00001352 Result.CursorKind = (CXCursorKind)KindValue;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001353 Result.CompletionString = CCStr;
1354 if (completion_iterator)
1355 completion_iterator(&Result, client_data);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001356 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001357
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001358 delete CCStr;
Douglas Gregor2b4074f2009-12-01 05:55:20 +00001359 };
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001360 delete F;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001361 }
1362
Douglas Gregor735df882009-12-02 09:21:34 +00001363 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1364 TemporaryFiles[i].eraseFromDisk();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001365}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001366
Steve Naroff600866c2009-08-27 19:51:58 +00001367} // end extern "C"