blob: f33fdbe5f7e61a3dbc93aa3631b0c5db8b1b6e0b [file] [log] [blame]
Ted Kremenek0ec2cca2010-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 Gregorba965fb2010-01-28 00:56:43 +000016#include "CIndexDiagnostic.h"
Benjamin Kramer064414532010-04-12 19:45:50 +000017#include "clang/Basic/SourceManager.h"
18#include "clang/Basic/FileManager.h"
Douglas Gregor8e984da2010-08-04 16:47:14 +000019#include "clang/Frontend/ASTUnit.h"
Benjamin Kramer064414532010-04-12 19:45:50 +000020#include "clang/Frontend/CompilerInstance.h"
Douglas Gregorba965fb2010-01-28 00:56:43 +000021#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenek0ec2cca2010-01-05 19:32:54 +000022#include "clang/Sema/CodeCompleteConsumer.h"
Douglas Gregor028d3e42010-08-09 20:45:32 +000023#include "llvm/ADT/SmallString.h"
Ted Kremenek0ec2cca2010-01-05 19:32:54 +000024#include "llvm/ADT/StringExtras.h"
Daniel Dunbar77af1c52010-08-19 23:44:10 +000025#include "llvm/Support/CrashRecoveryContext.h"
Ted Kremenek0ec2cca2010-01-05 19:32:54 +000026#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor028d3e42010-08-09 20:45:32 +000027#include "llvm/Support/Timer.h"
28#include "llvm/Support/raw_ostream.h"
Ted Kremenek0ec2cca2010-01-05 19:32:54 +000029#include "llvm/System/Program.h"
Douglas Gregord6009ff2010-07-26 16:29:14 +000030#include <cstdlib>
31#include <cstdio>
Ted Kremenek0ec2cca2010-01-05 19:32:54 +000032
Douglas Gregor028d3e42010-08-09 20:45:32 +000033
Ted Kremenek9e0cf092010-04-15 01:02:28 +000034#ifdef UDP_CODE_COMPLETION_LOGGER
35#include "clang/Basic/Version.h"
Ted Kremenek9e0cf092010-04-15 01:02:28 +000036#include <arpa/inet.h>
37#include <sys/socket.h>
38#include <sys/types.h>
39#include <unistd.h>
40#endif
41
Ted Kremenek0ec2cca2010-01-05 19:32:54 +000042using namespace clang;
Ted Kremenekf602f962010-02-17 01:42:24 +000043using namespace clang::cxstring;
Ted Kremenek0ec2cca2010-01-05 19:32:54 +000044
Douglas Gregora2db7932010-05-26 22:00:08 +000045namespace {
46 /// \brief Stored representation of a completion string.
47 ///
48 /// This is the representation behind a CXCompletionString.
49 class CXStoredCodeCompletionString : public CodeCompletionString {
50 unsigned Priority;
Douglas Gregorf757a122010-08-23 23:00:57 +000051 CXAvailabilityKind Availability;
Douglas Gregora2db7932010-05-26 22:00:08 +000052
53 public:
Douglas Gregorf757a122010-08-23 23:00:57 +000054 CXStoredCodeCompletionString(unsigned Priority,
55 CXAvailabilityKind Availability)
56 : Priority(Priority), Availability(Availability) { }
Douglas Gregora2db7932010-05-26 22:00:08 +000057
58 unsigned getPriority() const { return Priority; }
Douglas Gregorf757a122010-08-23 23:00:57 +000059 CXAvailabilityKind getAvailability() const { return Availability; }
Douglas Gregora2db7932010-05-26 22:00:08 +000060 };
61}
62
Ted Kremenek0ec2cca2010-01-05 19:32:54 +000063extern "C" {
64
65enum CXCompletionChunkKind
66clang_getCompletionChunkKind(CXCompletionString completion_string,
67 unsigned chunk_number) {
Douglas Gregora2db7932010-05-26 22:00:08 +000068 CXStoredCodeCompletionString *CCStr
69 = (CXStoredCodeCompletionString *)completion_string;
Ted Kremenek0ec2cca2010-01-05 19:32:54 +000070 if (!CCStr || chunk_number >= CCStr->size())
71 return CXCompletionChunk_Text;
72
73 switch ((*CCStr)[chunk_number].Kind) {
74 case CodeCompletionString::CK_TypedText:
75 return CXCompletionChunk_TypedText;
76 case CodeCompletionString::CK_Text:
77 return CXCompletionChunk_Text;
78 case CodeCompletionString::CK_Optional:
79 return CXCompletionChunk_Optional;
80 case CodeCompletionString::CK_Placeholder:
81 return CXCompletionChunk_Placeholder;
82 case CodeCompletionString::CK_Informative:
83 return CXCompletionChunk_Informative;
84 case CodeCompletionString::CK_ResultType:
85 return CXCompletionChunk_ResultType;
86 case CodeCompletionString::CK_CurrentParameter:
87 return CXCompletionChunk_CurrentParameter;
88 case CodeCompletionString::CK_LeftParen:
89 return CXCompletionChunk_LeftParen;
90 case CodeCompletionString::CK_RightParen:
91 return CXCompletionChunk_RightParen;
92 case CodeCompletionString::CK_LeftBracket:
93 return CXCompletionChunk_LeftBracket;
94 case CodeCompletionString::CK_RightBracket:
95 return CXCompletionChunk_RightBracket;
96 case CodeCompletionString::CK_LeftBrace:
97 return CXCompletionChunk_LeftBrace;
98 case CodeCompletionString::CK_RightBrace:
99 return CXCompletionChunk_RightBrace;
100 case CodeCompletionString::CK_LeftAngle:
101 return CXCompletionChunk_LeftAngle;
102 case CodeCompletionString::CK_RightAngle:
103 return CXCompletionChunk_RightAngle;
104 case CodeCompletionString::CK_Comma:
105 return CXCompletionChunk_Comma;
Douglas Gregor504a6ae2010-01-10 23:08:15 +0000106 case CodeCompletionString::CK_Colon:
107 return CXCompletionChunk_Colon;
108 case CodeCompletionString::CK_SemiColon:
109 return CXCompletionChunk_SemiColon;
110 case CodeCompletionString::CK_Equal:
111 return CXCompletionChunk_Equal;
112 case CodeCompletionString::CK_HorizontalSpace:
113 return CXCompletionChunk_HorizontalSpace;
114 case CodeCompletionString::CK_VerticalSpace:
115 return CXCompletionChunk_VerticalSpace;
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000116 }
117
118 // Should be unreachable, but let's be careful.
119 return CXCompletionChunk_Text;
120}
121
Ted Kremenekf602f962010-02-17 01:42:24 +0000122CXString clang_getCompletionChunkText(CXCompletionString completion_string,
123 unsigned chunk_number) {
Douglas Gregora2db7932010-05-26 22:00:08 +0000124 CXStoredCodeCompletionString *CCStr
125 = (CXStoredCodeCompletionString *)completion_string;
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000126 if (!CCStr || chunk_number >= CCStr->size())
Ted Kremenekf602f962010-02-17 01:42:24 +0000127 return createCXString(0);
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000128
129 switch ((*CCStr)[chunk_number].Kind) {
130 case CodeCompletionString::CK_TypedText:
131 case CodeCompletionString::CK_Text:
132 case CodeCompletionString::CK_Placeholder:
133 case CodeCompletionString::CK_CurrentParameter:
134 case CodeCompletionString::CK_Informative:
135 case CodeCompletionString::CK_LeftParen:
136 case CodeCompletionString::CK_RightParen:
137 case CodeCompletionString::CK_LeftBracket:
138 case CodeCompletionString::CK_RightBracket:
139 case CodeCompletionString::CK_LeftBrace:
140 case CodeCompletionString::CK_RightBrace:
141 case CodeCompletionString::CK_LeftAngle:
142 case CodeCompletionString::CK_RightAngle:
143 case CodeCompletionString::CK_Comma:
144 case CodeCompletionString::CK_ResultType:
Douglas Gregor504a6ae2010-01-10 23:08:15 +0000145 case CodeCompletionString::CK_Colon:
146 case CodeCompletionString::CK_SemiColon:
147 case CodeCompletionString::CK_Equal:
148 case CodeCompletionString::CK_HorizontalSpace:
Douglas Gregor09737ee2010-05-25 06:14:46 +0000149 case CodeCompletionString::CK_VerticalSpace:
Douglas Gregor8ed5b772010-10-08 20:39:29 +0000150 return createCXString((*CCStr)[chunk_number].Text, false);
Douglas Gregor09737ee2010-05-25 06:14:46 +0000151
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000152 case CodeCompletionString::CK_Optional:
153 // Note: treated as an empty text block.
Ted Kremenekf602f962010-02-17 01:42:24 +0000154 return createCXString("");
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000155 }
156
157 // Should be unreachable, but let's be careful.
Ted Kremenekf602f962010-02-17 01:42:24 +0000158 return createCXString(0);
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000159}
160
Ted Kremenekf602f962010-02-17 01:42:24 +0000161
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000162CXCompletionString
163clang_getCompletionChunkCompletionString(CXCompletionString completion_string,
164 unsigned chunk_number) {
Douglas Gregora2db7932010-05-26 22:00:08 +0000165 CXStoredCodeCompletionString *CCStr
166 = (CXStoredCodeCompletionString *)completion_string;
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000167 if (!CCStr || chunk_number >= CCStr->size())
168 return 0;
169
170 switch ((*CCStr)[chunk_number].Kind) {
171 case CodeCompletionString::CK_TypedText:
172 case CodeCompletionString::CK_Text:
173 case CodeCompletionString::CK_Placeholder:
174 case CodeCompletionString::CK_CurrentParameter:
175 case CodeCompletionString::CK_Informative:
176 case CodeCompletionString::CK_LeftParen:
177 case CodeCompletionString::CK_RightParen:
178 case CodeCompletionString::CK_LeftBracket:
179 case CodeCompletionString::CK_RightBracket:
180 case CodeCompletionString::CK_LeftBrace:
181 case CodeCompletionString::CK_RightBrace:
182 case CodeCompletionString::CK_LeftAngle:
183 case CodeCompletionString::CK_RightAngle:
184 case CodeCompletionString::CK_Comma:
185 case CodeCompletionString::CK_ResultType:
Douglas Gregor504a6ae2010-01-10 23:08:15 +0000186 case CodeCompletionString::CK_Colon:
187 case CodeCompletionString::CK_SemiColon:
188 case CodeCompletionString::CK_Equal:
189 case CodeCompletionString::CK_HorizontalSpace:
190 case CodeCompletionString::CK_VerticalSpace:
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000191 return 0;
192
193 case CodeCompletionString::CK_Optional:
194 // Note: treated as an empty text block.
195 return (*CCStr)[chunk_number].Optional;
196 }
197
198 // Should be unreachable, but let's be careful.
199 return 0;
200}
201
202unsigned clang_getNumCompletionChunks(CXCompletionString completion_string) {
Douglas Gregora2db7932010-05-26 22:00:08 +0000203 CXStoredCodeCompletionString *CCStr
204 = (CXStoredCodeCompletionString *)completion_string;
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000205 return CCStr? CCStr->size() : 0;
206}
207
Douglas Gregora2db7932010-05-26 22:00:08 +0000208unsigned clang_getCompletionPriority(CXCompletionString completion_string) {
209 CXStoredCodeCompletionString *CCStr
210 = (CXStoredCodeCompletionString *)completion_string;
Bill Wendling47bb3e22010-05-27 18:35:05 +0000211 return CCStr? CCStr->getPriority() : unsigned(CCP_Unlikely);
Douglas Gregora2db7932010-05-26 22:00:08 +0000212}
213
Douglas Gregorf757a122010-08-23 23:00:57 +0000214enum CXAvailabilityKind
215clang_getCompletionAvailability(CXCompletionString completion_string) {
216 CXStoredCodeCompletionString *CCStr
217 = (CXStoredCodeCompletionString *)completion_string;
218 return CCStr? CCStr->getAvailability() : CXAvailability_Available;
219}
220
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000221static bool ReadUnsigned(const char *&Memory, const char *MemoryEnd,
222 unsigned &Value) {
223 if (Memory + sizeof(unsigned) > MemoryEnd)
224 return true;
225
226 memmove(&Value, Memory, sizeof(unsigned));
227 Memory += sizeof(unsigned);
228 return false;
229}
230
231/// \brief The CXCodeCompleteResults structure we allocate internally;
232/// the client only sees the initial CXCodeCompleteResults structure.
233struct AllocatedCXCodeCompleteResults : public CXCodeCompleteResults {
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000234 AllocatedCXCodeCompleteResults();
235 ~AllocatedCXCodeCompleteResults();
236
Douglas Gregor33cdd812010-02-18 18:08:43 +0000237 /// \brief Diagnostics produced while performing code completion.
238 llvm::SmallVector<StoredDiagnostic, 8> Diagnostics;
239
Douglas Gregore0fbb832010-03-16 00:06:06 +0000240 /// \brief Diag object
Douglas Gregor8e984da2010-08-04 16:47:14 +0000241 llvm::IntrusiveRefCntPtr<Diagnostic> Diag;
Douglas Gregore0fbb832010-03-16 00:06:06 +0000242
Douglas Gregor33cdd812010-02-18 18:08:43 +0000243 /// \brief Language options used to adjust source locations.
Daniel Dunbar854d36b2010-01-30 23:31:40 +0000244 LangOptions LangOpts;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000245
246 /// \brief Source manager, used for diagnostics.
247 SourceManager SourceMgr;
248
249 /// \brief File manager, used for diagnostics.
250 FileManager FileMgr;
Douglas Gregor6cb5ba42010-02-18 23:35:40 +0000251
252 /// \brief Temporary files that should be removed once we have finished
253 /// with the code-completion results.
254 std::vector<llvm::sys::Path> TemporaryFiles;
Douglas Gregord8a5dba2010-08-04 17:07:00 +0000255
256 /// \brief Temporary buffers that will be deleted once we have finished with the code-completion results.
257 llvm::SmallVector<const llvm::MemoryBuffer *, 1> TemporaryBuffers;
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000258};
259
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000260AllocatedCXCodeCompleteResults::AllocatedCXCodeCompleteResults()
Douglas Gregord8a5dba2010-08-04 17:07:00 +0000261 : CXCodeCompleteResults(), Diag(new Diagnostic), SourceMgr(*Diag) { }
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000262
263AllocatedCXCodeCompleteResults::~AllocatedCXCodeCompleteResults() {
264 for (unsigned I = 0, N = NumResults; I != N; ++I)
Douglas Gregora2db7932010-05-26 22:00:08 +0000265 delete (CXStoredCodeCompletionString *)Results[I].CompletionString;
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000266 delete [] Results;
Douglas Gregor6cb5ba42010-02-18 23:35:40 +0000267
268 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
269 TemporaryFiles[I].eraseFromDisk();
Douglas Gregord8a5dba2010-08-04 17:07:00 +0000270 for (unsigned I = 0, N = TemporaryBuffers.size(); I != N; ++I)
271 delete TemporaryBuffers[I];
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000272}
273
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000274CXCodeCompleteResults *clang_codeComplete(CXIndex CIdx,
275 const char *source_filename,
276 int num_command_line_args,
Douglas Gregor57879fa2010-09-01 16:43:19 +0000277 const char * const *command_line_args,
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000278 unsigned num_unsaved_files,
279 struct CXUnsavedFile *unsaved_files,
280 const char *complete_filename,
281 unsigned complete_line,
Douglas Gregor33cdd812010-02-18 18:08:43 +0000282 unsigned complete_column) {
Ted Kremenek9e0cf092010-04-15 01:02:28 +0000283#ifdef UDP_CODE_COMPLETION_LOGGER
284#ifdef UDP_CODE_COMPLETION_LOGGER_PORT
285 const llvm::TimeRecord &StartTime = llvm::TimeRecord::getCurrentTime();
286#endif
287#endif
288
Douglas Gregord6009ff2010-07-26 16:29:14 +0000289 bool EnableLogging = getenv("LIBCLANG_CODE_COMPLETION_LOGGING") != 0;
Douglas Gregor028d3e42010-08-09 20:45:32 +0000290
291 llvm::OwningPtr<llvm::NamedRegionTimer> CCTimer;
292 if (getenv("LIBCLANG_TIMING")) {
293 llvm::SmallString<128> TimerName;
294 llvm::raw_svector_ostream TimerNameOut(TimerName);
Douglas Gregor8ef4c802010-08-09 21:00:09 +0000295 TimerNameOut << "Code completion (out-of-process) @ " << complete_filename
296 << ":" << complete_line << ":" << complete_column;
Douglas Gregor028d3e42010-08-09 20:45:32 +0000297 CCTimer.reset(new llvm::NamedRegionTimer(TimerNameOut.str()));
298 }
299
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000300 // The indexer, which is mainly used to determine where diagnostics go.
301 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
302
Douglas Gregorba965fb2010-01-28 00:56:43 +0000303 // Configure the diagnostics.
304 DiagnosticOptions DiagOpts;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000305 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
306 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregorba965fb2010-01-28 00:56:43 +0000307
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000308 // The set of temporary files that we've built.
309 std::vector<llvm::sys::Path> TemporaryFiles;
310
311 // Build up the arguments for invoking 'clang'.
312 std::vector<const char *> argv;
313
314 // First add the complete path to the 'clang' executable.
315 llvm::sys::Path ClangPath = CXXIdx->getClangPath();
316 argv.push_back(ClangPath.c_str());
317
Daniel Dunbardf000da2010-06-30 21:40:01 +0000318 // Always use Clang C++ support.
319 argv.push_back("-ccc-clang-cxx");
320
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000321 // Add the '-fsyntax-only' argument so that we only perform a basic
322 // syntax check of the code.
323 argv.push_back("-fsyntax-only");
324
325 // Add the appropriate '-code-completion-at=file:line:column' argument
326 // to perform code completion, with an "-Xclang" preceding it.
327 std::string code_complete_at;
328 code_complete_at += complete_filename;
329 code_complete_at += ":";
330 code_complete_at += llvm::utostr(complete_line);
331 code_complete_at += ":";
332 code_complete_at += llvm::utostr(complete_column);
333 argv.push_back("-Xclang");
334 argv.push_back("-code-completion-at");
335 argv.push_back("-Xclang");
336 argv.push_back(code_complete_at.c_str());
337 argv.push_back("-Xclang");
338 argv.push_back("-no-code-completion-debug-printer");
339 argv.push_back("-Xclang");
340 argv.push_back("-code-completion-macros");
Douglas Gregorac0605e2010-01-28 06:00:51 +0000341 argv.push_back("-fdiagnostics-binary");
342
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000343 // Remap any unsaved files to temporary files.
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000344 std::vector<std::string> RemapArgs;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000345 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
346 return 0;
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000347
348 // The pointers into the elements of RemapArgs are stable because we
349 // won't be adding anything to RemapArgs after this point.
350 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
351 argv.push_back(RemapArgs[i].c_str());
352
353 // Add the source file name (FIXME: later, we'll want to build temporary
354 // file from the buffer, or just feed the source text via standard input).
355 if (source_filename)
356 argv.push_back(source_filename);
357
358 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
359 for (int i = 0; i < num_command_line_args; ++i)
360 if (const char *arg = command_line_args[i]) {
361 if (strcmp(arg, "-o") == 0) {
362 ++i; // Also skip the matching argument.
363 continue;
364 }
365 if (strcmp(arg, "-emit-ast") == 0 ||
366 strcmp(arg, "-c") == 0 ||
367 strcmp(arg, "-fsyntax-only") == 0) {
368 continue;
369 }
370
371 // Keep the argument.
372 argv.push_back(arg);
373 }
374
Douglas Gregord6009ff2010-07-26 16:29:14 +0000375 if (EnableLogging) {
376 std::string Log = ClangPath.str();
377 for (unsigned I = 0, N = argv.size(); I != N; ++I) {
378 Log += ' ';
379 Log += argv[I];
380 }
381 fprintf(stderr, "libclang (Code Completion): %s\n", Log.c_str());
382 }
383
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000384 // Add the null terminator.
385 argv.push_back(NULL);
386
Douglas Gregorac0605e2010-01-28 06:00:51 +0000387 // Generate a temporary name for the code-completion results file.
Benjamin Kramerf156b9d2010-03-13 21:22:49 +0000388 char tmpFile[L_tmpnam];
389 char *tmpFileName = tmpnam(tmpFile);
390 llvm::sys::Path ResultsFile(tmpFileName);
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000391 TemporaryFiles.push_back(ResultsFile);
392
Douglas Gregorac0605e2010-01-28 06:00:51 +0000393 // Generate a temporary name for the diagnostics file.
Benjamin Kramerf156b9d2010-03-13 21:22:49 +0000394 char tmpFileResults[L_tmpnam];
395 char *tmpResultsFileName = tmpnam(tmpFileResults);
396 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregorac0605e2010-01-28 06:00:51 +0000397 TemporaryFiles.push_back(DiagnosticsFile);
398
Douglas Gregord6009ff2010-07-26 16:29:14 +0000399
400
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000401 // Invoke 'clang'.
402 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
403 // on Unix or NUL (Windows).
404 std::string ErrMsg;
Douglas Gregorac0605e2010-01-28 06:00:51 +0000405 const llvm::sys::Path *Redirects[] = { &DevNull, &ResultsFile,
406 &DiagnosticsFile, 0 };
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000407 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
408 /* redirects */ &Redirects[0],
409 /* secondsToWait */ 0,
410 /* memoryLimits */ 0, &ErrMsg);
411
Douglas Gregorba965fb2010-01-28 00:56:43 +0000412 if (!ErrMsg.empty()) {
413 std::string AllArgs;
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000414 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregorba965fb2010-01-28 00:56:43 +0000415 I != E; ++I) {
416 AllArgs += ' ';
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000417 if (*I)
Douglas Gregorba965fb2010-01-28 00:56:43 +0000418 AllArgs += *I;
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000419 }
Douglas Gregorba965fb2010-01-28 00:56:43 +0000420
Daniel Dunbar253dbad2010-02-23 20:23:45 +0000421 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000422 }
423
424 // Parse the resulting source file to find code-completion results.
425 using llvm::MemoryBuffer;
426 using llvm::StringRef;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000427 AllocatedCXCodeCompleteResults *Results = new AllocatedCXCodeCompleteResults;
428 Results->Results = 0;
429 Results->NumResults = 0;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000430 // FIXME: Set Results->LangOpts!
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000431 if (MemoryBuffer *F = MemoryBuffer::getFile(ResultsFile.c_str())) {
432 llvm::SmallVector<CXCompletionResult, 4> CompletionResults;
433 StringRef Buffer = F->getBuffer();
434 for (const char *Str = Buffer.data(), *StrEnd = Str + Buffer.size();
435 Str < StrEnd;) {
436 unsigned KindValue;
437 if (ReadUnsigned(Str, StrEnd, KindValue))
438 break;
439
Douglas Gregora2db7932010-05-26 22:00:08 +0000440 unsigned Priority;
441 if (ReadUnsigned(Str, StrEnd, Priority))
442 break;
443
Douglas Gregorf757a122010-08-23 23:00:57 +0000444 unsigned Availability;
445 if (ReadUnsigned(Str, StrEnd, Availability))
446 break;
447
Douglas Gregora2db7932010-05-26 22:00:08 +0000448 CXStoredCodeCompletionString *CCStr
Douglas Gregorf757a122010-08-23 23:00:57 +0000449 = new CXStoredCodeCompletionString(Priority,
450 (CXAvailabilityKind)Availability);
Douglas Gregora2db7932010-05-26 22:00:08 +0000451 if (!CCStr->Deserialize(Str, StrEnd)) {
452 delete CCStr;
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000453 continue;
Douglas Gregora2db7932010-05-26 22:00:08 +0000454 }
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000455
456 if (!CCStr->empty()) {
457 // Vend the code-completion result to the caller.
458 CXCompletionResult Result;
459 Result.CursorKind = (CXCursorKind)KindValue;
460 Result.CompletionString = CCStr;
461 CompletionResults.push_back(Result);
462 }
463 };
464
465 // Allocate the results.
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000466 Results->Results = new CXCompletionResult [CompletionResults.size()];
467 Results->NumResults = CompletionResults.size();
468 memcpy(Results->Results, CompletionResults.data(),
469 CompletionResults.size() * sizeof(CXCompletionResult));
Douglas Gregord8a5dba2010-08-04 17:07:00 +0000470 Results->TemporaryBuffers.push_back(F);
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000471 }
472
Douglas Gregor33cdd812010-02-18 18:08:43 +0000473 LoadSerializedDiagnostics(DiagnosticsFile, num_unsaved_files, unsaved_files,
474 Results->FileMgr, Results->SourceMgr,
475 Results->Diagnostics);
476
Douglas Gregor6cb5ba42010-02-18 23:35:40 +0000477 // Make sure we delete temporary files when the code-completion results are
478 // destroyed.
479 Results->TemporaryFiles.swap(TemporaryFiles);
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000480
Ted Kremenek9e0cf092010-04-15 01:02:28 +0000481#ifdef UDP_CODE_COMPLETION_LOGGER
482#ifdef UDP_CODE_COMPLETION_LOGGER_PORT
483 const llvm::TimeRecord &EndTime = llvm::TimeRecord::getCurrentTime();
484 llvm::SmallString<256> LogResult;
485 llvm::raw_svector_ostream os(LogResult);
486
487 // Figure out the language and whether or not it uses PCH.
488 const char *lang = 0;
489 bool usesPCH = false;
490
491 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
492 I != E; ++I) {
493 if (*I == 0)
494 continue;
495 if (strcmp(*I, "-x") == 0) {
496 if (I + 1 != E) {
497 lang = *(++I);
498 continue;
499 }
500 }
501 else if (strcmp(*I, "-include") == 0) {
502 if (I+1 != E) {
503 const char *arg = *(++I);
504 llvm::SmallString<512> pchName;
505 {
506 llvm::raw_svector_ostream os(pchName);
507 os << arg << ".pth";
508 }
509 pchName.push_back('\0');
510 struct stat stat_results;
511 if (stat(pchName.data(), &stat_results) == 0)
512 usesPCH = true;
513 continue;
514 }
515 }
516 }
517
Ted Kremenekcab334c2010-04-17 00:21:42 +0000518 os << "{ ";
519 os << "\"wall\": " << (EndTime.getWallTime() - StartTime.getWallTime());
520 os << ", \"numRes\": " << Results->NumResults;
521 os << ", \"diags\": " << Results->Diagnostics.size();
522 os << ", \"pch\": " << (usesPCH ? "true" : "false");
523 os << ", \"lang\": \"" << (lang ? lang : "<unknown>") << '"';
Ted Kremenek9e0cf092010-04-15 01:02:28 +0000524 const char *name = getlogin();
Ted Kremenekcab334c2010-04-17 00:21:42 +0000525 os << ", \"user\": \"" << (name ? name : "unknown") << '"';
526 os << ", \"clangVer\": \"" << getClangFullVersion() << '"';
527 os << " }";
Ted Kremenek9e0cf092010-04-15 01:02:28 +0000528
529 llvm::StringRef res = os.str();
530 if (res.size() > 0) {
531 do {
532 // Setup the UDP socket.
533 struct sockaddr_in servaddr;
534 bzero(&servaddr, sizeof(servaddr));
535 servaddr.sin_family = AF_INET;
536 servaddr.sin_port = htons(UDP_CODE_COMPLETION_LOGGER_PORT);
537 if (inet_pton(AF_INET, UDP_CODE_COMPLETION_LOGGER,
538 &servaddr.sin_addr) <= 0)
539 break;
540
541 int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
542 if (sockfd < 0)
543 break;
544
545 sendto(sockfd, res.data(), res.size(), 0,
546 (struct sockaddr *)&servaddr, sizeof(servaddr));
547 close(sockfd);
548 }
549 while (false);
550 }
551#endif
552#endif
Douglas Gregor9704c752010-08-27 21:13:41 +0000553 clang_sortCodeCompletionResults(Results->Results, Results->NumResults);
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000554 return Results;
555}
556
Douglas Gregor8e984da2010-08-04 16:47:14 +0000557} // end extern "C"
558
Douglas Gregor8e984da2010-08-04 16:47:14 +0000559namespace {
560 class CaptureCompletionResults : public CodeCompleteConsumer {
561 AllocatedCXCodeCompleteResults &AllocatedResults;
562
563 public:
564 explicit CaptureCompletionResults(AllocatedCXCodeCompleteResults &Results)
Douglas Gregor39982192010-08-15 06:18:01 +0000565 : CodeCompleteConsumer(true, false, true, false),
566 AllocatedResults(Results) { }
Douglas Gregor8e984da2010-08-04 16:47:14 +0000567
Douglas Gregor00c37ef2010-08-11 21:23:17 +0000568 virtual void ProcessCodeCompleteResults(Sema &S,
569 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +0000570 CodeCompletionResult *Results,
Douglas Gregor8e984da2010-08-04 16:47:14 +0000571 unsigned NumResults) {
572 AllocatedResults.Results = new CXCompletionResult [NumResults];
573 AllocatedResults.NumResults = NumResults;
574 for (unsigned I = 0; I != NumResults; ++I) {
575 CXStoredCodeCompletionString *StoredCompletion
Douglas Gregorf757a122010-08-23 23:00:57 +0000576 = new CXStoredCodeCompletionString(Results[I].Priority,
577 Results[I].Availability);
Douglas Gregor8e984da2010-08-04 16:47:14 +0000578 (void)Results[I].CreateCodeCompletionString(S, StoredCompletion);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000579 AllocatedResults.Results[I].CursorKind = Results[I].CursorKind;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000580 AllocatedResults.Results[I].CompletionString = StoredCompletion;
581 }
582 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +0000583
584 // FIXME: Add ProcessOverloadCandidates?
Douglas Gregor8e984da2010-08-04 16:47:14 +0000585 };
586}
587
588extern "C" {
Daniel Dunbar77af1c52010-08-19 23:44:10 +0000589struct CodeCompleteAtInfo {
590 CXTranslationUnit TU;
591 const char *complete_filename;
592 unsigned complete_line;
593 unsigned complete_column;
594 struct CXUnsavedFile *unsaved_files;
595 unsigned num_unsaved_files;
596 unsigned options;
597 CXCodeCompleteResults *result;
598};
599void clang_codeCompleteAt_Impl(void *UserData) {
600 CodeCompleteAtInfo *CCAI = static_cast<CodeCompleteAtInfo*>(UserData);
601 CXTranslationUnit TU = CCAI->TU;
602 const char *complete_filename = CCAI->complete_filename;
603 unsigned complete_line = CCAI->complete_line;
604 unsigned complete_column = CCAI->complete_column;
605 struct CXUnsavedFile *unsaved_files = CCAI->unsaved_files;
606 unsigned num_unsaved_files = CCAI->num_unsaved_files;
607 unsigned options = CCAI->options;
608 CCAI->result = 0;
609
Douglas Gregor8e984da2010-08-04 16:47:14 +0000610#ifdef UDP_CODE_COMPLETION_LOGGER
611#ifdef UDP_CODE_COMPLETION_LOGGER_PORT
612 const llvm::TimeRecord &StartTime = llvm::TimeRecord::getCurrentTime();
613#endif
614#endif
615
616 bool EnableLogging = getenv("LIBCLANG_CODE_COMPLETION_LOGGING") != 0;
617
618 ASTUnit *AST = static_cast<ASTUnit *>(TU);
619 if (!AST)
Daniel Dunbar77af1c52010-08-19 23:44:10 +0000620 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000621
Douglas Gregorca5b0532010-09-23 18:47:53 +0000622 ASTUnit::ConcurrencyCheck Check(*AST);
623
Douglas Gregor8e984da2010-08-04 16:47:14 +0000624 // Perform the remapping of source files.
625 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
626 for (unsigned I = 0; I != num_unsaved_files; ++I) {
627 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
628 const llvm::MemoryBuffer *Buffer
629 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
630 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
631 Buffer));
632 }
633
634 if (EnableLogging) {
635 // FIXME: Add logging.
636 }
637
638 // Parse the resulting source file to find code-completion results.
639 AllocatedCXCodeCompleteResults *Results = new AllocatedCXCodeCompleteResults;
640 Results->Results = 0;
641 Results->NumResults = 0;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000642
643 // Create a code-completion consumer to capture the results.
644 CaptureCompletionResults Capture(*Results);
645
646 // Perform completion.
647 AST->CodeComplete(complete_filename, complete_line, complete_column,
Douglas Gregorb68bc592010-08-05 09:09:23 +0000648 RemappedFiles.data(), RemappedFiles.size(),
649 (options & CXCodeComplete_IncludeMacros),
650 (options & CXCodeComplete_IncludeCodePatterns),
651 Capture,
Douglas Gregor8e984da2010-08-04 16:47:14 +0000652 *Results->Diag, Results->LangOpts, Results->SourceMgr,
Douglas Gregorb97b6662010-08-20 00:59:43 +0000653 Results->FileMgr, Results->Diagnostics,
654 Results->TemporaryBuffers);
Douglas Gregor8e984da2010-08-04 16:47:14 +0000655
656
657
658#ifdef UDP_CODE_COMPLETION_LOGGER
659#ifdef UDP_CODE_COMPLETION_LOGGER_PORT
660 const llvm::TimeRecord &EndTime = llvm::TimeRecord::getCurrentTime();
661 llvm::SmallString<256> LogResult;
662 llvm::raw_svector_ostream os(LogResult);
663
664 // Figure out the language and whether or not it uses PCH.
665 const char *lang = 0;
666 bool usesPCH = false;
667
668 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
669 I != E; ++I) {
670 if (*I == 0)
671 continue;
672 if (strcmp(*I, "-x") == 0) {
673 if (I + 1 != E) {
674 lang = *(++I);
675 continue;
676 }
677 }
678 else if (strcmp(*I, "-include") == 0) {
679 if (I+1 != E) {
680 const char *arg = *(++I);
681 llvm::SmallString<512> pchName;
682 {
683 llvm::raw_svector_ostream os(pchName);
684 os << arg << ".pth";
685 }
686 pchName.push_back('\0');
687 struct stat stat_results;
688 if (stat(pchName.data(), &stat_results) == 0)
689 usesPCH = true;
690 continue;
691 }
692 }
693 }
694
695 os << "{ ";
696 os << "\"wall\": " << (EndTime.getWallTime() - StartTime.getWallTime());
697 os << ", \"numRes\": " << Results->NumResults;
698 os << ", \"diags\": " << Results->Diagnostics.size();
699 os << ", \"pch\": " << (usesPCH ? "true" : "false");
700 os << ", \"lang\": \"" << (lang ? lang : "<unknown>") << '"';
701 const char *name = getlogin();
702 os << ", \"user\": \"" << (name ? name : "unknown") << '"';
703 os << ", \"clangVer\": \"" << getClangFullVersion() << '"';
704 os << " }";
705
706 llvm::StringRef res = os.str();
707 if (res.size() > 0) {
708 do {
709 // Setup the UDP socket.
710 struct sockaddr_in servaddr;
711 bzero(&servaddr, sizeof(servaddr));
712 servaddr.sin_family = AF_INET;
713 servaddr.sin_port = htons(UDP_CODE_COMPLETION_LOGGER_PORT);
714 if (inet_pton(AF_INET, UDP_CODE_COMPLETION_LOGGER,
715 &servaddr.sin_addr) <= 0)
716 break;
717
718 int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
719 if (sockfd < 0)
720 break;
721
722 sendto(sockfd, res.data(), res.size(), 0,
723 (struct sockaddr *)&servaddr, sizeof(servaddr));
724 close(sockfd);
725 }
726 while (false);
727 }
728#endif
729#endif
Daniel Dunbar77af1c52010-08-19 23:44:10 +0000730 CCAI->result = Results;
731}
732CXCodeCompleteResults *clang_codeCompleteAt(CXTranslationUnit TU,
733 const char *complete_filename,
734 unsigned complete_line,
735 unsigned complete_column,
736 struct CXUnsavedFile *unsaved_files,
737 unsigned num_unsaved_files,
738 unsigned options) {
739 CodeCompleteAtInfo CCAI = { TU, complete_filename, complete_line,
740 complete_column, unsaved_files, num_unsaved_files,
741 options, 0 };
742 llvm::CrashRecoveryContext CRC;
743
744 if (!CRC.RunSafely(clang_codeCompleteAt_Impl, &CCAI)) {
745 fprintf(stderr, "libclang: crash detected in code completion\n");
746 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
747 return 0;
748 }
749
750 return CCAI.result;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000751}
752
Douglas Gregorb68bc592010-08-05 09:09:23 +0000753unsigned clang_defaultCodeCompleteOptions(void) {
754 return CXCodeComplete_IncludeMacros;
755}
756
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000757void clang_disposeCodeCompleteResults(CXCodeCompleteResults *ResultsIn) {
758 if (!ResultsIn)
759 return;
760
761 AllocatedCXCodeCompleteResults *Results
762 = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000763 delete Results;
764}
Douglas Gregorf757a122010-08-23 23:00:57 +0000765
Douglas Gregor33cdd812010-02-18 18:08:43 +0000766unsigned
767clang_codeCompleteGetNumDiagnostics(CXCodeCompleteResults *ResultsIn) {
768 AllocatedCXCodeCompleteResults *Results
769 = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
770 if (!Results)
771 return 0;
772
773 return Results->Diagnostics.size();
774}
775
776CXDiagnostic
777clang_codeCompleteGetDiagnostic(CXCodeCompleteResults *ResultsIn,
778 unsigned Index) {
779 AllocatedCXCodeCompleteResults *Results
780 = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
781 if (!Results || Index >= Results->Diagnostics.size())
782 return 0;
783
784 return new CXStoredDiagnostic(Results->Diagnostics[Index], Results->LangOpts);
785}
786
787
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000788} // end extern "C"
Douglas Gregor49f67ce2010-08-26 13:48:20 +0000789
790namespace {
791 struct OrderCompletionResults {
792 bool operator()(const CXCompletionResult &XR,
793 const CXCompletionResult &YR) const {
794 CXStoredCodeCompletionString *X
795 = (CXStoredCodeCompletionString *)XR.CompletionString;
796 CXStoredCodeCompletionString *Y
797 = (CXStoredCodeCompletionString *)YR.CompletionString;
798
799 const char *XText = X->getTypedText();
800 const char *YText = Y->getTypedText();
801 if (!XText || !YText)
802 return XText != 0;
803
804 int result = llvm::StringRef(XText).compare_lower(YText);
805 if (result < 0)
806 return true;
807 if (result > 0)
808 return false;
809
810 result = llvm::StringRef(XText).compare(YText);
Douglas Gregorc7a7d922010-09-10 23:05:54 +0000811 return result < 0;
Douglas Gregor49f67ce2010-08-26 13:48:20 +0000812 }
813 };
814}
815
816extern "C" {
817 void clang_sortCodeCompletionResults(CXCompletionResult *Results,
818 unsigned NumResults) {
819 std::stable_sort(Results, Results + NumResults, OrderCompletionResults());
820 }
Douglas Gregor67c692c2010-08-26 15:07:07 +0000821}