blob: 0c8317e4461fca789d57e63acf5b925d2593bcfe [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"
Ted Kremenek0a90d322010-11-17 23:24:11 +000016#include "CXTranslationUnit.h"
Ted Kremeneked122732010-11-16 01:56:27 +000017#include "CXString.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000018#include "CIndexDiagnostic.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000019#include "clang/Basic/SourceManager.h"
20#include "clang/Basic/FileManager.h"
Douglas Gregor1abc6bc2010-08-04 16:47:14 +000021#include "clang/Frontend/ASTUnit.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000022#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000023#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000024#include "clang/Sema/CodeCompleteConsumer.h"
Douglas Gregordf95a132010-08-09 20:45:32 +000025#include "llvm/ADT/SmallString.h"
Ted Kremenekab188932010-01-05 19:32:54 +000026#include "llvm/ADT/StringExtras.h"
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +000027#include "llvm/Support/Atomic.h"
Daniel Dunbarb1fd3452010-08-19 23:44:10 +000028#include "llvm/Support/CrashRecoveryContext.h"
Ted Kremenekab188932010-01-05 19:32:54 +000029#include "llvm/Support/MemoryBuffer.h"
Douglas Gregordf95a132010-08-09 20:45:32 +000030#include "llvm/Support/Timer.h"
31#include "llvm/Support/raw_ostream.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000032#include "llvm/Support/Program.h"
Douglas Gregor3d398aa2010-07-26 16:29:14 +000033#include <cstdlib>
34#include <cstdio>
Ted Kremenekab188932010-01-05 19:32:54 +000035
Douglas Gregordf95a132010-08-09 20:45:32 +000036
Ted Kremenekda7af322010-04-15 01:02:28 +000037#ifdef UDP_CODE_COMPLETION_LOGGER
38#include "clang/Basic/Version.h"
Ted Kremenekda7af322010-04-15 01:02:28 +000039#include <arpa/inet.h>
40#include <sys/socket.h>
41#include <sys/types.h>
42#include <unistd.h>
43#endif
44
Ted Kremenekab188932010-01-05 19:32:54 +000045using namespace clang;
Ted Kremenek2ef6f8f2010-02-17 01:42:24 +000046using namespace clang::cxstring;
Ted Kremenekab188932010-01-05 19:32:54 +000047
48extern "C" {
49
50enum CXCompletionChunkKind
51clang_getCompletionChunkKind(CXCompletionString completion_string,
52 unsigned chunk_number) {
Douglas Gregor218937c2011-02-01 19:23:04 +000053 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
Ted Kremenekab188932010-01-05 19:32:54 +000054 if (!CCStr || chunk_number >= CCStr->size())
55 return CXCompletionChunk_Text;
56
57 switch ((*CCStr)[chunk_number].Kind) {
58 case CodeCompletionString::CK_TypedText:
59 return CXCompletionChunk_TypedText;
60 case CodeCompletionString::CK_Text:
61 return CXCompletionChunk_Text;
62 case CodeCompletionString::CK_Optional:
63 return CXCompletionChunk_Optional;
64 case CodeCompletionString::CK_Placeholder:
65 return CXCompletionChunk_Placeholder;
66 case CodeCompletionString::CK_Informative:
67 return CXCompletionChunk_Informative;
68 case CodeCompletionString::CK_ResultType:
69 return CXCompletionChunk_ResultType;
70 case CodeCompletionString::CK_CurrentParameter:
71 return CXCompletionChunk_CurrentParameter;
72 case CodeCompletionString::CK_LeftParen:
73 return CXCompletionChunk_LeftParen;
74 case CodeCompletionString::CK_RightParen:
75 return CXCompletionChunk_RightParen;
76 case CodeCompletionString::CK_LeftBracket:
77 return CXCompletionChunk_LeftBracket;
78 case CodeCompletionString::CK_RightBracket:
79 return CXCompletionChunk_RightBracket;
80 case CodeCompletionString::CK_LeftBrace:
81 return CXCompletionChunk_LeftBrace;
82 case CodeCompletionString::CK_RightBrace:
83 return CXCompletionChunk_RightBrace;
84 case CodeCompletionString::CK_LeftAngle:
85 return CXCompletionChunk_LeftAngle;
86 case CodeCompletionString::CK_RightAngle:
87 return CXCompletionChunk_RightAngle;
88 case CodeCompletionString::CK_Comma:
89 return CXCompletionChunk_Comma;
Douglas Gregor01dfea02010-01-10 23:08:15 +000090 case CodeCompletionString::CK_Colon:
91 return CXCompletionChunk_Colon;
92 case CodeCompletionString::CK_SemiColon:
93 return CXCompletionChunk_SemiColon;
94 case CodeCompletionString::CK_Equal:
95 return CXCompletionChunk_Equal;
96 case CodeCompletionString::CK_HorizontalSpace:
97 return CXCompletionChunk_HorizontalSpace;
98 case CodeCompletionString::CK_VerticalSpace:
99 return CXCompletionChunk_VerticalSpace;
Ted Kremenekab188932010-01-05 19:32:54 +0000100 }
101
102 // Should be unreachable, but let's be careful.
103 return CXCompletionChunk_Text;
104}
105
Ted Kremenek2ef6f8f2010-02-17 01:42:24 +0000106CXString clang_getCompletionChunkText(CXCompletionString completion_string,
107 unsigned chunk_number) {
Douglas Gregor218937c2011-02-01 19:23:04 +0000108 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
Ted Kremenekab188932010-01-05 19:32:54 +0000109 if (!CCStr || chunk_number >= CCStr->size())
Ted Kremeneka60ed472010-11-16 08:15:36 +0000110 return createCXString((const char*)0);
Ted Kremenekab188932010-01-05 19:32:54 +0000111
112 switch ((*CCStr)[chunk_number].Kind) {
113 case CodeCompletionString::CK_TypedText:
114 case CodeCompletionString::CK_Text:
115 case CodeCompletionString::CK_Placeholder:
116 case CodeCompletionString::CK_CurrentParameter:
117 case CodeCompletionString::CK_Informative:
118 case CodeCompletionString::CK_LeftParen:
119 case CodeCompletionString::CK_RightParen:
120 case CodeCompletionString::CK_LeftBracket:
121 case CodeCompletionString::CK_RightBracket:
122 case CodeCompletionString::CK_LeftBrace:
123 case CodeCompletionString::CK_RightBrace:
124 case CodeCompletionString::CK_LeftAngle:
125 case CodeCompletionString::CK_RightAngle:
126 case CodeCompletionString::CK_Comma:
127 case CodeCompletionString::CK_ResultType:
Douglas Gregor01dfea02010-01-10 23:08:15 +0000128 case CodeCompletionString::CK_Colon:
129 case CodeCompletionString::CK_SemiColon:
130 case CodeCompletionString::CK_Equal:
131 case CodeCompletionString::CK_HorizontalSpace:
Douglas Gregor21c241f2010-05-25 06:14:46 +0000132 case CodeCompletionString::CK_VerticalSpace:
Douglas Gregor5a9c0bc2010-10-08 20:39:29 +0000133 return createCXString((*CCStr)[chunk_number].Text, false);
Douglas Gregor21c241f2010-05-25 06:14:46 +0000134
Ted Kremenekab188932010-01-05 19:32:54 +0000135 case CodeCompletionString::CK_Optional:
136 // Note: treated as an empty text block.
Ted Kremenek2ef6f8f2010-02-17 01:42:24 +0000137 return createCXString("");
Ted Kremenekab188932010-01-05 19:32:54 +0000138 }
139
140 // Should be unreachable, but let's be careful.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000141 return createCXString((const char*)0);
Ted Kremenekab188932010-01-05 19:32:54 +0000142}
143
Ted Kremenek2ef6f8f2010-02-17 01:42:24 +0000144
Ted Kremenekab188932010-01-05 19:32:54 +0000145CXCompletionString
146clang_getCompletionChunkCompletionString(CXCompletionString completion_string,
147 unsigned chunk_number) {
Douglas Gregor218937c2011-02-01 19:23:04 +0000148 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
Ted Kremenekab188932010-01-05 19:32:54 +0000149 if (!CCStr || chunk_number >= CCStr->size())
150 return 0;
151
152 switch ((*CCStr)[chunk_number].Kind) {
153 case CodeCompletionString::CK_TypedText:
154 case CodeCompletionString::CK_Text:
155 case CodeCompletionString::CK_Placeholder:
156 case CodeCompletionString::CK_CurrentParameter:
157 case CodeCompletionString::CK_Informative:
158 case CodeCompletionString::CK_LeftParen:
159 case CodeCompletionString::CK_RightParen:
160 case CodeCompletionString::CK_LeftBracket:
161 case CodeCompletionString::CK_RightBracket:
162 case CodeCompletionString::CK_LeftBrace:
163 case CodeCompletionString::CK_RightBrace:
164 case CodeCompletionString::CK_LeftAngle:
165 case CodeCompletionString::CK_RightAngle:
166 case CodeCompletionString::CK_Comma:
167 case CodeCompletionString::CK_ResultType:
Douglas Gregor01dfea02010-01-10 23:08:15 +0000168 case CodeCompletionString::CK_Colon:
169 case CodeCompletionString::CK_SemiColon:
170 case CodeCompletionString::CK_Equal:
171 case CodeCompletionString::CK_HorizontalSpace:
172 case CodeCompletionString::CK_VerticalSpace:
Ted Kremenekab188932010-01-05 19:32:54 +0000173 return 0;
174
175 case CodeCompletionString::CK_Optional:
176 // Note: treated as an empty text block.
177 return (*CCStr)[chunk_number].Optional;
178 }
179
180 // Should be unreachable, but let's be careful.
181 return 0;
182}
183
184unsigned clang_getNumCompletionChunks(CXCompletionString completion_string) {
Douglas Gregor218937c2011-02-01 19:23:04 +0000185 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
Ted Kremenekab188932010-01-05 19:32:54 +0000186 return CCStr? CCStr->size() : 0;
187}
188
Douglas Gregor12e13132010-05-26 22:00:08 +0000189unsigned clang_getCompletionPriority(CXCompletionString completion_string) {
Douglas Gregor218937c2011-02-01 19:23:04 +0000190 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
Bill Wendlinga2ace582010-05-27 18:35:05 +0000191 return CCStr? CCStr->getPriority() : unsigned(CCP_Unlikely);
Douglas Gregor12e13132010-05-26 22:00:08 +0000192}
193
Douglas Gregor58ddb602010-08-23 23:00:57 +0000194enum CXAvailabilityKind
195clang_getCompletionAvailability(CXCompletionString completion_string) {
Douglas Gregor218937c2011-02-01 19:23:04 +0000196 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
197 return CCStr? static_cast<CXAvailabilityKind>(CCStr->getAvailability())
198 : CXAvailability_Available;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000199}
200
Ted Kremenekab188932010-01-05 19:32:54 +0000201/// \brief The CXCodeCompleteResults structure we allocate internally;
202/// the client only sees the initial CXCodeCompleteResults structure.
203struct AllocatedCXCodeCompleteResults : public CXCodeCompleteResults {
Anders Carlsson0d8d7e62011-03-18 18:22:40 +0000204 AllocatedCXCodeCompleteResults(const FileSystemOptions& FileSystemOpts);
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000205 ~AllocatedCXCodeCompleteResults();
206
Douglas Gregora88084b2010-02-18 18:08:43 +0000207 /// \brief Diagnostics produced while performing code completion.
208 llvm::SmallVector<StoredDiagnostic, 8> Diagnostics;
209
Douglas Gregorf715ca12010-03-16 00:06:06 +0000210 /// \brief Diag object
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000211 llvm::IntrusiveRefCntPtr<Diagnostic> Diag;
Douglas Gregorf715ca12010-03-16 00:06:06 +0000212
Douglas Gregora88084b2010-02-18 18:08:43 +0000213 /// \brief Language options used to adjust source locations.
Daniel Dunbar35b84402010-01-30 23:31:40 +0000214 LangOptions LangOpts;
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000215
216 FileSystemOptions FileSystemOpts;
217
Chris Lattner39b49bc2010-11-23 08:35:12 +0000218 /// \brief File manager, used for diagnostics.
Ted Kremenek4f327862011-03-21 18:40:17 +0000219 llvm::IntrusiveRefCntPtr<FileManager> FileMgr;
Chris Lattner39b49bc2010-11-23 08:35:12 +0000220
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000221 /// \brief Source manager, used for diagnostics.
Ted Kremenek4f327862011-03-21 18:40:17 +0000222 llvm::IntrusiveRefCntPtr<SourceManager> SourceMgr;
Douglas Gregor313e26c2010-02-18 23:35:40 +0000223
224 /// \brief Temporary files that should be removed once we have finished
225 /// with the code-completion results.
226 std::vector<llvm::sys::Path> TemporaryFiles;
Douglas Gregorb75d3df2010-08-04 17:07:00 +0000227
Chris Lattner7ad97ff2010-11-23 07:51:02 +0000228 /// \brief Temporary buffers that will be deleted once we have finished with
229 /// the code-completion results.
Douglas Gregorb75d3df2010-08-04 17:07:00 +0000230 llvm::SmallVector<const llvm::MemoryBuffer *, 1> TemporaryBuffers;
Douglas Gregor218937c2011-02-01 19:23:04 +0000231
Douglas Gregor48601b32011-02-16 19:08:06 +0000232 /// \brief Allocator used to store globally cached code-completion results.
233 llvm::IntrusiveRefCntPtr<clang::GlobalCodeCompletionAllocator>
234 CachedCompletionAllocator;
235
Douglas Gregor218937c2011-02-01 19:23:04 +0000236 /// \brief Allocator used to store code completion results.
Douglas Gregor110a68e2011-02-01 23:14:23 +0000237 clang::CodeCompletionAllocator CodeCompletionAllocator;
Ted Kremenekab188932010-01-05 19:32:54 +0000238};
239
Douglas Gregore3c60a72010-11-17 00:13:31 +0000240/// \brief Tracks the number of code-completion result objects that are
241/// currently active.
242///
243/// Used for debugging purposes only.
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000244static llvm::sys::cas_flag CodeCompletionResultObjects;
Douglas Gregore3c60a72010-11-17 00:13:31 +0000245
Anders Carlsson0d8d7e62011-03-18 18:22:40 +0000246AllocatedCXCodeCompleteResults::AllocatedCXCodeCompleteResults(
247 const FileSystemOptions& FileSystemOpts)
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000248 : CXCodeCompleteResults(),
249 Diag(new Diagnostic(
250 llvm::IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs))),
Anders Carlsson0d8d7e62011-03-18 18:22:40 +0000251 FileSystemOpts(FileSystemOpts),
Ted Kremenek4f327862011-03-21 18:40:17 +0000252 FileMgr(new FileManager(FileSystemOpts)),
253 SourceMgr(new SourceManager(*Diag, *FileMgr)) {
Douglas Gregore3c60a72010-11-17 00:13:31 +0000254 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000255 llvm::sys::AtomicIncrement(&CodeCompletionResultObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000256 fprintf(stderr, "+++ %d completion results\n", CodeCompletionResultObjects);
257 }
258}
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000259
260AllocatedCXCodeCompleteResults::~AllocatedCXCodeCompleteResults() {
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000261 delete [] Results;
Douglas Gregor313e26c2010-02-18 23:35:40 +0000262
263 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
264 TemporaryFiles[I].eraseFromDisk();
Douglas Gregorb75d3df2010-08-04 17:07:00 +0000265 for (unsigned I = 0, N = TemporaryBuffers.size(); I != N; ++I)
266 delete TemporaryBuffers[I];
Douglas Gregore3c60a72010-11-17 00:13:31 +0000267
268 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000269 llvm::sys::AtomicDecrement(&CodeCompletionResultObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000270 fprintf(stderr, "--- %d completion results\n", CodeCompletionResultObjects);
271 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000272}
273
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000274} // end extern "C"
275
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000276namespace {
277 class CaptureCompletionResults : public CodeCompleteConsumer {
278 AllocatedCXCodeCompleteResults &AllocatedResults;
Douglas Gregor32be4a52010-10-11 21:37:58 +0000279 llvm::SmallVector<CXCompletionResult, 16> StoredResults;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000280 public:
Douglas Gregor218937c2011-02-01 19:23:04 +0000281 CaptureCompletionResults(AllocatedCXCodeCompleteResults &Results)
Douglas Gregor8071e422010-08-15 06:18:01 +0000282 : CodeCompleteConsumer(true, false, true, false),
283 AllocatedResults(Results) { }
Douglas Gregor32be4a52010-10-11 21:37:58 +0000284 ~CaptureCompletionResults() { Finish(); }
285
Douglas Gregore6b1bb62010-08-11 21:23:17 +0000286 virtual void ProcessCodeCompleteResults(Sema &S,
287 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +0000288 CodeCompletionResult *Results,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000289 unsigned NumResults) {
Douglas Gregor32be4a52010-10-11 21:37:58 +0000290 StoredResults.reserve(StoredResults.size() + NumResults);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000291 for (unsigned I = 0; I != NumResults; ++I) {
Douglas Gregor218937c2011-02-01 19:23:04 +0000292 CodeCompletionString *StoredCompletion
293 = Results[I].CreateCodeCompletionString(S,
294 AllocatedResults.CodeCompletionAllocator);
Douglas Gregor32be4a52010-10-11 21:37:58 +0000295
296 CXCompletionResult R;
297 R.CursorKind = Results[I].CursorKind;
298 R.CompletionString = StoredCompletion;
299 StoredResults.push_back(R);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000300 }
301 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +0000302
Douglas Gregor32be4a52010-10-11 21:37:58 +0000303 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
304 OverloadCandidate *Candidates,
305 unsigned NumCandidates) {
306 StoredResults.reserve(StoredResults.size() + NumCandidates);
307 for (unsigned I = 0; I != NumCandidates; ++I) {
Douglas Gregor218937c2011-02-01 19:23:04 +0000308 CodeCompletionString *StoredCompletion
309 = Candidates[I].CreateSignatureString(CurrentArg, S,
310 AllocatedResults.CodeCompletionAllocator);
Douglas Gregor32be4a52010-10-11 21:37:58 +0000311
312 CXCompletionResult R;
313 R.CursorKind = CXCursor_NotImplemented;
314 R.CompletionString = StoredCompletion;
315 StoredResults.push_back(R);
316 }
317 }
318
Douglas Gregordae68752011-02-01 22:57:45 +0000319 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregor218937c2011-02-01 19:23:04 +0000320 return AllocatedResults.CodeCompletionAllocator;
321 }
322
Douglas Gregor32be4a52010-10-11 21:37:58 +0000323 private:
324 void Finish() {
325 AllocatedResults.Results = new CXCompletionResult [StoredResults.size()];
326 AllocatedResults.NumResults = StoredResults.size();
327 std::memcpy(AllocatedResults.Results, StoredResults.data(),
328 StoredResults.size() * sizeof(CXCompletionResult));
329 StoredResults.clear();
330 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000331 };
332}
333
334extern "C" {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +0000335struct CodeCompleteAtInfo {
336 CXTranslationUnit TU;
337 const char *complete_filename;
338 unsigned complete_line;
339 unsigned complete_column;
340 struct CXUnsavedFile *unsaved_files;
341 unsigned num_unsaved_files;
342 unsigned options;
343 CXCodeCompleteResults *result;
344};
345void clang_codeCompleteAt_Impl(void *UserData) {
346 CodeCompleteAtInfo *CCAI = static_cast<CodeCompleteAtInfo*>(UserData);
347 CXTranslationUnit TU = CCAI->TU;
348 const char *complete_filename = CCAI->complete_filename;
349 unsigned complete_line = CCAI->complete_line;
350 unsigned complete_column = CCAI->complete_column;
351 struct CXUnsavedFile *unsaved_files = CCAI->unsaved_files;
352 unsigned num_unsaved_files = CCAI->num_unsaved_files;
353 unsigned options = CCAI->options;
354 CCAI->result = 0;
355
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000356#ifdef UDP_CODE_COMPLETION_LOGGER
357#ifdef UDP_CODE_COMPLETION_LOGGER_PORT
358 const llvm::TimeRecord &StartTime = llvm::TimeRecord::getCurrentTime();
359#endif
360#endif
361
362 bool EnableLogging = getenv("LIBCLANG_CODE_COMPLETION_LOGGING") != 0;
363
Ted Kremeneka60ed472010-11-16 08:15:36 +0000364 ASTUnit *AST = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000365 if (!AST)
Daniel Dunbarb1fd3452010-08-19 23:44:10 +0000366 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000367
Douglas Gregor593b0c12010-09-23 18:47:53 +0000368 ASTUnit::ConcurrencyCheck Check(*AST);
369
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000370 // Perform the remapping of source files.
371 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
372 for (unsigned I = 0; I != num_unsaved_files; ++I) {
373 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
374 const llvm::MemoryBuffer *Buffer
375 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
376 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
377 Buffer));
378 }
379
380 if (EnableLogging) {
381 // FIXME: Add logging.
382 }
383
384 // Parse the resulting source file to find code-completion results.
Anders Carlsson0d8d7e62011-03-18 18:22:40 +0000385 AllocatedCXCodeCompleteResults *Results =
386 new AllocatedCXCodeCompleteResults(AST->getFileSystemOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000387 Results->Results = 0;
388 Results->NumResults = 0;
Douglas Gregor48601b32011-02-16 19:08:06 +0000389
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000390 // Create a code-completion consumer to capture the results.
391 CaptureCompletionResults Capture(*Results);
392
393 // Perform completion.
394 AST->CodeComplete(complete_filename, complete_line, complete_column,
Douglas Gregorcee235c2010-08-05 09:09:23 +0000395 RemappedFiles.data(), RemappedFiles.size(),
396 (options & CXCodeComplete_IncludeMacros),
397 (options & CXCodeComplete_IncludeCodePatterns),
398 Capture,
Ted Kremenek4f327862011-03-21 18:40:17 +0000399 *Results->Diag, Results->LangOpts, *Results->SourceMgr,
400 *Results->FileMgr, Results->Diagnostics,
Douglas Gregor2283d792010-08-20 00:59:43 +0000401 Results->TemporaryBuffers);
Douglas Gregor48601b32011-02-16 19:08:06 +0000402
403 // Keep a reference to the allocator used for cached global completions, so
404 // that we can be sure that the memory used by our code completion strings
405 // doesn't get freed due to subsequent reparses (while the code completion
406 // results are still active).
407 Results->CachedCompletionAllocator = AST->getCachedCompletionAllocator();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000408
409
410
411#ifdef UDP_CODE_COMPLETION_LOGGER
412#ifdef UDP_CODE_COMPLETION_LOGGER_PORT
413 const llvm::TimeRecord &EndTime = llvm::TimeRecord::getCurrentTime();
414 llvm::SmallString<256> LogResult;
415 llvm::raw_svector_ostream os(LogResult);
416
417 // Figure out the language and whether or not it uses PCH.
418 const char *lang = 0;
419 bool usesPCH = false;
420
421 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
422 I != E; ++I) {
423 if (*I == 0)
424 continue;
425 if (strcmp(*I, "-x") == 0) {
426 if (I + 1 != E) {
427 lang = *(++I);
428 continue;
429 }
430 }
431 else if (strcmp(*I, "-include") == 0) {
432 if (I+1 != E) {
433 const char *arg = *(++I);
434 llvm::SmallString<512> pchName;
435 {
436 llvm::raw_svector_ostream os(pchName);
437 os << arg << ".pth";
438 }
439 pchName.push_back('\0');
440 struct stat stat_results;
441 if (stat(pchName.data(), &stat_results) == 0)
442 usesPCH = true;
443 continue;
444 }
445 }
446 }
447
448 os << "{ ";
449 os << "\"wall\": " << (EndTime.getWallTime() - StartTime.getWallTime());
450 os << ", \"numRes\": " << Results->NumResults;
451 os << ", \"diags\": " << Results->Diagnostics.size();
452 os << ", \"pch\": " << (usesPCH ? "true" : "false");
453 os << ", \"lang\": \"" << (lang ? lang : "<unknown>") << '"';
454 const char *name = getlogin();
455 os << ", \"user\": \"" << (name ? name : "unknown") << '"';
456 os << ", \"clangVer\": \"" << getClangFullVersion() << '"';
457 os << " }";
458
459 llvm::StringRef res = os.str();
460 if (res.size() > 0) {
461 do {
462 // Setup the UDP socket.
463 struct sockaddr_in servaddr;
464 bzero(&servaddr, sizeof(servaddr));
465 servaddr.sin_family = AF_INET;
466 servaddr.sin_port = htons(UDP_CODE_COMPLETION_LOGGER_PORT);
467 if (inet_pton(AF_INET, UDP_CODE_COMPLETION_LOGGER,
468 &servaddr.sin_addr) <= 0)
469 break;
470
471 int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
472 if (sockfd < 0)
473 break;
474
475 sendto(sockfd, res.data(), res.size(), 0,
476 (struct sockaddr *)&servaddr, sizeof(servaddr));
477 close(sockfd);
478 }
479 while (false);
480 }
481#endif
482#endif
Daniel Dunbarb1fd3452010-08-19 23:44:10 +0000483 CCAI->result = Results;
484}
485CXCodeCompleteResults *clang_codeCompleteAt(CXTranslationUnit TU,
486 const char *complete_filename,
487 unsigned complete_line,
488 unsigned complete_column,
489 struct CXUnsavedFile *unsaved_files,
490 unsigned num_unsaved_files,
491 unsigned options) {
492 CodeCompleteAtInfo CCAI = { TU, complete_filename, complete_line,
493 complete_column, unsaved_files, num_unsaved_files,
494 options, 0 };
495 llvm::CrashRecoveryContext CRC;
496
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +0000497 if (!RunSafely(CRC, clang_codeCompleteAt_Impl, &CCAI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +0000498 fprintf(stderr, "libclang: crash detected in code completion\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +0000499 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarb1fd3452010-08-19 23:44:10 +0000500 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +0000501 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
502 PrintLibclangResourceUsage(TU);
Daniel Dunbarb1fd3452010-08-19 23:44:10 +0000503
504 return CCAI.result;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000505}
506
Douglas Gregorcee235c2010-08-05 09:09:23 +0000507unsigned clang_defaultCodeCompleteOptions(void) {
508 return CXCodeComplete_IncludeMacros;
509}
510
Ted Kremenekab188932010-01-05 19:32:54 +0000511void clang_disposeCodeCompleteResults(CXCodeCompleteResults *ResultsIn) {
512 if (!ResultsIn)
513 return;
514
515 AllocatedCXCodeCompleteResults *Results
516 = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
Ted Kremenekab188932010-01-05 19:32:54 +0000517 delete Results;
518}
Douglas Gregor58ddb602010-08-23 23:00:57 +0000519
Douglas Gregora88084b2010-02-18 18:08:43 +0000520unsigned
521clang_codeCompleteGetNumDiagnostics(CXCodeCompleteResults *ResultsIn) {
522 AllocatedCXCodeCompleteResults *Results
523 = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
524 if (!Results)
525 return 0;
526
527 return Results->Diagnostics.size();
528}
529
530CXDiagnostic
531clang_codeCompleteGetDiagnostic(CXCodeCompleteResults *ResultsIn,
532 unsigned Index) {
533 AllocatedCXCodeCompleteResults *Results
534 = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
535 if (!Results || Index >= Results->Diagnostics.size())
536 return 0;
537
538 return new CXStoredDiagnostic(Results->Diagnostics[Index], Results->LangOpts);
539}
540
541
Ted Kremenekab188932010-01-05 19:32:54 +0000542} // end extern "C"
Douglas Gregor1e5e6682010-08-26 13:48:20 +0000543
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +0000544/// \brief Simple utility function that appends a \p New string to the given
545/// \p Old string, using the \p Buffer for storage.
546///
547/// \param Old The string to which we are appending. This parameter will be
548/// updated to reflect the complete string.
549///
550///
551/// \param New The string to append to \p Old.
552///
553/// \param Buffer A buffer that stores the actual, concatenated string. It will
554/// be used if the old string is already-non-empty.
555static void AppendToString(llvm::StringRef &Old, llvm::StringRef New,
556 llvm::SmallString<256> &Buffer) {
557 if (Old.empty()) {
558 Old = New;
559 return;
560 }
561
562 if (Buffer.empty())
563 Buffer.append(Old.begin(), Old.end());
564 Buffer.append(New.begin(), New.end());
565 Old = Buffer.str();
566}
567
568/// \brief Get the typed-text blocks from the given code-completion string
569/// and return them as a single string.
570///
571/// \param String The code-completion string whose typed-text blocks will be
572/// concatenated.
573///
574/// \param Buffer A buffer used for storage of the completed name.
575static llvm::StringRef GetTypedName(CodeCompletionString *String,
576 llvm::SmallString<256> &Buffer) {
577 llvm::StringRef Result;
578 for (CodeCompletionString::iterator C = String->begin(), CEnd = String->end();
579 C != CEnd; ++C) {
580 if (C->Kind == CodeCompletionString::CK_TypedText)
581 AppendToString(Result, C->Text, Buffer);
582 }
583
584 return Result;
585}
586
Douglas Gregor1e5e6682010-08-26 13:48:20 +0000587namespace {
588 struct OrderCompletionResults {
589 bool operator()(const CXCompletionResult &XR,
590 const CXCompletionResult &YR) const {
Douglas Gregor218937c2011-02-01 19:23:04 +0000591 CodeCompletionString *X
592 = (CodeCompletionString *)XR.CompletionString;
593 CodeCompletionString *Y
594 = (CodeCompletionString *)YR.CompletionString;
Douglas Gregor1e5e6682010-08-26 13:48:20 +0000595
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +0000596 llvm::SmallString<256> XBuffer;
597 llvm::StringRef XText = GetTypedName(X, XBuffer);
598 llvm::SmallString<256> YBuffer;
599 llvm::StringRef YText = GetTypedName(Y, YBuffer);
Douglas Gregor1e5e6682010-08-26 13:48:20 +0000600
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +0000601 if (XText.empty() || YText.empty())
602 return !XText.empty();
603
604 int result = XText.compare_lower(YText);
Douglas Gregor1e5e6682010-08-26 13:48:20 +0000605 if (result < 0)
606 return true;
607 if (result > 0)
608 return false;
609
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +0000610 result = XText.compare(YText);
Douglas Gregor1aad3402010-09-10 23:05:54 +0000611 return result < 0;
Douglas Gregor1e5e6682010-08-26 13:48:20 +0000612 }
613 };
614}
615
616extern "C" {
617 void clang_sortCodeCompletionResults(CXCompletionResult *Results,
618 unsigned NumResults) {
619 std::stable_sort(Results, Results + NumResults, OrderCompletionResults());
620 }
Douglas Gregor458433d2010-08-26 15:07:07 +0000621}