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"
167df92ae9STed Kremenek #include "CXTranslationUnit.h"
174b4f3699STed Kremenek #include "CXString.h"
1863745d59SDouglas Gregor #include "CXCursor.h"
195b8ad406STed Kremenek #include "CXString.h"
20d5a2a073SDaniel Dunbar #include "CIndexDiagnostic.h"
2163745d59SDouglas Gregor #include "clang/AST/Type.h"
2263745d59SDouglas Gregor #include "clang/AST/Decl.h"
2363745d59SDouglas Gregor #include "clang/AST/DeclObjC.h"
24d5a2a073SDaniel Dunbar #include "clang/Basic/SourceManager.h"
25d5a2a073SDaniel Dunbar #include "clang/Basic/FileManager.h"
268e984da8SDouglas Gregor #include "clang/Frontend/ASTUnit.h"
27d5a2a073SDaniel Dunbar #include "clang/Frontend/CompilerInstance.h"
28d5a2a073SDaniel Dunbar #include "clang/Frontend/FrontendDiagnostic.h"
29d5a2a073SDaniel Dunbar #include "clang/Sema/CodeCompleteConsumer.h"
30028d3e4dSDouglas Gregor #include "llvm/ADT/SmallString.h"
31d5a2a073SDaniel Dunbar #include "llvm/ADT/StringExtras.h"
329aeaa4d6SDouglas Gregor #include "llvm/Support/Atomic.h"
3377af1c56SDaniel Dunbar #include "llvm/Support/CrashRecoveryContext.h"
34d5a2a073SDaniel Dunbar #include "llvm/Support/MemoryBuffer.h"
35028d3e4dSDouglas Gregor #include "llvm/Support/Timer.h"
36028d3e4dSDouglas Gregor #include "llvm/Support/raw_ostream.h"
378aaf4995SMichael J. Spencer #include "llvm/Support/Program.h"
38d6009ffbSDouglas Gregor #include <cstdlib>
39d6009ffbSDouglas Gregor #include <cstdio>
40d5a2a073SDaniel Dunbar 
41028d3e4dSDouglas Gregor 
42d5a2a073SDaniel Dunbar #ifdef UDP_CODE_COMPLETION_LOGGER
43d5a2a073SDaniel Dunbar #include "clang/Basic/Version.h"
44d5a2a073SDaniel Dunbar #include <arpa/inet.h>
45d5a2a073SDaniel Dunbar #include <sys/socket.h>
46d5a2a073SDaniel Dunbar #include <sys/types.h>
47d5a2a073SDaniel Dunbar #include <unistd.h>
48d5a2a073SDaniel Dunbar #endif
49d5a2a073SDaniel Dunbar 
50d5a2a073SDaniel Dunbar using namespace clang;
51d5a2a073SDaniel Dunbar using namespace clang::cxstring;
52d5a2a073SDaniel Dunbar 
53d5a2a073SDaniel Dunbar extern "C" {
54d5a2a073SDaniel Dunbar 
55d5a2a073SDaniel Dunbar enum CXCompletionChunkKind
56d5a2a073SDaniel Dunbar clang_getCompletionChunkKind(CXCompletionString completion_string,
57d5a2a073SDaniel Dunbar                              unsigned chunk_number) {
58b278aafbSDouglas Gregor   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
59d5a2a073SDaniel Dunbar   if (!CCStr || chunk_number >= CCStr->size())
60d5a2a073SDaniel Dunbar     return CXCompletionChunk_Text;
61d5a2a073SDaniel Dunbar 
62d5a2a073SDaniel Dunbar   switch ((*CCStr)[chunk_number].Kind) {
63d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_TypedText:
64d5a2a073SDaniel Dunbar     return CXCompletionChunk_TypedText;
65d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Text:
66d5a2a073SDaniel Dunbar     return CXCompletionChunk_Text;
67d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Optional:
68d5a2a073SDaniel Dunbar     return CXCompletionChunk_Optional;
69d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Placeholder:
70d5a2a073SDaniel Dunbar     return CXCompletionChunk_Placeholder;
71d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Informative:
72d5a2a073SDaniel Dunbar     return CXCompletionChunk_Informative;
73d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_ResultType:
74d5a2a073SDaniel Dunbar     return CXCompletionChunk_ResultType;
75d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_CurrentParameter:
76d5a2a073SDaniel Dunbar     return CXCompletionChunk_CurrentParameter;
77d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftParen:
78d5a2a073SDaniel Dunbar     return CXCompletionChunk_LeftParen;
79d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightParen:
80d5a2a073SDaniel Dunbar     return CXCompletionChunk_RightParen;
81d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftBracket:
82d5a2a073SDaniel Dunbar     return CXCompletionChunk_LeftBracket;
83d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightBracket:
84d5a2a073SDaniel Dunbar     return CXCompletionChunk_RightBracket;
85d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftBrace:
86d5a2a073SDaniel Dunbar     return CXCompletionChunk_LeftBrace;
87d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightBrace:
88d5a2a073SDaniel Dunbar     return CXCompletionChunk_RightBrace;
89d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftAngle:
90d5a2a073SDaniel Dunbar     return CXCompletionChunk_LeftAngle;
91d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightAngle:
92d5a2a073SDaniel Dunbar     return CXCompletionChunk_RightAngle;
93d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Comma:
94d5a2a073SDaniel Dunbar     return CXCompletionChunk_Comma;
95d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Colon:
96d5a2a073SDaniel Dunbar     return CXCompletionChunk_Colon;
97d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_SemiColon:
98d5a2a073SDaniel Dunbar     return CXCompletionChunk_SemiColon;
99d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Equal:
100d5a2a073SDaniel Dunbar     return CXCompletionChunk_Equal;
101d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_HorizontalSpace:
102d5a2a073SDaniel Dunbar     return CXCompletionChunk_HorizontalSpace;
103d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_VerticalSpace:
104d5a2a073SDaniel Dunbar     return CXCompletionChunk_VerticalSpace;
105d5a2a073SDaniel Dunbar   }
106d5a2a073SDaniel Dunbar 
107d5a2a073SDaniel Dunbar   // Should be unreachable, but let's be careful.
108d5a2a073SDaniel Dunbar   return CXCompletionChunk_Text;
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())
11591554285STed Kremenek     return createCXString((const char*)0);
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:
1388ed5b770SDouglas Gregor     return createCXString((*CCStr)[chunk_number].Text, false);
13909737ee8SDouglas Gregor 
140d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Optional:
141d5a2a073SDaniel Dunbar     // Note: treated as an empty text block.
142d5a2a073SDaniel Dunbar     return createCXString("");
143d5a2a073SDaniel Dunbar   }
144d5a2a073SDaniel Dunbar 
145d5a2a073SDaniel Dunbar   // Should be unreachable, but let's be careful.
14691554285STed Kremenek   return createCXString((const char*)0);
147d5a2a073SDaniel Dunbar }
148d5a2a073SDaniel Dunbar 
149d5a2a073SDaniel Dunbar 
150d5a2a073SDaniel Dunbar CXCompletionString
151d5a2a073SDaniel Dunbar clang_getCompletionChunkCompletionString(CXCompletionString completion_string,
152d5a2a073SDaniel Dunbar                                          unsigned chunk_number) {
153b278aafbSDouglas Gregor   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
154d5a2a073SDaniel Dunbar   if (!CCStr || chunk_number >= CCStr->size())
155d5a2a073SDaniel Dunbar     return 0;
156d5a2a073SDaniel Dunbar 
157d5a2a073SDaniel Dunbar   switch ((*CCStr)[chunk_number].Kind) {
158d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_TypedText:
159d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Text:
160d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Placeholder:
161d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_CurrentParameter:
162d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Informative:
163d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftParen:
164d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightParen:
165d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftBracket:
166d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightBracket:
167d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftBrace:
168d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightBrace:
169d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftAngle:
170d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightAngle:
171d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Comma:
172d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_ResultType:
173d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Colon:
174d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_SemiColon:
175d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Equal:
176d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_HorizontalSpace:
177d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_VerticalSpace:
178d5a2a073SDaniel Dunbar     return 0;
179d5a2a073SDaniel Dunbar 
180d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Optional:
181d5a2a073SDaniel Dunbar     // Note: treated as an empty text block.
182d5a2a073SDaniel Dunbar     return (*CCStr)[chunk_number].Optional;
183d5a2a073SDaniel Dunbar   }
184d5a2a073SDaniel Dunbar 
185d5a2a073SDaniel Dunbar   // Should be unreachable, but let's be careful.
186d5a2a073SDaniel Dunbar   return 0;
187d5a2a073SDaniel Dunbar }
188d5a2a073SDaniel Dunbar 
189d5a2a073SDaniel Dunbar unsigned clang_getNumCompletionChunks(CXCompletionString completion_string) {
190b278aafbSDouglas Gregor   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
191d5a2a073SDaniel Dunbar   return CCStr? CCStr->size() : 0;
192d5a2a073SDaniel Dunbar }
193d5a2a073SDaniel Dunbar 
194a2db793fSDouglas Gregor unsigned clang_getCompletionPriority(CXCompletionString completion_string) {
195b278aafbSDouglas Gregor   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
19647bb3e2bSBill Wendling   return CCStr? CCStr->getPriority() : unsigned(CCP_Unlikely);
197a2db793fSDouglas Gregor }
198a2db793fSDouglas Gregor 
199f757a12dSDouglas Gregor enum CXAvailabilityKind
200f757a12dSDouglas Gregor clang_getCompletionAvailability(CXCompletionString completion_string) {
201b278aafbSDouglas Gregor   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
202b278aafbSDouglas Gregor   return CCStr? static_cast<CXAvailabilityKind>(CCStr->getAvailability())
203b278aafbSDouglas Gregor               : CXAvailability_Available;
204f757a12dSDouglas Gregor }
205f757a12dSDouglas Gregor 
206*98ea7f67SErik Verbruggen unsigned clang_getCompletionNumAnnotations(CXCompletionString completion_string)
207*98ea7f67SErik Verbruggen {
208*98ea7f67SErik Verbruggen   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
209*98ea7f67SErik Verbruggen   return CCStr ? CCStr->getAnnotationCount() : 0;
210*98ea7f67SErik Verbruggen }
211*98ea7f67SErik Verbruggen 
212*98ea7f67SErik Verbruggen CXString clang_getCompletionAnnotation(CXCompletionString completion_string,
213*98ea7f67SErik Verbruggen                                        unsigned annotation_number) {
214*98ea7f67SErik Verbruggen   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
215*98ea7f67SErik Verbruggen   return CCStr ? createCXString(CCStr->getAnnotation(annotation_number))
216*98ea7f67SErik Verbruggen                : createCXString((const char *) 0);
217*98ea7f67SErik Verbruggen }
218*98ea7f67SErik Verbruggen 
219*98ea7f67SErik Verbruggen 
220d5a2a073SDaniel Dunbar /// \brief The CXCodeCompleteResults structure we allocate internally;
221d5a2a073SDaniel Dunbar /// the client only sees the initial CXCodeCompleteResults structure.
222d5a2a073SDaniel Dunbar struct AllocatedCXCodeCompleteResults : public CXCodeCompleteResults {
223c30dcecbSAnders Carlsson   AllocatedCXCodeCompleteResults(const FileSystemOptions& FileSystemOpts);
224d5a2a073SDaniel Dunbar   ~AllocatedCXCodeCompleteResults();
225d5a2a073SDaniel Dunbar 
226d5a2a073SDaniel Dunbar   /// \brief Diagnostics produced while performing code completion.
2270e62c1ccSChris Lattner   SmallVector<StoredDiagnostic, 8> Diagnostics;
228d5a2a073SDaniel Dunbar 
229d5a2a073SDaniel Dunbar   /// \brief Diag object
2309c902b55SDavid Blaikie   llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diag;
231d5a2a073SDaniel Dunbar 
232d5a2a073SDaniel Dunbar   /// \brief Language options used to adjust source locations.
233d5a2a073SDaniel Dunbar   LangOptions LangOpts;
234d5a2a073SDaniel Dunbar 
2355159f616SChris Lattner   FileSystemOptions FileSystemOpts;
2365159f616SChris Lattner 
237d5a2a073SDaniel Dunbar   /// \brief File manager, used for diagnostics.
2385e14d39aSTed Kremenek   llvm::IntrusiveRefCntPtr<FileManager> FileMgr;
239d5a2a073SDaniel Dunbar 
24071731d6bSArgyrios Kyrtzidis   /// \brief Source manager, used for diagnostics.
2415e14d39aSTed Kremenek   llvm::IntrusiveRefCntPtr<SourceManager> SourceMgr;
24271731d6bSArgyrios Kyrtzidis 
243d5a2a073SDaniel Dunbar   /// \brief Temporary files that should be removed once we have finished
244d5a2a073SDaniel Dunbar   /// with the code-completion results.
245d5a2a073SDaniel Dunbar   std::vector<llvm::sys::Path> TemporaryFiles;
246d8a5dba9SDouglas Gregor 
2473f5a9efbSChris Lattner   /// \brief Temporary buffers that will be deleted once we have finished with
2483f5a9efbSChris Lattner   /// the code-completion results.
2490e62c1ccSChris Lattner   SmallVector<const llvm::MemoryBuffer *, 1> TemporaryBuffers;
250b278aafbSDouglas Gregor 
251162b712dSDouglas Gregor   /// \brief Allocator used to store globally cached code-completion results.
252162b712dSDouglas Gregor   llvm::IntrusiveRefCntPtr<clang::GlobalCodeCompletionAllocator>
253162b712dSDouglas Gregor     CachedCompletionAllocator;
254162b712dSDouglas Gregor 
255b278aafbSDouglas Gregor   /// \brief Allocator used to store code completion results.
2566c7cb188SDouglas Gregor   clang::CodeCompletionAllocator CodeCompletionAllocator;
2572132584dSDouglas Gregor 
2582132584dSDouglas Gregor   /// \brief Context under which completion occurred.
2592132584dSDouglas Gregor   enum clang::CodeCompletionContext::Kind ContextKind;
2602132584dSDouglas Gregor 
2612132584dSDouglas Gregor   /// \brief A bitfield representing the acceptable completions for the
2622132584dSDouglas Gregor   /// current context.
2632132584dSDouglas Gregor   unsigned long long Contexts;
26463745d59SDouglas Gregor 
265ea777403SDouglas Gregor   /// \brief The kind of the container for the current context for completions.
26663745d59SDouglas Gregor   enum CXCursorKind ContainerKind;
267ea777403SDouglas Gregor   /// \brief The USR of the container for the current context for completions.
26863745d59SDouglas Gregor   CXString ContainerUSR;
269ea777403SDouglas Gregor   /// \brief a boolean value indicating whether there is complete information
270ea777403SDouglas Gregor   /// about the container
27163745d59SDouglas Gregor   unsigned ContainerIsIncomplete;
272ea777403SDouglas Gregor 
273ea777403SDouglas Gregor   /// \brief A string containing the Objective-C selector entered thus far for a
274ea777403SDouglas Gregor   /// message send.
275ea777403SDouglas Gregor   std::string Selector;
276d5a2a073SDaniel Dunbar };
277d5a2a073SDaniel Dunbar 
27868dbaeadSDouglas Gregor /// \brief Tracks the number of code-completion result objects that are
27968dbaeadSDouglas Gregor /// currently active.
28068dbaeadSDouglas Gregor ///
28168dbaeadSDouglas Gregor /// Used for debugging purposes only.
2829aeaa4d6SDouglas Gregor static llvm::sys::cas_flag CodeCompletionResultObjects;
28368dbaeadSDouglas Gregor 
284c30dcecbSAnders Carlsson AllocatedCXCodeCompleteResults::AllocatedCXCodeCompleteResults(
285c30dcecbSAnders Carlsson                                       const FileSystemOptions& FileSystemOpts)
286d0040648SArgyrios Kyrtzidis   : CXCodeCompleteResults(),
2879c902b55SDavid Blaikie     Diag(new DiagnosticsEngine(
288d0040648SArgyrios Kyrtzidis                    llvm::IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs))),
289c30dcecbSAnders Carlsson     FileSystemOpts(FileSystemOpts),
2905e14d39aSTed Kremenek     FileMgr(new FileManager(FileSystemOpts)),
291e442fe3dSDouglas Gregor     SourceMgr(new SourceManager(*Diag, *FileMgr)),
292e442fe3dSDouglas Gregor     Contexts(CXCompletionContext_Unknown),
293e442fe3dSDouglas Gregor     ContainerKind(CXCursor_InvalidCode),
294e442fe3dSDouglas Gregor     ContainerUSR(createCXString("")),
295e442fe3dSDouglas Gregor     ContainerIsIncomplete(1)
296e442fe3dSDouglas Gregor {
29768dbaeadSDouglas Gregor   if (getenv("LIBCLANG_OBJTRACKING")) {
2989aeaa4d6SDouglas Gregor     llvm::sys::AtomicIncrement(&CodeCompletionResultObjects);
29968dbaeadSDouglas Gregor     fprintf(stderr, "+++ %d completion results\n", CodeCompletionResultObjects);
30068dbaeadSDouglas Gregor   }
30168dbaeadSDouglas Gregor }
302d5a2a073SDaniel Dunbar 
303d5a2a073SDaniel Dunbar AllocatedCXCodeCompleteResults::~AllocatedCXCodeCompleteResults() {
304d5a2a073SDaniel Dunbar   delete [] Results;
305d5a2a073SDaniel Dunbar 
30663745d59SDouglas Gregor   clang_disposeString(ContainerUSR);
30763745d59SDouglas Gregor 
308d5a2a073SDaniel Dunbar   for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
309d5a2a073SDaniel Dunbar     TemporaryFiles[I].eraseFromDisk();
310d8a5dba9SDouglas Gregor   for (unsigned I = 0, N = TemporaryBuffers.size(); I != N; ++I)
311d8a5dba9SDouglas Gregor     delete TemporaryBuffers[I];
31268dbaeadSDouglas Gregor 
31368dbaeadSDouglas Gregor   if (getenv("LIBCLANG_OBJTRACKING")) {
3149aeaa4d6SDouglas Gregor     llvm::sys::AtomicDecrement(&CodeCompletionResultObjects);
31568dbaeadSDouglas Gregor     fprintf(stderr, "--- %d completion results\n", CodeCompletionResultObjects);
31668dbaeadSDouglas Gregor   }
317d5a2a073SDaniel Dunbar }
318d5a2a073SDaniel Dunbar 
3198e984da8SDouglas Gregor } // end extern "C"
3208e984da8SDouglas Gregor 
3212132584dSDouglas Gregor static unsigned long long getContextsForContextKind(
3222132584dSDouglas Gregor                                           enum CodeCompletionContext::Kind kind,
3232132584dSDouglas Gregor                                                     Sema &S) {
3242132584dSDouglas Gregor   unsigned long long contexts = 0;
3252132584dSDouglas Gregor   switch (kind) {
3262132584dSDouglas Gregor     case CodeCompletionContext::CCC_OtherWithMacros: {
3272132584dSDouglas Gregor       //We can allow macros here, but we don't know what else is permissible
3282132584dSDouglas Gregor       //So we'll say the only thing permissible are macros
3292132584dSDouglas Gregor       contexts = CXCompletionContext_MacroName;
3302132584dSDouglas Gregor       break;
3312132584dSDouglas Gregor     }
3322132584dSDouglas Gregor     case CodeCompletionContext::CCC_TopLevel:
3332132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCIvarList:
3342132584dSDouglas Gregor     case CodeCompletionContext::CCC_ClassStructUnion:
3352132584dSDouglas Gregor     case CodeCompletionContext::CCC_Type: {
3362132584dSDouglas Gregor       contexts = CXCompletionContext_AnyType |
3372132584dSDouglas Gregor                  CXCompletionContext_ObjCInterface;
3382132584dSDouglas Gregor       if (S.getLangOptions().CPlusPlus) {
3392132584dSDouglas Gregor         contexts |= CXCompletionContext_EnumTag |
3402132584dSDouglas Gregor                     CXCompletionContext_UnionTag |
3412132584dSDouglas Gregor                     CXCompletionContext_StructTag |
3422132584dSDouglas Gregor                     CXCompletionContext_ClassTag |
3432132584dSDouglas Gregor                     CXCompletionContext_NestedNameSpecifier;
3442132584dSDouglas Gregor       }
3452132584dSDouglas Gregor       break;
3462132584dSDouglas Gregor     }
3472132584dSDouglas Gregor     case CodeCompletionContext::CCC_Statement: {
3482132584dSDouglas Gregor       contexts = CXCompletionContext_AnyType |
3492132584dSDouglas Gregor                  CXCompletionContext_ObjCInterface |
3502132584dSDouglas Gregor                  CXCompletionContext_AnyValue;
3512132584dSDouglas Gregor       if (S.getLangOptions().CPlusPlus) {
3522132584dSDouglas Gregor         contexts |= CXCompletionContext_EnumTag |
3532132584dSDouglas Gregor                     CXCompletionContext_UnionTag |
3542132584dSDouglas Gregor                     CXCompletionContext_StructTag |
3552132584dSDouglas Gregor                     CXCompletionContext_ClassTag |
3562132584dSDouglas Gregor                     CXCompletionContext_NestedNameSpecifier;
3572132584dSDouglas Gregor       }
3582132584dSDouglas Gregor       break;
3592132584dSDouglas Gregor     }
3602132584dSDouglas Gregor     case CodeCompletionContext::CCC_Expression: {
3612132584dSDouglas Gregor       contexts = CXCompletionContext_AnyValue;
3622132584dSDouglas Gregor       if (S.getLangOptions().CPlusPlus) {
3632132584dSDouglas Gregor         contexts |= CXCompletionContext_AnyType |
3642132584dSDouglas Gregor                     CXCompletionContext_ObjCInterface |
3652132584dSDouglas Gregor                     CXCompletionContext_EnumTag |
3662132584dSDouglas Gregor                     CXCompletionContext_UnionTag |
3672132584dSDouglas Gregor                     CXCompletionContext_StructTag |
3682132584dSDouglas Gregor                     CXCompletionContext_ClassTag |
3692132584dSDouglas Gregor                     CXCompletionContext_NestedNameSpecifier;
3702132584dSDouglas Gregor       }
3712132584dSDouglas Gregor       break;
3722132584dSDouglas Gregor     }
3732132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCMessageReceiver: {
3742132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCObjectValue |
3752132584dSDouglas Gregor                  CXCompletionContext_ObjCSelectorValue |
3762132584dSDouglas Gregor                  CXCompletionContext_ObjCInterface;
3772132584dSDouglas Gregor       if (S.getLangOptions().CPlusPlus) {
3782132584dSDouglas Gregor         contexts |= CXCompletionContext_CXXClassTypeValue |
3792132584dSDouglas Gregor                     CXCompletionContext_AnyType |
3802132584dSDouglas Gregor                     CXCompletionContext_EnumTag |
3812132584dSDouglas Gregor                     CXCompletionContext_UnionTag |
3822132584dSDouglas Gregor                     CXCompletionContext_StructTag |
3832132584dSDouglas Gregor                     CXCompletionContext_ClassTag |
3842132584dSDouglas Gregor                     CXCompletionContext_NestedNameSpecifier;
3852132584dSDouglas Gregor       }
3862132584dSDouglas Gregor       break;
3872132584dSDouglas Gregor     }
3882132584dSDouglas Gregor     case CodeCompletionContext::CCC_DotMemberAccess: {
3892132584dSDouglas Gregor       contexts = CXCompletionContext_DotMemberAccess;
3902132584dSDouglas Gregor       break;
3912132584dSDouglas Gregor     }
3922132584dSDouglas Gregor     case CodeCompletionContext::CCC_ArrowMemberAccess: {
3932132584dSDouglas Gregor       contexts = CXCompletionContext_ArrowMemberAccess;
3942132584dSDouglas Gregor       break;
3952132584dSDouglas Gregor     }
3962132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCPropertyAccess: {
3972132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCPropertyAccess;
3982132584dSDouglas Gregor       break;
3992132584dSDouglas Gregor     }
4002132584dSDouglas Gregor     case CodeCompletionContext::CCC_EnumTag: {
4012132584dSDouglas Gregor       contexts = CXCompletionContext_EnumTag |
4022132584dSDouglas Gregor                  CXCompletionContext_NestedNameSpecifier;
4032132584dSDouglas Gregor       break;
4042132584dSDouglas Gregor     }
4052132584dSDouglas Gregor     case CodeCompletionContext::CCC_UnionTag: {
4062132584dSDouglas Gregor       contexts = CXCompletionContext_UnionTag |
4072132584dSDouglas Gregor                  CXCompletionContext_NestedNameSpecifier;
4082132584dSDouglas Gregor       break;
4092132584dSDouglas Gregor     }
4102132584dSDouglas Gregor     case CodeCompletionContext::CCC_ClassOrStructTag: {
4112132584dSDouglas Gregor       contexts = CXCompletionContext_StructTag |
4122132584dSDouglas Gregor                  CXCompletionContext_ClassTag |
4132132584dSDouglas Gregor                  CXCompletionContext_NestedNameSpecifier;
4142132584dSDouglas Gregor       break;
4152132584dSDouglas Gregor     }
4162132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCProtocolName: {
4172132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCProtocol;
4182132584dSDouglas Gregor       break;
4192132584dSDouglas Gregor     }
4202132584dSDouglas Gregor     case CodeCompletionContext::CCC_Namespace: {
4212132584dSDouglas Gregor       contexts = CXCompletionContext_Namespace;
4222132584dSDouglas Gregor       break;
4232132584dSDouglas Gregor     }
4242132584dSDouglas Gregor     case CodeCompletionContext::CCC_PotentiallyQualifiedName: {
4252132584dSDouglas Gregor       contexts = CXCompletionContext_NestedNameSpecifier;
4262132584dSDouglas Gregor       break;
4272132584dSDouglas Gregor     }
4282132584dSDouglas Gregor     case CodeCompletionContext::CCC_MacroNameUse: {
4292132584dSDouglas Gregor       contexts = CXCompletionContext_MacroName;
4302132584dSDouglas Gregor       break;
4312132584dSDouglas Gregor     }
4322132584dSDouglas Gregor     case CodeCompletionContext::CCC_NaturalLanguage: {
4332132584dSDouglas Gregor       contexts = CXCompletionContext_NaturalLanguage;
4342132584dSDouglas Gregor       break;
4352132584dSDouglas Gregor     }
4362132584dSDouglas Gregor     case CodeCompletionContext::CCC_SelectorName: {
4372132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCSelectorName;
4382132584dSDouglas Gregor       break;
4392132584dSDouglas Gregor     }
4402132584dSDouglas Gregor     case CodeCompletionContext::CCC_ParenthesizedExpression: {
4412132584dSDouglas Gregor       contexts = CXCompletionContext_AnyType |
4422132584dSDouglas Gregor                  CXCompletionContext_ObjCInterface |
4432132584dSDouglas Gregor                  CXCompletionContext_AnyValue;
4442132584dSDouglas Gregor       if (S.getLangOptions().CPlusPlus) {
4452132584dSDouglas Gregor         contexts |= CXCompletionContext_EnumTag |
4462132584dSDouglas Gregor                     CXCompletionContext_UnionTag |
4472132584dSDouglas Gregor                     CXCompletionContext_StructTag |
4482132584dSDouglas Gregor                     CXCompletionContext_ClassTag |
4492132584dSDouglas Gregor                     CXCompletionContext_NestedNameSpecifier;
4502132584dSDouglas Gregor       }
4512132584dSDouglas Gregor       break;
4522132584dSDouglas Gregor     }
4532132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCInstanceMessage: {
4542132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCInstanceMessage;
4552132584dSDouglas Gregor       break;
4562132584dSDouglas Gregor     }
4572132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCClassMessage: {
4582132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCClassMessage;
4592132584dSDouglas Gregor       break;
4602132584dSDouglas Gregor     }
4612c595adfSDouglas Gregor     case CodeCompletionContext::CCC_ObjCInterfaceName: {
4622132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCInterface;
4632132584dSDouglas Gregor       break;
4642132584dSDouglas Gregor     }
4652132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCCategoryName: {
4662132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCCategory;
4672132584dSDouglas Gregor       break;
4682132584dSDouglas Gregor     }
4692132584dSDouglas Gregor     case CodeCompletionContext::CCC_Other:
4702132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCInterface:
4712132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCImplementation:
4722132584dSDouglas Gregor     case CodeCompletionContext::CCC_Name:
4732132584dSDouglas Gregor     case CodeCompletionContext::CCC_MacroName:
4742132584dSDouglas Gregor     case CodeCompletionContext::CCC_PreprocessorExpression:
4752132584dSDouglas Gregor     case CodeCompletionContext::CCC_PreprocessorDirective:
4762132584dSDouglas Gregor     case CodeCompletionContext::CCC_TypeQualifiers: {
4772132584dSDouglas Gregor       //Only Clang results should be accepted, so we'll set all of the other
4782132584dSDouglas Gregor       //context bits to 0 (i.e. the empty set)
4792132584dSDouglas Gregor       contexts = CXCompletionContext_Unexposed;
4802132584dSDouglas Gregor       break;
4812132584dSDouglas Gregor     }
4822132584dSDouglas Gregor     case CodeCompletionContext::CCC_Recovery: {
4832132584dSDouglas Gregor       //We don't know what the current context is, so we'll return unknown
4842132584dSDouglas Gregor       //This is the equivalent of setting all of the other context bits
4852132584dSDouglas Gregor       contexts = CXCompletionContext_Unknown;
4862132584dSDouglas Gregor       break;
4872132584dSDouglas Gregor     }
4882132584dSDouglas Gregor   }
4892132584dSDouglas Gregor   return contexts;
4902132584dSDouglas Gregor }
4912132584dSDouglas Gregor 
4928e984da8SDouglas Gregor namespace {
4938e984da8SDouglas Gregor   class CaptureCompletionResults : public CodeCompleteConsumer {
4948e984da8SDouglas Gregor     AllocatedCXCodeCompleteResults &AllocatedResults;
4950e62c1ccSChris Lattner     SmallVector<CXCompletionResult, 16> StoredResults;
49663745d59SDouglas Gregor     CXTranslationUnit *TU;
4978e984da8SDouglas Gregor   public:
49863745d59SDouglas Gregor     CaptureCompletionResults(AllocatedCXCodeCompleteResults &Results,
49963745d59SDouglas Gregor                              CXTranslationUnit *TranslationUnit)
50039982197SDouglas Gregor       : CodeCompleteConsumer(true, false, true, false),
50163745d59SDouglas Gregor         AllocatedResults(Results), TU(TranslationUnit) { }
50236e3b5c7SDouglas Gregor     ~CaptureCompletionResults() { Finish(); }
5038e984da8SDouglas Gregor 
50400c37ef0SDouglas Gregor     virtual void ProcessCodeCompleteResults(Sema &S,
50500c37ef0SDouglas Gregor                                             CodeCompletionContext Context,
506276321a9SJohn McCall                                             CodeCompletionResult *Results,
5078e984da8SDouglas Gregor                                             unsigned NumResults) {
50836e3b5c7SDouglas Gregor       StoredResults.reserve(StoredResults.size() + NumResults);
5098e984da8SDouglas Gregor       for (unsigned I = 0; I != NumResults; ++I) {
510b278aafbSDouglas Gregor         CodeCompletionString *StoredCompletion
511b278aafbSDouglas Gregor           = Results[I].CreateCodeCompletionString(S,
512b278aafbSDouglas Gregor                                       AllocatedResults.CodeCompletionAllocator);
51336e3b5c7SDouglas Gregor 
51436e3b5c7SDouglas Gregor         CXCompletionResult R;
51536e3b5c7SDouglas Gregor         R.CursorKind = Results[I].CursorKind;
51636e3b5c7SDouglas Gregor         R.CompletionString = StoredCompletion;
51736e3b5c7SDouglas Gregor         StoredResults.push_back(R);
5188e984da8SDouglas Gregor       }
5192132584dSDouglas Gregor 
52063745d59SDouglas Gregor       enum CodeCompletionContext::Kind contextKind = Context.getKind();
5212132584dSDouglas Gregor 
52263745d59SDouglas Gregor       AllocatedResults.ContextKind = contextKind;
52363745d59SDouglas Gregor       AllocatedResults.Contexts = getContextsForContextKind(contextKind, S);
52463745d59SDouglas Gregor 
525ea777403SDouglas Gregor       AllocatedResults.Selector = "";
526ea777403SDouglas Gregor       if (Context.getNumSelIdents() > 0) {
527ea777403SDouglas Gregor         for (unsigned i = 0; i < Context.getNumSelIdents(); i++) {
528ea777403SDouglas Gregor           IdentifierInfo *selIdent = Context.getSelIdents()[i];
529ea777403SDouglas Gregor           if (selIdent != NULL) {
530ea777403SDouglas Gregor             StringRef selectorString = Context.getSelIdents()[i]->getName();
531632500cbSBenjamin Kramer             AllocatedResults.Selector += selectorString;
532ea777403SDouglas Gregor           }
533ea777403SDouglas Gregor           AllocatedResults.Selector += ":";
534ea777403SDouglas Gregor         }
535ea777403SDouglas Gregor       }
536ea777403SDouglas Gregor 
53763745d59SDouglas Gregor       QualType baseType = Context.getBaseType();
53863745d59SDouglas Gregor       NamedDecl *D = NULL;
53963745d59SDouglas Gregor 
54063745d59SDouglas Gregor       if (!baseType.isNull()) {
54163745d59SDouglas Gregor         // Get the declaration for a class/struct/union/enum type
54263745d59SDouglas Gregor         if (const TagType *Tag = baseType->getAs<TagType>())
54363745d59SDouglas Gregor           D = Tag->getDecl();
54463745d59SDouglas Gregor         // Get the @interface declaration for a (possibly-qualified) Objective-C
54563745d59SDouglas Gregor         // object pointer type, e.g., NSString*
54663745d59SDouglas Gregor         else if (const ObjCObjectPointerType *ObjPtr =
54763745d59SDouglas Gregor                  baseType->getAs<ObjCObjectPointerType>())
54863745d59SDouglas Gregor           D = ObjPtr->getInterfaceDecl();
54963745d59SDouglas Gregor         // Get the @interface declaration for an Objective-C object type
55063745d59SDouglas Gregor         else if (const ObjCObjectType *Obj = baseType->getAs<ObjCObjectType>())
55163745d59SDouglas Gregor           D = Obj->getInterface();
55263745d59SDouglas Gregor         // Get the class for a C++ injected-class-name
55363745d59SDouglas Gregor         else if (const InjectedClassNameType *Injected =
55463745d59SDouglas Gregor                  baseType->getAs<InjectedClassNameType>())
55563745d59SDouglas Gregor           D = Injected->getDecl();
55663745d59SDouglas Gregor       }
55763745d59SDouglas Gregor 
55863745d59SDouglas Gregor       if (D != NULL) {
55963745d59SDouglas Gregor         CXCursor cursor = cxcursor::MakeCXCursor(D, *TU);
56063745d59SDouglas Gregor 
56163745d59SDouglas Gregor         CXCursorKind cursorKind = clang_getCursorKind(cursor);
56263745d59SDouglas Gregor         CXString cursorUSR = clang_getCursorUSR(cursor);
56363745d59SDouglas Gregor 
5645b8ad406STed Kremenek         // Normally, clients of CXString shouldn't care whether or not
5655b8ad406STed Kremenek         // a CXString is managed by a pool or by explicitly malloc'ed memory.
5665b8ad406STed Kremenek         // However, there are cases when AllocatedResults outlives the
5675b8ad406STed Kremenek         // CXTranslationUnit.  This is a workaround that failure mode.
5685b8ad406STed Kremenek         if (cxstring::isManagedByPool(cursorUSR)) {
5695b8ad406STed Kremenek           CXString heapStr =
5705b8ad406STed Kremenek             cxstring::createCXString(clang_getCString(cursorUSR), true);
5715b8ad406STed Kremenek           clang_disposeString(cursorUSR);
5725b8ad406STed Kremenek           cursorUSR = heapStr;
5735b8ad406STed Kremenek         }
5745b8ad406STed Kremenek 
57563745d59SDouglas Gregor         AllocatedResults.ContainerKind = cursorKind;
57663745d59SDouglas Gregor         AllocatedResults.ContainerUSR = cursorUSR;
5775b8ad406STed Kremenek 
57863745d59SDouglas Gregor         const Type *type = baseType.getTypePtrOrNull();
57963745d59SDouglas Gregor         if (type != NULL) {
58063745d59SDouglas Gregor           AllocatedResults.ContainerIsIncomplete = type->isIncompleteType();
58163745d59SDouglas Gregor         }
58263745d59SDouglas Gregor         else {
58363745d59SDouglas Gregor           AllocatedResults.ContainerIsIncomplete = 1;
58463745d59SDouglas Gregor         }
58563745d59SDouglas Gregor       }
58663745d59SDouglas Gregor       else {
58763745d59SDouglas Gregor         AllocatedResults.ContainerKind = CXCursor_InvalidCode;
58863745d59SDouglas Gregor         AllocatedResults.ContainerUSR = createCXString("");
58963745d59SDouglas Gregor         AllocatedResults.ContainerIsIncomplete = 1;
59063745d59SDouglas Gregor       }
5918e984da8SDouglas Gregor     }
59249f67ce4SDouglas Gregor 
59336e3b5c7SDouglas Gregor     virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
59436e3b5c7SDouglas Gregor                                            OverloadCandidate *Candidates,
59536e3b5c7SDouglas Gregor                                            unsigned NumCandidates) {
59636e3b5c7SDouglas Gregor       StoredResults.reserve(StoredResults.size() + NumCandidates);
59736e3b5c7SDouglas Gregor       for (unsigned I = 0; I != NumCandidates; ++I) {
598b278aafbSDouglas Gregor         CodeCompletionString *StoredCompletion
599b278aafbSDouglas Gregor           = Candidates[I].CreateSignatureString(CurrentArg, S,
600b278aafbSDouglas Gregor                                       AllocatedResults.CodeCompletionAllocator);
60136e3b5c7SDouglas Gregor 
60236e3b5c7SDouglas Gregor         CXCompletionResult R;
60336e3b5c7SDouglas Gregor         R.CursorKind = CXCursor_NotImplemented;
60436e3b5c7SDouglas Gregor         R.CompletionString = StoredCompletion;
60536e3b5c7SDouglas Gregor         StoredResults.push_back(R);
60636e3b5c7SDouglas Gregor       }
60736e3b5c7SDouglas Gregor     }
60836e3b5c7SDouglas Gregor 
609bcbf46c7SDouglas Gregor     virtual CodeCompletionAllocator &getAllocator() {
610b278aafbSDouglas Gregor       return AllocatedResults.CodeCompletionAllocator;
611b278aafbSDouglas Gregor     }
612b278aafbSDouglas Gregor 
61336e3b5c7SDouglas Gregor   private:
61436e3b5c7SDouglas Gregor     void Finish() {
61536e3b5c7SDouglas Gregor       AllocatedResults.Results = new CXCompletionResult [StoredResults.size()];
61636e3b5c7SDouglas Gregor       AllocatedResults.NumResults = StoredResults.size();
61736e3b5c7SDouglas Gregor       std::memcpy(AllocatedResults.Results, StoredResults.data(),
61836e3b5c7SDouglas Gregor                   StoredResults.size() * sizeof(CXCompletionResult));
61936e3b5c7SDouglas Gregor       StoredResults.clear();
62036e3b5c7SDouglas Gregor     }
6218e984da8SDouglas Gregor   };
6228e984da8SDouglas Gregor }
6238e984da8SDouglas Gregor 
6248e984da8SDouglas Gregor extern "C" {
62577af1c56SDaniel Dunbar struct CodeCompleteAtInfo {
62677af1c56SDaniel Dunbar   CXTranslationUnit TU;
62777af1c56SDaniel Dunbar   const char *complete_filename;
62877af1c56SDaniel Dunbar   unsigned complete_line;
62977af1c56SDaniel Dunbar   unsigned complete_column;
63077af1c56SDaniel Dunbar   struct CXUnsavedFile *unsaved_files;
63177af1c56SDaniel Dunbar   unsigned num_unsaved_files;
63277af1c56SDaniel Dunbar   unsigned options;
63377af1c56SDaniel Dunbar   CXCodeCompleteResults *result;
63477af1c56SDaniel Dunbar };
63577af1c56SDaniel Dunbar void clang_codeCompleteAt_Impl(void *UserData) {
63677af1c56SDaniel Dunbar   CodeCompleteAtInfo *CCAI = static_cast<CodeCompleteAtInfo*>(UserData);
63777af1c56SDaniel Dunbar   CXTranslationUnit TU = CCAI->TU;
63877af1c56SDaniel Dunbar   const char *complete_filename = CCAI->complete_filename;
63977af1c56SDaniel Dunbar   unsigned complete_line = CCAI->complete_line;
64077af1c56SDaniel Dunbar   unsigned complete_column = CCAI->complete_column;
64177af1c56SDaniel Dunbar   struct CXUnsavedFile *unsaved_files = CCAI->unsaved_files;
64277af1c56SDaniel Dunbar   unsigned num_unsaved_files = CCAI->num_unsaved_files;
64377af1c56SDaniel Dunbar   unsigned options = CCAI->options;
64477af1c56SDaniel Dunbar   CCAI->result = 0;
64577af1c56SDaniel Dunbar 
6468e984da8SDouglas Gregor #ifdef UDP_CODE_COMPLETION_LOGGER
6478e984da8SDouglas Gregor #ifdef UDP_CODE_COMPLETION_LOGGER_PORT
6488e984da8SDouglas Gregor   const llvm::TimeRecord &StartTime =  llvm::TimeRecord::getCurrentTime();
6498e984da8SDouglas Gregor #endif
6508e984da8SDouglas Gregor #endif
6518e984da8SDouglas Gregor 
6528e984da8SDouglas Gregor   bool EnableLogging = getenv("LIBCLANG_CODE_COMPLETION_LOGGING") != 0;
6538e984da8SDouglas Gregor 
65491554285STed Kremenek   ASTUnit *AST = static_cast<ASTUnit *>(TU->TUData);
6558e984da8SDouglas Gregor   if (!AST)
65677af1c56SDaniel Dunbar     return;
6578e984da8SDouglas Gregor 
658ca5b0539SDouglas Gregor   ASTUnit::ConcurrencyCheck Check(*AST);
659ca5b0539SDouglas Gregor 
6608e984da8SDouglas Gregor   // Perform the remapping of source files.
6610e62c1ccSChris Lattner   SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
6628e984da8SDouglas Gregor   for (unsigned I = 0; I != num_unsaved_files; ++I) {
6630e62c1ccSChris Lattner     StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
6648e984da8SDouglas Gregor     const llvm::MemoryBuffer *Buffer
6658e984da8SDouglas Gregor       = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
6668e984da8SDouglas Gregor     RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
6678e984da8SDouglas Gregor                                            Buffer));
6688e984da8SDouglas Gregor   }
6698e984da8SDouglas Gregor 
6708e984da8SDouglas Gregor   if (EnableLogging) {
6718e984da8SDouglas Gregor     // FIXME: Add logging.
6728e984da8SDouglas Gregor   }
6738e984da8SDouglas Gregor 
6748e984da8SDouglas Gregor   // Parse the resulting source file to find code-completion results.
675c30dcecbSAnders Carlsson   AllocatedCXCodeCompleteResults *Results =
676c30dcecbSAnders Carlsson         new AllocatedCXCodeCompleteResults(AST->getFileSystemOpts());
6778e984da8SDouglas Gregor   Results->Results = 0;
6788e984da8SDouglas Gregor   Results->NumResults = 0;
6798e984da8SDouglas Gregor 
6808e984da8SDouglas Gregor   // Create a code-completion consumer to capture the results.
68163745d59SDouglas Gregor   CaptureCompletionResults Capture(*Results, &TU);
6828e984da8SDouglas Gregor 
6838e984da8SDouglas Gregor   // Perform completion.
6848e984da8SDouglas Gregor   AST->CodeComplete(complete_filename, complete_line, complete_column,
685b68bc59aSDouglas Gregor                     RemappedFiles.data(), RemappedFiles.size(),
686b68bc59aSDouglas Gregor                     (options & CXCodeComplete_IncludeMacros),
687b68bc59aSDouglas Gregor                     (options & CXCodeComplete_IncludeCodePatterns),
688b68bc59aSDouglas Gregor                     Capture,
6895e14d39aSTed Kremenek                     *Results->Diag, Results->LangOpts, *Results->SourceMgr,
6905e14d39aSTed Kremenek                     *Results->FileMgr, Results->Diagnostics,
691b97b666cSDouglas Gregor                     Results->TemporaryBuffers);
6928e984da8SDouglas Gregor 
693162b712dSDouglas Gregor   // Keep a reference to the allocator used for cached global completions, so
694162b712dSDouglas Gregor   // that we can be sure that the memory used by our code completion strings
695162b712dSDouglas Gregor   // doesn't get freed due to subsequent reparses (while the code completion
696162b712dSDouglas Gregor   // results are still active).
697162b712dSDouglas Gregor   Results->CachedCompletionAllocator = AST->getCachedCompletionAllocator();
698162b712dSDouglas Gregor 
6998e984da8SDouglas Gregor 
7008e984da8SDouglas Gregor 
7018e984da8SDouglas Gregor #ifdef UDP_CODE_COMPLETION_LOGGER
7028e984da8SDouglas Gregor #ifdef UDP_CODE_COMPLETION_LOGGER_PORT
7038e984da8SDouglas Gregor   const llvm::TimeRecord &EndTime =  llvm::TimeRecord::getCurrentTime();
7048e984da8SDouglas Gregor   llvm::SmallString<256> LogResult;
7058e984da8SDouglas Gregor   llvm::raw_svector_ostream os(LogResult);
7068e984da8SDouglas Gregor 
7078e984da8SDouglas Gregor   // Figure out the language and whether or not it uses PCH.
7088e984da8SDouglas Gregor   const char *lang = 0;
7098e984da8SDouglas Gregor   bool usesPCH = false;
7108e984da8SDouglas Gregor 
7118e984da8SDouglas Gregor   for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
7128e984da8SDouglas Gregor        I != E; ++I) {
7138e984da8SDouglas Gregor     if (*I == 0)
7148e984da8SDouglas Gregor       continue;
7158e984da8SDouglas Gregor     if (strcmp(*I, "-x") == 0) {
7168e984da8SDouglas Gregor       if (I + 1 != E) {
7178e984da8SDouglas Gregor         lang = *(++I);
7188e984da8SDouglas Gregor         continue;
7198e984da8SDouglas Gregor       }
7208e984da8SDouglas Gregor     }
7218e984da8SDouglas Gregor     else if (strcmp(*I, "-include") == 0) {
7228e984da8SDouglas Gregor       if (I+1 != E) {
7238e984da8SDouglas Gregor         const char *arg = *(++I);
7248e984da8SDouglas Gregor         llvm::SmallString<512> pchName;
7258e984da8SDouglas Gregor         {
7268e984da8SDouglas Gregor           llvm::raw_svector_ostream os(pchName);
7278e984da8SDouglas Gregor           os << arg << ".pth";
7288e984da8SDouglas Gregor         }
7298e984da8SDouglas Gregor         pchName.push_back('\0');
7308e984da8SDouglas Gregor         struct stat stat_results;
731ea777403SDouglas Gregor         if (stat(pchName.str().c_str(), &stat_results) == 0)
7328e984da8SDouglas Gregor           usesPCH = true;
7338e984da8SDouglas Gregor         continue;
7348e984da8SDouglas Gregor       }
7358e984da8SDouglas Gregor     }
7368e984da8SDouglas Gregor   }
7378e984da8SDouglas Gregor 
7388e984da8SDouglas Gregor   os << "{ ";
7398e984da8SDouglas Gregor   os << "\"wall\": " << (EndTime.getWallTime() - StartTime.getWallTime());
7408e984da8SDouglas Gregor   os << ", \"numRes\": " << Results->NumResults;
7418e984da8SDouglas Gregor   os << ", \"diags\": " << Results->Diagnostics.size();
7428e984da8SDouglas Gregor   os << ", \"pch\": " << (usesPCH ? "true" : "false");
7438e984da8SDouglas Gregor   os << ", \"lang\": \"" << (lang ? lang : "<unknown>") << '"';
7448e984da8SDouglas Gregor   const char *name = getlogin();
7458e984da8SDouglas Gregor   os << ", \"user\": \"" << (name ? name : "unknown") << '"';
7468e984da8SDouglas Gregor   os << ", \"clangVer\": \"" << getClangFullVersion() << '"';
7478e984da8SDouglas Gregor   os << " }";
7488e984da8SDouglas Gregor 
7490e62c1ccSChris Lattner   StringRef res = os.str();
7508e984da8SDouglas Gregor   if (res.size() > 0) {
7518e984da8SDouglas Gregor     do {
7528e984da8SDouglas Gregor       // Setup the UDP socket.
7538e984da8SDouglas Gregor       struct sockaddr_in servaddr;
7548e984da8SDouglas Gregor       bzero(&servaddr, sizeof(servaddr));
7558e984da8SDouglas Gregor       servaddr.sin_family = AF_INET;
7568e984da8SDouglas Gregor       servaddr.sin_port = htons(UDP_CODE_COMPLETION_LOGGER_PORT);
7578e984da8SDouglas Gregor       if (inet_pton(AF_INET, UDP_CODE_COMPLETION_LOGGER,
7588e984da8SDouglas Gregor                     &servaddr.sin_addr) <= 0)
7598e984da8SDouglas Gregor         break;
7608e984da8SDouglas Gregor 
7618e984da8SDouglas Gregor       int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
7628e984da8SDouglas Gregor       if (sockfd < 0)
7638e984da8SDouglas Gregor         break;
7648e984da8SDouglas Gregor 
7658e984da8SDouglas Gregor       sendto(sockfd, res.data(), res.size(), 0,
7668e984da8SDouglas Gregor              (struct sockaddr *)&servaddr, sizeof(servaddr));
7678e984da8SDouglas Gregor       close(sockfd);
7688e984da8SDouglas Gregor     }
7698e984da8SDouglas Gregor     while (false);
7708e984da8SDouglas Gregor   }
7718e984da8SDouglas Gregor #endif
7728e984da8SDouglas Gregor #endif
77377af1c56SDaniel Dunbar   CCAI->result = Results;
77477af1c56SDaniel Dunbar }
77577af1c56SDaniel Dunbar CXCodeCompleteResults *clang_codeCompleteAt(CXTranslationUnit TU,
77677af1c56SDaniel Dunbar                                             const char *complete_filename,
77777af1c56SDaniel Dunbar                                             unsigned complete_line,
77877af1c56SDaniel Dunbar                                             unsigned complete_column,
77977af1c56SDaniel Dunbar                                             struct CXUnsavedFile *unsaved_files,
78077af1c56SDaniel Dunbar                                             unsigned num_unsaved_files,
78177af1c56SDaniel Dunbar                                             unsigned options) {
78277af1c56SDaniel Dunbar   CodeCompleteAtInfo CCAI = { TU, complete_filename, complete_line,
78377af1c56SDaniel Dunbar                               complete_column, unsaved_files, num_unsaved_files,
78477af1c56SDaniel Dunbar                               options, 0 };
78577af1c56SDaniel Dunbar   llvm::CrashRecoveryContext CRC;
78677af1c56SDaniel Dunbar 
787b7383e6dSDaniel Dunbar   if (!RunSafely(CRC, clang_codeCompleteAt_Impl, &CCAI)) {
78877af1c56SDaniel Dunbar     fprintf(stderr, "libclang: crash detected in code completion\n");
78991554285STed Kremenek     static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
79077af1c56SDaniel Dunbar     return 0;
791af44c781SDouglas Gregor   } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
792af44c781SDouglas Gregor     PrintLibclangResourceUsage(TU);
79377af1c56SDaniel Dunbar 
79477af1c56SDaniel Dunbar   return CCAI.result;
7958e984da8SDouglas Gregor }
7968e984da8SDouglas Gregor 
797b68bc59aSDouglas Gregor unsigned clang_defaultCodeCompleteOptions(void) {
798b68bc59aSDouglas Gregor   return CXCodeComplete_IncludeMacros;
799b68bc59aSDouglas Gregor }
800b68bc59aSDouglas Gregor 
801d5a2a073SDaniel Dunbar void clang_disposeCodeCompleteResults(CXCodeCompleteResults *ResultsIn) {
802d5a2a073SDaniel Dunbar   if (!ResultsIn)
803d5a2a073SDaniel Dunbar     return;
804d5a2a073SDaniel Dunbar 
805d5a2a073SDaniel Dunbar   AllocatedCXCodeCompleteResults *Results
806d5a2a073SDaniel Dunbar     = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
807d5a2a073SDaniel Dunbar   delete Results;
808d5a2a073SDaniel Dunbar }
809d5a2a073SDaniel Dunbar 
810d5a2a073SDaniel Dunbar unsigned
811d5a2a073SDaniel Dunbar clang_codeCompleteGetNumDiagnostics(CXCodeCompleteResults *ResultsIn) {
812d5a2a073SDaniel Dunbar   AllocatedCXCodeCompleteResults *Results
813d5a2a073SDaniel Dunbar     = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
814d5a2a073SDaniel Dunbar   if (!Results)
815d5a2a073SDaniel Dunbar     return 0;
816d5a2a073SDaniel Dunbar 
817d5a2a073SDaniel Dunbar   return Results->Diagnostics.size();
818d5a2a073SDaniel Dunbar }
819d5a2a073SDaniel Dunbar 
820d5a2a073SDaniel Dunbar CXDiagnostic
821d5a2a073SDaniel Dunbar clang_codeCompleteGetDiagnostic(CXCodeCompleteResults *ResultsIn,
822d5a2a073SDaniel Dunbar                                 unsigned Index) {
823d5a2a073SDaniel Dunbar   AllocatedCXCodeCompleteResults *Results
824d5a2a073SDaniel Dunbar     = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
825d5a2a073SDaniel Dunbar   if (!Results || Index >= Results->Diagnostics.size())
826d5a2a073SDaniel Dunbar     return 0;
827d5a2a073SDaniel Dunbar 
828d5a2a073SDaniel Dunbar   return new CXStoredDiagnostic(Results->Diagnostics[Index], Results->LangOpts);
829d5a2a073SDaniel Dunbar }
830d5a2a073SDaniel Dunbar 
8312132584dSDouglas Gregor unsigned long long
8322132584dSDouglas Gregor clang_codeCompleteGetContexts(CXCodeCompleteResults *ResultsIn) {
8332132584dSDouglas Gregor   AllocatedCXCodeCompleteResults *Results
8342132584dSDouglas Gregor     = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
8352132584dSDouglas Gregor   if (!Results)
8362132584dSDouglas Gregor     return 0;
8372132584dSDouglas Gregor 
8382132584dSDouglas Gregor   return Results->Contexts;
8392132584dSDouglas Gregor }
840d5a2a073SDaniel Dunbar 
84163745d59SDouglas Gregor enum CXCursorKind clang_codeCompleteGetContainerKind(
84263745d59SDouglas Gregor                                                CXCodeCompleteResults *ResultsIn,
84363745d59SDouglas Gregor                                                      unsigned *IsIncomplete) {
84463745d59SDouglas Gregor   AllocatedCXCodeCompleteResults *Results =
84563745d59SDouglas Gregor     static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn);
84663745d59SDouglas Gregor   if (!Results)
84763745d59SDouglas Gregor     return CXCursor_InvalidCode;
84863745d59SDouglas Gregor 
84963745d59SDouglas Gregor   if (IsIncomplete != NULL) {
85063745d59SDouglas Gregor     *IsIncomplete = Results->ContainerIsIncomplete;
85163745d59SDouglas Gregor   }
85263745d59SDouglas Gregor 
85363745d59SDouglas Gregor   return Results->ContainerKind;
85463745d59SDouglas Gregor }
85563745d59SDouglas Gregor 
85663745d59SDouglas Gregor CXString clang_codeCompleteGetContainerUSR(CXCodeCompleteResults *ResultsIn) {
85763745d59SDouglas Gregor   AllocatedCXCodeCompleteResults *Results =
85863745d59SDouglas Gregor     static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn);
85963745d59SDouglas Gregor   if (!Results)
86063745d59SDouglas Gregor     return createCXString("");
86163745d59SDouglas Gregor 
86263745d59SDouglas Gregor   return createCXString(clang_getCString(Results->ContainerUSR));
86363745d59SDouglas Gregor }
86463745d59SDouglas Gregor 
865ea777403SDouglas Gregor 
866ea777403SDouglas Gregor CXString clang_codeCompleteGetObjCSelector(CXCodeCompleteResults *ResultsIn) {
867ea777403SDouglas Gregor   AllocatedCXCodeCompleteResults *Results =
868ea777403SDouglas Gregor     static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn);
869ea777403SDouglas Gregor   if (!Results)
870ea777403SDouglas Gregor     return createCXString("");
871ea777403SDouglas Gregor 
872ea777403SDouglas Gregor   return createCXString(Results->Selector);
873ea777403SDouglas Gregor }
874ea777403SDouglas Gregor 
875d5a2a073SDaniel Dunbar } // end extern "C"
87649f67ce4SDouglas Gregor 
8778e3e8743SDouglas Gregor /// \brief Simple utility function that appends a \p New string to the given
8788e3e8743SDouglas Gregor /// \p Old string, using the \p Buffer for storage.
8798e3e8743SDouglas Gregor ///
8808e3e8743SDouglas Gregor /// \param Old The string to which we are appending. This parameter will be
8818e3e8743SDouglas Gregor /// updated to reflect the complete string.
8828e3e8743SDouglas Gregor ///
8838e3e8743SDouglas Gregor ///
8848e3e8743SDouglas Gregor /// \param New The string to append to \p Old.
8858e3e8743SDouglas Gregor ///
8868e3e8743SDouglas Gregor /// \param Buffer A buffer that stores the actual, concatenated string. It will
8878e3e8743SDouglas Gregor /// be used if the old string is already-non-empty.
8880e62c1ccSChris Lattner static void AppendToString(StringRef &Old, StringRef New,
8898e3e8743SDouglas Gregor                            llvm::SmallString<256> &Buffer) {
8908e3e8743SDouglas Gregor   if (Old.empty()) {
8918e3e8743SDouglas Gregor     Old = New;
8928e3e8743SDouglas Gregor     return;
8938e3e8743SDouglas Gregor   }
8948e3e8743SDouglas Gregor 
8958e3e8743SDouglas Gregor   if (Buffer.empty())
8968e3e8743SDouglas Gregor     Buffer.append(Old.begin(), Old.end());
8978e3e8743SDouglas Gregor   Buffer.append(New.begin(), New.end());
8988e3e8743SDouglas Gregor   Old = Buffer.str();
8998e3e8743SDouglas Gregor }
9008e3e8743SDouglas Gregor 
9018e3e8743SDouglas Gregor /// \brief Get the typed-text blocks from the given code-completion string
9028e3e8743SDouglas Gregor /// and return them as a single string.
9038e3e8743SDouglas Gregor ///
9048e3e8743SDouglas Gregor /// \param String The code-completion string whose typed-text blocks will be
9058e3e8743SDouglas Gregor /// concatenated.
9068e3e8743SDouglas Gregor ///
9078e3e8743SDouglas Gregor /// \param Buffer A buffer used for storage of the completed name.
9080e62c1ccSChris Lattner static StringRef GetTypedName(CodeCompletionString *String,
9098e3e8743SDouglas Gregor                                     llvm::SmallString<256> &Buffer) {
9100e62c1ccSChris Lattner   StringRef Result;
9118e3e8743SDouglas Gregor   for (CodeCompletionString::iterator C = String->begin(), CEnd = String->end();
9128e3e8743SDouglas Gregor        C != CEnd; ++C) {
9138e3e8743SDouglas Gregor     if (C->Kind == CodeCompletionString::CK_TypedText)
9148e3e8743SDouglas Gregor       AppendToString(Result, C->Text, Buffer);
9158e3e8743SDouglas Gregor   }
9168e3e8743SDouglas Gregor 
9178e3e8743SDouglas Gregor   return Result;
9188e3e8743SDouglas Gregor }
9198e3e8743SDouglas Gregor 
92049f67ce4SDouglas Gregor namespace {
92149f67ce4SDouglas Gregor   struct OrderCompletionResults {
92249f67ce4SDouglas Gregor     bool operator()(const CXCompletionResult &XR,
92349f67ce4SDouglas Gregor                     const CXCompletionResult &YR) const {
924b278aafbSDouglas Gregor       CodeCompletionString *X
925b278aafbSDouglas Gregor         = (CodeCompletionString *)XR.CompletionString;
926b278aafbSDouglas Gregor       CodeCompletionString *Y
927b278aafbSDouglas Gregor         = (CodeCompletionString *)YR.CompletionString;
92849f67ce4SDouglas Gregor 
9298e3e8743SDouglas Gregor       llvm::SmallString<256> XBuffer;
9300e62c1ccSChris Lattner       StringRef XText = GetTypedName(X, XBuffer);
9318e3e8743SDouglas Gregor       llvm::SmallString<256> YBuffer;
9320e62c1ccSChris Lattner       StringRef YText = GetTypedName(Y, YBuffer);
93349f67ce4SDouglas Gregor 
9348e3e8743SDouglas Gregor       if (XText.empty() || YText.empty())
9358e3e8743SDouglas Gregor         return !XText.empty();
9368e3e8743SDouglas Gregor 
9378e3e8743SDouglas Gregor       int result = XText.compare_lower(YText);
93849f67ce4SDouglas Gregor       if (result < 0)
93949f67ce4SDouglas Gregor         return true;
94049f67ce4SDouglas Gregor       if (result > 0)
94149f67ce4SDouglas Gregor         return false;
94249f67ce4SDouglas Gregor 
9438e3e8743SDouglas Gregor       result = XText.compare(YText);
944c7a7d92aSDouglas Gregor       return result < 0;
94549f67ce4SDouglas Gregor     }
94649f67ce4SDouglas Gregor   };
94749f67ce4SDouglas Gregor }
94849f67ce4SDouglas Gregor 
94949f67ce4SDouglas Gregor extern "C" {
95049f67ce4SDouglas Gregor   void clang_sortCodeCompletionResults(CXCompletionResult *Results,
95149f67ce4SDouglas Gregor                                        unsigned NumResults) {
95249f67ce4SDouglas Gregor     std::stable_sort(Results, Results + NumResults, OrderCompletionResults());
95349f67ce4SDouglas Gregor   }
95449f67ce4SDouglas Gregor }
955