1 //===--- CodeCompleteConsumer.cpp - Code Completion Interface ---*- C++ -*-===//
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 CodeCompleteConsumer class.
11 //
12 //===----------------------------------------------------------------------===//
13 #include "clang/Sema/CodeCompleteConsumer.h"
14 #include "clang/Sema/Scope.h"
15 #include "clang/Sema/Sema.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/Lex/Preprocessor.h"
20 #include "clang-c/Index.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include <algorithm>
25 #include <cstring>
26 #include <functional>
27 
28 using namespace clang;
29 
30 //===----------------------------------------------------------------------===//
31 // Code completion context implementation
32 //===----------------------------------------------------------------------===//
33 
34 bool CodeCompletionContext::wantConstructorResults() const {
35   switch (Kind) {
36   case CCC_Recovery:
37   case CCC_Statement:
38   case CCC_Expression:
39   case CCC_ObjCMessageReceiver:
40   case CCC_ParenthesizedExpression:
41     return true;
42 
43   case CCC_TopLevel:
44   case CCC_ObjCInterface:
45   case CCC_ObjCImplementation:
46   case CCC_ObjCIvarList:
47   case CCC_ClassStructUnion:
48   case CCC_DotMemberAccess:
49   case CCC_ArrowMemberAccess:
50   case CCC_ObjCPropertyAccess:
51   case CCC_EnumTag:
52   case CCC_UnionTag:
53   case CCC_ClassOrStructTag:
54   case CCC_ObjCProtocolName:
55   case CCC_Namespace:
56   case CCC_Type:
57   case CCC_Name:
58   case CCC_PotentiallyQualifiedName:
59   case CCC_MacroName:
60   case CCC_MacroNameUse:
61   case CCC_PreprocessorExpression:
62   case CCC_PreprocessorDirective:
63   case CCC_NaturalLanguage:
64   case CCC_SelectorName:
65   case CCC_TypeQualifiers:
66   case CCC_Other:
67   case CCC_OtherWithMacros:
68   case CCC_ObjCInstanceMessage:
69   case CCC_ObjCClassMessage:
70   case CCC_ObjCInterfaceName:
71   case CCC_ObjCCategoryName:
72     return false;
73   }
74 
75   llvm_unreachable("Invalid CodeCompletionContext::Kind!");
76 }
77 
78 //===----------------------------------------------------------------------===//
79 // Code completion string implementation
80 //===----------------------------------------------------------------------===//
81 CodeCompletionString::Chunk::Chunk(ChunkKind Kind, const char *Text)
82   : Kind(Kind), Text("")
83 {
84   switch (Kind) {
85   case CK_TypedText:
86   case CK_Text:
87   case CK_Placeholder:
88   case CK_Informative:
89   case CK_ResultType:
90   case CK_CurrentParameter:
91     this->Text = Text;
92     break;
93 
94   case CK_Optional:
95     llvm_unreachable("Optional strings cannot be created from text");
96 
97   case CK_LeftParen:
98     this->Text = "(";
99     break;
100 
101   case CK_RightParen:
102     this->Text = ")";
103     break;
104 
105   case CK_LeftBracket:
106     this->Text = "[";
107     break;
108 
109   case CK_RightBracket:
110     this->Text = "]";
111     break;
112 
113   case CK_LeftBrace:
114     this->Text = "{";
115     break;
116 
117   case CK_RightBrace:
118     this->Text = "}";
119     break;
120 
121   case CK_LeftAngle:
122     this->Text = "<";
123     break;
124 
125   case CK_RightAngle:
126     this->Text = ">";
127     break;
128 
129   case CK_Comma:
130     this->Text = ", ";
131     break;
132 
133   case CK_Colon:
134     this->Text = ":";
135     break;
136 
137   case CK_SemiColon:
138     this->Text = ";";
139     break;
140 
141   case CK_Equal:
142     this->Text = " = ";
143     break;
144 
145   case CK_HorizontalSpace:
146     this->Text = " ";
147     break;
148 
149   case CK_VerticalSpace:
150     this->Text = "\n";
151     break;
152   }
153 }
154 
155 CodeCompletionString::Chunk
156 CodeCompletionString::Chunk::CreateText(const char *Text) {
157   return Chunk(CK_Text, Text);
158 }
159 
160 CodeCompletionString::Chunk
161 CodeCompletionString::Chunk::CreateOptional(CodeCompletionString *Optional) {
162   Chunk Result;
163   Result.Kind = CK_Optional;
164   Result.Optional = Optional;
165   return Result;
166 }
167 
168 CodeCompletionString::Chunk
169 CodeCompletionString::Chunk::CreatePlaceholder(const char *Placeholder) {
170   return Chunk(CK_Placeholder, Placeholder);
171 }
172 
173 CodeCompletionString::Chunk
174 CodeCompletionString::Chunk::CreateInformative(const char *Informative) {
175   return Chunk(CK_Informative, Informative);
176 }
177 
178 CodeCompletionString::Chunk
179 CodeCompletionString::Chunk::CreateResultType(const char *ResultType) {
180   return Chunk(CK_ResultType, ResultType);
181 }
182 
183 CodeCompletionString::Chunk
184 CodeCompletionString::Chunk::CreateCurrentParameter(
185                                                 const char *CurrentParameter) {
186   return Chunk(CK_CurrentParameter, CurrentParameter);
187 }
188 
189 CodeCompletionString::CodeCompletionString(const Chunk *Chunks,
190                                            unsigned NumChunks,
191                                            unsigned Priority,
192                                            CXAvailabilityKind Availability,
193                                            const char **Annotations,
194                                            unsigned NumAnnotations)
195   : NumChunks(NumChunks), NumAnnotations(NumAnnotations)
196   , Priority(Priority), Availability(Availability)
197 {
198   assert(NumChunks <= 0xffff);
199   assert(NumAnnotations <= 0xffff);
200 
201   Chunk *StoredChunks = reinterpret_cast<Chunk *>(this + 1);
202   for (unsigned I = 0; I != NumChunks; ++I)
203     StoredChunks[I] = Chunks[I];
204 
205   const char **StoredAnnotations = reinterpret_cast<const char **>(StoredChunks + NumChunks);
206   for (unsigned I = 0; I != NumAnnotations; ++I)
207     StoredAnnotations[I] = Annotations[I];
208 }
209 
210 unsigned CodeCompletionString::getAnnotationCount() const {
211   return NumAnnotations;
212 }
213 
214 const char *CodeCompletionString::getAnnotation(unsigned AnnotationNr) const {
215   if (AnnotationNr < NumAnnotations)
216     return reinterpret_cast<const char * const*>(end())[AnnotationNr];
217   else
218     return 0;
219 }
220 
221 
222 std::string CodeCompletionString::getAsString() const {
223   std::string Result;
224   llvm::raw_string_ostream OS(Result);
225 
226   for (iterator C = begin(), CEnd = end(); C != CEnd; ++C) {
227     switch (C->Kind) {
228     case CK_Optional: OS << "{#" << C->Optional->getAsString() << "#}"; break;
229     case CK_Placeholder: OS << "<#" << C->Text << "#>"; break;
230 
231     case CK_Informative:
232     case CK_ResultType:
233       OS << "[#" << C->Text << "#]";
234       break;
235 
236     case CK_CurrentParameter: OS << "<#" << C->Text << "#>"; break;
237     default: OS << C->Text; break;
238     }
239   }
240   return OS.str();
241 }
242 
243 const char *CodeCompletionString::getTypedText() const {
244   for (iterator C = begin(), CEnd = end(); C != CEnd; ++C)
245     if (C->Kind == CK_TypedText)
246       return C->Text;
247 
248   return 0;
249 }
250 
251 const char *CodeCompletionAllocator::CopyString(StringRef String) {
252   char *Mem = (char *)Allocate(String.size() + 1, 1);
253   std::copy(String.begin(), String.end(), Mem);
254   Mem[String.size()] = 0;
255   return Mem;
256 }
257 
258 const char *CodeCompletionAllocator::CopyString(Twine String) {
259   // FIXME: It would be more efficient to teach Twine to tell us its size and
260   // then add a routine there to fill in an allocated char* with the contents
261   // of the string.
262   llvm::SmallString<128> Data;
263   return CopyString(String.toStringRef(Data));
264 }
265 
266 CodeCompletionString *CodeCompletionBuilder::TakeString() {
267   void *Mem = Allocator.Allocate(
268                   sizeof(CodeCompletionString) + sizeof(Chunk) * Chunks.size()
269                                     + sizeof(const char *) * Annotations.size(),
270                                  llvm::alignOf<CodeCompletionString>());
271   CodeCompletionString *Result
272     = new (Mem) CodeCompletionString(Chunks.data(), Chunks.size(),
273                                      Priority, Availability,
274                                      Annotations.data(), Annotations.size());
275   Chunks.clear();
276   return Result;
277 }
278 
279 unsigned CodeCompletionResult::getPriorityFromDecl(NamedDecl *ND) {
280   if (!ND)
281     return CCP_Unlikely;
282 
283   // Context-based decisions.
284   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
285   if (DC->isFunctionOrMethod() || isa<BlockDecl>(DC)) {
286     // _cmd is relatively rare
287     if (ImplicitParamDecl *ImplicitParam = dyn_cast<ImplicitParamDecl>(ND))
288       if (ImplicitParam->getIdentifier() &&
289           ImplicitParam->getIdentifier()->isStr("_cmd"))
290         return CCP_ObjC_cmd;
291 
292     return CCP_LocalDeclaration;
293   }
294   if (DC->isRecord() || isa<ObjCContainerDecl>(DC))
295     return CCP_MemberDeclaration;
296 
297   // Content-based decisions.
298   if (isa<EnumConstantDecl>(ND))
299     return CCP_Constant;
300   if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
301     return CCP_Type;
302 
303   return CCP_Declaration;
304 }
305 
306 //===----------------------------------------------------------------------===//
307 // Code completion overload candidate implementation
308 //===----------------------------------------------------------------------===//
309 FunctionDecl *
310 CodeCompleteConsumer::OverloadCandidate::getFunction() const {
311   if (getKind() == CK_Function)
312     return Function;
313   else if (getKind() == CK_FunctionTemplate)
314     return FunctionTemplate->getTemplatedDecl();
315   else
316     return 0;
317 }
318 
319 const FunctionType *
320 CodeCompleteConsumer::OverloadCandidate::getFunctionType() const {
321   switch (Kind) {
322   case CK_Function:
323     return Function->getType()->getAs<FunctionType>();
324 
325   case CK_FunctionTemplate:
326     return FunctionTemplate->getTemplatedDecl()->getType()
327              ->getAs<FunctionType>();
328 
329   case CK_FunctionType:
330     return Type;
331   }
332 
333   llvm_unreachable("Invalid CandidateKind!");
334 }
335 
336 //===----------------------------------------------------------------------===//
337 // Code completion consumer implementation
338 //===----------------------------------------------------------------------===//
339 
340 CodeCompleteConsumer::~CodeCompleteConsumer() { }
341 
342 void
343 PrintingCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &SemaRef,
344                                                  CodeCompletionContext Context,
345                                                  CodeCompletionResult *Results,
346                                                          unsigned NumResults) {
347   std::stable_sort(Results, Results + NumResults);
348 
349   // Print the results.
350   for (unsigned I = 0; I != NumResults; ++I) {
351     OS << "COMPLETION: ";
352     switch (Results[I].Kind) {
353     case CodeCompletionResult::RK_Declaration:
354       OS << *Results[I].Declaration;
355       if (Results[I].Hidden)
356         OS << " (Hidden)";
357       if (CodeCompletionString *CCS
358             = Results[I].CreateCodeCompletionString(SemaRef, Allocator)) {
359         OS << " : " << CCS->getAsString();
360       }
361 
362       OS << '\n';
363       break;
364 
365     case CodeCompletionResult::RK_Keyword:
366       OS << Results[I].Keyword << '\n';
367       break;
368 
369     case CodeCompletionResult::RK_Macro: {
370       OS << Results[I].Macro->getName();
371       if (CodeCompletionString *CCS
372             = Results[I].CreateCodeCompletionString(SemaRef, Allocator)) {
373         OS << " : " << CCS->getAsString();
374       }
375       OS << '\n';
376       break;
377     }
378 
379     case CodeCompletionResult::RK_Pattern: {
380       OS << "Pattern : "
381          << Results[I].Pattern->getAsString() << '\n';
382       break;
383     }
384     }
385   }
386 }
387 
388 void
389 PrintingCodeCompleteConsumer::ProcessOverloadCandidates(Sema &SemaRef,
390                                                         unsigned CurrentArg,
391                                               OverloadCandidate *Candidates,
392                                                      unsigned NumCandidates) {
393   for (unsigned I = 0; I != NumCandidates; ++I) {
394     if (CodeCompletionString *CCS
395           = Candidates[I].CreateSignatureString(CurrentArg, SemaRef,
396                                                 Allocator)) {
397       OS << "OVERLOAD: " << CCS->getAsString() << "\n";
398     }
399   }
400 }
401 
402 void CodeCompletionResult::computeCursorKindAndAvailability(bool Accessible) {
403   switch (Kind) {
404   case RK_Declaration:
405     // Set the availability based on attributes.
406     switch (Declaration->getAvailability()) {
407     case AR_Available:
408     case AR_NotYetIntroduced:
409       Availability = CXAvailability_Available;
410       break;
411 
412     case AR_Deprecated:
413       Availability = CXAvailability_Deprecated;
414       break;
415 
416     case AR_Unavailable:
417       Availability = CXAvailability_NotAvailable;
418       break;
419     }
420 
421     if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Declaration))
422       if (Function->isDeleted())
423         Availability = CXAvailability_NotAvailable;
424 
425     CursorKind = getCursorKindForDecl(Declaration);
426     if (CursorKind == CXCursor_UnexposedDecl) {
427       // FIXME: Forward declarations of Objective-C classes and protocols
428       // are not directly exposed, but we want code completion to treat them
429       // like a definition.
430       if (isa<ObjCInterfaceDecl>(Declaration))
431         CursorKind = CXCursor_ObjCInterfaceDecl;
432       else if (isa<ObjCProtocolDecl>(Declaration))
433         CursorKind = CXCursor_ObjCProtocolDecl;
434       else
435         CursorKind = CXCursor_NotImplemented;
436     }
437     break;
438 
439   case RK_Macro:
440     Availability = CXAvailability_Available;
441     CursorKind = CXCursor_MacroDefinition;
442     break;
443 
444   case RK_Keyword:
445     Availability = CXAvailability_Available;
446     CursorKind = CXCursor_NotImplemented;
447     break;
448 
449   case RK_Pattern:
450     // Do nothing: Patterns can come with cursor kinds!
451     break;
452   }
453 
454   if (!Accessible)
455     Availability = CXAvailability_NotAccessible;
456 }
457 
458 /// \brief Retrieve the name that should be used to order a result.
459 ///
460 /// If the name needs to be constructed as a string, that string will be
461 /// saved into Saved and the returned StringRef will refer to it.
462 static StringRef getOrderedName(const CodeCompletionResult &R,
463                                     std::string &Saved) {
464   switch (R.Kind) {
465     case CodeCompletionResult::RK_Keyword:
466       return R.Keyword;
467 
468     case CodeCompletionResult::RK_Pattern:
469       return R.Pattern->getTypedText();
470 
471     case CodeCompletionResult::RK_Macro:
472       return R.Macro->getName();
473 
474     case CodeCompletionResult::RK_Declaration:
475       // Handle declarations below.
476       break;
477   }
478 
479   DeclarationName Name = R.Declaration->getDeclName();
480 
481   // If the name is a simple identifier (by far the common case), or a
482   // zero-argument selector, just return a reference to that identifier.
483   if (IdentifierInfo *Id = Name.getAsIdentifierInfo())
484     return Id->getName();
485   if (Name.isObjCZeroArgSelector())
486     if (IdentifierInfo *Id
487         = Name.getObjCSelector().getIdentifierInfoForSlot(0))
488       return Id->getName();
489 
490   Saved = Name.getAsString();
491   return Saved;
492 }
493 
494 bool clang::operator<(const CodeCompletionResult &X,
495                       const CodeCompletionResult &Y) {
496   std::string XSaved, YSaved;
497   StringRef XStr = getOrderedName(X, XSaved);
498   StringRef YStr = getOrderedName(Y, YSaved);
499   int cmp = XStr.compare_lower(YStr);
500   if (cmp)
501     return cmp < 0;
502 
503   // If case-insensitive comparison fails, try case-sensitive comparison.
504   cmp = XStr.compare(YStr);
505   if (cmp)
506     return cmp < 0;
507 
508   return false;
509 }
510