blob: 5c9fb3adf615de89ed14177b76d63090d232a265 [file] [log] [blame]
Ted Kremenekb60d87c2009-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 Dunbarbbc569c2009-11-30 20:42:43 +00007//
Ted Kremenekb60d87c2009-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 Naroffa1c72842009-08-28 15:28:48 +000015#include "clang/Index/Program.h"
16#include "clang/Index/Indexer.h"
Steve Naroffef9618b2009-09-04 15:44:05 +000017#include "clang/Index/ASTLocation.h"
18#include "clang/Index/Utils.h"
Douglas Gregor9eb77012009-11-07 00:00:49 +000019#include "clang/Sema/CodeCompleteConsumer.h"
Steve Naroffa1c72842009-08-28 15:28:48 +000020#include "clang/AST/DeclVisitor.h"
Steve Naroff66af1ae2009-09-22 19:25:29 +000021#include "clang/AST/StmtVisitor.h"
Steve Naroff3645f5a2009-09-02 13:28:54 +000022#include "clang/AST/Decl.h"
Benjamin Kramer8b83f5d2009-08-29 12:56:35 +000023#include "clang/Basic/FileManager.h"
Steve Naroff772c1a42009-08-31 14:26:51 +000024#include "clang/Basic/SourceManager.h"
Benjamin Kramer8b83f5d2009-08-29 12:56:35 +000025#include "clang/Frontend/ASTUnit.h"
Daniel Dunbar59203002009-12-03 01:45:44 +000026#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor9eb77012009-11-07 00:00:49 +000027#include "llvm/ADT/StringExtras.h"
Benjamin Kramer6bd6d502009-10-18 16:13:48 +000028#include "llvm/Config/config.h"
Ted Kremenek428c6372009-10-19 21:44:57 +000029#include "llvm/Support/Compiler.h"
Douglas Gregord3d923a2009-10-16 21:24:31 +000030#include "llvm/Support/MemoryBuffer.h"
31#include "llvm/System/Path.h"
Benjamin Kramer2836c4c2009-10-18 11:19:36 +000032#include "llvm/System/Program.h"
Ted Kremenek44886fd2009-10-22 03:24:01 +000033#include "llvm/Support/raw_ostream.h"
Ted Kremenek428c6372009-10-19 21:44:57 +000034
Benjamin Kramer8b83f5d2009-08-29 12:56:35 +000035#include <cstdio>
Ted Kremenek9dd89ba2009-10-19 21:17:25 +000036#include <vector>
Douglas Gregor9eb77012009-11-07 00:00:49 +000037#include <sstream>
Ted Kremenek9dd89ba2009-10-19 21:17:25 +000038
Benjamin Kramer6bd6d502009-10-18 16:13:48 +000039#ifdef LLVM_ON_WIN32
40#define WIN32_LEAN_AND_MEAN
41#include <windows.h>
42#else
Steve Naroff7781daa2009-10-15 20:04:39 +000043#include <dlfcn.h>
Daniel Dunbarcd237182009-10-17 23:53:11 +000044#endif
Steve Naroff7781daa2009-10-15 20:04:39 +000045
Steve Naroffa1c72842009-08-28 15:28:48 +000046using namespace clang;
47using namespace idx;
48
Steve Naroff1054e602009-08-31 00:59:03 +000049namespace {
Daniel Dunbarbbc569c2009-11-30 20:42:43 +000050static enum CXCursorKind TranslateDeclRefExpr(DeclRefExpr *DRE)
Steve Naroff76b8f132009-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 Dunbarbbc569c2009-11-30 20:42:43 +000059 else
Steve Naroff76b8f132009-09-23 17:52:52 +000060 return CXCursor_NotImplemented;
61}
62
63#if 0
64// Will be useful one day.
Steve Naroff66af1ae2009-09-22 19:25:29 +000065class CRefVisitor : public StmtVisitor<CRefVisitor> {
66 CXDecl CDecl;
67 CXDeclIterator Callback;
68 CXClientData CData;
Daniel Dunbarbbc569c2009-11-30 20:42:43 +000069
Steve Naroff66af1ae2009-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 Dunbarbbc569c2009-11-30 20:42:43 +000076 CRefVisitor(CXDecl C, CXDeclIterator cback, CXClientData D) :
Steve Naroff66af1ae2009-09-22 19:25:29 +000077 CDecl(C), Callback(cback), CData(D) {}
Daniel Dunbarbbc569c2009-11-30 20:42:43 +000078
Steve Naroff66af1ae2009-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 Naroff76b8f132009-09-23 17:52:52 +000085 Call(TranslateDeclRefExpr(Node), Node);
Steve Naroff66af1ae2009-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 Naroff76b8f132009-09-23 17:52:52 +000097#endif
Daniel Dunbarbbc569c2009-11-30 20:42:43 +000098
Ted Kremenek428c6372009-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 Dunbarbbc569c2009-11-30 20:42:43 +0000104 virtual void HandleDiagnostic(Diagnostic::Level, const DiagnosticInfo &) {}
Ted Kremenek428c6372009-10-19 21:44:57 +0000105};
Steve Naroff66af1ae2009-09-22 19:25:29 +0000106
Steve Naroff1054e602009-08-31 00:59:03 +0000107// Translation Unit Visitor.
108class TUVisitor : public DeclVisitor<TUVisitor> {
109 CXTranslationUnit TUnit;
110 CXTranslationUnitIterator Callback;
Steve Naroff69b10fd2009-09-01 15:55:40 +0000111 CXClientData CData;
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000112
Douglas Gregor16bef852009-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 Dunbarbbc569c2009-11-30 20:42:43 +0000117
Steve Naroff69b10fd2009-09-01 15:55:40 +0000118 void Call(enum CXCursorKind CK, NamedDecl *ND) {
Douglas Gregor16bef852009-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 Dunbarbbc569c2009-11-30 20:42:43 +0000122
Steve Naroff58bd62d2009-10-28 20:44:47 +0000123 // Filter any implicit declarations (since the source info will be bogus).
124 if (ND->isImplicit())
125 return;
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000126
Steve Naroff66af1ae2009-09-22 19:25:29 +0000127 CXCursor C = { CK, ND, 0 };
Steve Naroff69b10fd2009-09-01 15:55:40 +0000128 Callback(TUnit, C, CData);
129 }
Steve Naroff1054e602009-08-31 00:59:03 +0000130public:
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000131 TUVisitor(CXTranslationUnit CTU,
Douglas Gregor16bef852009-10-16 20:01:17 +0000132 CXTranslationUnitIterator cback, CXClientData D,
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000133 unsigned MaxPCHLevel) :
Douglas Gregor16bef852009-10-16 20:01:17 +0000134 TUnit(CTU), Callback(cback), CData(D), MaxPCHLevel(MaxPCHLevel) {}
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000135
Steve Naroff1054e602009-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 Kremenek98524b12009-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 Dunbarbbc569c2009-11-30 20:42:43 +0000160 }
Ted Kremenek98524b12009-11-17 07:02:15 +0000161 void VisitObjCProtocolDecl(ObjCProtocolDecl *ND) {
162 Call(CXCursor_ObjCProtocolDecl, ND);
Steve Naroff1054e602009-08-31 00:59:03 +0000163 }
164 void VisitTagDecl(TagDecl *ND) {
Steve Naroff3645f5a2009-09-02 13:28:54 +0000165 switch (ND->getTagKind()) {
Daniel Dunbar5b2f5ca2009-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 Naroff3645f5a2009-09-02 13:28:54 +0000178 }
Steve Naroff1054e602009-08-31 00:59:03 +0000179 }
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000180 void VisitTypedefDecl(TypedefDecl *ND) {
181 Call(CXCursor_TypedefDecl, ND);
182 }
Steve Naroff38c1a7b2009-09-03 15:49:00 +0000183 void VisitVarDecl(VarDecl *ND) {
184 Call(CXCursor_VarDecl, ND);
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000185 }
Steve Naroff1054e602009-08-31 00:59:03 +0000186};
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000187
Steve Naroff1054e602009-08-31 00:59:03 +0000188
Steve Naroff3645f5a2009-09-02 13:28:54 +0000189// Declaration visitor.
190class CDeclVisitor : public DeclVisitor<CDeclVisitor> {
191 CXDecl CDecl;
192 CXDeclIterator Callback;
193 CXClientData CData;
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000194
Douglas Gregor16bef852009-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 Dunbarbbc569c2009-11-30 20:42:43 +0000199
Steve Naroff3645f5a2009-09-02 13:28:54 +0000200 void Call(enum CXCursorKind CK, NamedDecl *ND) {
Steve Naroff38c1a7b2009-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 Dunbarbbc569c2009-11-30 20:42:43 +0000204
Douglas Gregor16bef852009-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 Dunbarbbc569c2009-11-30 20:42:43 +0000208
Steve Naroff66af1ae2009-09-22 19:25:29 +0000209 CXCursor C = { CK, ND, 0 };
Steve Naroff3645f5a2009-09-02 13:28:54 +0000210 Callback(CDecl, C, CData);
211 }
Steve Naroff1054e602009-08-31 00:59:03 +0000212public:
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000213 CDeclVisitor(CXDecl C, CXDeclIterator cback, CXClientData D,
214 unsigned MaxPCHLevel) :
Douglas Gregor16bef852009-10-16 20:01:17 +0000215 CDecl(C), Callback(cback), CData(D), MaxPCHLevel(MaxPCHLevel) {}
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000216
Steve Naroff38c1a7b2009-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 Naroff3645f5a2009-09-02 13:28:54 +0000223 void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Steve Naroff38c1a7b2009-09-03 15:49:00 +0000224 // Issue callbacks for super class.
Steve Naroff80a766b2009-09-02 18:26:48 +0000225 if (D->getSuperClass())
226 Call(CXCursor_ObjCSuperClassRef, D);
227
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000228 for (ObjCProtocolDecl::protocol_iterator I = D->protocol_begin(),
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +0000229 E = D->protocol_end(); I != E; ++I)
Steve Naroffef9618b2009-09-04 15:44:05 +0000230 Call(CXCursor_ObjCProtocolRef, *I);
Steve Naroff3645f5a2009-09-02 13:28:54 +0000231 VisitDeclContext(dyn_cast<DeclContext>(D));
232 }
Steve Naroffef9618b2009-09-04 15:44:05 +0000233 void VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000234 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +0000235 E = PID->protocol_end(); I != E; ++I)
Steve Naroffef9618b2009-09-04 15:44:05 +0000236 Call(CXCursor_ObjCProtocolRef, *I);
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000237
Steve Naroffef9618b2009-09-04 15:44:05 +0000238 VisitDeclContext(dyn_cast<DeclContext>(PID));
239 }
Steve Naroff3645f5a2009-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 Naroff1054e602009-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 Naroff3645f5a2009-09-02 13:28:54 +0000255 Call(CXCursor_EnumConstantDecl, ND);
Steve Naroff1054e602009-08-31 00:59:03 +0000256 }
257 void VisitFieldDecl(FieldDecl *ND) {
Steve Naroff3645f5a2009-09-02 13:28:54 +0000258 Call(CXCursor_FieldDecl, ND);
259 }
Steve Naroff38c1a7b2009-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 Naroff3645f5a2009-09-02 13:28:54 +0000266 void VisitObjCPropertyDecl(ObjCPropertyDecl *ND) {
267 Call(CXCursor_ObjCPropertyDecl, ND);
Steve Naroff1054e602009-08-31 00:59:03 +0000268 }
269 void VisitObjCIvarDecl(ObjCIvarDecl *ND) {
Steve Naroff3645f5a2009-09-02 13:28:54 +0000270 Call(CXCursor_ObjCIvarDecl, ND);
271 }
Steve Naroff38c1a7b2009-09-03 15:49:00 +0000272 void VisitFunctionDecl(FunctionDecl *ND) {
273 if (ND->isThisDeclarationADefinition()) {
274 VisitDeclContext(dyn_cast<DeclContext>(ND));
Steve Naroff76b8f132009-09-23 17:52:52 +0000275#if 0
276 // Not currently needed.
277 CompoundStmt *Body = dyn_cast<CompoundStmt>(ND->getBody());
Steve Naroff66af1ae2009-09-22 19:25:29 +0000278 CRefVisitor RVisit(CDecl, Callback, CData);
Steve Naroff76b8f132009-09-23 17:52:52 +0000279 RVisit.Visit(Body);
280#endif
Steve Naroff38c1a7b2009-09-03 15:49:00 +0000281 }
282 }
Steve Naroff3645f5a2009-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 Naroff38c1a7b2009-09-03 15:49:00 +0000287 VisitDeclContext(dyn_cast<DeclContext>(ND));
Steve Naroff3645f5a2009-09-02 13:28:54 +0000288 } else
289 Call(ND->isInstanceMethod() ? CXCursor_ObjCInstanceMethodDecl
290 : CXCursor_ObjCClassMethodDecl, ND);
Steve Naroff1054e602009-08-31 00:59:03 +0000291 }
292};
293
Douglas Gregor16bef852009-10-16 20:01:17 +0000294class CIndexer : public Indexer {
Daniel Dunbar1597da42009-12-06 09:56:30 +0000295 DiagnosticOptions DiagOpts;
Daniel Dunbar59203002009-12-03 01:45:44 +0000296 IgnoreDiagnosticsClient IgnoreDiagClient;
297 llvm::OwningPtr<Diagnostic> TextDiags;
298 Diagnostic IgnoreDiags;
299 bool UseExternalASTGeneration;
300 bool OnlyLocalDecls;
301 bool DisplayDiagnostics;
302
303 llvm::sys::Path ClangPath;
304
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000305public:
306 explicit CIndexer(Program *prog) : Indexer(*prog),
Daniel Dunbar59203002009-12-03 01:45:44 +0000307 IgnoreDiags(&IgnoreDiagClient),
308 UseExternalASTGeneration(false),
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000309 OnlyLocalDecls(false),
Daniel Dunbar59203002009-12-03 01:45:44 +0000310 DisplayDiagnostics(false) {
311 TextDiags.reset(
Daniel Dunbar1597da42009-12-06 09:56:30 +0000312 CompilerInstance::createDiagnostics(DiagOpts, 0, 0));
Daniel Dunbar59203002009-12-03 01:45:44 +0000313 }
Ted Kremenek05729c22009-10-17 06:21:47 +0000314
315 virtual ~CIndexer() { delete &getProgram(); }
Douglas Gregor16bef852009-10-16 20:01:17 +0000316
317 /// \brief Whether we only want to see "local" declarations (that did not
318 /// come from a previous precompiled header). If false, we want to see all
319 /// declarations.
320 bool getOnlyLocalDecls() const { return OnlyLocalDecls; }
321 void setOnlyLocalDecls(bool Local = true) { OnlyLocalDecls = Local; }
Benjamin Kramer817e7e42009-10-18 11:10:55 +0000322
Daniel Dunbar59203002009-12-03 01:45:44 +0000323 bool getDisplayDiagnostics() const { return DisplayDiagnostics; }
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000324 void setDisplayDiagnostics(bool Display = true) {
Steve Naroff531e2842009-10-20 14:46:24 +0000325 DisplayDiagnostics = Display;
326 }
Daniel Dunbar59203002009-12-03 01:45:44 +0000327
Daniel Dunbar11089662009-12-03 01:54:28 +0000328 bool getUseExternalASTGeneration() const { return UseExternalASTGeneration; }
329 void setUseExternalASTGeneration(bool Value) {
330 UseExternalASTGeneration = Value;
331 }
332
Daniel Dunbar59203002009-12-03 01:45:44 +0000333 Diagnostic &getDiags() {
334 return DisplayDiagnostics ? *TextDiags : IgnoreDiags;
335 }
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000336
Benjamin Kramer61f5d0c2009-10-18 16:11:04 +0000337 /// \brief Get the path of the clang binary.
Benjamin Kramerb625a132009-10-19 10:20:24 +0000338 const llvm::sys::Path& getClangPath();
Douglas Gregor16bef852009-10-16 20:01:17 +0000339};
Steve Naroff1054e602009-08-31 00:59:03 +0000340
Benjamin Kramer61f5d0c2009-10-18 16:11:04 +0000341const llvm::sys::Path& CIndexer::getClangPath() {
342 // Did we already compute the path?
343 if (!ClangPath.empty())
344 return ClangPath;
345
Steve Naroff7781daa2009-10-15 20:04:39 +0000346 // Find the location where this library lives (libCIndex.dylib).
Benjamin Kramer6bd6d502009-10-18 16:13:48 +0000347#ifdef LLVM_ON_WIN32
348 MEMORY_BASIC_INFORMATION mbi;
349 char path[MAX_PATH];
Benjamin Kramer49ce64e2009-10-18 16:20:58 +0000350 VirtualQuery((void *)(uintptr_t)clang_createTranslationUnit, &mbi,
Benjamin Kramer6bd6d502009-10-18 16:13:48 +0000351 sizeof(mbi));
352 GetModuleFileNameA((HINSTANCE)mbi.AllocationBase, path, MAX_PATH);
353
354 llvm::sys::Path CIndexPath(path);
John Thompson92ebab92009-11-11 23:11:14 +0000355
356 CIndexPath.eraseComponent();
357 CIndexPath.appendComponent("clang");
358 CIndexPath.appendSuffix("exe");
359 CIndexPath.makeAbsolute();
Benjamin Kramer6bd6d502009-10-18 16:13:48 +0000360#else
Steve Naroff7781daa2009-10-15 20:04:39 +0000361 // This silly cast below avoids a C++ warning.
362 Dl_info info;
363 if (dladdr((void *)(uintptr_t)clang_createTranslationUnit, &info) == 0)
364 assert(0 && "Call to dladdr() failed");
365
366 llvm::sys::Path CIndexPath(info.dli_fname);
Benjamin Kramer61f5d0c2009-10-18 16:11:04 +0000367
Steve Naroff7781daa2009-10-15 20:04:39 +0000368 // We now have the CIndex directory, locate clang relative to it.
Benjamin Kramer61f5d0c2009-10-18 16:11:04 +0000369 CIndexPath.eraseComponent();
370 CIndexPath.eraseComponent();
371 CIndexPath.appendComponent("bin");
372 CIndexPath.appendComponent("clang");
John Thompson92ebab92009-11-11 23:11:14 +0000373#endif
Benjamin Kramer61f5d0c2009-10-18 16:11:04 +0000374
375 // Cache our result.
376 ClangPath = CIndexPath;
377 return ClangPath;
378}
379
380}
381
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000382static SourceLocation getLocationFromCursor(CXCursor C,
Daniel Dunbar2679a882009-11-08 04:13:53 +0000383 SourceManager &SourceMgr,
384 NamedDecl *ND) {
385 if (clang_isReference(C.kind)) {
386 switch (C.kind) {
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +0000387 case CXCursor_ObjCClassRef: {
388 if (isa<ObjCInterfaceDecl>(ND)) {
389 // FIXME: This is a hack (storing the parent decl in the stmt slot).
390 NamedDecl *parentDecl = static_cast<NamedDecl *>(C.stmt);
391 return parentDecl->getLocation();
Daniel Dunbar2679a882009-11-08 04:13:53 +0000392 }
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +0000393 ObjCCategoryDecl *OID = dyn_cast<ObjCCategoryDecl>(ND);
394 assert(OID && "clang_getCursorLine(): Missing category decl");
395 return OID->getClassInterface()->getLocation();
396 }
397 case CXCursor_ObjCSuperClassRef: {
398 ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ND);
399 assert(OID && "clang_getCursorLine(): Missing interface decl");
400 return OID->getSuperClassLoc();
401 }
402 case CXCursor_ObjCProtocolRef: {
403 ObjCProtocolDecl *OID = dyn_cast<ObjCProtocolDecl>(ND);
404 assert(OID && "clang_getCursorLine(): Missing protocol decl");
405 return OID->getLocation();
406 }
407 case CXCursor_ObjCSelectorRef: {
408 ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(
409 static_cast<Stmt *>(C.stmt));
410 assert(OME && "clang_getCursorLine(): Missing message expr");
411 return OME->getLeftLoc(); /* FIXME: should be a range */
412 }
413 case CXCursor_VarRef:
414 case CXCursor_FunctionRef:
415 case CXCursor_EnumConstantRef: {
416 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(
417 static_cast<Stmt *>(C.stmt));
418 assert(DRE && "clang_getCursorLine(): Missing decl ref expr");
419 return DRE->getLocation();
420 }
421 default:
422 return SourceLocation();
Daniel Dunbar2679a882009-11-08 04:13:53 +0000423 }
424 } else { // We have a declaration or a definition.
425 SourceLocation SLoc;
426 switch (ND->getKind()) {
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +0000427 case Decl::ObjCInterface: {
428 SLoc = dyn_cast<ObjCInterfaceDecl>(ND)->getClassLoc();
429 break;
430 }
431 case Decl::ObjCProtocol: {
432 SLoc = ND->getLocation(); /* FIXME: need to get the name location. */
433 break;
434 }
435 default: {
436 SLoc = ND->getLocation();
437 break;
438 }
Daniel Dunbar2679a882009-11-08 04:13:53 +0000439 }
440 if (SLoc.isInvalid())
441 return SourceLocation();
442 return SourceMgr.getSpellingLoc(SLoc); // handles macro instantiations.
443 }
444}
445
Benjamin Kramer04c99a62009-11-09 19:13:48 +0000446static CXString createCXString(const char *String, bool DupString = false) {
447 CXString Str;
448 if (DupString) {
449 Str.Spelling = strdup(String);
450 Str.MustFreeString = 1;
451 } else {
452 Str.Spelling = String;
453 Str.MustFreeString = 0;
454 }
455 return Str;
456}
457
Benjamin Kramer61f5d0c2009-10-18 16:11:04 +0000458extern "C" {
459
Steve Naroff531e2842009-10-20 14:46:24 +0000460CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
Daniel Dunbar079203f2009-12-01 03:14:51 +0000461 int displayDiagnostics) {
Steve Naroff531e2842009-10-20 14:46:24 +0000462 CIndexer *CIdxr = new CIndexer(new Program());
463 if (excludeDeclarationsFromPCH)
464 CIdxr->setOnlyLocalDecls();
465 if (displayDiagnostics)
466 CIdxr->setDisplayDiagnostics();
467 return CIdxr;
Steve Naroffd5e8e862009-08-27 19:51:58 +0000468}
469
Daniel Dunbar079203f2009-12-01 03:14:51 +0000470void clang_disposeIndex(CXIndex CIdx) {
Steve Naroff3aa2d732009-09-17 18:33:27 +0000471 assert(CIdx && "Passed null CXIndex");
Douglas Gregor16bef852009-10-16 20:01:17 +0000472 delete static_cast<CIndexer *>(CIdx);
Steve Naroff3aa2d732009-09-17 18:33:27 +0000473}
474
Daniel Dunbar11089662009-12-03 01:54:28 +0000475void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
476 assert(CIdx && "Passed null CXIndex");
477 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
478 CXXIdx->setUseExternalASTGeneration(value);
479}
480
Steve Naroffa1c72842009-08-28 15:28:48 +0000481// FIXME: need to pass back error info.
Daniel Dunbar079203f2009-12-01 03:14:51 +0000482CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
483 const char *ast_filename) {
Steve Naroffa1c72842009-08-28 15:28:48 +0000484 assert(CIdx && "Passed null CXIndex");
Douglas Gregor16bef852009-10-16 20:01:17 +0000485 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000486
Daniel Dunbar59203002009-12-03 01:45:44 +0000487 return ASTUnit::LoadFromPCHFile(ast_filename, CXXIdx->getDiags(),
488 CXXIdx->getOnlyLocalDecls(),
489 /* UseBumpAllocator = */ true);
Steve Naroffd5e8e862009-08-27 19:51:58 +0000490}
491
Daniel Dunbar079203f2009-12-01 03:14:51 +0000492CXTranslationUnit
493clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
494 const char *source_filename,
495 int num_command_line_args,
496 const char **command_line_args) {
Steve Naroff531e2842009-10-20 14:46:24 +0000497 assert(CIdx && "Passed null CXIndex");
498 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
499
Daniel Dunbar11089662009-12-03 01:54:28 +0000500 if (!CXXIdx->getUseExternalASTGeneration()) {
501 llvm::SmallVector<const char *, 16> Args;
502
503 // The 'source_filename' argument is optional. If the caller does not
504 // specify it then it is assumed that the source file is specified
505 // in the actual argument list.
506 if (source_filename)
507 Args.push_back(source_filename);
508 Args.insert(Args.end(), command_line_args,
509 command_line_args + num_command_line_args);
510
511 void *MainAddr = (void *)(uintptr_t)clang_createTranslationUnit;
Daniel Dunbar72fe5b12009-12-05 02:17:18 +0000512
513 unsigned NumErrors = CXXIdx->getDiags().getNumErrors();
514 llvm::OwningPtr<ASTUnit> Unit(
515 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
516 CXXIdx->getDiags(), "<clang>", MainAddr,
517 CXXIdx->getOnlyLocalDecls(),
518 /* UseBumpAllocator = */ true));
519
520 // FIXME: Until we have broader testing, just drop the entire AST if we
521 // encountered an error.
522 if (NumErrors != CXXIdx->getDiags().getNumErrors())
523 return 0;
524
525 return Unit.take();
Daniel Dunbar11089662009-12-03 01:54:28 +0000526 }
527
Ted Kremenek649bf5c2009-10-22 00:03:57 +0000528 // Build up the arguments for invoking 'clang'.
Ted Kremenek51d06bb2009-10-15 23:21:22 +0000529 std::vector<const char *> argv;
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000530
Ted Kremenek649bf5c2009-10-22 00:03:57 +0000531 // First add the complete path to the 'clang' executable.
532 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer61f5d0c2009-10-18 16:11:04 +0000533 argv.push_back(ClangPath.c_str());
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000534
Ted Kremenek649bf5c2009-10-22 00:03:57 +0000535 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek51d06bb2009-10-15 23:21:22 +0000536 argv.push_back("-emit-ast");
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000537
Ted Kremenek649bf5c2009-10-22 00:03:57 +0000538 // The 'source_filename' argument is optional. If the caller does not
539 // specify it then it is assumed that the source file is specified
540 // in the actual argument list.
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000541 if (source_filename)
542 argv.push_back(source_filename);
Ted Kremenek649bf5c2009-10-22 00:03:57 +0000543
Steve Naroff1cfb96c2009-10-15 20:50:09 +0000544 // Generate a temporary name for the AST file.
Ted Kremenek649bf5c2009-10-22 00:03:57 +0000545 argv.push_back("-o");
Steve Naroff1cfb96c2009-10-15 20:50:09 +0000546 char astTmpFile[L_tmpnam];
Ted Kremenek51d06bb2009-10-15 23:21:22 +0000547 argv.push_back(tmpnam(astTmpFile));
Ted Kremenek649bf5c2009-10-22 00:03:57 +0000548
549 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
550 for (int i = 0; i < num_command_line_args; ++i)
551 if (const char *arg = command_line_args[i]) {
552 if (strcmp(arg, "-o") == 0) {
553 ++i; // Also skip the matching argument.
554 continue;
555 }
556 if (strcmp(arg, "-emit-ast") == 0 ||
557 strcmp(arg, "-c") == 0 ||
558 strcmp(arg, "-fsyntax-only") == 0) {
559 continue;
560 }
561
562 // Keep the argument.
563 argv.push_back(arg);
Steve Naroff531e2842009-10-20 14:46:24 +0000564 }
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000565
Ted Kremenek649bf5c2009-10-22 00:03:57 +0000566 // Add the null terminator.
Ted Kremenek51d06bb2009-10-15 23:21:22 +0000567 argv.push_back(NULL);
568
Ted Kremenek12e678d2009-10-26 22:14:08 +0000569 // Invoke 'clang'.
570 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
571 // on Unix or NUL (Windows).
Ted Kremenek44886fd2009-10-22 03:24:01 +0000572 std::string ErrMsg;
Ted Kremeneke2896882009-10-19 22:27:32 +0000573 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DevNull, NULL };
Ted Kremenek44886fd2009-10-22 03:24:01 +0000574 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
575 /* redirects */ !CXXIdx->getDisplayDiagnostics() ? &Redirects[0] : NULL,
576 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000577
Ted Kremenekba645742009-11-10 19:18:52 +0000578 if (CXXIdx->getDisplayDiagnostics() && !ErrMsg.empty()) {
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000579 llvm::errs() << "clang_createTranslationUnitFromSourceFile: " << ErrMsg
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +0000580 << '\n' << "Arguments: \n";
Ted Kremenek44886fd2009-10-22 03:24:01 +0000581 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Ted Kremenekbf0690c2009-10-26 22:08:39 +0000582 I!=E; ++I) {
583 if (*I)
584 llvm::errs() << ' ' << *I << '\n';
585 }
586 llvm::errs() << '\n';
Ted Kremenek44886fd2009-10-22 03:24:01 +0000587 }
Benjamin Kramer2836c4c2009-10-18 11:19:36 +0000588
Steve Naroff1cfb96c2009-10-15 20:50:09 +0000589 // Finally, we create the translation unit from the ast file.
Steve Naroff44cd60e2009-10-15 22:23:48 +0000590 ASTUnit *ATU = static_cast<ASTUnit *>(
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +0000591 clang_createTranslationUnit(CIdx, astTmpFile));
Steve Naroff531e2842009-10-20 14:46:24 +0000592 if (ATU)
593 ATU->unlinkTemporaryFile();
Steve Naroff44cd60e2009-10-15 22:23:48 +0000594 return ATU;
Steve Naroff7781daa2009-10-15 20:04:39 +0000595}
596
Daniel Dunbar079203f2009-12-01 03:14:51 +0000597void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Steve Naroff3aa2d732009-09-17 18:33:27 +0000598 assert(CTUnit && "Passed null CXTranslationUnit");
599 delete static_cast<ASTUnit *>(CTUnit);
600}
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000601
Daniel Dunbar079203f2009-12-01 03:14:51 +0000602CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Steve Naroff38c1a7b2009-09-03 15:49:00 +0000603 assert(CTUnit && "Passed null CXTranslationUnit");
Steve Naroffc0683b92009-09-03 18:19:54 +0000604 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Benjamin Kramer04c99a62009-11-09 19:13:48 +0000605 return createCXString(CXXUnit->getOriginalSourceFileName().c_str(), true);
Steve Naroff38c1a7b2009-09-03 15:49:00 +0000606}
Daniel Dunbare58bd8b2009-08-28 16:30:07 +0000607
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000608void clang_loadTranslationUnit(CXTranslationUnit CTUnit,
Steve Naroff3645f5a2009-09-02 13:28:54 +0000609 CXTranslationUnitIterator callback,
Daniel Dunbar079203f2009-12-01 03:14:51 +0000610 CXClientData CData) {
Steve Naroffa1c72842009-08-28 15:28:48 +0000611 assert(CTUnit && "Passed null CXTranslationUnit");
612 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
613 ASTContext &Ctx = CXXUnit->getASTContext();
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000614
Daniel Dunbar11089662009-12-03 01:54:28 +0000615 unsigned PCHLevel = Decl::MaxPCHLevel;
616
617 // Set the PCHLevel to filter out unwanted decls if requested.
618 if (CXXUnit->getOnlyLocalDecls()) {
619 PCHLevel = 0;
620
621 // If the main input was an AST, bump the level.
622 if (CXXUnit->isMainFileAST())
623 ++PCHLevel;
624 }
625
626 TUVisitor DVisit(CTUnit, callback, CData, PCHLevel);
Daniel Dunbar644dca02009-12-04 08:17:33 +0000627
628 // If using a non-AST based ASTUnit, iterate over the stored list of top-level
629 // decls.
630 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls()) {
631 const std::vector<Decl*> &TLDs = CXXUnit->getTopLevelDecls();
632 for (std::vector<Decl*>::const_iterator it = TLDs.begin(),
633 ie = TLDs.end(); it != ie; ++it) {
634 DVisit.Visit(*it);
635 }
636 } else
637 DVisit.Visit(Ctx.getTranslationUnitDecl());
Steve Naroffd5e8e862009-08-27 19:51:58 +0000638}
639
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000640void clang_loadDeclaration(CXDecl Dcl,
641 CXDeclIterator callback,
Daniel Dunbar079203f2009-12-01 03:14:51 +0000642 CXClientData CData) {
Steve Naroff3645f5a2009-09-02 13:28:54 +0000643 assert(Dcl && "Passed null CXDecl");
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000644
Douglas Gregor16bef852009-10-16 20:01:17 +0000645 CDeclVisitor DVisit(Dcl, callback, CData,
646 static_cast<Decl *>(Dcl)->getPCHLevel());
Steve Naroff3645f5a2009-09-02 13:28:54 +0000647 DVisit.Visit(static_cast<Decl *>(Dcl));
Steve Naroffd5e8e862009-08-27 19:51:58 +0000648}
649
Steve Naroff87219592009-08-28 12:07:44 +0000650// Some notes on CXEntity:
651//
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000652// - Since the 'ordinary' namespace includes functions, data, typedefs,
653// ObjC interfaces, thecurrent algorithm is a bit naive (resulting in one
Steve Naroff87219592009-08-28 12:07:44 +0000654// entity for 2 different types). For example:
655//
656// module1.m: @interface Foo @end Foo *x;
657// module2.m: void Foo(int);
658//
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000659// - Since the unique name spans translation units, static data/functions
Steve Naroff87219592009-08-28 12:07:44 +0000660// within a CXTranslationUnit are *not* currently represented by entities.
661// As a result, there will be no entity for the following:
662//
663// module.m: static void Foo() { }
664//
665
666
Daniel Dunbar079203f2009-12-01 03:14:51 +0000667const char *clang_getDeclarationName(CXEntity) {
Steve Naroffd5e8e862009-08-27 19:51:58 +0000668 return "";
669}
670
Daniel Dunbar079203f2009-12-01 03:14:51 +0000671const char *clang_getURI(CXEntity) {
672 return "";
673}
674
675CXEntity clang_getEntity(const char *URI) {
Steve Naroffd5e8e862009-08-27 19:51:58 +0000676 return 0;
677}
678
679//
680// CXDecl Operations.
681//
Daniel Dunbar079203f2009-12-01 03:14:51 +0000682
683CXEntity clang_getEntityFromDecl(CXDecl) {
Steve Naroffd5e8e862009-08-27 19:51:58 +0000684 return 0;
685}
Daniel Dunbar079203f2009-12-01 03:14:51 +0000686
687CXString clang_getDeclSpelling(CXDecl AnonDecl) {
Steve Naroff1054e602009-08-31 00:59:03 +0000688 assert(AnonDecl && "Passed null CXDecl");
689 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
Steve Naroff8675d5c2009-11-09 17:45:52 +0000690
Benjamin Kramer04c99a62009-11-09 19:13:48 +0000691 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
692 return createCXString(OMD->getSelector().getAsString().c_str(), true);
693
694 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Steve Narofff406f4d2009-10-29 21:11:04 +0000695 // No, this isn't the same as the code below. getIdentifier() is non-virtual
696 // and returns different names. NamedDecl returns the class name and
697 // ObjCCategoryImplDecl returns the category name.
Benjamin Kramer04c99a62009-11-09 19:13:48 +0000698 return createCXString(CIMP->getIdentifier()->getNameStart());
699
700 if (ND->getIdentifier())
701 return createCXString(ND->getIdentifier()->getNameStart());
702
703 return createCXString("");
Steve Naroffd5e8e862009-08-27 19:51:58 +0000704}
Steve Naroff80a766b2009-09-02 18:26:48 +0000705
Daniel Dunbar079203f2009-12-01 03:14:51 +0000706unsigned clang_getDeclLine(CXDecl AnonDecl) {
Steve Naroff63f475a2009-09-25 21:32:34 +0000707 assert(AnonDecl && "Passed null CXDecl");
708 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
709 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
710 return SourceMgr.getSpellingLineNumber(ND->getLocation());
711}
712
Daniel Dunbar079203f2009-12-01 03:14:51 +0000713unsigned clang_getDeclColumn(CXDecl AnonDecl) {
Steve Naroff63f475a2009-09-25 21:32:34 +0000714 assert(AnonDecl && "Passed null CXDecl");
715 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
716 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Steve Naroff43b118f2009-09-25 22:15:54 +0000717 return SourceMgr.getSpellingColumnNumber(ND->getLocation());
Steve Naroff63f475a2009-09-25 21:32:34 +0000718}
719
Daniel Dunbar079203f2009-12-01 03:14:51 +0000720const char *clang_getDeclSource(CXDecl AnonDecl) {
Steve Naroff26760892009-09-25 21:45:39 +0000721 assert(AnonDecl && "Passed null CXDecl");
Steve Naroff6231f182009-10-27 14:35:18 +0000722 FileEntry *FEnt = static_cast<FileEntry *>(clang_getDeclSourceFile(AnonDecl));
723 assert (FEnt && "Cannot find FileEntry for Decl");
724 return clang_getFileName(FEnt);
725}
726
727static const FileEntry *getFileEntryFromSourceLocation(SourceManager &SMgr,
Daniel Dunbar079203f2009-12-01 03:14:51 +0000728 SourceLocation SLoc) {
Steve Naroff6231f182009-10-27 14:35:18 +0000729 FileID FID;
730 if (SLoc.isFileID())
731 FID = SMgr.getFileID(SLoc);
732 else
733 FID = SMgr.getDecomposedSpellingLoc(SLoc).first;
734 return SMgr.getFileEntryForID(FID);
735}
736
Daniel Dunbar079203f2009-12-01 03:14:51 +0000737CXFile clang_getDeclSourceFile(CXDecl AnonDecl) {
Steve Naroff6231f182009-10-27 14:35:18 +0000738 assert(AnonDecl && "Passed null CXDecl");
Steve Naroff26760892009-09-25 21:45:39 +0000739 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
740 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Steve Naroff6231f182009-10-27 14:35:18 +0000741 return (void *)getFileEntryFromSourceLocation(SourceMgr, ND->getLocation());
742}
743
744const char *clang_getFileName(CXFile SFile) {
745 assert(SFile && "Passed null CXFile");
746 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
747 return FEnt->getName();
748}
749
750time_t clang_getFileTime(CXFile SFile) {
751 assert(SFile && "Passed null CXFile");
752 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
753 return FEnt->getModificationTime();
Steve Naroff26760892009-09-25 21:45:39 +0000754}
755
Daniel Dunbar079203f2009-12-01 03:14:51 +0000756CXString clang_getCursorSpelling(CXCursor C) {
Steve Naroff80a766b2009-09-02 18:26:48 +0000757 assert(C.decl && "CXCursor has null decl");
758 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
Steve Naroff8675d5c2009-11-09 17:45:52 +0000759
Steve Naroff80a766b2009-09-02 18:26:48 +0000760 if (clang_isReference(C.kind)) {
761 switch (C.kind) {
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +0000762 case CXCursor_ObjCSuperClassRef: {
763 ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ND);
764 assert(OID && "clang_getCursorLine(): Missing interface decl");
765 return createCXString(OID->getSuperClass()->getIdentifier()
766 ->getNameStart());
767 }
768 case CXCursor_ObjCClassRef: {
769 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ND))
Benjamin Kramer04c99a62009-11-09 19:13:48 +0000770 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +0000771
772 ObjCCategoryDecl *OCD = dyn_cast<ObjCCategoryDecl>(ND);
773 assert(OCD && "clang_getCursorLine(): Missing category decl");
774 return createCXString(OCD->getClassInterface()->getIdentifier()
775 ->getNameStart());
776 }
777 case CXCursor_ObjCProtocolRef: {
778 ObjCProtocolDecl *OID = dyn_cast<ObjCProtocolDecl>(ND);
779 assert(OID && "clang_getCursorLine(): Missing protocol decl");
780 return createCXString(OID->getIdentifier()->getNameStart());
781 }
782 case CXCursor_ObjCSelectorRef: {
783 ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(
784 static_cast<Stmt *>(C.stmt));
785 assert(OME && "clang_getCursorLine(): Missing message expr");
786 return createCXString(OME->getSelector().getAsString().c_str(), true);
787 }
788 case CXCursor_VarRef:
789 case CXCursor_FunctionRef:
790 case CXCursor_EnumConstantRef: {
791 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(
792 static_cast<Stmt *>(C.stmt));
793 assert(DRE && "clang_getCursorLine(): Missing decl ref expr");
794 return createCXString(DRE->getDecl()->getIdentifier()->getNameStart());
795 }
796 default:
797 return createCXString("<not implemented>");
Steve Naroff80a766b2009-09-02 18:26:48 +0000798 }
799 }
800 return clang_getDeclSpelling(C.decl);
801}
802
Daniel Dunbar079203f2009-12-01 03:14:51 +0000803const char *clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff1054e602009-08-31 00:59:03 +0000804 switch (Kind) {
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +0000805 case CXCursor_FunctionDecl: return "FunctionDecl";
806 case CXCursor_TypedefDecl: return "TypedefDecl";
807 case CXCursor_EnumDecl: return "EnumDecl";
808 case CXCursor_EnumConstantDecl: return "EnumConstantDecl";
809 case CXCursor_StructDecl: return "StructDecl";
810 case CXCursor_UnionDecl: return "UnionDecl";
811 case CXCursor_ClassDecl: return "ClassDecl";
812 case CXCursor_FieldDecl: return "FieldDecl";
813 case CXCursor_VarDecl: return "VarDecl";
814 case CXCursor_ParmDecl: return "ParmDecl";
815 case CXCursor_ObjCInterfaceDecl: return "ObjCInterfaceDecl";
816 case CXCursor_ObjCCategoryDecl: return "ObjCCategoryDecl";
817 case CXCursor_ObjCProtocolDecl: return "ObjCProtocolDecl";
818 case CXCursor_ObjCPropertyDecl: return "ObjCPropertyDecl";
819 case CXCursor_ObjCIvarDecl: return "ObjCIvarDecl";
820 case CXCursor_ObjCInstanceMethodDecl: return "ObjCInstanceMethodDecl";
821 case CXCursor_ObjCClassMethodDecl: return "ObjCClassMethodDecl";
822 case CXCursor_FunctionDefn: return "FunctionDefn";
823 case CXCursor_ObjCInstanceMethodDefn: return "ObjCInstanceMethodDefn";
824 case CXCursor_ObjCClassMethodDefn: return "ObjCClassMethodDefn";
825 case CXCursor_ObjCClassDefn: return "ObjCClassDefn";
826 case CXCursor_ObjCCategoryDefn: return "ObjCCategoryDefn";
827 case CXCursor_ObjCSuperClassRef: return "ObjCSuperClassRef";
828 case CXCursor_ObjCProtocolRef: return "ObjCProtocolRef";
829 case CXCursor_ObjCClassRef: return "ObjCClassRef";
830 case CXCursor_ObjCSelectorRef: return "ObjCSelectorRef";
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000831
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +0000832 case CXCursor_VarRef: return "VarRef";
833 case CXCursor_FunctionRef: return "FunctionRef";
834 case CXCursor_EnumConstantRef: return "EnumConstantRef";
835 case CXCursor_MemberRef: return "MemberRef";
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000836
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +0000837 case CXCursor_InvalidFile: return "InvalidFile";
838 case CXCursor_NoDeclFound: return "NoDeclFound";
839 case CXCursor_NotImplemented: return "NotImplemented";
840 default: return "<not implemented>";
Steve Naroff1054e602009-08-31 00:59:03 +0000841 }
Steve Naroffd5e8e862009-08-27 19:51:58 +0000842}
Steve Naroff1054e602009-08-31 00:59:03 +0000843
Steve Naroffef9618b2009-09-04 15:44:05 +0000844static enum CXCursorKind TranslateKind(Decl *D) {
845 switch (D->getKind()) {
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +0000846 case Decl::Function: return CXCursor_FunctionDecl;
847 case Decl::Typedef: return CXCursor_TypedefDecl;
848 case Decl::Enum: return CXCursor_EnumDecl;
849 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
850 case Decl::Record: return CXCursor_StructDecl; // FIXME: union/class
851 case Decl::Field: return CXCursor_FieldDecl;
852 case Decl::Var: return CXCursor_VarDecl;
853 case Decl::ParmVar: return CXCursor_ParmDecl;
854 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
855 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
856 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
857 case Decl::ObjCMethod: {
858 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D);
859 if (MD->isInstanceMethod())
860 return CXCursor_ObjCInstanceMethodDecl;
861 return CXCursor_ObjCClassMethodDecl;
862 }
863 default: break;
Steve Naroffef9618b2009-09-04 15:44:05 +0000864 }
Steve Naroff54f22fb2009-09-15 20:25:34 +0000865 return CXCursor_NotImplemented;
Steve Naroffef9618b2009-09-04 15:44:05 +0000866}
Steve Naroffd5e8e862009-08-27 19:51:58 +0000867//
868// CXCursor Operations.
869//
Daniel Dunbar079203f2009-12-01 03:14:51 +0000870
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000871CXCursor clang_getCursor(CXTranslationUnit CTUnit, const char *source_name,
Daniel Dunbar079203f2009-12-01 03:14:51 +0000872 unsigned line, unsigned column) {
Steve Naroffef9618b2009-09-04 15:44:05 +0000873 assert(CTUnit && "Passed null CXTranslationUnit");
874 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000875
Steve Naroffef9618b2009-09-04 15:44:05 +0000876 FileManager &FMgr = CXXUnit->getFileManager();
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000877 const FileEntry *File = FMgr.getFile(source_name,
878 source_name+strlen(source_name));
Steve Naroff54f22fb2009-09-15 20:25:34 +0000879 if (!File) {
Steve Naroff66af1ae2009-09-22 19:25:29 +0000880 CXCursor C = { CXCursor_InvalidFile, 0, 0 };
Steve Naroff54f22fb2009-09-15 20:25:34 +0000881 return C;
882 }
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000883 SourceLocation SLoc =
Steve Naroffef9618b2009-09-04 15:44:05 +0000884 CXXUnit->getSourceManager().getLocation(File, line, column);
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000885
Steve Naroff58bd62d2009-10-28 20:44:47 +0000886 ASTLocation LastLoc = CXXUnit->getLastASTLocation();
887
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000888 ASTLocation ALoc = ResolveLocationInAST(CXXUnit->getASTContext(), SLoc,
Steve Naroff58bd62d2009-10-28 20:44:47 +0000889 &LastLoc);
890 if (ALoc.isValid())
891 CXXUnit->setLastASTLocation(ALoc);
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000892
Argyrios Kyrtzidis4cbe8592009-09-29 19:44:27 +0000893 Decl *Dcl = ALoc.getParentDecl();
Argyrios Kyrtzidis419e38b2009-09-29 19:45:58 +0000894 if (ALoc.isNamedRef())
895 Dcl = ALoc.AsNamedRef().ND;
Argyrios Kyrtzidis4cbe8592009-09-29 19:44:27 +0000896 Stmt *Stm = ALoc.dyn_AsStmt();
Steve Naroff76b8f132009-09-23 17:52:52 +0000897 if (Dcl) {
898 if (Stm) {
899 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Stm)) {
900 CXCursor C = { TranslateDeclRefExpr(DRE), Dcl, Stm };
901 return C;
902 } else if (ObjCMessageExpr *MExp = dyn_cast<ObjCMessageExpr>(Stm)) {
903 CXCursor C = { CXCursor_ObjCSelectorRef, Dcl, MExp };
904 return C;
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000905 }
Steve Naroff76b8f132009-09-23 17:52:52 +0000906 // Fall through...treat as a decl, not a ref.
907 }
Steve Naroffa6c56bb2009-10-01 00:31:07 +0000908 if (ALoc.isNamedRef()) {
909 if (isa<ObjCInterfaceDecl>(Dcl)) {
910 CXCursor C = { CXCursor_ObjCClassRef, Dcl, ALoc.getParentDecl() };
911 return C;
912 }
913 if (isa<ObjCProtocolDecl>(Dcl)) {
914 CXCursor C = { CXCursor_ObjCProtocolRef, Dcl, ALoc.getParentDecl() };
915 return C;
916 }
917 }
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +0000918 CXCursor C = { TranslateKind(Dcl), Dcl, 0 };
Steve Naroff54f22fb2009-09-15 20:25:34 +0000919 return C;
920 }
Steve Naroff66af1ae2009-09-22 19:25:29 +0000921 CXCursor C = { CXCursor_NoDeclFound, 0, 0 };
Steve Naroffef9618b2009-09-04 15:44:05 +0000922 return C;
Steve Naroffd5e8e862009-08-27 19:51:58 +0000923}
924
Ted Kremeneke05d7802009-11-17 19:28:59 +0000925CXCursor clang_getNullCursor(void) {
926 CXCursor C;
927 C.kind = CXCursor_InvalidFile;
928 C.decl = NULL;
929 C.stmt = NULL;
930 return C;
931}
932
933unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
934 return X.kind == Y.kind && X.decl == Y.decl && X.stmt == Y.stmt;
935}
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000936
Daniel Dunbar079203f2009-12-01 03:14:51 +0000937CXCursor clang_getCursorFromDecl(CXDecl AnonDecl) {
Steve Naroff54f22fb2009-09-15 20:25:34 +0000938 assert(AnonDecl && "Passed null CXDecl");
939 NamedDecl *ND = static_cast<NamedDecl *>(AnonDecl);
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000940
Steve Naroff66af1ae2009-09-22 19:25:29 +0000941 CXCursor C = { TranslateKind(ND), ND, 0 };
Steve Naroff54f22fb2009-09-15 20:25:34 +0000942 return C;
943}
944
Daniel Dunbar079203f2009-12-01 03:14:51 +0000945unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff54f22fb2009-09-15 20:25:34 +0000946 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
947}
948
Daniel Dunbar079203f2009-12-01 03:14:51 +0000949unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff1054e602009-08-31 00:59:03 +0000950 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
951}
Steve Naroff772c1a42009-08-31 14:26:51 +0000952
Daniel Dunbar079203f2009-12-01 03:14:51 +0000953unsigned clang_isReference(enum CXCursorKind K) {
Steve Naroff80a766b2009-09-02 18:26:48 +0000954 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
955}
956
Daniel Dunbar079203f2009-12-01 03:14:51 +0000957unsigned clang_isDefinition(enum CXCursorKind K) {
Steve Naroff80a766b2009-09-02 18:26:48 +0000958 return K >= CXCursor_FirstDefn && K <= CXCursor_LastDefn;
959}
960
Daniel Dunbar079203f2009-12-01 03:14:51 +0000961CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroffef9618b2009-09-04 15:44:05 +0000962 return C.kind;
963}
964
Steve Naroff63f475a2009-09-25 21:32:34 +0000965static Decl *getDeclFromExpr(Stmt *E) {
966 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
967 return RefExpr->getDecl();
968 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
969 return ME->getMemberDecl();
970 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
971 return RE->getDecl();
972
973 if (CallExpr *CE = dyn_cast<CallExpr>(E))
974 return getDeclFromExpr(CE->getCallee());
975 if (CastExpr *CE = dyn_cast<CastExpr>(E))
976 return getDeclFromExpr(CE->getSubExpr());
977 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
978 return OME->getMethodDecl();
979
980 return 0;
981}
982
Daniel Dunbar079203f2009-12-01 03:14:51 +0000983CXDecl clang_getCursorDecl(CXCursor C) {
Steve Naroff63f475a2009-09-25 21:32:34 +0000984 if (clang_isDeclaration(C.kind))
985 return C.decl;
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000986
Steve Naroff63f475a2009-09-25 21:32:34 +0000987 if (clang_isReference(C.kind)) {
Steve Naroffa6c56bb2009-10-01 00:31:07 +0000988 if (C.stmt) {
Daniel Dunbarbbc569c2009-11-30 20:42:43 +0000989 if (C.kind == CXCursor_ObjCClassRef ||
Steve Naroffd7eb7172009-10-05 17:58:19 +0000990 C.kind == CXCursor_ObjCProtocolRef)
Steve Naroffa6c56bb2009-10-01 00:31:07 +0000991 return static_cast<Stmt *>(C.stmt);
992 else
993 return getDeclFromExpr(static_cast<Stmt *>(C.stmt));
994 } else
Steve Naroff63f475a2009-09-25 21:32:34 +0000995 return C.decl;
996 }
997 return 0;
Steve Naroffef9618b2009-09-04 15:44:05 +0000998}
999
Daniel Dunbar079203f2009-12-01 03:14:51 +00001000unsigned clang_getCursorLine(CXCursor C) {
Steve Naroff772c1a42009-08-31 14:26:51 +00001001 assert(C.decl && "CXCursor has null decl");
1002 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
Steve Naroff772c1a42009-08-31 14:26:51 +00001003 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001004
Steve Naroff80a766b2009-09-02 18:26:48 +00001005 SourceLocation SLoc = getLocationFromCursor(C, SourceMgr, ND);
Steve Naroff772c1a42009-08-31 14:26:51 +00001006 return SourceMgr.getSpellingLineNumber(SLoc);
Steve Naroffd5e8e862009-08-27 19:51:58 +00001007}
Steve Naroff80a766b2009-09-02 18:26:48 +00001008
Steve Naroff8675d5c2009-11-09 17:45:52 +00001009const char *clang_getCString(CXString string) {
1010 return string.Spelling;
1011}
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001012
Steve Naroff8675d5c2009-11-09 17:45:52 +00001013void clang_disposeString(CXString string) {
Benjamin Kramerd6f85a82009-11-09 18:24:53 +00001014 if (string.MustFreeString)
1015 free((void*)string.Spelling);
Steve Naroff8675d5c2009-11-09 17:45:52 +00001016}
1017
Daniel Dunbar079203f2009-12-01 03:14:51 +00001018unsigned clang_getCursorColumn(CXCursor C) {
Steve Naroff772c1a42009-08-31 14:26:51 +00001019 assert(C.decl && "CXCursor has null decl");
1020 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
Steve Naroff772c1a42009-08-31 14:26:51 +00001021 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001022
Steve Naroff80a766b2009-09-02 18:26:48 +00001023 SourceLocation SLoc = getLocationFromCursor(C, SourceMgr, ND);
Steve Naroff772c1a42009-08-31 14:26:51 +00001024 return SourceMgr.getSpellingColumnNumber(SLoc);
Steve Naroffd5e8e862009-08-27 19:51:58 +00001025}
Daniel Dunbar079203f2009-12-01 03:14:51 +00001026
1027const char *clang_getCursorSource(CXCursor C) {
Steve Naroff772c1a42009-08-31 14:26:51 +00001028 assert(C.decl && "CXCursor has null decl");
1029 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
Steve Naroff772c1a42009-08-31 14:26:51 +00001030 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001031
Steve Naroff80a766b2009-09-02 18:26:48 +00001032 SourceLocation SLoc = getLocationFromCursor(C, SourceMgr, ND);
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001033
Ted Kremenek4c4d6432009-11-17 05:31:58 +00001034 if (SLoc.isFileID()) {
1035 const char *bufferName = SourceMgr.getBufferName(SLoc);
1036 return bufferName[0] == '<' ? NULL : bufferName;
1037 }
Douglas Gregord3d923a2009-10-16 21:24:31 +00001038
1039 // Retrieve the file in which the macro was instantiated, then provide that
1040 // buffer name.
1041 // FIXME: Do we want to give specific macro-instantiation information?
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001042 const llvm::MemoryBuffer *Buffer
Douglas Gregord3d923a2009-10-16 21:24:31 +00001043 = SourceMgr.getBuffer(SourceMgr.getDecomposedSpellingLoc(SLoc).first);
1044 if (!Buffer)
1045 return 0;
1046
1047 return Buffer->getBufferIdentifier();
Steve Naroffd5e8e862009-08-27 19:51:58 +00001048}
1049
Daniel Dunbar079203f2009-12-01 03:14:51 +00001050CXFile clang_getCursorSourceFile(CXCursor C) {
Steve Naroff6231f182009-10-27 14:35:18 +00001051 assert(C.decl && "CXCursor has null decl");
1052 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
1053 SourceManager &SourceMgr = ND->getASTContext().getSourceManager();
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001054
Steve Naroff6231f182009-10-27 14:35:18 +00001055 return (void *)getFileEntryFromSourceLocation(SourceMgr,
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +00001056 getLocationFromCursor(C,SourceMgr, ND));
Steve Naroff6231f182009-10-27 14:35:18 +00001057}
1058
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001059void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff76b8f132009-09-23 17:52:52 +00001060 const char **startBuf,
1061 const char **endBuf,
1062 unsigned *startLine,
1063 unsigned *startColumn,
1064 unsigned *endLine,
Daniel Dunbar079203f2009-12-01 03:14:51 +00001065 unsigned *endColumn) {
Steve Naroff76b8f132009-09-23 17:52:52 +00001066 assert(C.decl && "CXCursor has null decl");
1067 NamedDecl *ND = static_cast<NamedDecl *>(C.decl);
1068 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
1069 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001070
Steve Naroff76b8f132009-09-23 17:52:52 +00001071 SourceManager &SM = FD->getASTContext().getSourceManager();
1072 *startBuf = SM.getCharacterData(Body->getLBracLoc());
1073 *endBuf = SM.getCharacterData(Body->getRBracLoc());
1074 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
1075 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
1076 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
1077 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
1078}
1079
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001080enum CXCompletionChunkKind
Douglas Gregor9eb77012009-11-07 00:00:49 +00001081clang_getCompletionChunkKind(CXCompletionString completion_string,
1082 unsigned chunk_number) {
1083 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
1084 if (!CCStr || chunk_number >= CCStr->size())
1085 return CXCompletionChunk_Text;
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001086
Douglas Gregor9eb77012009-11-07 00:00:49 +00001087 switch ((*CCStr)[chunk_number].Kind) {
1088 case CodeCompletionString::CK_TypedText:
1089 return CXCompletionChunk_TypedText;
1090 case CodeCompletionString::CK_Text:
1091 return CXCompletionChunk_Text;
1092 case CodeCompletionString::CK_Optional:
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001093 return CXCompletionChunk_Optional;
Douglas Gregor9eb77012009-11-07 00:00:49 +00001094 case CodeCompletionString::CK_Placeholder:
1095 return CXCompletionChunk_Placeholder;
1096 case CodeCompletionString::CK_Informative:
1097 return CXCompletionChunk_Informative;
1098 case CodeCompletionString::CK_CurrentParameter:
1099 return CXCompletionChunk_CurrentParameter;
1100 case CodeCompletionString::CK_LeftParen:
1101 return CXCompletionChunk_LeftParen;
1102 case CodeCompletionString::CK_RightParen:
1103 return CXCompletionChunk_RightParen;
1104 case CodeCompletionString::CK_LeftBracket:
1105 return CXCompletionChunk_LeftBracket;
1106 case CodeCompletionString::CK_RightBracket:
1107 return CXCompletionChunk_RightBracket;
1108 case CodeCompletionString::CK_LeftBrace:
1109 return CXCompletionChunk_LeftBrace;
1110 case CodeCompletionString::CK_RightBrace:
1111 return CXCompletionChunk_RightBrace;
1112 case CodeCompletionString::CK_LeftAngle:
1113 return CXCompletionChunk_LeftAngle;
1114 case CodeCompletionString::CK_RightAngle:
1115 return CXCompletionChunk_RightAngle;
1116 case CodeCompletionString::CK_Comma:
1117 return CXCompletionChunk_Comma;
1118 }
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001119
Douglas Gregor9eb77012009-11-07 00:00:49 +00001120 // Should be unreachable, but let's be careful.
1121 return CXCompletionChunk_Text;
1122}
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001123
Douglas Gregor9eb77012009-11-07 00:00:49 +00001124const char *clang_getCompletionChunkText(CXCompletionString completion_string,
1125 unsigned chunk_number) {
1126 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
1127 if (!CCStr || chunk_number >= CCStr->size())
1128 return 0;
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001129
Douglas Gregor9eb77012009-11-07 00:00:49 +00001130 switch ((*CCStr)[chunk_number].Kind) {
1131 case CodeCompletionString::CK_TypedText:
1132 case CodeCompletionString::CK_Text:
1133 case CodeCompletionString::CK_Placeholder:
1134 case CodeCompletionString::CK_CurrentParameter:
1135 case CodeCompletionString::CK_Informative:
1136 case CodeCompletionString::CK_LeftParen:
1137 case CodeCompletionString::CK_RightParen:
1138 case CodeCompletionString::CK_LeftBracket:
1139 case CodeCompletionString::CK_RightBracket:
1140 case CodeCompletionString::CK_LeftBrace:
1141 case CodeCompletionString::CK_RightBrace:
1142 case CodeCompletionString::CK_LeftAngle:
1143 case CodeCompletionString::CK_RightAngle:
1144 case CodeCompletionString::CK_Comma:
1145 return (*CCStr)[chunk_number].Text;
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001146
Douglas Gregor9eb77012009-11-07 00:00:49 +00001147 case CodeCompletionString::CK_Optional:
1148 // Note: treated as an empty text block.
Douglas Gregor01ddf7a2009-12-10 22:46:19 +00001149 return "";
Douglas Gregor9eb77012009-11-07 00:00:49 +00001150 }
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001151
Douglas Gregor9eb77012009-11-07 00:00:49 +00001152 // Should be unreachable, but let's be careful.
1153 return 0;
1154}
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001155
Douglas Gregor9eb77012009-11-07 00:00:49 +00001156CXCompletionString
1157clang_getCompletionChunkCompletionString(CXCompletionString completion_string,
1158 unsigned chunk_number) {
1159 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
1160 if (!CCStr || chunk_number >= CCStr->size())
1161 return 0;
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001162
Douglas Gregor9eb77012009-11-07 00:00:49 +00001163 switch ((*CCStr)[chunk_number].Kind) {
1164 case CodeCompletionString::CK_TypedText:
1165 case CodeCompletionString::CK_Text:
1166 case CodeCompletionString::CK_Placeholder:
1167 case CodeCompletionString::CK_CurrentParameter:
1168 case CodeCompletionString::CK_Informative:
1169 case CodeCompletionString::CK_LeftParen:
1170 case CodeCompletionString::CK_RightParen:
1171 case CodeCompletionString::CK_LeftBracket:
1172 case CodeCompletionString::CK_RightBracket:
1173 case CodeCompletionString::CK_LeftBrace:
1174 case CodeCompletionString::CK_RightBrace:
1175 case CodeCompletionString::CK_LeftAngle:
1176 case CodeCompletionString::CK_RightAngle:
1177 case CodeCompletionString::CK_Comma:
1178 return 0;
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001179
Douglas Gregor9eb77012009-11-07 00:00:49 +00001180 case CodeCompletionString::CK_Optional:
1181 // Note: treated as an empty text block.
1182 return (*CCStr)[chunk_number].Optional;
1183 }
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001184
Douglas Gregor9eb77012009-11-07 00:00:49 +00001185 // Should be unreachable, but let's be careful.
1186 return 0;
1187}
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001188
Douglas Gregor9eb77012009-11-07 00:00:49 +00001189unsigned clang_getNumCompletionChunks(CXCompletionString completion_string) {
1190 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
1191 return CCStr? CCStr->size() : 0;
1192}
Steve Naroff76b8f132009-09-23 17:52:52 +00001193
Douglas Gregorf09935f2009-12-01 05:55:20 +00001194static bool ReadUnsigned(const char *&Memory, const char *MemoryEnd,
1195 unsigned &Value) {
1196 if (Memory + sizeof(unsigned) > MemoryEnd)
1197 return true;
1198
1199 memmove(&Value, Memory, sizeof(unsigned));
1200 Memory += sizeof(unsigned);
1201 return false;
Douglas Gregor9eb77012009-11-07 00:00:49 +00001202}
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001203
1204void clang_codeComplete(CXIndex CIdx,
Douglas Gregor9eb77012009-11-07 00:00:49 +00001205 const char *source_filename,
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001206 int num_command_line_args,
Douglas Gregor9eb77012009-11-07 00:00:49 +00001207 const char **command_line_args,
Douglas Gregor9485bf92009-12-02 09:21:34 +00001208 unsigned num_unsaved_files,
1209 struct CXUnsavedFile *unsaved_files,
Douglas Gregor9eb77012009-11-07 00:00:49 +00001210 const char *complete_filename,
1211 unsigned complete_line,
1212 unsigned complete_column,
1213 CXCompletionIterator completion_iterator,
1214 CXClientData client_data) {
1215 // The indexer, which is mainly used to determine where diagnostics go.
1216 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001217
Douglas Gregor9485bf92009-12-02 09:21:34 +00001218 // The set of temporary files that we've built.
1219 std::vector<llvm::sys::Path> TemporaryFiles;
1220
Douglas Gregor9eb77012009-11-07 00:00:49 +00001221 // Build up the arguments for invoking 'clang'.
1222 std::vector<const char *> argv;
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001223
Douglas Gregor9eb77012009-11-07 00:00:49 +00001224 // First add the complete path to the 'clang' executable.
1225 llvm::sys::Path ClangPath = CXXIdx->getClangPath();
1226 argv.push_back(ClangPath.c_str());
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001227
1228 // Add the '-fsyntax-only' argument so that we only perform a basic
Douglas Gregor9eb77012009-11-07 00:00:49 +00001229 // syntax check of the code.
1230 argv.push_back("-fsyntax-only");
1231
1232 // Add the appropriate '-code-completion-at=file:line:column' argument
1233 // to perform code completion, with an "-Xclang" preceding it.
1234 std::string code_complete_at;
Douglas Gregor9eb77012009-11-07 00:00:49 +00001235 code_complete_at += complete_filename;
1236 code_complete_at += ":";
1237 code_complete_at += llvm::utostr(complete_line);
1238 code_complete_at += ":";
1239 code_complete_at += llvm::utostr(complete_column);
1240 argv.push_back("-Xclang");
Daniel Dunbar3eff9272009-12-03 05:32:40 +00001241 argv.push_back("-code-completion-at");
1242 argv.push_back("-Xclang");
Douglas Gregor9eb77012009-11-07 00:00:49 +00001243 argv.push_back(code_complete_at.c_str());
1244 argv.push_back("-Xclang");
Daniel Dunbard8027782009-11-19 05:32:09 +00001245 argv.push_back("-no-code-completion-debug-printer");
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001246
Douglas Gregor9485bf92009-12-02 09:21:34 +00001247 std::vector<std::string> RemapArgs;
1248 for (unsigned i = 0; i != num_unsaved_files; ++i) {
1249 char tmpFile[L_tmpnam];
1250 char *tmpFileName = tmpnam(tmpFile);
1251
1252 // Write the contents of this unsaved file into the temporary file.
1253 llvm::sys::Path SavedFile(tmpFileName);
1254 std::string ErrorInfo;
1255 llvm::raw_fd_ostream OS(SavedFile.c_str(), ErrorInfo);
1256 if (!ErrorInfo.empty())
1257 continue;
1258
1259 OS.write(unsaved_files[i].Contents, unsaved_files[i].Length);
1260 OS.close();
1261 if (OS.has_error()) {
1262 SavedFile.eraseFromDisk();
1263 continue;
1264 }
1265
1266 // Remap the file.
Daniel Dunbar3eff9272009-12-03 05:32:40 +00001267 std::string RemapArg = unsaved_files[i].Filename;
Douglas Gregor9485bf92009-12-02 09:21:34 +00001268 RemapArg += ';';
1269 RemapArg += tmpFileName;
1270 RemapArgs.push_back("-Xclang");
Daniel Dunbar3eff9272009-12-03 05:32:40 +00001271 RemapArgs.push_back("-remap-file");
1272 RemapArgs.push_back("-Xclang");
Douglas Gregor9485bf92009-12-02 09:21:34 +00001273 RemapArgs.push_back(RemapArg);
1274 TemporaryFiles.push_back(SavedFile);
1275 }
1276
1277 // The pointers into the elements of RemapArgs are stable because we
1278 // won't be adding anything to RemapArgs after this point.
1279 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1280 argv.push_back(RemapArgs[i].c_str());
1281
Douglas Gregor9eb77012009-11-07 00:00:49 +00001282 // Add the source file name (FIXME: later, we'll want to build temporary
1283 // file from the buffer, or just feed the source text via standard input).
Ted Kremenek123344e2009-11-17 18:18:02 +00001284 if (source_filename)
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001285 argv.push_back(source_filename);
1286
Douglas Gregor9eb77012009-11-07 00:00:49 +00001287 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1288 for (int i = 0; i < num_command_line_args; ++i)
1289 if (const char *arg = command_line_args[i]) {
1290 if (strcmp(arg, "-o") == 0) {
1291 ++i; // Also skip the matching argument.
1292 continue;
1293 }
1294 if (strcmp(arg, "-emit-ast") == 0 ||
1295 strcmp(arg, "-c") == 0 ||
1296 strcmp(arg, "-fsyntax-only") == 0) {
1297 continue;
1298 }
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001299
Douglas Gregor9eb77012009-11-07 00:00:49 +00001300 // Keep the argument.
1301 argv.push_back(arg);
1302 }
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001303
Douglas Gregor9eb77012009-11-07 00:00:49 +00001304 // Add the null terminator.
1305 argv.push_back(NULL);
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001306
Douglas Gregor9eb77012009-11-07 00:00:49 +00001307 // Generate a temporary name for the AST file.
1308 char tmpFile[L_tmpnam];
1309 char *tmpFileName = tmpnam(tmpFile);
1310 llvm::sys::Path ResultsFile(tmpFileName);
Douglas Gregor9485bf92009-12-02 09:21:34 +00001311 TemporaryFiles.push_back(ResultsFile);
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001312
Douglas Gregor9eb77012009-11-07 00:00:49 +00001313 // Invoke 'clang'.
1314 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1315 // on Unix or NUL (Windows).
1316 std::string ErrMsg;
1317 const llvm::sys::Path *Redirects[] = { &DevNull, &ResultsFile, &DevNull, 0 };
1318 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
1319 /* redirects */ &Redirects[0],
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001320 /* secondsToWait */ 0,
Douglas Gregor9eb77012009-11-07 00:00:49 +00001321 /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001322
Ted Kremenekba645742009-11-10 19:18:52 +00001323 if (CXXIdx->getDisplayDiagnostics() && !ErrMsg.empty()) {
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001324 llvm::errs() << "clang_codeComplete: " << ErrMsg
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +00001325 << '\n' << "Arguments: \n";
Douglas Gregor9eb77012009-11-07 00:00:49 +00001326 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
1327 I!=E; ++I) {
1328 if (*I)
1329 llvm::errs() << ' ' << *I << '\n';
1330 }
1331 llvm::errs() << '\n';
1332 }
1333
1334 // Parse the resulting source file to find code-completion results.
1335 using llvm::MemoryBuffer;
1336 using llvm::StringRef;
1337 if (MemoryBuffer *F = MemoryBuffer::getFile(ResultsFile.c_str())) {
1338 StringRef Buffer = F->getBuffer();
Douglas Gregorf09935f2009-12-01 05:55:20 +00001339 for (const char *Str = Buffer.data(), *StrEnd = Str + Buffer.size();
1340 Str < StrEnd;) {
1341 unsigned KindValue;
1342 if (ReadUnsigned(Str, StrEnd, KindValue))
Douglas Gregor9eb77012009-11-07 00:00:49 +00001343 break;
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001344
Douglas Gregorf09935f2009-12-01 05:55:20 +00001345 CodeCompletionString *CCStr
1346 = CodeCompletionString::Deserialize(Str, StrEnd);
1347 if (!CCStr)
1348 continue;
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001349
Douglas Gregorf09935f2009-12-01 05:55:20 +00001350 if (!CCStr->empty()) {
Douglas Gregor9eb77012009-11-07 00:00:49 +00001351 // Vend the code-completion result to the caller.
1352 CXCompletionResult Result;
Douglas Gregorf09935f2009-12-01 05:55:20 +00001353 Result.CursorKind = (CXCursorKind)KindValue;
Douglas Gregor9eb77012009-11-07 00:00:49 +00001354 Result.CompletionString = CCStr;
1355 if (completion_iterator)
1356 completion_iterator(&Result, client_data);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001357 }
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001358
Douglas Gregor9eb77012009-11-07 00:00:49 +00001359 delete CCStr;
Douglas Gregorf09935f2009-12-01 05:55:20 +00001360 };
Douglas Gregor9eb77012009-11-07 00:00:49 +00001361 delete F;
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001362 }
1363
Douglas Gregor9485bf92009-12-02 09:21:34 +00001364 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1365 TemporaryFiles[i].eraseFromDisk();
Douglas Gregor9eb77012009-11-07 00:00:49 +00001366}
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001367
Steve Naroffd5e8e862009-08-27 19:51:58 +00001368} // end extern "C"