blob: 9dbc7fa2a8feb51fa50d317e85843d6178e07eef [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 Gregore081a612011-07-21 01:05:26 +000018#include "CXCursor.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000019#include "CIndexDiagnostic.h"
Douglas Gregore081a612011-07-21 01:05:26 +000020#include "clang/AST/Type.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclObjC.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000023#include "clang/Basic/SourceManager.h"
24#include "clang/Basic/FileManager.h"
Douglas Gregor1abc6bc2010-08-04 16:47:14 +000025#include "clang/Frontend/ASTUnit.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000026#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000027#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000028#include "clang/Sema/CodeCompleteConsumer.h"
Douglas Gregordf95a132010-08-09 20:45:32 +000029#include "llvm/ADT/SmallString.h"
Ted Kremenekab188932010-01-05 19:32:54 +000030#include "llvm/ADT/StringExtras.h"
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +000031#include "llvm/Support/Atomic.h"
Daniel Dunbarb1fd3452010-08-19 23:44:10 +000032#include "llvm/Support/CrashRecoveryContext.h"
Ted Kremenekab188932010-01-05 19:32:54 +000033#include "llvm/Support/MemoryBuffer.h"
Douglas Gregordf95a132010-08-09 20:45:32 +000034#include "llvm/Support/Timer.h"
35#include "llvm/Support/raw_ostream.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000036#include "llvm/Support/Program.h"
Douglas Gregor3d398aa2010-07-26 16:29:14 +000037#include <cstdlib>
38#include <cstdio>
Ted Kremenekab188932010-01-05 19:32:54 +000039
Douglas Gregordf95a132010-08-09 20:45:32 +000040
Ted Kremenekda7af322010-04-15 01:02:28 +000041#ifdef UDP_CODE_COMPLETION_LOGGER
42#include "clang/Basic/Version.h"
Ted Kremenekda7af322010-04-15 01:02:28 +000043#include <arpa/inet.h>
44#include <sys/socket.h>
45#include <sys/types.h>
46#include <unistd.h>
47#endif
48
Ted Kremenekab188932010-01-05 19:32:54 +000049using namespace clang;
Ted Kremenek2ef6f8f2010-02-17 01:42:24 +000050using namespace clang::cxstring;
Ted Kremenekab188932010-01-05 19:32:54 +000051
52extern "C" {
53
54enum CXCompletionChunkKind
55clang_getCompletionChunkKind(CXCompletionString completion_string,
56 unsigned chunk_number) {
Douglas Gregor218937c2011-02-01 19:23:04 +000057 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
Ted Kremenekab188932010-01-05 19:32:54 +000058 if (!CCStr || chunk_number >= CCStr->size())
59 return CXCompletionChunk_Text;
60
61 switch ((*CCStr)[chunk_number].Kind) {
62 case CodeCompletionString::CK_TypedText:
63 return CXCompletionChunk_TypedText;
64 case CodeCompletionString::CK_Text:
65 return CXCompletionChunk_Text;
66 case CodeCompletionString::CK_Optional:
67 return CXCompletionChunk_Optional;
68 case CodeCompletionString::CK_Placeholder:
69 return CXCompletionChunk_Placeholder;
70 case CodeCompletionString::CK_Informative:
71 return CXCompletionChunk_Informative;
72 case CodeCompletionString::CK_ResultType:
73 return CXCompletionChunk_ResultType;
74 case CodeCompletionString::CK_CurrentParameter:
75 return CXCompletionChunk_CurrentParameter;
76 case CodeCompletionString::CK_LeftParen:
77 return CXCompletionChunk_LeftParen;
78 case CodeCompletionString::CK_RightParen:
79 return CXCompletionChunk_RightParen;
80 case CodeCompletionString::CK_LeftBracket:
81 return CXCompletionChunk_LeftBracket;
82 case CodeCompletionString::CK_RightBracket:
83 return CXCompletionChunk_RightBracket;
84 case CodeCompletionString::CK_LeftBrace:
85 return CXCompletionChunk_LeftBrace;
86 case CodeCompletionString::CK_RightBrace:
87 return CXCompletionChunk_RightBrace;
88 case CodeCompletionString::CK_LeftAngle:
89 return CXCompletionChunk_LeftAngle;
90 case CodeCompletionString::CK_RightAngle:
91 return CXCompletionChunk_RightAngle;
92 case CodeCompletionString::CK_Comma:
93 return CXCompletionChunk_Comma;
Douglas Gregor01dfea02010-01-10 23:08:15 +000094 case CodeCompletionString::CK_Colon:
95 return CXCompletionChunk_Colon;
96 case CodeCompletionString::CK_SemiColon:
97 return CXCompletionChunk_SemiColon;
98 case CodeCompletionString::CK_Equal:
99 return CXCompletionChunk_Equal;
100 case CodeCompletionString::CK_HorizontalSpace:
101 return CXCompletionChunk_HorizontalSpace;
102 case CodeCompletionString::CK_VerticalSpace:
103 return CXCompletionChunk_VerticalSpace;
Ted Kremenekab188932010-01-05 19:32:54 +0000104 }
105
106 // Should be unreachable, but let's be careful.
107 return CXCompletionChunk_Text;
108}
109
Ted Kremenek2ef6f8f2010-02-17 01:42:24 +0000110CXString clang_getCompletionChunkText(CXCompletionString completion_string,
111 unsigned chunk_number) {
Douglas Gregor218937c2011-02-01 19:23:04 +0000112 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
Ted Kremenekab188932010-01-05 19:32:54 +0000113 if (!CCStr || chunk_number >= CCStr->size())
Ted Kremeneka60ed472010-11-16 08:15:36 +0000114 return createCXString((const char*)0);
Ted Kremenekab188932010-01-05 19:32:54 +0000115
116 switch ((*CCStr)[chunk_number].Kind) {
117 case CodeCompletionString::CK_TypedText:
118 case CodeCompletionString::CK_Text:
119 case CodeCompletionString::CK_Placeholder:
120 case CodeCompletionString::CK_CurrentParameter:
121 case CodeCompletionString::CK_Informative:
122 case CodeCompletionString::CK_LeftParen:
123 case CodeCompletionString::CK_RightParen:
124 case CodeCompletionString::CK_LeftBracket:
125 case CodeCompletionString::CK_RightBracket:
126 case CodeCompletionString::CK_LeftBrace:
127 case CodeCompletionString::CK_RightBrace:
128 case CodeCompletionString::CK_LeftAngle:
129 case CodeCompletionString::CK_RightAngle:
130 case CodeCompletionString::CK_Comma:
131 case CodeCompletionString::CK_ResultType:
Douglas Gregor01dfea02010-01-10 23:08:15 +0000132 case CodeCompletionString::CK_Colon:
133 case CodeCompletionString::CK_SemiColon:
134 case CodeCompletionString::CK_Equal:
135 case CodeCompletionString::CK_HorizontalSpace:
Douglas Gregor21c241f2010-05-25 06:14:46 +0000136 case CodeCompletionString::CK_VerticalSpace:
Douglas Gregor5a9c0bc2010-10-08 20:39:29 +0000137 return createCXString((*CCStr)[chunk_number].Text, false);
Douglas Gregor21c241f2010-05-25 06:14:46 +0000138
Ted Kremenekab188932010-01-05 19:32:54 +0000139 case CodeCompletionString::CK_Optional:
140 // Note: treated as an empty text block.
Ted Kremenek2ef6f8f2010-02-17 01:42:24 +0000141 return createCXString("");
Ted Kremenekab188932010-01-05 19:32:54 +0000142 }
143
144 // Should be unreachable, but let's be careful.
Ted Kremeneka60ed472010-11-16 08:15:36 +0000145 return createCXString((const char*)0);
Ted Kremenekab188932010-01-05 19:32:54 +0000146}
147
Ted Kremenek2ef6f8f2010-02-17 01:42:24 +0000148
Ted Kremenekab188932010-01-05 19:32:54 +0000149CXCompletionString
150clang_getCompletionChunkCompletionString(CXCompletionString completion_string,
151 unsigned chunk_number) {
Douglas Gregor218937c2011-02-01 19:23:04 +0000152 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
Ted Kremenekab188932010-01-05 19:32:54 +0000153 if (!CCStr || chunk_number >= CCStr->size())
154 return 0;
155
156 switch ((*CCStr)[chunk_number].Kind) {
157 case CodeCompletionString::CK_TypedText:
158 case CodeCompletionString::CK_Text:
159 case CodeCompletionString::CK_Placeholder:
160 case CodeCompletionString::CK_CurrentParameter:
161 case CodeCompletionString::CK_Informative:
162 case CodeCompletionString::CK_LeftParen:
163 case CodeCompletionString::CK_RightParen:
164 case CodeCompletionString::CK_LeftBracket:
165 case CodeCompletionString::CK_RightBracket:
166 case CodeCompletionString::CK_LeftBrace:
167 case CodeCompletionString::CK_RightBrace:
168 case CodeCompletionString::CK_LeftAngle:
169 case CodeCompletionString::CK_RightAngle:
170 case CodeCompletionString::CK_Comma:
171 case CodeCompletionString::CK_ResultType:
Douglas Gregor01dfea02010-01-10 23:08:15 +0000172 case CodeCompletionString::CK_Colon:
173 case CodeCompletionString::CK_SemiColon:
174 case CodeCompletionString::CK_Equal:
175 case CodeCompletionString::CK_HorizontalSpace:
176 case CodeCompletionString::CK_VerticalSpace:
Ted Kremenekab188932010-01-05 19:32:54 +0000177 return 0;
178
179 case CodeCompletionString::CK_Optional:
180 // Note: treated as an empty text block.
181 return (*CCStr)[chunk_number].Optional;
182 }
183
184 // Should be unreachable, but let's be careful.
185 return 0;
186}
187
188unsigned clang_getNumCompletionChunks(CXCompletionString completion_string) {
Douglas Gregor218937c2011-02-01 19:23:04 +0000189 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
Ted Kremenekab188932010-01-05 19:32:54 +0000190 return CCStr? CCStr->size() : 0;
191}
192
Douglas Gregor12e13132010-05-26 22:00:08 +0000193unsigned clang_getCompletionPriority(CXCompletionString completion_string) {
Douglas Gregor218937c2011-02-01 19:23:04 +0000194 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
Bill Wendlinga2ace582010-05-27 18:35:05 +0000195 return CCStr? CCStr->getPriority() : unsigned(CCP_Unlikely);
Douglas Gregor12e13132010-05-26 22:00:08 +0000196}
197
Douglas Gregor58ddb602010-08-23 23:00:57 +0000198enum CXAvailabilityKind
199clang_getCompletionAvailability(CXCompletionString completion_string) {
Douglas Gregor218937c2011-02-01 19:23:04 +0000200 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
201 return CCStr? static_cast<CXAvailabilityKind>(CCStr->getAvailability())
202 : CXAvailability_Available;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000203}
204
Ted Kremenekab188932010-01-05 19:32:54 +0000205/// \brief The CXCodeCompleteResults structure we allocate internally;
206/// the client only sees the initial CXCodeCompleteResults structure.
207struct AllocatedCXCodeCompleteResults : public CXCodeCompleteResults {
Anders Carlsson0d8d7e62011-03-18 18:22:40 +0000208 AllocatedCXCodeCompleteResults(const FileSystemOptions& FileSystemOpts);
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000209 ~AllocatedCXCodeCompleteResults();
210
Douglas Gregora88084b2010-02-18 18:08:43 +0000211 /// \brief Diagnostics produced while performing code completion.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000212 SmallVector<StoredDiagnostic, 8> Diagnostics;
Douglas Gregora88084b2010-02-18 18:08:43 +0000213
Douglas Gregorf715ca12010-03-16 00:06:06 +0000214 /// \brief Diag object
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000215 llvm::IntrusiveRefCntPtr<Diagnostic> Diag;
Douglas Gregorf715ca12010-03-16 00:06:06 +0000216
Douglas Gregora88084b2010-02-18 18:08:43 +0000217 /// \brief Language options used to adjust source locations.
Daniel Dunbar35b84402010-01-30 23:31:40 +0000218 LangOptions LangOpts;
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000219
220 FileSystemOptions FileSystemOpts;
221
Chris Lattner39b49bc2010-11-23 08:35:12 +0000222 /// \brief File manager, used for diagnostics.
Ted Kremenek4f327862011-03-21 18:40:17 +0000223 llvm::IntrusiveRefCntPtr<FileManager> FileMgr;
Chris Lattner39b49bc2010-11-23 08:35:12 +0000224
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000225 /// \brief Source manager, used for diagnostics.
Ted Kremenek4f327862011-03-21 18:40:17 +0000226 llvm::IntrusiveRefCntPtr<SourceManager> SourceMgr;
Douglas Gregor313e26c2010-02-18 23:35:40 +0000227
228 /// \brief Temporary files that should be removed once we have finished
229 /// with the code-completion results.
230 std::vector<llvm::sys::Path> TemporaryFiles;
Douglas Gregorb75d3df2010-08-04 17:07:00 +0000231
Chris Lattner7ad97ff2010-11-23 07:51:02 +0000232 /// \brief Temporary buffers that will be deleted once we have finished with
233 /// the code-completion results.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000234 SmallVector<const llvm::MemoryBuffer *, 1> TemporaryBuffers;
Douglas Gregor218937c2011-02-01 19:23:04 +0000235
Douglas Gregor48601b32011-02-16 19:08:06 +0000236 /// \brief Allocator used to store globally cached code-completion results.
237 llvm::IntrusiveRefCntPtr<clang::GlobalCodeCompletionAllocator>
238 CachedCompletionAllocator;
239
Douglas Gregor218937c2011-02-01 19:23:04 +0000240 /// \brief Allocator used to store code completion results.
Douglas Gregor110a68e2011-02-01 23:14:23 +0000241 clang::CodeCompletionAllocator CodeCompletionAllocator;
Douglas Gregor3da626b2011-07-07 16:03:39 +0000242
243 /// \brief Context under which completion occurred.
244 enum clang::CodeCompletionContext::Kind ContextKind;
245
246 /// \brief A bitfield representing the acceptable completions for the
247 /// current context.
248 unsigned long long Contexts;
Douglas Gregore081a612011-07-21 01:05:26 +0000249
Douglas Gregor0a47d692011-07-26 15:24:30 +0000250 /// \brief The kind of the container for the current context for completions.
Douglas Gregore081a612011-07-21 01:05:26 +0000251 enum CXCursorKind ContainerKind;
Douglas Gregor0a47d692011-07-26 15:24:30 +0000252 /// \brief The USR of the container for the current context for completions.
Douglas Gregore081a612011-07-21 01:05:26 +0000253 CXString ContainerUSR;
Douglas Gregor0a47d692011-07-26 15:24:30 +0000254 /// \brief a boolean value indicating whether there is complete information
255 /// about the container
Douglas Gregore081a612011-07-21 01:05:26 +0000256 unsigned ContainerIsIncomplete;
Douglas Gregor0a47d692011-07-26 15:24:30 +0000257
258 /// \brief A string containing the Objective-C selector entered thus far for a
259 /// message send.
260 std::string Selector;
Ted Kremenekab188932010-01-05 19:32:54 +0000261};
262
Douglas Gregore3c60a72010-11-17 00:13:31 +0000263/// \brief Tracks the number of code-completion result objects that are
264/// currently active.
265///
266/// Used for debugging purposes only.
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000267static llvm::sys::cas_flag CodeCompletionResultObjects;
Douglas Gregore3c60a72010-11-17 00:13:31 +0000268
Anders Carlsson0d8d7e62011-03-18 18:22:40 +0000269AllocatedCXCodeCompleteResults::AllocatedCXCodeCompleteResults(
270 const FileSystemOptions& FileSystemOpts)
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000271 : CXCodeCompleteResults(),
272 Diag(new Diagnostic(
273 llvm::IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs))),
Anders Carlsson0d8d7e62011-03-18 18:22:40 +0000274 FileSystemOpts(FileSystemOpts),
Ted Kremenek4f327862011-03-21 18:40:17 +0000275 FileMgr(new FileManager(FileSystemOpts)),
276 SourceMgr(new SourceManager(*Diag, *FileMgr)) {
Douglas Gregore3c60a72010-11-17 00:13:31 +0000277 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000278 llvm::sys::AtomicIncrement(&CodeCompletionResultObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000279 fprintf(stderr, "+++ %d completion results\n", CodeCompletionResultObjects);
280 }
281}
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000282
283AllocatedCXCodeCompleteResults::~AllocatedCXCodeCompleteResults() {
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000284 delete [] Results;
Douglas Gregor313e26c2010-02-18 23:35:40 +0000285
Douglas Gregore081a612011-07-21 01:05:26 +0000286 clang_disposeString(ContainerUSR);
287
Douglas Gregor313e26c2010-02-18 23:35:40 +0000288 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
289 TemporaryFiles[I].eraseFromDisk();
Douglas Gregorb75d3df2010-08-04 17:07:00 +0000290 for (unsigned I = 0, N = TemporaryBuffers.size(); I != N; ++I)
291 delete TemporaryBuffers[I];
Douglas Gregore3c60a72010-11-17 00:13:31 +0000292
293 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000294 llvm::sys::AtomicDecrement(&CodeCompletionResultObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000295 fprintf(stderr, "--- %d completion results\n", CodeCompletionResultObjects);
296 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000297}
298
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000299} // end extern "C"
300
Douglas Gregor3da626b2011-07-07 16:03:39 +0000301static unsigned long long getContextsForContextKind(
302 enum CodeCompletionContext::Kind kind,
303 Sema &S) {
304 unsigned long long contexts = 0;
305 switch (kind) {
306 case CodeCompletionContext::CCC_OtherWithMacros: {
307 //We can allow macros here, but we don't know what else is permissible
308 //So we'll say the only thing permissible are macros
309 contexts = CXCompletionContext_MacroName;
310 break;
311 }
312 case CodeCompletionContext::CCC_TopLevel:
313 case CodeCompletionContext::CCC_ObjCIvarList:
314 case CodeCompletionContext::CCC_ClassStructUnion:
315 case CodeCompletionContext::CCC_Type: {
316 contexts = CXCompletionContext_AnyType |
317 CXCompletionContext_ObjCInterface;
318 if (S.getLangOptions().CPlusPlus) {
319 contexts |= CXCompletionContext_EnumTag |
320 CXCompletionContext_UnionTag |
321 CXCompletionContext_StructTag |
322 CXCompletionContext_ClassTag |
323 CXCompletionContext_NestedNameSpecifier;
324 }
325 break;
326 }
327 case CodeCompletionContext::CCC_Statement: {
328 contexts = CXCompletionContext_AnyType |
329 CXCompletionContext_ObjCInterface |
330 CXCompletionContext_AnyValue;
331 if (S.getLangOptions().CPlusPlus) {
332 contexts |= CXCompletionContext_EnumTag |
333 CXCompletionContext_UnionTag |
334 CXCompletionContext_StructTag |
335 CXCompletionContext_ClassTag |
336 CXCompletionContext_NestedNameSpecifier;
337 }
338 break;
339 }
340 case CodeCompletionContext::CCC_Expression: {
341 contexts = CXCompletionContext_AnyValue;
342 if (S.getLangOptions().CPlusPlus) {
343 contexts |= CXCompletionContext_AnyType |
344 CXCompletionContext_ObjCInterface |
345 CXCompletionContext_EnumTag |
346 CXCompletionContext_UnionTag |
347 CXCompletionContext_StructTag |
348 CXCompletionContext_ClassTag |
349 CXCompletionContext_NestedNameSpecifier;
350 }
351 break;
352 }
353 case CodeCompletionContext::CCC_ObjCMessageReceiver: {
354 contexts = CXCompletionContext_ObjCObjectValue |
355 CXCompletionContext_ObjCSelectorValue |
356 CXCompletionContext_ObjCInterface;
357 if (S.getLangOptions().CPlusPlus) {
358 contexts |= CXCompletionContext_CXXClassTypeValue |
359 CXCompletionContext_AnyType |
360 CXCompletionContext_EnumTag |
361 CXCompletionContext_UnionTag |
362 CXCompletionContext_StructTag |
363 CXCompletionContext_ClassTag |
364 CXCompletionContext_NestedNameSpecifier;
365 }
366 break;
367 }
368 case CodeCompletionContext::CCC_DotMemberAccess: {
369 contexts = CXCompletionContext_DotMemberAccess;
370 break;
371 }
372 case CodeCompletionContext::CCC_ArrowMemberAccess: {
373 contexts = CXCompletionContext_ArrowMemberAccess;
374 break;
375 }
376 case CodeCompletionContext::CCC_ObjCPropertyAccess: {
377 contexts = CXCompletionContext_ObjCPropertyAccess;
378 break;
379 }
380 case CodeCompletionContext::CCC_EnumTag: {
381 contexts = CXCompletionContext_EnumTag |
382 CXCompletionContext_NestedNameSpecifier;
383 break;
384 }
385 case CodeCompletionContext::CCC_UnionTag: {
386 contexts = CXCompletionContext_UnionTag |
387 CXCompletionContext_NestedNameSpecifier;
388 break;
389 }
390 case CodeCompletionContext::CCC_ClassOrStructTag: {
391 contexts = CXCompletionContext_StructTag |
392 CXCompletionContext_ClassTag |
393 CXCompletionContext_NestedNameSpecifier;
394 break;
395 }
396 case CodeCompletionContext::CCC_ObjCProtocolName: {
397 contexts = CXCompletionContext_ObjCProtocol;
398 break;
399 }
400 case CodeCompletionContext::CCC_Namespace: {
401 contexts = CXCompletionContext_Namespace;
402 break;
403 }
404 case CodeCompletionContext::CCC_PotentiallyQualifiedName: {
405 contexts = CXCompletionContext_NestedNameSpecifier;
406 break;
407 }
408 case CodeCompletionContext::CCC_MacroNameUse: {
409 contexts = CXCompletionContext_MacroName;
410 break;
411 }
412 case CodeCompletionContext::CCC_NaturalLanguage: {
413 contexts = CXCompletionContext_NaturalLanguage;
414 break;
415 }
416 case CodeCompletionContext::CCC_SelectorName: {
417 contexts = CXCompletionContext_ObjCSelectorName;
418 break;
419 }
420 case CodeCompletionContext::CCC_ParenthesizedExpression: {
421 contexts = CXCompletionContext_AnyType |
422 CXCompletionContext_ObjCInterface |
423 CXCompletionContext_AnyValue;
424 if (S.getLangOptions().CPlusPlus) {
425 contexts |= CXCompletionContext_EnumTag |
426 CXCompletionContext_UnionTag |
427 CXCompletionContext_StructTag |
428 CXCompletionContext_ClassTag |
429 CXCompletionContext_NestedNameSpecifier;
430 }
431 break;
432 }
433 case CodeCompletionContext::CCC_ObjCInstanceMessage: {
434 contexts = CXCompletionContext_ObjCInstanceMessage;
435 break;
436 }
437 case CodeCompletionContext::CCC_ObjCClassMessage: {
438 contexts = CXCompletionContext_ObjCClassMessage;
439 break;
440 }
441 case CodeCompletionContext::CCC_ObjCSuperclass: {
442 contexts = CXCompletionContext_ObjCInterface;
443 break;
444 }
445 case CodeCompletionContext::CCC_ObjCCategoryName: {
446 contexts = CXCompletionContext_ObjCCategory;
447 break;
448 }
449 case CodeCompletionContext::CCC_Other:
450 case CodeCompletionContext::CCC_ObjCInterface:
451 case CodeCompletionContext::CCC_ObjCImplementation:
452 case CodeCompletionContext::CCC_Name:
453 case CodeCompletionContext::CCC_MacroName:
454 case CodeCompletionContext::CCC_PreprocessorExpression:
455 case CodeCompletionContext::CCC_PreprocessorDirective:
456 case CodeCompletionContext::CCC_TypeQualifiers: {
457 //Only Clang results should be accepted, so we'll set all of the other
458 //context bits to 0 (i.e. the empty set)
459 contexts = CXCompletionContext_Unexposed;
460 break;
461 }
462 case CodeCompletionContext::CCC_Recovery: {
463 //We don't know what the current context is, so we'll return unknown
464 //This is the equivalent of setting all of the other context bits
465 contexts = CXCompletionContext_Unknown;
466 break;
467 }
468 }
469 return contexts;
470}
471
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000472namespace {
473 class CaptureCompletionResults : public CodeCompleteConsumer {
474 AllocatedCXCodeCompleteResults &AllocatedResults;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000475 SmallVector<CXCompletionResult, 16> StoredResults;
Douglas Gregore081a612011-07-21 01:05:26 +0000476 CXTranslationUnit *TU;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000477 public:
Douglas Gregore081a612011-07-21 01:05:26 +0000478 CaptureCompletionResults(AllocatedCXCodeCompleteResults &Results,
479 CXTranslationUnit *TranslationUnit)
Douglas Gregor8071e422010-08-15 06:18:01 +0000480 : CodeCompleteConsumer(true, false, true, false),
Douglas Gregore081a612011-07-21 01:05:26 +0000481 AllocatedResults(Results), TU(TranslationUnit) { }
Douglas Gregor32be4a52010-10-11 21:37:58 +0000482 ~CaptureCompletionResults() { Finish(); }
483
Douglas Gregore6b1bb62010-08-11 21:23:17 +0000484 virtual void ProcessCodeCompleteResults(Sema &S,
485 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +0000486 CodeCompletionResult *Results,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000487 unsigned NumResults) {
Douglas Gregor32be4a52010-10-11 21:37:58 +0000488 StoredResults.reserve(StoredResults.size() + NumResults);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000489 for (unsigned I = 0; I != NumResults; ++I) {
Douglas Gregor218937c2011-02-01 19:23:04 +0000490 CodeCompletionString *StoredCompletion
491 = Results[I].CreateCodeCompletionString(S,
492 AllocatedResults.CodeCompletionAllocator);
Douglas Gregor32be4a52010-10-11 21:37:58 +0000493
494 CXCompletionResult R;
495 R.CursorKind = Results[I].CursorKind;
496 R.CompletionString = StoredCompletion;
497 StoredResults.push_back(R);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000498 }
Douglas Gregor3da626b2011-07-07 16:03:39 +0000499
Douglas Gregore081a612011-07-21 01:05:26 +0000500 enum CodeCompletionContext::Kind contextKind = Context.getKind();
Douglas Gregor3da626b2011-07-07 16:03:39 +0000501
Douglas Gregore081a612011-07-21 01:05:26 +0000502 AllocatedResults.ContextKind = contextKind;
503 AllocatedResults.Contexts = getContextsForContextKind(contextKind, S);
504
Douglas Gregor0a47d692011-07-26 15:24:30 +0000505 AllocatedResults.Selector = "";
506 if (Context.getNumSelIdents() > 0) {
507 for (unsigned i = 0; i < Context.getNumSelIdents(); i++) {
508 IdentifierInfo *selIdent = Context.getSelIdents()[i];
509 if (selIdent != NULL) {
510 StringRef selectorString = Context.getSelIdents()[i]->getName();
Benjamin Kramera0651c52011-07-26 16:59:25 +0000511 AllocatedResults.Selector += selectorString;
Douglas Gregor0a47d692011-07-26 15:24:30 +0000512 }
513 AllocatedResults.Selector += ":";
514 }
515 }
516
Douglas Gregore081a612011-07-21 01:05:26 +0000517 QualType baseType = Context.getBaseType();
518 NamedDecl *D = NULL;
519
520 if (!baseType.isNull()) {
521 // Get the declaration for a class/struct/union/enum type
522 if (const TagType *Tag = baseType->getAs<TagType>())
523 D = Tag->getDecl();
524 // Get the @interface declaration for a (possibly-qualified) Objective-C
525 // object pointer type, e.g., NSString*
526 else if (const ObjCObjectPointerType *ObjPtr =
527 baseType->getAs<ObjCObjectPointerType>())
528 D = ObjPtr->getInterfaceDecl();
529 // Get the @interface declaration for an Objective-C object type
530 else if (const ObjCObjectType *Obj = baseType->getAs<ObjCObjectType>())
531 D = Obj->getInterface();
532 // Get the class for a C++ injected-class-name
533 else if (const InjectedClassNameType *Injected =
534 baseType->getAs<InjectedClassNameType>())
535 D = Injected->getDecl();
536 }
537
538 if (D != NULL) {
539 CXCursor cursor = cxcursor::MakeCXCursor(D, *TU);
540
541 CXCursorKind cursorKind = clang_getCursorKind(cursor);
542 CXString cursorUSR = clang_getCursorUSR(cursor);
543
544 AllocatedResults.ContainerKind = cursorKind;
545 AllocatedResults.ContainerUSR = cursorUSR;
546 const Type *type = baseType.getTypePtrOrNull();
547 if (type != NULL) {
548 AllocatedResults.ContainerIsIncomplete = type->isIncompleteType();
549 }
550 else {
551 AllocatedResults.ContainerIsIncomplete = 1;
552 }
553 }
554 else {
555 AllocatedResults.ContainerKind = CXCursor_InvalidCode;
556 AllocatedResults.ContainerUSR = createCXString("");
557 AllocatedResults.ContainerIsIncomplete = 1;
558 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000559 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +0000560
Douglas Gregor32be4a52010-10-11 21:37:58 +0000561 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
562 OverloadCandidate *Candidates,
563 unsigned NumCandidates) {
564 StoredResults.reserve(StoredResults.size() + NumCandidates);
565 for (unsigned I = 0; I != NumCandidates; ++I) {
Douglas Gregor218937c2011-02-01 19:23:04 +0000566 CodeCompletionString *StoredCompletion
567 = Candidates[I].CreateSignatureString(CurrentArg, S,
568 AllocatedResults.CodeCompletionAllocator);
Douglas Gregor32be4a52010-10-11 21:37:58 +0000569
570 CXCompletionResult R;
571 R.CursorKind = CXCursor_NotImplemented;
572 R.CompletionString = StoredCompletion;
573 StoredResults.push_back(R);
574 }
575 }
576
Douglas Gregordae68752011-02-01 22:57:45 +0000577 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregor218937c2011-02-01 19:23:04 +0000578 return AllocatedResults.CodeCompletionAllocator;
579 }
580
Douglas Gregor32be4a52010-10-11 21:37:58 +0000581 private:
582 void Finish() {
583 AllocatedResults.Results = new CXCompletionResult [StoredResults.size()];
584 AllocatedResults.NumResults = StoredResults.size();
585 std::memcpy(AllocatedResults.Results, StoredResults.data(),
586 StoredResults.size() * sizeof(CXCompletionResult));
587 StoredResults.clear();
588 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000589 };
590}
591
592extern "C" {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +0000593struct CodeCompleteAtInfo {
594 CXTranslationUnit TU;
595 const char *complete_filename;
596 unsigned complete_line;
597 unsigned complete_column;
598 struct CXUnsavedFile *unsaved_files;
599 unsigned num_unsaved_files;
600 unsigned options;
601 CXCodeCompleteResults *result;
602};
603void clang_codeCompleteAt_Impl(void *UserData) {
604 CodeCompleteAtInfo *CCAI = static_cast<CodeCompleteAtInfo*>(UserData);
605 CXTranslationUnit TU = CCAI->TU;
606 const char *complete_filename = CCAI->complete_filename;
607 unsigned complete_line = CCAI->complete_line;
608 unsigned complete_column = CCAI->complete_column;
609 struct CXUnsavedFile *unsaved_files = CCAI->unsaved_files;
610 unsigned num_unsaved_files = CCAI->num_unsaved_files;
611 unsigned options = CCAI->options;
612 CCAI->result = 0;
613
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000614#ifdef UDP_CODE_COMPLETION_LOGGER
615#ifdef UDP_CODE_COMPLETION_LOGGER_PORT
616 const llvm::TimeRecord &StartTime = llvm::TimeRecord::getCurrentTime();
617#endif
618#endif
619
620 bool EnableLogging = getenv("LIBCLANG_CODE_COMPLETION_LOGGING") != 0;
621
Ted Kremeneka60ed472010-11-16 08:15:36 +0000622 ASTUnit *AST = static_cast<ASTUnit *>(TU->TUData);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000623 if (!AST)
Daniel Dunbarb1fd3452010-08-19 23:44:10 +0000624 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000625
Douglas Gregor593b0c12010-09-23 18:47:53 +0000626 ASTUnit::ConcurrencyCheck Check(*AST);
627
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000628 // Perform the remapping of source files.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000629 SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000630 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000631 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000632 const llvm::MemoryBuffer *Buffer
633 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
634 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
635 Buffer));
636 }
637
638 if (EnableLogging) {
639 // FIXME: Add logging.
640 }
641
642 // Parse the resulting source file to find code-completion results.
Anders Carlsson0d8d7e62011-03-18 18:22:40 +0000643 AllocatedCXCodeCompleteResults *Results =
644 new AllocatedCXCodeCompleteResults(AST->getFileSystemOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000645 Results->Results = 0;
646 Results->NumResults = 0;
Douglas Gregor48601b32011-02-16 19:08:06 +0000647
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000648 // Create a code-completion consumer to capture the results.
Douglas Gregore081a612011-07-21 01:05:26 +0000649 CaptureCompletionResults Capture(*Results, &TU);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000650
651 // Perform completion.
652 AST->CodeComplete(complete_filename, complete_line, complete_column,
Douglas Gregorcee235c2010-08-05 09:09:23 +0000653 RemappedFiles.data(), RemappedFiles.size(),
654 (options & CXCodeComplete_IncludeMacros),
655 (options & CXCodeComplete_IncludeCodePatterns),
656 Capture,
Ted Kremenek4f327862011-03-21 18:40:17 +0000657 *Results->Diag, Results->LangOpts, *Results->SourceMgr,
658 *Results->FileMgr, Results->Diagnostics,
Douglas Gregor2283d792010-08-20 00:59:43 +0000659 Results->TemporaryBuffers);
Douglas Gregor48601b32011-02-16 19:08:06 +0000660
661 // Keep a reference to the allocator used for cached global completions, so
662 // that we can be sure that the memory used by our code completion strings
663 // doesn't get freed due to subsequent reparses (while the code completion
664 // results are still active).
665 Results->CachedCompletionAllocator = AST->getCachedCompletionAllocator();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000666
667
668
669#ifdef UDP_CODE_COMPLETION_LOGGER
670#ifdef UDP_CODE_COMPLETION_LOGGER_PORT
671 const llvm::TimeRecord &EndTime = llvm::TimeRecord::getCurrentTime();
672 llvm::SmallString<256> LogResult;
673 llvm::raw_svector_ostream os(LogResult);
674
675 // Figure out the language and whether or not it uses PCH.
676 const char *lang = 0;
677 bool usesPCH = false;
678
679 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
680 I != E; ++I) {
681 if (*I == 0)
682 continue;
683 if (strcmp(*I, "-x") == 0) {
684 if (I + 1 != E) {
685 lang = *(++I);
686 continue;
687 }
688 }
689 else if (strcmp(*I, "-include") == 0) {
690 if (I+1 != E) {
691 const char *arg = *(++I);
692 llvm::SmallString<512> pchName;
693 {
694 llvm::raw_svector_ostream os(pchName);
695 os << arg << ".pth";
696 }
697 pchName.push_back('\0');
698 struct stat stat_results;
Douglas Gregor0a47d692011-07-26 15:24:30 +0000699 if (stat(pchName.str().c_str(), &stat_results) == 0)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000700 usesPCH = true;
701 continue;
702 }
703 }
704 }
705
706 os << "{ ";
707 os << "\"wall\": " << (EndTime.getWallTime() - StartTime.getWallTime());
708 os << ", \"numRes\": " << Results->NumResults;
709 os << ", \"diags\": " << Results->Diagnostics.size();
710 os << ", \"pch\": " << (usesPCH ? "true" : "false");
711 os << ", \"lang\": \"" << (lang ? lang : "<unknown>") << '"';
712 const char *name = getlogin();
713 os << ", \"user\": \"" << (name ? name : "unknown") << '"';
714 os << ", \"clangVer\": \"" << getClangFullVersion() << '"';
715 os << " }";
716
Chris Lattner5f9e2722011-07-23 10:55:15 +0000717 StringRef res = os.str();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000718 if (res.size() > 0) {
719 do {
720 // Setup the UDP socket.
721 struct sockaddr_in servaddr;
722 bzero(&servaddr, sizeof(servaddr));
723 servaddr.sin_family = AF_INET;
724 servaddr.sin_port = htons(UDP_CODE_COMPLETION_LOGGER_PORT);
725 if (inet_pton(AF_INET, UDP_CODE_COMPLETION_LOGGER,
726 &servaddr.sin_addr) <= 0)
727 break;
728
729 int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
730 if (sockfd < 0)
731 break;
732
733 sendto(sockfd, res.data(), res.size(), 0,
734 (struct sockaddr *)&servaddr, sizeof(servaddr));
735 close(sockfd);
736 }
737 while (false);
738 }
739#endif
740#endif
Daniel Dunbarb1fd3452010-08-19 23:44:10 +0000741 CCAI->result = Results;
742}
743CXCodeCompleteResults *clang_codeCompleteAt(CXTranslationUnit TU,
744 const char *complete_filename,
745 unsigned complete_line,
746 unsigned complete_column,
747 struct CXUnsavedFile *unsaved_files,
748 unsigned num_unsaved_files,
749 unsigned options) {
750 CodeCompleteAtInfo CCAI = { TU, complete_filename, complete_line,
751 complete_column, unsaved_files, num_unsaved_files,
752 options, 0 };
753 llvm::CrashRecoveryContext CRC;
754
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +0000755 if (!RunSafely(CRC, clang_codeCompleteAt_Impl, &CCAI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +0000756 fprintf(stderr, "libclang: crash detected in code completion\n");
Ted Kremeneka60ed472010-11-16 08:15:36 +0000757 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
Daniel Dunbarb1fd3452010-08-19 23:44:10 +0000758 return 0;
Douglas Gregor6df78732011-05-05 20:27:22 +0000759 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
760 PrintLibclangResourceUsage(TU);
Daniel Dunbarb1fd3452010-08-19 23:44:10 +0000761
762 return CCAI.result;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000763}
764
Douglas Gregorcee235c2010-08-05 09:09:23 +0000765unsigned clang_defaultCodeCompleteOptions(void) {
766 return CXCodeComplete_IncludeMacros;
767}
768
Ted Kremenekab188932010-01-05 19:32:54 +0000769void clang_disposeCodeCompleteResults(CXCodeCompleteResults *ResultsIn) {
770 if (!ResultsIn)
771 return;
772
773 AllocatedCXCodeCompleteResults *Results
774 = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
Ted Kremenekab188932010-01-05 19:32:54 +0000775 delete Results;
776}
Douglas Gregor58ddb602010-08-23 23:00:57 +0000777
Douglas Gregora88084b2010-02-18 18:08:43 +0000778unsigned
779clang_codeCompleteGetNumDiagnostics(CXCodeCompleteResults *ResultsIn) {
780 AllocatedCXCodeCompleteResults *Results
781 = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
782 if (!Results)
783 return 0;
784
785 return Results->Diagnostics.size();
786}
787
788CXDiagnostic
789clang_codeCompleteGetDiagnostic(CXCodeCompleteResults *ResultsIn,
790 unsigned Index) {
791 AllocatedCXCodeCompleteResults *Results
792 = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
793 if (!Results || Index >= Results->Diagnostics.size())
794 return 0;
795
796 return new CXStoredDiagnostic(Results->Diagnostics[Index], Results->LangOpts);
797}
798
Douglas Gregor3da626b2011-07-07 16:03:39 +0000799unsigned long long
800clang_codeCompleteGetContexts(CXCodeCompleteResults *ResultsIn) {
801 AllocatedCXCodeCompleteResults *Results
802 = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
803 if (!Results)
804 return 0;
805
806 return Results->Contexts;
807}
Douglas Gregora88084b2010-02-18 18:08:43 +0000808
Douglas Gregore081a612011-07-21 01:05:26 +0000809enum CXCursorKind clang_codeCompleteGetContainerKind(
810 CXCodeCompleteResults *ResultsIn,
811 unsigned *IsIncomplete) {
812 AllocatedCXCodeCompleteResults *Results =
813 static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn);
814 if (!Results)
815 return CXCursor_InvalidCode;
816
817 if (IsIncomplete != NULL) {
818 *IsIncomplete = Results->ContainerIsIncomplete;
819 }
820
821 return Results->ContainerKind;
822}
823
824CXString clang_codeCompleteGetContainerUSR(CXCodeCompleteResults *ResultsIn) {
825 AllocatedCXCodeCompleteResults *Results =
826 static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn);
827 if (!Results)
828 return createCXString("");
829
830 return createCXString(clang_getCString(Results->ContainerUSR));
831}
Douglas Gregor0a47d692011-07-26 15:24:30 +0000832
833
834CXString clang_codeCompleteGetObjCSelector(CXCodeCompleteResults *ResultsIn) {
835 AllocatedCXCodeCompleteResults *Results =
836 static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn);
837 if (!Results)
838 return createCXString("");
839
840 return createCXString(Results->Selector);
841}
Douglas Gregore081a612011-07-21 01:05:26 +0000842
Ted Kremenekab188932010-01-05 19:32:54 +0000843} // end extern "C"
Douglas Gregor1e5e6682010-08-26 13:48:20 +0000844
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +0000845/// \brief Simple utility function that appends a \p New string to the given
846/// \p Old string, using the \p Buffer for storage.
847///
848/// \param Old The string to which we are appending. This parameter will be
849/// updated to reflect the complete string.
850///
851///
852/// \param New The string to append to \p Old.
853///
854/// \param Buffer A buffer that stores the actual, concatenated string. It will
855/// be used if the old string is already-non-empty.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000856static void AppendToString(StringRef &Old, StringRef New,
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +0000857 llvm::SmallString<256> &Buffer) {
858 if (Old.empty()) {
859 Old = New;
860 return;
861 }
862
863 if (Buffer.empty())
864 Buffer.append(Old.begin(), Old.end());
865 Buffer.append(New.begin(), New.end());
866 Old = Buffer.str();
867}
868
869/// \brief Get the typed-text blocks from the given code-completion string
870/// and return them as a single string.
871///
872/// \param String The code-completion string whose typed-text blocks will be
873/// concatenated.
874///
875/// \param Buffer A buffer used for storage of the completed name.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000876static StringRef GetTypedName(CodeCompletionString *String,
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +0000877 llvm::SmallString<256> &Buffer) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000878 StringRef Result;
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +0000879 for (CodeCompletionString::iterator C = String->begin(), CEnd = String->end();
880 C != CEnd; ++C) {
881 if (C->Kind == CodeCompletionString::CK_TypedText)
882 AppendToString(Result, C->Text, Buffer);
883 }
884
885 return Result;
886}
887
Douglas Gregor1e5e6682010-08-26 13:48:20 +0000888namespace {
889 struct OrderCompletionResults {
890 bool operator()(const CXCompletionResult &XR,
891 const CXCompletionResult &YR) const {
Douglas Gregor218937c2011-02-01 19:23:04 +0000892 CodeCompletionString *X
893 = (CodeCompletionString *)XR.CompletionString;
894 CodeCompletionString *Y
895 = (CodeCompletionString *)YR.CompletionString;
Douglas Gregor1e5e6682010-08-26 13:48:20 +0000896
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +0000897 llvm::SmallString<256> XBuffer;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000898 StringRef XText = GetTypedName(X, XBuffer);
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +0000899 llvm::SmallString<256> YBuffer;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000900 StringRef YText = GetTypedName(Y, YBuffer);
Douglas Gregor1e5e6682010-08-26 13:48:20 +0000901
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +0000902 if (XText.empty() || YText.empty())
903 return !XText.empty();
904
905 int result = XText.compare_lower(YText);
Douglas Gregor1e5e6682010-08-26 13:48:20 +0000906 if (result < 0)
907 return true;
908 if (result > 0)
909 return false;
910
Douglas Gregorc7b7b7a2010-10-18 21:05:04 +0000911 result = XText.compare(YText);
Douglas Gregor1aad3402010-09-10 23:05:54 +0000912 return result < 0;
Douglas Gregor1e5e6682010-08-26 13:48:20 +0000913 }
914 };
915}
916
917extern "C" {
918 void clang_sortCodeCompletionResults(CXCompletionResult *Results,
919 unsigned NumResults) {
920 std::stable_sort(Results, Results + NumResults, OrderCompletionResults());
921 }
Douglas Gregor458433d2010-08-26 15:07:07 +0000922}