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