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