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/SmallString.h"
22#include "llvm/ADT/STLExtras.h"
23#include "llvm/ADT/Twine.h"
24#include "llvm/Support/raw_ostream.h"
25#include <algorithm>
26#include <cstring>
27#include <functional>
28
29using namespace clang;
30
31//===----------------------------------------------------------------------===//
32// Code completion context implementation
33//===----------------------------------------------------------------------===//
34
35bool CodeCompletionContext::wantConstructorResults() const {
36  switch (Kind) {
37  case CCC_Recovery:
38  case CCC_Statement:
39  case CCC_Expression:
40  case CCC_ObjCMessageReceiver:
41  case CCC_ParenthesizedExpression:
42    return true;
43
44  case CCC_TopLevel:
45  case CCC_ObjCInterface:
46  case CCC_ObjCImplementation:
47  case CCC_ObjCIvarList:
48  case CCC_ClassStructUnion:
49  case CCC_DotMemberAccess:
50  case CCC_ArrowMemberAccess:
51  case CCC_ObjCPropertyAccess:
52  case CCC_EnumTag:
53  case CCC_UnionTag:
54  case CCC_ClassOrStructTag:
55  case CCC_ObjCProtocolName:
56  case CCC_Namespace:
57  case CCC_Type:
58  case CCC_Name:
59  case CCC_PotentiallyQualifiedName:
60  case CCC_MacroName:
61  case CCC_MacroNameUse:
62  case CCC_PreprocessorExpression:
63  case CCC_PreprocessorDirective:
64  case CCC_NaturalLanguage:
65  case CCC_SelectorName:
66  case CCC_TypeQualifiers:
67  case CCC_Other:
68  case CCC_OtherWithMacros:
69  case CCC_ObjCInstanceMessage:
70  case CCC_ObjCClassMessage:
71  case CCC_ObjCInterfaceName:
72  case CCC_ObjCCategoryName:
73    return false;
74  }
75
76  llvm_unreachable("Invalid CodeCompletionContext::Kind!");
77}
78
79//===----------------------------------------------------------------------===//
80// Code completion string implementation
81//===----------------------------------------------------------------------===//
82CodeCompletionString::Chunk::Chunk(ChunkKind Kind, const char *Text)
83  : Kind(Kind), Text("")
84{
85  switch (Kind) {
86  case CK_TypedText:
87  case CK_Text:
88  case CK_Placeholder:
89  case CK_Informative:
90  case CK_ResultType:
91  case CK_CurrentParameter:
92    this->Text = Text;
93    break;
94
95  case CK_Optional:
96    llvm_unreachable("Optional strings cannot be created from text");
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                                           CXCursorKind ParentKind,
197                                           StringRef ParentName,
198                                           const char *BriefComment)
199  : NumChunks(NumChunks), NumAnnotations(NumAnnotations),
200    Priority(Priority), Availability(Availability), ParentKind(ParentKind),
201    ParentName(ParentName), BriefComment(BriefComment)
202{
203  assert(NumChunks <= 0xffff);
204  assert(NumAnnotations <= 0xffff);
205
206  Chunk *StoredChunks = reinterpret_cast<Chunk *>(this + 1);
207  for (unsigned I = 0; I != NumChunks; ++I)
208    StoredChunks[I] = Chunks[I];
209
210  const char **StoredAnnotations = reinterpret_cast<const char **>(StoredChunks + NumChunks);
211  for (unsigned I = 0; I != NumAnnotations; ++I)
212    StoredAnnotations[I] = Annotations[I];
213}
214
215unsigned CodeCompletionString::getAnnotationCount() const {
216  return NumAnnotations;
217}
218
219const char *CodeCompletionString::getAnnotation(unsigned AnnotationNr) const {
220  if (AnnotationNr < NumAnnotations)
221    return reinterpret_cast<const char * const*>(end())[AnnotationNr];
222  else
223    return 0;
224}
225
226
227std::string CodeCompletionString::getAsString() const {
228  std::string Result;
229  llvm::raw_string_ostream OS(Result);
230
231  for (iterator C = begin(), CEnd = end(); C != CEnd; ++C) {
232    switch (C->Kind) {
233    case CK_Optional: OS << "{#" << C->Optional->getAsString() << "#}"; break;
234    case CK_Placeholder: OS << "<#" << C->Text << "#>"; break;
235
236    case CK_Informative:
237    case CK_ResultType:
238      OS << "[#" << C->Text << "#]";
239      break;
240
241    case CK_CurrentParameter: OS << "<#" << C->Text << "#>"; break;
242    default: OS << C->Text; break;
243    }
244  }
245  return OS.str();
246}
247
248const char *CodeCompletionString::getTypedText() const {
249  for (iterator C = begin(), CEnd = end(); C != CEnd; ++C)
250    if (C->Kind == CK_TypedText)
251      return C->Text;
252
253  return 0;
254}
255
256const char *CodeCompletionAllocator::CopyString(StringRef String) {
257  char *Mem = (char *)Allocate(String.size() + 1, 1);
258  std::copy(String.begin(), String.end(), Mem);
259  Mem[String.size()] = 0;
260  return Mem;
261}
262
263const char *CodeCompletionAllocator::CopyString(Twine String) {
264  // FIXME: It would be more efficient to teach Twine to tell us its size and
265  // then add a routine there to fill in an allocated char* with the contents
266  // of the string.
267  SmallString<128> Data;
268  return CopyString(String.toStringRef(Data));
269}
270
271StringRef CodeCompletionTUInfo::getParentName(DeclContext *DC) {
272  NamedDecl *ND = dyn_cast<NamedDecl>(DC);
273  if (!ND)
274    return StringRef();
275
276  // Check whether we've already cached the parent name.
277  StringRef &CachedParentName = ParentNames[DC];
278  if (!CachedParentName.empty())
279    return CachedParentName;
280
281  // If we already processed this DeclContext and assigned empty to it, the
282  // data pointer will be non-null.
283  if (CachedParentName.data() != 0)
284    return StringRef();
285
286  // Find the interesting names.
287  llvm::SmallVector<DeclContext *, 2> Contexts;
288  while (DC && !DC->isFunctionOrMethod()) {
289    if (NamedDecl *ND = dyn_cast<NamedDecl>(DC)) {
290      if (ND->getIdentifier())
291        Contexts.push_back(DC);
292    }
293
294    DC = DC->getParent();
295  }
296
297  {
298    llvm::SmallString<128> S;
299    llvm::raw_svector_ostream OS(S);
300    bool First = true;
301    for (unsigned I = Contexts.size(); I != 0; --I) {
302      if (First)
303        First = false;
304      else {
305        OS << "::";
306      }
307
308      DeclContext *CurDC = Contexts[I-1];
309      if (ObjCCategoryImplDecl *CatImpl = dyn_cast<ObjCCategoryImplDecl>(CurDC))
310        CurDC = CatImpl->getCategoryDecl();
311
312      if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(CurDC)) {
313        ObjCInterfaceDecl *Interface = Cat->getClassInterface();
314        if (!Interface) {
315          // Assign an empty StringRef but with non-null data to distinguish
316          // between empty because we didn't process the DeclContext yet.
317          CachedParentName = StringRef((const char *)~0U, 0);
318          return StringRef();
319        }
320
321        OS << Interface->getName() << '(' << Cat->getName() << ')';
322      } else {
323        OS << cast<NamedDecl>(CurDC)->getName();
324      }
325    }
326
327    CachedParentName = AllocatorRef->CopyString(OS.str());
328  }
329
330  return CachedParentName;
331}
332
333CodeCompletionString *CodeCompletionBuilder::TakeString() {
334  void *Mem = getAllocator().Allocate(
335                  sizeof(CodeCompletionString) + sizeof(Chunk) * Chunks.size()
336                                    + sizeof(const char *) * Annotations.size(),
337                                 llvm::alignOf<CodeCompletionString>());
338  CodeCompletionString *Result
339    = new (Mem) CodeCompletionString(Chunks.data(), Chunks.size(),
340                                     Priority, Availability,
341                                     Annotations.data(), Annotations.size(),
342                                     ParentKind, ParentName, BriefComment);
343  Chunks.clear();
344  return Result;
345}
346
347void CodeCompletionBuilder::AddTypedTextChunk(const char *Text) {
348  Chunks.push_back(Chunk(CodeCompletionString::CK_TypedText, Text));
349}
350
351void CodeCompletionBuilder::AddTextChunk(const char *Text) {
352  Chunks.push_back(Chunk::CreateText(Text));
353}
354
355void CodeCompletionBuilder::AddOptionalChunk(CodeCompletionString *Optional) {
356  Chunks.push_back(Chunk::CreateOptional(Optional));
357}
358
359void CodeCompletionBuilder::AddPlaceholderChunk(const char *Placeholder) {
360  Chunks.push_back(Chunk::CreatePlaceholder(Placeholder));
361}
362
363void CodeCompletionBuilder::AddInformativeChunk(const char *Text) {
364  Chunks.push_back(Chunk::CreateInformative(Text));
365}
366
367void CodeCompletionBuilder::AddResultTypeChunk(const char *ResultType) {
368  Chunks.push_back(Chunk::CreateResultType(ResultType));
369}
370
371void
372CodeCompletionBuilder::AddCurrentParameterChunk(const char *CurrentParameter) {
373  Chunks.push_back(Chunk::CreateCurrentParameter(CurrentParameter));
374}
375
376void CodeCompletionBuilder::AddChunk(CodeCompletionString::ChunkKind CK,
377                                     const char *Text) {
378  Chunks.push_back(Chunk(CK, Text));
379}
380
381void CodeCompletionBuilder::addParentContext(DeclContext *DC) {
382  if (DC->isTranslationUnit()) {
383    ParentKind = CXCursor_TranslationUnit;
384    return;
385  }
386
387  if (DC->isFunctionOrMethod())
388    return;
389
390  NamedDecl *ND = dyn_cast<NamedDecl>(DC);
391  if (!ND)
392    return;
393
394  ParentKind = getCursorKindForDecl(ND);
395  ParentName = getCodeCompletionTUInfo().getParentName(DC);
396}
397
398void CodeCompletionBuilder::addBriefComment(StringRef Comment) {
399  BriefComment = Allocator.CopyString(Comment);
400}
401
402unsigned CodeCompletionResult::getPriorityFromDecl(NamedDecl *ND) {
403  if (!ND)
404    return CCP_Unlikely;
405
406  // Context-based decisions.
407  DeclContext *DC = ND->getDeclContext()->getRedeclContext();
408  if (DC->isFunctionOrMethod() || isa<BlockDecl>(DC)) {
409    // _cmd is relatively rare
410    if (ImplicitParamDecl *ImplicitParam = dyn_cast<ImplicitParamDecl>(ND))
411      if (ImplicitParam->getIdentifier() &&
412          ImplicitParam->getIdentifier()->isStr("_cmd"))
413        return CCP_ObjC_cmd;
414
415    return CCP_LocalDeclaration;
416  }
417  if (DC->isRecord() || isa<ObjCContainerDecl>(DC))
418    return CCP_MemberDeclaration;
419
420  // Content-based decisions.
421  if (isa<EnumConstantDecl>(ND))
422    return CCP_Constant;
423  if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
424    return CCP_Type;
425
426  return CCP_Declaration;
427}
428
429//===----------------------------------------------------------------------===//
430// Code completion overload candidate implementation
431//===----------------------------------------------------------------------===//
432FunctionDecl *
433CodeCompleteConsumer::OverloadCandidate::getFunction() const {
434  if (getKind() == CK_Function)
435    return Function;
436  else if (getKind() == CK_FunctionTemplate)
437    return FunctionTemplate->getTemplatedDecl();
438  else
439    return 0;
440}
441
442const FunctionType *
443CodeCompleteConsumer::OverloadCandidate::getFunctionType() const {
444  switch (Kind) {
445  case CK_Function:
446    return Function->getType()->getAs<FunctionType>();
447
448  case CK_FunctionTemplate:
449    return FunctionTemplate->getTemplatedDecl()->getType()
450             ->getAs<FunctionType>();
451
452  case CK_FunctionType:
453    return Type;
454  }
455
456  llvm_unreachable("Invalid CandidateKind!");
457}
458
459//===----------------------------------------------------------------------===//
460// Code completion consumer implementation
461//===----------------------------------------------------------------------===//
462
463CodeCompleteConsumer::~CodeCompleteConsumer() { }
464
465void
466PrintingCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &SemaRef,
467                                                 CodeCompletionContext Context,
468                                                 CodeCompletionResult *Results,
469                                                         unsigned NumResults) {
470  std::stable_sort(Results, Results + NumResults);
471
472  // Print the results.
473  for (unsigned I = 0; I != NumResults; ++I) {
474    OS << "COMPLETION: ";
475    switch (Results[I].Kind) {
476    case CodeCompletionResult::RK_Declaration:
477      OS << *Results[I].Declaration;
478      if (Results[I].Hidden)
479        OS << " (Hidden)";
480      if (CodeCompletionString *CCS
481            = Results[I].CreateCodeCompletionString(SemaRef, getAllocator(),
482                                                    CCTUInfo,
483                                                    includeBriefComments())) {
484        OS << " : " << CCS->getAsString();
485        if (const char *BriefComment = CCS->getBriefComment())
486          OS << " : " << BriefComment;
487      }
488
489      OS << '\n';
490      break;
491
492    case CodeCompletionResult::RK_Keyword:
493      OS << Results[I].Keyword << '\n';
494      break;
495
496    case CodeCompletionResult::RK_Macro: {
497      OS << Results[I].Macro->getName();
498      if (CodeCompletionString *CCS
499            = Results[I].CreateCodeCompletionString(SemaRef, getAllocator(),
500                                                    CCTUInfo,
501                                                    includeBriefComments())) {
502        OS << " : " << CCS->getAsString();
503      }
504      OS << '\n';
505      break;
506    }
507
508    case CodeCompletionResult::RK_Pattern: {
509      OS << "Pattern : "
510         << Results[I].Pattern->getAsString() << '\n';
511      break;
512    }
513    }
514  }
515}
516
517void
518PrintingCodeCompleteConsumer::ProcessOverloadCandidates(Sema &SemaRef,
519                                                        unsigned CurrentArg,
520                                              OverloadCandidate *Candidates,
521                                                     unsigned NumCandidates) {
522  for (unsigned I = 0; I != NumCandidates; ++I) {
523    if (CodeCompletionString *CCS
524          = Candidates[I].CreateSignatureString(CurrentArg, SemaRef,
525                                                getAllocator(), CCTUInfo)) {
526      OS << "OVERLOAD: " << CCS->getAsString() << "\n";
527    }
528  }
529}
530
531/// \brief Retrieve the effective availability of the given declaration.
532static AvailabilityResult getDeclAvailability(Decl *D) {
533  AvailabilityResult AR = D->getAvailability();
534  if (isa<EnumConstantDecl>(D))
535    AR = std::max(AR, cast<Decl>(D->getDeclContext())->getAvailability());
536  return AR;
537}
538
539void CodeCompletionResult::computeCursorKindAndAvailability(bool Accessible) {
540  switch (Kind) {
541  case RK_Pattern:
542    if (!Declaration) {
543      // Do nothing: Patterns can come with cursor kinds!
544      break;
545    }
546    // Fall through
547
548  case RK_Declaration: {
549    // Set the availability based on attributes.
550    switch (getDeclAvailability(Declaration)) {
551    case AR_Available:
552    case AR_NotYetIntroduced:
553      Availability = CXAvailability_Available;
554      break;
555
556    case AR_Deprecated:
557      Availability = CXAvailability_Deprecated;
558      break;
559
560    case AR_Unavailable:
561      Availability = CXAvailability_NotAvailable;
562      break;
563    }
564
565    if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Declaration))
566      if (Function->isDeleted())
567        Availability = CXAvailability_NotAvailable;
568
569    CursorKind = getCursorKindForDecl(Declaration);
570    if (CursorKind == CXCursor_UnexposedDecl) {
571      // FIXME: Forward declarations of Objective-C classes and protocols
572      // are not directly exposed, but we want code completion to treat them
573      // like a definition.
574      if (isa<ObjCInterfaceDecl>(Declaration))
575        CursorKind = CXCursor_ObjCInterfaceDecl;
576      else if (isa<ObjCProtocolDecl>(Declaration))
577        CursorKind = CXCursor_ObjCProtocolDecl;
578      else
579        CursorKind = CXCursor_NotImplemented;
580    }
581    break;
582  }
583
584  case RK_Macro:
585  case RK_Keyword:
586    llvm_unreachable("Macro and keyword kinds are handled by the constructors");
587  }
588
589  if (!Accessible)
590    Availability = CXAvailability_NotAccessible;
591}
592
593/// \brief Retrieve the name that should be used to order a result.
594///
595/// If the name needs to be constructed as a string, that string will be
596/// saved into Saved and the returned StringRef will refer to it.
597static StringRef getOrderedName(const CodeCompletionResult &R,
598                                    std::string &Saved) {
599  switch (R.Kind) {
600    case CodeCompletionResult::RK_Keyword:
601      return R.Keyword;
602
603    case CodeCompletionResult::RK_Pattern:
604      return R.Pattern->getTypedText();
605
606    case CodeCompletionResult::RK_Macro:
607      return R.Macro->getName();
608
609    case CodeCompletionResult::RK_Declaration:
610      // Handle declarations below.
611      break;
612  }
613
614  DeclarationName Name = R.Declaration->getDeclName();
615
616  // If the name is a simple identifier (by far the common case), or a
617  // zero-argument selector, just return a reference to that identifier.
618  if (IdentifierInfo *Id = Name.getAsIdentifierInfo())
619    return Id->getName();
620  if (Name.isObjCZeroArgSelector())
621    if (IdentifierInfo *Id
622        = Name.getObjCSelector().getIdentifierInfoForSlot(0))
623      return Id->getName();
624
625  Saved = Name.getAsString();
626  return Saved;
627}
628
629bool clang::operator<(const CodeCompletionResult &X,
630                      const CodeCompletionResult &Y) {
631  std::string XSaved, YSaved;
632  StringRef XStr = getOrderedName(X, XSaved);
633  StringRef YStr = getOrderedName(Y, YSaved);
634  int cmp = XStr.compare_lower(YStr);
635  if (cmp)
636    return cmp < 0;
637
638  // If case-insensitive comparison fails, try case-sensitive comparison.
639  cmp = XStr.compare(YStr);
640  if (cmp)
641    return cmp < 0;
642
643  return false;
644}
645