1d5a2a073SDaniel Dunbar //===- CIndexCodeCompletion.cpp - Code Completion API hooks ---------------===//
2d5a2a073SDaniel Dunbar //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6d5a2a073SDaniel Dunbar //
7d5a2a073SDaniel Dunbar //===----------------------------------------------------------------------===//
8d5a2a073SDaniel Dunbar //
9d5a2a073SDaniel Dunbar // This file implements the Clang-C Source Indexing library hooks for
10d5a2a073SDaniel Dunbar // code completion.
11d5a2a073SDaniel Dunbar //
12d5a2a073SDaniel Dunbar //===----------------------------------------------------------------------===//
13d5a2a073SDaniel Dunbar 
14d5a2a073SDaniel Dunbar #include "CIndexer.h"
15cc0694c8SChandler Carruth #include "CIndexDiagnostic.h"
164b41745eSChandler Carruth #include "CLog.h"
1763745d59SDouglas Gregor #include "CXCursor.h"
183957e48aSIvan Donchevskii #include "CXSourceLocation.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/Sema/CodeCompleteConsumer.h"
290a4e61f8SDavid Blaikie #include "clang/Sema/Sema.h"
30028d3e4dSDouglas Gregor #include "llvm/ADT/SmallString.h"
31d5a2a073SDaniel Dunbar #include "llvm/ADT/StringExtras.h"
3277af1c56SDaniel Dunbar #include "llvm/Support/CrashRecoveryContext.h"
33b34c1fdfSRafael Espindola #include "llvm/Support/FileSystem.h"
34690f0e2fSAlex Lorenz #include "llvm/Support/FormatVariadic.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 enum CXCompletionChunkKind
57d5a2a073SDaniel Dunbar clang_getCompletionChunkKind(CXCompletionString completion_string,
58d5a2a073SDaniel Dunbar                              unsigned chunk_number) {
59b278aafbSDouglas Gregor   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
60d5a2a073SDaniel Dunbar   if (!CCStr || chunk_number >= CCStr->size())
61d5a2a073SDaniel Dunbar     return CXCompletionChunk_Text;
62d5a2a073SDaniel Dunbar 
63d5a2a073SDaniel Dunbar   switch ((*CCStr)[chunk_number].Kind) {
64d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_TypedText:
65d5a2a073SDaniel Dunbar     return CXCompletionChunk_TypedText;
66d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Text:
67d5a2a073SDaniel Dunbar     return CXCompletionChunk_Text;
68d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Optional:
69d5a2a073SDaniel Dunbar     return CXCompletionChunk_Optional;
70d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Placeholder:
71d5a2a073SDaniel Dunbar     return CXCompletionChunk_Placeholder;
72d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Informative:
73d5a2a073SDaniel Dunbar     return CXCompletionChunk_Informative;
74d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_ResultType:
75d5a2a073SDaniel Dunbar     return CXCompletionChunk_ResultType;
76d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_CurrentParameter:
77d5a2a073SDaniel Dunbar     return CXCompletionChunk_CurrentParameter;
78d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftParen:
79d5a2a073SDaniel Dunbar     return CXCompletionChunk_LeftParen;
80d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightParen:
81d5a2a073SDaniel Dunbar     return CXCompletionChunk_RightParen;
82d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftBracket:
83d5a2a073SDaniel Dunbar     return CXCompletionChunk_LeftBracket;
84d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightBracket:
85d5a2a073SDaniel Dunbar     return CXCompletionChunk_RightBracket;
86d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftBrace:
87d5a2a073SDaniel Dunbar     return CXCompletionChunk_LeftBrace;
88d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightBrace:
89d5a2a073SDaniel Dunbar     return CXCompletionChunk_RightBrace;
90d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftAngle:
91d5a2a073SDaniel Dunbar     return CXCompletionChunk_LeftAngle;
92d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightAngle:
93d5a2a073SDaniel Dunbar     return CXCompletionChunk_RightAngle;
94d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Comma:
95d5a2a073SDaniel Dunbar     return CXCompletionChunk_Comma;
96d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Colon:
97d5a2a073SDaniel Dunbar     return CXCompletionChunk_Colon;
98d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_SemiColon:
99d5a2a073SDaniel Dunbar     return CXCompletionChunk_SemiColon;
100d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Equal:
101d5a2a073SDaniel Dunbar     return CXCompletionChunk_Equal;
102d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_HorizontalSpace:
103d5a2a073SDaniel Dunbar     return CXCompletionChunk_HorizontalSpace;
104d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_VerticalSpace:
105d5a2a073SDaniel Dunbar     return CXCompletionChunk_VerticalSpace;
106d5a2a073SDaniel Dunbar   }
107d5a2a073SDaniel Dunbar 
1088a40f700SDavid Blaikie   llvm_unreachable("Invalid CompletionKind!");
109d5a2a073SDaniel Dunbar }
110d5a2a073SDaniel Dunbar 
111d5a2a073SDaniel Dunbar CXString clang_getCompletionChunkText(CXCompletionString completion_string,
112d5a2a073SDaniel Dunbar                                       unsigned chunk_number) {
113b278aafbSDouglas Gregor   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
114d5a2a073SDaniel Dunbar   if (!CCStr || chunk_number >= CCStr->size())
115f98dfbaeSDmitri Gribenko     return cxstring::createNull();
116d5a2a073SDaniel Dunbar 
117d5a2a073SDaniel Dunbar   switch ((*CCStr)[chunk_number].Kind) {
118d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_TypedText:
119d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Text:
120d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Placeholder:
121d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_CurrentParameter:
122d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Informative:
123d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftParen:
124d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightParen:
125d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftBracket:
126d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightBracket:
127d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftBrace:
128d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightBrace:
129d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftAngle:
130d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightAngle:
131d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Comma:
132d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_ResultType:
133d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Colon:
134d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_SemiColon:
135d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Equal:
136d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_HorizontalSpace:
13709737ee8SDouglas Gregor   case CodeCompletionString::CK_VerticalSpace:
1383c66b0beSDmitri Gribenko     return cxstring::createRef((*CCStr)[chunk_number].Text);
13909737ee8SDouglas Gregor 
140d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Optional:
141d5a2a073SDaniel Dunbar     // Note: treated as an empty text block.
14236a6dd04SDmitri Gribenko     return cxstring::createEmpty();
143d5a2a073SDaniel Dunbar   }
144d5a2a073SDaniel Dunbar 
145e4d798f0SDavid Blaikie   llvm_unreachable("Invalid CodeCompletionString Kind!");
146d5a2a073SDaniel Dunbar }
147d5a2a073SDaniel Dunbar 
148d5a2a073SDaniel Dunbar 
149d5a2a073SDaniel Dunbar CXCompletionString
150d5a2a073SDaniel Dunbar clang_getCompletionChunkCompletionString(CXCompletionString completion_string,
151d5a2a073SDaniel Dunbar                                          unsigned chunk_number) {
152b278aafbSDouglas Gregor   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
153d5a2a073SDaniel Dunbar   if (!CCStr || chunk_number >= CCStr->size())
15469186e73SCraig Topper     return nullptr;
155d5a2a073SDaniel Dunbar 
156d5a2a073SDaniel Dunbar   switch ((*CCStr)[chunk_number].Kind) {
157d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_TypedText:
158d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Text:
159d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Placeholder:
160d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_CurrentParameter:
161d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Informative:
162d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftParen:
163d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightParen:
164d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftBracket:
165d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightBracket:
166d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftBrace:
167d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightBrace:
168d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftAngle:
169d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightAngle:
170d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Comma:
171d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_ResultType:
172d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Colon:
173d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_SemiColon:
174d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Equal:
175d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_HorizontalSpace:
176d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_VerticalSpace:
17769186e73SCraig Topper     return nullptr;
178d5a2a073SDaniel Dunbar 
179d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Optional:
180d5a2a073SDaniel Dunbar     // Note: treated as an empty text block.
181d5a2a073SDaniel Dunbar     return (*CCStr)[chunk_number].Optional;
182d5a2a073SDaniel Dunbar   }
183d5a2a073SDaniel Dunbar 
1848a40f700SDavid Blaikie   llvm_unreachable("Invalid CompletionKind!");
185d5a2a073SDaniel Dunbar }
186d5a2a073SDaniel Dunbar 
187d5a2a073SDaniel Dunbar unsigned clang_getNumCompletionChunks(CXCompletionString completion_string) {
188b278aafbSDouglas Gregor   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
189d5a2a073SDaniel Dunbar   return CCStr? CCStr->size() : 0;
190d5a2a073SDaniel Dunbar }
191d5a2a073SDaniel Dunbar 
192a2db793fSDouglas Gregor unsigned clang_getCompletionPriority(CXCompletionString completion_string) {
193b278aafbSDouglas Gregor   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
19447bb3e2bSBill Wendling   return CCStr? CCStr->getPriority() : unsigned(CCP_Unlikely);
195a2db793fSDouglas Gregor }
196a2db793fSDouglas Gregor 
197f757a12dSDouglas Gregor enum CXAvailabilityKind
198f757a12dSDouglas Gregor clang_getCompletionAvailability(CXCompletionString completion_string) {
199b278aafbSDouglas Gregor   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
200b278aafbSDouglas Gregor   return CCStr? static_cast<CXAvailabilityKind>(CCStr->getAvailability())
201b278aafbSDouglas Gregor               : CXAvailability_Available;
202f757a12dSDouglas Gregor }
203f757a12dSDouglas Gregor 
20498ea7f67SErik Verbruggen unsigned clang_getCompletionNumAnnotations(CXCompletionString completion_string)
20598ea7f67SErik Verbruggen {
20698ea7f67SErik Verbruggen   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
20798ea7f67SErik Verbruggen   return CCStr ? CCStr->getAnnotationCount() : 0;
20898ea7f67SErik Verbruggen }
20998ea7f67SErik Verbruggen 
21098ea7f67SErik Verbruggen CXString clang_getCompletionAnnotation(CXCompletionString completion_string,
21198ea7f67SErik Verbruggen                                        unsigned annotation_number) {
21298ea7f67SErik Verbruggen   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
2133c66b0beSDmitri Gribenko   return CCStr ? cxstring::createRef(CCStr->getAnnotation(annotation_number))
214f98dfbaeSDmitri Gribenko                : cxstring::createNull();
21598ea7f67SErik Verbruggen }
21698ea7f67SErik Verbruggen 
21778254c88SDouglas Gregor CXString
21878254c88SDouglas Gregor clang_getCompletionParent(CXCompletionString completion_string,
21978254c88SDouglas Gregor                           CXCursorKind *kind) {
22078254c88SDouglas Gregor   if (kind)
22178254c88SDouglas Gregor     *kind = CXCursor_NotImplemented;
22278254c88SDouglas Gregor 
22378254c88SDouglas Gregor   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
22478254c88SDouglas Gregor   if (!CCStr)
225f98dfbaeSDmitri Gribenko     return cxstring::createNull();
22678254c88SDouglas Gregor 
2272f23e9c5SDmitri Gribenko   return cxstring::createRef(CCStr->getParentContextName());
22878254c88SDouglas Gregor }
22998ea7f67SErik Verbruggen 
2303292d06aSDmitri Gribenko CXString
2313292d06aSDmitri Gribenko clang_getCompletionBriefComment(CXCompletionString completion_string) {
2323292d06aSDmitri Gribenko   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
2333292d06aSDmitri Gribenko 
2343292d06aSDmitri Gribenko   if (!CCStr)
235f98dfbaeSDmitri Gribenko     return cxstring::createNull();
2363292d06aSDmitri Gribenko 
2373c66b0beSDmitri Gribenko   return cxstring::createRef(CCStr->getBriefComment());
2383292d06aSDmitri Gribenko }
2393292d06aSDmitri Gribenko 
240ba4c85e5SBenjamin Kramer namespace {
2413292d06aSDmitri Gribenko 
2429fc8faf9SAdrian Prantl /// The CXCodeCompleteResults structure we allocate internally;
243d5a2a073SDaniel Dunbar /// the client only sees the initial CXCodeCompleteResults structure.
2440b62f8a6SDmitri Gribenko ///
2450b62f8a6SDmitri Gribenko /// Normally, clients of CXString shouldn't care whether or not a CXString is
2460b62f8a6SDmitri Gribenko /// managed by a pool or by explicitly malloc'ed memory.  But
2470b62f8a6SDmitri Gribenko /// AllocatedCXCodeCompleteResults outlives the CXTranslationUnit, so we can
2480b62f8a6SDmitri Gribenko /// not rely on the StringPool in the TU.
249d5a2a073SDaniel Dunbar struct AllocatedCXCodeCompleteResults : public CXCodeCompleteResults {
2508832c066SBen Langmuir   AllocatedCXCodeCompleteResults(IntrusiveRefCntPtr<FileManager> FileMgr);
251d5a2a073SDaniel Dunbar   ~AllocatedCXCodeCompleteResults();
252d5a2a073SDaniel Dunbar 
2539fc8faf9SAdrian Prantl   /// Diagnostics produced while performing code completion.
2540e62c1ccSChris Lattner   SmallVector<StoredDiagnostic, 8> Diagnostics;
255d5a2a073SDaniel Dunbar 
2569fc8faf9SAdrian Prantl   /// Allocated API-exposed wrappters for Diagnostics.
2577dd96c23SNico Weber   SmallVector<CXStoredDiagnostic *, 8> DiagnosticsWrappers;
2587dd96c23SNico Weber 
259811db4eaSDouglas Gregor   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts;
260811db4eaSDouglas Gregor 
2619fc8faf9SAdrian Prantl   /// Diag object
262c95d8192SDylan Noblesmith   IntrusiveRefCntPtr<DiagnosticsEngine> Diag;
263d5a2a073SDaniel Dunbar 
2649fc8faf9SAdrian Prantl   /// Language options used to adjust source locations.
265d5a2a073SDaniel Dunbar   LangOptions LangOpts;
266d5a2a073SDaniel Dunbar 
2679fc8faf9SAdrian Prantl   /// File manager, used for diagnostics.
268c95d8192SDylan Noblesmith   IntrusiveRefCntPtr<FileManager> FileMgr;
269d5a2a073SDaniel Dunbar 
2709fc8faf9SAdrian Prantl   /// Source manager, used for diagnostics.
271c95d8192SDylan Noblesmith   IntrusiveRefCntPtr<SourceManager> SourceMgr;
27271731d6bSArgyrios Kyrtzidis 
2739fc8faf9SAdrian Prantl   /// Temporary buffers that will be deleted once we have finished with
2743f5a9efbSChris Lattner   /// the code-completion results.
2750e62c1ccSChris Lattner   SmallVector<const llvm::MemoryBuffer *, 1> TemporaryBuffers;
276b278aafbSDouglas Gregor 
2779fc8faf9SAdrian Prantl   /// Allocator used to store globally cached code-completion results.
278ea4395ebSDavid Blaikie   std::shared_ptr<clang::GlobalCodeCompletionAllocator>
279162b712dSDouglas Gregor       CachedCompletionAllocator;
280162b712dSDouglas Gregor 
2819fc8faf9SAdrian Prantl   /// Allocator used to store code completion results.
282ea4395ebSDavid Blaikie   std::shared_ptr<clang::GlobalCodeCompletionAllocator> CodeCompletionAllocator;
2832132584dSDouglas Gregor 
2849fc8faf9SAdrian Prantl   /// Context under which completion occurred.
2852132584dSDouglas Gregor   enum clang::CodeCompletionContext::Kind ContextKind;
2862132584dSDouglas Gregor 
2879fc8faf9SAdrian Prantl   /// A bitfield representing the acceptable completions for the
2882132584dSDouglas Gregor   /// current context.
2892132584dSDouglas Gregor   unsigned long long Contexts;
29063745d59SDouglas Gregor 
2919fc8faf9SAdrian Prantl   /// The kind of the container for the current context for completions.
29263745d59SDouglas Gregor   enum CXCursorKind ContainerKind;
2930b62f8a6SDmitri Gribenko 
2949fc8faf9SAdrian Prantl   /// The USR of the container for the current context for completions.
2950b62f8a6SDmitri Gribenko   std::string ContainerUSR;
2960b62f8a6SDmitri Gribenko 
2979fc8faf9SAdrian Prantl   /// a boolean value indicating whether there is complete information
298ea777403SDouglas Gregor   /// about the container
29963745d59SDouglas Gregor   unsigned ContainerIsIncomplete;
300ea777403SDouglas Gregor 
3019fc8faf9SAdrian Prantl   /// A string containing the Objective-C selector entered thus far for a
302ea777403SDouglas Gregor   /// message send.
303ea777403SDouglas Gregor   std::string Selector;
3043957e48aSIvan Donchevskii 
3053957e48aSIvan Donchevskii   /// Vector of fix-its for each completion result that *must* be applied
3063957e48aSIvan Donchevskii   /// before that result for the corresponding completion item.
3073957e48aSIvan Donchevskii   std::vector<std::vector<FixItHint>> FixItsVector;
308d5a2a073SDaniel Dunbar };
309d5a2a073SDaniel Dunbar 
310ba4c85e5SBenjamin Kramer } // end anonymous namespace
311ba4c85e5SBenjamin Kramer 
3123957e48aSIvan Donchevskii unsigned clang_getCompletionNumFixIts(CXCodeCompleteResults *results,
3133957e48aSIvan Donchevskii                                       unsigned completion_index) {
3143957e48aSIvan Donchevskii   AllocatedCXCodeCompleteResults *allocated_results = (AllocatedCXCodeCompleteResults *)results;
3153957e48aSIvan Donchevskii 
3163957e48aSIvan Donchevskii   if (!allocated_results || allocated_results->FixItsVector.size() <= completion_index)
3173957e48aSIvan Donchevskii     return 0;
3183957e48aSIvan Donchevskii 
3193957e48aSIvan Donchevskii   return static_cast<unsigned>(allocated_results->FixItsVector[completion_index].size());
3203957e48aSIvan Donchevskii }
3213957e48aSIvan Donchevskii 
3223957e48aSIvan Donchevskii CXString clang_getCompletionFixIt(CXCodeCompleteResults *results,
3233957e48aSIvan Donchevskii                                   unsigned completion_index,
3243957e48aSIvan Donchevskii                                   unsigned fixit_index,
3253957e48aSIvan Donchevskii                                   CXSourceRange *replacement_range) {
3263957e48aSIvan Donchevskii   AllocatedCXCodeCompleteResults *allocated_results = (AllocatedCXCodeCompleteResults *)results;
3273957e48aSIvan Donchevskii 
3283957e48aSIvan Donchevskii   if (!allocated_results || allocated_results->FixItsVector.size() <= completion_index) {
3293957e48aSIvan Donchevskii     if (replacement_range)
3303957e48aSIvan Donchevskii       *replacement_range = clang_getNullRange();
3313957e48aSIvan Donchevskii     return cxstring::createNull();
3323957e48aSIvan Donchevskii   }
3333957e48aSIvan Donchevskii 
3343957e48aSIvan Donchevskii   ArrayRef<FixItHint> FixIts = allocated_results->FixItsVector[completion_index];
3353957e48aSIvan Donchevskii   if (FixIts.size() <= fixit_index) {
3363957e48aSIvan Donchevskii     if (replacement_range)
3373957e48aSIvan Donchevskii       *replacement_range = clang_getNullRange();
3383957e48aSIvan Donchevskii     return cxstring::createNull();
3393957e48aSIvan Donchevskii   }
3403957e48aSIvan Donchevskii 
3413957e48aSIvan Donchevskii   const FixItHint &FixIt = FixIts[fixit_index];
3423957e48aSIvan Donchevskii   if (replacement_range) {
3433957e48aSIvan Donchevskii     *replacement_range = cxloc::translateSourceRange(
3443957e48aSIvan Donchevskii         *allocated_results->SourceMgr, allocated_results->LangOpts,
3453957e48aSIvan Donchevskii         FixIt.RemoveRange);
3463957e48aSIvan Donchevskii   }
3473957e48aSIvan Donchevskii 
3483957e48aSIvan Donchevskii   return cxstring::createRef(FixIt.CodeToInsert.c_str());
3493957e48aSIvan Donchevskii }
3503957e48aSIvan Donchevskii 
3519fc8faf9SAdrian Prantl /// Tracks the number of code-completion result objects that are
35268dbaeadSDouglas Gregor /// currently active.
35368dbaeadSDouglas Gregor ///
35468dbaeadSDouglas Gregor /// Used for debugging purposes only.
3554527fb2fSBenjamin Kramer static std::atomic<unsigned> CodeCompletionResultObjects;
35668dbaeadSDouglas Gregor 
357c30dcecbSAnders Carlsson AllocatedCXCodeCompleteResults::AllocatedCXCodeCompleteResults(
3588832c066SBen Langmuir     IntrusiveRefCntPtr<FileManager> FileMgr)
359ea4395ebSDavid Blaikie     : CXCodeCompleteResults(), DiagOpts(new DiagnosticOptions),
3609c902b55SDavid Blaikie       Diag(new DiagnosticsEngine(
3618832c066SBen Langmuir           IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), &*DiagOpts)),
362f6021ecdSBenjamin Kramer       FileMgr(std::move(FileMgr)),
363f6021ecdSBenjamin Kramer       SourceMgr(new SourceManager(*Diag, *this->FileMgr)),
364ea4395ebSDavid Blaikie       CodeCompletionAllocator(
365ea4395ebSDavid Blaikie           std::make_shared<clang::GlobalCodeCompletionAllocator>()),
366e442fe3dSDouglas Gregor       Contexts(CXCompletionContext_Unknown),
3678832c066SBen Langmuir       ContainerKind(CXCursor_InvalidCode), ContainerIsIncomplete(1) {
3684527fb2fSBenjamin Kramer   if (getenv("LIBCLANG_OBJTRACKING"))
3694527fb2fSBenjamin Kramer     fprintf(stderr, "+++ %u completion results\n",
3704527fb2fSBenjamin Kramer             ++CodeCompletionResultObjects);
37168dbaeadSDouglas Gregor }
372d5a2a073SDaniel Dunbar 
373d5a2a073SDaniel Dunbar AllocatedCXCodeCompleteResults::~AllocatedCXCodeCompleteResults() {
3747dd96c23SNico Weber   llvm::DeleteContainerPointers(DiagnosticsWrappers);
375d5a2a073SDaniel Dunbar   delete [] Results;
376d5a2a073SDaniel Dunbar 
377d8a5dba9SDouglas Gregor   for (unsigned I = 0, N = TemporaryBuffers.size(); I != N; ++I)
378d8a5dba9SDouglas Gregor     delete TemporaryBuffers[I];
37968dbaeadSDouglas Gregor 
3804527fb2fSBenjamin Kramer   if (getenv("LIBCLANG_OBJTRACKING"))
3814527fb2fSBenjamin Kramer     fprintf(stderr, "--- %u completion results\n",
3824527fb2fSBenjamin Kramer             --CodeCompletionResultObjects);
383d5a2a073SDaniel Dunbar }
384d5a2a073SDaniel Dunbar 
3852132584dSDouglas Gregor static unsigned long long getContextsForContextKind(
3862132584dSDouglas Gregor                                           enum CodeCompletionContext::Kind kind,
3872132584dSDouglas Gregor                                                     Sema &S) {
3882132584dSDouglas Gregor   unsigned long long contexts = 0;
3892132584dSDouglas Gregor   switch (kind) {
3902132584dSDouglas Gregor     case CodeCompletionContext::CCC_OtherWithMacros: {
3912132584dSDouglas Gregor       //We can allow macros here, but we don't know what else is permissible
3922132584dSDouglas Gregor       //So we'll say the only thing permissible are macros
3932132584dSDouglas Gregor       contexts = CXCompletionContext_MacroName;
3942132584dSDouglas Gregor       break;
3952132584dSDouglas Gregor     }
3962132584dSDouglas Gregor     case CodeCompletionContext::CCC_TopLevel:
3972132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCIvarList:
3982132584dSDouglas Gregor     case CodeCompletionContext::CCC_ClassStructUnion:
3992132584dSDouglas Gregor     case CodeCompletionContext::CCC_Type: {
4002132584dSDouglas Gregor       contexts = CXCompletionContext_AnyType |
4012132584dSDouglas Gregor                  CXCompletionContext_ObjCInterface;
402bbafb8a7SDavid Blaikie       if (S.getLangOpts().CPlusPlus) {
4032132584dSDouglas Gregor         contexts |= CXCompletionContext_EnumTag |
4042132584dSDouglas Gregor                     CXCompletionContext_UnionTag |
4052132584dSDouglas Gregor                     CXCompletionContext_StructTag |
4062132584dSDouglas Gregor                     CXCompletionContext_ClassTag |
4072132584dSDouglas Gregor                     CXCompletionContext_NestedNameSpecifier;
4082132584dSDouglas Gregor       }
4092132584dSDouglas Gregor       break;
4102132584dSDouglas Gregor     }
4112132584dSDouglas Gregor     case CodeCompletionContext::CCC_Statement: {
4122132584dSDouglas Gregor       contexts = CXCompletionContext_AnyType |
4132132584dSDouglas Gregor                  CXCompletionContext_ObjCInterface |
4142132584dSDouglas Gregor                  CXCompletionContext_AnyValue;
415bbafb8a7SDavid Blaikie       if (S.getLangOpts().CPlusPlus) {
4162132584dSDouglas Gregor         contexts |= CXCompletionContext_EnumTag |
4172132584dSDouglas Gregor                     CXCompletionContext_UnionTag |
4182132584dSDouglas Gregor                     CXCompletionContext_StructTag |
4192132584dSDouglas Gregor                     CXCompletionContext_ClassTag |
4202132584dSDouglas Gregor                     CXCompletionContext_NestedNameSpecifier;
4212132584dSDouglas Gregor       }
4222132584dSDouglas Gregor       break;
4232132584dSDouglas Gregor     }
4242132584dSDouglas Gregor     case CodeCompletionContext::CCC_Expression: {
4252132584dSDouglas Gregor       contexts = CXCompletionContext_AnyValue;
426bbafb8a7SDavid Blaikie       if (S.getLangOpts().CPlusPlus) {
4272132584dSDouglas Gregor         contexts |= CXCompletionContext_AnyType |
4282132584dSDouglas Gregor                     CXCompletionContext_ObjCInterface |
4292132584dSDouglas Gregor                     CXCompletionContext_EnumTag |
4302132584dSDouglas Gregor                     CXCompletionContext_UnionTag |
4312132584dSDouglas Gregor                     CXCompletionContext_StructTag |
4322132584dSDouglas Gregor                     CXCompletionContext_ClassTag |
4332132584dSDouglas Gregor                     CXCompletionContext_NestedNameSpecifier;
4342132584dSDouglas Gregor       }
4352132584dSDouglas Gregor       break;
4362132584dSDouglas Gregor     }
4372132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCMessageReceiver: {
4382132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCObjectValue |
4392132584dSDouglas Gregor                  CXCompletionContext_ObjCSelectorValue |
4402132584dSDouglas Gregor                  CXCompletionContext_ObjCInterface;
441bbafb8a7SDavid Blaikie       if (S.getLangOpts().CPlusPlus) {
4422132584dSDouglas Gregor         contexts |= CXCompletionContext_CXXClassTypeValue |
4432132584dSDouglas Gregor                     CXCompletionContext_AnyType |
4442132584dSDouglas Gregor                     CXCompletionContext_EnumTag |
4452132584dSDouglas Gregor                     CXCompletionContext_UnionTag |
4462132584dSDouglas Gregor                     CXCompletionContext_StructTag |
4472132584dSDouglas Gregor                     CXCompletionContext_ClassTag |
4482132584dSDouglas Gregor                     CXCompletionContext_NestedNameSpecifier;
4492132584dSDouglas Gregor       }
4502132584dSDouglas Gregor       break;
4512132584dSDouglas Gregor     }
4522132584dSDouglas Gregor     case CodeCompletionContext::CCC_DotMemberAccess: {
4532132584dSDouglas Gregor       contexts = CXCompletionContext_DotMemberAccess;
4542132584dSDouglas Gregor       break;
4552132584dSDouglas Gregor     }
4562132584dSDouglas Gregor     case CodeCompletionContext::CCC_ArrowMemberAccess: {
4572132584dSDouglas Gregor       contexts = CXCompletionContext_ArrowMemberAccess;
4582132584dSDouglas Gregor       break;
4592132584dSDouglas Gregor     }
4602132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCPropertyAccess: {
4612132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCPropertyAccess;
4622132584dSDouglas Gregor       break;
4632132584dSDouglas Gregor     }
4642132584dSDouglas Gregor     case CodeCompletionContext::CCC_EnumTag: {
4652132584dSDouglas Gregor       contexts = CXCompletionContext_EnumTag |
4662132584dSDouglas Gregor                  CXCompletionContext_NestedNameSpecifier;
4672132584dSDouglas Gregor       break;
4682132584dSDouglas Gregor     }
4692132584dSDouglas Gregor     case CodeCompletionContext::CCC_UnionTag: {
4702132584dSDouglas Gregor       contexts = CXCompletionContext_UnionTag |
4712132584dSDouglas Gregor                  CXCompletionContext_NestedNameSpecifier;
4722132584dSDouglas Gregor       break;
4732132584dSDouglas Gregor     }
4742132584dSDouglas Gregor     case CodeCompletionContext::CCC_ClassOrStructTag: {
4752132584dSDouglas Gregor       contexts = CXCompletionContext_StructTag |
4762132584dSDouglas Gregor                  CXCompletionContext_ClassTag |
4772132584dSDouglas Gregor                  CXCompletionContext_NestedNameSpecifier;
4782132584dSDouglas Gregor       break;
4792132584dSDouglas Gregor     }
4802132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCProtocolName: {
4812132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCProtocol;
4822132584dSDouglas Gregor       break;
4832132584dSDouglas Gregor     }
4842132584dSDouglas Gregor     case CodeCompletionContext::CCC_Namespace: {
4852132584dSDouglas Gregor       contexts = CXCompletionContext_Namespace;
4862132584dSDouglas Gregor       break;
4872132584dSDouglas Gregor     }
488b006e099SKadir Cetinkaya     case CodeCompletionContext::CCC_SymbolOrNewName:
489b006e099SKadir Cetinkaya     case CodeCompletionContext::CCC_Symbol: {
4902132584dSDouglas Gregor       contexts = CXCompletionContext_NestedNameSpecifier;
4912132584dSDouglas Gregor       break;
4922132584dSDouglas Gregor     }
4932132584dSDouglas Gregor     case CodeCompletionContext::CCC_MacroNameUse: {
4942132584dSDouglas Gregor       contexts = CXCompletionContext_MacroName;
4952132584dSDouglas Gregor       break;
4962132584dSDouglas Gregor     }
4972132584dSDouglas Gregor     case CodeCompletionContext::CCC_NaturalLanguage: {
4982132584dSDouglas Gregor       contexts = CXCompletionContext_NaturalLanguage;
4992132584dSDouglas Gregor       break;
5002132584dSDouglas Gregor     }
5013d8051abSSam McCall     case CodeCompletionContext::CCC_IncludedFile: {
5023d8051abSSam McCall       contexts = CXCompletionContext_IncludedFile;
5033d8051abSSam McCall       break;
5043d8051abSSam McCall     }
5052132584dSDouglas Gregor     case CodeCompletionContext::CCC_SelectorName: {
5062132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCSelectorName;
5072132584dSDouglas Gregor       break;
5082132584dSDouglas Gregor     }
5092132584dSDouglas Gregor     case CodeCompletionContext::CCC_ParenthesizedExpression: {
5102132584dSDouglas Gregor       contexts = CXCompletionContext_AnyType |
5112132584dSDouglas Gregor                  CXCompletionContext_ObjCInterface |
5122132584dSDouglas Gregor                  CXCompletionContext_AnyValue;
513bbafb8a7SDavid Blaikie       if (S.getLangOpts().CPlusPlus) {
5142132584dSDouglas Gregor         contexts |= CXCompletionContext_EnumTag |
5152132584dSDouglas Gregor                     CXCompletionContext_UnionTag |
5162132584dSDouglas Gregor                     CXCompletionContext_StructTag |
5172132584dSDouglas Gregor                     CXCompletionContext_ClassTag |
5182132584dSDouglas Gregor                     CXCompletionContext_NestedNameSpecifier;
5192132584dSDouglas Gregor       }
5202132584dSDouglas Gregor       break;
5212132584dSDouglas Gregor     }
5222132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCInstanceMessage: {
5232132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCInstanceMessage;
5242132584dSDouglas Gregor       break;
5252132584dSDouglas Gregor     }
5262132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCClassMessage: {
5272132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCClassMessage;
5282132584dSDouglas Gregor       break;
5292132584dSDouglas Gregor     }
5302c595adfSDouglas Gregor     case CodeCompletionContext::CCC_ObjCInterfaceName: {
5312132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCInterface;
5322132584dSDouglas Gregor       break;
5332132584dSDouglas Gregor     }
5342132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCCategoryName: {
5352132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCCategory;
5362132584dSDouglas Gregor       break;
5372132584dSDouglas Gregor     }
5382132584dSDouglas Gregor     case CodeCompletionContext::CCC_Other:
5392132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCInterface:
5402132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCImplementation:
541b006e099SKadir Cetinkaya     case CodeCompletionContext::CCC_NewName:
5422132584dSDouglas Gregor     case CodeCompletionContext::CCC_MacroName:
5432132584dSDouglas Gregor     case CodeCompletionContext::CCC_PreprocessorExpression:
5442132584dSDouglas Gregor     case CodeCompletionContext::CCC_PreprocessorDirective:
5452132584dSDouglas Gregor     case CodeCompletionContext::CCC_TypeQualifiers: {
5462132584dSDouglas Gregor       //Only Clang results should be accepted, so we'll set all of the other
5472132584dSDouglas Gregor       //context bits to 0 (i.e. the empty set)
5482132584dSDouglas Gregor       contexts = CXCompletionContext_Unexposed;
5492132584dSDouglas Gregor       break;
5502132584dSDouglas Gregor     }
5512132584dSDouglas Gregor     case CodeCompletionContext::CCC_Recovery: {
5522132584dSDouglas Gregor       //We don't know what the current context is, so we'll return unknown
5532132584dSDouglas Gregor       //This is the equivalent of setting all of the other context bits
5542132584dSDouglas Gregor       contexts = CXCompletionContext_Unknown;
5552132584dSDouglas Gregor       break;
5562132584dSDouglas Gregor     }
5572132584dSDouglas Gregor   }
5582132584dSDouglas Gregor   return contexts;
5592132584dSDouglas Gregor }
5602132584dSDouglas Gregor 
5618e984da8SDouglas Gregor namespace {
5628e984da8SDouglas Gregor   class CaptureCompletionResults : public CodeCompleteConsumer {
5638e984da8SDouglas Gregor     AllocatedCXCodeCompleteResults &AllocatedResults;
5649d7c0fefSArgyrios Kyrtzidis     CodeCompletionTUInfo CCTUInfo;
5650e62c1ccSChris Lattner     SmallVector<CXCompletionResult, 16> StoredResults;
56663745d59SDouglas Gregor     CXTranslationUnit *TU;
5678e984da8SDouglas Gregor   public:
5683292d06aSDmitri Gribenko     CaptureCompletionResults(const CodeCompleteOptions &Opts,
5693292d06aSDmitri Gribenko                              AllocatedCXCodeCompleteResults &Results,
57063745d59SDouglas Gregor                              CXTranslationUnit *TranslationUnit)
5713a75330fSSam McCall         : CodeCompleteConsumer(Opts), AllocatedResults(Results),
5723a75330fSSam McCall           CCTUInfo(Results.CodeCompletionAllocator), TU(TranslationUnit) {}
57334eb2072SAlexander Kornienko     ~CaptureCompletionResults() override { Finish(); }
5748e984da8SDouglas Gregor 
57536835568SCraig Topper     void ProcessCodeCompleteResults(Sema &S,
57600c37ef0SDouglas Gregor                                     CodeCompletionContext Context,
577276321a9SJohn McCall                                     CodeCompletionResult *Results,
57836835568SCraig Topper                                     unsigned NumResults) override {
57936e3b5c7SDouglas Gregor       StoredResults.reserve(StoredResults.size() + NumResults);
5803957e48aSIvan Donchevskii       if (includeFixIts())
5813957e48aSIvan Donchevskii         AllocatedResults.FixItsVector.reserve(NumResults);
5828e984da8SDouglas Gregor       for (unsigned I = 0; I != NumResults; ++I) {
583b278aafbSDouglas Gregor         CodeCompletionString *StoredCompletion
584c3425b1fSDouglas Gregor           = Results[I].CreateCodeCompletionString(S, Context, getAllocator(),
5853292d06aSDmitri Gribenko                                                   getCodeCompletionTUInfo(),
5863292d06aSDmitri Gribenko                                                   includeBriefComments());
58736e3b5c7SDouglas Gregor 
58836e3b5c7SDouglas Gregor         CXCompletionResult R;
58936e3b5c7SDouglas Gregor         R.CursorKind = Results[I].CursorKind;
59036e3b5c7SDouglas Gregor         R.CompletionString = StoredCompletion;
59136e3b5c7SDouglas Gregor         StoredResults.push_back(R);
5923957e48aSIvan Donchevskii         if (includeFixIts())
5933957e48aSIvan Donchevskii           AllocatedResults.FixItsVector.emplace_back(std::move(Results[I].FixIts));
5948e984da8SDouglas Gregor       }
5952132584dSDouglas Gregor 
59663745d59SDouglas Gregor       enum CodeCompletionContext::Kind contextKind = Context.getKind();
5972132584dSDouglas Gregor 
59863745d59SDouglas Gregor       AllocatedResults.ContextKind = contextKind;
59963745d59SDouglas Gregor       AllocatedResults.Contexts = getContextsForContextKind(contextKind, S);
60063745d59SDouglas Gregor 
601ea777403SDouglas Gregor       AllocatedResults.Selector = "";
6023f31bd18SDmitri Gribenko       ArrayRef<IdentifierInfo *> SelIdents = Context.getSelIdents();
6033f31bd18SDmitri Gribenko       for (ArrayRef<IdentifierInfo *>::iterator I = SelIdents.begin(),
6043f31bd18SDmitri Gribenko                                                 E = SelIdents.end();
6053f31bd18SDmitri Gribenko            I != E; ++I) {
6063f31bd18SDmitri Gribenko         if (IdentifierInfo *selIdent = *I)
6073f31bd18SDmitri Gribenko           AllocatedResults.Selector += selIdent->getName();
608ea777403SDouglas Gregor         AllocatedResults.Selector += ":";
609ea777403SDouglas Gregor       }
610ea777403SDouglas Gregor 
61163745d59SDouglas Gregor       QualType baseType = Context.getBaseType();
61269186e73SCraig Topper       NamedDecl *D = nullptr;
61363745d59SDouglas Gregor 
61463745d59SDouglas Gregor       if (!baseType.isNull()) {
61563745d59SDouglas Gregor         // Get the declaration for a class/struct/union/enum type
61663745d59SDouglas Gregor         if (const TagType *Tag = baseType->getAs<TagType>())
61763745d59SDouglas Gregor           D = Tag->getDecl();
61863745d59SDouglas Gregor         // Get the @interface declaration for a (possibly-qualified) Objective-C
61963745d59SDouglas Gregor         // object pointer type, e.g., NSString*
62063745d59SDouglas Gregor         else if (const ObjCObjectPointerType *ObjPtr =
62163745d59SDouglas Gregor                  baseType->getAs<ObjCObjectPointerType>())
62263745d59SDouglas Gregor           D = ObjPtr->getInterfaceDecl();
62363745d59SDouglas Gregor         // Get the @interface declaration for an Objective-C object type
62463745d59SDouglas Gregor         else if (const ObjCObjectType *Obj = baseType->getAs<ObjCObjectType>())
62563745d59SDouglas Gregor           D = Obj->getInterface();
62663745d59SDouglas Gregor         // Get the class for a C++ injected-class-name
62763745d59SDouglas Gregor         else if (const InjectedClassNameType *Injected =
62863745d59SDouglas Gregor                  baseType->getAs<InjectedClassNameType>())
62963745d59SDouglas Gregor           D = Injected->getDecl();
63063745d59SDouglas Gregor       }
63163745d59SDouglas Gregor 
63269186e73SCraig Topper       if (D != nullptr) {
63363745d59SDouglas Gregor         CXCursor cursor = cxcursor::MakeCXCursor(D, *TU);
63463745d59SDouglas Gregor 
6350b62f8a6SDmitri Gribenko         AllocatedResults.ContainerKind = clang_getCursorKind(cursor);
63663745d59SDouglas Gregor 
6370b62f8a6SDmitri Gribenko         CXString CursorUSR = clang_getCursorUSR(cursor);
6380b62f8a6SDmitri Gribenko         AllocatedResults.ContainerUSR = clang_getCString(CursorUSR);
6390b62f8a6SDmitri Gribenko         clang_disposeString(CursorUSR);
6405b8ad406STed Kremenek 
64163745d59SDouglas Gregor         const Type *type = baseType.getTypePtrOrNull();
64269186e73SCraig Topper         if (type) {
64363745d59SDouglas Gregor           AllocatedResults.ContainerIsIncomplete = type->isIncompleteType();
64463745d59SDouglas Gregor         }
64563745d59SDouglas Gregor         else {
64663745d59SDouglas Gregor           AllocatedResults.ContainerIsIncomplete = 1;
64763745d59SDouglas Gregor         }
64863745d59SDouglas Gregor       }
64963745d59SDouglas Gregor       else {
65063745d59SDouglas Gregor         AllocatedResults.ContainerKind = CXCursor_InvalidCode;
6510b62f8a6SDmitri Gribenko         AllocatedResults.ContainerUSR.clear();
65263745d59SDouglas Gregor         AllocatedResults.ContainerIsIncomplete = 1;
65363745d59SDouglas Gregor       }
6548e984da8SDouglas Gregor     }
65549f67ce4SDouglas Gregor 
65636835568SCraig Topper     void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
65736e3b5c7SDouglas Gregor                                    OverloadCandidate *Candidates,
6582fab2353SIlya Biryukov                                    unsigned NumCandidates,
6592fab2353SIlya Biryukov                                    SourceLocation OpenParLoc) override {
66036e3b5c7SDouglas Gregor       StoredResults.reserve(StoredResults.size() + NumCandidates);
66136e3b5c7SDouglas Gregor       for (unsigned I = 0; I != NumCandidates; ++I) {
662b278aafbSDouglas Gregor         CodeCompletionString *StoredCompletion
6639d7c0fefSArgyrios Kyrtzidis           = Candidates[I].CreateSignatureString(CurrentArg, S, getAllocator(),
6640c010cddSFrancisco Lopes da Silva                                                 getCodeCompletionTUInfo(),
6650c010cddSFrancisco Lopes da Silva                                                 includeBriefComments());
66636e3b5c7SDouglas Gregor 
66736e3b5c7SDouglas Gregor         CXCompletionResult R;
668975a9f6eSFrancisco Lopes da Silva         R.CursorKind = CXCursor_OverloadCandidate;
66936e3b5c7SDouglas Gregor         R.CompletionString = StoredCompletion;
67036e3b5c7SDouglas Gregor         StoredResults.push_back(R);
67136e3b5c7SDouglas Gregor       }
67236e3b5c7SDouglas Gregor     }
67336e3b5c7SDouglas Gregor 
67436835568SCraig Topper     CodeCompletionAllocator &getAllocator() override {
6759d7c0fefSArgyrios Kyrtzidis       return *AllocatedResults.CodeCompletionAllocator;
676b278aafbSDouglas Gregor     }
677b278aafbSDouglas Gregor 
67836835568SCraig Topper     CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo;}
6799d7c0fefSArgyrios Kyrtzidis 
68036e3b5c7SDouglas Gregor   private:
68136e3b5c7SDouglas Gregor     void Finish() {
68236e3b5c7SDouglas Gregor       AllocatedResults.Results = new CXCompletionResult [StoredResults.size()];
68336e3b5c7SDouglas Gregor       AllocatedResults.NumResults = StoredResults.size();
68436e3b5c7SDouglas Gregor       std::memcpy(AllocatedResults.Results, StoredResults.data(),
68536e3b5c7SDouglas Gregor                   StoredResults.size() * sizeof(CXCompletionResult));
68636e3b5c7SDouglas Gregor       StoredResults.clear();
68736e3b5c7SDouglas Gregor     }
6888e984da8SDouglas Gregor   };
689ab9db510SAlexander Kornienko }
6908e984da8SDouglas Gregor 
69111a9cd95SBenjamin Kramer static CXCodeCompleteResults *
69211a9cd95SBenjamin Kramer clang_codeCompleteAt_Impl(CXTranslationUnit TU, const char *complete_filename,
69311a9cd95SBenjamin Kramer                           unsigned complete_line, unsigned complete_column,
69411a9cd95SBenjamin Kramer                           ArrayRef<CXUnsavedFile> unsaved_files,
69511a9cd95SBenjamin Kramer                           unsigned options) {
6963292d06aSDmitri Gribenko   bool IncludeBriefComments = options & CXCodeComplete_IncludeBriefComments;
697bb2cf63bSSam McCall   bool SkipPreamble = options & CXCodeComplete_SkipPreamble;
6983957e48aSIvan Donchevskii   bool IncludeFixIts = options & CXCodeComplete_IncludeCompletionsWithFixIts;
69977af1c56SDaniel Dunbar 
7008e984da8SDouglas Gregor #ifdef UDP_CODE_COMPLETION_LOGGER
7018e984da8SDouglas Gregor #ifdef UDP_CODE_COMPLETION_LOGGER_PORT
7028e984da8SDouglas Gregor   const llvm::TimeRecord &StartTime =  llvm::TimeRecord::getCurrentTime();
7038e984da8SDouglas Gregor #endif
7048e984da8SDouglas Gregor #endif
70569186e73SCraig Topper   bool EnableLogging = getenv("LIBCLANG_CODE_COMPLETION_LOGGING") != nullptr;
7068e984da8SDouglas Gregor 
707852d622eSDmitri Gribenko   if (cxtu::isNotUsableTU(TU)) {
708256454fdSDmitri Gribenko     LOG_BAD_TU(TU);
70911a9cd95SBenjamin Kramer     return nullptr;
710256454fdSDmitri Gribenko   }
711256454fdSDmitri Gribenko 
712c22ea1ceSDmitri Gribenko   ASTUnit *AST = cxtu::getASTUnit(TU);
7138e984da8SDouglas Gregor   if (!AST)
71411a9cd95SBenjamin Kramer     return nullptr;
7158e984da8SDouglas Gregor 
716183436e5SDmitri Gribenko   CIndexer *CXXIdx = TU->CIdx;
7177317a5cbSArgyrios Kyrtzidis   if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
71858d5f3fdSArgyrios Kyrtzidis     setThreadBackgroundPriority();
7197317a5cbSArgyrios Kyrtzidis 
720ca5b0539SDouglas Gregor   ASTUnit::ConcurrencyCheck Check(*AST);
721ca5b0539SDouglas Gregor 
7228e984da8SDouglas Gregor   // Perform the remapping of source files.
7230e62c1ccSChris Lattner   SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
7249d85b18fSAlp Toker 
72511a9cd95SBenjamin Kramer   for (auto &UF : unsaved_files) {
726d87f8d76SRafael Espindola     std::unique_ptr<llvm::MemoryBuffer> MB =
7279d85b18fSAlp Toker         llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
728d87f8d76SRafael Espindola     RemappedFiles.push_back(std::make_pair(UF.Filename, MB.release()));
7298e984da8SDouglas Gregor   }
7308e984da8SDouglas Gregor 
7318e984da8SDouglas Gregor   if (EnableLogging) {
7328e984da8SDouglas Gregor     // FIXME: Add logging.
7338e984da8SDouglas Gregor   }
7348e984da8SDouglas Gregor 
7358e984da8SDouglas Gregor   // Parse the resulting source file to find code-completion results.
7368832c066SBen Langmuir   AllocatedCXCodeCompleteResults *Results = new AllocatedCXCodeCompleteResults(
7378832c066SBen Langmuir       &AST->getFileManager());
73869186e73SCraig Topper   Results->Results = nullptr;
7398e984da8SDouglas Gregor   Results->NumResults = 0;
7408e984da8SDouglas Gregor 
7418e984da8SDouglas Gregor   // Create a code-completion consumer to capture the results.
7423292d06aSDmitri Gribenko   CodeCompleteOptions Opts;
7433292d06aSDmitri Gribenko   Opts.IncludeBriefComments = IncludeBriefComments;
744bb2cf63bSSam McCall   Opts.LoadExternal = !SkipPreamble;
7453957e48aSIvan Donchevskii   Opts.IncludeFixIts = IncludeFixIts;
7463292d06aSDmitri Gribenko   CaptureCompletionResults Capture(Opts, *Results, &TU);
7478e984da8SDouglas Gregor 
7488e984da8SDouglas Gregor   // Perform completion.
749690f0e2fSAlex Lorenz   std::vector<const char *> CArgs;
750690f0e2fSAlex Lorenz   for (const auto &Arg : TU->Arguments)
751690f0e2fSAlex Lorenz     CArgs.push_back(Arg.c_str());
752690f0e2fSAlex Lorenz   std::string CompletionInvocation =
753690f0e2fSAlex Lorenz       llvm::formatv("-code-completion-at={0}:{1}:{2}", complete_filename,
754690f0e2fSAlex Lorenz                     complete_line, complete_column)
755690f0e2fSAlex Lorenz           .str();
756690f0e2fSAlex Lorenz   LibclangInvocationReporter InvocationReporter(
757690f0e2fSAlex Lorenz       *CXXIdx, LibclangInvocationReporter::OperationKind::CompletionOperation,
758690f0e2fSAlex Lorenz       TU->ParsingOptions, CArgs, CompletionInvocation, unsaved_files);
7598e984da8SDouglas Gregor   AST->CodeComplete(complete_filename, complete_line, complete_column,
760bb165fb0SAdrian Prantl                     RemappedFiles, (options & CXCodeComplete_IncludeMacros),
761b68bc59aSDouglas Gregor                     (options & CXCodeComplete_IncludeCodePatterns),
762bb165fb0SAdrian Prantl                     IncludeBriefComments, Capture,
763bb165fb0SAdrian Prantl                     CXXIdx->getPCHContainerOperations(), *Results->Diag,
764bb165fb0SAdrian Prantl                     Results->LangOpts, *Results->SourceMgr, *Results->FileMgr,
765bb165fb0SAdrian Prantl                     Results->Diagnostics, Results->TemporaryBuffers);
7668e984da8SDouglas Gregor 
7677dd96c23SNico Weber   Results->DiagnosticsWrappers.resize(Results->Diagnostics.size());
7687dd96c23SNico Weber 
769162b712dSDouglas Gregor   // Keep a reference to the allocator used for cached global completions, so
770162b712dSDouglas Gregor   // that we can be sure that the memory used by our code completion strings
771162b712dSDouglas Gregor   // doesn't get freed due to subsequent reparses (while the code completion
772162b712dSDouglas Gregor   // results are still active).
773162b712dSDouglas Gregor   Results->CachedCompletionAllocator = AST->getCachedCompletionAllocator();
774162b712dSDouglas Gregor 
7758e984da8SDouglas Gregor 
7768e984da8SDouglas Gregor 
7778e984da8SDouglas Gregor #ifdef UDP_CODE_COMPLETION_LOGGER
7788e984da8SDouglas Gregor #ifdef UDP_CODE_COMPLETION_LOGGER_PORT
7798e984da8SDouglas Gregor   const llvm::TimeRecord &EndTime =  llvm::TimeRecord::getCurrentTime();
780f1a13f29SDylan Noblesmith   SmallString<256> LogResult;
7818e984da8SDouglas Gregor   llvm::raw_svector_ostream os(LogResult);
7828e984da8SDouglas Gregor 
7838e984da8SDouglas Gregor   // Figure out the language and whether or not it uses PCH.
7848e984da8SDouglas Gregor   const char *lang = 0;
7858e984da8SDouglas Gregor   bool usesPCH = false;
7868e984da8SDouglas Gregor 
7878e984da8SDouglas Gregor   for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
7888e984da8SDouglas Gregor        I != E; ++I) {
7898e984da8SDouglas Gregor     if (*I == 0)
7908e984da8SDouglas Gregor       continue;
7918e984da8SDouglas Gregor     if (strcmp(*I, "-x") == 0) {
7928e984da8SDouglas Gregor       if (I + 1 != E) {
7938e984da8SDouglas Gregor         lang = *(++I);
7948e984da8SDouglas Gregor         continue;
7958e984da8SDouglas Gregor       }
7968e984da8SDouglas Gregor     }
7978e984da8SDouglas Gregor     else if (strcmp(*I, "-include") == 0) {
7988e984da8SDouglas Gregor       if (I+1 != E) {
7998e984da8SDouglas Gregor         const char *arg = *(++I);
800f1a13f29SDylan Noblesmith         SmallString<512> pchName;
8018e984da8SDouglas Gregor         {
8028e984da8SDouglas Gregor           llvm::raw_svector_ostream os(pchName);
8038e984da8SDouglas Gregor           os << arg << ".pth";
8048e984da8SDouglas Gregor         }
8058e984da8SDouglas Gregor         pchName.push_back('\0');
806*930ada91SVolodymyr Sapsai         llvm::sys::fs::file_status stat_results;
807*930ada91SVolodymyr Sapsai         if (!llvm::sys::fs::status(pchName, stat_results))
8088e984da8SDouglas Gregor           usesPCH = true;
8098e984da8SDouglas Gregor         continue;
8108e984da8SDouglas Gregor       }
8118e984da8SDouglas Gregor     }
8128e984da8SDouglas Gregor   }
8138e984da8SDouglas Gregor 
8148e984da8SDouglas Gregor   os << "{ ";
8158e984da8SDouglas Gregor   os << "\"wall\": " << (EndTime.getWallTime() - StartTime.getWallTime());
8168e984da8SDouglas Gregor   os << ", \"numRes\": " << Results->NumResults;
8178e984da8SDouglas Gregor   os << ", \"diags\": " << Results->Diagnostics.size();
8188e984da8SDouglas Gregor   os << ", \"pch\": " << (usesPCH ? "true" : "false");
8198e984da8SDouglas Gregor   os << ", \"lang\": \"" << (lang ? lang : "<unknown>") << '"';
8208e984da8SDouglas Gregor   const char *name = getlogin();
8218e984da8SDouglas Gregor   os << ", \"user\": \"" << (name ? name : "unknown") << '"';
8228e984da8SDouglas Gregor   os << ", \"clangVer\": \"" << getClangFullVersion() << '"';
8238e984da8SDouglas Gregor   os << " }";
8248e984da8SDouglas Gregor 
8250e62c1ccSChris Lattner   StringRef res = os.str();
8268e984da8SDouglas Gregor   if (res.size() > 0) {
8278e984da8SDouglas Gregor     do {
8288e984da8SDouglas Gregor       // Setup the UDP socket.
8298e984da8SDouglas Gregor       struct sockaddr_in servaddr;
8308e984da8SDouglas Gregor       bzero(&servaddr, sizeof(servaddr));
8318e984da8SDouglas Gregor       servaddr.sin_family = AF_INET;
8328e984da8SDouglas Gregor       servaddr.sin_port = htons(UDP_CODE_COMPLETION_LOGGER_PORT);
8338e984da8SDouglas Gregor       if (inet_pton(AF_INET, UDP_CODE_COMPLETION_LOGGER,
8348e984da8SDouglas Gregor                     &servaddr.sin_addr) <= 0)
8358e984da8SDouglas Gregor         break;
8368e984da8SDouglas Gregor 
8378e984da8SDouglas Gregor       int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
8388e984da8SDouglas Gregor       if (sockfd < 0)
8398e984da8SDouglas Gregor         break;
8408e984da8SDouglas Gregor 
8418e984da8SDouglas Gregor       sendto(sockfd, res.data(), res.size(), 0,
8428e984da8SDouglas Gregor              (struct sockaddr *)&servaddr, sizeof(servaddr));
8438e984da8SDouglas Gregor       close(sockfd);
8448e984da8SDouglas Gregor     }
8458e984da8SDouglas Gregor     while (false);
8468e984da8SDouglas Gregor   }
8478e984da8SDouglas Gregor #endif
8488e984da8SDouglas Gregor #endif
84911a9cd95SBenjamin Kramer   return Results;
85077af1c56SDaniel Dunbar }
85111a9cd95SBenjamin Kramer 
85277af1c56SDaniel Dunbar CXCodeCompleteResults *clang_codeCompleteAt(CXTranslationUnit TU,
85377af1c56SDaniel Dunbar                                             const char *complete_filename,
85477af1c56SDaniel Dunbar                                             unsigned complete_line,
85577af1c56SDaniel Dunbar                                             unsigned complete_column,
85677af1c56SDaniel Dunbar                                             struct CXUnsavedFile *unsaved_files,
85777af1c56SDaniel Dunbar                                             unsigned num_unsaved_files,
85877af1c56SDaniel Dunbar                                             unsigned options) {
859ea474358SArgyrios Kyrtzidis   LOG_FUNC_SECTION {
860ea474358SArgyrios Kyrtzidis     *Log << TU << ' '
861ea474358SArgyrios Kyrtzidis          << complete_filename << ':' << complete_line << ':' << complete_column;
862ea474358SArgyrios Kyrtzidis   }
863ea474358SArgyrios Kyrtzidis 
8649d85b18fSAlp Toker   if (num_unsaved_files && !unsaved_files)
8659d85b18fSAlp Toker     return nullptr;
8669d85b18fSAlp Toker 
86711a9cd95SBenjamin Kramer   CXCodeCompleteResults *result;
86811a9cd95SBenjamin Kramer   auto CodeCompleteAtImpl = [=, &result]() {
86911a9cd95SBenjamin Kramer     result = clang_codeCompleteAt_Impl(
87011a9cd95SBenjamin Kramer         TU, complete_filename, complete_line, complete_column,
87111a9cd95SBenjamin Kramer         llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
87211a9cd95SBenjamin Kramer   };
8739999f4f8SArgyrios Kyrtzidis 
87477af1c56SDaniel Dunbar   llvm::CrashRecoveryContext CRC;
87577af1c56SDaniel Dunbar 
87611a9cd95SBenjamin Kramer   if (!RunSafely(CRC, CodeCompleteAtImpl)) {
87777af1c56SDaniel Dunbar     fprintf(stderr, "libclang: crash detected in code completion\n");
878c22ea1ceSDmitri Gribenko     cxtu::getASTUnit(TU)->setUnsafeToFree(true);
87969186e73SCraig Topper     return nullptr;
880af44c781SDouglas Gregor   } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
881af44c781SDouglas Gregor     PrintLibclangResourceUsage(TU);
88277af1c56SDaniel Dunbar 
88311a9cd95SBenjamin Kramer   return result;
8848e984da8SDouglas Gregor }
8858e984da8SDouglas Gregor 
886b68bc59aSDouglas Gregor unsigned clang_defaultCodeCompleteOptions(void) {
887b68bc59aSDouglas Gregor   return CXCodeComplete_IncludeMacros;
888b68bc59aSDouglas Gregor }
889b68bc59aSDouglas Gregor 
890d5a2a073SDaniel Dunbar void clang_disposeCodeCompleteResults(CXCodeCompleteResults *ResultsIn) {
891d5a2a073SDaniel Dunbar   if (!ResultsIn)
892d5a2a073SDaniel Dunbar     return;
893d5a2a073SDaniel Dunbar 
894d5a2a073SDaniel Dunbar   AllocatedCXCodeCompleteResults *Results
895d5a2a073SDaniel Dunbar     = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
896d5a2a073SDaniel Dunbar   delete Results;
897d5a2a073SDaniel Dunbar }
898d5a2a073SDaniel Dunbar 
899d5a2a073SDaniel Dunbar unsigned
900d5a2a073SDaniel Dunbar clang_codeCompleteGetNumDiagnostics(CXCodeCompleteResults *ResultsIn) {
901d5a2a073SDaniel Dunbar   AllocatedCXCodeCompleteResults *Results
902d5a2a073SDaniel Dunbar     = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
903d5a2a073SDaniel Dunbar   if (!Results)
904d5a2a073SDaniel Dunbar     return 0;
905d5a2a073SDaniel Dunbar 
906d5a2a073SDaniel Dunbar   return Results->Diagnostics.size();
907d5a2a073SDaniel Dunbar }
908d5a2a073SDaniel Dunbar 
909d5a2a073SDaniel Dunbar CXDiagnostic
910d5a2a073SDaniel Dunbar clang_codeCompleteGetDiagnostic(CXCodeCompleteResults *ResultsIn,
911d5a2a073SDaniel Dunbar                                 unsigned Index) {
912d5a2a073SDaniel Dunbar   AllocatedCXCodeCompleteResults *Results
913d5a2a073SDaniel Dunbar     = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
914d5a2a073SDaniel Dunbar   if (!Results || Index >= Results->Diagnostics.size())
91569186e73SCraig Topper     return nullptr;
916d5a2a073SDaniel Dunbar 
9177dd96c23SNico Weber   CXStoredDiagnostic *Diag = Results->DiagnosticsWrappers[Index];
9187dd96c23SNico Weber   if (!Diag)
9197dd96c23SNico Weber     Results->DiagnosticsWrappers[Index] = Diag =
9207dd96c23SNico Weber         new CXStoredDiagnostic(Results->Diagnostics[Index], Results->LangOpts);
9217dd96c23SNico Weber   return Diag;
922d5a2a073SDaniel Dunbar }
923d5a2a073SDaniel Dunbar 
9242132584dSDouglas Gregor unsigned long long
9252132584dSDouglas Gregor clang_codeCompleteGetContexts(CXCodeCompleteResults *ResultsIn) {
9262132584dSDouglas Gregor   AllocatedCXCodeCompleteResults *Results
9272132584dSDouglas Gregor     = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
9282132584dSDouglas Gregor   if (!Results)
9292132584dSDouglas Gregor     return 0;
9302132584dSDouglas Gregor 
9312132584dSDouglas Gregor   return Results->Contexts;
9322132584dSDouglas Gregor }
933d5a2a073SDaniel Dunbar 
93463745d59SDouglas Gregor enum CXCursorKind clang_codeCompleteGetContainerKind(
93563745d59SDouglas Gregor                                                CXCodeCompleteResults *ResultsIn,
93663745d59SDouglas Gregor                                                      unsigned *IsIncomplete) {
93763745d59SDouglas Gregor   AllocatedCXCodeCompleteResults *Results =
93863745d59SDouglas Gregor     static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn);
93963745d59SDouglas Gregor   if (!Results)
94063745d59SDouglas Gregor     return CXCursor_InvalidCode;
94163745d59SDouglas Gregor 
94269186e73SCraig Topper   if (IsIncomplete != nullptr) {
94363745d59SDouglas Gregor     *IsIncomplete = Results->ContainerIsIncomplete;
94463745d59SDouglas Gregor   }
94563745d59SDouglas Gregor 
94663745d59SDouglas Gregor   return Results->ContainerKind;
94763745d59SDouglas Gregor }
94863745d59SDouglas Gregor 
94963745d59SDouglas Gregor CXString clang_codeCompleteGetContainerUSR(CXCodeCompleteResults *ResultsIn) {
95063745d59SDouglas Gregor   AllocatedCXCodeCompleteResults *Results =
95163745d59SDouglas Gregor     static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn);
95263745d59SDouglas Gregor   if (!Results)
95336a6dd04SDmitri Gribenko     return cxstring::createEmpty();
95463745d59SDouglas Gregor 
9550b62f8a6SDmitri Gribenko   return cxstring::createRef(Results->ContainerUSR.c_str());
95663745d59SDouglas Gregor }
95763745d59SDouglas Gregor 
958ea777403SDouglas Gregor 
959ea777403SDouglas Gregor CXString clang_codeCompleteGetObjCSelector(CXCodeCompleteResults *ResultsIn) {
960ea777403SDouglas Gregor   AllocatedCXCodeCompleteResults *Results =
961ea777403SDouglas Gregor     static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn);
962ea777403SDouglas Gregor   if (!Results)
96336a6dd04SDmitri Gribenko     return cxstring::createEmpty();
964ea777403SDouglas Gregor 
9652f23e9c5SDmitri Gribenko   return cxstring::createDup(Results->Selector);
966ea777403SDouglas Gregor }
967ea777403SDouglas Gregor 
9689fc8faf9SAdrian Prantl /// Simple utility function that appends a \p New string to the given
9698e3e8743SDouglas Gregor /// \p Old string, using the \p Buffer for storage.
9708e3e8743SDouglas Gregor ///
9718e3e8743SDouglas Gregor /// \param Old The string to which we are appending. This parameter will be
9728e3e8743SDouglas Gregor /// updated to reflect the complete string.
9738e3e8743SDouglas Gregor ///
9748e3e8743SDouglas Gregor ///
9758e3e8743SDouglas Gregor /// \param New The string to append to \p Old.
9768e3e8743SDouglas Gregor ///
9778e3e8743SDouglas Gregor /// \param Buffer A buffer that stores the actual, concatenated string. It will
9788e3e8743SDouglas Gregor /// be used if the old string is already-non-empty.
9790e62c1ccSChris Lattner static void AppendToString(StringRef &Old, StringRef New,
980f1a13f29SDylan Noblesmith                            SmallString<256> &Buffer) {
9818e3e8743SDouglas Gregor   if (Old.empty()) {
9828e3e8743SDouglas Gregor     Old = New;
9838e3e8743SDouglas Gregor     return;
9848e3e8743SDouglas Gregor   }
9858e3e8743SDouglas Gregor 
9868e3e8743SDouglas Gregor   if (Buffer.empty())
9878e3e8743SDouglas Gregor     Buffer.append(Old.begin(), Old.end());
9888e3e8743SDouglas Gregor   Buffer.append(New.begin(), New.end());
9898e3e8743SDouglas Gregor   Old = Buffer.str();
9908e3e8743SDouglas Gregor }
9918e3e8743SDouglas Gregor 
9929fc8faf9SAdrian Prantl /// Get the typed-text blocks from the given code-completion string
9938e3e8743SDouglas Gregor /// and return them as a single string.
9948e3e8743SDouglas Gregor ///
9958e3e8743SDouglas Gregor /// \param String The code-completion string whose typed-text blocks will be
9968e3e8743SDouglas Gregor /// concatenated.
9978e3e8743SDouglas Gregor ///
9988e3e8743SDouglas Gregor /// \param Buffer A buffer used for storage of the completed name.
9990e62c1ccSChris Lattner static StringRef GetTypedName(CodeCompletionString *String,
1000f1a13f29SDylan Noblesmith                                     SmallString<256> &Buffer) {
10010e62c1ccSChris Lattner   StringRef Result;
10028e3e8743SDouglas Gregor   for (CodeCompletionString::iterator C = String->begin(), CEnd = String->end();
10038e3e8743SDouglas Gregor        C != CEnd; ++C) {
10048e3e8743SDouglas Gregor     if (C->Kind == CodeCompletionString::CK_TypedText)
10058e3e8743SDouglas Gregor       AppendToString(Result, C->Text, Buffer);
10068e3e8743SDouglas Gregor   }
10078e3e8743SDouglas Gregor 
10088e3e8743SDouglas Gregor   return Result;
10098e3e8743SDouglas Gregor }
10108e3e8743SDouglas Gregor 
101149f67ce4SDouglas Gregor namespace {
101249f67ce4SDouglas Gregor   struct OrderCompletionResults {
101349f67ce4SDouglas Gregor     bool operator()(const CXCompletionResult &XR,
101449f67ce4SDouglas Gregor                     const CXCompletionResult &YR) const {
1015b278aafbSDouglas Gregor       CodeCompletionString *X
1016b278aafbSDouglas Gregor         = (CodeCompletionString *)XR.CompletionString;
1017b278aafbSDouglas Gregor       CodeCompletionString *Y
1018b278aafbSDouglas Gregor         = (CodeCompletionString *)YR.CompletionString;
101949f67ce4SDouglas Gregor 
1020f1a13f29SDylan Noblesmith       SmallString<256> XBuffer;
10210e62c1ccSChris Lattner       StringRef XText = GetTypedName(X, XBuffer);
1022f1a13f29SDylan Noblesmith       SmallString<256> YBuffer;
10230e62c1ccSChris Lattner       StringRef YText = GetTypedName(Y, YBuffer);
102449f67ce4SDouglas Gregor 
10258e3e8743SDouglas Gregor       if (XText.empty() || YText.empty())
10268e3e8743SDouglas Gregor         return !XText.empty();
10278e3e8743SDouglas Gregor 
10288e3e8743SDouglas Gregor       int result = XText.compare_lower(YText);
102949f67ce4SDouglas Gregor       if (result < 0)
103049f67ce4SDouglas Gregor         return true;
103149f67ce4SDouglas Gregor       if (result > 0)
103249f67ce4SDouglas Gregor         return false;
103349f67ce4SDouglas Gregor 
10348e3e8743SDouglas Gregor       result = XText.compare(YText);
1035c7a7d92aSDouglas Gregor       return result < 0;
103649f67ce4SDouglas Gregor     }
103749f67ce4SDouglas Gregor   };
1038ab9db510SAlexander Kornienko }
103949f67ce4SDouglas Gregor 
104049f67ce4SDouglas Gregor void clang_sortCodeCompletionResults(CXCompletionResult *Results,
104149f67ce4SDouglas Gregor                                      unsigned NumResults) {
104249f67ce4SDouglas Gregor   std::stable_sort(Results, Results + NumResults, OrderCompletionResults());
104349f67ce4SDouglas Gregor }
1044