blob: fe3aa376941408af88c6ac94171585cfdf2cdacc [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"
Daniel Dunbar869824e2009-12-13 03:46:13 +000015#include "clang/AST/Decl.h"
Steve Naroff50398192009-08-28 15:28:48 +000016#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000017#include "clang/AST/StmtVisitor.h"
Benjamin Kramerd01a0bc2009-08-29 12:56:35 +000018#include "clang/Basic/FileManager.h"
Steve Naroff2d4d6292009-08-31 14:26:51 +000019#include "clang/Basic/SourceManager.h"
Daniel Dunbar869824e2009-12-13 03:46:13 +000020#include "clang/Basic/Version.h"
Benjamin Kramerd01a0bc2009-08-29 12:56:35 +000021#include "clang/Frontend/ASTUnit.h"
Daniel Dunbar5262fda2009-12-03 01:45:44 +000022#include "clang/Frontend/CompilerInstance.h"
Daniel Dunbar869824e2009-12-13 03:46:13 +000023#include "clang/Index/ASTLocation.h"
24#include "clang/Index/Indexer.h"
25#include "clang/Index/Program.h"
26#include "clang/Index/Utils.h"
27#include "clang/Sema/CodeCompleteConsumer.h"
Douglas Gregor0c8296d2009-11-07 00:00:49 +000028#include "llvm/ADT/StringExtras.h"
Benjamin Kramer20d75812009-10-18 16:13:48 +000029#include "llvm/Config/config.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000030#include "llvm/Support/Compiler.h"
Douglas Gregor02465752009-10-16 21:24:31 +000031#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar869824e2009-12-13 03:46:13 +000032#include "llvm/Support/raw_ostream.h"
Douglas Gregor02465752009-10-16 21:24:31 +000033#include "llvm/System/Path.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000034#include "llvm/System/Program.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000035
Benjamin Kramerd01a0bc2009-08-29 12:56:35 +000036#include <cstdio>
Ted Kremenek49358d82009-10-19 21:17:25 +000037#include <vector>
Douglas Gregor0c8296d2009-11-07 00:00:49 +000038#include <sstream>
Ted Kremenek49358d82009-10-19 21:17:25 +000039
Benjamin Kramer20d75812009-10-18 16:13:48 +000040#ifdef LLVM_ON_WIN32
41#define WIN32_LEAN_AND_MEAN
42#include <windows.h>
43#else
Steve Naroff5b7d8e22009-10-15 20:04:39 +000044#include <dlfcn.h>
Daniel Dunbara47dd192009-10-17 23:53:11 +000045#endif
Steve Naroff5b7d8e22009-10-15 20:04:39 +000046
Steve Naroff50398192009-08-28 15:28:48 +000047using namespace clang;
48using namespace idx;
49
Steve Naroff89922f82009-08-31 00:59:03 +000050namespace {
Daniel Dunbar0d7dd222009-11-30 20:42:43 +000051static enum CXCursorKind TranslateDeclRefExpr(DeclRefExpr *DRE)
Steve Naroff4ade6d62009-09-23 17:52:52 +000052{
53 NamedDecl *D = DRE->getDecl();
54 if (isa<VarDecl>(D))
55 return CXCursor_VarRef;
56 else if (isa<FunctionDecl>(D))
57 return CXCursor_FunctionRef;
58 else if (isa<EnumConstantDecl>(D))
59 return CXCursor_EnumConstantRef;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +000060 else
Steve Naroff4ade6d62009-09-23 17:52:52 +000061 return CXCursor_NotImplemented;
62}
63
64#if 0
65// Will be useful one day.
Steve Narofffb570422009-09-22 19:25:29 +000066class CRefVisitor : public StmtVisitor<CRefVisitor> {
67 CXDecl CDecl;
68 CXDeclIterator Callback;
69 CXClientData CData;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +000070
Steve Narofffb570422009-09-22 19:25:29 +000071 void Call(enum CXCursorKind CK, Stmt *SRef) {
72 CXCursor C = { CK, CDecl, SRef };
73 Callback(CDecl, C, CData);
74 }
75
76public:
Daniel Dunbar0d7dd222009-11-30 20:42:43 +000077 CRefVisitor(CXDecl C, CXDeclIterator cback, CXClientData D) :
Steve Narofffb570422009-09-22 19:25:29 +000078 CDecl(C), Callback(cback), CData(D) {}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +000079
Steve Narofffb570422009-09-22 19:25:29 +000080 void VisitStmt(Stmt *S) {
81 for (Stmt::child_iterator C = S->child_begin(), CEnd = S->child_end();
82 C != CEnd; ++C)
83 Visit(*C);
84 }
85 void VisitDeclRefExpr(DeclRefExpr *Node) {
Steve Naroff4ade6d62009-09-23 17:52:52 +000086 Call(TranslateDeclRefExpr(Node), Node);
Steve Narofffb570422009-09-22 19:25:29 +000087 }
88 void VisitMemberExpr(MemberExpr *Node) {
89 Call(CXCursor_MemberRef, Node);
90 }
91 void VisitObjCMessageExpr(ObjCMessageExpr *Node) {
92 Call(CXCursor_ObjCSelectorRef, Node);
93 }
94 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *Node) {
95 Call(CXCursor_ObjCIvarRef, Node);
96 }
97};
Steve Naroff4ade6d62009-09-23 17:52:52 +000098#endif
Daniel Dunbar0d7dd222009-11-30 20:42:43 +000099
Ted Kremenekfc062212009-10-19 21:44:57 +0000100/// IgnoreDiagnosticsClient - A DiagnosticsClient that just ignores emitted
101/// warnings and errors.
102class VISIBILITY_HIDDEN IgnoreDiagnosticsClient : public DiagnosticClient {
103public:
104 virtual ~IgnoreDiagnosticsClient() {}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000105 virtual void HandleDiagnostic(Diagnostic::Level, const DiagnosticInfo &) {}
Ted Kremenekfc062212009-10-19 21:44:57 +0000106};
Steve Narofffb570422009-09-22 19:25:29 +0000107
Steve Naroff89922f82009-08-31 00:59:03 +0000108// Translation Unit Visitor.
109class TUVisitor : public DeclVisitor<TUVisitor> {
110 CXTranslationUnit TUnit;
111 CXTranslationUnitIterator Callback;
Steve Naroff2b8ee6c2009-09-01 15:55:40 +0000112 CXClientData CData;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000113
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000114 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
115 // to the visitor. Declarations with a PCH level greater than this value will
116 // be suppressed.
117 unsigned MaxPCHLevel;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000118
Steve Naroff2b8ee6c2009-09-01 15:55:40 +0000119 void Call(enum CXCursorKind CK, NamedDecl *ND) {
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000120 // Filter any declarations that have a PCH level greater than what we allow.
121 if (ND->getPCHLevel() > MaxPCHLevel)
122 return;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000123
Steve Narofff96b5242009-10-28 20:44:47 +0000124 // Filter any implicit declarations (since the source info will be bogus).
125 if (ND->isImplicit())
126 return;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000127
Steve Narofffb570422009-09-22 19:25:29 +0000128 CXCursor C = { CK, ND, 0 };
Steve Naroff2b8ee6c2009-09-01 15:55:40 +0000129 Callback(TUnit, C, CData);
130 }
Steve Naroff89922f82009-08-31 00:59:03 +0000131public:
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000132 TUVisitor(CXTranslationUnit CTU,
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000133 CXTranslationUnitIterator cback, CXClientData D,
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000134 unsigned MaxPCHLevel) :
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000135 TUnit(CTU), Callback(cback), CData(D), MaxPCHLevel(MaxPCHLevel) {}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000136
Steve Naroff89922f82009-08-31 00:59:03 +0000137 void VisitTranslationUnitDecl(TranslationUnitDecl *D) {
138 VisitDeclContext(dyn_cast<DeclContext>(D));
139 }
140 void VisitDeclContext(DeclContext *DC) {
141 for (DeclContext::decl_iterator
142 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I)
143 Visit(*I);
144 }
Ted Kremenekef7fdc62009-11-17 07:02:15 +0000145
146 void VisitFunctionDecl(FunctionDecl *ND) {
147 Call(ND->isThisDeclarationADefinition() ? CXCursor_FunctionDefn
148 : CXCursor_FunctionDecl, ND);
149 }
150 void VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
151 Call(CXCursor_ObjCCategoryDecl, ND);
152 }
153 void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *ND) {
154 Call(CXCursor_ObjCCategoryDefn, ND);
155 }
156 void VisitObjCImplementationDecl(ObjCImplementationDecl *ND) {
157 Call(CXCursor_ObjCClassDefn, ND);
158 }
159 void VisitObjCInterfaceDecl(ObjCInterfaceDecl *ND) {
160 Call(CXCursor_ObjCInterfaceDecl, ND);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000161 }
Ted Kremenekef7fdc62009-11-17 07:02:15 +0000162 void VisitObjCProtocolDecl(ObjCProtocolDecl *ND) {
163 Call(CXCursor_ObjCProtocolDecl, ND);
Steve Naroff89922f82009-08-31 00:59:03 +0000164 }
165 void VisitTagDecl(TagDecl *ND) {
Steve Naroffc857ea42009-09-02 13:28:54 +0000166 switch (ND->getTagKind()) {
Daniel Dunbaracca7252009-11-30 20:42:49 +0000167 case TagDecl::TK_struct:
168 Call(CXCursor_StructDecl, ND);
169 break;
170 case TagDecl::TK_class:
171 Call(CXCursor_ClassDecl, ND);
172 break;
173 case TagDecl::TK_union:
174 Call(CXCursor_UnionDecl, ND);
175 break;
176 case TagDecl::TK_enum:
177 Call(CXCursor_EnumDecl, ND);
178 break;
Steve Naroffc857ea42009-09-02 13:28:54 +0000179 }
Steve Naroff89922f82009-08-31 00:59:03 +0000180 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000181 void VisitTypedefDecl(TypedefDecl *ND) {
182 Call(CXCursor_TypedefDecl, ND);
183 }
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000184 void VisitVarDecl(VarDecl *ND) {
185 Call(CXCursor_VarDecl, ND);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000186 }
Steve Naroff89922f82009-08-31 00:59:03 +0000187};
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000188
Steve Naroff89922f82009-08-31 00:59:03 +0000189
Steve Naroffc857ea42009-09-02 13:28:54 +0000190// Declaration visitor.
191class CDeclVisitor : public DeclVisitor<CDeclVisitor> {
192 CXDecl CDecl;
193 CXDeclIterator Callback;
194 CXClientData CData;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000195
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000196 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
197 // to the visitor. Declarations with a PCH level greater than this value will
198 // be suppressed.
199 unsigned MaxPCHLevel;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000200
Steve Naroffc857ea42009-09-02 13:28:54 +0000201 void Call(enum CXCursorKind CK, NamedDecl *ND) {
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000202 // Disable the callback when the context is equal to the visiting decl.
203 if (CDecl == ND && !clang_isReference(CK))
204 return;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000205
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000206 // Filter any declarations that have a PCH level greater than what we allow.
207 if (ND->getPCHLevel() > MaxPCHLevel)
208 return;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000209
Steve Narofffb570422009-09-22 19:25:29 +0000210 CXCursor C = { CK, ND, 0 };
Steve Naroffc857ea42009-09-02 13:28:54 +0000211 Callback(CDecl, C, CData);
212 }
Steve Naroff89922f82009-08-31 00:59:03 +0000213public:
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000214 CDeclVisitor(CXDecl C, CXDeclIterator cback, CXClientData D,
215 unsigned MaxPCHLevel) :
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000216 CDecl(C), Callback(cback), CData(D), MaxPCHLevel(MaxPCHLevel) {}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000217
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000218 void VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
219 // Issue callbacks for the containing class.
220 Call(CXCursor_ObjCClassRef, ND);
221 // FIXME: Issue callbacks for protocol refs.
222 VisitDeclContext(dyn_cast<DeclContext>(ND));
223 }
Steve Naroffc857ea42009-09-02 13:28:54 +0000224 void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000225 // Issue callbacks for super class.
Steve Narofff334b4e2009-09-02 18:26:48 +0000226 if (D->getSuperClass())
227 Call(CXCursor_ObjCSuperClassRef, D);
228
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000229 for (ObjCProtocolDecl::protocol_iterator I = D->protocol_begin(),
Daniel Dunbaracca7252009-11-30 20:42:49 +0000230 E = D->protocol_end(); I != E; ++I)
Steve Naroff9efa7672009-09-04 15:44:05 +0000231 Call(CXCursor_ObjCProtocolRef, *I);
Steve Naroffc857ea42009-09-02 13:28:54 +0000232 VisitDeclContext(dyn_cast<DeclContext>(D));
233 }
Steve Naroff9efa7672009-09-04 15:44:05 +0000234 void VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000235 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
Daniel Dunbaracca7252009-11-30 20:42:49 +0000236 E = PID->protocol_end(); I != E; ++I)
Steve Naroff9efa7672009-09-04 15:44:05 +0000237 Call(CXCursor_ObjCProtocolRef, *I);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000238
Steve Naroff9efa7672009-09-04 15:44:05 +0000239 VisitDeclContext(dyn_cast<DeclContext>(PID));
240 }
Steve Naroffc857ea42009-09-02 13:28:54 +0000241 void VisitTagDecl(TagDecl *D) {
242 VisitDeclContext(dyn_cast<DeclContext>(D));
243 }
244 void VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
245 VisitDeclContext(dyn_cast<DeclContext>(D));
246 }
247 void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
248 VisitDeclContext(dyn_cast<DeclContext>(D));
249 }
Steve Naroff89922f82009-08-31 00:59:03 +0000250 void VisitDeclContext(DeclContext *DC) {
251 for (DeclContext::decl_iterator
252 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I)
253 Visit(*I);
254 }
255 void VisitEnumConstantDecl(EnumConstantDecl *ND) {
Steve Naroffc857ea42009-09-02 13:28:54 +0000256 Call(CXCursor_EnumConstantDecl, ND);
Steve Naroff89922f82009-08-31 00:59:03 +0000257 }
258 void VisitFieldDecl(FieldDecl *ND) {
Steve Naroffc857ea42009-09-02 13:28:54 +0000259 Call(CXCursor_FieldDecl, ND);
260 }
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000261 void VisitVarDecl(VarDecl *ND) {
262 Call(CXCursor_VarDecl, ND);
263 }
264 void VisitParmVarDecl(ParmVarDecl *ND) {
265 Call(CXCursor_ParmDecl, ND);
266 }
Steve Naroffc857ea42009-09-02 13:28:54 +0000267 void VisitObjCPropertyDecl(ObjCPropertyDecl *ND) {
268 Call(CXCursor_ObjCPropertyDecl, ND);
Steve Naroff89922f82009-08-31 00:59:03 +0000269 }
270 void VisitObjCIvarDecl(ObjCIvarDecl *ND) {
Steve Naroffc857ea42009-09-02 13:28:54 +0000271 Call(CXCursor_ObjCIvarDecl, ND);
272 }
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000273 void VisitFunctionDecl(FunctionDecl *ND) {
274 if (ND->isThisDeclarationADefinition()) {
275 VisitDeclContext(dyn_cast<DeclContext>(ND));
Steve Naroff4ade6d62009-09-23 17:52:52 +0000276#if 0
277 // Not currently needed.
278 CompoundStmt *Body = dyn_cast<CompoundStmt>(ND->getBody());
Steve Narofffb570422009-09-22 19:25:29 +0000279 CRefVisitor RVisit(CDecl, Callback, CData);
Steve Naroff4ade6d62009-09-23 17:52:52 +0000280 RVisit.Visit(Body);
281#endif
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000282 }
283 }
Steve Naroffc857ea42009-09-02 13:28:54 +0000284 void VisitObjCMethodDecl(ObjCMethodDecl *ND) {
285 if (ND->getBody()) {
286 Call(ND->isInstanceMethod() ? CXCursor_ObjCInstanceMethodDefn
287 : CXCursor_ObjCClassMethodDefn, ND);
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000288 VisitDeclContext(dyn_cast<DeclContext>(ND));
Steve Naroffc857ea42009-09-02 13:28:54 +0000289 } else
290 Call(ND->isInstanceMethod() ? CXCursor_ObjCInstanceMethodDecl
291 : CXCursor_ObjCClassMethodDecl, ND);
Steve Naroff89922f82009-08-31 00:59:03 +0000292 }
293};
294
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000295class CIndexer : public Indexer {
Daniel Dunbarbb3503a2009-12-06 09:56:30 +0000296 DiagnosticOptions DiagOpts;
Daniel Dunbar5262fda2009-12-03 01:45:44 +0000297 IgnoreDiagnosticsClient IgnoreDiagClient;
298 llvm::OwningPtr<Diagnostic> TextDiags;
299 Diagnostic IgnoreDiags;
300 bool UseExternalASTGeneration;
301 bool OnlyLocalDecls;
302 bool DisplayDiagnostics;
303
304 llvm::sys::Path ClangPath;
305
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000306public:
307 explicit CIndexer(Program *prog) : Indexer(*prog),
Daniel Dunbar5262fda2009-12-03 01:45:44 +0000308 IgnoreDiags(&IgnoreDiagClient),
309 UseExternalASTGeneration(false),
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000310 OnlyLocalDecls(false),
Daniel Dunbar5262fda2009-12-03 01:45:44 +0000311 DisplayDiagnostics(false) {
312 TextDiags.reset(
Daniel Dunbarbb3503a2009-12-06 09:56:30 +0000313 CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
Daniel Dunbar5262fda2009-12-03 01:45:44 +0000314 }
Ted Kremenekdff76892009-10-17 06:21:47 +0000315
316 virtual ~CIndexer() { delete &getProgram(); }
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000317
318 /// \brief Whether we only want to see "local" declarations (that did not
319 /// come from a previous precompiled header). If false, we want to see all
320 /// declarations.
321 bool getOnlyLocalDecls() const { return OnlyLocalDecls; }
322 void setOnlyLocalDecls(bool Local = true) { OnlyLocalDecls = Local; }
Benjamin Kramer96707622009-10-18 11:10:55 +0000323
Daniel Dunbar5262fda2009-12-03 01:45:44 +0000324 bool getDisplayDiagnostics() const { return DisplayDiagnostics; }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000325 void setDisplayDiagnostics(bool Display = true) {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000326 DisplayDiagnostics = Display;
327 }
Daniel Dunbar5262fda2009-12-03 01:45:44 +0000328
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000329 bool getUseExternalASTGeneration() const { return UseExternalASTGeneration; }
330 void setUseExternalASTGeneration(bool Value) {
331 UseExternalASTGeneration = Value;
332 }
333
Daniel Dunbar5262fda2009-12-03 01:45:44 +0000334 Diagnostic &getDiags() {
335 return DisplayDiagnostics ? *TextDiags : IgnoreDiags;
336 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000337
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000338 /// \brief Get the path of the clang binary.
Benjamin Kramerc5a9e952009-10-19 10:20:24 +0000339 const llvm::sys::Path& getClangPath();
Daniel Dunbar869824e2009-12-13 03:46:13 +0000340
341 /// \brief Get the path of the clang resource files.
342 std::string getClangResourcesPath();
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000343};
Steve Naroff89922f82009-08-31 00:59:03 +0000344
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000345const llvm::sys::Path& CIndexer::getClangPath() {
346 // Did we already compute the path?
347 if (!ClangPath.empty())
348 return ClangPath;
349
Steve Naroff5b7d8e22009-10-15 20:04:39 +0000350 // Find the location where this library lives (libCIndex.dylib).
Benjamin Kramer20d75812009-10-18 16:13:48 +0000351#ifdef LLVM_ON_WIN32
352 MEMORY_BASIC_INFORMATION mbi;
353 char path[MAX_PATH];
Benjamin Krameredcd8282009-10-18 16:20:58 +0000354 VirtualQuery((void *)(uintptr_t)clang_createTranslationUnit, &mbi,
Benjamin Kramer20d75812009-10-18 16:13:48 +0000355 sizeof(mbi));
356 GetModuleFileNameA((HINSTANCE)mbi.AllocationBase, path, MAX_PATH);
357
358 llvm::sys::Path CIndexPath(path);
John Thompson6a6742a2009-11-11 23:11:14 +0000359
360 CIndexPath.eraseComponent();
361 CIndexPath.appendComponent("clang");
362 CIndexPath.appendSuffix("exe");
363 CIndexPath.makeAbsolute();
Benjamin Kramer20d75812009-10-18 16:13:48 +0000364#else
Steve Naroff5b7d8e22009-10-15 20:04:39 +0000365 // This silly cast below avoids a C++ warning.
366 Dl_info info;
367 if (dladdr((void *)(uintptr_t)clang_createTranslationUnit, &info) == 0)
368 assert(0 && "Call to dladdr() failed");
369
370 llvm::sys::Path CIndexPath(info.dli_fname);
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000371
Steve Naroff5b7d8e22009-10-15 20:04:39 +0000372 // We now have the CIndex directory, locate clang relative to it.
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000373 CIndexPath.eraseComponent();
374 CIndexPath.eraseComponent();
375 CIndexPath.appendComponent("bin");
376 CIndexPath.appendComponent("clang");
John Thompson6a6742a2009-11-11 23:11:14 +0000377#endif
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000378
379 // Cache our result.
380 ClangPath = CIndexPath;
381 return ClangPath;
382}
383
Daniel Dunbar869824e2009-12-13 03:46:13 +0000384std::string CIndexer::getClangResourcesPath() {
385 llvm::sys::Path P = getClangPath();
386
387 if (!P.empty()) {
388 P.eraseComponent(); // Remove /clang from foo/bin/clang
389 P.eraseComponent(); // Remove /bin from foo/bin
390
391 // Get foo/lib/clang/<version>/include
392 P.appendComponent("lib");
393 P.appendComponent("clang");
394 P.appendComponent(CLANG_VERSION_STRING);
395 }
396
397 return P.str();
398}
399
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000400}
401
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000402static SourceLocation getLocationFromCursor(CXCursor C,
Daniel Dunbarc6190332009-11-08 04:13:53 +0000403 SourceManager &SourceMgr,
404 NamedDecl *ND) {
405 if (clang_isReference(C.kind)) {
406 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +0000407 case CXCursor_ObjCClassRef: {
408 if (isa<ObjCInterfaceDecl>(ND)) {
409 // FIXME: This is a hack (storing the parent decl in the stmt slot).
410 NamedDecl *parentDecl = static_cast<NamedDecl *>(C.stmt);
411 return parentDecl->getLocation();
Daniel Dunbarc6190332009-11-08 04:13:53 +0000412 }
Daniel Dunbaracca7252009-11-30 20:42:49 +0000413 ObjCCategoryDecl *OID = dyn_cast<ObjCCategoryDecl>(ND);
414 assert(OID && "clang_getCursorLine(): Missing category decl");
415 return OID->getClassInterface()->getLocation();
416 }
417 case CXCursor_ObjCSuperClassRef: {
418 ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ND);
419 assert(OID && "clang_getCursorLine(): Missing interface decl");
420 return OID->getSuperClassLoc();
421 }
422 case CXCursor_ObjCProtocolRef: {
423 ObjCProtocolDecl *OID = dyn_cast<ObjCProtocolDecl>(ND);
424 assert(OID && "clang_getCursorLine(): Missing protocol decl");
425 return OID->getLocation();
426 }
427 case CXCursor_ObjCSelectorRef: {
428 ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(
429 static_cast<Stmt *>(C.stmt));
430 assert(OME && "clang_getCursorLine(): Missing message expr");
431 return OME->getLeftLoc(); /* FIXME: should be a range */
432 }
433 case CXCursor_VarRef:
434 case CXCursor_FunctionRef:
435 case CXCursor_EnumConstantRef: {
436 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(
437 static_cast<Stmt *>(C.stmt));
438 assert(DRE && "clang_getCursorLine(): Missing decl ref expr");
439 return DRE->getLocation();
440 }
441 default:
442 return SourceLocation();
Daniel Dunbarc6190332009-11-08 04:13:53 +0000443 }
444 } else { // We have a declaration or a definition.
445 SourceLocation SLoc;
446 switch (ND->getKind()) {
Daniel Dunbaracca7252009-11-30 20:42:49 +0000447 case Decl::ObjCInterface: {
448 SLoc = dyn_cast<ObjCInterfaceDecl>(ND)->getClassLoc();
449 break;
450 }
451 case Decl::ObjCProtocol: {
452 SLoc = ND->getLocation(); /* FIXME: need to get the name location. */
453 break;
454 }
455 default: {
456 SLoc = ND->getLocation();
457 break;
458 }
Daniel Dunbarc6190332009-11-08 04:13:53 +0000459 }
460 if (SLoc.isInvalid())
461 return SourceLocation();
462 return SourceMgr.getSpellingLoc(SLoc); // handles macro instantiations.
463 }
464}
465
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000466static CXString createCXString(const char *String, bool DupString = false) {
467 CXString Str;
468 if (DupString) {
469 Str.Spelling = strdup(String);
470 Str.MustFreeString = 1;
471 } else {
472 Str.Spelling = String;
473 Str.MustFreeString = 0;
474 }
475 return Str;
476}
477
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000478extern "C" {
479
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000480CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000481 int displayDiagnostics) {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000482 CIndexer *CIdxr = new CIndexer(new Program());
483 if (excludeDeclarationsFromPCH)
484 CIdxr->setOnlyLocalDecls();
485 if (displayDiagnostics)
486 CIdxr->setDisplayDiagnostics();
487 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +0000488}
489
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000490void clang_disposeIndex(CXIndex CIdx) {
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000491 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000492 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000493}
494
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000495void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
496 assert(CIdx && "Passed null CXIndex");
497 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
498 CXXIdx->setUseExternalASTGeneration(value);
499}
500
Steve Naroff50398192009-08-28 15:28:48 +0000501// FIXME: need to pass back error info.
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000502CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
503 const char *ast_filename) {
Steve Naroff50398192009-08-28 15:28:48 +0000504 assert(CIdx && "Passed null CXIndex");
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000505 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000506
Daniel Dunbar5262fda2009-12-03 01:45:44 +0000507 return ASTUnit::LoadFromPCHFile(ast_filename, CXXIdx->getDiags(),
508 CXXIdx->getOnlyLocalDecls(),
509 /* UseBumpAllocator = */ true);
Steve Naroff600866c2009-08-27 19:51:58 +0000510}
511
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000512CXTranslationUnit
513clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
514 const char *source_filename,
515 int num_command_line_args,
516 const char **command_line_args) {
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000517 assert(CIdx && "Passed null CXIndex");
518 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
519
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000520 if (!CXXIdx->getUseExternalASTGeneration()) {
521 llvm::SmallVector<const char *, 16> Args;
522
523 // The 'source_filename' argument is optional. If the caller does not
524 // specify it then it is assumed that the source file is specified
525 // in the actual argument list.
526 if (source_filename)
527 Args.push_back(source_filename);
528 Args.insert(Args.end(), command_line_args,
529 command_line_args + num_command_line_args);
530
Daniel Dunbar94220972009-12-05 02:17:18 +0000531 unsigned NumErrors = CXXIdx->getDiags().getNumErrors();
532 llvm::OwningPtr<ASTUnit> Unit(
533 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Daniel Dunbar869824e2009-12-13 03:46:13 +0000534 CXXIdx->getDiags(),
535 CXXIdx->getClangResourcesPath(),
Daniel Dunbar94220972009-12-05 02:17:18 +0000536 CXXIdx->getOnlyLocalDecls(),
537 /* UseBumpAllocator = */ true));
538
539 // FIXME: Until we have broader testing, just drop the entire AST if we
540 // encountered an error.
541 if (NumErrors != CXXIdx->getDiags().getNumErrors())
542 return 0;
543
544 return Unit.take();
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000545 }
546
Ted Kremenek139ba862009-10-22 00:03:57 +0000547 // Build up the arguments for invoking 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000548 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000549
Ted Kremenek139ba862009-10-22 00:03:57 +0000550 // First add the complete path to the 'clang' executable.
551 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000552 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000553
Ted Kremenek139ba862009-10-22 00:03:57 +0000554 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000555 argv.push_back("-emit-ast");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000556
Ted Kremenek139ba862009-10-22 00:03:57 +0000557 // The 'source_filename' argument is optional. If the caller does not
558 // specify it then it is assumed that the source file is specified
559 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000560 if (source_filename)
561 argv.push_back(source_filename);
Ted Kremenek139ba862009-10-22 00:03:57 +0000562
Steve Naroff37b5ac22009-10-15 20:50:09 +0000563 // Generate a temporary name for the AST file.
Ted Kremenek139ba862009-10-22 00:03:57 +0000564 argv.push_back("-o");
Steve Naroff37b5ac22009-10-15 20:50:09 +0000565 char astTmpFile[L_tmpnam];
Ted Kremenek74cd0692009-10-15 23:21:22 +0000566 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek139ba862009-10-22 00:03:57 +0000567
568 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
569 for (int i = 0; i < num_command_line_args; ++i)
570 if (const char *arg = command_line_args[i]) {
571 if (strcmp(arg, "-o") == 0) {
572 ++i; // Also skip the matching argument.
573 continue;
574 }
575 if (strcmp(arg, "-emit-ast") == 0 ||
576 strcmp(arg, "-c") == 0 ||
577 strcmp(arg, "-fsyntax-only") == 0) {
578 continue;
579 }
580
581 // Keep the argument.
582 argv.push_back(arg);
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000583 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000584
Ted Kremenek139ba862009-10-22 00:03:57 +0000585 // Add the null terminator.
Ted Kremenek74cd0692009-10-15 23:21:22 +0000586 argv.push_back(NULL);
587
Ted Kremenekfeb15e32009-10-26 22:14:08 +0000588 // Invoke 'clang'.
589 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
590 // on Unix or NUL (Windows).
Ted Kremenek379afec2009-10-22 03:24:01 +0000591 std::string ErrMsg;
Ted Kremenekc46e4632009-10-19 22:27:32 +0000592 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DevNull, NULL };
Ted Kremenek379afec2009-10-22 03:24:01 +0000593 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
594 /* redirects */ !CXXIdx->getDisplayDiagnostics() ? &Redirects[0] : NULL,
595 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000596
Ted Kremenek0854d702009-11-10 19:18:52 +0000597 if (CXXIdx->getDisplayDiagnostics() && !ErrMsg.empty()) {
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000598 llvm::errs() << "clang_createTranslationUnitFromSourceFile: " << ErrMsg
Daniel Dunbaracca7252009-11-30 20:42:49 +0000599 << '\n' << "Arguments: \n";
Ted Kremenek379afec2009-10-22 03:24:01 +0000600 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Ted Kremenek779e5f42009-10-26 22:08:39 +0000601 I!=E; ++I) {
602 if (*I)
603 llvm::errs() << ' ' << *I << '\n';
604 }
605 llvm::errs() << '\n';
Ted Kremenek379afec2009-10-22 03:24:01 +0000606 }
Benjamin Kramer0829a832009-10-18 11:19:36 +0000607
Steve Naroff37b5ac22009-10-15 20:50:09 +0000608 // Finally, we create the translation unit from the ast file.
Steve Naroffe19944c2009-10-15 22:23:48 +0000609 ASTUnit *ATU = static_cast<ASTUnit *>(
Daniel Dunbaracca7252009-11-30 20:42:49 +0000610 clang_createTranslationUnit(CIdx, astTmpFile));
Steve Naroffe56b4ba2009-10-20 14:46:24 +0000611 if (ATU)
612 ATU->unlinkTemporaryFile();
Steve Naroffe19944c2009-10-15 22:23:48 +0000613 return ATU;
Steve Naroff5b7d8e22009-10-15 20:04:39 +0000614}
615
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000616void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Steve Naroff2bd6b9f2009-09-17 18:33:27 +0000617 assert(CTUnit && "Passed null CXTranslationUnit");
618 delete static_cast<ASTUnit *>(CTUnit);
619}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000620
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000621CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000622 assert(CTUnit && "Passed null CXTranslationUnit");
Steve Naroff77accc12009-09-03 18:19:54 +0000623 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000624 return createCXString(CXXUnit->getOriginalSourceFileName().c_str(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000625}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +0000626
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000627void clang_loadTranslationUnit(CXTranslationUnit CTUnit,
Steve Naroffc857ea42009-09-02 13:28:54 +0000628 CXTranslationUnitIterator callback,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000629 CXClientData CData) {
Steve Naroff50398192009-08-28 15:28:48 +0000630 assert(CTUnit && "Passed null CXTranslationUnit");
631 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
632 ASTContext &Ctx = CXXUnit->getASTContext();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000633
Daniel Dunbar8506dde2009-12-03 01:54:28 +0000634 unsigned PCHLevel = Decl::MaxPCHLevel;
635
636 // Set the PCHLevel to filter out unwanted decls if requested.
637 if (CXXUnit->getOnlyLocalDecls()) {
638 PCHLevel = 0;
639
640 // If the main input was an AST, bump the level.
641 if (CXXUnit->isMainFileAST())
642 ++PCHLevel;
643 }
644
645 TUVisitor DVisit(CTUnit, callback, CData, PCHLevel);
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000646
647 // If using a non-AST based ASTUnit, iterate over the stored list of top-level
648 // decls.
649 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls()) {
650 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
651 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
652 ie = TLDs.end(); it != ie; ++it) {
653 DVisit.Visit(*it);
654 }
655 } else
656 DVisit.Visit(Ctx.getTranslationUnitDecl());
Steve Naroff600866c2009-08-27 19:51:58 +0000657}
658
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000659void clang_loadDeclaration(CXDecl Dcl,
660 CXDeclIterator callback,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000661 CXClientData CData) {
Steve Naroffc857ea42009-09-02 13:28:54 +0000662 assert(Dcl && "Passed null CXDecl");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000663
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000664 CDeclVisitor DVisit(Dcl, callback, CData,
665 static_cast<Decl *>(Dcl)->getPCHLevel());
Steve Naroffc857ea42009-09-02 13:28:54 +0000666 DVisit.Visit(static_cast<Decl *>(Dcl));
Steve Naroff600866c2009-08-27 19:51:58 +0000667}
668
Steve Naroff7e8f8182009-08-28 12:07:44 +0000669// Some notes on CXEntity:
670//
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000671// - Since the 'ordinary' namespace includes functions, data, typedefs,
672// ObjC interfaces, thecurrent algorithm is a bit naive (resulting in one
Steve Naroff7e8f8182009-08-28 12:07:44 +0000673// entity for 2 different types). For example:
674//
675// module1.m: @interface Foo @end Foo *x;
676// module2.m: void Foo(int);
677//
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000678// - Since the unique name spans translation units, static data/functions
Steve Naroff7e8f8182009-08-28 12:07:44 +0000679// within a CXTranslationUnit are *not* currently represented by entities.
680// As a result, there will be no entity for the following:
681//
682// module.m: static void Foo() { }
683//
684
685
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000686const char *clang_getDeclarationName(CXEntity) {
Steve Naroff600866c2009-08-27 19:51:58 +0000687 return "";
688}
689
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000690const char *clang_getURI(CXEntity) {
691 return "";
692}
693
694CXEntity clang_getEntity(const char *URI) {
Steve Naroff600866c2009-08-27 19:51:58 +0000695 return 0;
696}
697
698//
699// CXDecl Operations.
700//
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000701
702CXEntity clang_getEntityFromDecl(CXDecl) {
Steve Naroff600866c2009-08-27 19:51:58 +0000703 return 0;
704}
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000705
706CXString clang_getDeclSpelling(CXDecl AnonDecl) {
Steve Naroff89922f82009-08-31 00:59:03 +0000707 assert(AnonDecl && "Passed null CXDecl");
708 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
Steve Naroffef0cef62009-11-09 17:45:52 +0000709
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000710 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
711 return createCXString(OMD->getSelector().getAsString().c_str(), true);
712
713 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Steve Naroff0d69b8c2009-10-29 21:11:04 +0000714 // No, this isn't the same as the code below. getIdentifier() is non-virtual
715 // and returns different names. NamedDecl returns the class name and
716 // ObjCCategoryImplDecl returns the category name.
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000717 return createCXString(CIMP->getIdentifier()->getNameStart());
718
719 if (ND->getIdentifier())
720 return createCXString(ND->getIdentifier()->getNameStart());
721
722 return createCXString("");
Steve Naroff600866c2009-08-27 19:51:58 +0000723}
Steve Narofff334b4e2009-09-02 18:26:48 +0000724
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000725unsigned clang_getDeclLine(CXDecl AnonDecl) {
Steve Naroff699a07d2009-09-25 21:32:34 +0000726 assert(AnonDecl && "Passed null CXDecl");
727 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
728 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
729 return SourceMgr.getSpellingLineNumber(ND->getLocation());
730}
731
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000732unsigned clang_getDeclColumn(CXDecl AnonDecl) {
Steve Naroff699a07d2009-09-25 21:32:34 +0000733 assert(AnonDecl && "Passed null CXDecl");
734 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
735 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Steve Naroff74165242009-09-25 22:15:54 +0000736 return SourceMgr.getSpellingColumnNumber(ND->getLocation());
Steve Naroff699a07d2009-09-25 21:32:34 +0000737}
738
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000739const char *clang_getDeclSource(CXDecl AnonDecl) {
Steve Naroffee9405e2009-09-25 21:45:39 +0000740 assert(AnonDecl && "Passed null CXDecl");
Steve Naroff88145032009-10-27 14:35:18 +0000741 FileEntry *FEnt = static_cast<FileEntry *>(clang_getDeclSourceFile(AnonDecl));
742 assert (FEnt && "Cannot find FileEntry for Decl");
743 return clang_getFileName(FEnt);
744}
745
746static const FileEntry *getFileEntryFromSourceLocation(SourceManager &SMgr,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000747 SourceLocation SLoc) {
Steve Naroff88145032009-10-27 14:35:18 +0000748 FileID FID;
749 if (SLoc.isFileID())
750 FID = SMgr.getFileID(SLoc);
751 else
752 FID = SMgr.getDecomposedSpellingLoc(SLoc).first;
753 return SMgr.getFileEntryForID(FID);
754}
755
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000756CXFile clang_getDeclSourceFile(CXDecl AnonDecl) {
Steve Naroff88145032009-10-27 14:35:18 +0000757 assert(AnonDecl && "Passed null CXDecl");
Steve Naroffee9405e2009-09-25 21:45:39 +0000758 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
759 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Steve Naroff88145032009-10-27 14:35:18 +0000760 return (void *)getFileEntryFromSourceLocation(SourceMgr, ND->getLocation());
761}
762
763const char *clang_getFileName(CXFile SFile) {
764 assert(SFile && "Passed null CXFile");
765 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
766 return FEnt->getName();
767}
768
769time_t clang_getFileTime(CXFile SFile) {
770 assert(SFile && "Passed null CXFile");
771 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
772 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +0000773}
774
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000775CXString clang_getCursorSpelling(CXCursor C) {
Steve Narofff334b4e2009-09-02 18:26:48 +0000776 assert(C.decl && "CXCursor has null decl");
777 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
Steve Naroffef0cef62009-11-09 17:45:52 +0000778
Steve Narofff334b4e2009-09-02 18:26:48 +0000779 if (clang_isReference(C.kind)) {
780 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +0000781 case CXCursor_ObjCSuperClassRef: {
782 ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ND);
783 assert(OID && "clang_getCursorLine(): Missing interface decl");
784 return createCXString(OID->getSuperClass()->getIdentifier()
785 ->getNameStart());
786 }
787 case CXCursor_ObjCClassRef: {
788 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ND))
Benjamin Kramer62cf3222009-11-09 19:13:48 +0000789 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +0000790
791 ObjCCategoryDecl *OCD = dyn_cast<ObjCCategoryDecl>(ND);
792 assert(OCD && "clang_getCursorLine(): Missing category decl");
793 return createCXString(OCD->getClassInterface()->getIdentifier()
794 ->getNameStart());
795 }
796 case CXCursor_ObjCProtocolRef: {
797 ObjCProtocolDecl *OID = dyn_cast<ObjCProtocolDecl>(ND);
798 assert(OID && "clang_getCursorLine(): Missing protocol decl");
799 return createCXString(OID->getIdentifier()->getNameStart());
800 }
801 case CXCursor_ObjCSelectorRef: {
802 ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(
803 static_cast<Stmt *>(C.stmt));
804 assert(OME && "clang_getCursorLine(): Missing message expr");
805 return createCXString(OME->getSelector().getAsString().c_str(), true);
806 }
807 case CXCursor_VarRef:
808 case CXCursor_FunctionRef:
809 case CXCursor_EnumConstantRef: {
810 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(
811 static_cast<Stmt *>(C.stmt));
812 assert(DRE && "clang_getCursorLine(): Missing decl ref expr");
813 return createCXString(DRE->getDecl()->getIdentifier()->getNameStart());
814 }
815 default:
816 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +0000817 }
818 }
819 return clang_getDeclSpelling(C.decl);
820}
821
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000822const char *clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +0000823 switch (Kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +0000824 case CXCursor_FunctionDecl: return "FunctionDecl";
825 case CXCursor_TypedefDecl: return "TypedefDecl";
826 case CXCursor_EnumDecl: return "EnumDecl";
827 case CXCursor_EnumConstantDecl: return "EnumConstantDecl";
828 case CXCursor_StructDecl: return "StructDecl";
829 case CXCursor_UnionDecl: return "UnionDecl";
830 case CXCursor_ClassDecl: return "ClassDecl";
831 case CXCursor_FieldDecl: return "FieldDecl";
832 case CXCursor_VarDecl: return "VarDecl";
833 case CXCursor_ParmDecl: return "ParmDecl";
834 case CXCursor_ObjCInterfaceDecl: return "ObjCInterfaceDecl";
835 case CXCursor_ObjCCategoryDecl: return "ObjCCategoryDecl";
836 case CXCursor_ObjCProtocolDecl: return "ObjCProtocolDecl";
837 case CXCursor_ObjCPropertyDecl: return "ObjCPropertyDecl";
838 case CXCursor_ObjCIvarDecl: return "ObjCIvarDecl";
839 case CXCursor_ObjCInstanceMethodDecl: return "ObjCInstanceMethodDecl";
840 case CXCursor_ObjCClassMethodDecl: return "ObjCClassMethodDecl";
841 case CXCursor_FunctionDefn: return "FunctionDefn";
842 case CXCursor_ObjCInstanceMethodDefn: return "ObjCInstanceMethodDefn";
843 case CXCursor_ObjCClassMethodDefn: return "ObjCClassMethodDefn";
844 case CXCursor_ObjCClassDefn: return "ObjCClassDefn";
845 case CXCursor_ObjCCategoryDefn: return "ObjCCategoryDefn";
846 case CXCursor_ObjCSuperClassRef: return "ObjCSuperClassRef";
847 case CXCursor_ObjCProtocolRef: return "ObjCProtocolRef";
848 case CXCursor_ObjCClassRef: return "ObjCClassRef";
849 case CXCursor_ObjCSelectorRef: return "ObjCSelectorRef";
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000850
Daniel Dunbaracca7252009-11-30 20:42:49 +0000851 case CXCursor_VarRef: return "VarRef";
852 case CXCursor_FunctionRef: return "FunctionRef";
853 case CXCursor_EnumConstantRef: return "EnumConstantRef";
854 case CXCursor_MemberRef: return "MemberRef";
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000855
Daniel Dunbaracca7252009-11-30 20:42:49 +0000856 case CXCursor_InvalidFile: return "InvalidFile";
857 case CXCursor_NoDeclFound: return "NoDeclFound";
858 case CXCursor_NotImplemented: return "NotImplemented";
859 default: return "<not implemented>";
Steve Naroff89922f82009-08-31 00:59:03 +0000860 }
Steve Naroff600866c2009-08-27 19:51:58 +0000861}
Steve Naroff89922f82009-08-31 00:59:03 +0000862
Steve Naroff9efa7672009-09-04 15:44:05 +0000863static enum CXCursorKind TranslateKind(Decl *D) {
864 switch (D->getKind()) {
Daniel Dunbaracca7252009-11-30 20:42:49 +0000865 case Decl::Function: return CXCursor_FunctionDecl;
866 case Decl::Typedef: return CXCursor_TypedefDecl;
867 case Decl::Enum: return CXCursor_EnumDecl;
868 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
869 case Decl::Record: return CXCursor_StructDecl; // FIXME: union/class
870 case Decl::Field: return CXCursor_FieldDecl;
871 case Decl::Var: return CXCursor_VarDecl;
872 case Decl::ParmVar: return CXCursor_ParmDecl;
873 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
874 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
875 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
876 case Decl::ObjCMethod: {
877 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D);
878 if (MD->isInstanceMethod())
879 return CXCursor_ObjCInstanceMethodDecl;
880 return CXCursor_ObjCClassMethodDecl;
881 }
882 default: break;
Steve Naroff9efa7672009-09-04 15:44:05 +0000883 }
Steve Naroff77128dd2009-09-15 20:25:34 +0000884 return CXCursor_NotImplemented;
Steve Naroff9efa7672009-09-04 15:44:05 +0000885}
Steve Naroff600866c2009-08-27 19:51:58 +0000886//
887// CXCursor Operations.
888//
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000889
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000890CXCursor clang_getCursor(CXTranslationUnit CTUnit, const char *source_name,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000891 unsigned line, unsigned column) {
Steve Naroff9efa7672009-09-04 15:44:05 +0000892 assert(CTUnit && "Passed null CXTranslationUnit");
893 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000894
Steve Naroff9efa7672009-09-04 15:44:05 +0000895 FileManager &FMgr = CXXUnit->getFileManager();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000896 const FileEntry *File = FMgr.getFile(source_name,
897 source_name+strlen(source_name));
Steve Naroff77128dd2009-09-15 20:25:34 +0000898 if (!File) {
Steve Narofffb570422009-09-22 19:25:29 +0000899 CXCursor C = { CXCursor_InvalidFile, 0, 0 };
Steve Naroff77128dd2009-09-15 20:25:34 +0000900 return C;
901 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000902 SourceLocation SLoc =
Steve Naroff9efa7672009-09-04 15:44:05 +0000903 CXXUnit->getSourceManager().getLocation(File, line, column);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000904
Steve Narofff96b5242009-10-28 20:44:47 +0000905 ASTLocation LastLoc = CXXUnit->getLastASTLocation();
906
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000907 ASTLocation ALoc = ResolveLocationInAST(CXXUnit->getASTContext(), SLoc,
Steve Narofff96b5242009-10-28 20:44:47 +0000908 &LastLoc);
909 if (ALoc.isValid())
910 CXXUnit->setLastASTLocation(ALoc);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000911
Argyrios Kyrtzidisf4526e32009-09-29 19:44:27 +0000912 Decl *Dcl = ALoc.getParentDecl();
Argyrios Kyrtzidis05a76512009-09-29 19:45:58 +0000913 if (ALoc.isNamedRef())
914 Dcl = ALoc.AsNamedRef().ND;
Argyrios Kyrtzidisf4526e32009-09-29 19:44:27 +0000915 Stmt *Stm = ALoc.dyn_AsStmt();
Steve Naroff4ade6d62009-09-23 17:52:52 +0000916 if (Dcl) {
917 if (Stm) {
918 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Stm)) {
919 CXCursor C = { TranslateDeclRefExpr(DRE), Dcl, Stm };
920 return C;
921 } else if (ObjCMessageExpr *MExp = dyn_cast<ObjCMessageExpr>(Stm)) {
922 CXCursor C = { CXCursor_ObjCSelectorRef, Dcl, MExp };
923 return C;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000924 }
Steve Naroff4ade6d62009-09-23 17:52:52 +0000925 // Fall through...treat as a decl, not a ref.
926 }
Steve Naroff85e2db72009-10-01 00:31:07 +0000927 if (ALoc.isNamedRef()) {
928 if (isa<ObjCInterfaceDecl>(Dcl)) {
929 CXCursor C = { CXCursor_ObjCClassRef, Dcl, ALoc.getParentDecl() };
930 return C;
931 }
932 if (isa<ObjCProtocolDecl>(Dcl)) {
933 CXCursor C = { CXCursor_ObjCProtocolRef, Dcl, ALoc.getParentDecl() };
934 return C;
935 }
936 }
Daniel Dunbaracca7252009-11-30 20:42:49 +0000937 CXCursor C = { TranslateKind(Dcl), Dcl, 0 };
Steve Naroff77128dd2009-09-15 20:25:34 +0000938 return C;
939 }
Steve Narofffb570422009-09-22 19:25:29 +0000940 CXCursor C = { CXCursor_NoDeclFound, 0, 0 };
Steve Naroff9efa7672009-09-04 15:44:05 +0000941 return C;
Steve Naroff600866c2009-08-27 19:51:58 +0000942}
943
Ted Kremenek73885552009-11-17 19:28:59 +0000944CXCursor clang_getNullCursor(void) {
945 CXCursor C;
946 C.kind = CXCursor_InvalidFile;
947 C.decl = NULL;
948 C.stmt = NULL;
949 return C;
950}
951
952unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
953 return X.kind == Y.kind && X.decl == Y.decl && X.stmt == Y.stmt;
954}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000955
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000956CXCursor clang_getCursorFromDecl(CXDecl AnonDecl) {
Steve Naroff77128dd2009-09-15 20:25:34 +0000957 assert(AnonDecl && "Passed null CXDecl");
958 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +0000959
Steve Narofffb570422009-09-22 19:25:29 +0000960 CXCursor C = { TranslateKind(ND), ND, 0 };
Steve Naroff77128dd2009-09-15 20:25:34 +0000961 return C;
962}
963
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000964unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +0000965 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
966}
967
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000968unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +0000969 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
970}
Steve Naroff2d4d6292009-08-31 14:26:51 +0000971
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000972unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +0000973 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
974}
975
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000976unsigned clang_isDefinition(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +0000977 return K >= CXCursor_FirstDefn && K <= CXCursor_LastDefn;
978}
979
Daniel Dunbar9ebfa312009-12-01 03:14:51 +0000980CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +0000981 return C.kind;
982}
983
Steve Naroff699a07d2009-09-25 21:32:34 +0000984static Decl *getDeclFromExpr(Stmt *E) {
985 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
986 return RefExpr->getDecl();
987 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
988 return ME->getMemberDecl();
989 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
990 return RE->getDecl();
991
992 if (CallExpr *CE = dyn_cast<CallExpr>(E))
993 return getDeclFromExpr(CE->getCallee());
994 if (CastExpr *CE = dyn_cast<CastExpr>(E))
995 return getDeclFromExpr(CE->getSubExpr());
996 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
997 return OME->getMethodDecl();
998
999 return 0;
1000}
1001
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001002CXDecl clang_getCursorDecl(CXCursor C) {
Steve Naroff699a07d2009-09-25 21:32:34 +00001003 if (clang_isDeclaration(C.kind))
1004 return C.decl;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001005
Steve Naroff699a07d2009-09-25 21:32:34 +00001006 if (clang_isReference(C.kind)) {
Steve Naroff85e2db72009-10-01 00:31:07 +00001007 if (C.stmt) {
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001008 if (C.kind == CXCursor_ObjCClassRef ||
Steve Narofff9adf8f2009-10-05 17:58:19 +00001009 C.kind == CXCursor_ObjCProtocolRef)
Steve Naroff85e2db72009-10-01 00:31:07 +00001010 return static_cast<Stmt *>(C.stmt);
1011 else
1012 return getDeclFromExpr(static_cast<Stmt *>(C.stmt));
1013 } else
Steve Naroff699a07d2009-09-25 21:32:34 +00001014 return C.decl;
1015 }
1016 return 0;
Steve Naroff9efa7672009-09-04 15:44:05 +00001017}
1018
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001019unsigned clang_getCursorLine(CXCursor C) {
Steve Naroff2d4d6292009-08-31 14:26:51 +00001020 assert(C.decl && "CXCursor has null decl");
1021 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
Steve Naroff2d4d6292009-08-31 14:26:51 +00001022 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001023
Steve Narofff334b4e2009-09-02 18:26:48 +00001024 SourceLocation SLoc = getLocationFromCursor(C, SourceMgr, ND);
Steve Naroff2d4d6292009-08-31 14:26:51 +00001025 return SourceMgr.getSpellingLineNumber(SLoc);
Steve Naroff600866c2009-08-27 19:51:58 +00001026}
Steve Narofff334b4e2009-09-02 18:26:48 +00001027
Steve Naroffef0cef62009-11-09 17:45:52 +00001028const char *clang_getCString(CXString string) {
1029 return string.Spelling;
1030}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001031
Steve Naroffef0cef62009-11-09 17:45:52 +00001032void clang_disposeString(CXString string) {
Benjamin Kramer858e5de2009-11-09 18:24:53 +00001033 if (string.MustFreeString)
1034 free((void*)string.Spelling);
Steve Naroffef0cef62009-11-09 17:45:52 +00001035}
1036
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001037unsigned clang_getCursorColumn(CXCursor C) {
Steve Naroff2d4d6292009-08-31 14:26:51 +00001038 assert(C.decl && "CXCursor has null decl");
1039 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
Steve Naroff2d4d6292009-08-31 14:26:51 +00001040 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001041
Steve Narofff334b4e2009-09-02 18:26:48 +00001042 SourceLocation SLoc = getLocationFromCursor(C, SourceMgr, ND);
Steve Naroff2d4d6292009-08-31 14:26:51 +00001043 return SourceMgr.getSpellingColumnNumber(SLoc);
Steve Naroff600866c2009-08-27 19:51:58 +00001044}
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001045
1046const char *clang_getCursorSource(CXCursor C) {
Steve Naroff2d4d6292009-08-31 14:26:51 +00001047 assert(C.decl && "CXCursor has null decl");
1048 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
Steve Naroff2d4d6292009-08-31 14:26:51 +00001049 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001050
Steve Narofff334b4e2009-09-02 18:26:48 +00001051 SourceLocation SLoc = getLocationFromCursor(C, SourceMgr, ND);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001052
Ted Kremenek9298cfc2009-11-17 05:31:58 +00001053 if (SLoc.isFileID()) {
1054 const char *bufferName = SourceMgr.getBufferName(SLoc);
1055 return bufferName[0] == '<' ? NULL : bufferName;
1056 }
Douglas Gregor02465752009-10-16 21:24:31 +00001057
1058 // Retrieve the file in which the macro was instantiated, then provide that
1059 // buffer name.
1060 // FIXME: Do we want to give specific macro-instantiation information?
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001061 const llvm::MemoryBuffer *Buffer
Douglas Gregor02465752009-10-16 21:24:31 +00001062 = SourceMgr.getBuffer(SourceMgr.getDecomposedSpellingLoc(SLoc).first);
1063 if (!Buffer)
1064 return 0;
1065
1066 return Buffer->getBufferIdentifier();
Steve Naroff600866c2009-08-27 19:51:58 +00001067}
1068
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001069CXFile clang_getCursorSourceFile(CXCursor C) {
Steve Naroff88145032009-10-27 14:35:18 +00001070 assert(C.decl && "CXCursor has null decl");
1071 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
1072 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001073
Steve Naroff88145032009-10-27 14:35:18 +00001074 return (void *)getFileEntryFromSourceLocation(SourceMgr,
Daniel Dunbaracca7252009-11-30 20:42:49 +00001075 getLocationFromCursor(C,SourceMgr, ND));
Steve Naroff88145032009-10-27 14:35:18 +00001076}
1077
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001078void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00001079 const char **startBuf,
1080 const char **endBuf,
1081 unsigned *startLine,
1082 unsigned *startColumn,
1083 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00001084 unsigned *endColumn) {
Steve Naroff4ade6d62009-09-23 17:52:52 +00001085 assert(C.decl && "CXCursor has null decl");
1086 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
1087 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
1088 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001089
Steve Naroff4ade6d62009-09-23 17:52:52 +00001090 SourceManager &SM = FD->getASTContext().getSourceManager();
1091 *startBuf = SM.getCharacterData(Body->getLBracLoc());
1092 *endBuf = SM.getCharacterData(Body->getRBracLoc());
1093 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
1094 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
1095 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
1096 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
1097}
1098
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001099enum CXCompletionChunkKind
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001100clang_getCompletionChunkKind(CXCompletionString completion_string,
1101 unsigned chunk_number) {
1102 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
1103 if (!CCStr || chunk_number >= CCStr->size())
1104 return CXCompletionChunk_Text;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001105
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001106 switch ((*CCStr)[chunk_number].Kind) {
1107 case CodeCompletionString::CK_TypedText:
1108 return CXCompletionChunk_TypedText;
1109 case CodeCompletionString::CK_Text:
1110 return CXCompletionChunk_Text;
1111 case CodeCompletionString::CK_Optional:
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001112 return CXCompletionChunk_Optional;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001113 case CodeCompletionString::CK_Placeholder:
1114 return CXCompletionChunk_Placeholder;
1115 case CodeCompletionString::CK_Informative:
1116 return CXCompletionChunk_Informative;
1117 case CodeCompletionString::CK_CurrentParameter:
1118 return CXCompletionChunk_CurrentParameter;
1119 case CodeCompletionString::CK_LeftParen:
1120 return CXCompletionChunk_LeftParen;
1121 case CodeCompletionString::CK_RightParen:
1122 return CXCompletionChunk_RightParen;
1123 case CodeCompletionString::CK_LeftBracket:
1124 return CXCompletionChunk_LeftBracket;
1125 case CodeCompletionString::CK_RightBracket:
1126 return CXCompletionChunk_RightBracket;
1127 case CodeCompletionString::CK_LeftBrace:
1128 return CXCompletionChunk_LeftBrace;
1129 case CodeCompletionString::CK_RightBrace:
1130 return CXCompletionChunk_RightBrace;
1131 case CodeCompletionString::CK_LeftAngle:
1132 return CXCompletionChunk_LeftAngle;
1133 case CodeCompletionString::CK_RightAngle:
1134 return CXCompletionChunk_RightAngle;
1135 case CodeCompletionString::CK_Comma:
1136 return CXCompletionChunk_Comma;
1137 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001138
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001139 // Should be unreachable, but let's be careful.
1140 return CXCompletionChunk_Text;
1141}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001142
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001143const char *clang_getCompletionChunkText(CXCompletionString completion_string,
1144 unsigned chunk_number) {
1145 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
1146 if (!CCStr || chunk_number >= CCStr->size())
1147 return 0;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001148
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001149 switch ((*CCStr)[chunk_number].Kind) {
1150 case CodeCompletionString::CK_TypedText:
1151 case CodeCompletionString::CK_Text:
1152 case CodeCompletionString::CK_Placeholder:
1153 case CodeCompletionString::CK_CurrentParameter:
1154 case CodeCompletionString::CK_Informative:
1155 case CodeCompletionString::CK_LeftParen:
1156 case CodeCompletionString::CK_RightParen:
1157 case CodeCompletionString::CK_LeftBracket:
1158 case CodeCompletionString::CK_RightBracket:
1159 case CodeCompletionString::CK_LeftBrace:
1160 case CodeCompletionString::CK_RightBrace:
1161 case CodeCompletionString::CK_LeftAngle:
1162 case CodeCompletionString::CK_RightAngle:
1163 case CodeCompletionString::CK_Comma:
1164 return (*CCStr)[chunk_number].Text;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001165
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001166 case CodeCompletionString::CK_Optional:
1167 // Note: treated as an empty text block.
Douglas Gregor90742c12009-12-10 22:46:19 +00001168 return "";
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001169 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001170
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001171 // Should be unreachable, but let's be careful.
1172 return 0;
1173}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001174
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001175CXCompletionString
1176clang_getCompletionChunkCompletionString(CXCompletionString completion_string,
1177 unsigned chunk_number) {
1178 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
1179 if (!CCStr || chunk_number >= CCStr->size())
1180 return 0;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001181
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001182 switch ((*CCStr)[chunk_number].Kind) {
1183 case CodeCompletionString::CK_TypedText:
1184 case CodeCompletionString::CK_Text:
1185 case CodeCompletionString::CK_Placeholder:
1186 case CodeCompletionString::CK_CurrentParameter:
1187 case CodeCompletionString::CK_Informative:
1188 case CodeCompletionString::CK_LeftParen:
1189 case CodeCompletionString::CK_RightParen:
1190 case CodeCompletionString::CK_LeftBracket:
1191 case CodeCompletionString::CK_RightBracket:
1192 case CodeCompletionString::CK_LeftBrace:
1193 case CodeCompletionString::CK_RightBrace:
1194 case CodeCompletionString::CK_LeftAngle:
1195 case CodeCompletionString::CK_RightAngle:
1196 case CodeCompletionString::CK_Comma:
1197 return 0;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001198
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001199 case CodeCompletionString::CK_Optional:
1200 // Note: treated as an empty text block.
1201 return (*CCStr)[chunk_number].Optional;
1202 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001203
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001204 // Should be unreachable, but let's be careful.
1205 return 0;
1206}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001207
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001208unsigned clang_getNumCompletionChunks(CXCompletionString completion_string) {
1209 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
1210 return CCStr? CCStr->size() : 0;
1211}
Steve Naroff4ade6d62009-09-23 17:52:52 +00001212
Douglas Gregor2b4074f2009-12-01 05:55:20 +00001213static bool ReadUnsigned(const char *&Memory, const char *MemoryEnd,
1214 unsigned &Value) {
1215 if (Memory + sizeof(unsigned) > MemoryEnd)
1216 return true;
1217
1218 memmove(&Value, Memory, sizeof(unsigned));
1219 Memory += sizeof(unsigned);
1220 return false;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001221}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001222
1223void clang_codeComplete(CXIndex CIdx,
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001224 const char *source_filename,
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001225 int num_command_line_args,
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001226 const char **command_line_args,
Douglas Gregor735df882009-12-02 09:21:34 +00001227 unsigned num_unsaved_files,
1228 struct CXUnsavedFile *unsaved_files,
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001229 const char *complete_filename,
1230 unsigned complete_line,
1231 unsigned complete_column,
1232 CXCompletionIterator completion_iterator,
1233 CXClientData client_data) {
1234 // The indexer, which is mainly used to determine where diagnostics go.
1235 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001236
Douglas Gregor735df882009-12-02 09:21:34 +00001237 // The set of temporary files that we've built.
1238 std::vector<llvm::sys::Path> TemporaryFiles;
1239
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001240 // Build up the arguments for invoking 'clang'.
1241 std::vector<const char *> argv;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001242
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001243 // First add the complete path to the 'clang' executable.
1244 llvm::sys::Path ClangPath = CXXIdx->getClangPath();
1245 argv.push_back(ClangPath.c_str());
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001246
1247 // Add the '-fsyntax-only' argument so that we only perform a basic
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001248 // syntax check of the code.
1249 argv.push_back("-fsyntax-only");
1250
1251 // Add the appropriate '-code-completion-at=file:line:column' argument
1252 // to perform code completion, with an "-Xclang" preceding it.
1253 std::string code_complete_at;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001254 code_complete_at += complete_filename;
1255 code_complete_at += ":";
1256 code_complete_at += llvm::utostr(complete_line);
1257 code_complete_at += ":";
1258 code_complete_at += llvm::utostr(complete_column);
1259 argv.push_back("-Xclang");
Daniel Dunbar7bd71652009-12-03 05:32:40 +00001260 argv.push_back("-code-completion-at");
1261 argv.push_back("-Xclang");
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001262 argv.push_back(code_complete_at.c_str());
1263 argv.push_back("-Xclang");
Daniel Dunbar4db166b2009-11-19 05:32:09 +00001264 argv.push_back("-no-code-completion-debug-printer");
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001265
Douglas Gregor735df882009-12-02 09:21:34 +00001266 std::vector<std::string> RemapArgs;
1267 for (unsigned i = 0; i != num_unsaved_files; ++i) {
1268 char tmpFile[L_tmpnam];
1269 char *tmpFileName = tmpnam(tmpFile);
1270
1271 // Write the contents of this unsaved file into the temporary file.
1272 llvm::sys::Path SavedFile(tmpFileName);
1273 std::string ErrorInfo;
1274 llvm::raw_fd_ostream OS(SavedFile.c_str(), ErrorInfo);
1275 if (!ErrorInfo.empty())
1276 continue;
1277
1278 OS.write(unsaved_files[i].Contents, unsaved_files[i].Length);
1279 OS.close();
1280 if (OS.has_error()) {
1281 SavedFile.eraseFromDisk();
1282 continue;
1283 }
1284
1285 // Remap the file.
Daniel Dunbar7bd71652009-12-03 05:32:40 +00001286 std::string RemapArg = unsaved_files[i].Filename;
Douglas Gregor735df882009-12-02 09:21:34 +00001287 RemapArg += ';';
1288 RemapArg += tmpFileName;
1289 RemapArgs.push_back("-Xclang");
Daniel Dunbar7bd71652009-12-03 05:32:40 +00001290 RemapArgs.push_back("-remap-file");
1291 RemapArgs.push_back("-Xclang");
Douglas Gregor735df882009-12-02 09:21:34 +00001292 RemapArgs.push_back(RemapArg);
1293 TemporaryFiles.push_back(SavedFile);
1294 }
1295
1296 // The pointers into the elements of RemapArgs are stable because we
1297 // won't be adding anything to RemapArgs after this point.
1298 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1299 argv.push_back(RemapArgs[i].c_str());
1300
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001301 // Add the source file name (FIXME: later, we'll want to build temporary
1302 // file from the buffer, or just feed the source text via standard input).
Ted Kremenek4633d1b2009-11-17 18:18:02 +00001303 if (source_filename)
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001304 argv.push_back(source_filename);
1305
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001306 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1307 for (int i = 0; i < num_command_line_args; ++i)
1308 if (const char *arg = command_line_args[i]) {
1309 if (strcmp(arg, "-o") == 0) {
1310 ++i; // Also skip the matching argument.
1311 continue;
1312 }
1313 if (strcmp(arg, "-emit-ast") == 0 ||
1314 strcmp(arg, "-c") == 0 ||
1315 strcmp(arg, "-fsyntax-only") == 0) {
1316 continue;
1317 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001318
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001319 // Keep the argument.
1320 argv.push_back(arg);
1321 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001322
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001323 // Add the null terminator.
1324 argv.push_back(NULL);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001325
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001326 // Generate a temporary name for the AST file.
1327 char tmpFile[L_tmpnam];
1328 char *tmpFileName = tmpnam(tmpFile);
1329 llvm::sys::Path ResultsFile(tmpFileName);
Douglas Gregor735df882009-12-02 09:21:34 +00001330 TemporaryFiles.push_back(ResultsFile);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001331
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001332 // Invoke 'clang'.
1333 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1334 // on Unix or NUL (Windows).
1335 std::string ErrMsg;
1336 const llvm::sys::Path *Redirects[] = { &DevNull, &ResultsFile, &DevNull, 0 };
1337 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
1338 /* redirects */ &Redirects[0],
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001339 /* secondsToWait */ 0,
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001340 /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001341
Ted Kremenek0854d702009-11-10 19:18:52 +00001342 if (CXXIdx->getDisplayDiagnostics() && !ErrMsg.empty()) {
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001343 llvm::errs() << "clang_codeComplete: " << ErrMsg
Daniel Dunbaracca7252009-11-30 20:42:49 +00001344 << '\n' << "Arguments: \n";
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001345 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
1346 I!=E; ++I) {
1347 if (*I)
1348 llvm::errs() << ' ' << *I << '\n';
1349 }
1350 llvm::errs() << '\n';
1351 }
1352
1353 // Parse the resulting source file to find code-completion results.
1354 using llvm::MemoryBuffer;
1355 using llvm::StringRef;
1356 if (MemoryBuffer *F = MemoryBuffer::getFile(ResultsFile.c_str())) {
1357 StringRef Buffer = F->getBuffer();
Douglas Gregor2b4074f2009-12-01 05:55:20 +00001358 for (const char *Str = Buffer.data(), *StrEnd = Str + Buffer.size();
1359 Str < StrEnd;) {
1360 unsigned KindValue;
1361 if (ReadUnsigned(Str, StrEnd, KindValue))
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001362 break;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001363
Douglas Gregor2b4074f2009-12-01 05:55:20 +00001364 CodeCompletionString *CCStr
1365 = CodeCompletionString::Deserialize(Str, StrEnd);
1366 if (!CCStr)
1367 continue;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001368
Douglas Gregor2b4074f2009-12-01 05:55:20 +00001369 if (!CCStr->empty()) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001370 // Vend the code-completion result to the caller.
1371 CXCompletionResult Result;
Douglas Gregor2b4074f2009-12-01 05:55:20 +00001372 Result.CursorKind = (CXCursorKind)KindValue;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001373 Result.CompletionString = CCStr;
1374 if (completion_iterator)
1375 completion_iterator(&Result, client_data);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001376 }
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001377
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001378 delete CCStr;
Douglas Gregor2b4074f2009-12-01 05:55:20 +00001379 };
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001380 delete F;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001381 }
1382
Douglas Gregor735df882009-12-02 09:21:34 +00001383 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1384 TemporaryFiles[i].eraseFromDisk();
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001385}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00001386
Steve Naroff600866c2009-08-27 19:51:58 +00001387} // end extern "C"