xref: /freebsd/contrib/llvm-project/clang/lib/Sema/CodeCompleteConsumer.cpp (revision f126890ac5386406dadf7c4cfa9566cbb56537c5)
1 //===- CodeCompleteConsumer.cpp - Code Completion Interface ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements the CodeCompleteConsumer class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/Sema/CodeCompleteConsumer.h"
14 #include "clang-c/Index.h"
15 #include "clang/AST/Decl.h"
16 #include "clang/AST/DeclBase.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/DeclarationName.h"
20 #include "clang/AST/Type.h"
21 #include "clang/Basic/IdentifierTable.h"
22 #include "clang/Lex/Preprocessor.h"
23 #include "clang/Sema/Sema.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/Support/Casting.h"
30 #include "llvm/Support/Compiler.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/FormatVariadic.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include <algorithm>
35 #include <cassert>
36 #include <cstdint>
37 #include <string>
38 
39 using namespace clang;
40 
41 //===----------------------------------------------------------------------===//
42 // Code completion context implementation
43 //===----------------------------------------------------------------------===//
44 
45 bool CodeCompletionContext::wantConstructorResults() const {
46   switch (CCKind) {
47   case CCC_Recovery:
48   case CCC_Statement:
49   case CCC_Expression:
50   case CCC_ObjCMessageReceiver:
51   case CCC_ParenthesizedExpression:
52   case CCC_Symbol:
53   case CCC_SymbolOrNewName:
54     return true;
55 
56   case CCC_TopLevel:
57   case CCC_ObjCInterface:
58   case CCC_ObjCImplementation:
59   case CCC_ObjCIvarList:
60   case CCC_ClassStructUnion:
61   case CCC_DotMemberAccess:
62   case CCC_ArrowMemberAccess:
63   case CCC_ObjCPropertyAccess:
64   case CCC_EnumTag:
65   case CCC_UnionTag:
66   case CCC_ClassOrStructTag:
67   case CCC_ObjCProtocolName:
68   case CCC_Namespace:
69   case CCC_Type:
70   case CCC_NewName:
71   case CCC_MacroName:
72   case CCC_MacroNameUse:
73   case CCC_PreprocessorExpression:
74   case CCC_PreprocessorDirective:
75   case CCC_NaturalLanguage:
76   case CCC_SelectorName:
77   case CCC_TypeQualifiers:
78   case CCC_Other:
79   case CCC_OtherWithMacros:
80   case CCC_ObjCInstanceMessage:
81   case CCC_ObjCClassMessage:
82   case CCC_ObjCInterfaceName:
83   case CCC_ObjCCategoryName:
84   case CCC_IncludedFile:
85   case CCC_Attribute:
86   case CCC_ObjCClassForwardDecl:
87     return false;
88   }
89 
90   llvm_unreachable("Invalid CodeCompletionContext::Kind!");
91 }
92 
93 StringRef clang::getCompletionKindString(CodeCompletionContext::Kind Kind) {
94   using CCKind = CodeCompletionContext::Kind;
95   switch (Kind) {
96   case CCKind::CCC_Other:
97     return "Other";
98   case CCKind::CCC_OtherWithMacros:
99     return "OtherWithMacros";
100   case CCKind::CCC_TopLevel:
101     return "TopLevel";
102   case CCKind::CCC_ObjCInterface:
103     return "ObjCInterface";
104   case CCKind::CCC_ObjCImplementation:
105     return "ObjCImplementation";
106   case CCKind::CCC_ObjCIvarList:
107     return "ObjCIvarList";
108   case CCKind::CCC_ClassStructUnion:
109     return "ClassStructUnion";
110   case CCKind::CCC_Statement:
111     return "Statement";
112   case CCKind::CCC_Expression:
113     return "Expression";
114   case CCKind::CCC_ObjCMessageReceiver:
115     return "ObjCMessageReceiver";
116   case CCKind::CCC_DotMemberAccess:
117     return "DotMemberAccess";
118   case CCKind::CCC_ArrowMemberAccess:
119     return "ArrowMemberAccess";
120   case CCKind::CCC_ObjCPropertyAccess:
121     return "ObjCPropertyAccess";
122   case CCKind::CCC_EnumTag:
123     return "EnumTag";
124   case CCKind::CCC_UnionTag:
125     return "UnionTag";
126   case CCKind::CCC_ClassOrStructTag:
127     return "ClassOrStructTag";
128   case CCKind::CCC_ObjCProtocolName:
129     return "ObjCProtocolName";
130   case CCKind::CCC_Namespace:
131     return "Namespace";
132   case CCKind::CCC_Type:
133     return "Type";
134   case CCKind::CCC_NewName:
135     return "NewName";
136   case CCKind::CCC_Symbol:
137     return "Symbol";
138   case CCKind::CCC_SymbolOrNewName:
139     return "SymbolOrNewName";
140   case CCKind::CCC_MacroName:
141     return "MacroName";
142   case CCKind::CCC_MacroNameUse:
143     return "MacroNameUse";
144   case CCKind::CCC_PreprocessorExpression:
145     return "PreprocessorExpression";
146   case CCKind::CCC_PreprocessorDirective:
147     return "PreprocessorDirective";
148   case CCKind::CCC_NaturalLanguage:
149     return "NaturalLanguage";
150   case CCKind::CCC_SelectorName:
151     return "SelectorName";
152   case CCKind::CCC_TypeQualifiers:
153     return "TypeQualifiers";
154   case CCKind::CCC_ParenthesizedExpression:
155     return "ParenthesizedExpression";
156   case CCKind::CCC_ObjCInstanceMessage:
157     return "ObjCInstanceMessage";
158   case CCKind::CCC_ObjCClassMessage:
159     return "ObjCClassMessage";
160   case CCKind::CCC_ObjCInterfaceName:
161     return "ObjCInterfaceName";
162   case CCKind::CCC_ObjCCategoryName:
163     return "ObjCCategoryName";
164   case CCKind::CCC_IncludedFile:
165     return "IncludedFile";
166   case CCKind::CCC_Attribute:
167     return "Attribute";
168   case CCKind::CCC_Recovery:
169     return "Recovery";
170   case CCKind::CCC_ObjCClassForwardDecl:
171     return "ObjCClassForwardDecl";
172   }
173   llvm_unreachable("Invalid CodeCompletionContext::Kind!");
174 }
175 
176 //===----------------------------------------------------------------------===//
177 // Code completion string implementation
178 //===----------------------------------------------------------------------===//
179 
180 CodeCompletionString::Chunk::Chunk(ChunkKind Kind, const char *Text)
181     : Kind(Kind), Text("") {
182   switch (Kind) {
183   case CK_TypedText:
184   case CK_Text:
185   case CK_Placeholder:
186   case CK_Informative:
187   case CK_ResultType:
188   case CK_CurrentParameter:
189     this->Text = Text;
190     break;
191 
192   case CK_Optional:
193     llvm_unreachable("Optional strings cannot be created from text");
194 
195   case CK_LeftParen:
196     this->Text = "(";
197     break;
198 
199   case CK_RightParen:
200     this->Text = ")";
201     break;
202 
203   case CK_LeftBracket:
204     this->Text = "[";
205     break;
206 
207   case CK_RightBracket:
208     this->Text = "]";
209     break;
210 
211   case CK_LeftBrace:
212     this->Text = "{";
213     break;
214 
215   case CK_RightBrace:
216     this->Text = "}";
217     break;
218 
219   case CK_LeftAngle:
220     this->Text = "<";
221     break;
222 
223   case CK_RightAngle:
224     this->Text = ">";
225     break;
226 
227   case CK_Comma:
228     this->Text = ", ";
229     break;
230 
231   case CK_Colon:
232     this->Text = ":";
233     break;
234 
235   case CK_SemiColon:
236     this->Text = ";";
237     break;
238 
239   case CK_Equal:
240     this->Text = " = ";
241     break;
242 
243   case CK_HorizontalSpace:
244     this->Text = " ";
245     break;
246 
247   case CK_VerticalSpace:
248     this->Text = "\n";
249     break;
250   }
251 }
252 
253 CodeCompletionString::Chunk
254 CodeCompletionString::Chunk::CreateText(const char *Text) {
255   return Chunk(CK_Text, Text);
256 }
257 
258 CodeCompletionString::Chunk
259 CodeCompletionString::Chunk::CreateOptional(CodeCompletionString *Optional) {
260   Chunk Result;
261   Result.Kind = CK_Optional;
262   Result.Optional = Optional;
263   return Result;
264 }
265 
266 CodeCompletionString::Chunk
267 CodeCompletionString::Chunk::CreatePlaceholder(const char *Placeholder) {
268   return Chunk(CK_Placeholder, Placeholder);
269 }
270 
271 CodeCompletionString::Chunk
272 CodeCompletionString::Chunk::CreateInformative(const char *Informative) {
273   return Chunk(CK_Informative, Informative);
274 }
275 
276 CodeCompletionString::Chunk
277 CodeCompletionString::Chunk::CreateResultType(const char *ResultType) {
278   return Chunk(CK_ResultType, ResultType);
279 }
280 
281 CodeCompletionString::Chunk CodeCompletionString::Chunk::CreateCurrentParameter(
282     const char *CurrentParameter) {
283   return Chunk(CK_CurrentParameter, CurrentParameter);
284 }
285 
286 CodeCompletionString::CodeCompletionString(
287     const Chunk *Chunks, unsigned NumChunks, unsigned Priority,
288     CXAvailabilityKind Availability, const char **Annotations,
289     unsigned NumAnnotations, StringRef ParentName, const char *BriefComment)
290     : NumChunks(NumChunks), NumAnnotations(NumAnnotations), Priority(Priority),
291       Availability(Availability), ParentName(ParentName),
292       BriefComment(BriefComment) {
293   assert(NumChunks <= 0xffff);
294   assert(NumAnnotations <= 0xffff);
295 
296   Chunk *StoredChunks = reinterpret_cast<Chunk *>(this + 1);
297   for (unsigned I = 0; I != NumChunks; ++I)
298     StoredChunks[I] = Chunks[I];
299 
300   const char **StoredAnnotations =
301       reinterpret_cast<const char **>(StoredChunks + NumChunks);
302   for (unsigned I = 0; I != NumAnnotations; ++I)
303     StoredAnnotations[I] = Annotations[I];
304 }
305 
306 unsigned CodeCompletionString::getAnnotationCount() const {
307   return NumAnnotations;
308 }
309 
310 const char *CodeCompletionString::getAnnotation(unsigned AnnotationNr) const {
311   if (AnnotationNr < NumAnnotations)
312     return reinterpret_cast<const char *const *>(end())[AnnotationNr];
313   else
314     return nullptr;
315 }
316 
317 std::string CodeCompletionString::getAsString() const {
318   std::string Result;
319   llvm::raw_string_ostream OS(Result);
320 
321   for (const Chunk &C : *this) {
322     switch (C.Kind) {
323     case CK_Optional:
324       OS << "{#" << C.Optional->getAsString() << "#}";
325       break;
326     case CK_Placeholder:
327       OS << "<#" << C.Text << "#>";
328       break;
329     case CK_Informative:
330     case CK_ResultType:
331       OS << "[#" << C.Text << "#]";
332       break;
333     case CK_CurrentParameter:
334       OS << "<#" << C.Text << "#>";
335       break;
336     default:
337       OS << C.Text;
338       break;
339     }
340   }
341   return Result;
342 }
343 
344 const char *CodeCompletionString::getTypedText() const {
345   for (const Chunk &C : *this)
346     if (C.Kind == CK_TypedText)
347       return C.Text;
348 
349   return nullptr;
350 }
351 
352 std::string CodeCompletionString::getAllTypedText() const {
353   std::string Res;
354   for (const Chunk &C : *this)
355     if (C.Kind == CK_TypedText)
356       Res += C.Text;
357 
358   return Res;
359 }
360 
361 const char *CodeCompletionAllocator::CopyString(const Twine &String) {
362   SmallString<128> Data;
363   StringRef Ref = String.toStringRef(Data);
364   // FIXME: It would be more efficient to teach Twine to tell us its size and
365   // then add a routine there to fill in an allocated char* with the contents
366   // of the string.
367   char *Mem = (char *)Allocate(Ref.size() + 1, 1);
368   std::copy(Ref.begin(), Ref.end(), Mem);
369   Mem[Ref.size()] = 0;
370   return Mem;
371 }
372 
373 StringRef CodeCompletionTUInfo::getParentName(const DeclContext *DC) {
374   if (!isa<NamedDecl>(DC))
375     return {};
376 
377   // Check whether we've already cached the parent name.
378   StringRef &CachedParentName = ParentNames[DC];
379   if (!CachedParentName.empty())
380     return CachedParentName;
381 
382   // If we already processed this DeclContext and assigned empty to it, the
383   // data pointer will be non-null.
384   if (CachedParentName.data() != nullptr)
385     return {};
386 
387   // Find the interesting names.
388   SmallVector<const DeclContext *, 2> Contexts;
389   while (DC && !DC->isFunctionOrMethod()) {
390     if (const auto *ND = dyn_cast<NamedDecl>(DC)) {
391       if (ND->getIdentifier())
392         Contexts.push_back(DC);
393     }
394 
395     DC = DC->getParent();
396   }
397 
398   {
399     SmallString<128> S;
400     llvm::raw_svector_ostream OS(S);
401     bool First = true;
402     for (const DeclContext *CurDC : llvm::reverse(Contexts)) {
403       if (First)
404         First = false;
405       else {
406         OS << "::";
407       }
408 
409       if (const auto *CatImpl = dyn_cast<ObjCCategoryImplDecl>(CurDC))
410         CurDC = CatImpl->getCategoryDecl();
411 
412       if (const auto *Cat = dyn_cast<ObjCCategoryDecl>(CurDC)) {
413         const ObjCInterfaceDecl *Interface = Cat->getClassInterface();
414         if (!Interface) {
415           // Assign an empty StringRef but with non-null data to distinguish
416           // between empty because we didn't process the DeclContext yet.
417           CachedParentName = StringRef((const char *)(uintptr_t)~0U, 0);
418           return {};
419         }
420 
421         OS << Interface->getName() << '(' << Cat->getName() << ')';
422       } else {
423         OS << cast<NamedDecl>(CurDC)->getName();
424       }
425     }
426 
427     CachedParentName = AllocatorRef->CopyString(OS.str());
428   }
429 
430   return CachedParentName;
431 }
432 
433 CodeCompletionString *CodeCompletionBuilder::TakeString() {
434   void *Mem = getAllocator().Allocate(
435       sizeof(CodeCompletionString) + sizeof(Chunk) * Chunks.size() +
436           sizeof(const char *) * Annotations.size(),
437       alignof(CodeCompletionString));
438   CodeCompletionString *Result = new (Mem) CodeCompletionString(
439       Chunks.data(), Chunks.size(), Priority, Availability, Annotations.data(),
440       Annotations.size(), ParentName, BriefComment);
441   Chunks.clear();
442   return Result;
443 }
444 
445 void CodeCompletionBuilder::AddTypedTextChunk(const char *Text) {
446   Chunks.push_back(Chunk(CodeCompletionString::CK_TypedText, Text));
447 }
448 
449 void CodeCompletionBuilder::AddTextChunk(const char *Text) {
450   Chunks.push_back(Chunk::CreateText(Text));
451 }
452 
453 void CodeCompletionBuilder::AddOptionalChunk(CodeCompletionString *Optional) {
454   Chunks.push_back(Chunk::CreateOptional(Optional));
455 }
456 
457 void CodeCompletionBuilder::AddPlaceholderChunk(const char *Placeholder) {
458   Chunks.push_back(Chunk::CreatePlaceholder(Placeholder));
459 }
460 
461 void CodeCompletionBuilder::AddInformativeChunk(const char *Text) {
462   Chunks.push_back(Chunk::CreateInformative(Text));
463 }
464 
465 void CodeCompletionBuilder::AddResultTypeChunk(const char *ResultType) {
466   Chunks.push_back(Chunk::CreateResultType(ResultType));
467 }
468 
469 void CodeCompletionBuilder::AddCurrentParameterChunk(
470     const char *CurrentParameter) {
471   Chunks.push_back(Chunk::CreateCurrentParameter(CurrentParameter));
472 }
473 
474 void CodeCompletionBuilder::AddChunk(CodeCompletionString::ChunkKind CK,
475                                      const char *Text) {
476   Chunks.push_back(Chunk(CK, Text));
477 }
478 
479 void CodeCompletionBuilder::addParentContext(const DeclContext *DC) {
480   if (DC->isTranslationUnit())
481     return;
482 
483   if (DC->isFunctionOrMethod())
484     return;
485 
486   if (!isa<NamedDecl>(DC))
487     return;
488 
489   ParentName = getCodeCompletionTUInfo().getParentName(DC);
490 }
491 
492 void CodeCompletionBuilder::addBriefComment(StringRef Comment) {
493   BriefComment = Allocator.CopyString(Comment);
494 }
495 
496 //===----------------------------------------------------------------------===//
497 // Code completion overload candidate implementation
498 //===----------------------------------------------------------------------===//
499 FunctionDecl *CodeCompleteConsumer::OverloadCandidate::getFunction() const {
500   if (getKind() == CK_Function)
501     return Function;
502   else if (getKind() == CK_FunctionTemplate)
503     return FunctionTemplate->getTemplatedDecl();
504   else
505     return nullptr;
506 }
507 
508 const FunctionType *
509 CodeCompleteConsumer::OverloadCandidate::getFunctionType() const {
510   switch (Kind) {
511   case CK_Function:
512     return Function->getType()->getAs<FunctionType>();
513 
514   case CK_FunctionTemplate:
515     return FunctionTemplate->getTemplatedDecl()
516         ->getType()
517         ->getAs<FunctionType>();
518 
519   case CK_FunctionType:
520     return Type;
521   case CK_FunctionProtoTypeLoc:
522     return ProtoTypeLoc.getTypePtr();
523   case CK_Template:
524   case CK_Aggregate:
525     return nullptr;
526   }
527 
528   llvm_unreachable("Invalid CandidateKind!");
529 }
530 
531 const FunctionProtoTypeLoc
532 CodeCompleteConsumer::OverloadCandidate::getFunctionProtoTypeLoc() const {
533   if (Kind == CK_FunctionProtoTypeLoc)
534     return ProtoTypeLoc;
535   return FunctionProtoTypeLoc();
536 }
537 
538 unsigned CodeCompleteConsumer::OverloadCandidate::getNumParams() const {
539   if (Kind == CK_Template)
540     return Template->getTemplateParameters()->size();
541 
542   if (Kind == CK_Aggregate) {
543     unsigned Count =
544         std::distance(AggregateType->field_begin(), AggregateType->field_end());
545     if (const auto *CRD = dyn_cast<CXXRecordDecl>(AggregateType))
546       Count += CRD->getNumBases();
547     return Count;
548   }
549 
550   if (const auto *FT = getFunctionType())
551     if (const auto *FPT = dyn_cast<FunctionProtoType>(FT))
552       return FPT->getNumParams();
553 
554   return 0;
555 }
556 
557 QualType
558 CodeCompleteConsumer::OverloadCandidate::getParamType(unsigned N) const {
559   if (Kind == CK_Aggregate) {
560     if (const auto *CRD = dyn_cast<CXXRecordDecl>(AggregateType)) {
561       if (N < CRD->getNumBases())
562         return std::next(CRD->bases_begin(), N)->getType();
563       N -= CRD->getNumBases();
564     }
565     for (const auto *Field : AggregateType->fields())
566       if (N-- == 0)
567         return Field->getType();
568     return QualType();
569   }
570 
571   if (Kind == CK_Template) {
572     TemplateParameterList *TPL = getTemplate()->getTemplateParameters();
573     if (N < TPL->size())
574       if (const auto *D = dyn_cast<NonTypeTemplateParmDecl>(TPL->getParam(N)))
575         return D->getType();
576     return QualType();
577   }
578 
579   if (const auto *FT = getFunctionType())
580     if (const auto *FPT = dyn_cast<FunctionProtoType>(FT))
581       if (N < FPT->getNumParams())
582         return FPT->getParamType(N);
583   return QualType();
584 }
585 
586 const NamedDecl *
587 CodeCompleteConsumer::OverloadCandidate::getParamDecl(unsigned N) const {
588   if (Kind == CK_Aggregate) {
589     if (const auto *CRD = dyn_cast<CXXRecordDecl>(AggregateType)) {
590       if (N < CRD->getNumBases())
591         return std::next(CRD->bases_begin(), N)->getType()->getAsTagDecl();
592       N -= CRD->getNumBases();
593     }
594     for (const auto *Field : AggregateType->fields())
595       if (N-- == 0)
596         return Field;
597     return nullptr;
598   }
599 
600   if (Kind == CK_Template) {
601     TemplateParameterList *TPL = getTemplate()->getTemplateParameters();
602     if (N < TPL->size())
603       return TPL->getParam(N);
604     return nullptr;
605   }
606 
607   // Note that if we only have a FunctionProtoType, we don't have param decls.
608   if (const auto *FD = getFunction()) {
609     if (N < FD->param_size())
610       return FD->getParamDecl(N);
611   } else if (Kind == CK_FunctionProtoTypeLoc) {
612     if (N < ProtoTypeLoc.getNumParams()) {
613       return ProtoTypeLoc.getParam(N);
614     }
615   }
616 
617   return nullptr;
618 }
619 
620 //===----------------------------------------------------------------------===//
621 // Code completion consumer implementation
622 //===----------------------------------------------------------------------===//
623 
624 CodeCompleteConsumer::~CodeCompleteConsumer() = default;
625 
626 bool PrintingCodeCompleteConsumer::isResultFilteredOut(
627     StringRef Filter, CodeCompletionResult Result) {
628   switch (Result.Kind) {
629   case CodeCompletionResult::RK_Declaration:
630     return !(Result.Declaration->getIdentifier() &&
631              Result.Declaration->getIdentifier()->getName().startswith(Filter));
632   case CodeCompletionResult::RK_Keyword:
633     return !StringRef(Result.Keyword).startswith(Filter);
634   case CodeCompletionResult::RK_Macro:
635     return !Result.Macro->getName().startswith(Filter);
636   case CodeCompletionResult::RK_Pattern:
637     return !(Result.Pattern->getTypedText() &&
638              StringRef(Result.Pattern->getTypedText()).startswith(Filter));
639   }
640   llvm_unreachable("Unknown code completion result Kind.");
641 }
642 
643 void PrintingCodeCompleteConsumer::ProcessCodeCompleteResults(
644     Sema &SemaRef, CodeCompletionContext Context, CodeCompletionResult *Results,
645     unsigned NumResults) {
646   std::stable_sort(Results, Results + NumResults);
647 
648   if (!Context.getPreferredType().isNull())
649     OS << "PREFERRED-TYPE: " << Context.getPreferredType() << '\n';
650 
651   StringRef Filter = SemaRef.getPreprocessor().getCodeCompletionFilter();
652   // Print the completions.
653   for (unsigned I = 0; I != NumResults; ++I) {
654     if (!Filter.empty() && isResultFilteredOut(Filter, Results[I]))
655       continue;
656     OS << "COMPLETION: ";
657     switch (Results[I].Kind) {
658     case CodeCompletionResult::RK_Declaration:
659       OS << *Results[I].Declaration;
660       {
661         std::vector<std::string> Tags;
662         if (Results[I].Hidden)
663           Tags.push_back("Hidden");
664         if (Results[I].InBaseClass)
665           Tags.push_back("InBase");
666         if (Results[I].Availability ==
667             CXAvailabilityKind::CXAvailability_NotAccessible)
668           Tags.push_back("Inaccessible");
669         if (!Tags.empty())
670           OS << " (" << llvm::join(Tags, ",") << ")";
671       }
672       if (CodeCompletionString *CCS = Results[I].CreateCodeCompletionString(
673               SemaRef, Context, getAllocator(), CCTUInfo,
674               includeBriefComments())) {
675         OS << " : " << CCS->getAsString();
676         if (const char *BriefComment = CCS->getBriefComment())
677           OS << " : " << BriefComment;
678       }
679       break;
680 
681     case CodeCompletionResult::RK_Keyword:
682       OS << Results[I].Keyword;
683       break;
684 
685     case CodeCompletionResult::RK_Macro:
686       OS << Results[I].Macro->getName();
687       if (CodeCompletionString *CCS = Results[I].CreateCodeCompletionString(
688               SemaRef, Context, getAllocator(), CCTUInfo,
689               includeBriefComments())) {
690         OS << " : " << CCS->getAsString();
691       }
692       break;
693 
694     case CodeCompletionResult::RK_Pattern:
695       OS << "Pattern : " << Results[I].Pattern->getAsString();
696       break;
697     }
698     for (const FixItHint &FixIt : Results[I].FixIts) {
699       const SourceLocation BLoc = FixIt.RemoveRange.getBegin();
700       const SourceLocation ELoc = FixIt.RemoveRange.getEnd();
701 
702       SourceManager &SM = SemaRef.SourceMgr;
703       std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
704       std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
705       // Adjust for token ranges.
706       if (FixIt.RemoveRange.isTokenRange())
707         EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, SemaRef.LangOpts);
708 
709       OS << " (requires fix-it:"
710          << " {" << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
711          << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
712          << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
713          << SM.getColumnNumber(EInfo.first, EInfo.second) << "}"
714          << " to \"" << FixIt.CodeToInsert << "\")";
715     }
716     OS << '\n';
717   }
718 }
719 
720 // This function is used solely to preserve the former presentation of overloads
721 // by "clang -cc1 -code-completion-at", since CodeCompletionString::getAsString
722 // needs to be improved for printing the newer and more detailed overload
723 // chunks.
724 static std::string getOverloadAsString(const CodeCompletionString &CCS) {
725   std::string Result;
726   llvm::raw_string_ostream OS(Result);
727 
728   for (auto &C : CCS) {
729     switch (C.Kind) {
730     case CodeCompletionString::CK_Informative:
731     case CodeCompletionString::CK_ResultType:
732       OS << "[#" << C.Text << "#]";
733       break;
734 
735     case CodeCompletionString::CK_CurrentParameter:
736       OS << "<#" << C.Text << "#>";
737       break;
738 
739     // FIXME: We can also print optional parameters of an overload.
740     case CodeCompletionString::CK_Optional:
741       break;
742 
743     default:
744       OS << C.Text;
745       break;
746     }
747   }
748   return Result;
749 }
750 
751 void PrintingCodeCompleteConsumer::ProcessOverloadCandidates(
752     Sema &SemaRef, unsigned CurrentArg, OverloadCandidate *Candidates,
753     unsigned NumCandidates, SourceLocation OpenParLoc, bool Braced) {
754   OS << "OPENING_PAREN_LOC: ";
755   OpenParLoc.print(OS, SemaRef.getSourceManager());
756   OS << "\n";
757 
758   for (unsigned I = 0; I != NumCandidates; ++I) {
759     if (CodeCompletionString *CCS = Candidates[I].CreateSignatureString(
760             CurrentArg, SemaRef, getAllocator(), CCTUInfo,
761             includeBriefComments(), Braced)) {
762       OS << "OVERLOAD: " << getOverloadAsString(*CCS) << "\n";
763     }
764   }
765 }
766 
767 /// Retrieve the effective availability of the given declaration.
768 static AvailabilityResult getDeclAvailability(const Decl *D) {
769   AvailabilityResult AR = D->getAvailability();
770   if (isa<EnumConstantDecl>(D))
771     AR = std::max(AR, cast<Decl>(D->getDeclContext())->getAvailability());
772   return AR;
773 }
774 
775 void CodeCompletionResult::computeCursorKindAndAvailability(bool Accessible) {
776   switch (Kind) {
777   case RK_Pattern:
778     if (!Declaration) {
779       // Do nothing: Patterns can come with cursor kinds!
780       break;
781     }
782     [[fallthrough]];
783 
784   case RK_Declaration: {
785     // Set the availability based on attributes.
786     switch (getDeclAvailability(Declaration)) {
787     case AR_Available:
788     case AR_NotYetIntroduced:
789       Availability = CXAvailability_Available;
790       break;
791 
792     case AR_Deprecated:
793       Availability = CXAvailability_Deprecated;
794       break;
795 
796     case AR_Unavailable:
797       Availability = CXAvailability_NotAvailable;
798       break;
799     }
800 
801     if (const auto *Function = dyn_cast<FunctionDecl>(Declaration))
802       if (Function->isDeleted())
803         Availability = CXAvailability_NotAvailable;
804 
805     CursorKind = getCursorKindForDecl(Declaration);
806     if (CursorKind == CXCursor_UnexposedDecl) {
807       // FIXME: Forward declarations of Objective-C classes and protocols
808       // are not directly exposed, but we want code completion to treat them
809       // like a definition.
810       if (isa<ObjCInterfaceDecl>(Declaration))
811         CursorKind = CXCursor_ObjCInterfaceDecl;
812       else if (isa<ObjCProtocolDecl>(Declaration))
813         CursorKind = CXCursor_ObjCProtocolDecl;
814       else
815         CursorKind = CXCursor_NotImplemented;
816     }
817     break;
818   }
819 
820   case RK_Macro:
821   case RK_Keyword:
822     llvm_unreachable("Macro and keyword kinds are handled by the constructors");
823   }
824 
825   if (!Accessible)
826     Availability = CXAvailability_NotAccessible;
827 }
828 
829 /// Retrieve the name that should be used to order a result.
830 ///
831 /// If the name needs to be constructed as a string, that string will be
832 /// saved into Saved and the returned StringRef will refer to it.
833 StringRef CodeCompletionResult::getOrderedName(std::string &Saved) const {
834   switch (Kind) {
835   case RK_Keyword:
836     return Keyword;
837   case RK_Pattern:
838     return Pattern->getTypedText();
839   case RK_Macro:
840     return Macro->getName();
841   case RK_Declaration:
842     // Handle declarations below.
843     break;
844   }
845 
846   DeclarationName Name = Declaration->getDeclName();
847 
848   // If the name is a simple identifier (by far the common case), or a
849   // zero-argument selector, just return a reference to that identifier.
850   if (IdentifierInfo *Id = Name.getAsIdentifierInfo())
851     return Id->getName();
852   if (Name.isObjCZeroArgSelector())
853     if (IdentifierInfo *Id = Name.getObjCSelector().getIdentifierInfoForSlot(0))
854       return Id->getName();
855 
856   Saved = Name.getAsString();
857   return Saved;
858 }
859 
860 bool clang::operator<(const CodeCompletionResult &X,
861                       const CodeCompletionResult &Y) {
862   std::string XSaved, YSaved;
863   StringRef XStr = X.getOrderedName(XSaved);
864   StringRef YStr = Y.getOrderedName(YSaved);
865   int cmp = XStr.compare_insensitive(YStr);
866   if (cmp)
867     return cmp < 0;
868 
869   // If case-insensitive comparison fails, try case-sensitive comparison.
870   return XStr.compare(YStr) < 0;
871 }
872