1d5a2a073SDaniel Dunbar //===- CIndexCodeCompletion.cpp - Code Completion API hooks ---------------===//
2d5a2a073SDaniel Dunbar //
3d5a2a073SDaniel Dunbar //                     The LLVM Compiler Infrastructure
4d5a2a073SDaniel Dunbar //
5d5a2a073SDaniel Dunbar // This file is distributed under the University of Illinois Open Source
6d5a2a073SDaniel Dunbar // License. See LICENSE.TXT for details.
7d5a2a073SDaniel Dunbar //
8d5a2a073SDaniel Dunbar //===----------------------------------------------------------------------===//
9d5a2a073SDaniel Dunbar //
10d5a2a073SDaniel Dunbar // This file implements the Clang-C Source Indexing library hooks for
11d5a2a073SDaniel Dunbar // code completion.
12d5a2a073SDaniel Dunbar //
13d5a2a073SDaniel Dunbar //===----------------------------------------------------------------------===//
14d5a2a073SDaniel Dunbar 
15d5a2a073SDaniel Dunbar #include "CIndexer.h"
16cc0694c8SChandler Carruth #include "CIndexDiagnostic.h"
174b41745eSChandler Carruth #include "CLog.h"
1863745d59SDouglas Gregor #include "CXCursor.h"
195b8ad406STed Kremenek #include "CXString.h"
20cc0694c8SChandler Carruth #include "CXTranslationUnit.h"
2163745d59SDouglas Gregor #include "clang/AST/Decl.h"
2263745d59SDouglas Gregor #include "clang/AST/DeclObjC.h"
23cc0694c8SChandler Carruth #include "clang/AST/Type.h"
24d5a2a073SDaniel Dunbar #include "clang/Basic/FileManager.h"
25cc0694c8SChandler Carruth #include "clang/Basic/SourceManager.h"
268e984da8SDouglas Gregor #include "clang/Frontend/ASTUnit.h"
27d5a2a073SDaniel Dunbar #include "clang/Frontend/CompilerInstance.h"
28d5a2a073SDaniel Dunbar #include "clang/Frontend/FrontendDiagnostic.h"
29d5a2a073SDaniel Dunbar #include "clang/Sema/CodeCompleteConsumer.h"
300a4e61f8SDavid Blaikie #include "clang/Sema/Sema.h"
31028d3e4dSDouglas Gregor #include "llvm/ADT/SmallString.h"
32d5a2a073SDaniel Dunbar #include "llvm/ADT/StringExtras.h"
3377af1c56SDaniel Dunbar #include "llvm/Support/CrashRecoveryContext.h"
34b34c1fdfSRafael Espindola #include "llvm/Support/FileSystem.h"
35d5a2a073SDaniel Dunbar #include "llvm/Support/MemoryBuffer.h"
36cc0694c8SChandler Carruth #include "llvm/Support/Program.h"
37028d3e4dSDouglas Gregor #include "llvm/Support/Timer.h"
38028d3e4dSDouglas Gregor #include "llvm/Support/raw_ostream.h"
394527fb2fSBenjamin Kramer #include <atomic>
40d6009ffbSDouglas Gregor #include <cstdio>
41cc0694c8SChandler Carruth #include <cstdlib>
420b62f8a6SDmitri Gribenko #include <string>
43d5a2a073SDaniel Dunbar 
44028d3e4dSDouglas Gregor 
45d5a2a073SDaniel Dunbar #ifdef UDP_CODE_COMPLETION_LOGGER
46d5a2a073SDaniel Dunbar #include "clang/Basic/Version.h"
47d5a2a073SDaniel Dunbar #include <arpa/inet.h>
48d5a2a073SDaniel Dunbar #include <sys/socket.h>
49d5a2a073SDaniel Dunbar #include <sys/types.h>
50d5a2a073SDaniel Dunbar #include <unistd.h>
51d5a2a073SDaniel Dunbar #endif
52d5a2a073SDaniel Dunbar 
53d5a2a073SDaniel Dunbar using namespace clang;
54ea474358SArgyrios Kyrtzidis using namespace clang::cxindex;
55d5a2a073SDaniel Dunbar 
56d5a2a073SDaniel Dunbar extern "C" {
57d5a2a073SDaniel Dunbar 
58d5a2a073SDaniel Dunbar enum CXCompletionChunkKind
59d5a2a073SDaniel Dunbar clang_getCompletionChunkKind(CXCompletionString completion_string,
60d5a2a073SDaniel Dunbar                              unsigned chunk_number) {
61b278aafbSDouglas Gregor   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
62d5a2a073SDaniel Dunbar   if (!CCStr || chunk_number >= CCStr->size())
63d5a2a073SDaniel Dunbar     return CXCompletionChunk_Text;
64d5a2a073SDaniel Dunbar 
65d5a2a073SDaniel Dunbar   switch ((*CCStr)[chunk_number].Kind) {
66d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_TypedText:
67d5a2a073SDaniel Dunbar     return CXCompletionChunk_TypedText;
68d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Text:
69d5a2a073SDaniel Dunbar     return CXCompletionChunk_Text;
70d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Optional:
71d5a2a073SDaniel Dunbar     return CXCompletionChunk_Optional;
72d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Placeholder:
73d5a2a073SDaniel Dunbar     return CXCompletionChunk_Placeholder;
74d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Informative:
75d5a2a073SDaniel Dunbar     return CXCompletionChunk_Informative;
76d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_ResultType:
77d5a2a073SDaniel Dunbar     return CXCompletionChunk_ResultType;
78d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_CurrentParameter:
79d5a2a073SDaniel Dunbar     return CXCompletionChunk_CurrentParameter;
80d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftParen:
81d5a2a073SDaniel Dunbar     return CXCompletionChunk_LeftParen;
82d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightParen:
83d5a2a073SDaniel Dunbar     return CXCompletionChunk_RightParen;
84d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftBracket:
85d5a2a073SDaniel Dunbar     return CXCompletionChunk_LeftBracket;
86d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightBracket:
87d5a2a073SDaniel Dunbar     return CXCompletionChunk_RightBracket;
88d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftBrace:
89d5a2a073SDaniel Dunbar     return CXCompletionChunk_LeftBrace;
90d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightBrace:
91d5a2a073SDaniel Dunbar     return CXCompletionChunk_RightBrace;
92d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftAngle:
93d5a2a073SDaniel Dunbar     return CXCompletionChunk_LeftAngle;
94d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightAngle:
95d5a2a073SDaniel Dunbar     return CXCompletionChunk_RightAngle;
96d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Comma:
97d5a2a073SDaniel Dunbar     return CXCompletionChunk_Comma;
98d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Colon:
99d5a2a073SDaniel Dunbar     return CXCompletionChunk_Colon;
100d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_SemiColon:
101d5a2a073SDaniel Dunbar     return CXCompletionChunk_SemiColon;
102d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Equal:
103d5a2a073SDaniel Dunbar     return CXCompletionChunk_Equal;
104d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_HorizontalSpace:
105d5a2a073SDaniel Dunbar     return CXCompletionChunk_HorizontalSpace;
106d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_VerticalSpace:
107d5a2a073SDaniel Dunbar     return CXCompletionChunk_VerticalSpace;
108d5a2a073SDaniel Dunbar   }
109d5a2a073SDaniel Dunbar 
1108a40f700SDavid Blaikie   llvm_unreachable("Invalid CompletionKind!");
111d5a2a073SDaniel Dunbar }
112d5a2a073SDaniel Dunbar 
113d5a2a073SDaniel Dunbar CXString clang_getCompletionChunkText(CXCompletionString completion_string,
114d5a2a073SDaniel Dunbar                                       unsigned chunk_number) {
115b278aafbSDouglas Gregor   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
116d5a2a073SDaniel Dunbar   if (!CCStr || chunk_number >= CCStr->size())
117f98dfbaeSDmitri Gribenko     return cxstring::createNull();
118d5a2a073SDaniel Dunbar 
119d5a2a073SDaniel Dunbar   switch ((*CCStr)[chunk_number].Kind) {
120d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_TypedText:
121d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Text:
122d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Placeholder:
123d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_CurrentParameter:
124d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Informative:
125d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftParen:
126d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightParen:
127d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftBracket:
128d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightBracket:
129d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftBrace:
130d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightBrace:
131d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftAngle:
132d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightAngle:
133d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Comma:
134d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_ResultType:
135d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Colon:
136d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_SemiColon:
137d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Equal:
138d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_HorizontalSpace:
13909737ee8SDouglas Gregor   case CodeCompletionString::CK_VerticalSpace:
1403c66b0beSDmitri Gribenko     return cxstring::createRef((*CCStr)[chunk_number].Text);
14109737ee8SDouglas Gregor 
142d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Optional:
143d5a2a073SDaniel Dunbar     // Note: treated as an empty text block.
14436a6dd04SDmitri Gribenko     return cxstring::createEmpty();
145d5a2a073SDaniel Dunbar   }
146d5a2a073SDaniel Dunbar 
147e4d798f0SDavid Blaikie   llvm_unreachable("Invalid CodeCompletionString Kind!");
148d5a2a073SDaniel Dunbar }
149d5a2a073SDaniel Dunbar 
150d5a2a073SDaniel Dunbar 
151d5a2a073SDaniel Dunbar CXCompletionString
152d5a2a073SDaniel Dunbar clang_getCompletionChunkCompletionString(CXCompletionString completion_string,
153d5a2a073SDaniel Dunbar                                          unsigned chunk_number) {
154b278aafbSDouglas Gregor   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
155d5a2a073SDaniel Dunbar   if (!CCStr || chunk_number >= CCStr->size())
15669186e73SCraig Topper     return nullptr;
157d5a2a073SDaniel Dunbar 
158d5a2a073SDaniel Dunbar   switch ((*CCStr)[chunk_number].Kind) {
159d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_TypedText:
160d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Text:
161d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Placeholder:
162d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_CurrentParameter:
163d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Informative:
164d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftParen:
165d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightParen:
166d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftBracket:
167d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightBracket:
168d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftBrace:
169d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightBrace:
170d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftAngle:
171d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightAngle:
172d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Comma:
173d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_ResultType:
174d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Colon:
175d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_SemiColon:
176d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Equal:
177d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_HorizontalSpace:
178d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_VerticalSpace:
17969186e73SCraig Topper     return nullptr;
180d5a2a073SDaniel Dunbar 
181d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Optional:
182d5a2a073SDaniel Dunbar     // Note: treated as an empty text block.
183d5a2a073SDaniel Dunbar     return (*CCStr)[chunk_number].Optional;
184d5a2a073SDaniel Dunbar   }
185d5a2a073SDaniel Dunbar 
1868a40f700SDavid Blaikie   llvm_unreachable("Invalid CompletionKind!");
187d5a2a073SDaniel Dunbar }
188d5a2a073SDaniel Dunbar 
189d5a2a073SDaniel Dunbar unsigned clang_getNumCompletionChunks(CXCompletionString completion_string) {
190b278aafbSDouglas Gregor   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
191d5a2a073SDaniel Dunbar   return CCStr? CCStr->size() : 0;
192d5a2a073SDaniel Dunbar }
193d5a2a073SDaniel Dunbar 
194a2db793fSDouglas Gregor unsigned clang_getCompletionPriority(CXCompletionString completion_string) {
195b278aafbSDouglas Gregor   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
19647bb3e2bSBill Wendling   return CCStr? CCStr->getPriority() : unsigned(CCP_Unlikely);
197a2db793fSDouglas Gregor }
198a2db793fSDouglas Gregor 
199f757a12dSDouglas Gregor enum CXAvailabilityKind
200f757a12dSDouglas Gregor clang_getCompletionAvailability(CXCompletionString completion_string) {
201b278aafbSDouglas Gregor   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
202b278aafbSDouglas Gregor   return CCStr? static_cast<CXAvailabilityKind>(CCStr->getAvailability())
203b278aafbSDouglas Gregor               : CXAvailability_Available;
204f757a12dSDouglas Gregor }
205f757a12dSDouglas Gregor 
20698ea7f67SErik Verbruggen unsigned clang_getCompletionNumAnnotations(CXCompletionString completion_string)
20798ea7f67SErik Verbruggen {
20898ea7f67SErik Verbruggen   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
20998ea7f67SErik Verbruggen   return CCStr ? CCStr->getAnnotationCount() : 0;
21098ea7f67SErik Verbruggen }
21198ea7f67SErik Verbruggen 
21298ea7f67SErik Verbruggen CXString clang_getCompletionAnnotation(CXCompletionString completion_string,
21398ea7f67SErik Verbruggen                                        unsigned annotation_number) {
21498ea7f67SErik Verbruggen   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
2153c66b0beSDmitri Gribenko   return CCStr ? cxstring::createRef(CCStr->getAnnotation(annotation_number))
216f98dfbaeSDmitri Gribenko                : cxstring::createNull();
21798ea7f67SErik Verbruggen }
21898ea7f67SErik Verbruggen 
21978254c88SDouglas Gregor CXString
22078254c88SDouglas Gregor clang_getCompletionParent(CXCompletionString completion_string,
22178254c88SDouglas Gregor                           CXCursorKind *kind) {
22278254c88SDouglas Gregor   if (kind)
22378254c88SDouglas Gregor     *kind = CXCursor_NotImplemented;
22478254c88SDouglas Gregor 
22578254c88SDouglas Gregor   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
22678254c88SDouglas Gregor   if (!CCStr)
227f98dfbaeSDmitri Gribenko     return cxstring::createNull();
22878254c88SDouglas Gregor 
2292f23e9c5SDmitri Gribenko   return cxstring::createRef(CCStr->getParentContextName());
23078254c88SDouglas Gregor }
23198ea7f67SErik Verbruggen 
2323292d06aSDmitri Gribenko CXString
2333292d06aSDmitri Gribenko clang_getCompletionBriefComment(CXCompletionString completion_string) {
2343292d06aSDmitri Gribenko   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
2353292d06aSDmitri Gribenko 
2363292d06aSDmitri Gribenko   if (!CCStr)
237f98dfbaeSDmitri Gribenko     return cxstring::createNull();
2383292d06aSDmitri Gribenko 
2393c66b0beSDmitri Gribenko   return cxstring::createRef(CCStr->getBriefComment());
2403292d06aSDmitri Gribenko }
2413292d06aSDmitri Gribenko 
242ba4c85e5SBenjamin Kramer namespace {
2433292d06aSDmitri Gribenko 
244d5a2a073SDaniel Dunbar /// \brief The CXCodeCompleteResults structure we allocate internally;
245d5a2a073SDaniel Dunbar /// the client only sees the initial CXCodeCompleteResults structure.
2460b62f8a6SDmitri Gribenko ///
2470b62f8a6SDmitri Gribenko /// Normally, clients of CXString shouldn't care whether or not a CXString is
2480b62f8a6SDmitri Gribenko /// managed by a pool or by explicitly malloc'ed memory.  But
2490b62f8a6SDmitri Gribenko /// AllocatedCXCodeCompleteResults outlives the CXTranslationUnit, so we can
2500b62f8a6SDmitri Gribenko /// not rely on the StringPool in the TU.
251d5a2a073SDaniel Dunbar struct AllocatedCXCodeCompleteResults : public CXCodeCompleteResults {
2528832c066SBen Langmuir   AllocatedCXCodeCompleteResults(IntrusiveRefCntPtr<FileManager> FileMgr);
253d5a2a073SDaniel Dunbar   ~AllocatedCXCodeCompleteResults();
254d5a2a073SDaniel Dunbar 
255d5a2a073SDaniel Dunbar   /// \brief Diagnostics produced while performing code completion.
2560e62c1ccSChris Lattner   SmallVector<StoredDiagnostic, 8> Diagnostics;
257d5a2a073SDaniel Dunbar 
2587dd96c23SNico Weber   /// \brief Allocated API-exposed wrappters for Diagnostics.
2597dd96c23SNico Weber   SmallVector<CXStoredDiagnostic *, 8> DiagnosticsWrappers;
2607dd96c23SNico Weber 
261811db4eaSDouglas Gregor   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts;
262811db4eaSDouglas Gregor 
263d5a2a073SDaniel Dunbar   /// \brief Diag object
264c95d8192SDylan Noblesmith   IntrusiveRefCntPtr<DiagnosticsEngine> Diag;
265d5a2a073SDaniel Dunbar 
266d5a2a073SDaniel Dunbar   /// \brief Language options used to adjust source locations.
267d5a2a073SDaniel Dunbar   LangOptions LangOpts;
268d5a2a073SDaniel Dunbar 
269d5a2a073SDaniel Dunbar   /// \brief File manager, used for diagnostics.
270c95d8192SDylan Noblesmith   IntrusiveRefCntPtr<FileManager> FileMgr;
271d5a2a073SDaniel Dunbar 
27271731d6bSArgyrios Kyrtzidis   /// \brief Source manager, used for diagnostics.
273c95d8192SDylan Noblesmith   IntrusiveRefCntPtr<SourceManager> SourceMgr;
27471731d6bSArgyrios Kyrtzidis 
275d5a2a073SDaniel Dunbar   /// \brief Temporary files that should be removed once we have finished
276d5a2a073SDaniel Dunbar   /// with the code-completion results.
277b34c1fdfSRafael Espindola   std::vector<std::string> TemporaryFiles;
278d8a5dba9SDouglas Gregor 
2793f5a9efbSChris Lattner   /// \brief Temporary buffers that will be deleted once we have finished with
2803f5a9efbSChris Lattner   /// the code-completion results.
2810e62c1ccSChris Lattner   SmallVector<const llvm::MemoryBuffer *, 1> TemporaryBuffers;
282b278aafbSDouglas Gregor 
283162b712dSDouglas Gregor   /// \brief Allocator used to store globally cached code-completion results.
284c95d8192SDylan Noblesmith   IntrusiveRefCntPtr<clang::GlobalCodeCompletionAllocator>
285162b712dSDouglas Gregor     CachedCompletionAllocator;
286162b712dSDouglas Gregor 
287b278aafbSDouglas Gregor   /// \brief Allocator used to store code completion results.
2889d7c0fefSArgyrios Kyrtzidis   IntrusiveRefCntPtr<clang::GlobalCodeCompletionAllocator>
2899d7c0fefSArgyrios Kyrtzidis     CodeCompletionAllocator;
2902132584dSDouglas Gregor 
2912132584dSDouglas Gregor   /// \brief Context under which completion occurred.
2922132584dSDouglas Gregor   enum clang::CodeCompletionContext::Kind ContextKind;
2932132584dSDouglas Gregor 
2942132584dSDouglas Gregor   /// \brief A bitfield representing the acceptable completions for the
2952132584dSDouglas Gregor   /// current context.
2962132584dSDouglas Gregor   unsigned long long Contexts;
29763745d59SDouglas Gregor 
298ea777403SDouglas Gregor   /// \brief The kind of the container for the current context for completions.
29963745d59SDouglas Gregor   enum CXCursorKind ContainerKind;
3000b62f8a6SDmitri Gribenko 
301ea777403SDouglas Gregor   /// \brief The USR of the container for the current context for completions.
3020b62f8a6SDmitri Gribenko   std::string ContainerUSR;
3030b62f8a6SDmitri Gribenko 
304ea777403SDouglas Gregor   /// \brief a boolean value indicating whether there is complete information
305ea777403SDouglas Gregor   /// about the container
30663745d59SDouglas Gregor   unsigned ContainerIsIncomplete;
307ea777403SDouglas Gregor 
308ea777403SDouglas Gregor   /// \brief A string containing the Objective-C selector entered thus far for a
309ea777403SDouglas Gregor   /// message send.
310ea777403SDouglas Gregor   std::string Selector;
311d5a2a073SDaniel Dunbar };
312d5a2a073SDaniel Dunbar 
313ba4c85e5SBenjamin Kramer } // end anonymous namespace
314ba4c85e5SBenjamin Kramer 
31568dbaeadSDouglas Gregor /// \brief Tracks the number of code-completion result objects that are
31668dbaeadSDouglas Gregor /// currently active.
31768dbaeadSDouglas Gregor ///
31868dbaeadSDouglas Gregor /// Used for debugging purposes only.
3194527fb2fSBenjamin Kramer static std::atomic<unsigned> CodeCompletionResultObjects;
32068dbaeadSDouglas Gregor 
321c30dcecbSAnders Carlsson AllocatedCXCodeCompleteResults::AllocatedCXCodeCompleteResults(
3228832c066SBen Langmuir     IntrusiveRefCntPtr<FileManager> FileMgr)
323d0040648SArgyrios Kyrtzidis     : CXCodeCompleteResults(),
324811db4eaSDouglas Gregor       DiagOpts(new DiagnosticOptions),
3259c902b55SDavid Blaikie       Diag(new DiagnosticsEngine(
3268832c066SBen Langmuir           IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), &*DiagOpts)),
3278832c066SBen Langmuir       FileMgr(FileMgr), SourceMgr(new SourceManager(*Diag, *FileMgr)),
3289d7c0fefSArgyrios Kyrtzidis       CodeCompletionAllocator(new clang::GlobalCodeCompletionAllocator),
329e442fe3dSDouglas Gregor       Contexts(CXCompletionContext_Unknown),
3308832c066SBen Langmuir       ContainerKind(CXCursor_InvalidCode), ContainerIsIncomplete(1) {
3314527fb2fSBenjamin Kramer   if (getenv("LIBCLANG_OBJTRACKING"))
3324527fb2fSBenjamin Kramer     fprintf(stderr, "+++ %u completion results\n",
3334527fb2fSBenjamin Kramer             ++CodeCompletionResultObjects);
33468dbaeadSDouglas Gregor }
335d5a2a073SDaniel Dunbar 
336d5a2a073SDaniel Dunbar AllocatedCXCodeCompleteResults::~AllocatedCXCodeCompleteResults() {
3377dd96c23SNico Weber   llvm::DeleteContainerPointers(DiagnosticsWrappers);
338d5a2a073SDaniel Dunbar   delete [] Results;
339d5a2a073SDaniel Dunbar 
340d5a2a073SDaniel Dunbar   for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
341b34c1fdfSRafael Espindola     llvm::sys::fs::remove(TemporaryFiles[I]);
342d8a5dba9SDouglas Gregor   for (unsigned I = 0, N = TemporaryBuffers.size(); I != N; ++I)
343d8a5dba9SDouglas Gregor     delete TemporaryBuffers[I];
34468dbaeadSDouglas Gregor 
3454527fb2fSBenjamin Kramer   if (getenv("LIBCLANG_OBJTRACKING"))
3464527fb2fSBenjamin Kramer     fprintf(stderr, "--- %u completion results\n",
3474527fb2fSBenjamin Kramer             --CodeCompletionResultObjects);
348d5a2a073SDaniel Dunbar }
349d5a2a073SDaniel Dunbar 
3508e984da8SDouglas Gregor } // end extern "C"
3518e984da8SDouglas Gregor 
3522132584dSDouglas Gregor static unsigned long long getContextsForContextKind(
3532132584dSDouglas Gregor                                           enum CodeCompletionContext::Kind kind,
3542132584dSDouglas Gregor                                                     Sema &S) {
3552132584dSDouglas Gregor   unsigned long long contexts = 0;
3562132584dSDouglas Gregor   switch (kind) {
3572132584dSDouglas Gregor     case CodeCompletionContext::CCC_OtherWithMacros: {
3582132584dSDouglas Gregor       //We can allow macros here, but we don't know what else is permissible
3592132584dSDouglas Gregor       //So we'll say the only thing permissible are macros
3602132584dSDouglas Gregor       contexts = CXCompletionContext_MacroName;
3612132584dSDouglas Gregor       break;
3622132584dSDouglas Gregor     }
3632132584dSDouglas Gregor     case CodeCompletionContext::CCC_TopLevel:
3642132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCIvarList:
3652132584dSDouglas Gregor     case CodeCompletionContext::CCC_ClassStructUnion:
3662132584dSDouglas Gregor     case CodeCompletionContext::CCC_Type: {
3672132584dSDouglas Gregor       contexts = CXCompletionContext_AnyType |
3682132584dSDouglas Gregor                  CXCompletionContext_ObjCInterface;
369bbafb8a7SDavid Blaikie       if (S.getLangOpts().CPlusPlus) {
3702132584dSDouglas Gregor         contexts |= CXCompletionContext_EnumTag |
3712132584dSDouglas Gregor                     CXCompletionContext_UnionTag |
3722132584dSDouglas Gregor                     CXCompletionContext_StructTag |
3732132584dSDouglas Gregor                     CXCompletionContext_ClassTag |
3742132584dSDouglas Gregor                     CXCompletionContext_NestedNameSpecifier;
3752132584dSDouglas Gregor       }
3762132584dSDouglas Gregor       break;
3772132584dSDouglas Gregor     }
3782132584dSDouglas Gregor     case CodeCompletionContext::CCC_Statement: {
3792132584dSDouglas Gregor       contexts = CXCompletionContext_AnyType |
3802132584dSDouglas Gregor                  CXCompletionContext_ObjCInterface |
3812132584dSDouglas Gregor                  CXCompletionContext_AnyValue;
382bbafb8a7SDavid Blaikie       if (S.getLangOpts().CPlusPlus) {
3832132584dSDouglas Gregor         contexts |= CXCompletionContext_EnumTag |
3842132584dSDouglas Gregor                     CXCompletionContext_UnionTag |
3852132584dSDouglas Gregor                     CXCompletionContext_StructTag |
3862132584dSDouglas Gregor                     CXCompletionContext_ClassTag |
3872132584dSDouglas Gregor                     CXCompletionContext_NestedNameSpecifier;
3882132584dSDouglas Gregor       }
3892132584dSDouglas Gregor       break;
3902132584dSDouglas Gregor     }
3912132584dSDouglas Gregor     case CodeCompletionContext::CCC_Expression: {
3922132584dSDouglas Gregor       contexts = CXCompletionContext_AnyValue;
393bbafb8a7SDavid Blaikie       if (S.getLangOpts().CPlusPlus) {
3942132584dSDouglas Gregor         contexts |= CXCompletionContext_AnyType |
3952132584dSDouglas Gregor                     CXCompletionContext_ObjCInterface |
3962132584dSDouglas Gregor                     CXCompletionContext_EnumTag |
3972132584dSDouglas Gregor                     CXCompletionContext_UnionTag |
3982132584dSDouglas Gregor                     CXCompletionContext_StructTag |
3992132584dSDouglas Gregor                     CXCompletionContext_ClassTag |
4002132584dSDouglas Gregor                     CXCompletionContext_NestedNameSpecifier;
4012132584dSDouglas Gregor       }
4022132584dSDouglas Gregor       break;
4032132584dSDouglas Gregor     }
4042132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCMessageReceiver: {
4052132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCObjectValue |
4062132584dSDouglas Gregor                  CXCompletionContext_ObjCSelectorValue |
4072132584dSDouglas Gregor                  CXCompletionContext_ObjCInterface;
408bbafb8a7SDavid Blaikie       if (S.getLangOpts().CPlusPlus) {
4092132584dSDouglas Gregor         contexts |= CXCompletionContext_CXXClassTypeValue |
4102132584dSDouglas Gregor                     CXCompletionContext_AnyType |
4112132584dSDouglas Gregor                     CXCompletionContext_EnumTag |
4122132584dSDouglas Gregor                     CXCompletionContext_UnionTag |
4132132584dSDouglas Gregor                     CXCompletionContext_StructTag |
4142132584dSDouglas Gregor                     CXCompletionContext_ClassTag |
4152132584dSDouglas Gregor                     CXCompletionContext_NestedNameSpecifier;
4162132584dSDouglas Gregor       }
4172132584dSDouglas Gregor       break;
4182132584dSDouglas Gregor     }
4192132584dSDouglas Gregor     case CodeCompletionContext::CCC_DotMemberAccess: {
4202132584dSDouglas Gregor       contexts = CXCompletionContext_DotMemberAccess;
4212132584dSDouglas Gregor       break;
4222132584dSDouglas Gregor     }
4232132584dSDouglas Gregor     case CodeCompletionContext::CCC_ArrowMemberAccess: {
4242132584dSDouglas Gregor       contexts = CXCompletionContext_ArrowMemberAccess;
4252132584dSDouglas Gregor       break;
4262132584dSDouglas Gregor     }
4272132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCPropertyAccess: {
4282132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCPropertyAccess;
4292132584dSDouglas Gregor       break;
4302132584dSDouglas Gregor     }
4312132584dSDouglas Gregor     case CodeCompletionContext::CCC_EnumTag: {
4322132584dSDouglas Gregor       contexts = CXCompletionContext_EnumTag |
4332132584dSDouglas Gregor                  CXCompletionContext_NestedNameSpecifier;
4342132584dSDouglas Gregor       break;
4352132584dSDouglas Gregor     }
4362132584dSDouglas Gregor     case CodeCompletionContext::CCC_UnionTag: {
4372132584dSDouglas Gregor       contexts = CXCompletionContext_UnionTag |
4382132584dSDouglas Gregor                  CXCompletionContext_NestedNameSpecifier;
4392132584dSDouglas Gregor       break;
4402132584dSDouglas Gregor     }
4412132584dSDouglas Gregor     case CodeCompletionContext::CCC_ClassOrStructTag: {
4422132584dSDouglas Gregor       contexts = CXCompletionContext_StructTag |
4432132584dSDouglas Gregor                  CXCompletionContext_ClassTag |
4442132584dSDouglas Gregor                  CXCompletionContext_NestedNameSpecifier;
4452132584dSDouglas Gregor       break;
4462132584dSDouglas Gregor     }
4472132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCProtocolName: {
4482132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCProtocol;
4492132584dSDouglas Gregor       break;
4502132584dSDouglas Gregor     }
4512132584dSDouglas Gregor     case CodeCompletionContext::CCC_Namespace: {
4522132584dSDouglas Gregor       contexts = CXCompletionContext_Namespace;
4532132584dSDouglas Gregor       break;
4542132584dSDouglas Gregor     }
4552132584dSDouglas Gregor     case CodeCompletionContext::CCC_PotentiallyQualifiedName: {
4562132584dSDouglas Gregor       contexts = CXCompletionContext_NestedNameSpecifier;
4572132584dSDouglas Gregor       break;
4582132584dSDouglas Gregor     }
4592132584dSDouglas Gregor     case CodeCompletionContext::CCC_MacroNameUse: {
4602132584dSDouglas Gregor       contexts = CXCompletionContext_MacroName;
4612132584dSDouglas Gregor       break;
4622132584dSDouglas Gregor     }
4632132584dSDouglas Gregor     case CodeCompletionContext::CCC_NaturalLanguage: {
4642132584dSDouglas Gregor       contexts = CXCompletionContext_NaturalLanguage;
4652132584dSDouglas Gregor       break;
4662132584dSDouglas Gregor     }
4672132584dSDouglas Gregor     case CodeCompletionContext::CCC_SelectorName: {
4682132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCSelectorName;
4692132584dSDouglas Gregor       break;
4702132584dSDouglas Gregor     }
4712132584dSDouglas Gregor     case CodeCompletionContext::CCC_ParenthesizedExpression: {
4722132584dSDouglas Gregor       contexts = CXCompletionContext_AnyType |
4732132584dSDouglas Gregor                  CXCompletionContext_ObjCInterface |
4742132584dSDouglas Gregor                  CXCompletionContext_AnyValue;
475bbafb8a7SDavid Blaikie       if (S.getLangOpts().CPlusPlus) {
4762132584dSDouglas Gregor         contexts |= CXCompletionContext_EnumTag |
4772132584dSDouglas Gregor                     CXCompletionContext_UnionTag |
4782132584dSDouglas Gregor                     CXCompletionContext_StructTag |
4792132584dSDouglas Gregor                     CXCompletionContext_ClassTag |
4802132584dSDouglas Gregor                     CXCompletionContext_NestedNameSpecifier;
4812132584dSDouglas Gregor       }
4822132584dSDouglas Gregor       break;
4832132584dSDouglas Gregor     }
4842132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCInstanceMessage: {
4852132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCInstanceMessage;
4862132584dSDouglas Gregor       break;
4872132584dSDouglas Gregor     }
4882132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCClassMessage: {
4892132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCClassMessage;
4902132584dSDouglas Gregor       break;
4912132584dSDouglas Gregor     }
4922c595adfSDouglas Gregor     case CodeCompletionContext::CCC_ObjCInterfaceName: {
4932132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCInterface;
4942132584dSDouglas Gregor       break;
4952132584dSDouglas Gregor     }
4962132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCCategoryName: {
4972132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCCategory;
4982132584dSDouglas Gregor       break;
4992132584dSDouglas Gregor     }
5002132584dSDouglas Gregor     case CodeCompletionContext::CCC_Other:
5012132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCInterface:
5022132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCImplementation:
5032132584dSDouglas Gregor     case CodeCompletionContext::CCC_Name:
5042132584dSDouglas Gregor     case CodeCompletionContext::CCC_MacroName:
5052132584dSDouglas Gregor     case CodeCompletionContext::CCC_PreprocessorExpression:
5062132584dSDouglas Gregor     case CodeCompletionContext::CCC_PreprocessorDirective:
5072132584dSDouglas Gregor     case CodeCompletionContext::CCC_TypeQualifiers: {
5082132584dSDouglas Gregor       //Only Clang results should be accepted, so we'll set all of the other
5092132584dSDouglas Gregor       //context bits to 0 (i.e. the empty set)
5102132584dSDouglas Gregor       contexts = CXCompletionContext_Unexposed;
5112132584dSDouglas Gregor       break;
5122132584dSDouglas Gregor     }
5132132584dSDouglas Gregor     case CodeCompletionContext::CCC_Recovery: {
5142132584dSDouglas Gregor       //We don't know what the current context is, so we'll return unknown
5152132584dSDouglas Gregor       //This is the equivalent of setting all of the other context bits
5162132584dSDouglas Gregor       contexts = CXCompletionContext_Unknown;
5172132584dSDouglas Gregor       break;
5182132584dSDouglas Gregor     }
5192132584dSDouglas Gregor   }
5202132584dSDouglas Gregor   return contexts;
5212132584dSDouglas Gregor }
5222132584dSDouglas Gregor 
5238e984da8SDouglas Gregor namespace {
5248e984da8SDouglas Gregor   class CaptureCompletionResults : public CodeCompleteConsumer {
5258e984da8SDouglas Gregor     AllocatedCXCodeCompleteResults &AllocatedResults;
5269d7c0fefSArgyrios Kyrtzidis     CodeCompletionTUInfo CCTUInfo;
5270e62c1ccSChris Lattner     SmallVector<CXCompletionResult, 16> StoredResults;
52863745d59SDouglas Gregor     CXTranslationUnit *TU;
5298e984da8SDouglas Gregor   public:
5303292d06aSDmitri Gribenko     CaptureCompletionResults(const CodeCompleteOptions &Opts,
5313292d06aSDmitri Gribenko                              AllocatedCXCodeCompleteResults &Results,
53263745d59SDouglas Gregor                              CXTranslationUnit *TranslationUnit)
5333292d06aSDmitri Gribenko       : CodeCompleteConsumer(Opts, false),
5349d7c0fefSArgyrios Kyrtzidis         AllocatedResults(Results), CCTUInfo(Results.CodeCompletionAllocator),
5359d7c0fefSArgyrios Kyrtzidis         TU(TranslationUnit) { }
53636e3b5c7SDouglas Gregor     ~CaptureCompletionResults() { Finish(); }
5378e984da8SDouglas Gregor 
53836835568SCraig Topper     void ProcessCodeCompleteResults(Sema &S,
53900c37ef0SDouglas Gregor                                     CodeCompletionContext Context,
540276321a9SJohn McCall                                     CodeCompletionResult *Results,
54136835568SCraig Topper                                     unsigned NumResults) override {
54236e3b5c7SDouglas Gregor       StoredResults.reserve(StoredResults.size() + NumResults);
5438e984da8SDouglas Gregor       for (unsigned I = 0; I != NumResults; ++I) {
544b278aafbSDouglas Gregor         CodeCompletionString *StoredCompletion
5459d7c0fefSArgyrios Kyrtzidis           = Results[I].CreateCodeCompletionString(S, getAllocator(),
5463292d06aSDmitri Gribenko                                                   getCodeCompletionTUInfo(),
5473292d06aSDmitri Gribenko                                                   includeBriefComments());
54836e3b5c7SDouglas Gregor 
54936e3b5c7SDouglas Gregor         CXCompletionResult R;
55036e3b5c7SDouglas Gregor         R.CursorKind = Results[I].CursorKind;
55136e3b5c7SDouglas Gregor         R.CompletionString = StoredCompletion;
55236e3b5c7SDouglas Gregor         StoredResults.push_back(R);
5538e984da8SDouglas Gregor       }
5542132584dSDouglas Gregor 
55563745d59SDouglas Gregor       enum CodeCompletionContext::Kind contextKind = Context.getKind();
5562132584dSDouglas Gregor 
55763745d59SDouglas Gregor       AllocatedResults.ContextKind = contextKind;
55863745d59SDouglas Gregor       AllocatedResults.Contexts = getContextsForContextKind(contextKind, S);
55963745d59SDouglas Gregor 
560ea777403SDouglas Gregor       AllocatedResults.Selector = "";
5613f31bd18SDmitri Gribenko       ArrayRef<IdentifierInfo *> SelIdents = Context.getSelIdents();
5623f31bd18SDmitri Gribenko       for (ArrayRef<IdentifierInfo *>::iterator I = SelIdents.begin(),
5633f31bd18SDmitri Gribenko                                                 E = SelIdents.end();
5643f31bd18SDmitri Gribenko            I != E; ++I) {
5653f31bd18SDmitri Gribenko         if (IdentifierInfo *selIdent = *I)
5663f31bd18SDmitri Gribenko           AllocatedResults.Selector += selIdent->getName();
567ea777403SDouglas Gregor         AllocatedResults.Selector += ":";
568ea777403SDouglas Gregor       }
569ea777403SDouglas Gregor 
57063745d59SDouglas Gregor       QualType baseType = Context.getBaseType();
57169186e73SCraig Topper       NamedDecl *D = nullptr;
57263745d59SDouglas Gregor 
57363745d59SDouglas Gregor       if (!baseType.isNull()) {
57463745d59SDouglas Gregor         // Get the declaration for a class/struct/union/enum type
57563745d59SDouglas Gregor         if (const TagType *Tag = baseType->getAs<TagType>())
57663745d59SDouglas Gregor           D = Tag->getDecl();
57763745d59SDouglas Gregor         // Get the @interface declaration for a (possibly-qualified) Objective-C
57863745d59SDouglas Gregor         // object pointer type, e.g., NSString*
57963745d59SDouglas Gregor         else if (const ObjCObjectPointerType *ObjPtr =
58063745d59SDouglas Gregor                  baseType->getAs<ObjCObjectPointerType>())
58163745d59SDouglas Gregor           D = ObjPtr->getInterfaceDecl();
58263745d59SDouglas Gregor         // Get the @interface declaration for an Objective-C object type
58363745d59SDouglas Gregor         else if (const ObjCObjectType *Obj = baseType->getAs<ObjCObjectType>())
58463745d59SDouglas Gregor           D = Obj->getInterface();
58563745d59SDouglas Gregor         // Get the class for a C++ injected-class-name
58663745d59SDouglas Gregor         else if (const InjectedClassNameType *Injected =
58763745d59SDouglas Gregor                  baseType->getAs<InjectedClassNameType>())
58863745d59SDouglas Gregor           D = Injected->getDecl();
58963745d59SDouglas Gregor       }
59063745d59SDouglas Gregor 
59169186e73SCraig Topper       if (D != nullptr) {
59263745d59SDouglas Gregor         CXCursor cursor = cxcursor::MakeCXCursor(D, *TU);
59363745d59SDouglas Gregor 
5940b62f8a6SDmitri Gribenko         AllocatedResults.ContainerKind = clang_getCursorKind(cursor);
59563745d59SDouglas Gregor 
5960b62f8a6SDmitri Gribenko         CXString CursorUSR = clang_getCursorUSR(cursor);
5970b62f8a6SDmitri Gribenko         AllocatedResults.ContainerUSR = clang_getCString(CursorUSR);
5980b62f8a6SDmitri Gribenko         clang_disposeString(CursorUSR);
5995b8ad406STed Kremenek 
60063745d59SDouglas Gregor         const Type *type = baseType.getTypePtrOrNull();
60169186e73SCraig Topper         if (type) {
60263745d59SDouglas Gregor           AllocatedResults.ContainerIsIncomplete = type->isIncompleteType();
60363745d59SDouglas Gregor         }
60463745d59SDouglas Gregor         else {
60563745d59SDouglas Gregor           AllocatedResults.ContainerIsIncomplete = 1;
60663745d59SDouglas Gregor         }
60763745d59SDouglas Gregor       }
60863745d59SDouglas Gregor       else {
60963745d59SDouglas Gregor         AllocatedResults.ContainerKind = CXCursor_InvalidCode;
6100b62f8a6SDmitri Gribenko         AllocatedResults.ContainerUSR.clear();
61163745d59SDouglas Gregor         AllocatedResults.ContainerIsIncomplete = 1;
61263745d59SDouglas Gregor       }
6138e984da8SDouglas Gregor     }
61449f67ce4SDouglas Gregor 
61536835568SCraig Topper     void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
61636e3b5c7SDouglas Gregor                                    OverloadCandidate *Candidates,
61736835568SCraig Topper                                    unsigned NumCandidates) override {
61836e3b5c7SDouglas Gregor       StoredResults.reserve(StoredResults.size() + NumCandidates);
61936e3b5c7SDouglas Gregor       for (unsigned I = 0; I != NumCandidates; ++I) {
620b278aafbSDouglas Gregor         CodeCompletionString *StoredCompletion
6219d7c0fefSArgyrios Kyrtzidis           = Candidates[I].CreateSignatureString(CurrentArg, S, getAllocator(),
6229d7c0fefSArgyrios Kyrtzidis                                                 getCodeCompletionTUInfo());
62336e3b5c7SDouglas Gregor 
62436e3b5c7SDouglas Gregor         CXCompletionResult R;
625*975a9f6eSFrancisco Lopes da Silva         R.CursorKind = CXCursor_OverloadCandidate;
62636e3b5c7SDouglas Gregor         R.CompletionString = StoredCompletion;
62736e3b5c7SDouglas Gregor         StoredResults.push_back(R);
62836e3b5c7SDouglas Gregor       }
62936e3b5c7SDouglas Gregor     }
63036e3b5c7SDouglas Gregor 
63136835568SCraig Topper     CodeCompletionAllocator &getAllocator() override {
6329d7c0fefSArgyrios Kyrtzidis       return *AllocatedResults.CodeCompletionAllocator;
633b278aafbSDouglas Gregor     }
634b278aafbSDouglas Gregor 
63536835568SCraig Topper     CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo;}
6369d7c0fefSArgyrios Kyrtzidis 
63736e3b5c7SDouglas Gregor   private:
63836e3b5c7SDouglas Gregor     void Finish() {
63936e3b5c7SDouglas Gregor       AllocatedResults.Results = new CXCompletionResult [StoredResults.size()];
64036e3b5c7SDouglas Gregor       AllocatedResults.NumResults = StoredResults.size();
64136e3b5c7SDouglas Gregor       std::memcpy(AllocatedResults.Results, StoredResults.data(),
64236e3b5c7SDouglas Gregor                   StoredResults.size() * sizeof(CXCompletionResult));
64336e3b5c7SDouglas Gregor       StoredResults.clear();
64436e3b5c7SDouglas Gregor     }
6458e984da8SDouglas Gregor   };
6468e984da8SDouglas Gregor }
6478e984da8SDouglas Gregor 
6488e984da8SDouglas Gregor extern "C" {
64977af1c56SDaniel Dunbar struct CodeCompleteAtInfo {
65077af1c56SDaniel Dunbar   CXTranslationUnit TU;
65177af1c56SDaniel Dunbar   const char *complete_filename;
65277af1c56SDaniel Dunbar   unsigned complete_line;
65377af1c56SDaniel Dunbar   unsigned complete_column;
6549d85b18fSAlp Toker   ArrayRef<CXUnsavedFile> unsaved_files;
65577af1c56SDaniel Dunbar   unsigned options;
65677af1c56SDaniel Dunbar   CXCodeCompleteResults *result;
65777af1c56SDaniel Dunbar };
65877af1c56SDaniel Dunbar void clang_codeCompleteAt_Impl(void *UserData) {
65977af1c56SDaniel Dunbar   CodeCompleteAtInfo *CCAI = static_cast<CodeCompleteAtInfo*>(UserData);
66077af1c56SDaniel Dunbar   CXTranslationUnit TU = CCAI->TU;
66177af1c56SDaniel Dunbar   const char *complete_filename = CCAI->complete_filename;
66277af1c56SDaniel Dunbar   unsigned complete_line = CCAI->complete_line;
66377af1c56SDaniel Dunbar   unsigned complete_column = CCAI->complete_column;
66477af1c56SDaniel Dunbar   unsigned options = CCAI->options;
6653292d06aSDmitri Gribenko   bool IncludeBriefComments = options & CXCodeComplete_IncludeBriefComments;
66669186e73SCraig Topper   CCAI->result = nullptr;
66777af1c56SDaniel Dunbar 
6688e984da8SDouglas Gregor #ifdef UDP_CODE_COMPLETION_LOGGER
6698e984da8SDouglas Gregor #ifdef UDP_CODE_COMPLETION_LOGGER_PORT
6708e984da8SDouglas Gregor   const llvm::TimeRecord &StartTime =  llvm::TimeRecord::getCurrentTime();
6718e984da8SDouglas Gregor #endif
6728e984da8SDouglas Gregor #endif
6738e984da8SDouglas Gregor 
67469186e73SCraig Topper   bool EnableLogging = getenv("LIBCLANG_CODE_COMPLETION_LOGGING") != nullptr;
6758e984da8SDouglas Gregor 
676852d622eSDmitri Gribenko   if (cxtu::isNotUsableTU(TU)) {
677256454fdSDmitri Gribenko     LOG_BAD_TU(TU);
678256454fdSDmitri Gribenko     return;
679256454fdSDmitri Gribenko   }
680256454fdSDmitri Gribenko 
681c22ea1ceSDmitri Gribenko   ASTUnit *AST = cxtu::getASTUnit(TU);
6828e984da8SDouglas Gregor   if (!AST)
68377af1c56SDaniel Dunbar     return;
6848e984da8SDouglas Gregor 
685183436e5SDmitri Gribenko   CIndexer *CXXIdx = TU->CIdx;
6867317a5cbSArgyrios Kyrtzidis   if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
68758d5f3fdSArgyrios Kyrtzidis     setThreadBackgroundPriority();
6887317a5cbSArgyrios Kyrtzidis 
689ca5b0539SDouglas Gregor   ASTUnit::ConcurrencyCheck Check(*AST);
690ca5b0539SDouglas Gregor 
6918e984da8SDouglas Gregor   // Perform the remapping of source files.
6920e62c1ccSChris Lattner   SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
6939d85b18fSAlp Toker 
6949d85b18fSAlp Toker   for (auto &UF : CCAI->unsaved_files) {
695d87f8d76SRafael Espindola     std::unique_ptr<llvm::MemoryBuffer> MB =
6969d85b18fSAlp Toker         llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
697d87f8d76SRafael Espindola     RemappedFiles.push_back(std::make_pair(UF.Filename, MB.release()));
6988e984da8SDouglas Gregor   }
6998e984da8SDouglas Gregor 
7008e984da8SDouglas Gregor   if (EnableLogging) {
7018e984da8SDouglas Gregor     // FIXME: Add logging.
7028e984da8SDouglas Gregor   }
7038e984da8SDouglas Gregor 
7048e984da8SDouglas Gregor   // Parse the resulting source file to find code-completion results.
7058832c066SBen Langmuir   AllocatedCXCodeCompleteResults *Results = new AllocatedCXCodeCompleteResults(
7068832c066SBen Langmuir       &AST->getFileManager());
70769186e73SCraig Topper   Results->Results = nullptr;
7088e984da8SDouglas Gregor   Results->NumResults = 0;
7098e984da8SDouglas Gregor 
7108e984da8SDouglas Gregor   // Create a code-completion consumer to capture the results.
7113292d06aSDmitri Gribenko   CodeCompleteOptions Opts;
7123292d06aSDmitri Gribenko   Opts.IncludeBriefComments = IncludeBriefComments;
7133292d06aSDmitri Gribenko   CaptureCompletionResults Capture(Opts, *Results, &TU);
7148e984da8SDouglas Gregor 
7158e984da8SDouglas Gregor   // Perform completion.
7168e984da8SDouglas Gregor   AST->CodeComplete(complete_filename, complete_line, complete_column,
7172febd212SDmitri Gribenko                     RemappedFiles,
718b68bc59aSDouglas Gregor                     (options & CXCodeComplete_IncludeMacros),
719b68bc59aSDouglas Gregor                     (options & CXCodeComplete_IncludeCodePatterns),
7203292d06aSDmitri Gribenko                     IncludeBriefComments,
721b68bc59aSDouglas Gregor                     Capture,
7225e14d39aSTed Kremenek                     *Results->Diag, Results->LangOpts, *Results->SourceMgr,
7235e14d39aSTed Kremenek                     *Results->FileMgr, Results->Diagnostics,
724b97b666cSDouglas Gregor                     Results->TemporaryBuffers);
7258e984da8SDouglas Gregor 
7267dd96c23SNico Weber   Results->DiagnosticsWrappers.resize(Results->Diagnostics.size());
7277dd96c23SNico Weber 
728162b712dSDouglas Gregor   // Keep a reference to the allocator used for cached global completions, so
729162b712dSDouglas Gregor   // that we can be sure that the memory used by our code completion strings
730162b712dSDouglas Gregor   // doesn't get freed due to subsequent reparses (while the code completion
731162b712dSDouglas Gregor   // results are still active).
732162b712dSDouglas Gregor   Results->CachedCompletionAllocator = AST->getCachedCompletionAllocator();
733162b712dSDouglas Gregor 
7348e984da8SDouglas Gregor 
7358e984da8SDouglas Gregor 
7368e984da8SDouglas Gregor #ifdef UDP_CODE_COMPLETION_LOGGER
7378e984da8SDouglas Gregor #ifdef UDP_CODE_COMPLETION_LOGGER_PORT
7388e984da8SDouglas Gregor   const llvm::TimeRecord &EndTime =  llvm::TimeRecord::getCurrentTime();
739f1a13f29SDylan Noblesmith   SmallString<256> LogResult;
7408e984da8SDouglas Gregor   llvm::raw_svector_ostream os(LogResult);
7418e984da8SDouglas Gregor 
7428e984da8SDouglas Gregor   // Figure out the language and whether or not it uses PCH.
7438e984da8SDouglas Gregor   const char *lang = 0;
7448e984da8SDouglas Gregor   bool usesPCH = false;
7458e984da8SDouglas Gregor 
7468e984da8SDouglas Gregor   for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
7478e984da8SDouglas Gregor        I != E; ++I) {
7488e984da8SDouglas Gregor     if (*I == 0)
7498e984da8SDouglas Gregor       continue;
7508e984da8SDouglas Gregor     if (strcmp(*I, "-x") == 0) {
7518e984da8SDouglas Gregor       if (I + 1 != E) {
7528e984da8SDouglas Gregor         lang = *(++I);
7538e984da8SDouglas Gregor         continue;
7548e984da8SDouglas Gregor       }
7558e984da8SDouglas Gregor     }
7568e984da8SDouglas Gregor     else if (strcmp(*I, "-include") == 0) {
7578e984da8SDouglas Gregor       if (I+1 != E) {
7588e984da8SDouglas Gregor         const char *arg = *(++I);
759f1a13f29SDylan Noblesmith         SmallString<512> pchName;
7608e984da8SDouglas Gregor         {
7618e984da8SDouglas Gregor           llvm::raw_svector_ostream os(pchName);
7628e984da8SDouglas Gregor           os << arg << ".pth";
7638e984da8SDouglas Gregor         }
7648e984da8SDouglas Gregor         pchName.push_back('\0');
7658e984da8SDouglas Gregor         struct stat stat_results;
766ea777403SDouglas Gregor         if (stat(pchName.str().c_str(), &stat_results) == 0)
7678e984da8SDouglas Gregor           usesPCH = true;
7688e984da8SDouglas Gregor         continue;
7698e984da8SDouglas Gregor       }
7708e984da8SDouglas Gregor     }
7718e984da8SDouglas Gregor   }
7728e984da8SDouglas Gregor 
7738e984da8SDouglas Gregor   os << "{ ";
7748e984da8SDouglas Gregor   os << "\"wall\": " << (EndTime.getWallTime() - StartTime.getWallTime());
7758e984da8SDouglas Gregor   os << ", \"numRes\": " << Results->NumResults;
7768e984da8SDouglas Gregor   os << ", \"diags\": " << Results->Diagnostics.size();
7778e984da8SDouglas Gregor   os << ", \"pch\": " << (usesPCH ? "true" : "false");
7788e984da8SDouglas Gregor   os << ", \"lang\": \"" << (lang ? lang : "<unknown>") << '"';
7798e984da8SDouglas Gregor   const char *name = getlogin();
7808e984da8SDouglas Gregor   os << ", \"user\": \"" << (name ? name : "unknown") << '"';
7818e984da8SDouglas Gregor   os << ", \"clangVer\": \"" << getClangFullVersion() << '"';
7828e984da8SDouglas Gregor   os << " }";
7838e984da8SDouglas Gregor 
7840e62c1ccSChris Lattner   StringRef res = os.str();
7858e984da8SDouglas Gregor   if (res.size() > 0) {
7868e984da8SDouglas Gregor     do {
7878e984da8SDouglas Gregor       // Setup the UDP socket.
7888e984da8SDouglas Gregor       struct sockaddr_in servaddr;
7898e984da8SDouglas Gregor       bzero(&servaddr, sizeof(servaddr));
7908e984da8SDouglas Gregor       servaddr.sin_family = AF_INET;
7918e984da8SDouglas Gregor       servaddr.sin_port = htons(UDP_CODE_COMPLETION_LOGGER_PORT);
7928e984da8SDouglas Gregor       if (inet_pton(AF_INET, UDP_CODE_COMPLETION_LOGGER,
7938e984da8SDouglas Gregor                     &servaddr.sin_addr) <= 0)
7948e984da8SDouglas Gregor         break;
7958e984da8SDouglas Gregor 
7968e984da8SDouglas Gregor       int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
7978e984da8SDouglas Gregor       if (sockfd < 0)
7988e984da8SDouglas Gregor         break;
7998e984da8SDouglas Gregor 
8008e984da8SDouglas Gregor       sendto(sockfd, res.data(), res.size(), 0,
8018e984da8SDouglas Gregor              (struct sockaddr *)&servaddr, sizeof(servaddr));
8028e984da8SDouglas Gregor       close(sockfd);
8038e984da8SDouglas Gregor     }
8048e984da8SDouglas Gregor     while (false);
8058e984da8SDouglas Gregor   }
8068e984da8SDouglas Gregor #endif
8078e984da8SDouglas Gregor #endif
80877af1c56SDaniel Dunbar   CCAI->result = Results;
80977af1c56SDaniel Dunbar }
81077af1c56SDaniel Dunbar CXCodeCompleteResults *clang_codeCompleteAt(CXTranslationUnit TU,
81177af1c56SDaniel Dunbar                                             const char *complete_filename,
81277af1c56SDaniel Dunbar                                             unsigned complete_line,
81377af1c56SDaniel Dunbar                                             unsigned complete_column,
81477af1c56SDaniel Dunbar                                             struct CXUnsavedFile *unsaved_files,
81577af1c56SDaniel Dunbar                                             unsigned num_unsaved_files,
81677af1c56SDaniel Dunbar                                             unsigned options) {
817ea474358SArgyrios Kyrtzidis   LOG_FUNC_SECTION {
818ea474358SArgyrios Kyrtzidis     *Log << TU << ' '
819ea474358SArgyrios Kyrtzidis          << complete_filename << ':' << complete_line << ':' << complete_column;
820ea474358SArgyrios Kyrtzidis   }
821ea474358SArgyrios Kyrtzidis 
8229d85b18fSAlp Toker   if (num_unsaved_files && !unsaved_files)
8239d85b18fSAlp Toker     return nullptr;
8249d85b18fSAlp Toker 
82577af1c56SDaniel Dunbar   CodeCompleteAtInfo CCAI = {TU, complete_filename, complete_line,
8269d85b18fSAlp Toker     complete_column, llvm::makeArrayRef(unsaved_files, num_unsaved_files),
82769186e73SCraig Topper     options, nullptr};
8289999f4f8SArgyrios Kyrtzidis 
8299999f4f8SArgyrios Kyrtzidis   if (getenv("LIBCLANG_NOTHREADS")) {
8309999f4f8SArgyrios Kyrtzidis     clang_codeCompleteAt_Impl(&CCAI);
8319999f4f8SArgyrios Kyrtzidis     return CCAI.result;
8329999f4f8SArgyrios Kyrtzidis   }
8339999f4f8SArgyrios Kyrtzidis 
83477af1c56SDaniel Dunbar   llvm::CrashRecoveryContext CRC;
83577af1c56SDaniel Dunbar 
836b7383e6dSDaniel Dunbar   if (!RunSafely(CRC, clang_codeCompleteAt_Impl, &CCAI)) {
83777af1c56SDaniel Dunbar     fprintf(stderr, "libclang: crash detected in code completion\n");
838c22ea1ceSDmitri Gribenko     cxtu::getASTUnit(TU)->setUnsafeToFree(true);
83969186e73SCraig Topper     return nullptr;
840af44c781SDouglas Gregor   } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
841af44c781SDouglas Gregor     PrintLibclangResourceUsage(TU);
84277af1c56SDaniel Dunbar 
84377af1c56SDaniel Dunbar   return CCAI.result;
8448e984da8SDouglas Gregor }
8458e984da8SDouglas Gregor 
846b68bc59aSDouglas Gregor unsigned clang_defaultCodeCompleteOptions(void) {
847b68bc59aSDouglas Gregor   return CXCodeComplete_IncludeMacros;
848b68bc59aSDouglas Gregor }
849b68bc59aSDouglas Gregor 
850d5a2a073SDaniel Dunbar void clang_disposeCodeCompleteResults(CXCodeCompleteResults *ResultsIn) {
851d5a2a073SDaniel Dunbar   if (!ResultsIn)
852d5a2a073SDaniel Dunbar     return;
853d5a2a073SDaniel Dunbar 
854d5a2a073SDaniel Dunbar   AllocatedCXCodeCompleteResults *Results
855d5a2a073SDaniel Dunbar     = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
856d5a2a073SDaniel Dunbar   delete Results;
857d5a2a073SDaniel Dunbar }
858d5a2a073SDaniel Dunbar 
859d5a2a073SDaniel Dunbar unsigned
860d5a2a073SDaniel Dunbar clang_codeCompleteGetNumDiagnostics(CXCodeCompleteResults *ResultsIn) {
861d5a2a073SDaniel Dunbar   AllocatedCXCodeCompleteResults *Results
862d5a2a073SDaniel Dunbar     = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
863d5a2a073SDaniel Dunbar   if (!Results)
864d5a2a073SDaniel Dunbar     return 0;
865d5a2a073SDaniel Dunbar 
866d5a2a073SDaniel Dunbar   return Results->Diagnostics.size();
867d5a2a073SDaniel Dunbar }
868d5a2a073SDaniel Dunbar 
869d5a2a073SDaniel Dunbar CXDiagnostic
870d5a2a073SDaniel Dunbar clang_codeCompleteGetDiagnostic(CXCodeCompleteResults *ResultsIn,
871d5a2a073SDaniel Dunbar                                 unsigned Index) {
872d5a2a073SDaniel Dunbar   AllocatedCXCodeCompleteResults *Results
873d5a2a073SDaniel Dunbar     = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
874d5a2a073SDaniel Dunbar   if (!Results || Index >= Results->Diagnostics.size())
87569186e73SCraig Topper     return nullptr;
876d5a2a073SDaniel Dunbar 
8777dd96c23SNico Weber   CXStoredDiagnostic *Diag = Results->DiagnosticsWrappers[Index];
8787dd96c23SNico Weber   if (!Diag)
8797dd96c23SNico Weber     Results->DiagnosticsWrappers[Index] = Diag =
8807dd96c23SNico Weber         new CXStoredDiagnostic(Results->Diagnostics[Index], Results->LangOpts);
8817dd96c23SNico Weber   return Diag;
882d5a2a073SDaniel Dunbar }
883d5a2a073SDaniel Dunbar 
8842132584dSDouglas Gregor unsigned long long
8852132584dSDouglas Gregor clang_codeCompleteGetContexts(CXCodeCompleteResults *ResultsIn) {
8862132584dSDouglas Gregor   AllocatedCXCodeCompleteResults *Results
8872132584dSDouglas Gregor     = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
8882132584dSDouglas Gregor   if (!Results)
8892132584dSDouglas Gregor     return 0;
8902132584dSDouglas Gregor 
8912132584dSDouglas Gregor   return Results->Contexts;
8922132584dSDouglas Gregor }
893d5a2a073SDaniel Dunbar 
89463745d59SDouglas Gregor enum CXCursorKind clang_codeCompleteGetContainerKind(
89563745d59SDouglas Gregor                                                CXCodeCompleteResults *ResultsIn,
89663745d59SDouglas Gregor                                                      unsigned *IsIncomplete) {
89763745d59SDouglas Gregor   AllocatedCXCodeCompleteResults *Results =
89863745d59SDouglas Gregor     static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn);
89963745d59SDouglas Gregor   if (!Results)
90063745d59SDouglas Gregor     return CXCursor_InvalidCode;
90163745d59SDouglas Gregor 
90269186e73SCraig Topper   if (IsIncomplete != nullptr) {
90363745d59SDouglas Gregor     *IsIncomplete = Results->ContainerIsIncomplete;
90463745d59SDouglas Gregor   }
90563745d59SDouglas Gregor 
90663745d59SDouglas Gregor   return Results->ContainerKind;
90763745d59SDouglas Gregor }
90863745d59SDouglas Gregor 
90963745d59SDouglas Gregor CXString clang_codeCompleteGetContainerUSR(CXCodeCompleteResults *ResultsIn) {
91063745d59SDouglas Gregor   AllocatedCXCodeCompleteResults *Results =
91163745d59SDouglas Gregor     static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn);
91263745d59SDouglas Gregor   if (!Results)
91336a6dd04SDmitri Gribenko     return cxstring::createEmpty();
91463745d59SDouglas Gregor 
9150b62f8a6SDmitri Gribenko   return cxstring::createRef(Results->ContainerUSR.c_str());
91663745d59SDouglas Gregor }
91763745d59SDouglas Gregor 
918ea777403SDouglas Gregor 
919ea777403SDouglas Gregor CXString clang_codeCompleteGetObjCSelector(CXCodeCompleteResults *ResultsIn) {
920ea777403SDouglas Gregor   AllocatedCXCodeCompleteResults *Results =
921ea777403SDouglas Gregor     static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn);
922ea777403SDouglas Gregor   if (!Results)
92336a6dd04SDmitri Gribenko     return cxstring::createEmpty();
924ea777403SDouglas Gregor 
9252f23e9c5SDmitri Gribenko   return cxstring::createDup(Results->Selector);
926ea777403SDouglas Gregor }
927ea777403SDouglas Gregor 
928d5a2a073SDaniel Dunbar } // end extern "C"
92949f67ce4SDouglas Gregor 
9308e3e8743SDouglas Gregor /// \brief Simple utility function that appends a \p New string to the given
9318e3e8743SDouglas Gregor /// \p Old string, using the \p Buffer for storage.
9328e3e8743SDouglas Gregor ///
9338e3e8743SDouglas Gregor /// \param Old The string to which we are appending. This parameter will be
9348e3e8743SDouglas Gregor /// updated to reflect the complete string.
9358e3e8743SDouglas Gregor ///
9368e3e8743SDouglas Gregor ///
9378e3e8743SDouglas Gregor /// \param New The string to append to \p Old.
9388e3e8743SDouglas Gregor ///
9398e3e8743SDouglas Gregor /// \param Buffer A buffer that stores the actual, concatenated string. It will
9408e3e8743SDouglas Gregor /// be used if the old string is already-non-empty.
9410e62c1ccSChris Lattner static void AppendToString(StringRef &Old, StringRef New,
942f1a13f29SDylan Noblesmith                            SmallString<256> &Buffer) {
9438e3e8743SDouglas Gregor   if (Old.empty()) {
9448e3e8743SDouglas Gregor     Old = New;
9458e3e8743SDouglas Gregor     return;
9468e3e8743SDouglas Gregor   }
9478e3e8743SDouglas Gregor 
9488e3e8743SDouglas Gregor   if (Buffer.empty())
9498e3e8743SDouglas Gregor     Buffer.append(Old.begin(), Old.end());
9508e3e8743SDouglas Gregor   Buffer.append(New.begin(), New.end());
9518e3e8743SDouglas Gregor   Old = Buffer.str();
9528e3e8743SDouglas Gregor }
9538e3e8743SDouglas Gregor 
9548e3e8743SDouglas Gregor /// \brief Get the typed-text blocks from the given code-completion string
9558e3e8743SDouglas Gregor /// and return them as a single string.
9568e3e8743SDouglas Gregor ///
9578e3e8743SDouglas Gregor /// \param String The code-completion string whose typed-text blocks will be
9588e3e8743SDouglas Gregor /// concatenated.
9598e3e8743SDouglas Gregor ///
9608e3e8743SDouglas Gregor /// \param Buffer A buffer used for storage of the completed name.
9610e62c1ccSChris Lattner static StringRef GetTypedName(CodeCompletionString *String,
962f1a13f29SDylan Noblesmith                                     SmallString<256> &Buffer) {
9630e62c1ccSChris Lattner   StringRef Result;
9648e3e8743SDouglas Gregor   for (CodeCompletionString::iterator C = String->begin(), CEnd = String->end();
9658e3e8743SDouglas Gregor        C != CEnd; ++C) {
9668e3e8743SDouglas Gregor     if (C->Kind == CodeCompletionString::CK_TypedText)
9678e3e8743SDouglas Gregor       AppendToString(Result, C->Text, Buffer);
9688e3e8743SDouglas Gregor   }
9698e3e8743SDouglas Gregor 
9708e3e8743SDouglas Gregor   return Result;
9718e3e8743SDouglas Gregor }
9728e3e8743SDouglas Gregor 
97349f67ce4SDouglas Gregor namespace {
97449f67ce4SDouglas Gregor   struct OrderCompletionResults {
97549f67ce4SDouglas Gregor     bool operator()(const CXCompletionResult &XR,
97649f67ce4SDouglas Gregor                     const CXCompletionResult &YR) const {
977b278aafbSDouglas Gregor       CodeCompletionString *X
978b278aafbSDouglas Gregor         = (CodeCompletionString *)XR.CompletionString;
979b278aafbSDouglas Gregor       CodeCompletionString *Y
980b278aafbSDouglas Gregor         = (CodeCompletionString *)YR.CompletionString;
98149f67ce4SDouglas Gregor 
982f1a13f29SDylan Noblesmith       SmallString<256> XBuffer;
9830e62c1ccSChris Lattner       StringRef XText = GetTypedName(X, XBuffer);
984f1a13f29SDylan Noblesmith       SmallString<256> YBuffer;
9850e62c1ccSChris Lattner       StringRef YText = GetTypedName(Y, YBuffer);
98649f67ce4SDouglas Gregor 
9878e3e8743SDouglas Gregor       if (XText.empty() || YText.empty())
9888e3e8743SDouglas Gregor         return !XText.empty();
9898e3e8743SDouglas Gregor 
9908e3e8743SDouglas Gregor       int result = XText.compare_lower(YText);
99149f67ce4SDouglas Gregor       if (result < 0)
99249f67ce4SDouglas Gregor         return true;
99349f67ce4SDouglas Gregor       if (result > 0)
99449f67ce4SDouglas Gregor         return false;
99549f67ce4SDouglas Gregor 
9968e3e8743SDouglas Gregor       result = XText.compare(YText);
997c7a7d92aSDouglas Gregor       return result < 0;
99849f67ce4SDouglas Gregor     }
99949f67ce4SDouglas Gregor   };
100049f67ce4SDouglas Gregor }
100149f67ce4SDouglas Gregor 
100249f67ce4SDouglas Gregor extern "C" {
100349f67ce4SDouglas Gregor   void clang_sortCodeCompletionResults(CXCompletionResult *Results,
100449f67ce4SDouglas Gregor                                        unsigned NumResults) {
100549f67ce4SDouglas Gregor     std::stable_sort(Results, Results + NumResults, OrderCompletionResults());
100649f67ce4SDouglas Gregor   }
100749f67ce4SDouglas Gregor }
1008