CodeCompleteConsumer.cpp revision 6bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89
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-c/Index.h"
15#include "clang/AST/DeclCXX.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/DeclTemplate.h"
18#include "clang/Sema/Scope.h"
19#include "clang/Sema/Sema.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SmallString.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  llvm_unreachable("Invalid CodeCompletionContext::Kind!");
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
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
155CodeCompletionString::Chunk
156CodeCompletionString::Chunk::CreateText(const char *Text) {
157  return Chunk(CK_Text, Text);
158}
159
160CodeCompletionString::Chunk
161CodeCompletionString::Chunk::CreateOptional(CodeCompletionString *Optional) {
162  Chunk Result;
163  Result.Kind = CK_Optional;
164  Result.Optional = Optional;
165  return Result;
166}
167
168CodeCompletionString::Chunk
169CodeCompletionString::Chunk::CreatePlaceholder(const char *Placeholder) {
170  return Chunk(CK_Placeholder, Placeholder);
171}
172
173CodeCompletionString::Chunk
174CodeCompletionString::Chunk::CreateInformative(const char *Informative) {
175  return Chunk(CK_Informative, Informative);
176}
177
178CodeCompletionString::Chunk
179CodeCompletionString::Chunk::CreateResultType(const char *ResultType) {
180  return Chunk(CK_ResultType, ResultType);
181}
182
183CodeCompletionString::Chunk
184CodeCompletionString::Chunk::CreateCurrentParameter(
185                                                const char *CurrentParameter) {
186  return Chunk(CK_CurrentParameter, CurrentParameter);
187}
188
189CodeCompletionString::CodeCompletionString(const Chunk *Chunks,
190                                           unsigned NumChunks,
191                                           unsigned Priority,
192                                           CXAvailabilityKind Availability,
193                                           const char **Annotations,
194                                           unsigned NumAnnotations,
195                                           StringRef ParentName,
196                                           const char *BriefComment)
197  : NumChunks(NumChunks), NumAnnotations(NumAnnotations),
198    Priority(Priority), Availability(Availability),
199    ParentName(ParentName), BriefComment(BriefComment)
200{
201  assert(NumChunks <= 0xffff);
202  assert(NumAnnotations <= 0xffff);
203
204  Chunk *StoredChunks = reinterpret_cast<Chunk *>(this + 1);
205  for (unsigned I = 0; I != NumChunks; ++I)
206    StoredChunks[I] = Chunks[I];
207
208  const char **StoredAnnotations = reinterpret_cast<const char **>(StoredChunks + NumChunks);
209  for (unsigned I = 0; I != NumAnnotations; ++I)
210    StoredAnnotations[I] = Annotations[I];
211}
212
213unsigned CodeCompletionString::getAnnotationCount() const {
214  return NumAnnotations;
215}
216
217const char *CodeCompletionString::getAnnotation(unsigned AnnotationNr) const {
218  if (AnnotationNr < NumAnnotations)
219    return reinterpret_cast<const char * const*>(end())[AnnotationNr];
220  else
221    return nullptr;
222}
223
224
225std::string CodeCompletionString::getAsString() const {
226  std::string Result;
227  llvm::raw_string_ostream OS(Result);
228
229  for (iterator C = begin(), CEnd = end(); C != CEnd; ++C) {
230    switch (C->Kind) {
231    case CK_Optional: OS << "{#" << C->Optional->getAsString() << "#}"; break;
232    case CK_Placeholder: OS << "<#" << C->Text << "#>"; break;
233
234    case CK_Informative:
235    case CK_ResultType:
236      OS << "[#" << C->Text << "#]";
237      break;
238
239    case CK_CurrentParameter: OS << "<#" << C->Text << "#>"; break;
240    default: OS << C->Text; break;
241    }
242  }
243  return OS.str();
244}
245
246const char *CodeCompletionString::getTypedText() const {
247  for (iterator C = begin(), CEnd = end(); C != CEnd; ++C)
248    if (C->Kind == CK_TypedText)
249      return C->Text;
250
251  return nullptr;
252}
253
254const char *CodeCompletionAllocator::CopyString(StringRef String) {
255  char *Mem = (char *)Allocate(String.size() + 1, 1);
256  std::copy(String.begin(), String.end(), Mem);
257  Mem[String.size()] = 0;
258  return Mem;
259}
260
261const char *CodeCompletionAllocator::CopyString(Twine String) {
262  // FIXME: It would be more efficient to teach Twine to tell us its size and
263  // then add a routine there to fill in an allocated char* with the contents
264  // of the string.
265  SmallString<128> Data;
266  return CopyString(String.toStringRef(Data));
267}
268
269StringRef CodeCompletionTUInfo::getParentName(const DeclContext *DC) {
270  const NamedDecl *ND = dyn_cast<NamedDecl>(DC);
271  if (!ND)
272    return StringRef();
273
274  // Check whether we've already cached the parent name.
275  StringRef &CachedParentName = ParentNames[DC];
276  if (!CachedParentName.empty())
277    return CachedParentName;
278
279  // If we already processed this DeclContext and assigned empty to it, the
280  // data pointer will be non-null.
281  if (CachedParentName.data() != nullptr)
282    return StringRef();
283
284  // Find the interesting names.
285  SmallVector<const DeclContext *, 2> Contexts;
286  while (DC && !DC->isFunctionOrMethod()) {
287    if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC)) {
288      if (ND->getIdentifier())
289        Contexts.push_back(DC);
290    }
291
292    DC = DC->getParent();
293  }
294
295  {
296    SmallString<128> S;
297    llvm::raw_svector_ostream OS(S);
298    bool First = true;
299    for (unsigned I = Contexts.size(); I != 0; --I) {
300      if (First)
301        First = false;
302      else {
303        OS << "::";
304      }
305
306      const DeclContext *CurDC = Contexts[I-1];
307      if (const ObjCCategoryImplDecl *CatImpl = dyn_cast<ObjCCategoryImplDecl>(CurDC))
308        CurDC = CatImpl->getCategoryDecl();
309
310      if (const ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(CurDC)) {
311        const ObjCInterfaceDecl *Interface = Cat->getClassInterface();
312        if (!Interface) {
313          // Assign an empty StringRef but with non-null data to distinguish
314          // between empty because we didn't process the DeclContext yet.
315          CachedParentName = StringRef((const char *)~0U, 0);
316          return StringRef();
317        }
318
319        OS << Interface->getName() << '(' << Cat->getName() << ')';
320      } else {
321        OS << cast<NamedDecl>(CurDC)->getName();
322      }
323    }
324
325    CachedParentName = AllocatorRef->CopyString(OS.str());
326  }
327
328  return CachedParentName;
329}
330
331CodeCompletionString *CodeCompletionBuilder::TakeString() {
332  void *Mem = getAllocator().Allocate(
333                  sizeof(CodeCompletionString) + sizeof(Chunk) * Chunks.size()
334                                    + sizeof(const char *) * Annotations.size(),
335                                 llvm::alignOf<CodeCompletionString>());
336  CodeCompletionString *Result
337    = new (Mem) CodeCompletionString(Chunks.data(), Chunks.size(),
338                                     Priority, Availability,
339                                     Annotations.data(), Annotations.size(),
340                                     ParentName, BriefComment);
341  Chunks.clear();
342  return Result;
343}
344
345void CodeCompletionBuilder::AddTypedTextChunk(const char *Text) {
346  Chunks.push_back(Chunk(CodeCompletionString::CK_TypedText, Text));
347}
348
349void CodeCompletionBuilder::AddTextChunk(const char *Text) {
350  Chunks.push_back(Chunk::CreateText(Text));
351}
352
353void CodeCompletionBuilder::AddOptionalChunk(CodeCompletionString *Optional) {
354  Chunks.push_back(Chunk::CreateOptional(Optional));
355}
356
357void CodeCompletionBuilder::AddPlaceholderChunk(const char *Placeholder) {
358  Chunks.push_back(Chunk::CreatePlaceholder(Placeholder));
359}
360
361void CodeCompletionBuilder::AddInformativeChunk(const char *Text) {
362  Chunks.push_back(Chunk::CreateInformative(Text));
363}
364
365void CodeCompletionBuilder::AddResultTypeChunk(const char *ResultType) {
366  Chunks.push_back(Chunk::CreateResultType(ResultType));
367}
368
369void
370CodeCompletionBuilder::AddCurrentParameterChunk(const char *CurrentParameter) {
371  Chunks.push_back(Chunk::CreateCurrentParameter(CurrentParameter));
372}
373
374void CodeCompletionBuilder::AddChunk(CodeCompletionString::ChunkKind CK,
375                                     const char *Text) {
376  Chunks.push_back(Chunk(CK, Text));
377}
378
379void CodeCompletionBuilder::addParentContext(const DeclContext *DC) {
380  if (DC->isTranslationUnit()) {
381    return;
382  }
383
384  if (DC->isFunctionOrMethod())
385    return;
386
387  const NamedDecl *ND = dyn_cast<NamedDecl>(DC);
388  if (!ND)
389    return;
390
391  ParentName = getCodeCompletionTUInfo().getParentName(DC);
392}
393
394void CodeCompletionBuilder::addBriefComment(StringRef Comment) {
395  BriefComment = Allocator.CopyString(Comment);
396}
397
398//===----------------------------------------------------------------------===//
399// Code completion overload candidate implementation
400//===----------------------------------------------------------------------===//
401FunctionDecl *
402CodeCompleteConsumer::OverloadCandidate::getFunction() const {
403  if (getKind() == CK_Function)
404    return Function;
405  else if (getKind() == CK_FunctionTemplate)
406    return FunctionTemplate->getTemplatedDecl();
407  else
408    return nullptr;
409}
410
411const FunctionType *
412CodeCompleteConsumer::OverloadCandidate::getFunctionType() const {
413  switch (Kind) {
414  case CK_Function:
415    return Function->getType()->getAs<FunctionType>();
416
417  case CK_FunctionTemplate:
418    return FunctionTemplate->getTemplatedDecl()->getType()
419             ->getAs<FunctionType>();
420
421  case CK_FunctionType:
422    return Type;
423  }
424
425  llvm_unreachable("Invalid CandidateKind!");
426}
427
428//===----------------------------------------------------------------------===//
429// Code completion consumer implementation
430//===----------------------------------------------------------------------===//
431
432CodeCompleteConsumer::~CodeCompleteConsumer() { }
433
434void
435PrintingCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &SemaRef,
436                                                 CodeCompletionContext Context,
437                                                 CodeCompletionResult *Results,
438                                                         unsigned NumResults) {
439  std::stable_sort(Results, Results + NumResults);
440
441  // Print the results.
442  for (unsigned I = 0; I != NumResults; ++I) {
443    OS << "COMPLETION: ";
444    switch (Results[I].Kind) {
445    case CodeCompletionResult::RK_Declaration:
446      OS << *Results[I].Declaration;
447      if (Results[I].Hidden)
448        OS << " (Hidden)";
449      if (CodeCompletionString *CCS
450            = Results[I].CreateCodeCompletionString(SemaRef, getAllocator(),
451                                                    CCTUInfo,
452                                                    includeBriefComments())) {
453        OS << " : " << CCS->getAsString();
454        if (const char *BriefComment = CCS->getBriefComment())
455          OS << " : " << BriefComment;
456      }
457
458      OS << '\n';
459      break;
460
461    case CodeCompletionResult::RK_Keyword:
462      OS << Results[I].Keyword << '\n';
463      break;
464
465    case CodeCompletionResult::RK_Macro: {
466      OS << Results[I].Macro->getName();
467      if (CodeCompletionString *CCS
468            = Results[I].CreateCodeCompletionString(SemaRef, getAllocator(),
469                                                    CCTUInfo,
470                                                    includeBriefComments())) {
471        OS << " : " << CCS->getAsString();
472      }
473      OS << '\n';
474      break;
475    }
476
477    case CodeCompletionResult::RK_Pattern: {
478      OS << "Pattern : "
479         << Results[I].Pattern->getAsString() << '\n';
480      break;
481    }
482    }
483  }
484}
485
486void
487PrintingCodeCompleteConsumer::ProcessOverloadCandidates(Sema &SemaRef,
488                                                        unsigned CurrentArg,
489                                              OverloadCandidate *Candidates,
490                                                     unsigned NumCandidates) {
491  for (unsigned I = 0; I != NumCandidates; ++I) {
492    if (CodeCompletionString *CCS
493          = Candidates[I].CreateSignatureString(CurrentArg, SemaRef,
494                                                getAllocator(), CCTUInfo)) {
495      OS << "OVERLOAD: " << CCS->getAsString() << "\n";
496    }
497  }
498}
499
500/// \brief Retrieve the effective availability of the given declaration.
501static AvailabilityResult getDeclAvailability(const Decl *D) {
502  AvailabilityResult AR = D->getAvailability();
503  if (isa<EnumConstantDecl>(D))
504    AR = std::max(AR, cast<Decl>(D->getDeclContext())->getAvailability());
505  return AR;
506}
507
508void CodeCompletionResult::computeCursorKindAndAvailability(bool Accessible) {
509  switch (Kind) {
510  case RK_Pattern:
511    if (!Declaration) {
512      // Do nothing: Patterns can come with cursor kinds!
513      break;
514    }
515    // Fall through
516
517  case RK_Declaration: {
518    // Set the availability based on attributes.
519    switch (getDeclAvailability(Declaration)) {
520    case AR_Available:
521    case AR_NotYetIntroduced:
522      Availability = CXAvailability_Available;
523      break;
524
525    case AR_Deprecated:
526      Availability = CXAvailability_Deprecated;
527      break;
528
529    case AR_Unavailable:
530      Availability = CXAvailability_NotAvailable;
531      break;
532    }
533
534    if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Declaration))
535      if (Function->isDeleted())
536        Availability = CXAvailability_NotAvailable;
537
538    CursorKind = getCursorKindForDecl(Declaration);
539    if (CursorKind == CXCursor_UnexposedDecl) {
540      // FIXME: Forward declarations of Objective-C classes and protocols
541      // are not directly exposed, but we want code completion to treat them
542      // like a definition.
543      if (isa<ObjCInterfaceDecl>(Declaration))
544        CursorKind = CXCursor_ObjCInterfaceDecl;
545      else if (isa<ObjCProtocolDecl>(Declaration))
546        CursorKind = CXCursor_ObjCProtocolDecl;
547      else
548        CursorKind = CXCursor_NotImplemented;
549    }
550    break;
551  }
552
553  case RK_Macro:
554  case RK_Keyword:
555    llvm_unreachable("Macro and keyword kinds are handled by the constructors");
556  }
557
558  if (!Accessible)
559    Availability = CXAvailability_NotAccessible;
560}
561
562/// \brief Retrieve the name that should be used to order a result.
563///
564/// If the name needs to be constructed as a string, that string will be
565/// saved into Saved and the returned StringRef will refer to it.
566static StringRef getOrderedName(const CodeCompletionResult &R,
567                                    std::string &Saved) {
568  switch (R.Kind) {
569    case CodeCompletionResult::RK_Keyword:
570      return R.Keyword;
571
572    case CodeCompletionResult::RK_Pattern:
573      return R.Pattern->getTypedText();
574
575    case CodeCompletionResult::RK_Macro:
576      return R.Macro->getName();
577
578    case CodeCompletionResult::RK_Declaration:
579      // Handle declarations below.
580      break;
581  }
582
583  DeclarationName Name = R.Declaration->getDeclName();
584
585  // If the name is a simple identifier (by far the common case), or a
586  // zero-argument selector, just return a reference to that identifier.
587  if (IdentifierInfo *Id = Name.getAsIdentifierInfo())
588    return Id->getName();
589  if (Name.isObjCZeroArgSelector())
590    if (IdentifierInfo *Id
591        = Name.getObjCSelector().getIdentifierInfoForSlot(0))
592      return Id->getName();
593
594  Saved = Name.getAsString();
595  return Saved;
596}
597
598bool clang::operator<(const CodeCompletionResult &X,
599                      const CodeCompletionResult &Y) {
600  std::string XSaved, YSaved;
601  StringRef XStr = getOrderedName(X, XSaved);
602  StringRef YStr = getOrderedName(Y, YSaved);
603  int cmp = XStr.compare_lower(YStr);
604  if (cmp)
605    return cmp < 0;
606
607  // If case-insensitive comparison fails, try case-sensitive comparison.
608  cmp = XStr.compare(YStr);
609  if (cmp)
610    return cmp < 0;
611
612  return false;
613}
614