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