1 //===- CIndexCodeCompletion.cpp - Code Completion API hooks ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Clang-C Source Indexing library hooks for
11 // code completion.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "CIndexer.h"
16 #include "CIndexDiagnostic.h"
17 #include "CLog.h"
18 #include "CXCursor.h"
19 #include "CXString.h"
20 #include "CXTranslationUnit.h"
21 #include "clang/AST/Decl.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/Type.h"
24 #include "clang/Basic/FileManager.h"
25 #include "clang/Basic/SourceManager.h"
26 #include "clang/Frontend/ASTUnit.h"
27 #include "clang/Frontend/CompilerInstance.h"
28 #include "clang/Frontend/FrontendDiagnostic.h"
29 #include "clang/Sema/CodeCompleteConsumer.h"
30 #include "clang/Sema/Sema.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/Support/CrashRecoveryContext.h"
34 #include "llvm/Support/FileSystem.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/Program.h"
37 #include "llvm/Support/Timer.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include <atomic>
40 #include <cstdio>
41 #include <cstdlib>
42 #include <string>
43 
44 
45 #ifdef UDP_CODE_COMPLETION_LOGGER
46 #include "clang/Basic/Version.h"
47 #include <arpa/inet.h>
48 #include <sys/socket.h>
49 #include <sys/types.h>
50 #include <unistd.h>
51 #endif
52 
53 using namespace clang;
54 using namespace clang::cxindex;
55 
56 extern "C" {
57 
58 enum CXCompletionChunkKind
59 clang_getCompletionChunkKind(CXCompletionString completion_string,
60                              unsigned chunk_number) {
61   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
62   if (!CCStr || chunk_number >= CCStr->size())
63     return CXCompletionChunk_Text;
64 
65   switch ((*CCStr)[chunk_number].Kind) {
66   case CodeCompletionString::CK_TypedText:
67     return CXCompletionChunk_TypedText;
68   case CodeCompletionString::CK_Text:
69     return CXCompletionChunk_Text;
70   case CodeCompletionString::CK_Optional:
71     return CXCompletionChunk_Optional;
72   case CodeCompletionString::CK_Placeholder:
73     return CXCompletionChunk_Placeholder;
74   case CodeCompletionString::CK_Informative:
75     return CXCompletionChunk_Informative;
76   case CodeCompletionString::CK_ResultType:
77     return CXCompletionChunk_ResultType;
78   case CodeCompletionString::CK_CurrentParameter:
79     return CXCompletionChunk_CurrentParameter;
80   case CodeCompletionString::CK_LeftParen:
81     return CXCompletionChunk_LeftParen;
82   case CodeCompletionString::CK_RightParen:
83     return CXCompletionChunk_RightParen;
84   case CodeCompletionString::CK_LeftBracket:
85     return CXCompletionChunk_LeftBracket;
86   case CodeCompletionString::CK_RightBracket:
87     return CXCompletionChunk_RightBracket;
88   case CodeCompletionString::CK_LeftBrace:
89     return CXCompletionChunk_LeftBrace;
90   case CodeCompletionString::CK_RightBrace:
91     return CXCompletionChunk_RightBrace;
92   case CodeCompletionString::CK_LeftAngle:
93     return CXCompletionChunk_LeftAngle;
94   case CodeCompletionString::CK_RightAngle:
95     return CXCompletionChunk_RightAngle;
96   case CodeCompletionString::CK_Comma:
97     return CXCompletionChunk_Comma;
98   case CodeCompletionString::CK_Colon:
99     return CXCompletionChunk_Colon;
100   case CodeCompletionString::CK_SemiColon:
101     return CXCompletionChunk_SemiColon;
102   case CodeCompletionString::CK_Equal:
103     return CXCompletionChunk_Equal;
104   case CodeCompletionString::CK_HorizontalSpace:
105     return CXCompletionChunk_HorizontalSpace;
106   case CodeCompletionString::CK_VerticalSpace:
107     return CXCompletionChunk_VerticalSpace;
108   }
109 
110   llvm_unreachable("Invalid CompletionKind!");
111 }
112 
113 CXString clang_getCompletionChunkText(CXCompletionString completion_string,
114                                       unsigned chunk_number) {
115   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
116   if (!CCStr || chunk_number >= CCStr->size())
117     return cxstring::createNull();
118 
119   switch ((*CCStr)[chunk_number].Kind) {
120   case CodeCompletionString::CK_TypedText:
121   case CodeCompletionString::CK_Text:
122   case CodeCompletionString::CK_Placeholder:
123   case CodeCompletionString::CK_CurrentParameter:
124   case CodeCompletionString::CK_Informative:
125   case CodeCompletionString::CK_LeftParen:
126   case CodeCompletionString::CK_RightParen:
127   case CodeCompletionString::CK_LeftBracket:
128   case CodeCompletionString::CK_RightBracket:
129   case CodeCompletionString::CK_LeftBrace:
130   case CodeCompletionString::CK_RightBrace:
131   case CodeCompletionString::CK_LeftAngle:
132   case CodeCompletionString::CK_RightAngle:
133   case CodeCompletionString::CK_Comma:
134   case CodeCompletionString::CK_ResultType:
135   case CodeCompletionString::CK_Colon:
136   case CodeCompletionString::CK_SemiColon:
137   case CodeCompletionString::CK_Equal:
138   case CodeCompletionString::CK_HorizontalSpace:
139   case CodeCompletionString::CK_VerticalSpace:
140     return cxstring::createRef((*CCStr)[chunk_number].Text);
141 
142   case CodeCompletionString::CK_Optional:
143     // Note: treated as an empty text block.
144     return cxstring::createEmpty();
145   }
146 
147   llvm_unreachable("Invalid CodeCompletionString Kind!");
148 }
149 
150 
151 CXCompletionString
152 clang_getCompletionChunkCompletionString(CXCompletionString completion_string,
153                                          unsigned chunk_number) {
154   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
155   if (!CCStr || chunk_number >= CCStr->size())
156     return 0;
157 
158   switch ((*CCStr)[chunk_number].Kind) {
159   case CodeCompletionString::CK_TypedText:
160   case CodeCompletionString::CK_Text:
161   case CodeCompletionString::CK_Placeholder:
162   case CodeCompletionString::CK_CurrentParameter:
163   case CodeCompletionString::CK_Informative:
164   case CodeCompletionString::CK_LeftParen:
165   case CodeCompletionString::CK_RightParen:
166   case CodeCompletionString::CK_LeftBracket:
167   case CodeCompletionString::CK_RightBracket:
168   case CodeCompletionString::CK_LeftBrace:
169   case CodeCompletionString::CK_RightBrace:
170   case CodeCompletionString::CK_LeftAngle:
171   case CodeCompletionString::CK_RightAngle:
172   case CodeCompletionString::CK_Comma:
173   case CodeCompletionString::CK_ResultType:
174   case CodeCompletionString::CK_Colon:
175   case CodeCompletionString::CK_SemiColon:
176   case CodeCompletionString::CK_Equal:
177   case CodeCompletionString::CK_HorizontalSpace:
178   case CodeCompletionString::CK_VerticalSpace:
179     return 0;
180 
181   case CodeCompletionString::CK_Optional:
182     // Note: treated as an empty text block.
183     return (*CCStr)[chunk_number].Optional;
184   }
185 
186   llvm_unreachable("Invalid CompletionKind!");
187 }
188 
189 unsigned clang_getNumCompletionChunks(CXCompletionString completion_string) {
190   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
191   return CCStr? CCStr->size() : 0;
192 }
193 
194 unsigned clang_getCompletionPriority(CXCompletionString completion_string) {
195   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
196   return CCStr? CCStr->getPriority() : unsigned(CCP_Unlikely);
197 }
198 
199 enum CXAvailabilityKind
200 clang_getCompletionAvailability(CXCompletionString completion_string) {
201   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
202   return CCStr? static_cast<CXAvailabilityKind>(CCStr->getAvailability())
203               : CXAvailability_Available;
204 }
205 
206 unsigned clang_getCompletionNumAnnotations(CXCompletionString completion_string)
207 {
208   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
209   return CCStr ? CCStr->getAnnotationCount() : 0;
210 }
211 
212 CXString clang_getCompletionAnnotation(CXCompletionString completion_string,
213                                        unsigned annotation_number) {
214   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
215   return CCStr ? cxstring::createRef(CCStr->getAnnotation(annotation_number))
216                : cxstring::createNull();
217 }
218 
219 CXString
220 clang_getCompletionParent(CXCompletionString completion_string,
221                           CXCursorKind *kind) {
222   if (kind)
223     *kind = CXCursor_NotImplemented;
224 
225   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
226   if (!CCStr)
227     return cxstring::createNull();
228 
229   return cxstring::createRef(CCStr->getParentContextName());
230 }
231 
232 CXString
233 clang_getCompletionBriefComment(CXCompletionString completion_string) {
234   CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
235 
236   if (!CCStr)
237     return cxstring::createNull();
238 
239   return cxstring::createRef(CCStr->getBriefComment());
240 }
241 
242 namespace {
243 
244 /// \brief The CXCodeCompleteResults structure we allocate internally;
245 /// the client only sees the initial CXCodeCompleteResults structure.
246 ///
247 /// Normally, clients of CXString shouldn't care whether or not a CXString is
248 /// managed by a pool or by explicitly malloc'ed memory.  But
249 /// AllocatedCXCodeCompleteResults outlives the CXTranslationUnit, so we can
250 /// not rely on the StringPool in the TU.
251 struct AllocatedCXCodeCompleteResults : public CXCodeCompleteResults {
252   AllocatedCXCodeCompleteResults(IntrusiveRefCntPtr<FileManager> FileMgr);
253   ~AllocatedCXCodeCompleteResults();
254 
255   /// \brief Diagnostics produced while performing code completion.
256   SmallVector<StoredDiagnostic, 8> Diagnostics;
257 
258   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts;
259 
260   /// \brief Diag object
261   IntrusiveRefCntPtr<DiagnosticsEngine> Diag;
262 
263   /// \brief Language options used to adjust source locations.
264   LangOptions LangOpts;
265 
266   /// \brief File manager, used for diagnostics.
267   IntrusiveRefCntPtr<FileManager> FileMgr;
268 
269   /// \brief Source manager, used for diagnostics.
270   IntrusiveRefCntPtr<SourceManager> SourceMgr;
271 
272   /// \brief Temporary files that should be removed once we have finished
273   /// with the code-completion results.
274   std::vector<std::string> TemporaryFiles;
275 
276   /// \brief Temporary buffers that will be deleted once we have finished with
277   /// the code-completion results.
278   SmallVector<const llvm::MemoryBuffer *, 1> TemporaryBuffers;
279 
280   /// \brief Allocator used to store globally cached code-completion results.
281   IntrusiveRefCntPtr<clang::GlobalCodeCompletionAllocator>
282     CachedCompletionAllocator;
283 
284   /// \brief Allocator used to store code completion results.
285   IntrusiveRefCntPtr<clang::GlobalCodeCompletionAllocator>
286     CodeCompletionAllocator;
287 
288   /// \brief Context under which completion occurred.
289   enum clang::CodeCompletionContext::Kind ContextKind;
290 
291   /// \brief A bitfield representing the acceptable completions for the
292   /// current context.
293   unsigned long long Contexts;
294 
295   /// \brief The kind of the container for the current context for completions.
296   enum CXCursorKind ContainerKind;
297 
298   /// \brief The USR of the container for the current context for completions.
299   std::string ContainerUSR;
300 
301   /// \brief a boolean value indicating whether there is complete information
302   /// about the container
303   unsigned ContainerIsIncomplete;
304 
305   /// \brief A string containing the Objective-C selector entered thus far for a
306   /// message send.
307   std::string Selector;
308 };
309 
310 } // end anonymous namespace
311 
312 /// \brief Tracks the number of code-completion result objects that are
313 /// currently active.
314 ///
315 /// Used for debugging purposes only.
316 static std::atomic<unsigned> CodeCompletionResultObjects;
317 
318 AllocatedCXCodeCompleteResults::AllocatedCXCodeCompleteResults(
319     IntrusiveRefCntPtr<FileManager> FileMgr)
320     : CXCodeCompleteResults(),
321       DiagOpts(new DiagnosticOptions),
322       Diag(new DiagnosticsEngine(
323           IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), &*DiagOpts)),
324       FileMgr(FileMgr), SourceMgr(new SourceManager(*Diag, *FileMgr)),
325       CodeCompletionAllocator(new clang::GlobalCodeCompletionAllocator),
326       Contexts(CXCompletionContext_Unknown),
327       ContainerKind(CXCursor_InvalidCode), ContainerIsIncomplete(1) {
328   if (getenv("LIBCLANG_OBJTRACKING"))
329     fprintf(stderr, "+++ %u completion results\n",
330             ++CodeCompletionResultObjects);
331 }
332 
333 AllocatedCXCodeCompleteResults::~AllocatedCXCodeCompleteResults() {
334   delete [] Results;
335 
336   for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
337     llvm::sys::fs::remove(TemporaryFiles[I]);
338   for (unsigned I = 0, N = TemporaryBuffers.size(); I != N; ++I)
339     delete TemporaryBuffers[I];
340 
341   if (getenv("LIBCLANG_OBJTRACKING"))
342     fprintf(stderr, "--- %u completion results\n",
343             --CodeCompletionResultObjects);
344 }
345 
346 } // end extern "C"
347 
348 static unsigned long long getContextsForContextKind(
349                                           enum CodeCompletionContext::Kind kind,
350                                                     Sema &S) {
351   unsigned long long contexts = 0;
352   switch (kind) {
353     case CodeCompletionContext::CCC_OtherWithMacros: {
354       //We can allow macros here, but we don't know what else is permissible
355       //So we'll say the only thing permissible are macros
356       contexts = CXCompletionContext_MacroName;
357       break;
358     }
359     case CodeCompletionContext::CCC_TopLevel:
360     case CodeCompletionContext::CCC_ObjCIvarList:
361     case CodeCompletionContext::CCC_ClassStructUnion:
362     case CodeCompletionContext::CCC_Type: {
363       contexts = CXCompletionContext_AnyType |
364                  CXCompletionContext_ObjCInterface;
365       if (S.getLangOpts().CPlusPlus) {
366         contexts |= CXCompletionContext_EnumTag |
367                     CXCompletionContext_UnionTag |
368                     CXCompletionContext_StructTag |
369                     CXCompletionContext_ClassTag |
370                     CXCompletionContext_NestedNameSpecifier;
371       }
372       break;
373     }
374     case CodeCompletionContext::CCC_Statement: {
375       contexts = CXCompletionContext_AnyType |
376                  CXCompletionContext_ObjCInterface |
377                  CXCompletionContext_AnyValue;
378       if (S.getLangOpts().CPlusPlus) {
379         contexts |= CXCompletionContext_EnumTag |
380                     CXCompletionContext_UnionTag |
381                     CXCompletionContext_StructTag |
382                     CXCompletionContext_ClassTag |
383                     CXCompletionContext_NestedNameSpecifier;
384       }
385       break;
386     }
387     case CodeCompletionContext::CCC_Expression: {
388       contexts = CXCompletionContext_AnyValue;
389       if (S.getLangOpts().CPlusPlus) {
390         contexts |= CXCompletionContext_AnyType |
391                     CXCompletionContext_ObjCInterface |
392                     CXCompletionContext_EnumTag |
393                     CXCompletionContext_UnionTag |
394                     CXCompletionContext_StructTag |
395                     CXCompletionContext_ClassTag |
396                     CXCompletionContext_NestedNameSpecifier;
397       }
398       break;
399     }
400     case CodeCompletionContext::CCC_ObjCMessageReceiver: {
401       contexts = CXCompletionContext_ObjCObjectValue |
402                  CXCompletionContext_ObjCSelectorValue |
403                  CXCompletionContext_ObjCInterface;
404       if (S.getLangOpts().CPlusPlus) {
405         contexts |= CXCompletionContext_CXXClassTypeValue |
406                     CXCompletionContext_AnyType |
407                     CXCompletionContext_EnumTag |
408                     CXCompletionContext_UnionTag |
409                     CXCompletionContext_StructTag |
410                     CXCompletionContext_ClassTag |
411                     CXCompletionContext_NestedNameSpecifier;
412       }
413       break;
414     }
415     case CodeCompletionContext::CCC_DotMemberAccess: {
416       contexts = CXCompletionContext_DotMemberAccess;
417       break;
418     }
419     case CodeCompletionContext::CCC_ArrowMemberAccess: {
420       contexts = CXCompletionContext_ArrowMemberAccess;
421       break;
422     }
423     case CodeCompletionContext::CCC_ObjCPropertyAccess: {
424       contexts = CXCompletionContext_ObjCPropertyAccess;
425       break;
426     }
427     case CodeCompletionContext::CCC_EnumTag: {
428       contexts = CXCompletionContext_EnumTag |
429                  CXCompletionContext_NestedNameSpecifier;
430       break;
431     }
432     case CodeCompletionContext::CCC_UnionTag: {
433       contexts = CXCompletionContext_UnionTag |
434                  CXCompletionContext_NestedNameSpecifier;
435       break;
436     }
437     case CodeCompletionContext::CCC_ClassOrStructTag: {
438       contexts = CXCompletionContext_StructTag |
439                  CXCompletionContext_ClassTag |
440                  CXCompletionContext_NestedNameSpecifier;
441       break;
442     }
443     case CodeCompletionContext::CCC_ObjCProtocolName: {
444       contexts = CXCompletionContext_ObjCProtocol;
445       break;
446     }
447     case CodeCompletionContext::CCC_Namespace: {
448       contexts = CXCompletionContext_Namespace;
449       break;
450     }
451     case CodeCompletionContext::CCC_PotentiallyQualifiedName: {
452       contexts = CXCompletionContext_NestedNameSpecifier;
453       break;
454     }
455     case CodeCompletionContext::CCC_MacroNameUse: {
456       contexts = CXCompletionContext_MacroName;
457       break;
458     }
459     case CodeCompletionContext::CCC_NaturalLanguage: {
460       contexts = CXCompletionContext_NaturalLanguage;
461       break;
462     }
463     case CodeCompletionContext::CCC_SelectorName: {
464       contexts = CXCompletionContext_ObjCSelectorName;
465       break;
466     }
467     case CodeCompletionContext::CCC_ParenthesizedExpression: {
468       contexts = CXCompletionContext_AnyType |
469                  CXCompletionContext_ObjCInterface |
470                  CXCompletionContext_AnyValue;
471       if (S.getLangOpts().CPlusPlus) {
472         contexts |= CXCompletionContext_EnumTag |
473                     CXCompletionContext_UnionTag |
474                     CXCompletionContext_StructTag |
475                     CXCompletionContext_ClassTag |
476                     CXCompletionContext_NestedNameSpecifier;
477       }
478       break;
479     }
480     case CodeCompletionContext::CCC_ObjCInstanceMessage: {
481       contexts = CXCompletionContext_ObjCInstanceMessage;
482       break;
483     }
484     case CodeCompletionContext::CCC_ObjCClassMessage: {
485       contexts = CXCompletionContext_ObjCClassMessage;
486       break;
487     }
488     case CodeCompletionContext::CCC_ObjCInterfaceName: {
489       contexts = CXCompletionContext_ObjCInterface;
490       break;
491     }
492     case CodeCompletionContext::CCC_ObjCCategoryName: {
493       contexts = CXCompletionContext_ObjCCategory;
494       break;
495     }
496     case CodeCompletionContext::CCC_Other:
497     case CodeCompletionContext::CCC_ObjCInterface:
498     case CodeCompletionContext::CCC_ObjCImplementation:
499     case CodeCompletionContext::CCC_Name:
500     case CodeCompletionContext::CCC_MacroName:
501     case CodeCompletionContext::CCC_PreprocessorExpression:
502     case CodeCompletionContext::CCC_PreprocessorDirective:
503     case CodeCompletionContext::CCC_TypeQualifiers: {
504       //Only Clang results should be accepted, so we'll set all of the other
505       //context bits to 0 (i.e. the empty set)
506       contexts = CXCompletionContext_Unexposed;
507       break;
508     }
509     case CodeCompletionContext::CCC_Recovery: {
510       //We don't know what the current context is, so we'll return unknown
511       //This is the equivalent of setting all of the other context bits
512       contexts = CXCompletionContext_Unknown;
513       break;
514     }
515   }
516   return contexts;
517 }
518 
519 namespace {
520   class CaptureCompletionResults : public CodeCompleteConsumer {
521     AllocatedCXCodeCompleteResults &AllocatedResults;
522     CodeCompletionTUInfo CCTUInfo;
523     SmallVector<CXCompletionResult, 16> StoredResults;
524     CXTranslationUnit *TU;
525   public:
526     CaptureCompletionResults(const CodeCompleteOptions &Opts,
527                              AllocatedCXCodeCompleteResults &Results,
528                              CXTranslationUnit *TranslationUnit)
529       : CodeCompleteConsumer(Opts, false),
530         AllocatedResults(Results), CCTUInfo(Results.CodeCompletionAllocator),
531         TU(TranslationUnit) { }
532     ~CaptureCompletionResults() { Finish(); }
533 
534     void ProcessCodeCompleteResults(Sema &S,
535                                     CodeCompletionContext Context,
536                                     CodeCompletionResult *Results,
537                                     unsigned NumResults) override {
538       StoredResults.reserve(StoredResults.size() + NumResults);
539       for (unsigned I = 0; I != NumResults; ++I) {
540         CodeCompletionString *StoredCompletion
541           = Results[I].CreateCodeCompletionString(S, getAllocator(),
542                                                   getCodeCompletionTUInfo(),
543                                                   includeBriefComments());
544 
545         CXCompletionResult R;
546         R.CursorKind = Results[I].CursorKind;
547         R.CompletionString = StoredCompletion;
548         StoredResults.push_back(R);
549       }
550 
551       enum CodeCompletionContext::Kind contextKind = Context.getKind();
552 
553       AllocatedResults.ContextKind = contextKind;
554       AllocatedResults.Contexts = getContextsForContextKind(contextKind, S);
555 
556       AllocatedResults.Selector = "";
557       ArrayRef<IdentifierInfo *> SelIdents = Context.getSelIdents();
558       for (ArrayRef<IdentifierInfo *>::iterator I = SelIdents.begin(),
559                                                 E = SelIdents.end();
560            I != E; ++I) {
561         if (IdentifierInfo *selIdent = *I)
562           AllocatedResults.Selector += selIdent->getName();
563         AllocatedResults.Selector += ":";
564       }
565 
566       QualType baseType = Context.getBaseType();
567       NamedDecl *D = NULL;
568 
569       if (!baseType.isNull()) {
570         // Get the declaration for a class/struct/union/enum type
571         if (const TagType *Tag = baseType->getAs<TagType>())
572           D = Tag->getDecl();
573         // Get the @interface declaration for a (possibly-qualified) Objective-C
574         // object pointer type, e.g., NSString*
575         else if (const ObjCObjectPointerType *ObjPtr =
576                  baseType->getAs<ObjCObjectPointerType>())
577           D = ObjPtr->getInterfaceDecl();
578         // Get the @interface declaration for an Objective-C object type
579         else if (const ObjCObjectType *Obj = baseType->getAs<ObjCObjectType>())
580           D = Obj->getInterface();
581         // Get the class for a C++ injected-class-name
582         else if (const InjectedClassNameType *Injected =
583                  baseType->getAs<InjectedClassNameType>())
584           D = Injected->getDecl();
585       }
586 
587       if (D != NULL) {
588         CXCursor cursor = cxcursor::MakeCXCursor(D, *TU);
589 
590         AllocatedResults.ContainerKind = clang_getCursorKind(cursor);
591 
592         CXString CursorUSR = clang_getCursorUSR(cursor);
593         AllocatedResults.ContainerUSR = clang_getCString(CursorUSR);
594         clang_disposeString(CursorUSR);
595 
596         const Type *type = baseType.getTypePtrOrNull();
597         if (type != NULL) {
598           AllocatedResults.ContainerIsIncomplete = type->isIncompleteType();
599         }
600         else {
601           AllocatedResults.ContainerIsIncomplete = 1;
602         }
603       }
604       else {
605         AllocatedResults.ContainerKind = CXCursor_InvalidCode;
606         AllocatedResults.ContainerUSR.clear();
607         AllocatedResults.ContainerIsIncomplete = 1;
608       }
609     }
610 
611     void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
612                                    OverloadCandidate *Candidates,
613                                    unsigned NumCandidates) override {
614       StoredResults.reserve(StoredResults.size() + NumCandidates);
615       for (unsigned I = 0; I != NumCandidates; ++I) {
616         CodeCompletionString *StoredCompletion
617           = Candidates[I].CreateSignatureString(CurrentArg, S, getAllocator(),
618                                                 getCodeCompletionTUInfo());
619 
620         CXCompletionResult R;
621         R.CursorKind = CXCursor_NotImplemented;
622         R.CompletionString = StoredCompletion;
623         StoredResults.push_back(R);
624       }
625     }
626 
627     CodeCompletionAllocator &getAllocator() override {
628       return *AllocatedResults.CodeCompletionAllocator;
629     }
630 
631     CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo;}
632 
633   private:
634     void Finish() {
635       AllocatedResults.Results = new CXCompletionResult [StoredResults.size()];
636       AllocatedResults.NumResults = StoredResults.size();
637       std::memcpy(AllocatedResults.Results, StoredResults.data(),
638                   StoredResults.size() * sizeof(CXCompletionResult));
639       StoredResults.clear();
640     }
641   };
642 }
643 
644 extern "C" {
645 struct CodeCompleteAtInfo {
646   CXTranslationUnit TU;
647   const char *complete_filename;
648   unsigned complete_line;
649   unsigned complete_column;
650   struct CXUnsavedFile *unsaved_files;
651   unsigned num_unsaved_files;
652   unsigned options;
653   CXCodeCompleteResults *result;
654 };
655 void clang_codeCompleteAt_Impl(void *UserData) {
656   CodeCompleteAtInfo *CCAI = static_cast<CodeCompleteAtInfo*>(UserData);
657   CXTranslationUnit TU = CCAI->TU;
658   const char *complete_filename = CCAI->complete_filename;
659   unsigned complete_line = CCAI->complete_line;
660   unsigned complete_column = CCAI->complete_column;
661   struct CXUnsavedFile *unsaved_files = CCAI->unsaved_files;
662   unsigned num_unsaved_files = CCAI->num_unsaved_files;
663   unsigned options = CCAI->options;
664   bool IncludeBriefComments = options & CXCodeComplete_IncludeBriefComments;
665   CCAI->result = 0;
666 
667 #ifdef UDP_CODE_COMPLETION_LOGGER
668 #ifdef UDP_CODE_COMPLETION_LOGGER_PORT
669   const llvm::TimeRecord &StartTime =  llvm::TimeRecord::getCurrentTime();
670 #endif
671 #endif
672 
673   bool EnableLogging = getenv("LIBCLANG_CODE_COMPLETION_LOGGING") != 0;
674 
675   if (cxtu::isNotUsableTU(TU)) {
676     LOG_BAD_TU(TU);
677     return;
678   }
679 
680   ASTUnit *AST = cxtu::getASTUnit(TU);
681   if (!AST)
682     return;
683 
684   CIndexer *CXXIdx = TU->CIdx;
685   if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
686     setThreadBackgroundPriority();
687 
688   ASTUnit::ConcurrencyCheck Check(*AST);
689 
690   // Perform the remapping of source files.
691   SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
692   for (unsigned I = 0; I != num_unsaved_files; ++I) {
693     StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
694     const llvm::MemoryBuffer *Buffer
695       = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
696     RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
697                                            Buffer));
698   }
699 
700   if (EnableLogging) {
701     // FIXME: Add logging.
702   }
703 
704   // Parse the resulting source file to find code-completion results.
705   AllocatedCXCodeCompleteResults *Results = new AllocatedCXCodeCompleteResults(
706       &AST->getFileManager());
707   Results->Results = 0;
708   Results->NumResults = 0;
709 
710   // Create a code-completion consumer to capture the results.
711   CodeCompleteOptions Opts;
712   Opts.IncludeBriefComments = IncludeBriefComments;
713   CaptureCompletionResults Capture(Opts, *Results, &TU);
714 
715   // Perform completion.
716   AST->CodeComplete(complete_filename, complete_line, complete_column,
717                     RemappedFiles,
718                     (options & CXCodeComplete_IncludeMacros),
719                     (options & CXCodeComplete_IncludeCodePatterns),
720                     IncludeBriefComments,
721                     Capture,
722                     *Results->Diag, Results->LangOpts, *Results->SourceMgr,
723                     *Results->FileMgr, Results->Diagnostics,
724                     Results->TemporaryBuffers);
725 
726   // Keep a reference to the allocator used for cached global completions, so
727   // that we can be sure that the memory used by our code completion strings
728   // doesn't get freed due to subsequent reparses (while the code completion
729   // results are still active).
730   Results->CachedCompletionAllocator = AST->getCachedCompletionAllocator();
731 
732 
733 
734 #ifdef UDP_CODE_COMPLETION_LOGGER
735 #ifdef UDP_CODE_COMPLETION_LOGGER_PORT
736   const llvm::TimeRecord &EndTime =  llvm::TimeRecord::getCurrentTime();
737   SmallString<256> LogResult;
738   llvm::raw_svector_ostream os(LogResult);
739 
740   // Figure out the language and whether or not it uses PCH.
741   const char *lang = 0;
742   bool usesPCH = false;
743 
744   for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
745        I != E; ++I) {
746     if (*I == 0)
747       continue;
748     if (strcmp(*I, "-x") == 0) {
749       if (I + 1 != E) {
750         lang = *(++I);
751         continue;
752       }
753     }
754     else if (strcmp(*I, "-include") == 0) {
755       if (I+1 != E) {
756         const char *arg = *(++I);
757         SmallString<512> pchName;
758         {
759           llvm::raw_svector_ostream os(pchName);
760           os << arg << ".pth";
761         }
762         pchName.push_back('\0');
763         struct stat stat_results;
764         if (stat(pchName.str().c_str(), &stat_results) == 0)
765           usesPCH = true;
766         continue;
767       }
768     }
769   }
770 
771   os << "{ ";
772   os << "\"wall\": " << (EndTime.getWallTime() - StartTime.getWallTime());
773   os << ", \"numRes\": " << Results->NumResults;
774   os << ", \"diags\": " << Results->Diagnostics.size();
775   os << ", \"pch\": " << (usesPCH ? "true" : "false");
776   os << ", \"lang\": \"" << (lang ? lang : "<unknown>") << '"';
777   const char *name = getlogin();
778   os << ", \"user\": \"" << (name ? name : "unknown") << '"';
779   os << ", \"clangVer\": \"" << getClangFullVersion() << '"';
780   os << " }";
781 
782   StringRef res = os.str();
783   if (res.size() > 0) {
784     do {
785       // Setup the UDP socket.
786       struct sockaddr_in servaddr;
787       bzero(&servaddr, sizeof(servaddr));
788       servaddr.sin_family = AF_INET;
789       servaddr.sin_port = htons(UDP_CODE_COMPLETION_LOGGER_PORT);
790       if (inet_pton(AF_INET, UDP_CODE_COMPLETION_LOGGER,
791                     &servaddr.sin_addr) <= 0)
792         break;
793 
794       int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
795       if (sockfd < 0)
796         break;
797 
798       sendto(sockfd, res.data(), res.size(), 0,
799              (struct sockaddr *)&servaddr, sizeof(servaddr));
800       close(sockfd);
801     }
802     while (false);
803   }
804 #endif
805 #endif
806   CCAI->result = Results;
807 }
808 CXCodeCompleteResults *clang_codeCompleteAt(CXTranslationUnit TU,
809                                             const char *complete_filename,
810                                             unsigned complete_line,
811                                             unsigned complete_column,
812                                             struct CXUnsavedFile *unsaved_files,
813                                             unsigned num_unsaved_files,
814                                             unsigned options) {
815   LOG_FUNC_SECTION {
816     *Log << TU << ' '
817          << complete_filename << ':' << complete_line << ':' << complete_column;
818   }
819 
820   CodeCompleteAtInfo CCAI = { TU, complete_filename, complete_line,
821                               complete_column, unsaved_files, num_unsaved_files,
822                               options, 0 };
823 
824   if (getenv("LIBCLANG_NOTHREADS")) {
825     clang_codeCompleteAt_Impl(&CCAI);
826     return CCAI.result;
827   }
828 
829   llvm::CrashRecoveryContext CRC;
830 
831   if (!RunSafely(CRC, clang_codeCompleteAt_Impl, &CCAI)) {
832     fprintf(stderr, "libclang: crash detected in code completion\n");
833     cxtu::getASTUnit(TU)->setUnsafeToFree(true);
834     return 0;
835   } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
836     PrintLibclangResourceUsage(TU);
837 
838   return CCAI.result;
839 }
840 
841 unsigned clang_defaultCodeCompleteOptions(void) {
842   return CXCodeComplete_IncludeMacros;
843 }
844 
845 void clang_disposeCodeCompleteResults(CXCodeCompleteResults *ResultsIn) {
846   if (!ResultsIn)
847     return;
848 
849   AllocatedCXCodeCompleteResults *Results
850     = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
851   delete Results;
852 }
853 
854 unsigned
855 clang_codeCompleteGetNumDiagnostics(CXCodeCompleteResults *ResultsIn) {
856   AllocatedCXCodeCompleteResults *Results
857     = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
858   if (!Results)
859     return 0;
860 
861   return Results->Diagnostics.size();
862 }
863 
864 CXDiagnostic
865 clang_codeCompleteGetDiagnostic(CXCodeCompleteResults *ResultsIn,
866                                 unsigned Index) {
867   AllocatedCXCodeCompleteResults *Results
868     = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
869   if (!Results || Index >= Results->Diagnostics.size())
870     return 0;
871 
872   return new CXStoredDiagnostic(Results->Diagnostics[Index], Results->LangOpts);
873 }
874 
875 unsigned long long
876 clang_codeCompleteGetContexts(CXCodeCompleteResults *ResultsIn) {
877   AllocatedCXCodeCompleteResults *Results
878     = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
879   if (!Results)
880     return 0;
881 
882   return Results->Contexts;
883 }
884 
885 enum CXCursorKind clang_codeCompleteGetContainerKind(
886                                                CXCodeCompleteResults *ResultsIn,
887                                                      unsigned *IsIncomplete) {
888   AllocatedCXCodeCompleteResults *Results =
889     static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn);
890   if (!Results)
891     return CXCursor_InvalidCode;
892 
893   if (IsIncomplete != NULL) {
894     *IsIncomplete = Results->ContainerIsIncomplete;
895   }
896 
897   return Results->ContainerKind;
898 }
899 
900 CXString clang_codeCompleteGetContainerUSR(CXCodeCompleteResults *ResultsIn) {
901   AllocatedCXCodeCompleteResults *Results =
902     static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn);
903   if (!Results)
904     return cxstring::createEmpty();
905 
906   return cxstring::createRef(Results->ContainerUSR.c_str());
907 }
908 
909 
910 CXString clang_codeCompleteGetObjCSelector(CXCodeCompleteResults *ResultsIn) {
911   AllocatedCXCodeCompleteResults *Results =
912     static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn);
913   if (!Results)
914     return cxstring::createEmpty();
915 
916   return cxstring::createDup(Results->Selector);
917 }
918 
919 } // end extern "C"
920 
921 /// \brief Simple utility function that appends a \p New string to the given
922 /// \p Old string, using the \p Buffer for storage.
923 ///
924 /// \param Old The string to which we are appending. This parameter will be
925 /// updated to reflect the complete string.
926 ///
927 ///
928 /// \param New The string to append to \p Old.
929 ///
930 /// \param Buffer A buffer that stores the actual, concatenated string. It will
931 /// be used if the old string is already-non-empty.
932 static void AppendToString(StringRef &Old, StringRef New,
933                            SmallString<256> &Buffer) {
934   if (Old.empty()) {
935     Old = New;
936     return;
937   }
938 
939   if (Buffer.empty())
940     Buffer.append(Old.begin(), Old.end());
941   Buffer.append(New.begin(), New.end());
942   Old = Buffer.str();
943 }
944 
945 /// \brief Get the typed-text blocks from the given code-completion string
946 /// and return them as a single string.
947 ///
948 /// \param String The code-completion string whose typed-text blocks will be
949 /// concatenated.
950 ///
951 /// \param Buffer A buffer used for storage of the completed name.
952 static StringRef GetTypedName(CodeCompletionString *String,
953                                     SmallString<256> &Buffer) {
954   StringRef Result;
955   for (CodeCompletionString::iterator C = String->begin(), CEnd = String->end();
956        C != CEnd; ++C) {
957     if (C->Kind == CodeCompletionString::CK_TypedText)
958       AppendToString(Result, C->Text, Buffer);
959   }
960 
961   return Result;
962 }
963 
964 namespace {
965   struct OrderCompletionResults {
966     bool operator()(const CXCompletionResult &XR,
967                     const CXCompletionResult &YR) const {
968       CodeCompletionString *X
969         = (CodeCompletionString *)XR.CompletionString;
970       CodeCompletionString *Y
971         = (CodeCompletionString *)YR.CompletionString;
972 
973       SmallString<256> XBuffer;
974       StringRef XText = GetTypedName(X, XBuffer);
975       SmallString<256> YBuffer;
976       StringRef YText = GetTypedName(Y, YBuffer);
977 
978       if (XText.empty() || YText.empty())
979         return !XText.empty();
980 
981       int result = XText.compare_lower(YText);
982       if (result < 0)
983         return true;
984       if (result > 0)
985         return false;
986 
987       result = XText.compare(YText);
988       return result < 0;
989     }
990   };
991 }
992 
993 extern "C" {
994   void clang_sortCodeCompletionResults(CXCompletionResult *Results,
995                                        unsigned NumResults) {
996     std::stable_sort(Results, Results + NumResults, OrderCompletionResults());
997   }
998 }
999