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