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"
193957e48aSIvan Donchevskii #include "CXSourceLocation.h"
205b8ad406STed Kremenek #include "CXString.h"
21cc0694c8SChandler Carruth #include "CXTranslationUnit.h"
2263745d59SDouglas Gregor #include "clang/AST/Decl.h"
2363745d59SDouglas Gregor #include "clang/AST/DeclObjC.h"
24cc0694c8SChandler Carruth #include "clang/AST/Type.h"
25d5a2a073SDaniel Dunbar #include "clang/Basic/FileManager.h"
26cc0694c8SChandler Carruth #include "clang/Basic/SourceManager.h"
278e984da8SDouglas Gregor #include "clang/Frontend/ASTUnit.h"
28d5a2a073SDaniel Dunbar #include "clang/Frontend/CompilerInstance.h"
29d5a2a073SDaniel Dunbar #include "clang/Frontend/FrontendDiagnostic.h"
30d5a2a073SDaniel Dunbar #include "clang/Sema/CodeCompleteConsumer.h"
310a4e61f8SDavid Blaikie #include "clang/Sema/Sema.h"
32028d3e4dSDouglas Gregor #include "llvm/ADT/SmallString.h"
33d5a2a073SDaniel Dunbar #include "llvm/ADT/StringExtras.h"
3477af1c56SDaniel Dunbar #include "llvm/Support/CrashRecoveryContext.h"
35b34c1fdfSRafael Espindola #include "llvm/Support/FileSystem.h"
36690f0e2fSAlex Lorenz #include "llvm/Support/FormatVariadic.h"
37d5a2a073SDaniel Dunbar #include "llvm/Support/MemoryBuffer.h"
38cc0694c8SChandler Carruth #include "llvm/Support/Program.h"
39028d3e4dSDouglas Gregor #include "llvm/Support/Timer.h"
40028d3e4dSDouglas Gregor #include "llvm/Support/raw_ostream.h"
414527fb2fSBenjamin Kramer #include <atomic>
42d6009ffbSDouglas Gregor #include <cstdio>
43cc0694c8SChandler Carruth #include <cstdlib>
440b62f8a6SDmitri Gribenko #include <string>
45d5a2a073SDaniel Dunbar 
46028d3e4dSDouglas Gregor 
47d5a2a073SDaniel Dunbar #ifdef UDP_CODE_COMPLETION_LOGGER
48d5a2a073SDaniel Dunbar #include "clang/Basic/Version.h"
49d5a2a073SDaniel Dunbar #include <arpa/inet.h>
50d5a2a073SDaniel Dunbar #include <sys/socket.h>
51d5a2a073SDaniel Dunbar #include <sys/types.h>
52d5a2a073SDaniel Dunbar #include <unistd.h>
53d5a2a073SDaniel Dunbar #endif
54d5a2a073SDaniel Dunbar 
55d5a2a073SDaniel Dunbar using namespace clang;
56ea474358SArgyrios Kyrtzidis using namespace clang::cxindex;
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 
2449fc8faf9SAdrian Prantl /// 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 
2559fc8faf9SAdrian Prantl   /// Diagnostics produced while performing code completion.
2560e62c1ccSChris Lattner   SmallVector<StoredDiagnostic, 8> Diagnostics;
257d5a2a073SDaniel Dunbar 
2589fc8faf9SAdrian Prantl   /// Allocated API-exposed wrappters for Diagnostics.
2597dd96c23SNico Weber   SmallVector<CXStoredDiagnostic *, 8> DiagnosticsWrappers;
2607dd96c23SNico Weber 
261811db4eaSDouglas Gregor   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts;
262811db4eaSDouglas Gregor 
2639fc8faf9SAdrian Prantl   /// Diag object
264c95d8192SDylan Noblesmith   IntrusiveRefCntPtr<DiagnosticsEngine> Diag;
265d5a2a073SDaniel Dunbar 
2669fc8faf9SAdrian Prantl   /// Language options used to adjust source locations.
267d5a2a073SDaniel Dunbar   LangOptions LangOpts;
268d5a2a073SDaniel Dunbar 
2699fc8faf9SAdrian Prantl   /// File manager, used for diagnostics.
270c95d8192SDylan Noblesmith   IntrusiveRefCntPtr<FileManager> FileMgr;
271d5a2a073SDaniel Dunbar 
2729fc8faf9SAdrian Prantl   /// Source manager, used for diagnostics.
273c95d8192SDylan Noblesmith   IntrusiveRefCntPtr<SourceManager> SourceMgr;
27471731d6bSArgyrios Kyrtzidis 
2759fc8faf9SAdrian Prantl   /// Temporary buffers that will be deleted once we have finished with
2763f5a9efbSChris Lattner   /// the code-completion results.
2770e62c1ccSChris Lattner   SmallVector<const llvm::MemoryBuffer *, 1> TemporaryBuffers;
278b278aafbSDouglas Gregor 
2799fc8faf9SAdrian Prantl   /// Allocator used to store globally cached code-completion results.
280ea4395ebSDavid Blaikie   std::shared_ptr<clang::GlobalCodeCompletionAllocator>
281162b712dSDouglas Gregor       CachedCompletionAllocator;
282162b712dSDouglas Gregor 
2839fc8faf9SAdrian Prantl   /// Allocator used to store code completion results.
284ea4395ebSDavid Blaikie   std::shared_ptr<clang::GlobalCodeCompletionAllocator> CodeCompletionAllocator;
2852132584dSDouglas Gregor 
2869fc8faf9SAdrian Prantl   /// Context under which completion occurred.
2872132584dSDouglas Gregor   enum clang::CodeCompletionContext::Kind ContextKind;
2882132584dSDouglas Gregor 
2899fc8faf9SAdrian Prantl   /// A bitfield representing the acceptable completions for the
2902132584dSDouglas Gregor   /// current context.
2912132584dSDouglas Gregor   unsigned long long Contexts;
29263745d59SDouglas Gregor 
2939fc8faf9SAdrian Prantl   /// The kind of the container for the current context for completions.
29463745d59SDouglas Gregor   enum CXCursorKind ContainerKind;
2950b62f8a6SDmitri Gribenko 
2969fc8faf9SAdrian Prantl   /// The USR of the container for the current context for completions.
2970b62f8a6SDmitri Gribenko   std::string ContainerUSR;
2980b62f8a6SDmitri Gribenko 
2999fc8faf9SAdrian Prantl   /// a boolean value indicating whether there is complete information
300ea777403SDouglas Gregor   /// about the container
30163745d59SDouglas Gregor   unsigned ContainerIsIncomplete;
302ea777403SDouglas Gregor 
3039fc8faf9SAdrian Prantl   /// A string containing the Objective-C selector entered thus far for a
304ea777403SDouglas Gregor   /// message send.
305ea777403SDouglas Gregor   std::string Selector;
3063957e48aSIvan Donchevskii 
3073957e48aSIvan Donchevskii   /// Vector of fix-its for each completion result that *must* be applied
3083957e48aSIvan Donchevskii   /// before that result for the corresponding completion item.
3093957e48aSIvan Donchevskii   std::vector<std::vector<FixItHint>> FixItsVector;
310d5a2a073SDaniel Dunbar };
311d5a2a073SDaniel Dunbar 
312ba4c85e5SBenjamin Kramer } // end anonymous namespace
313ba4c85e5SBenjamin Kramer 
3143957e48aSIvan Donchevskii unsigned clang_getCompletionNumFixIts(CXCodeCompleteResults *results,
3153957e48aSIvan Donchevskii                                       unsigned completion_index) {
3163957e48aSIvan Donchevskii   AllocatedCXCodeCompleteResults *allocated_results = (AllocatedCXCodeCompleteResults *)results;
3173957e48aSIvan Donchevskii 
3183957e48aSIvan Donchevskii   if (!allocated_results || allocated_results->FixItsVector.size() <= completion_index)
3193957e48aSIvan Donchevskii     return 0;
3203957e48aSIvan Donchevskii 
3213957e48aSIvan Donchevskii   return static_cast<unsigned>(allocated_results->FixItsVector[completion_index].size());
3223957e48aSIvan Donchevskii }
3233957e48aSIvan Donchevskii 
3243957e48aSIvan Donchevskii CXString clang_getCompletionFixIt(CXCodeCompleteResults *results,
3253957e48aSIvan Donchevskii                                   unsigned completion_index,
3263957e48aSIvan Donchevskii                                   unsigned fixit_index,
3273957e48aSIvan Donchevskii                                   CXSourceRange *replacement_range) {
3283957e48aSIvan Donchevskii   AllocatedCXCodeCompleteResults *allocated_results = (AllocatedCXCodeCompleteResults *)results;
3293957e48aSIvan Donchevskii 
3303957e48aSIvan Donchevskii   if (!allocated_results || allocated_results->FixItsVector.size() <= completion_index) {
3313957e48aSIvan Donchevskii     if (replacement_range)
3323957e48aSIvan Donchevskii       *replacement_range = clang_getNullRange();
3333957e48aSIvan Donchevskii     return cxstring::createNull();
3343957e48aSIvan Donchevskii   }
3353957e48aSIvan Donchevskii 
3363957e48aSIvan Donchevskii   ArrayRef<FixItHint> FixIts = allocated_results->FixItsVector[completion_index];
3373957e48aSIvan Donchevskii   if (FixIts.size() <= fixit_index) {
3383957e48aSIvan Donchevskii     if (replacement_range)
3393957e48aSIvan Donchevskii       *replacement_range = clang_getNullRange();
3403957e48aSIvan Donchevskii     return cxstring::createNull();
3413957e48aSIvan Donchevskii   }
3423957e48aSIvan Donchevskii 
3433957e48aSIvan Donchevskii   const FixItHint &FixIt = FixIts[fixit_index];
3443957e48aSIvan Donchevskii   if (replacement_range) {
3453957e48aSIvan Donchevskii     *replacement_range = cxloc::translateSourceRange(
3463957e48aSIvan Donchevskii         *allocated_results->SourceMgr, allocated_results->LangOpts,
3473957e48aSIvan Donchevskii         FixIt.RemoveRange);
3483957e48aSIvan Donchevskii   }
3493957e48aSIvan Donchevskii 
3503957e48aSIvan Donchevskii   return cxstring::createRef(FixIt.CodeToInsert.c_str());
3513957e48aSIvan Donchevskii }
3523957e48aSIvan Donchevskii 
3539fc8faf9SAdrian Prantl /// Tracks the number of code-completion result objects that are
35468dbaeadSDouglas Gregor /// currently active.
35568dbaeadSDouglas Gregor ///
35668dbaeadSDouglas Gregor /// Used for debugging purposes only.
3574527fb2fSBenjamin Kramer static std::atomic<unsigned> CodeCompletionResultObjects;
35868dbaeadSDouglas Gregor 
359c30dcecbSAnders Carlsson AllocatedCXCodeCompleteResults::AllocatedCXCodeCompleteResults(
3608832c066SBen Langmuir     IntrusiveRefCntPtr<FileManager> FileMgr)
361ea4395ebSDavid Blaikie     : CXCodeCompleteResults(), DiagOpts(new DiagnosticOptions),
3629c902b55SDavid Blaikie       Diag(new DiagnosticsEngine(
3638832c066SBen Langmuir           IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), &*DiagOpts)),
364f6021ecdSBenjamin Kramer       FileMgr(std::move(FileMgr)),
365f6021ecdSBenjamin Kramer       SourceMgr(new SourceManager(*Diag, *this->FileMgr)),
366ea4395ebSDavid Blaikie       CodeCompletionAllocator(
367ea4395ebSDavid Blaikie           std::make_shared<clang::GlobalCodeCompletionAllocator>()),
368e442fe3dSDouglas Gregor       Contexts(CXCompletionContext_Unknown),
3698832c066SBen Langmuir       ContainerKind(CXCursor_InvalidCode), ContainerIsIncomplete(1) {
3704527fb2fSBenjamin Kramer   if (getenv("LIBCLANG_OBJTRACKING"))
3714527fb2fSBenjamin Kramer     fprintf(stderr, "+++ %u completion results\n",
3724527fb2fSBenjamin Kramer             ++CodeCompletionResultObjects);
37368dbaeadSDouglas Gregor }
374d5a2a073SDaniel Dunbar 
375d5a2a073SDaniel Dunbar AllocatedCXCodeCompleteResults::~AllocatedCXCodeCompleteResults() {
3767dd96c23SNico Weber   llvm::DeleteContainerPointers(DiagnosticsWrappers);
377d5a2a073SDaniel Dunbar   delete [] Results;
378d5a2a073SDaniel Dunbar 
379d8a5dba9SDouglas Gregor   for (unsigned I = 0, N = TemporaryBuffers.size(); I != N; ++I)
380d8a5dba9SDouglas Gregor     delete TemporaryBuffers[I];
38168dbaeadSDouglas Gregor 
3824527fb2fSBenjamin Kramer   if (getenv("LIBCLANG_OBJTRACKING"))
3834527fb2fSBenjamin Kramer     fprintf(stderr, "--- %u completion results\n",
3844527fb2fSBenjamin Kramer             --CodeCompletionResultObjects);
385d5a2a073SDaniel Dunbar }
386d5a2a073SDaniel Dunbar 
3872132584dSDouglas Gregor static unsigned long long getContextsForContextKind(
3882132584dSDouglas Gregor                                           enum CodeCompletionContext::Kind kind,
3892132584dSDouglas Gregor                                                     Sema &S) {
3902132584dSDouglas Gregor   unsigned long long contexts = 0;
3912132584dSDouglas Gregor   switch (kind) {
3922132584dSDouglas Gregor     case CodeCompletionContext::CCC_OtherWithMacros: {
3932132584dSDouglas Gregor       //We can allow macros here, but we don't know what else is permissible
3942132584dSDouglas Gregor       //So we'll say the only thing permissible are macros
3952132584dSDouglas Gregor       contexts = CXCompletionContext_MacroName;
3962132584dSDouglas Gregor       break;
3972132584dSDouglas Gregor     }
3982132584dSDouglas Gregor     case CodeCompletionContext::CCC_TopLevel:
3992132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCIvarList:
4002132584dSDouglas Gregor     case CodeCompletionContext::CCC_ClassStructUnion:
4012132584dSDouglas Gregor     case CodeCompletionContext::CCC_Type: {
4022132584dSDouglas Gregor       contexts = CXCompletionContext_AnyType |
4032132584dSDouglas Gregor                  CXCompletionContext_ObjCInterface;
404bbafb8a7SDavid Blaikie       if (S.getLangOpts().CPlusPlus) {
4052132584dSDouglas Gregor         contexts |= CXCompletionContext_EnumTag |
4062132584dSDouglas Gregor                     CXCompletionContext_UnionTag |
4072132584dSDouglas Gregor                     CXCompletionContext_StructTag |
4082132584dSDouglas Gregor                     CXCompletionContext_ClassTag |
4092132584dSDouglas Gregor                     CXCompletionContext_NestedNameSpecifier;
4102132584dSDouglas Gregor       }
4112132584dSDouglas Gregor       break;
4122132584dSDouglas Gregor     }
4132132584dSDouglas Gregor     case CodeCompletionContext::CCC_Statement: {
4142132584dSDouglas Gregor       contexts = CXCompletionContext_AnyType |
4152132584dSDouglas Gregor                  CXCompletionContext_ObjCInterface |
4162132584dSDouglas Gregor                  CXCompletionContext_AnyValue;
417bbafb8a7SDavid Blaikie       if (S.getLangOpts().CPlusPlus) {
4182132584dSDouglas Gregor         contexts |= CXCompletionContext_EnumTag |
4192132584dSDouglas Gregor                     CXCompletionContext_UnionTag |
4202132584dSDouglas Gregor                     CXCompletionContext_StructTag |
4212132584dSDouglas Gregor                     CXCompletionContext_ClassTag |
4222132584dSDouglas Gregor                     CXCompletionContext_NestedNameSpecifier;
4232132584dSDouglas Gregor       }
4242132584dSDouglas Gregor       break;
4252132584dSDouglas Gregor     }
4262132584dSDouglas Gregor     case CodeCompletionContext::CCC_Expression: {
4272132584dSDouglas Gregor       contexts = CXCompletionContext_AnyValue;
428bbafb8a7SDavid Blaikie       if (S.getLangOpts().CPlusPlus) {
4292132584dSDouglas Gregor         contexts |= CXCompletionContext_AnyType |
4302132584dSDouglas Gregor                     CXCompletionContext_ObjCInterface |
4312132584dSDouglas Gregor                     CXCompletionContext_EnumTag |
4322132584dSDouglas Gregor                     CXCompletionContext_UnionTag |
4332132584dSDouglas Gregor                     CXCompletionContext_StructTag |
4342132584dSDouglas Gregor                     CXCompletionContext_ClassTag |
4352132584dSDouglas Gregor                     CXCompletionContext_NestedNameSpecifier;
4362132584dSDouglas Gregor       }
4372132584dSDouglas Gregor       break;
4382132584dSDouglas Gregor     }
4392132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCMessageReceiver: {
4402132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCObjectValue |
4412132584dSDouglas Gregor                  CXCompletionContext_ObjCSelectorValue |
4422132584dSDouglas Gregor                  CXCompletionContext_ObjCInterface;
443bbafb8a7SDavid Blaikie       if (S.getLangOpts().CPlusPlus) {
4442132584dSDouglas Gregor         contexts |= CXCompletionContext_CXXClassTypeValue |
4452132584dSDouglas Gregor                     CXCompletionContext_AnyType |
4462132584dSDouglas Gregor                     CXCompletionContext_EnumTag |
4472132584dSDouglas Gregor                     CXCompletionContext_UnionTag |
4482132584dSDouglas Gregor                     CXCompletionContext_StructTag |
4492132584dSDouglas Gregor                     CXCompletionContext_ClassTag |
4502132584dSDouglas Gregor                     CXCompletionContext_NestedNameSpecifier;
4512132584dSDouglas Gregor       }
4522132584dSDouglas Gregor       break;
4532132584dSDouglas Gregor     }
4542132584dSDouglas Gregor     case CodeCompletionContext::CCC_DotMemberAccess: {
4552132584dSDouglas Gregor       contexts = CXCompletionContext_DotMemberAccess;
4562132584dSDouglas Gregor       break;
4572132584dSDouglas Gregor     }
4582132584dSDouglas Gregor     case CodeCompletionContext::CCC_ArrowMemberAccess: {
4592132584dSDouglas Gregor       contexts = CXCompletionContext_ArrowMemberAccess;
4602132584dSDouglas Gregor       break;
4612132584dSDouglas Gregor     }
4622132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCPropertyAccess: {
4632132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCPropertyAccess;
4642132584dSDouglas Gregor       break;
4652132584dSDouglas Gregor     }
4662132584dSDouglas Gregor     case CodeCompletionContext::CCC_EnumTag: {
4672132584dSDouglas Gregor       contexts = CXCompletionContext_EnumTag |
4682132584dSDouglas Gregor                  CXCompletionContext_NestedNameSpecifier;
4692132584dSDouglas Gregor       break;
4702132584dSDouglas Gregor     }
4712132584dSDouglas Gregor     case CodeCompletionContext::CCC_UnionTag: {
4722132584dSDouglas Gregor       contexts = CXCompletionContext_UnionTag |
4732132584dSDouglas Gregor                  CXCompletionContext_NestedNameSpecifier;
4742132584dSDouglas Gregor       break;
4752132584dSDouglas Gregor     }
4762132584dSDouglas Gregor     case CodeCompletionContext::CCC_ClassOrStructTag: {
4772132584dSDouglas Gregor       contexts = CXCompletionContext_StructTag |
4782132584dSDouglas Gregor                  CXCompletionContext_ClassTag |
4792132584dSDouglas Gregor                  CXCompletionContext_NestedNameSpecifier;
4802132584dSDouglas Gregor       break;
4812132584dSDouglas Gregor     }
4822132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCProtocolName: {
4832132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCProtocol;
4842132584dSDouglas Gregor       break;
4852132584dSDouglas Gregor     }
4862132584dSDouglas Gregor     case CodeCompletionContext::CCC_Namespace: {
4872132584dSDouglas Gregor       contexts = CXCompletionContext_Namespace;
4882132584dSDouglas Gregor       break;
4892132584dSDouglas Gregor     }
4902132584dSDouglas Gregor     case CodeCompletionContext::CCC_PotentiallyQualifiedName: {
4912132584dSDouglas Gregor       contexts = CXCompletionContext_NestedNameSpecifier;
4922132584dSDouglas Gregor       break;
4932132584dSDouglas Gregor     }
4942132584dSDouglas Gregor     case CodeCompletionContext::CCC_MacroNameUse: {
4952132584dSDouglas Gregor       contexts = CXCompletionContext_MacroName;
4962132584dSDouglas Gregor       break;
4972132584dSDouglas Gregor     }
4982132584dSDouglas Gregor     case CodeCompletionContext::CCC_NaturalLanguage: {
4992132584dSDouglas Gregor       contexts = CXCompletionContext_NaturalLanguage;
5002132584dSDouglas Gregor       break;
5012132584dSDouglas Gregor     }
502*3d8051abSSam McCall     case CodeCompletionContext::CCC_IncludedFile: {
503*3d8051abSSam McCall       contexts = CXCompletionContext_IncludedFile;
504*3d8051abSSam McCall       break;
505*3d8051abSSam McCall     }
5062132584dSDouglas Gregor     case CodeCompletionContext::CCC_SelectorName: {
5072132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCSelectorName;
5082132584dSDouglas Gregor       break;
5092132584dSDouglas Gregor     }
5102132584dSDouglas Gregor     case CodeCompletionContext::CCC_ParenthesizedExpression: {
5112132584dSDouglas Gregor       contexts = CXCompletionContext_AnyType |
5122132584dSDouglas Gregor                  CXCompletionContext_ObjCInterface |
5132132584dSDouglas Gregor                  CXCompletionContext_AnyValue;
514bbafb8a7SDavid Blaikie       if (S.getLangOpts().CPlusPlus) {
5152132584dSDouglas Gregor         contexts |= CXCompletionContext_EnumTag |
5162132584dSDouglas Gregor                     CXCompletionContext_UnionTag |
5172132584dSDouglas Gregor                     CXCompletionContext_StructTag |
5182132584dSDouglas Gregor                     CXCompletionContext_ClassTag |
5192132584dSDouglas Gregor                     CXCompletionContext_NestedNameSpecifier;
5202132584dSDouglas Gregor       }
5212132584dSDouglas Gregor       break;
5222132584dSDouglas Gregor     }
5232132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCInstanceMessage: {
5242132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCInstanceMessage;
5252132584dSDouglas Gregor       break;
5262132584dSDouglas Gregor     }
5272132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCClassMessage: {
5282132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCClassMessage;
5292132584dSDouglas Gregor       break;
5302132584dSDouglas Gregor     }
5312c595adfSDouglas Gregor     case CodeCompletionContext::CCC_ObjCInterfaceName: {
5322132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCInterface;
5332132584dSDouglas Gregor       break;
5342132584dSDouglas Gregor     }
5352132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCCategoryName: {
5362132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCCategory;
5372132584dSDouglas Gregor       break;
5382132584dSDouglas Gregor     }
5392132584dSDouglas Gregor     case CodeCompletionContext::CCC_Other:
5402132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCInterface:
5412132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCImplementation:
5422132584dSDouglas Gregor     case CodeCompletionContext::CCC_Name:
5432132584dSDouglas Gregor     case CodeCompletionContext::CCC_MacroName:
5442132584dSDouglas Gregor     case CodeCompletionContext::CCC_PreprocessorExpression:
5452132584dSDouglas Gregor     case CodeCompletionContext::CCC_PreprocessorDirective:
5462132584dSDouglas Gregor     case CodeCompletionContext::CCC_TypeQualifiers: {
5472132584dSDouglas Gregor       //Only Clang results should be accepted, so we'll set all of the other
5482132584dSDouglas Gregor       //context bits to 0 (i.e. the empty set)
5492132584dSDouglas Gregor       contexts = CXCompletionContext_Unexposed;
5502132584dSDouglas Gregor       break;
5512132584dSDouglas Gregor     }
5522132584dSDouglas Gregor     case CodeCompletionContext::CCC_Recovery: {
5532132584dSDouglas Gregor       //We don't know what the current context is, so we'll return unknown
5542132584dSDouglas Gregor       //This is the equivalent of setting all of the other context bits
5552132584dSDouglas Gregor       contexts = CXCompletionContext_Unknown;
5562132584dSDouglas Gregor       break;
5572132584dSDouglas Gregor     }
5582132584dSDouglas Gregor   }
5592132584dSDouglas Gregor   return contexts;
5602132584dSDouglas Gregor }
5612132584dSDouglas Gregor 
5628e984da8SDouglas Gregor namespace {
5638e984da8SDouglas Gregor   class CaptureCompletionResults : public CodeCompleteConsumer {
5648e984da8SDouglas Gregor     AllocatedCXCodeCompleteResults &AllocatedResults;
5659d7c0fefSArgyrios Kyrtzidis     CodeCompletionTUInfo CCTUInfo;
5660e62c1ccSChris Lattner     SmallVector<CXCompletionResult, 16> StoredResults;
56763745d59SDouglas Gregor     CXTranslationUnit *TU;
5688e984da8SDouglas Gregor   public:
5693292d06aSDmitri Gribenko     CaptureCompletionResults(const CodeCompleteOptions &Opts,
5703292d06aSDmitri Gribenko                              AllocatedCXCodeCompleteResults &Results,
57163745d59SDouglas Gregor                              CXTranslationUnit *TranslationUnit)
5723292d06aSDmitri Gribenko       : CodeCompleteConsumer(Opts, false),
5739d7c0fefSArgyrios Kyrtzidis         AllocatedResults(Results), CCTUInfo(Results.CodeCompletionAllocator),
5749d7c0fefSArgyrios Kyrtzidis         TU(TranslationUnit) { }
57534eb2072SAlexander Kornienko     ~CaptureCompletionResults() override { Finish(); }
5768e984da8SDouglas Gregor 
57736835568SCraig Topper     void ProcessCodeCompleteResults(Sema &S,
57800c37ef0SDouglas Gregor                                     CodeCompletionContext Context,
579276321a9SJohn McCall                                     CodeCompletionResult *Results,
58036835568SCraig Topper                                     unsigned NumResults) override {
58136e3b5c7SDouglas Gregor       StoredResults.reserve(StoredResults.size() + NumResults);
5823957e48aSIvan Donchevskii       if (includeFixIts())
5833957e48aSIvan Donchevskii         AllocatedResults.FixItsVector.reserve(NumResults);
5848e984da8SDouglas Gregor       for (unsigned I = 0; I != NumResults; ++I) {
585b278aafbSDouglas Gregor         CodeCompletionString *StoredCompletion
586c3425b1fSDouglas Gregor           = Results[I].CreateCodeCompletionString(S, Context, getAllocator(),
5873292d06aSDmitri Gribenko                                                   getCodeCompletionTUInfo(),
5883292d06aSDmitri Gribenko                                                   includeBriefComments());
58936e3b5c7SDouglas Gregor 
59036e3b5c7SDouglas Gregor         CXCompletionResult R;
59136e3b5c7SDouglas Gregor         R.CursorKind = Results[I].CursorKind;
59236e3b5c7SDouglas Gregor         R.CompletionString = StoredCompletion;
59336e3b5c7SDouglas Gregor         StoredResults.push_back(R);
5943957e48aSIvan Donchevskii         if (includeFixIts())
5953957e48aSIvan Donchevskii           AllocatedResults.FixItsVector.emplace_back(std::move(Results[I].FixIts));
5968e984da8SDouglas Gregor       }
5972132584dSDouglas Gregor 
59863745d59SDouglas Gregor       enum CodeCompletionContext::Kind contextKind = Context.getKind();
5992132584dSDouglas Gregor 
60063745d59SDouglas Gregor       AllocatedResults.ContextKind = contextKind;
60163745d59SDouglas Gregor       AllocatedResults.Contexts = getContextsForContextKind(contextKind, S);
60263745d59SDouglas Gregor 
603ea777403SDouglas Gregor       AllocatedResults.Selector = "";
6043f31bd18SDmitri Gribenko       ArrayRef<IdentifierInfo *> SelIdents = Context.getSelIdents();
6053f31bd18SDmitri Gribenko       for (ArrayRef<IdentifierInfo *>::iterator I = SelIdents.begin(),
6063f31bd18SDmitri Gribenko                                                 E = SelIdents.end();
6073f31bd18SDmitri Gribenko            I != E; ++I) {
6083f31bd18SDmitri Gribenko         if (IdentifierInfo *selIdent = *I)
6093f31bd18SDmitri Gribenko           AllocatedResults.Selector += selIdent->getName();
610ea777403SDouglas Gregor         AllocatedResults.Selector += ":";
611ea777403SDouglas Gregor       }
612ea777403SDouglas Gregor 
61363745d59SDouglas Gregor       QualType baseType = Context.getBaseType();
61469186e73SCraig Topper       NamedDecl *D = nullptr;
61563745d59SDouglas Gregor 
61663745d59SDouglas Gregor       if (!baseType.isNull()) {
61763745d59SDouglas Gregor         // Get the declaration for a class/struct/union/enum type
61863745d59SDouglas Gregor         if (const TagType *Tag = baseType->getAs<TagType>())
61963745d59SDouglas Gregor           D = Tag->getDecl();
62063745d59SDouglas Gregor         // Get the @interface declaration for a (possibly-qualified) Objective-C
62163745d59SDouglas Gregor         // object pointer type, e.g., NSString*
62263745d59SDouglas Gregor         else if (const ObjCObjectPointerType *ObjPtr =
62363745d59SDouglas Gregor                  baseType->getAs<ObjCObjectPointerType>())
62463745d59SDouglas Gregor           D = ObjPtr->getInterfaceDecl();
62563745d59SDouglas Gregor         // Get the @interface declaration for an Objective-C object type
62663745d59SDouglas Gregor         else if (const ObjCObjectType *Obj = baseType->getAs<ObjCObjectType>())
62763745d59SDouglas Gregor           D = Obj->getInterface();
62863745d59SDouglas Gregor         // Get the class for a C++ injected-class-name
62963745d59SDouglas Gregor         else if (const InjectedClassNameType *Injected =
63063745d59SDouglas Gregor                  baseType->getAs<InjectedClassNameType>())
63163745d59SDouglas Gregor           D = Injected->getDecl();
63263745d59SDouglas Gregor       }
63363745d59SDouglas Gregor 
63469186e73SCraig Topper       if (D != nullptr) {
63563745d59SDouglas Gregor         CXCursor cursor = cxcursor::MakeCXCursor(D, *TU);
63663745d59SDouglas Gregor 
6370b62f8a6SDmitri Gribenko         AllocatedResults.ContainerKind = clang_getCursorKind(cursor);
63863745d59SDouglas Gregor 
6390b62f8a6SDmitri Gribenko         CXString CursorUSR = clang_getCursorUSR(cursor);
6400b62f8a6SDmitri Gribenko         AllocatedResults.ContainerUSR = clang_getCString(CursorUSR);
6410b62f8a6SDmitri Gribenko         clang_disposeString(CursorUSR);
6425b8ad406STed Kremenek 
64363745d59SDouglas Gregor         const Type *type = baseType.getTypePtrOrNull();
64469186e73SCraig Topper         if (type) {
64563745d59SDouglas Gregor           AllocatedResults.ContainerIsIncomplete = type->isIncompleteType();
64663745d59SDouglas Gregor         }
64763745d59SDouglas Gregor         else {
64863745d59SDouglas Gregor           AllocatedResults.ContainerIsIncomplete = 1;
64963745d59SDouglas Gregor         }
65063745d59SDouglas Gregor       }
65163745d59SDouglas Gregor       else {
65263745d59SDouglas Gregor         AllocatedResults.ContainerKind = CXCursor_InvalidCode;
6530b62f8a6SDmitri Gribenko         AllocatedResults.ContainerUSR.clear();
65463745d59SDouglas Gregor         AllocatedResults.ContainerIsIncomplete = 1;
65563745d59SDouglas Gregor       }
6568e984da8SDouglas Gregor     }
65749f67ce4SDouglas Gregor 
65836835568SCraig Topper     void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
65936e3b5c7SDouglas Gregor                                    OverloadCandidate *Candidates,
6602fab2353SIlya Biryukov                                    unsigned NumCandidates,
6612fab2353SIlya Biryukov                                    SourceLocation OpenParLoc) override {
66236e3b5c7SDouglas Gregor       StoredResults.reserve(StoredResults.size() + NumCandidates);
66336e3b5c7SDouglas Gregor       for (unsigned I = 0; I != NumCandidates; ++I) {
664b278aafbSDouglas Gregor         CodeCompletionString *StoredCompletion
6659d7c0fefSArgyrios Kyrtzidis           = Candidates[I].CreateSignatureString(CurrentArg, S, getAllocator(),
6660c010cddSFrancisco Lopes da Silva                                                 getCodeCompletionTUInfo(),
6670c010cddSFrancisco Lopes da Silva                                                 includeBriefComments());
66836e3b5c7SDouglas Gregor 
66936e3b5c7SDouglas Gregor         CXCompletionResult R;
670975a9f6eSFrancisco Lopes da Silva         R.CursorKind = CXCursor_OverloadCandidate;
67136e3b5c7SDouglas Gregor         R.CompletionString = StoredCompletion;
67236e3b5c7SDouglas Gregor         StoredResults.push_back(R);
67336e3b5c7SDouglas Gregor       }
67436e3b5c7SDouglas Gregor     }
67536e3b5c7SDouglas Gregor 
67636835568SCraig Topper     CodeCompletionAllocator &getAllocator() override {
6779d7c0fefSArgyrios Kyrtzidis       return *AllocatedResults.CodeCompletionAllocator;
678b278aafbSDouglas Gregor     }
679b278aafbSDouglas Gregor 
68036835568SCraig Topper     CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo;}
6819d7c0fefSArgyrios Kyrtzidis 
68236e3b5c7SDouglas Gregor   private:
68336e3b5c7SDouglas Gregor     void Finish() {
68436e3b5c7SDouglas Gregor       AllocatedResults.Results = new CXCompletionResult [StoredResults.size()];
68536e3b5c7SDouglas Gregor       AllocatedResults.NumResults = StoredResults.size();
68636e3b5c7SDouglas Gregor       std::memcpy(AllocatedResults.Results, StoredResults.data(),
68736e3b5c7SDouglas Gregor                   StoredResults.size() * sizeof(CXCompletionResult));
68836e3b5c7SDouglas Gregor       StoredResults.clear();
68936e3b5c7SDouglas Gregor     }
6908e984da8SDouglas Gregor   };
691ab9db510SAlexander Kornienko }
6928e984da8SDouglas Gregor 
69311a9cd95SBenjamin Kramer static CXCodeCompleteResults *
69411a9cd95SBenjamin Kramer clang_codeCompleteAt_Impl(CXTranslationUnit TU, const char *complete_filename,
69511a9cd95SBenjamin Kramer                           unsigned complete_line, unsigned complete_column,
69611a9cd95SBenjamin Kramer                           ArrayRef<CXUnsavedFile> unsaved_files,
69711a9cd95SBenjamin Kramer                           unsigned options) {
6983292d06aSDmitri Gribenko   bool IncludeBriefComments = options & CXCodeComplete_IncludeBriefComments;
699bb2cf63bSSam McCall   bool SkipPreamble = options & CXCodeComplete_SkipPreamble;
7003957e48aSIvan Donchevskii   bool IncludeFixIts = options & CXCodeComplete_IncludeCompletionsWithFixIts;
70177af1c56SDaniel Dunbar 
7028e984da8SDouglas Gregor #ifdef UDP_CODE_COMPLETION_LOGGER
7038e984da8SDouglas Gregor #ifdef UDP_CODE_COMPLETION_LOGGER_PORT
7048e984da8SDouglas Gregor   const llvm::TimeRecord &StartTime =  llvm::TimeRecord::getCurrentTime();
7058e984da8SDouglas Gregor #endif
7068e984da8SDouglas Gregor #endif
70769186e73SCraig Topper   bool EnableLogging = getenv("LIBCLANG_CODE_COMPLETION_LOGGING") != nullptr;
7088e984da8SDouglas Gregor 
709852d622eSDmitri Gribenko   if (cxtu::isNotUsableTU(TU)) {
710256454fdSDmitri Gribenko     LOG_BAD_TU(TU);
71111a9cd95SBenjamin Kramer     return nullptr;
712256454fdSDmitri Gribenko   }
713256454fdSDmitri Gribenko 
714c22ea1ceSDmitri Gribenko   ASTUnit *AST = cxtu::getASTUnit(TU);
7158e984da8SDouglas Gregor   if (!AST)
71611a9cd95SBenjamin Kramer     return nullptr;
7178e984da8SDouglas Gregor 
718183436e5SDmitri Gribenko   CIndexer *CXXIdx = TU->CIdx;
7197317a5cbSArgyrios Kyrtzidis   if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
72058d5f3fdSArgyrios Kyrtzidis     setThreadBackgroundPriority();
7217317a5cbSArgyrios Kyrtzidis 
722ca5b0539SDouglas Gregor   ASTUnit::ConcurrencyCheck Check(*AST);
723ca5b0539SDouglas Gregor 
7248e984da8SDouglas Gregor   // Perform the remapping of source files.
7250e62c1ccSChris Lattner   SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
7269d85b18fSAlp Toker 
72711a9cd95SBenjamin Kramer   for (auto &UF : unsaved_files) {
728d87f8d76SRafael Espindola     std::unique_ptr<llvm::MemoryBuffer> MB =
7299d85b18fSAlp Toker         llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
730d87f8d76SRafael Espindola     RemappedFiles.push_back(std::make_pair(UF.Filename, MB.release()));
7318e984da8SDouglas Gregor   }
7328e984da8SDouglas Gregor 
7338e984da8SDouglas Gregor   if (EnableLogging) {
7348e984da8SDouglas Gregor     // FIXME: Add logging.
7358e984da8SDouglas Gregor   }
7368e984da8SDouglas Gregor 
7378e984da8SDouglas Gregor   // Parse the resulting source file to find code-completion results.
7388832c066SBen Langmuir   AllocatedCXCodeCompleteResults *Results = new AllocatedCXCodeCompleteResults(
7398832c066SBen Langmuir       &AST->getFileManager());
74069186e73SCraig Topper   Results->Results = nullptr;
7418e984da8SDouglas Gregor   Results->NumResults = 0;
7428e984da8SDouglas Gregor 
7438e984da8SDouglas Gregor   // Create a code-completion consumer to capture the results.
7443292d06aSDmitri Gribenko   CodeCompleteOptions Opts;
7453292d06aSDmitri Gribenko   Opts.IncludeBriefComments = IncludeBriefComments;
746bb2cf63bSSam McCall   Opts.LoadExternal = !SkipPreamble;
7473957e48aSIvan Donchevskii   Opts.IncludeFixIts = IncludeFixIts;
7483292d06aSDmitri Gribenko   CaptureCompletionResults Capture(Opts, *Results, &TU);
7498e984da8SDouglas Gregor 
7508e984da8SDouglas Gregor   // Perform completion.
751690f0e2fSAlex Lorenz   std::vector<const char *> CArgs;
752690f0e2fSAlex Lorenz   for (const auto &Arg : TU->Arguments)
753690f0e2fSAlex Lorenz     CArgs.push_back(Arg.c_str());
754690f0e2fSAlex Lorenz   std::string CompletionInvocation =
755690f0e2fSAlex Lorenz       llvm::formatv("-code-completion-at={0}:{1}:{2}", complete_filename,
756690f0e2fSAlex Lorenz                     complete_line, complete_column)
757690f0e2fSAlex Lorenz           .str();
758690f0e2fSAlex Lorenz   LibclangInvocationReporter InvocationReporter(
759690f0e2fSAlex Lorenz       *CXXIdx, LibclangInvocationReporter::OperationKind::CompletionOperation,
760690f0e2fSAlex Lorenz       TU->ParsingOptions, CArgs, CompletionInvocation, unsaved_files);
7618e984da8SDouglas Gregor   AST->CodeComplete(complete_filename, complete_line, complete_column,
762bb165fb0SAdrian Prantl                     RemappedFiles, (options & CXCodeComplete_IncludeMacros),
763b68bc59aSDouglas Gregor                     (options & CXCodeComplete_IncludeCodePatterns),
764bb165fb0SAdrian Prantl                     IncludeBriefComments, Capture,
765bb165fb0SAdrian Prantl                     CXXIdx->getPCHContainerOperations(), *Results->Diag,
766bb165fb0SAdrian Prantl                     Results->LangOpts, *Results->SourceMgr, *Results->FileMgr,
767bb165fb0SAdrian Prantl                     Results->Diagnostics, Results->TemporaryBuffers);
7688e984da8SDouglas Gregor 
7697dd96c23SNico Weber   Results->DiagnosticsWrappers.resize(Results->Diagnostics.size());
7707dd96c23SNico Weber 
771162b712dSDouglas Gregor   // Keep a reference to the allocator used for cached global completions, so
772162b712dSDouglas Gregor   // that we can be sure that the memory used by our code completion strings
773162b712dSDouglas Gregor   // doesn't get freed due to subsequent reparses (while the code completion
774162b712dSDouglas Gregor   // results are still active).
775162b712dSDouglas Gregor   Results->CachedCompletionAllocator = AST->getCachedCompletionAllocator();
776162b712dSDouglas Gregor 
7778e984da8SDouglas Gregor 
7788e984da8SDouglas Gregor 
7798e984da8SDouglas Gregor #ifdef UDP_CODE_COMPLETION_LOGGER
7808e984da8SDouglas Gregor #ifdef UDP_CODE_COMPLETION_LOGGER_PORT
7818e984da8SDouglas Gregor   const llvm::TimeRecord &EndTime =  llvm::TimeRecord::getCurrentTime();
782f1a13f29SDylan Noblesmith   SmallString<256> LogResult;
7838e984da8SDouglas Gregor   llvm::raw_svector_ostream os(LogResult);
7848e984da8SDouglas Gregor 
7858e984da8SDouglas Gregor   // Figure out the language and whether or not it uses PCH.
7868e984da8SDouglas Gregor   const char *lang = 0;
7878e984da8SDouglas Gregor   bool usesPCH = false;
7888e984da8SDouglas Gregor 
7898e984da8SDouglas Gregor   for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
7908e984da8SDouglas Gregor        I != E; ++I) {
7918e984da8SDouglas Gregor     if (*I == 0)
7928e984da8SDouglas Gregor       continue;
7938e984da8SDouglas Gregor     if (strcmp(*I, "-x") == 0) {
7948e984da8SDouglas Gregor       if (I + 1 != E) {
7958e984da8SDouglas Gregor         lang = *(++I);
7968e984da8SDouglas Gregor         continue;
7978e984da8SDouglas Gregor       }
7988e984da8SDouglas Gregor     }
7998e984da8SDouglas Gregor     else if (strcmp(*I, "-include") == 0) {
8008e984da8SDouglas Gregor       if (I+1 != E) {
8018e984da8SDouglas Gregor         const char *arg = *(++I);
802f1a13f29SDylan Noblesmith         SmallString<512> pchName;
8038e984da8SDouglas Gregor         {
8048e984da8SDouglas Gregor           llvm::raw_svector_ostream os(pchName);
8058e984da8SDouglas Gregor           os << arg << ".pth";
8068e984da8SDouglas Gregor         }
8078e984da8SDouglas Gregor         pchName.push_back('\0');
8088e984da8SDouglas Gregor         struct stat stat_results;
809ea777403SDouglas Gregor         if (stat(pchName.str().c_str(), &stat_results) == 0)
8108e984da8SDouglas Gregor           usesPCH = true;
8118e984da8SDouglas Gregor         continue;
8128e984da8SDouglas Gregor       }
8138e984da8SDouglas Gregor     }
8148e984da8SDouglas Gregor   }
8158e984da8SDouglas Gregor 
8168e984da8SDouglas Gregor   os << "{ ";
8178e984da8SDouglas Gregor   os << "\"wall\": " << (EndTime.getWallTime() - StartTime.getWallTime());
8188e984da8SDouglas Gregor   os << ", \"numRes\": " << Results->NumResults;
8198e984da8SDouglas Gregor   os << ", \"diags\": " << Results->Diagnostics.size();
8208e984da8SDouglas Gregor   os << ", \"pch\": " << (usesPCH ? "true" : "false");
8218e984da8SDouglas Gregor   os << ", \"lang\": \"" << (lang ? lang : "<unknown>") << '"';
8228e984da8SDouglas Gregor   const char *name = getlogin();
8238e984da8SDouglas Gregor   os << ", \"user\": \"" << (name ? name : "unknown") << '"';
8248e984da8SDouglas Gregor   os << ", \"clangVer\": \"" << getClangFullVersion() << '"';
8258e984da8SDouglas Gregor   os << " }";
8268e984da8SDouglas Gregor 
8270e62c1ccSChris Lattner   StringRef res = os.str();
8288e984da8SDouglas Gregor   if (res.size() > 0) {
8298e984da8SDouglas Gregor     do {
8308e984da8SDouglas Gregor       // Setup the UDP socket.
8318e984da8SDouglas Gregor       struct sockaddr_in servaddr;
8328e984da8SDouglas Gregor       bzero(&servaddr, sizeof(servaddr));
8338e984da8SDouglas Gregor       servaddr.sin_family = AF_INET;
8348e984da8SDouglas Gregor       servaddr.sin_port = htons(UDP_CODE_COMPLETION_LOGGER_PORT);
8358e984da8SDouglas Gregor       if (inet_pton(AF_INET, UDP_CODE_COMPLETION_LOGGER,
8368e984da8SDouglas Gregor                     &servaddr.sin_addr) <= 0)
8378e984da8SDouglas Gregor         break;
8388e984da8SDouglas Gregor 
8398e984da8SDouglas Gregor       int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
8408e984da8SDouglas Gregor       if (sockfd < 0)
8418e984da8SDouglas Gregor         break;
8428e984da8SDouglas Gregor 
8438e984da8SDouglas Gregor       sendto(sockfd, res.data(), res.size(), 0,
8448e984da8SDouglas Gregor              (struct sockaddr *)&servaddr, sizeof(servaddr));
8458e984da8SDouglas Gregor       close(sockfd);
8468e984da8SDouglas Gregor     }
8478e984da8SDouglas Gregor     while (false);
8488e984da8SDouglas Gregor   }
8498e984da8SDouglas Gregor #endif
8508e984da8SDouglas Gregor #endif
85111a9cd95SBenjamin Kramer   return Results;
85277af1c56SDaniel Dunbar }
85311a9cd95SBenjamin Kramer 
85477af1c56SDaniel Dunbar CXCodeCompleteResults *clang_codeCompleteAt(CXTranslationUnit TU,
85577af1c56SDaniel Dunbar                                             const char *complete_filename,
85677af1c56SDaniel Dunbar                                             unsigned complete_line,
85777af1c56SDaniel Dunbar                                             unsigned complete_column,
85877af1c56SDaniel Dunbar                                             struct CXUnsavedFile *unsaved_files,
85977af1c56SDaniel Dunbar                                             unsigned num_unsaved_files,
86077af1c56SDaniel Dunbar                                             unsigned options) {
861ea474358SArgyrios Kyrtzidis   LOG_FUNC_SECTION {
862ea474358SArgyrios Kyrtzidis     *Log << TU << ' '
863ea474358SArgyrios Kyrtzidis          << complete_filename << ':' << complete_line << ':' << complete_column;
864ea474358SArgyrios Kyrtzidis   }
865ea474358SArgyrios Kyrtzidis 
8669d85b18fSAlp Toker   if (num_unsaved_files && !unsaved_files)
8679d85b18fSAlp Toker     return nullptr;
8689d85b18fSAlp Toker 
86911a9cd95SBenjamin Kramer   CXCodeCompleteResults *result;
87011a9cd95SBenjamin Kramer   auto CodeCompleteAtImpl = [=, &result]() {
87111a9cd95SBenjamin Kramer     result = clang_codeCompleteAt_Impl(
87211a9cd95SBenjamin Kramer         TU, complete_filename, complete_line, complete_column,
87311a9cd95SBenjamin Kramer         llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
87411a9cd95SBenjamin Kramer   };
8759999f4f8SArgyrios Kyrtzidis 
87677af1c56SDaniel Dunbar   llvm::CrashRecoveryContext CRC;
87777af1c56SDaniel Dunbar 
87811a9cd95SBenjamin Kramer   if (!RunSafely(CRC, CodeCompleteAtImpl)) {
87977af1c56SDaniel Dunbar     fprintf(stderr, "libclang: crash detected in code completion\n");
880c22ea1ceSDmitri Gribenko     cxtu::getASTUnit(TU)->setUnsafeToFree(true);
88169186e73SCraig Topper     return nullptr;
882af44c781SDouglas Gregor   } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
883af44c781SDouglas Gregor     PrintLibclangResourceUsage(TU);
88477af1c56SDaniel Dunbar 
88511a9cd95SBenjamin Kramer   return result;
8868e984da8SDouglas Gregor }
8878e984da8SDouglas Gregor 
888b68bc59aSDouglas Gregor unsigned clang_defaultCodeCompleteOptions(void) {
889b68bc59aSDouglas Gregor   return CXCodeComplete_IncludeMacros;
890b68bc59aSDouglas Gregor }
891b68bc59aSDouglas Gregor 
892d5a2a073SDaniel Dunbar void clang_disposeCodeCompleteResults(CXCodeCompleteResults *ResultsIn) {
893d5a2a073SDaniel Dunbar   if (!ResultsIn)
894d5a2a073SDaniel Dunbar     return;
895d5a2a073SDaniel Dunbar 
896d5a2a073SDaniel Dunbar   AllocatedCXCodeCompleteResults *Results
897d5a2a073SDaniel Dunbar     = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
898d5a2a073SDaniel Dunbar   delete Results;
899d5a2a073SDaniel Dunbar }
900d5a2a073SDaniel Dunbar 
901d5a2a073SDaniel Dunbar unsigned
902d5a2a073SDaniel Dunbar clang_codeCompleteGetNumDiagnostics(CXCodeCompleteResults *ResultsIn) {
903d5a2a073SDaniel Dunbar   AllocatedCXCodeCompleteResults *Results
904d5a2a073SDaniel Dunbar     = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
905d5a2a073SDaniel Dunbar   if (!Results)
906d5a2a073SDaniel Dunbar     return 0;
907d5a2a073SDaniel Dunbar 
908d5a2a073SDaniel Dunbar   return Results->Diagnostics.size();
909d5a2a073SDaniel Dunbar }
910d5a2a073SDaniel Dunbar 
911d5a2a073SDaniel Dunbar CXDiagnostic
912d5a2a073SDaniel Dunbar clang_codeCompleteGetDiagnostic(CXCodeCompleteResults *ResultsIn,
913d5a2a073SDaniel Dunbar                                 unsigned Index) {
914d5a2a073SDaniel Dunbar   AllocatedCXCodeCompleteResults *Results
915d5a2a073SDaniel Dunbar     = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
916d5a2a073SDaniel Dunbar   if (!Results || Index >= Results->Diagnostics.size())
91769186e73SCraig Topper     return nullptr;
918d5a2a073SDaniel Dunbar 
9197dd96c23SNico Weber   CXStoredDiagnostic *Diag = Results->DiagnosticsWrappers[Index];
9207dd96c23SNico Weber   if (!Diag)
9217dd96c23SNico Weber     Results->DiagnosticsWrappers[Index] = Diag =
9227dd96c23SNico Weber         new CXStoredDiagnostic(Results->Diagnostics[Index], Results->LangOpts);
9237dd96c23SNico Weber   return Diag;
924d5a2a073SDaniel Dunbar }
925d5a2a073SDaniel Dunbar 
9262132584dSDouglas Gregor unsigned long long
9272132584dSDouglas Gregor clang_codeCompleteGetContexts(CXCodeCompleteResults *ResultsIn) {
9282132584dSDouglas Gregor   AllocatedCXCodeCompleteResults *Results
9292132584dSDouglas Gregor     = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
9302132584dSDouglas Gregor   if (!Results)
9312132584dSDouglas Gregor     return 0;
9322132584dSDouglas Gregor 
9332132584dSDouglas Gregor   return Results->Contexts;
9342132584dSDouglas Gregor }
935d5a2a073SDaniel Dunbar 
93663745d59SDouglas Gregor enum CXCursorKind clang_codeCompleteGetContainerKind(
93763745d59SDouglas Gregor                                                CXCodeCompleteResults *ResultsIn,
93863745d59SDouglas Gregor                                                      unsigned *IsIncomplete) {
93963745d59SDouglas Gregor   AllocatedCXCodeCompleteResults *Results =
94063745d59SDouglas Gregor     static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn);
94163745d59SDouglas Gregor   if (!Results)
94263745d59SDouglas Gregor     return CXCursor_InvalidCode;
94363745d59SDouglas Gregor 
94469186e73SCraig Topper   if (IsIncomplete != nullptr) {
94563745d59SDouglas Gregor     *IsIncomplete = Results->ContainerIsIncomplete;
94663745d59SDouglas Gregor   }
94763745d59SDouglas Gregor 
94863745d59SDouglas Gregor   return Results->ContainerKind;
94963745d59SDouglas Gregor }
95063745d59SDouglas Gregor 
95163745d59SDouglas Gregor CXString clang_codeCompleteGetContainerUSR(CXCodeCompleteResults *ResultsIn) {
95263745d59SDouglas Gregor   AllocatedCXCodeCompleteResults *Results =
95363745d59SDouglas Gregor     static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn);
95463745d59SDouglas Gregor   if (!Results)
95536a6dd04SDmitri Gribenko     return cxstring::createEmpty();
95663745d59SDouglas Gregor 
9570b62f8a6SDmitri Gribenko   return cxstring::createRef(Results->ContainerUSR.c_str());
95863745d59SDouglas Gregor }
95963745d59SDouglas Gregor 
960ea777403SDouglas Gregor 
961ea777403SDouglas Gregor CXString clang_codeCompleteGetObjCSelector(CXCodeCompleteResults *ResultsIn) {
962ea777403SDouglas Gregor   AllocatedCXCodeCompleteResults *Results =
963ea777403SDouglas Gregor     static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn);
964ea777403SDouglas Gregor   if (!Results)
96536a6dd04SDmitri Gribenko     return cxstring::createEmpty();
966ea777403SDouglas Gregor 
9672f23e9c5SDmitri Gribenko   return cxstring::createDup(Results->Selector);
968ea777403SDouglas Gregor }
969ea777403SDouglas Gregor 
9709fc8faf9SAdrian Prantl /// Simple utility function that appends a \p New string to the given
9718e3e8743SDouglas Gregor /// \p Old string, using the \p Buffer for storage.
9728e3e8743SDouglas Gregor ///
9738e3e8743SDouglas Gregor /// \param Old The string to which we are appending. This parameter will be
9748e3e8743SDouglas Gregor /// updated to reflect the complete string.
9758e3e8743SDouglas Gregor ///
9768e3e8743SDouglas Gregor ///
9778e3e8743SDouglas Gregor /// \param New The string to append to \p Old.
9788e3e8743SDouglas Gregor ///
9798e3e8743SDouglas Gregor /// \param Buffer A buffer that stores the actual, concatenated string. It will
9808e3e8743SDouglas Gregor /// be used if the old string is already-non-empty.
9810e62c1ccSChris Lattner static void AppendToString(StringRef &Old, StringRef New,
982f1a13f29SDylan Noblesmith                            SmallString<256> &Buffer) {
9838e3e8743SDouglas Gregor   if (Old.empty()) {
9848e3e8743SDouglas Gregor     Old = New;
9858e3e8743SDouglas Gregor     return;
9868e3e8743SDouglas Gregor   }
9878e3e8743SDouglas Gregor 
9888e3e8743SDouglas Gregor   if (Buffer.empty())
9898e3e8743SDouglas Gregor     Buffer.append(Old.begin(), Old.end());
9908e3e8743SDouglas Gregor   Buffer.append(New.begin(), New.end());
9918e3e8743SDouglas Gregor   Old = Buffer.str();
9928e3e8743SDouglas Gregor }
9938e3e8743SDouglas Gregor 
9949fc8faf9SAdrian Prantl /// Get the typed-text blocks from the given code-completion string
9958e3e8743SDouglas Gregor /// and return them as a single string.
9968e3e8743SDouglas Gregor ///
9978e3e8743SDouglas Gregor /// \param String The code-completion string whose typed-text blocks will be
9988e3e8743SDouglas Gregor /// concatenated.
9998e3e8743SDouglas Gregor ///
10008e3e8743SDouglas Gregor /// \param Buffer A buffer used for storage of the completed name.
10010e62c1ccSChris Lattner static StringRef GetTypedName(CodeCompletionString *String,
1002f1a13f29SDylan Noblesmith                                     SmallString<256> &Buffer) {
10030e62c1ccSChris Lattner   StringRef Result;
10048e3e8743SDouglas Gregor   for (CodeCompletionString::iterator C = String->begin(), CEnd = String->end();
10058e3e8743SDouglas Gregor        C != CEnd; ++C) {
10068e3e8743SDouglas Gregor     if (C->Kind == CodeCompletionString::CK_TypedText)
10078e3e8743SDouglas Gregor       AppendToString(Result, C->Text, Buffer);
10088e3e8743SDouglas Gregor   }
10098e3e8743SDouglas Gregor 
10108e3e8743SDouglas Gregor   return Result;
10118e3e8743SDouglas Gregor }
10128e3e8743SDouglas Gregor 
101349f67ce4SDouglas Gregor namespace {
101449f67ce4SDouglas Gregor   struct OrderCompletionResults {
101549f67ce4SDouglas Gregor     bool operator()(const CXCompletionResult &XR,
101649f67ce4SDouglas Gregor                     const CXCompletionResult &YR) const {
1017b278aafbSDouglas Gregor       CodeCompletionString *X
1018b278aafbSDouglas Gregor         = (CodeCompletionString *)XR.CompletionString;
1019b278aafbSDouglas Gregor       CodeCompletionString *Y
1020b278aafbSDouglas Gregor         = (CodeCompletionString *)YR.CompletionString;
102149f67ce4SDouglas Gregor 
1022f1a13f29SDylan Noblesmith       SmallString<256> XBuffer;
10230e62c1ccSChris Lattner       StringRef XText = GetTypedName(X, XBuffer);
1024f1a13f29SDylan Noblesmith       SmallString<256> YBuffer;
10250e62c1ccSChris Lattner       StringRef YText = GetTypedName(Y, YBuffer);
102649f67ce4SDouglas Gregor 
10278e3e8743SDouglas Gregor       if (XText.empty() || YText.empty())
10288e3e8743SDouglas Gregor         return !XText.empty();
10298e3e8743SDouglas Gregor 
10308e3e8743SDouglas Gregor       int result = XText.compare_lower(YText);
103149f67ce4SDouglas Gregor       if (result < 0)
103249f67ce4SDouglas Gregor         return true;
103349f67ce4SDouglas Gregor       if (result > 0)
103449f67ce4SDouglas Gregor         return false;
103549f67ce4SDouglas Gregor 
10368e3e8743SDouglas Gregor       result = XText.compare(YText);
1037c7a7d92aSDouglas Gregor       return result < 0;
103849f67ce4SDouglas Gregor     }
103949f67ce4SDouglas Gregor   };
1040ab9db510SAlexander Kornienko }
104149f67ce4SDouglas Gregor 
104249f67ce4SDouglas Gregor void clang_sortCodeCompletionResults(CXCompletionResult *Results,
104349f67ce4SDouglas Gregor                                      unsigned NumResults) {
104449f67ce4SDouglas Gregor   std::stable_sort(Results, Results + NumResults, OrderCompletionResults());
104549f67ce4SDouglas Gregor }
1046