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