blob: f0e90212f7fb3227c150812c7c85559be79de131 [file] [log] [blame]
Ted Kremenekab188932010-01-05 19:32:54 +00001//===- CIndexCodeCompletion.cpp - Code Completion API hooks ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Clang-C Source Indexing library hooks for
11// code completion.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CIndexer.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000016#include "CIndexDiagnostic.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000017#include "clang/Basic/SourceManager.h"
18#include "clang/Basic/FileManager.h"
Douglas Gregor1abc6bc2010-08-04 16:47:14 +000019#include "clang/Frontend/ASTUnit.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000020#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000021#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000022#include "clang/Sema/CodeCompleteConsumer.h"
Douglas Gregordf95a132010-08-09 20:45:32 +000023#include "llvm/ADT/SmallString.h"
Ted Kremenekab188932010-01-05 19:32:54 +000024#include "llvm/ADT/StringExtras.h"
25#include "llvm/Support/MemoryBuffer.h"
Douglas Gregordf95a132010-08-09 20:45:32 +000026#include "llvm/Support/Timer.h"
27#include "llvm/Support/raw_ostream.h"
Ted Kremenekab188932010-01-05 19:32:54 +000028#include "llvm/System/Program.h"
Douglas Gregor3d398aa2010-07-26 16:29:14 +000029#include <cstdlib>
30#include <cstdio>
Ted Kremenekab188932010-01-05 19:32:54 +000031
Douglas Gregordf95a132010-08-09 20:45:32 +000032
Ted Kremenekda7af322010-04-15 01:02:28 +000033#ifdef UDP_CODE_COMPLETION_LOGGER
34#include "clang/Basic/Version.h"
Ted Kremenekda7af322010-04-15 01:02:28 +000035#include <arpa/inet.h>
36#include <sys/socket.h>
37#include <sys/types.h>
38#include <unistd.h>
39#endif
40
Ted Kremenekab188932010-01-05 19:32:54 +000041using namespace clang;
Ted Kremenek2ef6f8f2010-02-17 01:42:24 +000042using namespace clang::cxstring;
Ted Kremenekab188932010-01-05 19:32:54 +000043
Douglas Gregor12e13132010-05-26 22:00:08 +000044namespace {
45 /// \brief Stored representation of a completion string.
46 ///
47 /// This is the representation behind a CXCompletionString.
48 class CXStoredCodeCompletionString : public CodeCompletionString {
49 unsigned Priority;
50
51 public:
52 CXStoredCodeCompletionString(unsigned Priority) : Priority(Priority) { }
53
54 unsigned getPriority() const { return Priority; }
55 };
56}
57
Ted Kremenekab188932010-01-05 19:32:54 +000058extern "C" {
59
60enum CXCompletionChunkKind
61clang_getCompletionChunkKind(CXCompletionString completion_string,
62 unsigned chunk_number) {
Douglas Gregor12e13132010-05-26 22:00:08 +000063 CXStoredCodeCompletionString *CCStr
64 = (CXStoredCodeCompletionString *)completion_string;
Ted Kremenekab188932010-01-05 19:32:54 +000065 if (!CCStr || chunk_number >= CCStr->size())
66 return CXCompletionChunk_Text;
67
68 switch ((*CCStr)[chunk_number].Kind) {
69 case CodeCompletionString::CK_TypedText:
70 return CXCompletionChunk_TypedText;
71 case CodeCompletionString::CK_Text:
72 return CXCompletionChunk_Text;
73 case CodeCompletionString::CK_Optional:
74 return CXCompletionChunk_Optional;
75 case CodeCompletionString::CK_Placeholder:
76 return CXCompletionChunk_Placeholder;
77 case CodeCompletionString::CK_Informative:
78 return CXCompletionChunk_Informative;
79 case CodeCompletionString::CK_ResultType:
80 return CXCompletionChunk_ResultType;
81 case CodeCompletionString::CK_CurrentParameter:
82 return CXCompletionChunk_CurrentParameter;
83 case CodeCompletionString::CK_LeftParen:
84 return CXCompletionChunk_LeftParen;
85 case CodeCompletionString::CK_RightParen:
86 return CXCompletionChunk_RightParen;
87 case CodeCompletionString::CK_LeftBracket:
88 return CXCompletionChunk_LeftBracket;
89 case CodeCompletionString::CK_RightBracket:
90 return CXCompletionChunk_RightBracket;
91 case CodeCompletionString::CK_LeftBrace:
92 return CXCompletionChunk_LeftBrace;
93 case CodeCompletionString::CK_RightBrace:
94 return CXCompletionChunk_RightBrace;
95 case CodeCompletionString::CK_LeftAngle:
96 return CXCompletionChunk_LeftAngle;
97 case CodeCompletionString::CK_RightAngle:
98 return CXCompletionChunk_RightAngle;
99 case CodeCompletionString::CK_Comma:
100 return CXCompletionChunk_Comma;
Douglas Gregor01dfea02010-01-10 23:08:15 +0000101 case CodeCompletionString::CK_Colon:
102 return CXCompletionChunk_Colon;
103 case CodeCompletionString::CK_SemiColon:
104 return CXCompletionChunk_SemiColon;
105 case CodeCompletionString::CK_Equal:
106 return CXCompletionChunk_Equal;
107 case CodeCompletionString::CK_HorizontalSpace:
108 return CXCompletionChunk_HorizontalSpace;
109 case CodeCompletionString::CK_VerticalSpace:
110 return CXCompletionChunk_VerticalSpace;
Ted Kremenekab188932010-01-05 19:32:54 +0000111 }
112
113 // Should be unreachable, but let's be careful.
114 return CXCompletionChunk_Text;
115}
116
Ted Kremenek2ef6f8f2010-02-17 01:42:24 +0000117CXString clang_getCompletionChunkText(CXCompletionString completion_string,
118 unsigned chunk_number) {
Douglas Gregor12e13132010-05-26 22:00:08 +0000119 CXStoredCodeCompletionString *CCStr
120 = (CXStoredCodeCompletionString *)completion_string;
Ted Kremenekab188932010-01-05 19:32:54 +0000121 if (!CCStr || chunk_number >= CCStr->size())
Ted Kremenek2ef6f8f2010-02-17 01:42:24 +0000122 return createCXString(0);
Ted Kremenekab188932010-01-05 19:32:54 +0000123
124 switch ((*CCStr)[chunk_number].Kind) {
125 case CodeCompletionString::CK_TypedText:
126 case CodeCompletionString::CK_Text:
127 case CodeCompletionString::CK_Placeholder:
128 case CodeCompletionString::CK_CurrentParameter:
129 case CodeCompletionString::CK_Informative:
130 case CodeCompletionString::CK_LeftParen:
131 case CodeCompletionString::CK_RightParen:
132 case CodeCompletionString::CK_LeftBracket:
133 case CodeCompletionString::CK_RightBracket:
134 case CodeCompletionString::CK_LeftBrace:
135 case CodeCompletionString::CK_RightBrace:
136 case CodeCompletionString::CK_LeftAngle:
137 case CodeCompletionString::CK_RightAngle:
138 case CodeCompletionString::CK_Comma:
139 case CodeCompletionString::CK_ResultType:
Douglas Gregor01dfea02010-01-10 23:08:15 +0000140 case CodeCompletionString::CK_Colon:
141 case CodeCompletionString::CK_SemiColon:
142 case CodeCompletionString::CK_Equal:
143 case CodeCompletionString::CK_HorizontalSpace:
Ted Kremenek2ef6f8f2010-02-17 01:42:24 +0000144 return createCXString((*CCStr)[chunk_number].Text, false);
Ted Kremenekab188932010-01-05 19:32:54 +0000145
Douglas Gregor21c241f2010-05-25 06:14:46 +0000146 case CodeCompletionString::CK_VerticalSpace:
147 // FIXME: Temporary hack until we figure out how to handle vertical space.
148 return createCXString(" ");
149
Ted Kremenekab188932010-01-05 19:32:54 +0000150 case CodeCompletionString::CK_Optional:
151 // Note: treated as an empty text block.
Ted Kremenek2ef6f8f2010-02-17 01:42:24 +0000152 return createCXString("");
Ted Kremenekab188932010-01-05 19:32:54 +0000153 }
154
155 // Should be unreachable, but let's be careful.
Ted Kremenek2ef6f8f2010-02-17 01:42:24 +0000156 return createCXString(0);
Ted Kremenekab188932010-01-05 19:32:54 +0000157}
158
Ted Kremenek2ef6f8f2010-02-17 01:42:24 +0000159
Ted Kremenekab188932010-01-05 19:32:54 +0000160CXCompletionString
161clang_getCompletionChunkCompletionString(CXCompletionString completion_string,
162 unsigned chunk_number) {
Douglas Gregor12e13132010-05-26 22:00:08 +0000163 CXStoredCodeCompletionString *CCStr
164 = (CXStoredCodeCompletionString *)completion_string;
Ted Kremenekab188932010-01-05 19:32:54 +0000165 if (!CCStr || chunk_number >= CCStr->size())
166 return 0;
167
168 switch ((*CCStr)[chunk_number].Kind) {
169 case CodeCompletionString::CK_TypedText:
170 case CodeCompletionString::CK_Text:
171 case CodeCompletionString::CK_Placeholder:
172 case CodeCompletionString::CK_CurrentParameter:
173 case CodeCompletionString::CK_Informative:
174 case CodeCompletionString::CK_LeftParen:
175 case CodeCompletionString::CK_RightParen:
176 case CodeCompletionString::CK_LeftBracket:
177 case CodeCompletionString::CK_RightBracket:
178 case CodeCompletionString::CK_LeftBrace:
179 case CodeCompletionString::CK_RightBrace:
180 case CodeCompletionString::CK_LeftAngle:
181 case CodeCompletionString::CK_RightAngle:
182 case CodeCompletionString::CK_Comma:
183 case CodeCompletionString::CK_ResultType:
Douglas Gregor01dfea02010-01-10 23:08:15 +0000184 case CodeCompletionString::CK_Colon:
185 case CodeCompletionString::CK_SemiColon:
186 case CodeCompletionString::CK_Equal:
187 case CodeCompletionString::CK_HorizontalSpace:
188 case CodeCompletionString::CK_VerticalSpace:
Ted Kremenekab188932010-01-05 19:32:54 +0000189 return 0;
190
191 case CodeCompletionString::CK_Optional:
192 // Note: treated as an empty text block.
193 return (*CCStr)[chunk_number].Optional;
194 }
195
196 // Should be unreachable, but let's be careful.
197 return 0;
198}
199
200unsigned clang_getNumCompletionChunks(CXCompletionString completion_string) {
Douglas Gregor12e13132010-05-26 22:00:08 +0000201 CXStoredCodeCompletionString *CCStr
202 = (CXStoredCodeCompletionString *)completion_string;
Ted Kremenekab188932010-01-05 19:32:54 +0000203 return CCStr? CCStr->size() : 0;
204}
205
Douglas Gregor12e13132010-05-26 22:00:08 +0000206unsigned clang_getCompletionPriority(CXCompletionString completion_string) {
207 CXStoredCodeCompletionString *CCStr
208 = (CXStoredCodeCompletionString *)completion_string;
Bill Wendlinga2ace582010-05-27 18:35:05 +0000209 return CCStr? CCStr->getPriority() : unsigned(CCP_Unlikely);
Douglas Gregor12e13132010-05-26 22:00:08 +0000210}
211
Ted Kremenekab188932010-01-05 19:32:54 +0000212static bool ReadUnsigned(const char *&Memory, const char *MemoryEnd,
213 unsigned &Value) {
214 if (Memory + sizeof(unsigned) > MemoryEnd)
215 return true;
216
217 memmove(&Value, Memory, sizeof(unsigned));
218 Memory += sizeof(unsigned);
219 return false;
220}
221
222/// \brief The CXCodeCompleteResults structure we allocate internally;
223/// the client only sees the initial CXCodeCompleteResults structure.
224struct AllocatedCXCodeCompleteResults : public CXCodeCompleteResults {
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000225 AllocatedCXCodeCompleteResults();
226 ~AllocatedCXCodeCompleteResults();
227
Douglas Gregora88084b2010-02-18 18:08:43 +0000228 /// \brief Diagnostics produced while performing code completion.
229 llvm::SmallVector<StoredDiagnostic, 8> Diagnostics;
230
Douglas Gregorf715ca12010-03-16 00:06:06 +0000231 /// \brief Diag object
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000232 llvm::IntrusiveRefCntPtr<Diagnostic> Diag;
Douglas Gregorf715ca12010-03-16 00:06:06 +0000233
Douglas Gregora88084b2010-02-18 18:08:43 +0000234 /// \brief Language options used to adjust source locations.
Daniel Dunbar35b84402010-01-30 23:31:40 +0000235 LangOptions LangOpts;
Douglas Gregora88084b2010-02-18 18:08:43 +0000236
237 /// \brief Source manager, used for diagnostics.
238 SourceManager SourceMgr;
239
240 /// \brief File manager, used for diagnostics.
241 FileManager FileMgr;
Douglas Gregor313e26c2010-02-18 23:35:40 +0000242
243 /// \brief Temporary files that should be removed once we have finished
244 /// with the code-completion results.
245 std::vector<llvm::sys::Path> TemporaryFiles;
Douglas Gregorb75d3df2010-08-04 17:07:00 +0000246
247 /// \brief Temporary buffers that will be deleted once we have finished with the code-completion results.
248 llvm::SmallVector<const llvm::MemoryBuffer *, 1> TemporaryBuffers;
Ted Kremenekab188932010-01-05 19:32:54 +0000249};
250
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000251AllocatedCXCodeCompleteResults::AllocatedCXCodeCompleteResults()
Douglas Gregorb75d3df2010-08-04 17:07:00 +0000252 : CXCodeCompleteResults(), Diag(new Diagnostic), SourceMgr(*Diag) { }
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000253
254AllocatedCXCodeCompleteResults::~AllocatedCXCodeCompleteResults() {
255 for (unsigned I = 0, N = NumResults; I != N; ++I)
Douglas Gregor12e13132010-05-26 22:00:08 +0000256 delete (CXStoredCodeCompletionString *)Results[I].CompletionString;
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000257 delete [] Results;
Douglas Gregor313e26c2010-02-18 23:35:40 +0000258
259 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
260 TemporaryFiles[I].eraseFromDisk();
Douglas Gregorb75d3df2010-08-04 17:07:00 +0000261 for (unsigned I = 0, N = TemporaryBuffers.size(); I != N; ++I)
262 delete TemporaryBuffers[I];
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000263}
264
Ted Kremenekab188932010-01-05 19:32:54 +0000265CXCodeCompleteResults *clang_codeComplete(CXIndex CIdx,
266 const char *source_filename,
267 int num_command_line_args,
268 const char **command_line_args,
269 unsigned num_unsaved_files,
270 struct CXUnsavedFile *unsaved_files,
271 const char *complete_filename,
272 unsigned complete_line,
Douglas Gregora88084b2010-02-18 18:08:43 +0000273 unsigned complete_column) {
Ted Kremenekda7af322010-04-15 01:02:28 +0000274#ifdef UDP_CODE_COMPLETION_LOGGER
275#ifdef UDP_CODE_COMPLETION_LOGGER_PORT
276 const llvm::TimeRecord &StartTime = llvm::TimeRecord::getCurrentTime();
277#endif
278#endif
279
Douglas Gregor3d398aa2010-07-26 16:29:14 +0000280 bool EnableLogging = getenv("LIBCLANG_CODE_COMPLETION_LOGGING") != 0;
Douglas Gregordf95a132010-08-09 20:45:32 +0000281
282 llvm::OwningPtr<llvm::NamedRegionTimer> CCTimer;
283 if (getenv("LIBCLANG_TIMING")) {
284 llvm::SmallString<128> TimerName;
285 llvm::raw_svector_ostream TimerNameOut(TimerName);
Douglas Gregor7a07fcb2010-08-09 21:00:09 +0000286 TimerNameOut << "Code completion (out-of-process) @ " << complete_filename
287 << ":" << complete_line << ":" << complete_column;
Douglas Gregordf95a132010-08-09 20:45:32 +0000288 CCTimer.reset(new llvm::NamedRegionTimer(TimerNameOut.str()));
289 }
290
Ted Kremenekab188932010-01-05 19:32:54 +0000291 // The indexer, which is mainly used to determine where diagnostics go.
292 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
293
Douglas Gregor936ea3b2010-01-28 00:56:43 +0000294 // Configure the diagnostics.
295 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +0000296 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
297 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregor936ea3b2010-01-28 00:56:43 +0000298
Ted Kremenekab188932010-01-05 19:32:54 +0000299 // The set of temporary files that we've built.
300 std::vector<llvm::sys::Path> TemporaryFiles;
301
302 // Build up the arguments for invoking 'clang'.
303 std::vector<const char *> argv;
304
305 // First add the complete path to the 'clang' executable.
306 llvm::sys::Path ClangPath = CXXIdx->getClangPath();
307 argv.push_back(ClangPath.c_str());
308
Daniel Dunbar3d9c6e12010-06-30 21:40:01 +0000309 // Always use Clang C++ support.
310 argv.push_back("-ccc-clang-cxx");
311
Ted Kremenekab188932010-01-05 19:32:54 +0000312 // Add the '-fsyntax-only' argument so that we only perform a basic
313 // syntax check of the code.
314 argv.push_back("-fsyntax-only");
315
316 // Add the appropriate '-code-completion-at=file:line:column' argument
317 // to perform code completion, with an "-Xclang" preceding it.
318 std::string code_complete_at;
319 code_complete_at += complete_filename;
320 code_complete_at += ":";
321 code_complete_at += llvm::utostr(complete_line);
322 code_complete_at += ":";
323 code_complete_at += llvm::utostr(complete_column);
324 argv.push_back("-Xclang");
325 argv.push_back("-code-completion-at");
326 argv.push_back("-Xclang");
327 argv.push_back(code_complete_at.c_str());
328 argv.push_back("-Xclang");
329 argv.push_back("-no-code-completion-debug-printer");
330 argv.push_back("-Xclang");
331 argv.push_back("-code-completion-macros");
Douglas Gregord93256e2010-01-28 06:00:51 +0000332 argv.push_back("-fdiagnostics-binary");
333
Douglas Gregor4db64a42010-01-23 00:14:00 +0000334 // Remap any unsaved files to temporary files.
Ted Kremenekab188932010-01-05 19:32:54 +0000335 std::vector<std::string> RemapArgs;
Douglas Gregor4db64a42010-01-23 00:14:00 +0000336 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
337 return 0;
Ted Kremenekab188932010-01-05 19:32:54 +0000338
339 // The pointers into the elements of RemapArgs are stable because we
340 // won't be adding anything to RemapArgs after this point.
341 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
342 argv.push_back(RemapArgs[i].c_str());
343
344 // Add the source file name (FIXME: later, we'll want to build temporary
345 // file from the buffer, or just feed the source text via standard input).
346 if (source_filename)
347 argv.push_back(source_filename);
348
349 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
350 for (int i = 0; i < num_command_line_args; ++i)
351 if (const char *arg = command_line_args[i]) {
352 if (strcmp(arg, "-o") == 0) {
353 ++i; // Also skip the matching argument.
354 continue;
355 }
356 if (strcmp(arg, "-emit-ast") == 0 ||
357 strcmp(arg, "-c") == 0 ||
358 strcmp(arg, "-fsyntax-only") == 0) {
359 continue;
360 }
361
362 // Keep the argument.
363 argv.push_back(arg);
364 }
365
Douglas Gregor3d398aa2010-07-26 16:29:14 +0000366 if (EnableLogging) {
367 std::string Log = ClangPath.str();
368 for (unsigned I = 0, N = argv.size(); I != N; ++I) {
369 Log += ' ';
370 Log += argv[I];
371 }
372 fprintf(stderr, "libclang (Code Completion): %s\n", Log.c_str());
373 }
374
Ted Kremenekab188932010-01-05 19:32:54 +0000375 // Add the null terminator.
376 argv.push_back(NULL);
377
Douglas Gregord93256e2010-01-28 06:00:51 +0000378 // Generate a temporary name for the code-completion results file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +0000379 char tmpFile[L_tmpnam];
380 char *tmpFileName = tmpnam(tmpFile);
381 llvm::sys::Path ResultsFile(tmpFileName);
Ted Kremenekab188932010-01-05 19:32:54 +0000382 TemporaryFiles.push_back(ResultsFile);
383
Douglas Gregord93256e2010-01-28 06:00:51 +0000384 // Generate a temporary name for the diagnostics file.
Benjamin Kramerc2a98162010-03-13 21:22:49 +0000385 char tmpFileResults[L_tmpnam];
386 char *tmpResultsFileName = tmpnam(tmpFileResults);
387 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregord93256e2010-01-28 06:00:51 +0000388 TemporaryFiles.push_back(DiagnosticsFile);
389
Douglas Gregor3d398aa2010-07-26 16:29:14 +0000390
391
Ted Kremenekab188932010-01-05 19:32:54 +0000392 // Invoke 'clang'.
393 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
394 // on Unix or NUL (Windows).
395 std::string ErrMsg;
Douglas Gregord93256e2010-01-28 06:00:51 +0000396 const llvm::sys::Path *Redirects[] = { &DevNull, &ResultsFile,
397 &DiagnosticsFile, 0 };
Ted Kremenekab188932010-01-05 19:32:54 +0000398 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
399 /* redirects */ &Redirects[0],
400 /* secondsToWait */ 0,
401 /* memoryLimits */ 0, &ErrMsg);
402
Douglas Gregor936ea3b2010-01-28 00:56:43 +0000403 if (!ErrMsg.empty()) {
404 std::string AllArgs;
Ted Kremenekab188932010-01-05 19:32:54 +0000405 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregor936ea3b2010-01-28 00:56:43 +0000406 I != E; ++I) {
407 AllArgs += ' ';
Ted Kremenekab188932010-01-05 19:32:54 +0000408 if (*I)
Douglas Gregor936ea3b2010-01-28 00:56:43 +0000409 AllArgs += *I;
Ted Kremenekab188932010-01-05 19:32:54 +0000410 }
Douglas Gregor936ea3b2010-01-28 00:56:43 +0000411
Daniel Dunbar32141c82010-02-23 20:23:45 +0000412 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenekab188932010-01-05 19:32:54 +0000413 }
414
415 // Parse the resulting source file to find code-completion results.
416 using llvm::MemoryBuffer;
417 using llvm::StringRef;
Douglas Gregora88084b2010-02-18 18:08:43 +0000418 AllocatedCXCodeCompleteResults *Results = new AllocatedCXCodeCompleteResults;
419 Results->Results = 0;
420 Results->NumResults = 0;
Douglas Gregora88084b2010-02-18 18:08:43 +0000421 // FIXME: Set Results->LangOpts!
Ted Kremenekab188932010-01-05 19:32:54 +0000422 if (MemoryBuffer *F = MemoryBuffer::getFile(ResultsFile.c_str())) {
423 llvm::SmallVector<CXCompletionResult, 4> CompletionResults;
424 StringRef Buffer = F->getBuffer();
425 for (const char *Str = Buffer.data(), *StrEnd = Str + Buffer.size();
426 Str < StrEnd;) {
427 unsigned KindValue;
428 if (ReadUnsigned(Str, StrEnd, KindValue))
429 break;
430
Douglas Gregor12e13132010-05-26 22:00:08 +0000431 unsigned Priority;
432 if (ReadUnsigned(Str, StrEnd, Priority))
433 break;
434
435 CXStoredCodeCompletionString *CCStr
436 = new CXStoredCodeCompletionString(Priority);
437 if (!CCStr->Deserialize(Str, StrEnd)) {
438 delete CCStr;
Ted Kremenekab188932010-01-05 19:32:54 +0000439 continue;
Douglas Gregor12e13132010-05-26 22:00:08 +0000440 }
Ted Kremenekab188932010-01-05 19:32:54 +0000441
442 if (!CCStr->empty()) {
443 // Vend the code-completion result to the caller.
444 CXCompletionResult Result;
445 Result.CursorKind = (CXCursorKind)KindValue;
446 Result.CompletionString = CCStr;
447 CompletionResults.push_back(Result);
448 }
449 };
450
451 // Allocate the results.
Ted Kremenekab188932010-01-05 19:32:54 +0000452 Results->Results = new CXCompletionResult [CompletionResults.size()];
453 Results->NumResults = CompletionResults.size();
454 memcpy(Results->Results, CompletionResults.data(),
455 CompletionResults.size() * sizeof(CXCompletionResult));
Douglas Gregorb75d3df2010-08-04 17:07:00 +0000456 Results->TemporaryBuffers.push_back(F);
Ted Kremenekab188932010-01-05 19:32:54 +0000457 }
458
Douglas Gregora88084b2010-02-18 18:08:43 +0000459 LoadSerializedDiagnostics(DiagnosticsFile, num_unsaved_files, unsaved_files,
460 Results->FileMgr, Results->SourceMgr,
461 Results->Diagnostics);
462
Douglas Gregor313e26c2010-02-18 23:35:40 +0000463 // Make sure we delete temporary files when the code-completion results are
464 // destroyed.
465 Results->TemporaryFiles.swap(TemporaryFiles);
Ted Kremenekab188932010-01-05 19:32:54 +0000466
Ted Kremenekda7af322010-04-15 01:02:28 +0000467#ifdef UDP_CODE_COMPLETION_LOGGER
468#ifdef UDP_CODE_COMPLETION_LOGGER_PORT
469 const llvm::TimeRecord &EndTime = llvm::TimeRecord::getCurrentTime();
470 llvm::SmallString<256> LogResult;
471 llvm::raw_svector_ostream os(LogResult);
472
473 // Figure out the language and whether or not it uses PCH.
474 const char *lang = 0;
475 bool usesPCH = false;
476
477 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
478 I != E; ++I) {
479 if (*I == 0)
480 continue;
481 if (strcmp(*I, "-x") == 0) {
482 if (I + 1 != E) {
483 lang = *(++I);
484 continue;
485 }
486 }
487 else if (strcmp(*I, "-include") == 0) {
488 if (I+1 != E) {
489 const char *arg = *(++I);
490 llvm::SmallString<512> pchName;
491 {
492 llvm::raw_svector_ostream os(pchName);
493 os << arg << ".pth";
494 }
495 pchName.push_back('\0');
496 struct stat stat_results;
497 if (stat(pchName.data(), &stat_results) == 0)
498 usesPCH = true;
499 continue;
500 }
501 }
502 }
503
Ted Kremenek2ee297f2010-04-17 00:21:42 +0000504 os << "{ ";
505 os << "\"wall\": " << (EndTime.getWallTime() - StartTime.getWallTime());
506 os << ", \"numRes\": " << Results->NumResults;
507 os << ", \"diags\": " << Results->Diagnostics.size();
508 os << ", \"pch\": " << (usesPCH ? "true" : "false");
509 os << ", \"lang\": \"" << (lang ? lang : "<unknown>") << '"';
Ted Kremenekda7af322010-04-15 01:02:28 +0000510 const char *name = getlogin();
Ted Kremenek2ee297f2010-04-17 00:21:42 +0000511 os << ", \"user\": \"" << (name ? name : "unknown") << '"';
512 os << ", \"clangVer\": \"" << getClangFullVersion() << '"';
513 os << " }";
Ted Kremenekda7af322010-04-15 01:02:28 +0000514
515 llvm::StringRef res = os.str();
516 if (res.size() > 0) {
517 do {
518 // Setup the UDP socket.
519 struct sockaddr_in servaddr;
520 bzero(&servaddr, sizeof(servaddr));
521 servaddr.sin_family = AF_INET;
522 servaddr.sin_port = htons(UDP_CODE_COMPLETION_LOGGER_PORT);
523 if (inet_pton(AF_INET, UDP_CODE_COMPLETION_LOGGER,
524 &servaddr.sin_addr) <= 0)
525 break;
526
527 int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
528 if (sockfd < 0)
529 break;
530
531 sendto(sockfd, res.data(), res.size(), 0,
532 (struct sockaddr *)&servaddr, sizeof(servaddr));
533 close(sockfd);
534 }
535 while (false);
536 }
537#endif
538#endif
Ted Kremenekab188932010-01-05 19:32:54 +0000539 return Results;
540}
541
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000542} // end extern "C"
543
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000544namespace {
545 class CaptureCompletionResults : public CodeCompleteConsumer {
546 AllocatedCXCodeCompleteResults &AllocatedResults;
547
548 public:
549 explicit CaptureCompletionResults(AllocatedCXCodeCompleteResults &Results)
550 : CodeCompleteConsumer(true, false, false), AllocatedResults(Results) { }
551
Douglas Gregore6b1bb62010-08-11 21:23:17 +0000552 virtual void ProcessCodeCompleteResults(Sema &S,
553 CodeCompletionContext Context,
554 Result *Results,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000555 unsigned NumResults) {
556 AllocatedResults.Results = new CXCompletionResult [NumResults];
557 AllocatedResults.NumResults = NumResults;
558 for (unsigned I = 0; I != NumResults; ++I) {
559 CXStoredCodeCompletionString *StoredCompletion
560 = new CXStoredCodeCompletionString(Results[I].Priority);
561 (void)Results[I].CreateCodeCompletionString(S, StoredCompletion);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000562 AllocatedResults.Results[I].CursorKind = Results[I].CursorKind;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000563 AllocatedResults.Results[I].CompletionString = StoredCompletion;
564 }
565 }
566 };
567}
568
569extern "C" {
570CXCodeCompleteResults *clang_codeCompleteAt(CXTranslationUnit TU,
571 const char *complete_filename,
572 unsigned complete_line,
573 unsigned complete_column,
574 struct CXUnsavedFile *unsaved_files,
Douglas Gregorcee235c2010-08-05 09:09:23 +0000575 unsigned num_unsaved_files,
576 unsigned options) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000577#ifdef UDP_CODE_COMPLETION_LOGGER
578#ifdef UDP_CODE_COMPLETION_LOGGER_PORT
579 const llvm::TimeRecord &StartTime = llvm::TimeRecord::getCurrentTime();
580#endif
581#endif
582
583 bool EnableLogging = getenv("LIBCLANG_CODE_COMPLETION_LOGGING") != 0;
584
585 ASTUnit *AST = static_cast<ASTUnit *>(TU);
586 if (!AST)
587 return 0;
588
589 // Perform the remapping of source files.
590 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
591 for (unsigned I = 0; I != num_unsaved_files; ++I) {
592 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
593 const llvm::MemoryBuffer *Buffer
594 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
595 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
596 Buffer));
597 }
598
599 if (EnableLogging) {
600 // FIXME: Add logging.
601 }
602
603 // Parse the resulting source file to find code-completion results.
604 AllocatedCXCodeCompleteResults *Results = new AllocatedCXCodeCompleteResults;
605 Results->Results = 0;
606 Results->NumResults = 0;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000607
608 // Create a code-completion consumer to capture the results.
609 CaptureCompletionResults Capture(*Results);
610
Douglas Gregorb75d3df2010-08-04 17:07:00 +0000611 // Make sure that we free the temporary buffers when the
612 // code-completion constructor is freed.
613 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I)
614 Results->TemporaryBuffers.push_back(RemappedFiles[I].second);
615
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000616 // Perform completion.
617 AST->CodeComplete(complete_filename, complete_line, complete_column,
Douglas Gregorcee235c2010-08-05 09:09:23 +0000618 RemappedFiles.data(), RemappedFiles.size(),
619 (options & CXCodeComplete_IncludeMacros),
620 (options & CXCodeComplete_IncludeCodePatterns),
621 Capture,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000622 *Results->Diag, Results->LangOpts, Results->SourceMgr,
623 Results->FileMgr, Results->Diagnostics);
624
625
626
627#ifdef UDP_CODE_COMPLETION_LOGGER
628#ifdef UDP_CODE_COMPLETION_LOGGER_PORT
629 const llvm::TimeRecord &EndTime = llvm::TimeRecord::getCurrentTime();
630 llvm::SmallString<256> LogResult;
631 llvm::raw_svector_ostream os(LogResult);
632
633 // Figure out the language and whether or not it uses PCH.
634 const char *lang = 0;
635 bool usesPCH = false;
636
637 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
638 I != E; ++I) {
639 if (*I == 0)
640 continue;
641 if (strcmp(*I, "-x") == 0) {
642 if (I + 1 != E) {
643 lang = *(++I);
644 continue;
645 }
646 }
647 else if (strcmp(*I, "-include") == 0) {
648 if (I+1 != E) {
649 const char *arg = *(++I);
650 llvm::SmallString<512> pchName;
651 {
652 llvm::raw_svector_ostream os(pchName);
653 os << arg << ".pth";
654 }
655 pchName.push_back('\0');
656 struct stat stat_results;
657 if (stat(pchName.data(), &stat_results) == 0)
658 usesPCH = true;
659 continue;
660 }
661 }
662 }
663
664 os << "{ ";
665 os << "\"wall\": " << (EndTime.getWallTime() - StartTime.getWallTime());
666 os << ", \"numRes\": " << Results->NumResults;
667 os << ", \"diags\": " << Results->Diagnostics.size();
668 os << ", \"pch\": " << (usesPCH ? "true" : "false");
669 os << ", \"lang\": \"" << (lang ? lang : "<unknown>") << '"';
670 const char *name = getlogin();
671 os << ", \"user\": \"" << (name ? name : "unknown") << '"';
672 os << ", \"clangVer\": \"" << getClangFullVersion() << '"';
673 os << " }";
674
675 llvm::StringRef res = os.str();
676 if (res.size() > 0) {
677 do {
678 // Setup the UDP socket.
679 struct sockaddr_in servaddr;
680 bzero(&servaddr, sizeof(servaddr));
681 servaddr.sin_family = AF_INET;
682 servaddr.sin_port = htons(UDP_CODE_COMPLETION_LOGGER_PORT);
683 if (inet_pton(AF_INET, UDP_CODE_COMPLETION_LOGGER,
684 &servaddr.sin_addr) <= 0)
685 break;
686
687 int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
688 if (sockfd < 0)
689 break;
690
691 sendto(sockfd, res.data(), res.size(), 0,
692 (struct sockaddr *)&servaddr, sizeof(servaddr));
693 close(sockfd);
694 }
695 while (false);
696 }
697#endif
698#endif
699 return Results;
700}
701
Douglas Gregorcee235c2010-08-05 09:09:23 +0000702unsigned clang_defaultCodeCompleteOptions(void) {
703 return CXCodeComplete_IncludeMacros;
704}
705
Ted Kremenekab188932010-01-05 19:32:54 +0000706void clang_disposeCodeCompleteResults(CXCodeCompleteResults *ResultsIn) {
707 if (!ResultsIn)
708 return;
709
710 AllocatedCXCodeCompleteResults *Results
711 = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
Ted Kremenekab188932010-01-05 19:32:54 +0000712 delete Results;
713}
714
Douglas Gregora88084b2010-02-18 18:08:43 +0000715unsigned
716clang_codeCompleteGetNumDiagnostics(CXCodeCompleteResults *ResultsIn) {
717 AllocatedCXCodeCompleteResults *Results
718 = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
719 if (!Results)
720 return 0;
721
722 return Results->Diagnostics.size();
723}
724
725CXDiagnostic
726clang_codeCompleteGetDiagnostic(CXCodeCompleteResults *ResultsIn,
727 unsigned Index) {
728 AllocatedCXCodeCompleteResults *Results
729 = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
730 if (!Results || Index >= Results->Diagnostics.size())
731 return 0;
732
733 return new CXStoredDiagnostic(Results->Diagnostics[Index], Results->LangOpts);
734}
735
736
Ted Kremenekab188932010-01-05 19:32:54 +0000737} // end extern "C"