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"
164b4f3699STed Kremenek #include "CXString.h"
17d5a2a073SDaniel Dunbar #include "CIndexDiagnostic.h"
18d5a2a073SDaniel Dunbar #include "clang/Basic/SourceManager.h"
19d5a2a073SDaniel Dunbar #include "clang/Basic/FileManager.h"
208e984da8SDouglas Gregor #include "clang/Frontend/ASTUnit.h"
21d5a2a073SDaniel Dunbar #include "clang/Frontend/CompilerInstance.h"
22d5a2a073SDaniel Dunbar #include "clang/Frontend/FrontendDiagnostic.h"
23d5a2a073SDaniel Dunbar #include "clang/Sema/CodeCompleteConsumer.h"
24028d3e4dSDouglas Gregor #include "llvm/ADT/SmallString.h"
25d5a2a073SDaniel Dunbar #include "llvm/ADT/StringExtras.h"
2677af1c56SDaniel Dunbar #include "llvm/Support/CrashRecoveryContext.h"
27d5a2a073SDaniel Dunbar #include "llvm/Support/MemoryBuffer.h"
28028d3e4dSDouglas Gregor #include "llvm/Support/Timer.h"
29028d3e4dSDouglas Gregor #include "llvm/Support/raw_ostream.h"
30d5a2a073SDaniel Dunbar #include "llvm/System/Program.h"
31d6009ffbSDouglas Gregor #include <cstdlib>
32d6009ffbSDouglas Gregor #include <cstdio>
33d5a2a073SDaniel Dunbar 
34028d3e4dSDouglas Gregor 
35d5a2a073SDaniel Dunbar #ifdef UDP_CODE_COMPLETION_LOGGER
36d5a2a073SDaniel Dunbar #include "clang/Basic/Version.h"
37d5a2a073SDaniel Dunbar #include <arpa/inet.h>
38d5a2a073SDaniel Dunbar #include <sys/socket.h>
39d5a2a073SDaniel Dunbar #include <sys/types.h>
40d5a2a073SDaniel Dunbar #include <unistd.h>
41d5a2a073SDaniel Dunbar #endif
42d5a2a073SDaniel Dunbar 
43d5a2a073SDaniel Dunbar using namespace clang;
44d5a2a073SDaniel Dunbar using namespace clang::cxstring;
45d5a2a073SDaniel Dunbar 
46a2db793fSDouglas Gregor namespace {
47a2db793fSDouglas Gregor   /// \brief Stored representation of a completion string.
48a2db793fSDouglas Gregor   ///
49a2db793fSDouglas Gregor   /// This is the representation behind a CXCompletionString.
50a2db793fSDouglas Gregor   class CXStoredCodeCompletionString : public CodeCompletionString {
51a2db793fSDouglas Gregor     unsigned Priority;
52f757a12dSDouglas Gregor     CXAvailabilityKind Availability;
53a2db793fSDouglas Gregor 
54a2db793fSDouglas Gregor   public:
55f757a12dSDouglas Gregor     CXStoredCodeCompletionString(unsigned Priority,
56f757a12dSDouglas Gregor                                  CXAvailabilityKind Availability)
57f757a12dSDouglas Gregor       : Priority(Priority), Availability(Availability) { }
58a2db793fSDouglas Gregor 
59a2db793fSDouglas Gregor     unsigned getPriority() const { return Priority; }
60f757a12dSDouglas Gregor     CXAvailabilityKind getAvailability() const { return Availability; }
61a2db793fSDouglas Gregor   };
62a2db793fSDouglas Gregor }
63a2db793fSDouglas Gregor 
64d5a2a073SDaniel Dunbar extern "C" {
65d5a2a073SDaniel Dunbar 
66d5a2a073SDaniel Dunbar enum CXCompletionChunkKind
67d5a2a073SDaniel Dunbar clang_getCompletionChunkKind(CXCompletionString completion_string,
68d5a2a073SDaniel Dunbar                              unsigned chunk_number) {
69a2db793fSDouglas Gregor   CXStoredCodeCompletionString *CCStr
70a2db793fSDouglas Gregor     = (CXStoredCodeCompletionString *)completion_string;
71d5a2a073SDaniel Dunbar   if (!CCStr || chunk_number >= CCStr->size())
72d5a2a073SDaniel Dunbar     return CXCompletionChunk_Text;
73d5a2a073SDaniel Dunbar 
74d5a2a073SDaniel Dunbar   switch ((*CCStr)[chunk_number].Kind) {
75d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_TypedText:
76d5a2a073SDaniel Dunbar     return CXCompletionChunk_TypedText;
77d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Text:
78d5a2a073SDaniel Dunbar     return CXCompletionChunk_Text;
79d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Optional:
80d5a2a073SDaniel Dunbar     return CXCompletionChunk_Optional;
81d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Placeholder:
82d5a2a073SDaniel Dunbar     return CXCompletionChunk_Placeholder;
83d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Informative:
84d5a2a073SDaniel Dunbar     return CXCompletionChunk_Informative;
85d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_ResultType:
86d5a2a073SDaniel Dunbar     return CXCompletionChunk_ResultType;
87d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_CurrentParameter:
88d5a2a073SDaniel Dunbar     return CXCompletionChunk_CurrentParameter;
89d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftParen:
90d5a2a073SDaniel Dunbar     return CXCompletionChunk_LeftParen;
91d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightParen:
92d5a2a073SDaniel Dunbar     return CXCompletionChunk_RightParen;
93d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftBracket:
94d5a2a073SDaniel Dunbar     return CXCompletionChunk_LeftBracket;
95d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightBracket:
96d5a2a073SDaniel Dunbar     return CXCompletionChunk_RightBracket;
97d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftBrace:
98d5a2a073SDaniel Dunbar     return CXCompletionChunk_LeftBrace;
99d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightBrace:
100d5a2a073SDaniel Dunbar     return CXCompletionChunk_RightBrace;
101d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftAngle:
102d5a2a073SDaniel Dunbar     return CXCompletionChunk_LeftAngle;
103d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightAngle:
104d5a2a073SDaniel Dunbar     return CXCompletionChunk_RightAngle;
105d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Comma:
106d5a2a073SDaniel Dunbar     return CXCompletionChunk_Comma;
107d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Colon:
108d5a2a073SDaniel Dunbar     return CXCompletionChunk_Colon;
109d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_SemiColon:
110d5a2a073SDaniel Dunbar     return CXCompletionChunk_SemiColon;
111d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Equal:
112d5a2a073SDaniel Dunbar     return CXCompletionChunk_Equal;
113d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_HorizontalSpace:
114d5a2a073SDaniel Dunbar     return CXCompletionChunk_HorizontalSpace;
115d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_VerticalSpace:
116d5a2a073SDaniel Dunbar     return CXCompletionChunk_VerticalSpace;
117d5a2a073SDaniel Dunbar   }
118d5a2a073SDaniel Dunbar 
119d5a2a073SDaniel Dunbar   // Should be unreachable, but let's be careful.
120d5a2a073SDaniel Dunbar   return CXCompletionChunk_Text;
121d5a2a073SDaniel Dunbar }
122d5a2a073SDaniel Dunbar 
123d5a2a073SDaniel Dunbar CXString clang_getCompletionChunkText(CXCompletionString completion_string,
124d5a2a073SDaniel Dunbar                                       unsigned chunk_number) {
125a2db793fSDouglas Gregor   CXStoredCodeCompletionString *CCStr
126a2db793fSDouglas Gregor     = (CXStoredCodeCompletionString *)completion_string;
127d5a2a073SDaniel Dunbar   if (!CCStr || chunk_number >= CCStr->size())
128*91554285STed Kremenek     return createCXString((const char*)0);
129d5a2a073SDaniel Dunbar 
130d5a2a073SDaniel Dunbar   switch ((*CCStr)[chunk_number].Kind) {
131d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_TypedText:
132d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Text:
133d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Placeholder:
134d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_CurrentParameter:
135d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Informative:
136d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftParen:
137d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightParen:
138d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftBracket:
139d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightBracket:
140d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftBrace:
141d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightBrace:
142d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftAngle:
143d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightAngle:
144d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Comma:
145d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_ResultType:
146d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Colon:
147d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_SemiColon:
148d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Equal:
149d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_HorizontalSpace:
15009737ee8SDouglas Gregor   case CodeCompletionString::CK_VerticalSpace:
1518ed5b770SDouglas Gregor     return createCXString((*CCStr)[chunk_number].Text, false);
15209737ee8SDouglas Gregor 
153d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Optional:
154d5a2a073SDaniel Dunbar     // Note: treated as an empty text block.
155d5a2a073SDaniel Dunbar     return createCXString("");
156d5a2a073SDaniel Dunbar   }
157d5a2a073SDaniel Dunbar 
158d5a2a073SDaniel Dunbar   // Should be unreachable, but let's be careful.
159*91554285STed Kremenek   return createCXString((const char*)0);
160d5a2a073SDaniel Dunbar }
161d5a2a073SDaniel Dunbar 
162d5a2a073SDaniel Dunbar 
163d5a2a073SDaniel Dunbar CXCompletionString
164d5a2a073SDaniel Dunbar clang_getCompletionChunkCompletionString(CXCompletionString completion_string,
165d5a2a073SDaniel Dunbar                                          unsigned chunk_number) {
166a2db793fSDouglas Gregor   CXStoredCodeCompletionString *CCStr
167a2db793fSDouglas Gregor     = (CXStoredCodeCompletionString *)completion_string;
168d5a2a073SDaniel Dunbar   if (!CCStr || chunk_number >= CCStr->size())
169d5a2a073SDaniel Dunbar     return 0;
170d5a2a073SDaniel Dunbar 
171d5a2a073SDaniel Dunbar   switch ((*CCStr)[chunk_number].Kind) {
172d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_TypedText:
173d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Text:
174d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Placeholder:
175d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_CurrentParameter:
176d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Informative:
177d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftParen:
178d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightParen:
179d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftBracket:
180d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightBracket:
181d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftBrace:
182d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightBrace:
183d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftAngle:
184d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightAngle:
185d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Comma:
186d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_ResultType:
187d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Colon:
188d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_SemiColon:
189d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Equal:
190d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_HorizontalSpace:
191d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_VerticalSpace:
192d5a2a073SDaniel Dunbar     return 0;
193d5a2a073SDaniel Dunbar 
194d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Optional:
195d5a2a073SDaniel Dunbar     // Note: treated as an empty text block.
196d5a2a073SDaniel Dunbar     return (*CCStr)[chunk_number].Optional;
197d5a2a073SDaniel Dunbar   }
198d5a2a073SDaniel Dunbar 
199d5a2a073SDaniel Dunbar   // Should be unreachable, but let's be careful.
200d5a2a073SDaniel Dunbar   return 0;
201d5a2a073SDaniel Dunbar }
202d5a2a073SDaniel Dunbar 
203d5a2a073SDaniel Dunbar unsigned clang_getNumCompletionChunks(CXCompletionString completion_string) {
204a2db793fSDouglas Gregor   CXStoredCodeCompletionString *CCStr
205a2db793fSDouglas Gregor     = (CXStoredCodeCompletionString *)completion_string;
206d5a2a073SDaniel Dunbar   return CCStr? CCStr->size() : 0;
207d5a2a073SDaniel Dunbar }
208d5a2a073SDaniel Dunbar 
209a2db793fSDouglas Gregor unsigned clang_getCompletionPriority(CXCompletionString completion_string) {
210a2db793fSDouglas Gregor   CXStoredCodeCompletionString *CCStr
211a2db793fSDouglas Gregor     = (CXStoredCodeCompletionString *)completion_string;
21247bb3e2bSBill Wendling   return CCStr? CCStr->getPriority() : unsigned(CCP_Unlikely);
213a2db793fSDouglas Gregor }
214a2db793fSDouglas Gregor 
215f757a12dSDouglas Gregor enum CXAvailabilityKind
216f757a12dSDouglas Gregor clang_getCompletionAvailability(CXCompletionString completion_string) {
217f757a12dSDouglas Gregor   CXStoredCodeCompletionString *CCStr
218f757a12dSDouglas Gregor     = (CXStoredCodeCompletionString *)completion_string;
219f757a12dSDouglas Gregor   return CCStr? CCStr->getAvailability() : CXAvailability_Available;
220f757a12dSDouglas Gregor }
221f757a12dSDouglas Gregor 
222d5a2a073SDaniel Dunbar /// \brief The CXCodeCompleteResults structure we allocate internally;
223d5a2a073SDaniel Dunbar /// the client only sees the initial CXCodeCompleteResults structure.
224d5a2a073SDaniel Dunbar struct AllocatedCXCodeCompleteResults : public CXCodeCompleteResults {
225d5a2a073SDaniel Dunbar   AllocatedCXCodeCompleteResults();
226d5a2a073SDaniel Dunbar   ~AllocatedCXCodeCompleteResults();
227d5a2a073SDaniel Dunbar 
228d5a2a073SDaniel Dunbar   /// \brief Diagnostics produced while performing code completion.
229d5a2a073SDaniel Dunbar   llvm::SmallVector<StoredDiagnostic, 8> Diagnostics;
230d5a2a073SDaniel Dunbar 
231d5a2a073SDaniel Dunbar   /// \brief Diag object
2328e984da8SDouglas Gregor   llvm::IntrusiveRefCntPtr<Diagnostic> Diag;
233d5a2a073SDaniel Dunbar 
234d5a2a073SDaniel Dunbar   /// \brief Language options used to adjust source locations.
235d5a2a073SDaniel Dunbar   LangOptions LangOpts;
236d5a2a073SDaniel Dunbar 
237d5a2a073SDaniel Dunbar   /// \brief File manager, used for diagnostics.
238d5a2a073SDaniel Dunbar   FileManager FileMgr;
239d5a2a073SDaniel Dunbar 
24071731d6bSArgyrios Kyrtzidis   FileSystemOptions FileSystemOpts;
24171731d6bSArgyrios Kyrtzidis 
24271731d6bSArgyrios Kyrtzidis   /// \brief Source manager, used for diagnostics.
24371731d6bSArgyrios Kyrtzidis   SourceManager SourceMgr;
24471731d6bSArgyrios Kyrtzidis 
245d5a2a073SDaniel Dunbar   /// \brief Temporary files that should be removed once we have finished
246d5a2a073SDaniel Dunbar   /// with the code-completion results.
247d5a2a073SDaniel Dunbar   std::vector<llvm::sys::Path> TemporaryFiles;
248d8a5dba9SDouglas Gregor 
249d8a5dba9SDouglas Gregor   /// \brief Temporary buffers that will be deleted once we have finished with the code-completion results.
250d8a5dba9SDouglas Gregor   llvm::SmallVector<const llvm::MemoryBuffer *, 1> TemporaryBuffers;
251d5a2a073SDaniel Dunbar };
252d5a2a073SDaniel Dunbar 
253d5a2a073SDaniel Dunbar AllocatedCXCodeCompleteResults::AllocatedCXCodeCompleteResults()
25471731d6bSArgyrios Kyrtzidis   : CXCodeCompleteResults(), Diag(new Diagnostic),
25571731d6bSArgyrios Kyrtzidis     SourceMgr(*Diag, FileMgr, FileSystemOpts) { }
256d5a2a073SDaniel Dunbar 
257d5a2a073SDaniel Dunbar AllocatedCXCodeCompleteResults::~AllocatedCXCodeCompleteResults() {
258d5a2a073SDaniel Dunbar   for (unsigned I = 0, N = NumResults; I != N; ++I)
259a2db793fSDouglas Gregor     delete (CXStoredCodeCompletionString *)Results[I].CompletionString;
260d5a2a073SDaniel Dunbar   delete [] Results;
261d5a2a073SDaniel Dunbar 
262d5a2a073SDaniel Dunbar   for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
263d5a2a073SDaniel Dunbar     TemporaryFiles[I].eraseFromDisk();
264d8a5dba9SDouglas Gregor   for (unsigned I = 0, N = TemporaryBuffers.size(); I != N; ++I)
265d8a5dba9SDouglas Gregor     delete TemporaryBuffers[I];
266d5a2a073SDaniel Dunbar }
267d5a2a073SDaniel Dunbar 
2688e984da8SDouglas Gregor } // end extern "C"
2698e984da8SDouglas Gregor 
2708e984da8SDouglas Gregor namespace {
2718e984da8SDouglas Gregor   class CaptureCompletionResults : public CodeCompleteConsumer {
2728e984da8SDouglas Gregor     AllocatedCXCodeCompleteResults &AllocatedResults;
27336e3b5c7SDouglas Gregor     llvm::SmallVector<CXCompletionResult, 16> StoredResults;
2748e984da8SDouglas Gregor 
2758e984da8SDouglas Gregor   public:
2768e984da8SDouglas Gregor     explicit CaptureCompletionResults(AllocatedCXCodeCompleteResults &Results)
27739982197SDouglas Gregor       : CodeCompleteConsumer(true, false, true, false),
27839982197SDouglas Gregor         AllocatedResults(Results) { }
27936e3b5c7SDouglas Gregor     ~CaptureCompletionResults() { Finish(); }
2808e984da8SDouglas Gregor 
28100c37ef0SDouglas Gregor     virtual void ProcessCodeCompleteResults(Sema &S,
28200c37ef0SDouglas Gregor                                             CodeCompletionContext Context,
283276321a9SJohn McCall                                             CodeCompletionResult *Results,
2848e984da8SDouglas Gregor                                             unsigned NumResults) {
28536e3b5c7SDouglas Gregor       StoredResults.reserve(StoredResults.size() + NumResults);
2868e984da8SDouglas Gregor       for (unsigned I = 0; I != NumResults; ++I) {
2878e984da8SDouglas Gregor         CXStoredCodeCompletionString *StoredCompletion
288f757a12dSDouglas Gregor           = new CXStoredCodeCompletionString(Results[I].Priority,
289f757a12dSDouglas Gregor                                              Results[I].Availability);
2908e984da8SDouglas Gregor         (void)Results[I].CreateCodeCompletionString(S, StoredCompletion);
29136e3b5c7SDouglas Gregor 
29236e3b5c7SDouglas Gregor         CXCompletionResult R;
29336e3b5c7SDouglas Gregor         R.CursorKind = Results[I].CursorKind;
29436e3b5c7SDouglas Gregor         R.CompletionString = StoredCompletion;
29536e3b5c7SDouglas Gregor         StoredResults.push_back(R);
2968e984da8SDouglas Gregor       }
2978e984da8SDouglas Gregor     }
29849f67ce4SDouglas Gregor 
29936e3b5c7SDouglas Gregor     virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
30036e3b5c7SDouglas Gregor                                            OverloadCandidate *Candidates,
30136e3b5c7SDouglas Gregor                                            unsigned NumCandidates) {
30236e3b5c7SDouglas Gregor       StoredResults.reserve(StoredResults.size() + NumCandidates);
30336e3b5c7SDouglas Gregor       for (unsigned I = 0; I != NumCandidates; ++I) {
30436e3b5c7SDouglas Gregor         // FIXME: Set priority, availability appropriately.
30536e3b5c7SDouglas Gregor         CXStoredCodeCompletionString *StoredCompletion
30636e3b5c7SDouglas Gregor           = new CXStoredCodeCompletionString(1, CXAvailability_Available);
30736e3b5c7SDouglas Gregor         (void)Candidates[I].CreateSignatureString(CurrentArg, S,
30836e3b5c7SDouglas Gregor                                                   StoredCompletion);
30936e3b5c7SDouglas Gregor 
31036e3b5c7SDouglas Gregor         CXCompletionResult R;
31136e3b5c7SDouglas Gregor         R.CursorKind = CXCursor_NotImplemented;
31236e3b5c7SDouglas Gregor         R.CompletionString = StoredCompletion;
31336e3b5c7SDouglas Gregor         StoredResults.push_back(R);
31436e3b5c7SDouglas Gregor       }
31536e3b5c7SDouglas Gregor     }
31636e3b5c7SDouglas Gregor 
31736e3b5c7SDouglas Gregor   private:
31836e3b5c7SDouglas Gregor     void Finish() {
31936e3b5c7SDouglas Gregor       AllocatedResults.Results = new CXCompletionResult [StoredResults.size()];
32036e3b5c7SDouglas Gregor       AllocatedResults.NumResults = StoredResults.size();
32136e3b5c7SDouglas Gregor       std::memcpy(AllocatedResults.Results, StoredResults.data(),
32236e3b5c7SDouglas Gregor                   StoredResults.size() * sizeof(CXCompletionResult));
32336e3b5c7SDouglas Gregor       StoredResults.clear();
32436e3b5c7SDouglas Gregor     }
3258e984da8SDouglas Gregor   };
3268e984da8SDouglas Gregor }
3278e984da8SDouglas Gregor 
3288e984da8SDouglas Gregor extern "C" {
32977af1c56SDaniel Dunbar struct CodeCompleteAtInfo {
33077af1c56SDaniel Dunbar   CXTranslationUnit TU;
33177af1c56SDaniel Dunbar   const char *complete_filename;
33277af1c56SDaniel Dunbar   unsigned complete_line;
33377af1c56SDaniel Dunbar   unsigned complete_column;
33477af1c56SDaniel Dunbar   struct CXUnsavedFile *unsaved_files;
33577af1c56SDaniel Dunbar   unsigned num_unsaved_files;
33677af1c56SDaniel Dunbar   unsigned options;
33777af1c56SDaniel Dunbar   CXCodeCompleteResults *result;
33877af1c56SDaniel Dunbar };
33977af1c56SDaniel Dunbar void clang_codeCompleteAt_Impl(void *UserData) {
34077af1c56SDaniel Dunbar   CodeCompleteAtInfo *CCAI = static_cast<CodeCompleteAtInfo*>(UserData);
34177af1c56SDaniel Dunbar   CXTranslationUnit TU = CCAI->TU;
34277af1c56SDaniel Dunbar   const char *complete_filename = CCAI->complete_filename;
34377af1c56SDaniel Dunbar   unsigned complete_line = CCAI->complete_line;
34477af1c56SDaniel Dunbar   unsigned complete_column = CCAI->complete_column;
34577af1c56SDaniel Dunbar   struct CXUnsavedFile *unsaved_files = CCAI->unsaved_files;
34677af1c56SDaniel Dunbar   unsigned num_unsaved_files = CCAI->num_unsaved_files;
34777af1c56SDaniel Dunbar   unsigned options = CCAI->options;
34877af1c56SDaniel Dunbar   CCAI->result = 0;
34977af1c56SDaniel Dunbar 
3508e984da8SDouglas Gregor #ifdef UDP_CODE_COMPLETION_LOGGER
3518e984da8SDouglas Gregor #ifdef UDP_CODE_COMPLETION_LOGGER_PORT
3528e984da8SDouglas Gregor   const llvm::TimeRecord &StartTime =  llvm::TimeRecord::getCurrentTime();
3538e984da8SDouglas Gregor #endif
3548e984da8SDouglas Gregor #endif
3558e984da8SDouglas Gregor 
3568e984da8SDouglas Gregor   bool EnableLogging = getenv("LIBCLANG_CODE_COMPLETION_LOGGING") != 0;
3578e984da8SDouglas Gregor 
358*91554285STed Kremenek   ASTUnit *AST = static_cast<ASTUnit *>(TU->TUData);
3598e984da8SDouglas Gregor   if (!AST)
36077af1c56SDaniel Dunbar     return;
3618e984da8SDouglas Gregor 
362ca5b0539SDouglas Gregor   ASTUnit::ConcurrencyCheck Check(*AST);
363ca5b0539SDouglas Gregor 
3648e984da8SDouglas Gregor   // Perform the remapping of source files.
3658e984da8SDouglas Gregor   llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
3668e984da8SDouglas Gregor   for (unsigned I = 0; I != num_unsaved_files; ++I) {
3678e984da8SDouglas Gregor     llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
3688e984da8SDouglas Gregor     const llvm::MemoryBuffer *Buffer
3698e984da8SDouglas Gregor       = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
3708e984da8SDouglas Gregor     RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
3718e984da8SDouglas Gregor                                            Buffer));
3728e984da8SDouglas Gregor   }
3738e984da8SDouglas Gregor 
3748e984da8SDouglas Gregor   if (EnableLogging) {
3758e984da8SDouglas Gregor     // FIXME: Add logging.
3768e984da8SDouglas Gregor   }
3778e984da8SDouglas Gregor 
3788e984da8SDouglas Gregor   // Parse the resulting source file to find code-completion results.
3798e984da8SDouglas Gregor   AllocatedCXCodeCompleteResults *Results = new AllocatedCXCodeCompleteResults;
3808e984da8SDouglas Gregor   Results->Results = 0;
3818e984da8SDouglas Gregor   Results->NumResults = 0;
3828e984da8SDouglas Gregor 
3838e984da8SDouglas Gregor   // Create a code-completion consumer to capture the results.
3848e984da8SDouglas Gregor   CaptureCompletionResults Capture(*Results);
3858e984da8SDouglas Gregor 
3868e984da8SDouglas Gregor   // Perform completion.
3878e984da8SDouglas Gregor   AST->CodeComplete(complete_filename, complete_line, complete_column,
388b68bc59aSDouglas Gregor                     RemappedFiles.data(), RemappedFiles.size(),
389b68bc59aSDouglas Gregor                     (options & CXCodeComplete_IncludeMacros),
390b68bc59aSDouglas Gregor                     (options & CXCodeComplete_IncludeCodePatterns),
391b68bc59aSDouglas Gregor                     Capture,
3928e984da8SDouglas Gregor                     *Results->Diag, Results->LangOpts, Results->SourceMgr,
393b97b666cSDouglas Gregor                     Results->FileMgr, Results->Diagnostics,
394b97b666cSDouglas Gregor                     Results->TemporaryBuffers);
3958e984da8SDouglas Gregor 
3968e984da8SDouglas Gregor 
3978e984da8SDouglas Gregor 
3988e984da8SDouglas Gregor #ifdef UDP_CODE_COMPLETION_LOGGER
3998e984da8SDouglas Gregor #ifdef UDP_CODE_COMPLETION_LOGGER_PORT
4008e984da8SDouglas Gregor   const llvm::TimeRecord &EndTime =  llvm::TimeRecord::getCurrentTime();
4018e984da8SDouglas Gregor   llvm::SmallString<256> LogResult;
4028e984da8SDouglas Gregor   llvm::raw_svector_ostream os(LogResult);
4038e984da8SDouglas Gregor 
4048e984da8SDouglas Gregor   // Figure out the language and whether or not it uses PCH.
4058e984da8SDouglas Gregor   const char *lang = 0;
4068e984da8SDouglas Gregor   bool usesPCH = false;
4078e984da8SDouglas Gregor 
4088e984da8SDouglas Gregor   for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
4098e984da8SDouglas Gregor        I != E; ++I) {
4108e984da8SDouglas Gregor     if (*I == 0)
4118e984da8SDouglas Gregor       continue;
4128e984da8SDouglas Gregor     if (strcmp(*I, "-x") == 0) {
4138e984da8SDouglas Gregor       if (I + 1 != E) {
4148e984da8SDouglas Gregor         lang = *(++I);
4158e984da8SDouglas Gregor         continue;
4168e984da8SDouglas Gregor       }
4178e984da8SDouglas Gregor     }
4188e984da8SDouglas Gregor     else if (strcmp(*I, "-include") == 0) {
4198e984da8SDouglas Gregor       if (I+1 != E) {
4208e984da8SDouglas Gregor         const char *arg = *(++I);
4218e984da8SDouglas Gregor         llvm::SmallString<512> pchName;
4228e984da8SDouglas Gregor         {
4238e984da8SDouglas Gregor           llvm::raw_svector_ostream os(pchName);
4248e984da8SDouglas Gregor           os << arg << ".pth";
4258e984da8SDouglas Gregor         }
4268e984da8SDouglas Gregor         pchName.push_back('\0');
4278e984da8SDouglas Gregor         struct stat stat_results;
4288e984da8SDouglas Gregor         if (stat(pchName.data(), &stat_results) == 0)
4298e984da8SDouglas Gregor           usesPCH = true;
4308e984da8SDouglas Gregor         continue;
4318e984da8SDouglas Gregor       }
4328e984da8SDouglas Gregor     }
4338e984da8SDouglas Gregor   }
4348e984da8SDouglas Gregor 
4358e984da8SDouglas Gregor   os << "{ ";
4368e984da8SDouglas Gregor   os << "\"wall\": " << (EndTime.getWallTime() - StartTime.getWallTime());
4378e984da8SDouglas Gregor   os << ", \"numRes\": " << Results->NumResults;
4388e984da8SDouglas Gregor   os << ", \"diags\": " << Results->Diagnostics.size();
4398e984da8SDouglas Gregor   os << ", \"pch\": " << (usesPCH ? "true" : "false");
4408e984da8SDouglas Gregor   os << ", \"lang\": \"" << (lang ? lang : "<unknown>") << '"';
4418e984da8SDouglas Gregor   const char *name = getlogin();
4428e984da8SDouglas Gregor   os << ", \"user\": \"" << (name ? name : "unknown") << '"';
4438e984da8SDouglas Gregor   os << ", \"clangVer\": \"" << getClangFullVersion() << '"';
4448e984da8SDouglas Gregor   os << " }";
4458e984da8SDouglas Gregor 
4468e984da8SDouglas Gregor   llvm::StringRef res = os.str();
4478e984da8SDouglas Gregor   if (res.size() > 0) {
4488e984da8SDouglas Gregor     do {
4498e984da8SDouglas Gregor       // Setup the UDP socket.
4508e984da8SDouglas Gregor       struct sockaddr_in servaddr;
4518e984da8SDouglas Gregor       bzero(&servaddr, sizeof(servaddr));
4528e984da8SDouglas Gregor       servaddr.sin_family = AF_INET;
4538e984da8SDouglas Gregor       servaddr.sin_port = htons(UDP_CODE_COMPLETION_LOGGER_PORT);
4548e984da8SDouglas Gregor       if (inet_pton(AF_INET, UDP_CODE_COMPLETION_LOGGER,
4558e984da8SDouglas Gregor                     &servaddr.sin_addr) <= 0)
4568e984da8SDouglas Gregor         break;
4578e984da8SDouglas Gregor 
4588e984da8SDouglas Gregor       int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
4598e984da8SDouglas Gregor       if (sockfd < 0)
4608e984da8SDouglas Gregor         break;
4618e984da8SDouglas Gregor 
4628e984da8SDouglas Gregor       sendto(sockfd, res.data(), res.size(), 0,
4638e984da8SDouglas Gregor              (struct sockaddr *)&servaddr, sizeof(servaddr));
4648e984da8SDouglas Gregor       close(sockfd);
4658e984da8SDouglas Gregor     }
4668e984da8SDouglas Gregor     while (false);
4678e984da8SDouglas Gregor   }
4688e984da8SDouglas Gregor #endif
4698e984da8SDouglas Gregor #endif
47077af1c56SDaniel Dunbar   CCAI->result = Results;
47177af1c56SDaniel Dunbar }
47277af1c56SDaniel Dunbar CXCodeCompleteResults *clang_codeCompleteAt(CXTranslationUnit TU,
47377af1c56SDaniel Dunbar                                             const char *complete_filename,
47477af1c56SDaniel Dunbar                                             unsigned complete_line,
47577af1c56SDaniel Dunbar                                             unsigned complete_column,
47677af1c56SDaniel Dunbar                                             struct CXUnsavedFile *unsaved_files,
47777af1c56SDaniel Dunbar                                             unsigned num_unsaved_files,
47877af1c56SDaniel Dunbar                                             unsigned options) {
47977af1c56SDaniel Dunbar   CodeCompleteAtInfo CCAI = { TU, complete_filename, complete_line,
48077af1c56SDaniel Dunbar                               complete_column, unsaved_files, num_unsaved_files,
48177af1c56SDaniel Dunbar                               options, 0 };
48277af1c56SDaniel Dunbar   llvm::CrashRecoveryContext CRC;
48377af1c56SDaniel Dunbar 
484b7383e6dSDaniel Dunbar   if (!RunSafely(CRC, clang_codeCompleteAt_Impl, &CCAI)) {
48577af1c56SDaniel Dunbar     fprintf(stderr, "libclang: crash detected in code completion\n");
486*91554285STed Kremenek     static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
48777af1c56SDaniel Dunbar     return 0;
48877af1c56SDaniel Dunbar   }
48977af1c56SDaniel Dunbar 
49077af1c56SDaniel Dunbar   return CCAI.result;
4918e984da8SDouglas Gregor }
4928e984da8SDouglas Gregor 
493b68bc59aSDouglas Gregor unsigned clang_defaultCodeCompleteOptions(void) {
494b68bc59aSDouglas Gregor   return CXCodeComplete_IncludeMacros;
495b68bc59aSDouglas Gregor }
496b68bc59aSDouglas Gregor 
497d5a2a073SDaniel Dunbar void clang_disposeCodeCompleteResults(CXCodeCompleteResults *ResultsIn) {
498d5a2a073SDaniel Dunbar   if (!ResultsIn)
499d5a2a073SDaniel Dunbar     return;
500d5a2a073SDaniel Dunbar 
501d5a2a073SDaniel Dunbar   AllocatedCXCodeCompleteResults *Results
502d5a2a073SDaniel Dunbar     = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
503d5a2a073SDaniel Dunbar   delete Results;
504d5a2a073SDaniel Dunbar }
505d5a2a073SDaniel Dunbar 
506d5a2a073SDaniel Dunbar unsigned
507d5a2a073SDaniel Dunbar clang_codeCompleteGetNumDiagnostics(CXCodeCompleteResults *ResultsIn) {
508d5a2a073SDaniel Dunbar   AllocatedCXCodeCompleteResults *Results
509d5a2a073SDaniel Dunbar     = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
510d5a2a073SDaniel Dunbar   if (!Results)
511d5a2a073SDaniel Dunbar     return 0;
512d5a2a073SDaniel Dunbar 
513d5a2a073SDaniel Dunbar   return Results->Diagnostics.size();
514d5a2a073SDaniel Dunbar }
515d5a2a073SDaniel Dunbar 
516d5a2a073SDaniel Dunbar CXDiagnostic
517d5a2a073SDaniel Dunbar clang_codeCompleteGetDiagnostic(CXCodeCompleteResults *ResultsIn,
518d5a2a073SDaniel Dunbar                                 unsigned Index) {
519d5a2a073SDaniel Dunbar   AllocatedCXCodeCompleteResults *Results
520d5a2a073SDaniel Dunbar     = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
521d5a2a073SDaniel Dunbar   if (!Results || Index >= Results->Diagnostics.size())
522d5a2a073SDaniel Dunbar     return 0;
523d5a2a073SDaniel Dunbar 
524d5a2a073SDaniel Dunbar   return new CXStoredDiagnostic(Results->Diagnostics[Index], Results->LangOpts);
525d5a2a073SDaniel Dunbar }
526d5a2a073SDaniel Dunbar 
527d5a2a073SDaniel Dunbar 
528d5a2a073SDaniel Dunbar } // end extern "C"
52949f67ce4SDouglas Gregor 
5308e3e8743SDouglas Gregor /// \brief Simple utility function that appends a \p New string to the given
5318e3e8743SDouglas Gregor /// \p Old string, using the \p Buffer for storage.
5328e3e8743SDouglas Gregor ///
5338e3e8743SDouglas Gregor /// \param Old The string to which we are appending. This parameter will be
5348e3e8743SDouglas Gregor /// updated to reflect the complete string.
5358e3e8743SDouglas Gregor ///
5368e3e8743SDouglas Gregor ///
5378e3e8743SDouglas Gregor /// \param New The string to append to \p Old.
5388e3e8743SDouglas Gregor ///
5398e3e8743SDouglas Gregor /// \param Buffer A buffer that stores the actual, concatenated string. It will
5408e3e8743SDouglas Gregor /// be used if the old string is already-non-empty.
5418e3e8743SDouglas Gregor static void AppendToString(llvm::StringRef &Old, llvm::StringRef New,
5428e3e8743SDouglas Gregor                            llvm::SmallString<256> &Buffer) {
5438e3e8743SDouglas Gregor   if (Old.empty()) {
5448e3e8743SDouglas Gregor     Old = New;
5458e3e8743SDouglas Gregor     return;
5468e3e8743SDouglas Gregor   }
5478e3e8743SDouglas Gregor 
5488e3e8743SDouglas Gregor   if (Buffer.empty())
5498e3e8743SDouglas Gregor     Buffer.append(Old.begin(), Old.end());
5508e3e8743SDouglas Gregor   Buffer.append(New.begin(), New.end());
5518e3e8743SDouglas Gregor   Old = Buffer.str();
5528e3e8743SDouglas Gregor }
5538e3e8743SDouglas Gregor 
5548e3e8743SDouglas Gregor /// \brief Get the typed-text blocks from the given code-completion string
5558e3e8743SDouglas Gregor /// and return them as a single string.
5568e3e8743SDouglas Gregor ///
5578e3e8743SDouglas Gregor /// \param String The code-completion string whose typed-text blocks will be
5588e3e8743SDouglas Gregor /// concatenated.
5598e3e8743SDouglas Gregor ///
5608e3e8743SDouglas Gregor /// \param Buffer A buffer used for storage of the completed name.
5618e3e8743SDouglas Gregor static llvm::StringRef GetTypedName(CodeCompletionString *String,
5628e3e8743SDouglas Gregor                                     llvm::SmallString<256> &Buffer) {
5638e3e8743SDouglas Gregor   llvm::StringRef Result;
5648e3e8743SDouglas Gregor   for (CodeCompletionString::iterator C = String->begin(), CEnd = String->end();
5658e3e8743SDouglas Gregor        C != CEnd; ++C) {
5668e3e8743SDouglas Gregor     if (C->Kind == CodeCompletionString::CK_TypedText)
5678e3e8743SDouglas Gregor       AppendToString(Result, C->Text, Buffer);
5688e3e8743SDouglas Gregor   }
5698e3e8743SDouglas Gregor 
5708e3e8743SDouglas Gregor   return Result;
5718e3e8743SDouglas Gregor }
5728e3e8743SDouglas Gregor 
57349f67ce4SDouglas Gregor namespace {
57449f67ce4SDouglas Gregor   struct OrderCompletionResults {
57549f67ce4SDouglas Gregor     bool operator()(const CXCompletionResult &XR,
57649f67ce4SDouglas Gregor                     const CXCompletionResult &YR) const {
57749f67ce4SDouglas Gregor       CXStoredCodeCompletionString *X
57849f67ce4SDouglas Gregor         = (CXStoredCodeCompletionString *)XR.CompletionString;
57949f67ce4SDouglas Gregor       CXStoredCodeCompletionString *Y
58049f67ce4SDouglas Gregor         = (CXStoredCodeCompletionString *)YR.CompletionString;
58149f67ce4SDouglas Gregor 
5828e3e8743SDouglas Gregor       llvm::SmallString<256> XBuffer;
5838e3e8743SDouglas Gregor       llvm::StringRef XText = GetTypedName(X, XBuffer);
5848e3e8743SDouglas Gregor       llvm::SmallString<256> YBuffer;
5858e3e8743SDouglas Gregor       llvm::StringRef YText = GetTypedName(Y, YBuffer);
58649f67ce4SDouglas Gregor 
5878e3e8743SDouglas Gregor       if (XText.empty() || YText.empty())
5888e3e8743SDouglas Gregor         return !XText.empty();
5898e3e8743SDouglas Gregor 
5908e3e8743SDouglas Gregor       int result = XText.compare_lower(YText);
59149f67ce4SDouglas Gregor       if (result < 0)
59249f67ce4SDouglas Gregor         return true;
59349f67ce4SDouglas Gregor       if (result > 0)
59449f67ce4SDouglas Gregor         return false;
59549f67ce4SDouglas Gregor 
5968e3e8743SDouglas Gregor       result = XText.compare(YText);
597c7a7d92aSDouglas Gregor       return result < 0;
59849f67ce4SDouglas Gregor     }
59949f67ce4SDouglas Gregor   };
60049f67ce4SDouglas Gregor }
60149f67ce4SDouglas Gregor 
60249f67ce4SDouglas Gregor extern "C" {
60349f67ce4SDouglas Gregor   void clang_sortCodeCompletionResults(CXCompletionResult *Results,
60449f67ce4SDouglas Gregor                                        unsigned NumResults) {
60549f67ce4SDouglas Gregor     std::stable_sort(Results, Results + NumResults, OrderCompletionResults());
60649f67ce4SDouglas Gregor   }
60749f67ce4SDouglas Gregor }
608