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