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 
1078a40f700SDavid Blaikie   llvm_unreachable("Invalid CompletionKind!");
108d5a2a073SDaniel Dunbar }
109d5a2a073SDaniel Dunbar 
110d5a2a073SDaniel Dunbar CXString clang_getCompletionChunkText(CXCompletionString completion_string,
111d5a2a073SDaniel Dunbar                                       unsigned chunk_number) {
112b278aafbSDouglas Gregor   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
113d5a2a073SDaniel Dunbar   if (!CCStr || chunk_number >= CCStr->size())
11491554285STed Kremenek     return createCXString((const char*)0);
115d5a2a073SDaniel Dunbar 
116d5a2a073SDaniel Dunbar   switch ((*CCStr)[chunk_number].Kind) {
117d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_TypedText:
118d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Text:
119d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Placeholder:
120d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_CurrentParameter:
121d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Informative:
122d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftParen:
123d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightParen:
124d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftBracket:
125d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightBracket:
126d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftBrace:
127d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightBrace:
128d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftAngle:
129d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightAngle:
130d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Comma:
131d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_ResultType:
132d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Colon:
133d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_SemiColon:
134d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Equal:
135d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_HorizontalSpace:
13609737ee8SDouglas Gregor   case CodeCompletionString::CK_VerticalSpace:
1378ed5b770SDouglas Gregor     return createCXString((*CCStr)[chunk_number].Text, false);
13809737ee8SDouglas Gregor 
139d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Optional:
140d5a2a073SDaniel Dunbar     // Note: treated as an empty text block.
141d5a2a073SDaniel Dunbar     return createCXString("");
142d5a2a073SDaniel Dunbar   }
143d5a2a073SDaniel Dunbar 
144e4d798f0SDavid Blaikie   llvm_unreachable("Invalid CodeCompletionString Kind!");
145d5a2a073SDaniel Dunbar }
146d5a2a073SDaniel Dunbar 
147d5a2a073SDaniel Dunbar 
148d5a2a073SDaniel Dunbar CXCompletionString
149d5a2a073SDaniel Dunbar clang_getCompletionChunkCompletionString(CXCompletionString completion_string,
150d5a2a073SDaniel Dunbar                                          unsigned chunk_number) {
151b278aafbSDouglas Gregor   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
152d5a2a073SDaniel Dunbar   if (!CCStr || chunk_number >= CCStr->size())
153d5a2a073SDaniel Dunbar     return 0;
154d5a2a073SDaniel Dunbar 
155d5a2a073SDaniel Dunbar   switch ((*CCStr)[chunk_number].Kind) {
156d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_TypedText:
157d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Text:
158d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Placeholder:
159d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_CurrentParameter:
160d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Informative:
161d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftParen:
162d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightParen:
163d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftBracket:
164d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightBracket:
165d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftBrace:
166d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightBrace:
167d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_LeftAngle:
168d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_RightAngle:
169d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Comma:
170d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_ResultType:
171d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Colon:
172d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_SemiColon:
173d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Equal:
174d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_HorizontalSpace:
175d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_VerticalSpace:
176d5a2a073SDaniel Dunbar     return 0;
177d5a2a073SDaniel Dunbar 
178d5a2a073SDaniel Dunbar   case CodeCompletionString::CK_Optional:
179d5a2a073SDaniel Dunbar     // Note: treated as an empty text block.
180d5a2a073SDaniel Dunbar     return (*CCStr)[chunk_number].Optional;
181d5a2a073SDaniel Dunbar   }
182d5a2a073SDaniel Dunbar 
1838a40f700SDavid Blaikie   llvm_unreachable("Invalid CompletionKind!");
184d5a2a073SDaniel Dunbar }
185d5a2a073SDaniel Dunbar 
186d5a2a073SDaniel Dunbar unsigned clang_getNumCompletionChunks(CXCompletionString completion_string) {
187b278aafbSDouglas Gregor   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
188d5a2a073SDaniel Dunbar   return CCStr? CCStr->size() : 0;
189d5a2a073SDaniel Dunbar }
190d5a2a073SDaniel Dunbar 
191a2db793fSDouglas Gregor unsigned clang_getCompletionPriority(CXCompletionString completion_string) {
192b278aafbSDouglas Gregor   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
19347bb3e2bSBill Wendling   return CCStr? CCStr->getPriority() : unsigned(CCP_Unlikely);
194a2db793fSDouglas Gregor }
195a2db793fSDouglas Gregor 
196f757a12dSDouglas Gregor enum CXAvailabilityKind
197f757a12dSDouglas Gregor clang_getCompletionAvailability(CXCompletionString completion_string) {
198b278aafbSDouglas Gregor   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
199b278aafbSDouglas Gregor   return CCStr? static_cast<CXAvailabilityKind>(CCStr->getAvailability())
200b278aafbSDouglas Gregor               : CXAvailability_Available;
201f757a12dSDouglas Gregor }
202f757a12dSDouglas Gregor 
20398ea7f67SErik Verbruggen unsigned clang_getCompletionNumAnnotations(CXCompletionString completion_string)
20498ea7f67SErik Verbruggen {
20598ea7f67SErik Verbruggen   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
20698ea7f67SErik Verbruggen   return CCStr ? CCStr->getAnnotationCount() : 0;
20798ea7f67SErik Verbruggen }
20898ea7f67SErik Verbruggen 
20998ea7f67SErik Verbruggen CXString clang_getCompletionAnnotation(CXCompletionString completion_string,
21098ea7f67SErik Verbruggen                                        unsigned annotation_number) {
21198ea7f67SErik Verbruggen   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
21298ea7f67SErik Verbruggen   return CCStr ? createCXString(CCStr->getAnnotation(annotation_number))
21398ea7f67SErik Verbruggen                : createCXString((const char *) 0);
21498ea7f67SErik Verbruggen }
21598ea7f67SErik Verbruggen 
21678254c88SDouglas Gregor CXString
21778254c88SDouglas Gregor clang_getCompletionParent(CXCompletionString completion_string,
21878254c88SDouglas Gregor                           CXCursorKind *kind) {
21978254c88SDouglas Gregor   if (kind)
22078254c88SDouglas Gregor     *kind = CXCursor_NotImplemented;
22178254c88SDouglas Gregor 
22278254c88SDouglas Gregor   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
22378254c88SDouglas Gregor   if (!CCStr)
22478254c88SDouglas Gregor     return createCXString((const char *)0);
22578254c88SDouglas Gregor 
22678254c88SDouglas Gregor   if (kind)
22778254c88SDouglas Gregor     *kind = CCStr->getParentContextKind();
22878254c88SDouglas Gregor   return createCXString(CCStr->getParentContextName(), /*DupString=*/false);
22978254c88SDouglas Gregor }
23098ea7f67SErik Verbruggen 
231d5a2a073SDaniel Dunbar /// \brief The CXCodeCompleteResults structure we allocate internally;
232d5a2a073SDaniel Dunbar /// the client only sees the initial CXCodeCompleteResults structure.
233d5a2a073SDaniel Dunbar struct AllocatedCXCodeCompleteResults : public CXCodeCompleteResults {
234c30dcecbSAnders Carlsson   AllocatedCXCodeCompleteResults(const FileSystemOptions& FileSystemOpts);
235d5a2a073SDaniel Dunbar   ~AllocatedCXCodeCompleteResults();
236d5a2a073SDaniel Dunbar 
237d5a2a073SDaniel Dunbar   /// \brief Diagnostics produced while performing code completion.
2380e62c1ccSChris Lattner   SmallVector<StoredDiagnostic, 8> Diagnostics;
239d5a2a073SDaniel Dunbar 
240d5a2a073SDaniel Dunbar   /// \brief Diag object
241c95d8192SDylan Noblesmith   IntrusiveRefCntPtr<DiagnosticsEngine> Diag;
242d5a2a073SDaniel Dunbar 
243d5a2a073SDaniel Dunbar   /// \brief Language options used to adjust source locations.
244d5a2a073SDaniel Dunbar   LangOptions LangOpts;
245d5a2a073SDaniel Dunbar 
2465159f616SChris Lattner   FileSystemOptions FileSystemOpts;
2475159f616SChris Lattner 
248d5a2a073SDaniel Dunbar   /// \brief File manager, used for diagnostics.
249c95d8192SDylan Noblesmith   IntrusiveRefCntPtr<FileManager> FileMgr;
250d5a2a073SDaniel Dunbar 
25171731d6bSArgyrios Kyrtzidis   /// \brief Source manager, used for diagnostics.
252c95d8192SDylan Noblesmith   IntrusiveRefCntPtr<SourceManager> SourceMgr;
25371731d6bSArgyrios Kyrtzidis 
254d5a2a073SDaniel Dunbar   /// \brief Temporary files that should be removed once we have finished
255d5a2a073SDaniel Dunbar   /// with the code-completion results.
256d5a2a073SDaniel Dunbar   std::vector<llvm::sys::Path> TemporaryFiles;
257d8a5dba9SDouglas Gregor 
2583f5a9efbSChris Lattner   /// \brief Temporary buffers that will be deleted once we have finished with
2593f5a9efbSChris Lattner   /// the code-completion results.
2600e62c1ccSChris Lattner   SmallVector<const llvm::MemoryBuffer *, 1> TemporaryBuffers;
261b278aafbSDouglas Gregor 
262162b712dSDouglas Gregor   /// \brief Allocator used to store globally cached code-completion results.
263c95d8192SDylan Noblesmith   IntrusiveRefCntPtr<clang::GlobalCodeCompletionAllocator>
264162b712dSDouglas Gregor     CachedCompletionAllocator;
265162b712dSDouglas Gregor 
266b278aafbSDouglas Gregor   /// \brief Allocator used to store code completion results.
267*9d7c0fefSArgyrios Kyrtzidis   IntrusiveRefCntPtr<clang::GlobalCodeCompletionAllocator>
268*9d7c0fefSArgyrios Kyrtzidis     CodeCompletionAllocator;
2692132584dSDouglas Gregor 
2702132584dSDouglas Gregor   /// \brief Context under which completion occurred.
2712132584dSDouglas Gregor   enum clang::CodeCompletionContext::Kind ContextKind;
2722132584dSDouglas Gregor 
2732132584dSDouglas Gregor   /// \brief A bitfield representing the acceptable completions for the
2742132584dSDouglas Gregor   /// current context.
2752132584dSDouglas Gregor   unsigned long long Contexts;
27663745d59SDouglas Gregor 
277ea777403SDouglas Gregor   /// \brief The kind of the container for the current context for completions.
27863745d59SDouglas Gregor   enum CXCursorKind ContainerKind;
279ea777403SDouglas Gregor   /// \brief The USR of the container for the current context for completions.
28063745d59SDouglas Gregor   CXString ContainerUSR;
281ea777403SDouglas Gregor   /// \brief a boolean value indicating whether there is complete information
282ea777403SDouglas Gregor   /// about the container
28363745d59SDouglas Gregor   unsigned ContainerIsIncomplete;
284ea777403SDouglas Gregor 
285ea777403SDouglas Gregor   /// \brief A string containing the Objective-C selector entered thus far for a
286ea777403SDouglas Gregor   /// message send.
287ea777403SDouglas Gregor   std::string Selector;
288d5a2a073SDaniel Dunbar };
289d5a2a073SDaniel Dunbar 
29068dbaeadSDouglas Gregor /// \brief Tracks the number of code-completion result objects that are
29168dbaeadSDouglas Gregor /// currently active.
29268dbaeadSDouglas Gregor ///
29368dbaeadSDouglas Gregor /// Used for debugging purposes only.
2949aeaa4d6SDouglas Gregor static llvm::sys::cas_flag CodeCompletionResultObjects;
29568dbaeadSDouglas Gregor 
296c30dcecbSAnders Carlsson AllocatedCXCodeCompleteResults::AllocatedCXCodeCompleteResults(
297c30dcecbSAnders Carlsson                                       const FileSystemOptions& FileSystemOpts)
298d0040648SArgyrios Kyrtzidis   : CXCodeCompleteResults(),
2999c902b55SDavid Blaikie     Diag(new DiagnosticsEngine(
300c95d8192SDylan Noblesmith                    IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs))),
301c30dcecbSAnders Carlsson     FileSystemOpts(FileSystemOpts),
3025e14d39aSTed Kremenek     FileMgr(new FileManager(FileSystemOpts)),
303e442fe3dSDouglas Gregor     SourceMgr(new SourceManager(*Diag, *FileMgr)),
304*9d7c0fefSArgyrios Kyrtzidis     CodeCompletionAllocator(new clang::GlobalCodeCompletionAllocator),
305e442fe3dSDouglas Gregor     Contexts(CXCompletionContext_Unknown),
306e442fe3dSDouglas Gregor     ContainerKind(CXCursor_InvalidCode),
307e442fe3dSDouglas Gregor     ContainerUSR(createCXString("")),
308e442fe3dSDouglas Gregor     ContainerIsIncomplete(1)
309e442fe3dSDouglas Gregor {
31068dbaeadSDouglas Gregor   if (getenv("LIBCLANG_OBJTRACKING")) {
3119aeaa4d6SDouglas Gregor     llvm::sys::AtomicIncrement(&CodeCompletionResultObjects);
31268dbaeadSDouglas Gregor     fprintf(stderr, "+++ %d completion results\n", CodeCompletionResultObjects);
31368dbaeadSDouglas Gregor   }
31468dbaeadSDouglas Gregor }
315d5a2a073SDaniel Dunbar 
316d5a2a073SDaniel Dunbar AllocatedCXCodeCompleteResults::~AllocatedCXCodeCompleteResults() {
317d5a2a073SDaniel Dunbar   delete [] Results;
318d5a2a073SDaniel Dunbar 
31963745d59SDouglas Gregor   clang_disposeString(ContainerUSR);
32063745d59SDouglas Gregor 
321d5a2a073SDaniel Dunbar   for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
322d5a2a073SDaniel Dunbar     TemporaryFiles[I].eraseFromDisk();
323d8a5dba9SDouglas Gregor   for (unsigned I = 0, N = TemporaryBuffers.size(); I != N; ++I)
324d8a5dba9SDouglas Gregor     delete TemporaryBuffers[I];
32568dbaeadSDouglas Gregor 
32668dbaeadSDouglas Gregor   if (getenv("LIBCLANG_OBJTRACKING")) {
3279aeaa4d6SDouglas Gregor     llvm::sys::AtomicDecrement(&CodeCompletionResultObjects);
32868dbaeadSDouglas Gregor     fprintf(stderr, "--- %d completion results\n", CodeCompletionResultObjects);
32968dbaeadSDouglas Gregor   }
330d5a2a073SDaniel Dunbar }
331d5a2a073SDaniel Dunbar 
3328e984da8SDouglas Gregor } // end extern "C"
3338e984da8SDouglas Gregor 
3342132584dSDouglas Gregor static unsigned long long getContextsForContextKind(
3352132584dSDouglas Gregor                                           enum CodeCompletionContext::Kind kind,
3362132584dSDouglas Gregor                                                     Sema &S) {
3372132584dSDouglas Gregor   unsigned long long contexts = 0;
3382132584dSDouglas Gregor   switch (kind) {
3392132584dSDouglas Gregor     case CodeCompletionContext::CCC_OtherWithMacros: {
3402132584dSDouglas Gregor       //We can allow macros here, but we don't know what else is permissible
3412132584dSDouglas Gregor       //So we'll say the only thing permissible are macros
3422132584dSDouglas Gregor       contexts = CXCompletionContext_MacroName;
3432132584dSDouglas Gregor       break;
3442132584dSDouglas Gregor     }
3452132584dSDouglas Gregor     case CodeCompletionContext::CCC_TopLevel:
3462132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCIvarList:
3472132584dSDouglas Gregor     case CodeCompletionContext::CCC_ClassStructUnion:
3482132584dSDouglas Gregor     case CodeCompletionContext::CCC_Type: {
3492132584dSDouglas Gregor       contexts = CXCompletionContext_AnyType |
3502132584dSDouglas Gregor                  CXCompletionContext_ObjCInterface;
351bbafb8a7SDavid Blaikie       if (S.getLangOpts().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_Statement: {
3612132584dSDouglas Gregor       contexts = CXCompletionContext_AnyType |
3622132584dSDouglas Gregor                  CXCompletionContext_ObjCInterface |
3632132584dSDouglas Gregor                  CXCompletionContext_AnyValue;
364bbafb8a7SDavid Blaikie       if (S.getLangOpts().CPlusPlus) {
3652132584dSDouglas Gregor         contexts |= 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_Expression: {
3742132584dSDouglas Gregor       contexts = CXCompletionContext_AnyValue;
375bbafb8a7SDavid Blaikie       if (S.getLangOpts().CPlusPlus) {
3762132584dSDouglas Gregor         contexts |= CXCompletionContext_AnyType |
3772132584dSDouglas Gregor                     CXCompletionContext_ObjCInterface |
3782132584dSDouglas Gregor                     CXCompletionContext_EnumTag |
3792132584dSDouglas Gregor                     CXCompletionContext_UnionTag |
3802132584dSDouglas Gregor                     CXCompletionContext_StructTag |
3812132584dSDouglas Gregor                     CXCompletionContext_ClassTag |
3822132584dSDouglas Gregor                     CXCompletionContext_NestedNameSpecifier;
3832132584dSDouglas Gregor       }
3842132584dSDouglas Gregor       break;
3852132584dSDouglas Gregor     }
3862132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCMessageReceiver: {
3872132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCObjectValue |
3882132584dSDouglas Gregor                  CXCompletionContext_ObjCSelectorValue |
3892132584dSDouglas Gregor                  CXCompletionContext_ObjCInterface;
390bbafb8a7SDavid Blaikie       if (S.getLangOpts().CPlusPlus) {
3912132584dSDouglas Gregor         contexts |= CXCompletionContext_CXXClassTypeValue |
3922132584dSDouglas Gregor                     CXCompletionContext_AnyType |
3932132584dSDouglas Gregor                     CXCompletionContext_EnumTag |
3942132584dSDouglas Gregor                     CXCompletionContext_UnionTag |
3952132584dSDouglas Gregor                     CXCompletionContext_StructTag |
3962132584dSDouglas Gregor                     CXCompletionContext_ClassTag |
3972132584dSDouglas Gregor                     CXCompletionContext_NestedNameSpecifier;
3982132584dSDouglas Gregor       }
3992132584dSDouglas Gregor       break;
4002132584dSDouglas Gregor     }
4012132584dSDouglas Gregor     case CodeCompletionContext::CCC_DotMemberAccess: {
4022132584dSDouglas Gregor       contexts = CXCompletionContext_DotMemberAccess;
4032132584dSDouglas Gregor       break;
4042132584dSDouglas Gregor     }
4052132584dSDouglas Gregor     case CodeCompletionContext::CCC_ArrowMemberAccess: {
4062132584dSDouglas Gregor       contexts = CXCompletionContext_ArrowMemberAccess;
4072132584dSDouglas Gregor       break;
4082132584dSDouglas Gregor     }
4092132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCPropertyAccess: {
4102132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCPropertyAccess;
4112132584dSDouglas Gregor       break;
4122132584dSDouglas Gregor     }
4132132584dSDouglas Gregor     case CodeCompletionContext::CCC_EnumTag: {
4142132584dSDouglas Gregor       contexts = CXCompletionContext_EnumTag |
4152132584dSDouglas Gregor                  CXCompletionContext_NestedNameSpecifier;
4162132584dSDouglas Gregor       break;
4172132584dSDouglas Gregor     }
4182132584dSDouglas Gregor     case CodeCompletionContext::CCC_UnionTag: {
4192132584dSDouglas Gregor       contexts = CXCompletionContext_UnionTag |
4202132584dSDouglas Gregor                  CXCompletionContext_NestedNameSpecifier;
4212132584dSDouglas Gregor       break;
4222132584dSDouglas Gregor     }
4232132584dSDouglas Gregor     case CodeCompletionContext::CCC_ClassOrStructTag: {
4242132584dSDouglas Gregor       contexts = CXCompletionContext_StructTag |
4252132584dSDouglas Gregor                  CXCompletionContext_ClassTag |
4262132584dSDouglas Gregor                  CXCompletionContext_NestedNameSpecifier;
4272132584dSDouglas Gregor       break;
4282132584dSDouglas Gregor     }
4292132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCProtocolName: {
4302132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCProtocol;
4312132584dSDouglas Gregor       break;
4322132584dSDouglas Gregor     }
4332132584dSDouglas Gregor     case CodeCompletionContext::CCC_Namespace: {
4342132584dSDouglas Gregor       contexts = CXCompletionContext_Namespace;
4352132584dSDouglas Gregor       break;
4362132584dSDouglas Gregor     }
4372132584dSDouglas Gregor     case CodeCompletionContext::CCC_PotentiallyQualifiedName: {
4382132584dSDouglas Gregor       contexts = CXCompletionContext_NestedNameSpecifier;
4392132584dSDouglas Gregor       break;
4402132584dSDouglas Gregor     }
4412132584dSDouglas Gregor     case CodeCompletionContext::CCC_MacroNameUse: {
4422132584dSDouglas Gregor       contexts = CXCompletionContext_MacroName;
4432132584dSDouglas Gregor       break;
4442132584dSDouglas Gregor     }
4452132584dSDouglas Gregor     case CodeCompletionContext::CCC_NaturalLanguage: {
4462132584dSDouglas Gregor       contexts = CXCompletionContext_NaturalLanguage;
4472132584dSDouglas Gregor       break;
4482132584dSDouglas Gregor     }
4492132584dSDouglas Gregor     case CodeCompletionContext::CCC_SelectorName: {
4502132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCSelectorName;
4512132584dSDouglas Gregor       break;
4522132584dSDouglas Gregor     }
4532132584dSDouglas Gregor     case CodeCompletionContext::CCC_ParenthesizedExpression: {
4542132584dSDouglas Gregor       contexts = CXCompletionContext_AnyType |
4552132584dSDouglas Gregor                  CXCompletionContext_ObjCInterface |
4562132584dSDouglas Gregor                  CXCompletionContext_AnyValue;
457bbafb8a7SDavid Blaikie       if (S.getLangOpts().CPlusPlus) {
4582132584dSDouglas Gregor         contexts |= CXCompletionContext_EnumTag |
4592132584dSDouglas Gregor                     CXCompletionContext_UnionTag |
4602132584dSDouglas Gregor                     CXCompletionContext_StructTag |
4612132584dSDouglas Gregor                     CXCompletionContext_ClassTag |
4622132584dSDouglas Gregor                     CXCompletionContext_NestedNameSpecifier;
4632132584dSDouglas Gregor       }
4642132584dSDouglas Gregor       break;
4652132584dSDouglas Gregor     }
4662132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCInstanceMessage: {
4672132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCInstanceMessage;
4682132584dSDouglas Gregor       break;
4692132584dSDouglas Gregor     }
4702132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCClassMessage: {
4712132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCClassMessage;
4722132584dSDouglas Gregor       break;
4732132584dSDouglas Gregor     }
4742c595adfSDouglas Gregor     case CodeCompletionContext::CCC_ObjCInterfaceName: {
4752132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCInterface;
4762132584dSDouglas Gregor       break;
4772132584dSDouglas Gregor     }
4782132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCCategoryName: {
4792132584dSDouglas Gregor       contexts = CXCompletionContext_ObjCCategory;
4802132584dSDouglas Gregor       break;
4812132584dSDouglas Gregor     }
4822132584dSDouglas Gregor     case CodeCompletionContext::CCC_Other:
4832132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCInterface:
4842132584dSDouglas Gregor     case CodeCompletionContext::CCC_ObjCImplementation:
4852132584dSDouglas Gregor     case CodeCompletionContext::CCC_Name:
4862132584dSDouglas Gregor     case CodeCompletionContext::CCC_MacroName:
4872132584dSDouglas Gregor     case CodeCompletionContext::CCC_PreprocessorExpression:
4882132584dSDouglas Gregor     case CodeCompletionContext::CCC_PreprocessorDirective:
4892132584dSDouglas Gregor     case CodeCompletionContext::CCC_TypeQualifiers: {
4902132584dSDouglas Gregor       //Only Clang results should be accepted, so we'll set all of the other
4912132584dSDouglas Gregor       //context bits to 0 (i.e. the empty set)
4922132584dSDouglas Gregor       contexts = CXCompletionContext_Unexposed;
4932132584dSDouglas Gregor       break;
4942132584dSDouglas Gregor     }
4952132584dSDouglas Gregor     case CodeCompletionContext::CCC_Recovery: {
4962132584dSDouglas Gregor       //We don't know what the current context is, so we'll return unknown
4972132584dSDouglas Gregor       //This is the equivalent of setting all of the other context bits
4982132584dSDouglas Gregor       contexts = CXCompletionContext_Unknown;
4992132584dSDouglas Gregor       break;
5002132584dSDouglas Gregor     }
5012132584dSDouglas Gregor   }
5022132584dSDouglas Gregor   return contexts;
5032132584dSDouglas Gregor }
5042132584dSDouglas Gregor 
5058e984da8SDouglas Gregor namespace {
5068e984da8SDouglas Gregor   class CaptureCompletionResults : public CodeCompleteConsumer {
5078e984da8SDouglas Gregor     AllocatedCXCodeCompleteResults &AllocatedResults;
508*9d7c0fefSArgyrios Kyrtzidis     CodeCompletionTUInfo CCTUInfo;
5090e62c1ccSChris Lattner     SmallVector<CXCompletionResult, 16> StoredResults;
51063745d59SDouglas Gregor     CXTranslationUnit *TU;
5118e984da8SDouglas Gregor   public:
51263745d59SDouglas Gregor     CaptureCompletionResults(AllocatedCXCodeCompleteResults &Results,
51363745d59SDouglas Gregor                              CXTranslationUnit *TranslationUnit)
51439982197SDouglas Gregor       : CodeCompleteConsumer(true, false, true, false),
515*9d7c0fefSArgyrios Kyrtzidis         AllocatedResults(Results), CCTUInfo(Results.CodeCompletionAllocator),
516*9d7c0fefSArgyrios Kyrtzidis         TU(TranslationUnit) { }
51736e3b5c7SDouglas Gregor     ~CaptureCompletionResults() { Finish(); }
5188e984da8SDouglas Gregor 
51900c37ef0SDouglas Gregor     virtual void ProcessCodeCompleteResults(Sema &S,
52000c37ef0SDouglas Gregor                                             CodeCompletionContext Context,
521276321a9SJohn McCall                                             CodeCompletionResult *Results,
5228e984da8SDouglas Gregor                                             unsigned NumResults) {
52336e3b5c7SDouglas Gregor       StoredResults.reserve(StoredResults.size() + NumResults);
5248e984da8SDouglas Gregor       for (unsigned I = 0; I != NumResults; ++I) {
525b278aafbSDouglas Gregor         CodeCompletionString *StoredCompletion
526*9d7c0fefSArgyrios Kyrtzidis           = Results[I].CreateCodeCompletionString(S, getAllocator(),
527*9d7c0fefSArgyrios Kyrtzidis                                                   getCodeCompletionTUInfo());
52836e3b5c7SDouglas Gregor 
52936e3b5c7SDouglas Gregor         CXCompletionResult R;
53036e3b5c7SDouglas Gregor         R.CursorKind = Results[I].CursorKind;
53136e3b5c7SDouglas Gregor         R.CompletionString = StoredCompletion;
53236e3b5c7SDouglas Gregor         StoredResults.push_back(R);
5338e984da8SDouglas Gregor       }
5342132584dSDouglas Gregor 
53563745d59SDouglas Gregor       enum CodeCompletionContext::Kind contextKind = Context.getKind();
5362132584dSDouglas Gregor 
53763745d59SDouglas Gregor       AllocatedResults.ContextKind = contextKind;
53863745d59SDouglas Gregor       AllocatedResults.Contexts = getContextsForContextKind(contextKind, S);
53963745d59SDouglas Gregor 
540ea777403SDouglas Gregor       AllocatedResults.Selector = "";
541ea777403SDouglas Gregor       if (Context.getNumSelIdents() > 0) {
542ea777403SDouglas Gregor         for (unsigned i = 0; i < Context.getNumSelIdents(); i++) {
543ea777403SDouglas Gregor           IdentifierInfo *selIdent = Context.getSelIdents()[i];
544ea777403SDouglas Gregor           if (selIdent != NULL) {
545ea777403SDouglas Gregor             StringRef selectorString = Context.getSelIdents()[i]->getName();
546632500cbSBenjamin Kramer             AllocatedResults.Selector += selectorString;
547ea777403SDouglas Gregor           }
548ea777403SDouglas Gregor           AllocatedResults.Selector += ":";
549ea777403SDouglas Gregor         }
550ea777403SDouglas Gregor       }
551ea777403SDouglas Gregor 
55263745d59SDouglas Gregor       QualType baseType = Context.getBaseType();
55363745d59SDouglas Gregor       NamedDecl *D = NULL;
55463745d59SDouglas Gregor 
55563745d59SDouglas Gregor       if (!baseType.isNull()) {
55663745d59SDouglas Gregor         // Get the declaration for a class/struct/union/enum type
55763745d59SDouglas Gregor         if (const TagType *Tag = baseType->getAs<TagType>())
55863745d59SDouglas Gregor           D = Tag->getDecl();
55963745d59SDouglas Gregor         // Get the @interface declaration for a (possibly-qualified) Objective-C
56063745d59SDouglas Gregor         // object pointer type, e.g., NSString*
56163745d59SDouglas Gregor         else if (const ObjCObjectPointerType *ObjPtr =
56263745d59SDouglas Gregor                  baseType->getAs<ObjCObjectPointerType>())
56363745d59SDouglas Gregor           D = ObjPtr->getInterfaceDecl();
56463745d59SDouglas Gregor         // Get the @interface declaration for an Objective-C object type
56563745d59SDouglas Gregor         else if (const ObjCObjectType *Obj = baseType->getAs<ObjCObjectType>())
56663745d59SDouglas Gregor           D = Obj->getInterface();
56763745d59SDouglas Gregor         // Get the class for a C++ injected-class-name
56863745d59SDouglas Gregor         else if (const InjectedClassNameType *Injected =
56963745d59SDouglas Gregor                  baseType->getAs<InjectedClassNameType>())
57063745d59SDouglas Gregor           D = Injected->getDecl();
57163745d59SDouglas Gregor       }
57263745d59SDouglas Gregor 
57363745d59SDouglas Gregor       if (D != NULL) {
57463745d59SDouglas Gregor         CXCursor cursor = cxcursor::MakeCXCursor(D, *TU);
57563745d59SDouglas Gregor 
57663745d59SDouglas Gregor         CXCursorKind cursorKind = clang_getCursorKind(cursor);
57763745d59SDouglas Gregor         CXString cursorUSR = clang_getCursorUSR(cursor);
57863745d59SDouglas Gregor 
5795b8ad406STed Kremenek         // Normally, clients of CXString shouldn't care whether or not
5805b8ad406STed Kremenek         // a CXString is managed by a pool or by explicitly malloc'ed memory.
5815b8ad406STed Kremenek         // However, there are cases when AllocatedResults outlives the
5825b8ad406STed Kremenek         // CXTranslationUnit.  This is a workaround that failure mode.
5835b8ad406STed Kremenek         if (cxstring::isManagedByPool(cursorUSR)) {
5845b8ad406STed Kremenek           CXString heapStr =
5855b8ad406STed Kremenek             cxstring::createCXString(clang_getCString(cursorUSR), true);
5865b8ad406STed Kremenek           clang_disposeString(cursorUSR);
5875b8ad406STed Kremenek           cursorUSR = heapStr;
5885b8ad406STed Kremenek         }
5895b8ad406STed Kremenek 
59063745d59SDouglas Gregor         AllocatedResults.ContainerKind = cursorKind;
59163745d59SDouglas Gregor         AllocatedResults.ContainerUSR = cursorUSR;
5925b8ad406STed Kremenek 
59363745d59SDouglas Gregor         const Type *type = baseType.getTypePtrOrNull();
59463745d59SDouglas Gregor         if (type != NULL) {
59563745d59SDouglas Gregor           AllocatedResults.ContainerIsIncomplete = type->isIncompleteType();
59663745d59SDouglas Gregor         }
59763745d59SDouglas Gregor         else {
59863745d59SDouglas Gregor           AllocatedResults.ContainerIsIncomplete = 1;
59963745d59SDouglas Gregor         }
60063745d59SDouglas Gregor       }
60163745d59SDouglas Gregor       else {
60263745d59SDouglas Gregor         AllocatedResults.ContainerKind = CXCursor_InvalidCode;
60363745d59SDouglas Gregor         AllocatedResults.ContainerUSR = createCXString("");
60463745d59SDouglas Gregor         AllocatedResults.ContainerIsIncomplete = 1;
60563745d59SDouglas Gregor       }
6068e984da8SDouglas Gregor     }
60749f67ce4SDouglas Gregor 
60836e3b5c7SDouglas Gregor     virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
60936e3b5c7SDouglas Gregor                                            OverloadCandidate *Candidates,
61036e3b5c7SDouglas Gregor                                            unsigned NumCandidates) {
61136e3b5c7SDouglas Gregor       StoredResults.reserve(StoredResults.size() + NumCandidates);
61236e3b5c7SDouglas Gregor       for (unsigned I = 0; I != NumCandidates; ++I) {
613b278aafbSDouglas Gregor         CodeCompletionString *StoredCompletion
614*9d7c0fefSArgyrios Kyrtzidis           = Candidates[I].CreateSignatureString(CurrentArg, S, getAllocator(),
615*9d7c0fefSArgyrios Kyrtzidis                                                 getCodeCompletionTUInfo());
61636e3b5c7SDouglas Gregor 
61736e3b5c7SDouglas Gregor         CXCompletionResult R;
61836e3b5c7SDouglas Gregor         R.CursorKind = CXCursor_NotImplemented;
61936e3b5c7SDouglas Gregor         R.CompletionString = StoredCompletion;
62036e3b5c7SDouglas Gregor         StoredResults.push_back(R);
62136e3b5c7SDouglas Gregor       }
62236e3b5c7SDouglas Gregor     }
62336e3b5c7SDouglas Gregor 
624bcbf46c7SDouglas Gregor     virtual CodeCompletionAllocator &getAllocator() {
625*9d7c0fefSArgyrios Kyrtzidis       return *AllocatedResults.CodeCompletionAllocator;
626b278aafbSDouglas Gregor     }
627b278aafbSDouglas Gregor 
628*9d7c0fefSArgyrios Kyrtzidis     virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() { return CCTUInfo; }
629*9d7c0fefSArgyrios Kyrtzidis 
63036e3b5c7SDouglas Gregor   private:
63136e3b5c7SDouglas Gregor     void Finish() {
63236e3b5c7SDouglas Gregor       AllocatedResults.Results = new CXCompletionResult [StoredResults.size()];
63336e3b5c7SDouglas Gregor       AllocatedResults.NumResults = StoredResults.size();
63436e3b5c7SDouglas Gregor       std::memcpy(AllocatedResults.Results, StoredResults.data(),
63536e3b5c7SDouglas Gregor                   StoredResults.size() * sizeof(CXCompletionResult));
63636e3b5c7SDouglas Gregor       StoredResults.clear();
63736e3b5c7SDouglas Gregor     }
6388e984da8SDouglas Gregor   };
6398e984da8SDouglas Gregor }
6408e984da8SDouglas Gregor 
6418e984da8SDouglas Gregor extern "C" {
64277af1c56SDaniel Dunbar struct CodeCompleteAtInfo {
64377af1c56SDaniel Dunbar   CXTranslationUnit TU;
64477af1c56SDaniel Dunbar   const char *complete_filename;
64577af1c56SDaniel Dunbar   unsigned complete_line;
64677af1c56SDaniel Dunbar   unsigned complete_column;
64777af1c56SDaniel Dunbar   struct CXUnsavedFile *unsaved_files;
64877af1c56SDaniel Dunbar   unsigned num_unsaved_files;
64977af1c56SDaniel Dunbar   unsigned options;
65077af1c56SDaniel Dunbar   CXCodeCompleteResults *result;
65177af1c56SDaniel Dunbar };
65277af1c56SDaniel Dunbar void clang_codeCompleteAt_Impl(void *UserData) {
65377af1c56SDaniel Dunbar   CodeCompleteAtInfo *CCAI = static_cast<CodeCompleteAtInfo*>(UserData);
65477af1c56SDaniel Dunbar   CXTranslationUnit TU = CCAI->TU;
65577af1c56SDaniel Dunbar   const char *complete_filename = CCAI->complete_filename;
65677af1c56SDaniel Dunbar   unsigned complete_line = CCAI->complete_line;
65777af1c56SDaniel Dunbar   unsigned complete_column = CCAI->complete_column;
65877af1c56SDaniel Dunbar   struct CXUnsavedFile *unsaved_files = CCAI->unsaved_files;
65977af1c56SDaniel Dunbar   unsigned num_unsaved_files = CCAI->num_unsaved_files;
66077af1c56SDaniel Dunbar   unsigned options = CCAI->options;
66177af1c56SDaniel Dunbar   CCAI->result = 0;
66277af1c56SDaniel Dunbar 
6638e984da8SDouglas Gregor #ifdef UDP_CODE_COMPLETION_LOGGER
6648e984da8SDouglas Gregor #ifdef UDP_CODE_COMPLETION_LOGGER_PORT
6658e984da8SDouglas Gregor   const llvm::TimeRecord &StartTime =  llvm::TimeRecord::getCurrentTime();
6668e984da8SDouglas Gregor #endif
6678e984da8SDouglas Gregor #endif
6688e984da8SDouglas Gregor 
6698e984da8SDouglas Gregor   bool EnableLogging = getenv("LIBCLANG_CODE_COMPLETION_LOGGING") != 0;
6708e984da8SDouglas Gregor 
67191554285STed Kremenek   ASTUnit *AST = static_cast<ASTUnit *>(TU->TUData);
6728e984da8SDouglas Gregor   if (!AST)
67377af1c56SDaniel Dunbar     return;
6748e984da8SDouglas Gregor 
6757317a5cbSArgyrios Kyrtzidis   CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
6767317a5cbSArgyrios Kyrtzidis   if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
67758d5f3fdSArgyrios Kyrtzidis     setThreadBackgroundPriority();
6787317a5cbSArgyrios Kyrtzidis 
679ca5b0539SDouglas Gregor   ASTUnit::ConcurrencyCheck Check(*AST);
680ca5b0539SDouglas Gregor 
6818e984da8SDouglas Gregor   // Perform the remapping of source files.
6820e62c1ccSChris Lattner   SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
6838e984da8SDouglas Gregor   for (unsigned I = 0; I != num_unsaved_files; ++I) {
6840e62c1ccSChris Lattner     StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
6858e984da8SDouglas Gregor     const llvm::MemoryBuffer *Buffer
6868e984da8SDouglas Gregor       = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
6878e984da8SDouglas Gregor     RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
6888e984da8SDouglas Gregor                                            Buffer));
6898e984da8SDouglas Gregor   }
6908e984da8SDouglas Gregor 
6918e984da8SDouglas Gregor   if (EnableLogging) {
6928e984da8SDouglas Gregor     // FIXME: Add logging.
6938e984da8SDouglas Gregor   }
6948e984da8SDouglas Gregor 
6958e984da8SDouglas Gregor   // Parse the resulting source file to find code-completion results.
696c30dcecbSAnders Carlsson   AllocatedCXCodeCompleteResults *Results =
697c30dcecbSAnders Carlsson         new AllocatedCXCodeCompleteResults(AST->getFileSystemOpts());
6988e984da8SDouglas Gregor   Results->Results = 0;
6998e984da8SDouglas Gregor   Results->NumResults = 0;
7008e984da8SDouglas Gregor 
7018e984da8SDouglas Gregor   // Create a code-completion consumer to capture the results.
70263745d59SDouglas Gregor   CaptureCompletionResults Capture(*Results, &TU);
7038e984da8SDouglas Gregor 
7048e984da8SDouglas Gregor   // Perform completion.
7058e984da8SDouglas Gregor   AST->CodeComplete(complete_filename, complete_line, complete_column,
706b68bc59aSDouglas Gregor                     RemappedFiles.data(), RemappedFiles.size(),
707b68bc59aSDouglas Gregor                     (options & CXCodeComplete_IncludeMacros),
708b68bc59aSDouglas Gregor                     (options & CXCodeComplete_IncludeCodePatterns),
709b68bc59aSDouglas Gregor                     Capture,
7105e14d39aSTed Kremenek                     *Results->Diag, Results->LangOpts, *Results->SourceMgr,
7115e14d39aSTed Kremenek                     *Results->FileMgr, Results->Diagnostics,
712b97b666cSDouglas Gregor                     Results->TemporaryBuffers);
7138e984da8SDouglas Gregor 
714162b712dSDouglas Gregor   // Keep a reference to the allocator used for cached global completions, so
715162b712dSDouglas Gregor   // that we can be sure that the memory used by our code completion strings
716162b712dSDouglas Gregor   // doesn't get freed due to subsequent reparses (while the code completion
717162b712dSDouglas Gregor   // results are still active).
718162b712dSDouglas Gregor   Results->CachedCompletionAllocator = AST->getCachedCompletionAllocator();
719162b712dSDouglas Gregor 
7208e984da8SDouglas Gregor 
7218e984da8SDouglas Gregor 
7228e984da8SDouglas Gregor #ifdef UDP_CODE_COMPLETION_LOGGER
7238e984da8SDouglas Gregor #ifdef UDP_CODE_COMPLETION_LOGGER_PORT
7248e984da8SDouglas Gregor   const llvm::TimeRecord &EndTime =  llvm::TimeRecord::getCurrentTime();
725f1a13f29SDylan Noblesmith   SmallString<256> LogResult;
7268e984da8SDouglas Gregor   llvm::raw_svector_ostream os(LogResult);
7278e984da8SDouglas Gregor 
7288e984da8SDouglas Gregor   // Figure out the language and whether or not it uses PCH.
7298e984da8SDouglas Gregor   const char *lang = 0;
7308e984da8SDouglas Gregor   bool usesPCH = false;
7318e984da8SDouglas Gregor 
7328e984da8SDouglas Gregor   for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
7338e984da8SDouglas Gregor        I != E; ++I) {
7348e984da8SDouglas Gregor     if (*I == 0)
7358e984da8SDouglas Gregor       continue;
7368e984da8SDouglas Gregor     if (strcmp(*I, "-x") == 0) {
7378e984da8SDouglas Gregor       if (I + 1 != E) {
7388e984da8SDouglas Gregor         lang = *(++I);
7398e984da8SDouglas Gregor         continue;
7408e984da8SDouglas Gregor       }
7418e984da8SDouglas Gregor     }
7428e984da8SDouglas Gregor     else if (strcmp(*I, "-include") == 0) {
7438e984da8SDouglas Gregor       if (I+1 != E) {
7448e984da8SDouglas Gregor         const char *arg = *(++I);
745f1a13f29SDylan Noblesmith         SmallString<512> pchName;
7468e984da8SDouglas Gregor         {
7478e984da8SDouglas Gregor           llvm::raw_svector_ostream os(pchName);
7488e984da8SDouglas Gregor           os << arg << ".pth";
7498e984da8SDouglas Gregor         }
7508e984da8SDouglas Gregor         pchName.push_back('\0');
7518e984da8SDouglas Gregor         struct stat stat_results;
752ea777403SDouglas Gregor         if (stat(pchName.str().c_str(), &stat_results) == 0)
7538e984da8SDouglas Gregor           usesPCH = true;
7548e984da8SDouglas Gregor         continue;
7558e984da8SDouglas Gregor       }
7568e984da8SDouglas Gregor     }
7578e984da8SDouglas Gregor   }
7588e984da8SDouglas Gregor 
7598e984da8SDouglas Gregor   os << "{ ";
7608e984da8SDouglas Gregor   os << "\"wall\": " << (EndTime.getWallTime() - StartTime.getWallTime());
7618e984da8SDouglas Gregor   os << ", \"numRes\": " << Results->NumResults;
7628e984da8SDouglas Gregor   os << ", \"diags\": " << Results->Diagnostics.size();
7638e984da8SDouglas Gregor   os << ", \"pch\": " << (usesPCH ? "true" : "false");
7648e984da8SDouglas Gregor   os << ", \"lang\": \"" << (lang ? lang : "<unknown>") << '"';
7658e984da8SDouglas Gregor   const char *name = getlogin();
7668e984da8SDouglas Gregor   os << ", \"user\": \"" << (name ? name : "unknown") << '"';
7678e984da8SDouglas Gregor   os << ", \"clangVer\": \"" << getClangFullVersion() << '"';
7688e984da8SDouglas Gregor   os << " }";
7698e984da8SDouglas Gregor 
7700e62c1ccSChris Lattner   StringRef res = os.str();
7718e984da8SDouglas Gregor   if (res.size() > 0) {
7728e984da8SDouglas Gregor     do {
7738e984da8SDouglas Gregor       // Setup the UDP socket.
7748e984da8SDouglas Gregor       struct sockaddr_in servaddr;
7758e984da8SDouglas Gregor       bzero(&servaddr, sizeof(servaddr));
7768e984da8SDouglas Gregor       servaddr.sin_family = AF_INET;
7778e984da8SDouglas Gregor       servaddr.sin_port = htons(UDP_CODE_COMPLETION_LOGGER_PORT);
7788e984da8SDouglas Gregor       if (inet_pton(AF_INET, UDP_CODE_COMPLETION_LOGGER,
7798e984da8SDouglas Gregor                     &servaddr.sin_addr) <= 0)
7808e984da8SDouglas Gregor         break;
7818e984da8SDouglas Gregor 
7828e984da8SDouglas Gregor       int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
7838e984da8SDouglas Gregor       if (sockfd < 0)
7848e984da8SDouglas Gregor         break;
7858e984da8SDouglas Gregor 
7868e984da8SDouglas Gregor       sendto(sockfd, res.data(), res.size(), 0,
7878e984da8SDouglas Gregor              (struct sockaddr *)&servaddr, sizeof(servaddr));
7888e984da8SDouglas Gregor       close(sockfd);
7898e984da8SDouglas Gregor     }
7908e984da8SDouglas Gregor     while (false);
7918e984da8SDouglas Gregor   }
7928e984da8SDouglas Gregor #endif
7938e984da8SDouglas Gregor #endif
79477af1c56SDaniel Dunbar   CCAI->result = Results;
79577af1c56SDaniel Dunbar }
79677af1c56SDaniel Dunbar CXCodeCompleteResults *clang_codeCompleteAt(CXTranslationUnit TU,
79777af1c56SDaniel Dunbar                                             const char *complete_filename,
79877af1c56SDaniel Dunbar                                             unsigned complete_line,
79977af1c56SDaniel Dunbar                                             unsigned complete_column,
80077af1c56SDaniel Dunbar                                             struct CXUnsavedFile *unsaved_files,
80177af1c56SDaniel Dunbar                                             unsigned num_unsaved_files,
80277af1c56SDaniel Dunbar                                             unsigned options) {
80377af1c56SDaniel Dunbar   CodeCompleteAtInfo CCAI = { TU, complete_filename, complete_line,
80477af1c56SDaniel Dunbar                               complete_column, unsaved_files, num_unsaved_files,
80577af1c56SDaniel Dunbar                               options, 0 };
80677af1c56SDaniel Dunbar   llvm::CrashRecoveryContext CRC;
80777af1c56SDaniel Dunbar 
808b7383e6dSDaniel Dunbar   if (!RunSafely(CRC, clang_codeCompleteAt_Impl, &CCAI)) {
80977af1c56SDaniel Dunbar     fprintf(stderr, "libclang: crash detected in code completion\n");
81091554285STed Kremenek     static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
81177af1c56SDaniel Dunbar     return 0;
812af44c781SDouglas Gregor   } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
813af44c781SDouglas Gregor     PrintLibclangResourceUsage(TU);
81477af1c56SDaniel Dunbar 
81577af1c56SDaniel Dunbar   return CCAI.result;
8168e984da8SDouglas Gregor }
8178e984da8SDouglas Gregor 
818b68bc59aSDouglas Gregor unsigned clang_defaultCodeCompleteOptions(void) {
819b68bc59aSDouglas Gregor   return CXCodeComplete_IncludeMacros;
820b68bc59aSDouglas Gregor }
821b68bc59aSDouglas Gregor 
822d5a2a073SDaniel Dunbar void clang_disposeCodeCompleteResults(CXCodeCompleteResults *ResultsIn) {
823d5a2a073SDaniel Dunbar   if (!ResultsIn)
824d5a2a073SDaniel Dunbar     return;
825d5a2a073SDaniel Dunbar 
826d5a2a073SDaniel Dunbar   AllocatedCXCodeCompleteResults *Results
827d5a2a073SDaniel Dunbar     = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
828d5a2a073SDaniel Dunbar   delete Results;
829d5a2a073SDaniel Dunbar }
830d5a2a073SDaniel Dunbar 
831d5a2a073SDaniel Dunbar unsigned
832d5a2a073SDaniel Dunbar clang_codeCompleteGetNumDiagnostics(CXCodeCompleteResults *ResultsIn) {
833d5a2a073SDaniel Dunbar   AllocatedCXCodeCompleteResults *Results
834d5a2a073SDaniel Dunbar     = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
835d5a2a073SDaniel Dunbar   if (!Results)
836d5a2a073SDaniel Dunbar     return 0;
837d5a2a073SDaniel Dunbar 
838d5a2a073SDaniel Dunbar   return Results->Diagnostics.size();
839d5a2a073SDaniel Dunbar }
840d5a2a073SDaniel Dunbar 
841d5a2a073SDaniel Dunbar CXDiagnostic
842d5a2a073SDaniel Dunbar clang_codeCompleteGetDiagnostic(CXCodeCompleteResults *ResultsIn,
843d5a2a073SDaniel Dunbar                                 unsigned Index) {
844d5a2a073SDaniel Dunbar   AllocatedCXCodeCompleteResults *Results
845d5a2a073SDaniel Dunbar     = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
846d5a2a073SDaniel Dunbar   if (!Results || Index >= Results->Diagnostics.size())
847d5a2a073SDaniel Dunbar     return 0;
848d5a2a073SDaniel Dunbar 
849d5a2a073SDaniel Dunbar   return new CXStoredDiagnostic(Results->Diagnostics[Index], Results->LangOpts);
850d5a2a073SDaniel Dunbar }
851d5a2a073SDaniel Dunbar 
8522132584dSDouglas Gregor unsigned long long
8532132584dSDouglas Gregor clang_codeCompleteGetContexts(CXCodeCompleteResults *ResultsIn) {
8542132584dSDouglas Gregor   AllocatedCXCodeCompleteResults *Results
8552132584dSDouglas Gregor     = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
8562132584dSDouglas Gregor   if (!Results)
8572132584dSDouglas Gregor     return 0;
8582132584dSDouglas Gregor 
8592132584dSDouglas Gregor   return Results->Contexts;
8602132584dSDouglas Gregor }
861d5a2a073SDaniel Dunbar 
86263745d59SDouglas Gregor enum CXCursorKind clang_codeCompleteGetContainerKind(
86363745d59SDouglas Gregor                                                CXCodeCompleteResults *ResultsIn,
86463745d59SDouglas Gregor                                                      unsigned *IsIncomplete) {
86563745d59SDouglas Gregor   AllocatedCXCodeCompleteResults *Results =
86663745d59SDouglas Gregor     static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn);
86763745d59SDouglas Gregor   if (!Results)
86863745d59SDouglas Gregor     return CXCursor_InvalidCode;
86963745d59SDouglas Gregor 
87063745d59SDouglas Gregor   if (IsIncomplete != NULL) {
87163745d59SDouglas Gregor     *IsIncomplete = Results->ContainerIsIncomplete;
87263745d59SDouglas Gregor   }
87363745d59SDouglas Gregor 
87463745d59SDouglas Gregor   return Results->ContainerKind;
87563745d59SDouglas Gregor }
87663745d59SDouglas Gregor 
87763745d59SDouglas Gregor CXString clang_codeCompleteGetContainerUSR(CXCodeCompleteResults *ResultsIn) {
87863745d59SDouglas Gregor   AllocatedCXCodeCompleteResults *Results =
87963745d59SDouglas Gregor     static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn);
88063745d59SDouglas Gregor   if (!Results)
88163745d59SDouglas Gregor     return createCXString("");
88263745d59SDouglas Gregor 
88363745d59SDouglas Gregor   return createCXString(clang_getCString(Results->ContainerUSR));
88463745d59SDouglas Gregor }
88563745d59SDouglas Gregor 
886ea777403SDouglas Gregor 
887ea777403SDouglas Gregor CXString clang_codeCompleteGetObjCSelector(CXCodeCompleteResults *ResultsIn) {
888ea777403SDouglas Gregor   AllocatedCXCodeCompleteResults *Results =
889ea777403SDouglas Gregor     static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn);
890ea777403SDouglas Gregor   if (!Results)
891ea777403SDouglas Gregor     return createCXString("");
892ea777403SDouglas Gregor 
893ea777403SDouglas Gregor   return createCXString(Results->Selector);
894ea777403SDouglas Gregor }
895ea777403SDouglas Gregor 
896d5a2a073SDaniel Dunbar } // end extern "C"
89749f67ce4SDouglas Gregor 
8988e3e8743SDouglas Gregor /// \brief Simple utility function that appends a \p New string to the given
8998e3e8743SDouglas Gregor /// \p Old string, using the \p Buffer for storage.
9008e3e8743SDouglas Gregor ///
9018e3e8743SDouglas Gregor /// \param Old The string to which we are appending. This parameter will be
9028e3e8743SDouglas Gregor /// updated to reflect the complete string.
9038e3e8743SDouglas Gregor ///
9048e3e8743SDouglas Gregor ///
9058e3e8743SDouglas Gregor /// \param New The string to append to \p Old.
9068e3e8743SDouglas Gregor ///
9078e3e8743SDouglas Gregor /// \param Buffer A buffer that stores the actual, concatenated string. It will
9088e3e8743SDouglas Gregor /// be used if the old string is already-non-empty.
9090e62c1ccSChris Lattner static void AppendToString(StringRef &Old, StringRef New,
910f1a13f29SDylan Noblesmith                            SmallString<256> &Buffer) {
9118e3e8743SDouglas Gregor   if (Old.empty()) {
9128e3e8743SDouglas Gregor     Old = New;
9138e3e8743SDouglas Gregor     return;
9148e3e8743SDouglas Gregor   }
9158e3e8743SDouglas Gregor 
9168e3e8743SDouglas Gregor   if (Buffer.empty())
9178e3e8743SDouglas Gregor     Buffer.append(Old.begin(), Old.end());
9188e3e8743SDouglas Gregor   Buffer.append(New.begin(), New.end());
9198e3e8743SDouglas Gregor   Old = Buffer.str();
9208e3e8743SDouglas Gregor }
9218e3e8743SDouglas Gregor 
9228e3e8743SDouglas Gregor /// \brief Get the typed-text blocks from the given code-completion string
9238e3e8743SDouglas Gregor /// and return them as a single string.
9248e3e8743SDouglas Gregor ///
9258e3e8743SDouglas Gregor /// \param String The code-completion string whose typed-text blocks will be
9268e3e8743SDouglas Gregor /// concatenated.
9278e3e8743SDouglas Gregor ///
9288e3e8743SDouglas Gregor /// \param Buffer A buffer used for storage of the completed name.
9290e62c1ccSChris Lattner static StringRef GetTypedName(CodeCompletionString *String,
930f1a13f29SDylan Noblesmith                                     SmallString<256> &Buffer) {
9310e62c1ccSChris Lattner   StringRef Result;
9328e3e8743SDouglas Gregor   for (CodeCompletionString::iterator C = String->begin(), CEnd = String->end();
9338e3e8743SDouglas Gregor        C != CEnd; ++C) {
9348e3e8743SDouglas Gregor     if (C->Kind == CodeCompletionString::CK_TypedText)
9358e3e8743SDouglas Gregor       AppendToString(Result, C->Text, Buffer);
9368e3e8743SDouglas Gregor   }
9378e3e8743SDouglas Gregor 
9388e3e8743SDouglas Gregor   return Result;
9398e3e8743SDouglas Gregor }
9408e3e8743SDouglas Gregor 
94149f67ce4SDouglas Gregor namespace {
94249f67ce4SDouglas Gregor   struct OrderCompletionResults {
94349f67ce4SDouglas Gregor     bool operator()(const CXCompletionResult &XR,
94449f67ce4SDouglas Gregor                     const CXCompletionResult &YR) const {
945b278aafbSDouglas Gregor       CodeCompletionString *X
946b278aafbSDouglas Gregor         = (CodeCompletionString *)XR.CompletionString;
947b278aafbSDouglas Gregor       CodeCompletionString *Y
948b278aafbSDouglas Gregor         = (CodeCompletionString *)YR.CompletionString;
94949f67ce4SDouglas Gregor 
950f1a13f29SDylan Noblesmith       SmallString<256> XBuffer;
9510e62c1ccSChris Lattner       StringRef XText = GetTypedName(X, XBuffer);
952f1a13f29SDylan Noblesmith       SmallString<256> YBuffer;
9530e62c1ccSChris Lattner       StringRef YText = GetTypedName(Y, YBuffer);
95449f67ce4SDouglas Gregor 
9558e3e8743SDouglas Gregor       if (XText.empty() || YText.empty())
9568e3e8743SDouglas Gregor         return !XText.empty();
9578e3e8743SDouglas Gregor 
9588e3e8743SDouglas Gregor       int result = XText.compare_lower(YText);
95949f67ce4SDouglas Gregor       if (result < 0)
96049f67ce4SDouglas Gregor         return true;
96149f67ce4SDouglas Gregor       if (result > 0)
96249f67ce4SDouglas Gregor         return false;
96349f67ce4SDouglas Gregor 
9648e3e8743SDouglas Gregor       result = XText.compare(YText);
965c7a7d92aSDouglas Gregor       return result < 0;
96649f67ce4SDouglas Gregor     }
96749f67ce4SDouglas Gregor   };
96849f67ce4SDouglas Gregor }
96949f67ce4SDouglas Gregor 
97049f67ce4SDouglas Gregor extern "C" {
97149f67ce4SDouglas Gregor   void clang_sortCodeCompletionResults(CXCompletionResult *Results,
97249f67ce4SDouglas Gregor                                        unsigned NumResults) {
97349f67ce4SDouglas Gregor     std::stable_sort(Results, Results + NumResults, OrderCompletionResults());
97449f67ce4SDouglas Gregor   }
97549f67ce4SDouglas Gregor }
976