xref: /llvm-project/clang/lib/Sema/SemaCodeComplete.cpp (revision deffae5da123b32098914d8346bf4358a6792bdc)
1 //===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
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 defines the code-completion semantic actions.
10 //
11 //===----------------------------------------------------------------------===//
12 #include "clang/AST/ASTConcept.h"
13 #include "clang/AST/Decl.h"
14 #include "clang/AST/DeclBase.h"
15 #include "clang/AST/DeclCXX.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ExprConcepts.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/AST/NestedNameSpecifier.h"
23 #include "clang/AST/OperationKinds.h"
24 #include "clang/AST/QualTypeNames.h"
25 #include "clang/AST/RecursiveASTVisitor.h"
26 #include "clang/AST/Type.h"
27 #include "clang/Basic/AttributeCommonInfo.h"
28 #include "clang/Basic/CharInfo.h"
29 #include "clang/Basic/OperatorKinds.h"
30 #include "clang/Basic/Specifiers.h"
31 #include "clang/Lex/HeaderSearch.h"
32 #include "clang/Lex/MacroInfo.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/CodeCompleteConsumer.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/Designator.h"
37 #include "clang/Sema/Lookup.h"
38 #include "clang/Sema/Overload.h"
39 #include "clang/Sema/ParsedAttr.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/Sema.h"
44 #include "clang/Sema/SemaInternal.h"
45 #include "llvm/ADT/ArrayRef.h"
46 #include "llvm/ADT/DenseSet.h"
47 #include "llvm/ADT/SmallBitVector.h"
48 #include "llvm/ADT/SmallPtrSet.h"
49 #include "llvm/ADT/SmallString.h"
50 #include "llvm/ADT/StringExtras.h"
51 #include "llvm/ADT/StringSwitch.h"
52 #include "llvm/ADT/Twine.h"
53 #include "llvm/ADT/iterator_range.h"
54 #include "llvm/Support/Casting.h"
55 #include "llvm/Support/Path.h"
56 #include "llvm/Support/raw_ostream.h"
57 
58 #include <list>
59 #include <map>
60 #include <optional>
61 #include <string>
62 #include <vector>
63 
64 using namespace clang;
65 using namespace sema;
66 
67 namespace {
68 /// A container of code-completion results.
69 class ResultBuilder {
70 public:
71   /// The type of a name-lookup filter, which can be provided to the
72   /// name-lookup routines to specify which declarations should be included in
73   /// the result set (when it returns true) and which declarations should be
74   /// filtered out (returns false).
75   typedef bool (ResultBuilder::*LookupFilter)(const NamedDecl *) const;
76 
77   typedef CodeCompletionResult Result;
78 
79 private:
80   /// The actual results we have found.
81   std::vector<Result> Results;
82 
83   /// A record of all of the declarations we have found and placed
84   /// into the result set, used to ensure that no declaration ever gets into
85   /// the result set twice.
86   llvm::SmallPtrSet<const Decl *, 16> AllDeclsFound;
87 
88   typedef std::pair<const NamedDecl *, unsigned> DeclIndexPair;
89 
90   /// An entry in the shadow map, which is optimized to store
91   /// a single (declaration, index) mapping (the common case) but
92   /// can also store a list of (declaration, index) mappings.
93   class ShadowMapEntry {
94     typedef SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
95 
96     /// Contains either the solitary NamedDecl * or a vector
97     /// of (declaration, index) pairs.
98     llvm::PointerUnion<const NamedDecl *, DeclIndexPairVector *> DeclOrVector;
99 
100     /// When the entry contains a single declaration, this is
101     /// the index associated with that entry.
102     unsigned SingleDeclIndex = 0;
103 
104   public:
105     ShadowMapEntry() = default;
106     ShadowMapEntry(const ShadowMapEntry &) = delete;
107     ShadowMapEntry(ShadowMapEntry &&Move) { *this = std::move(Move); }
108     ShadowMapEntry &operator=(const ShadowMapEntry &) = delete;
109     ShadowMapEntry &operator=(ShadowMapEntry &&Move) {
110       SingleDeclIndex = Move.SingleDeclIndex;
111       DeclOrVector = Move.DeclOrVector;
112       Move.DeclOrVector = nullptr;
113       return *this;
114     }
115 
116     void Add(const NamedDecl *ND, unsigned Index) {
117       if (DeclOrVector.isNull()) {
118         // 0 - > 1 elements: just set the single element information.
119         DeclOrVector = ND;
120         SingleDeclIndex = Index;
121         return;
122       }
123 
124       if (const NamedDecl *PrevND =
125               DeclOrVector.dyn_cast<const NamedDecl *>()) {
126         // 1 -> 2 elements: create the vector of results and push in the
127         // existing declaration.
128         DeclIndexPairVector *Vec = new DeclIndexPairVector;
129         Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
130         DeclOrVector = Vec;
131       }
132 
133       // Add the new element to the end of the vector.
134       DeclOrVector.get<DeclIndexPairVector *>()->push_back(
135           DeclIndexPair(ND, Index));
136     }
137 
138     ~ShadowMapEntry() {
139       if (DeclIndexPairVector *Vec =
140               DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
141         delete Vec;
142         DeclOrVector = ((NamedDecl *)nullptr);
143       }
144     }
145 
146     // Iteration.
147     class iterator;
148     iterator begin() const;
149     iterator end() const;
150   };
151 
152   /// A mapping from declaration names to the declarations that have
153   /// this name within a particular scope and their index within the list of
154   /// results.
155   typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
156 
157   /// The semantic analysis object for which results are being
158   /// produced.
159   Sema &SemaRef;
160 
161   /// The allocator used to allocate new code-completion strings.
162   CodeCompletionAllocator &Allocator;
163 
164   CodeCompletionTUInfo &CCTUInfo;
165 
166   /// If non-NULL, a filter function used to remove any code-completion
167   /// results that are not desirable.
168   LookupFilter Filter;
169 
170   /// Whether we should allow declarations as
171   /// nested-name-specifiers that would otherwise be filtered out.
172   bool AllowNestedNameSpecifiers;
173 
174   /// If set, the type that we would prefer our resulting value
175   /// declarations to have.
176   ///
177   /// Closely matching the preferred type gives a boost to a result's
178   /// priority.
179   CanQualType PreferredType;
180 
181   /// A list of shadow maps, which is used to model name hiding at
182   /// different levels of, e.g., the inheritance hierarchy.
183   std::list<ShadowMap> ShadowMaps;
184 
185   /// Overloaded C++ member functions found by SemaLookup.
186   /// Used to determine when one overload is dominated by another.
187   llvm::DenseMap<std::pair<DeclContext *, /*Name*/uintptr_t>, ShadowMapEntry>
188       OverloadMap;
189 
190   /// If we're potentially referring to a C++ member function, the set
191   /// of qualifiers applied to the object type.
192   Qualifiers ObjectTypeQualifiers;
193   /// The kind of the object expression, for rvalue/lvalue overloads.
194   ExprValueKind ObjectKind;
195 
196   /// Whether the \p ObjectTypeQualifiers field is active.
197   bool HasObjectTypeQualifiers;
198 
199   /// The selector that we prefer.
200   Selector PreferredSelector;
201 
202   /// The completion context in which we are gathering results.
203   CodeCompletionContext CompletionContext;
204 
205   /// If we are in an instance method definition, the \@implementation
206   /// object.
207   ObjCImplementationDecl *ObjCImplementation;
208 
209   void AdjustResultPriorityForDecl(Result &R);
210 
211   void MaybeAddConstructorResults(Result R);
212 
213 public:
214   explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator,
215                          CodeCompletionTUInfo &CCTUInfo,
216                          const CodeCompletionContext &CompletionContext,
217                          LookupFilter Filter = nullptr)
218       : SemaRef(SemaRef), Allocator(Allocator), CCTUInfo(CCTUInfo),
219         Filter(Filter), AllowNestedNameSpecifiers(false),
220         HasObjectTypeQualifiers(false), CompletionContext(CompletionContext),
221         ObjCImplementation(nullptr) {
222     // If this is an Objective-C instance method definition, dig out the
223     // corresponding implementation.
224     switch (CompletionContext.getKind()) {
225     case CodeCompletionContext::CCC_Expression:
226     case CodeCompletionContext::CCC_ObjCMessageReceiver:
227     case CodeCompletionContext::CCC_ParenthesizedExpression:
228     case CodeCompletionContext::CCC_Statement:
229     case CodeCompletionContext::CCC_TopLevelOrExpression:
230     case CodeCompletionContext::CCC_Recovery:
231       if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
232         if (Method->isInstanceMethod())
233           if (ObjCInterfaceDecl *Interface = Method->getClassInterface())
234             ObjCImplementation = Interface->getImplementation();
235       break;
236 
237     default:
238       break;
239     }
240   }
241 
242   /// Determine the priority for a reference to the given declaration.
243   unsigned getBasePriority(const NamedDecl *D);
244 
245   /// Whether we should include code patterns in the completion
246   /// results.
247   bool includeCodePatterns() const {
248     return SemaRef.CodeCompleter &&
249            SemaRef.CodeCompleter->includeCodePatterns();
250   }
251 
252   /// Set the filter used for code-completion results.
253   void setFilter(LookupFilter Filter) { this->Filter = Filter; }
254 
255   Result *data() { return Results.empty() ? nullptr : &Results.front(); }
256   unsigned size() const { return Results.size(); }
257   bool empty() const { return Results.empty(); }
258 
259   /// Specify the preferred type.
260   void setPreferredType(QualType T) {
261     PreferredType = SemaRef.Context.getCanonicalType(T);
262   }
263 
264   /// Set the cv-qualifiers on the object type, for us in filtering
265   /// calls to member functions.
266   ///
267   /// When there are qualifiers in this set, they will be used to filter
268   /// out member functions that aren't available (because there will be a
269   /// cv-qualifier mismatch) or prefer functions with an exact qualifier
270   /// match.
271   void setObjectTypeQualifiers(Qualifiers Quals, ExprValueKind Kind) {
272     ObjectTypeQualifiers = Quals;
273     ObjectKind = Kind;
274     HasObjectTypeQualifiers = true;
275   }
276 
277   /// Set the preferred selector.
278   ///
279   /// When an Objective-C method declaration result is added, and that
280   /// method's selector matches this preferred selector, we give that method
281   /// a slight priority boost.
282   void setPreferredSelector(Selector Sel) { PreferredSelector = Sel; }
283 
284   /// Retrieve the code-completion context for which results are
285   /// being collected.
286   const CodeCompletionContext &getCompletionContext() const {
287     return CompletionContext;
288   }
289 
290   /// Specify whether nested-name-specifiers are allowed.
291   void allowNestedNameSpecifiers(bool Allow = true) {
292     AllowNestedNameSpecifiers = Allow;
293   }
294 
295   /// Return the semantic analysis object for which we are collecting
296   /// code completion results.
297   Sema &getSema() const { return SemaRef; }
298 
299   /// Retrieve the allocator used to allocate code completion strings.
300   CodeCompletionAllocator &getAllocator() const { return Allocator; }
301 
302   CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
303 
304   /// Determine whether the given declaration is at all interesting
305   /// as a code-completion result.
306   ///
307   /// \param ND the declaration that we are inspecting.
308   ///
309   /// \param AsNestedNameSpecifier will be set true if this declaration is
310   /// only interesting when it is a nested-name-specifier.
311   bool isInterestingDecl(const NamedDecl *ND,
312                          bool &AsNestedNameSpecifier) const;
313 
314   /// Decide whether or not a use of function Decl can be a call.
315   ///
316   /// \param ND the function declaration.
317   ///
318   /// \param BaseExprType the object type in a member access expression,
319   /// if any.
320   bool canFunctionBeCalled(const NamedDecl *ND, QualType BaseExprType) const;
321 
322   /// Decide whether or not a use of member function Decl can be a call.
323   ///
324   /// \param Method the function declaration.
325   ///
326   /// \param BaseExprType the object type in a member access expression,
327   /// if any.
328   bool canCxxMethodBeCalled(const CXXMethodDecl *Method,
329                             QualType BaseExprType) const;
330 
331   /// Check whether the result is hidden by the Hiding declaration.
332   ///
333   /// \returns true if the result is hidden and cannot be found, false if
334   /// the hidden result could still be found. When false, \p R may be
335   /// modified to describe how the result can be found (e.g., via extra
336   /// qualification).
337   bool CheckHiddenResult(Result &R, DeclContext *CurContext,
338                          const NamedDecl *Hiding);
339 
340   /// Add a new result to this result set (if it isn't already in one
341   /// of the shadow maps), or replace an existing result (for, e.g., a
342   /// redeclaration).
343   ///
344   /// \param R the result to add (if it is unique).
345   ///
346   /// \param CurContext the context in which this result will be named.
347   void MaybeAddResult(Result R, DeclContext *CurContext = nullptr);
348 
349   /// Add a new result to this result set, where we already know
350   /// the hiding declaration (if any).
351   ///
352   /// \param R the result to add (if it is unique).
353   ///
354   /// \param CurContext the context in which this result will be named.
355   ///
356   /// \param Hiding the declaration that hides the result.
357   ///
358   /// \param InBaseClass whether the result was found in a base
359   /// class of the searched context.
360   ///
361   /// \param BaseExprType the type of expression that precedes the "." or "->"
362   /// in a member access expression.
363   void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
364                  bool InBaseClass, QualType BaseExprType);
365 
366   /// Add a new non-declaration result to this result set.
367   void AddResult(Result R);
368 
369   /// Enter into a new scope.
370   void EnterNewScope();
371 
372   /// Exit from the current scope.
373   void ExitScope();
374 
375   /// Ignore this declaration, if it is seen again.
376   void Ignore(const Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
377 
378   /// Add a visited context.
379   void addVisitedContext(DeclContext *Ctx) {
380     CompletionContext.addVisitedContext(Ctx);
381   }
382 
383   /// \name Name lookup predicates
384   ///
385   /// These predicates can be passed to the name lookup functions to filter the
386   /// results of name lookup. All of the predicates have the same type, so that
387   ///
388   //@{
389   bool IsOrdinaryName(const NamedDecl *ND) const;
390   bool IsOrdinaryNonTypeName(const NamedDecl *ND) const;
391   bool IsIntegralConstantValue(const NamedDecl *ND) const;
392   bool IsOrdinaryNonValueName(const NamedDecl *ND) const;
393   bool IsNestedNameSpecifier(const NamedDecl *ND) const;
394   bool IsEnum(const NamedDecl *ND) const;
395   bool IsClassOrStruct(const NamedDecl *ND) const;
396   bool IsUnion(const NamedDecl *ND) const;
397   bool IsNamespace(const NamedDecl *ND) const;
398   bool IsNamespaceOrAlias(const NamedDecl *ND) const;
399   bool IsType(const NamedDecl *ND) const;
400   bool IsMember(const NamedDecl *ND) const;
401   bool IsObjCIvar(const NamedDecl *ND) const;
402   bool IsObjCMessageReceiver(const NamedDecl *ND) const;
403   bool IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const;
404   bool IsObjCCollection(const NamedDecl *ND) const;
405   bool IsImpossibleToSatisfy(const NamedDecl *ND) const;
406   //@}
407 };
408 } // namespace
409 
410 void PreferredTypeBuilder::enterReturn(Sema &S, SourceLocation Tok) {
411   if (!Enabled)
412     return;
413   if (isa<BlockDecl>(S.CurContext)) {
414     if (sema::BlockScopeInfo *BSI = S.getCurBlock()) {
415       ComputeType = nullptr;
416       Type = BSI->ReturnType;
417       ExpectedLoc = Tok;
418     }
419   } else if (const auto *Function = dyn_cast<FunctionDecl>(S.CurContext)) {
420     ComputeType = nullptr;
421     Type = Function->getReturnType();
422     ExpectedLoc = Tok;
423   } else if (const auto *Method = dyn_cast<ObjCMethodDecl>(S.CurContext)) {
424     ComputeType = nullptr;
425     Type = Method->getReturnType();
426     ExpectedLoc = Tok;
427   }
428 }
429 
430 void PreferredTypeBuilder::enterVariableInit(SourceLocation Tok, Decl *D) {
431   if (!Enabled)
432     return;
433   auto *VD = llvm::dyn_cast_or_null<ValueDecl>(D);
434   ComputeType = nullptr;
435   Type = VD ? VD->getType() : QualType();
436   ExpectedLoc = Tok;
437 }
438 
439 static QualType getDesignatedType(QualType BaseType, const Designation &Desig);
440 
441 void PreferredTypeBuilder::enterDesignatedInitializer(SourceLocation Tok,
442                                                       QualType BaseType,
443                                                       const Designation &D) {
444   if (!Enabled)
445     return;
446   ComputeType = nullptr;
447   Type = getDesignatedType(BaseType, D);
448   ExpectedLoc = Tok;
449 }
450 
451 void PreferredTypeBuilder::enterFunctionArgument(
452     SourceLocation Tok, llvm::function_ref<QualType()> ComputeType) {
453   if (!Enabled)
454     return;
455   this->ComputeType = ComputeType;
456   Type = QualType();
457   ExpectedLoc = Tok;
458 }
459 
460 void PreferredTypeBuilder::enterParenExpr(SourceLocation Tok,
461                                           SourceLocation LParLoc) {
462   if (!Enabled)
463     return;
464   // expected type for parenthesized expression does not change.
465   if (ExpectedLoc == LParLoc)
466     ExpectedLoc = Tok;
467 }
468 
469 static QualType getPreferredTypeOfBinaryRHS(Sema &S, Expr *LHS,
470                                             tok::TokenKind Op) {
471   if (!LHS)
472     return QualType();
473 
474   QualType LHSType = LHS->getType();
475   if (LHSType->isPointerType()) {
476     if (Op == tok::plus || Op == tok::plusequal || Op == tok::minusequal)
477       return S.getASTContext().getPointerDiffType();
478     // Pointer difference is more common than subtracting an int from a pointer.
479     if (Op == tok::minus)
480       return LHSType;
481   }
482 
483   switch (Op) {
484   // No way to infer the type of RHS from LHS.
485   case tok::comma:
486     return QualType();
487   // Prefer the type of the left operand for all of these.
488   // Arithmetic operations.
489   case tok::plus:
490   case tok::plusequal:
491   case tok::minus:
492   case tok::minusequal:
493   case tok::percent:
494   case tok::percentequal:
495   case tok::slash:
496   case tok::slashequal:
497   case tok::star:
498   case tok::starequal:
499   // Assignment.
500   case tok::equal:
501   // Comparison operators.
502   case tok::equalequal:
503   case tok::exclaimequal:
504   case tok::less:
505   case tok::lessequal:
506   case tok::greater:
507   case tok::greaterequal:
508   case tok::spaceship:
509     return LHS->getType();
510   // Binary shifts are often overloaded, so don't try to guess those.
511   case tok::greatergreater:
512   case tok::greatergreaterequal:
513   case tok::lessless:
514   case tok::lesslessequal:
515     if (LHSType->isIntegralOrEnumerationType())
516       return S.getASTContext().IntTy;
517     return QualType();
518   // Logical operators, assume we want bool.
519   case tok::ampamp:
520   case tok::pipepipe:
521   case tok::caretcaret:
522     return S.getASTContext().BoolTy;
523   // Operators often used for bit manipulation are typically used with the type
524   // of the left argument.
525   case tok::pipe:
526   case tok::pipeequal:
527   case tok::caret:
528   case tok::caretequal:
529   case tok::amp:
530   case tok::ampequal:
531     if (LHSType->isIntegralOrEnumerationType())
532       return LHSType;
533     return QualType();
534   // RHS should be a pointer to a member of the 'LHS' type, but we can't give
535   // any particular type here.
536   case tok::periodstar:
537   case tok::arrowstar:
538     return QualType();
539   default:
540     // FIXME(ibiryukov): handle the missing op, re-add the assertion.
541     // assert(false && "unhandled binary op");
542     return QualType();
543   }
544 }
545 
546 /// Get preferred type for an argument of an unary expression. \p ContextType is
547 /// preferred type of the whole unary expression.
548 static QualType getPreferredTypeOfUnaryArg(Sema &S, QualType ContextType,
549                                            tok::TokenKind Op) {
550   switch (Op) {
551   case tok::exclaim:
552     return S.getASTContext().BoolTy;
553   case tok::amp:
554     if (!ContextType.isNull() && ContextType->isPointerType())
555       return ContextType->getPointeeType();
556     return QualType();
557   case tok::star:
558     if (ContextType.isNull())
559       return QualType();
560     return S.getASTContext().getPointerType(ContextType.getNonReferenceType());
561   case tok::plus:
562   case tok::minus:
563   case tok::tilde:
564   case tok::minusminus:
565   case tok::plusplus:
566     if (ContextType.isNull())
567       return S.getASTContext().IntTy;
568     // leave as is, these operators typically return the same type.
569     return ContextType;
570   case tok::kw___real:
571   case tok::kw___imag:
572     return QualType();
573   default:
574     assert(false && "unhandled unary op");
575     return QualType();
576   }
577 }
578 
579 void PreferredTypeBuilder::enterBinary(Sema &S, SourceLocation Tok, Expr *LHS,
580                                        tok::TokenKind Op) {
581   if (!Enabled)
582     return;
583   ComputeType = nullptr;
584   Type = getPreferredTypeOfBinaryRHS(S, LHS, Op);
585   ExpectedLoc = Tok;
586 }
587 
588 void PreferredTypeBuilder::enterMemAccess(Sema &S, SourceLocation Tok,
589                                           Expr *Base) {
590   if (!Enabled || !Base)
591     return;
592   // Do we have expected type for Base?
593   if (ExpectedLoc != Base->getBeginLoc())
594     return;
595   // Keep the expected type, only update the location.
596   ExpectedLoc = Tok;
597 }
598 
599 void PreferredTypeBuilder::enterUnary(Sema &S, SourceLocation Tok,
600                                       tok::TokenKind OpKind,
601                                       SourceLocation OpLoc) {
602   if (!Enabled)
603     return;
604   ComputeType = nullptr;
605   Type = getPreferredTypeOfUnaryArg(S, this->get(OpLoc), OpKind);
606   ExpectedLoc = Tok;
607 }
608 
609 void PreferredTypeBuilder::enterSubscript(Sema &S, SourceLocation Tok,
610                                           Expr *LHS) {
611   if (!Enabled)
612     return;
613   ComputeType = nullptr;
614   Type = S.getASTContext().IntTy;
615   ExpectedLoc = Tok;
616 }
617 
618 void PreferredTypeBuilder::enterTypeCast(SourceLocation Tok,
619                                          QualType CastType) {
620   if (!Enabled)
621     return;
622   ComputeType = nullptr;
623   Type = !CastType.isNull() ? CastType.getCanonicalType() : QualType();
624   ExpectedLoc = Tok;
625 }
626 
627 void PreferredTypeBuilder::enterCondition(Sema &S, SourceLocation Tok) {
628   if (!Enabled)
629     return;
630   ComputeType = nullptr;
631   Type = S.getASTContext().BoolTy;
632   ExpectedLoc = Tok;
633 }
634 
635 class ResultBuilder::ShadowMapEntry::iterator {
636   llvm::PointerUnion<const NamedDecl *, const DeclIndexPair *> DeclOrIterator;
637   unsigned SingleDeclIndex;
638 
639 public:
640   typedef DeclIndexPair value_type;
641   typedef value_type reference;
642   typedef std::ptrdiff_t difference_type;
643   typedef std::input_iterator_tag iterator_category;
644 
645   class pointer {
646     DeclIndexPair Value;
647 
648   public:
649     pointer(const DeclIndexPair &Value) : Value(Value) {}
650 
651     const DeclIndexPair *operator->() const { return &Value; }
652   };
653 
654   iterator() : DeclOrIterator((NamedDecl *)nullptr), SingleDeclIndex(0) {}
655 
656   iterator(const NamedDecl *SingleDecl, unsigned Index)
657       : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) {}
658 
659   iterator(const DeclIndexPair *Iterator)
660       : DeclOrIterator(Iterator), SingleDeclIndex(0) {}
661 
662   iterator &operator++() {
663     if (DeclOrIterator.is<const NamedDecl *>()) {
664       DeclOrIterator = (NamedDecl *)nullptr;
665       SingleDeclIndex = 0;
666       return *this;
667     }
668 
669     const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair *>();
670     ++I;
671     DeclOrIterator = I;
672     return *this;
673   }
674 
675   /*iterator operator++(int) {
676     iterator tmp(*this);
677     ++(*this);
678     return tmp;
679   }*/
680 
681   reference operator*() const {
682     if (const NamedDecl *ND = DeclOrIterator.dyn_cast<const NamedDecl *>())
683       return reference(ND, SingleDeclIndex);
684 
685     return *DeclOrIterator.get<const DeclIndexPair *>();
686   }
687 
688   pointer operator->() const { return pointer(**this); }
689 
690   friend bool operator==(const iterator &X, const iterator &Y) {
691     return X.DeclOrIterator.getOpaqueValue() ==
692                Y.DeclOrIterator.getOpaqueValue() &&
693            X.SingleDeclIndex == Y.SingleDeclIndex;
694   }
695 
696   friend bool operator!=(const iterator &X, const iterator &Y) {
697     return !(X == Y);
698   }
699 };
700 
701 ResultBuilder::ShadowMapEntry::iterator
702 ResultBuilder::ShadowMapEntry::begin() const {
703   if (DeclOrVector.isNull())
704     return iterator();
705 
706   if (const NamedDecl *ND = DeclOrVector.dyn_cast<const NamedDecl *>())
707     return iterator(ND, SingleDeclIndex);
708 
709   return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
710 }
711 
712 ResultBuilder::ShadowMapEntry::iterator
713 ResultBuilder::ShadowMapEntry::end() const {
714   if (DeclOrVector.is<const NamedDecl *>() || DeclOrVector.isNull())
715     return iterator();
716 
717   return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
718 }
719 
720 /// Compute the qualification required to get from the current context
721 /// (\p CurContext) to the target context (\p TargetContext).
722 ///
723 /// \param Context the AST context in which the qualification will be used.
724 ///
725 /// \param CurContext the context where an entity is being named, which is
726 /// typically based on the current scope.
727 ///
728 /// \param TargetContext the context in which the named entity actually
729 /// resides.
730 ///
731 /// \returns a nested name specifier that refers into the target context, or
732 /// NULL if no qualification is needed.
733 static NestedNameSpecifier *
734 getRequiredQualification(ASTContext &Context, const DeclContext *CurContext,
735                          const DeclContext *TargetContext) {
736   SmallVector<const DeclContext *, 4> TargetParents;
737 
738   for (const DeclContext *CommonAncestor = TargetContext;
739        CommonAncestor && !CommonAncestor->Encloses(CurContext);
740        CommonAncestor = CommonAncestor->getLookupParent()) {
741     if (CommonAncestor->isTransparentContext() ||
742         CommonAncestor->isFunctionOrMethod())
743       continue;
744 
745     TargetParents.push_back(CommonAncestor);
746   }
747 
748   NestedNameSpecifier *Result = nullptr;
749   while (!TargetParents.empty()) {
750     const DeclContext *Parent = TargetParents.pop_back_val();
751 
752     if (const auto *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
753       if (!Namespace->getIdentifier())
754         continue;
755 
756       Result = NestedNameSpecifier::Create(Context, Result, Namespace);
757     } else if (const auto *TD = dyn_cast<TagDecl>(Parent))
758       Result = NestedNameSpecifier::Create(
759           Context, Result, false, Context.getTypeDeclType(TD).getTypePtr());
760   }
761   return Result;
762 }
763 
764 // Some declarations have reserved names that we don't want to ever show.
765 // Filter out names reserved for the implementation if they come from a
766 // system header.
767 static bool shouldIgnoreDueToReservedName(const NamedDecl *ND, Sema &SemaRef) {
768   // Debuggers want access to all identifiers, including reserved ones.
769   if (SemaRef.getLangOpts().DebuggerSupport)
770     return false;
771 
772   ReservedIdentifierStatus Status = ND->isReserved(SemaRef.getLangOpts());
773   // Ignore reserved names for compiler provided decls.
774   if (isReservedInAllContexts(Status) && ND->getLocation().isInvalid())
775     return true;
776 
777   // For system headers ignore only double-underscore names.
778   // This allows for system headers providing private symbols with a single
779   // underscore.
780   if (Status == ReservedIdentifierStatus::StartsWithDoubleUnderscore &&
781       SemaRef.SourceMgr.isInSystemHeader(
782           SemaRef.SourceMgr.getSpellingLoc(ND->getLocation())))
783     return true;
784 
785   return false;
786 }
787 
788 bool ResultBuilder::isInterestingDecl(const NamedDecl *ND,
789                                       bool &AsNestedNameSpecifier) const {
790   AsNestedNameSpecifier = false;
791 
792   auto *Named = ND;
793   ND = ND->getUnderlyingDecl();
794 
795   // Skip unnamed entities.
796   if (!ND->getDeclName())
797     return false;
798 
799   // Friend declarations and declarations introduced due to friends are never
800   // added as results.
801   if (ND->getFriendObjectKind() == Decl::FOK_Undeclared)
802     return false;
803 
804   // Class template (partial) specializations are never added as results.
805   if (isa<ClassTemplateSpecializationDecl>(ND) ||
806       isa<ClassTemplatePartialSpecializationDecl>(ND))
807     return false;
808 
809   // Using declarations themselves are never added as results.
810   if (isa<UsingDecl>(ND))
811     return false;
812 
813   if (shouldIgnoreDueToReservedName(ND, SemaRef))
814     return false;
815 
816   if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
817       (isa<NamespaceDecl>(ND) && Filter != &ResultBuilder::IsNamespace &&
818        Filter != &ResultBuilder::IsNamespaceOrAlias && Filter != nullptr))
819     AsNestedNameSpecifier = true;
820 
821   // Filter out any unwanted results.
822   if (Filter && !(this->*Filter)(Named)) {
823     // Check whether it is interesting as a nested-name-specifier.
824     if (AllowNestedNameSpecifiers && SemaRef.getLangOpts().CPlusPlus &&
825         IsNestedNameSpecifier(ND) &&
826         (Filter != &ResultBuilder::IsMember ||
827          (isa<CXXRecordDecl>(ND) &&
828           cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
829       AsNestedNameSpecifier = true;
830       return true;
831     }
832 
833     return false;
834   }
835   // ... then it must be interesting!
836   return true;
837 }
838 
839 bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
840                                       const NamedDecl *Hiding) {
841   // In C, there is no way to refer to a hidden name.
842   // FIXME: This isn't true; we can find a tag name hidden by an ordinary
843   // name if we introduce the tag type.
844   if (!SemaRef.getLangOpts().CPlusPlus)
845     return true;
846 
847   const DeclContext *HiddenCtx =
848       R.Declaration->getDeclContext()->getRedeclContext();
849 
850   // There is no way to qualify a name declared in a function or method.
851   if (HiddenCtx->isFunctionOrMethod())
852     return true;
853 
854   if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
855     return true;
856 
857   // We can refer to the result with the appropriate qualification. Do it.
858   R.Hidden = true;
859   R.QualifierIsInformative = false;
860 
861   if (!R.Qualifier)
862     R.Qualifier = getRequiredQualification(SemaRef.Context, CurContext,
863                                            R.Declaration->getDeclContext());
864   return false;
865 }
866 
867 /// A simplified classification of types used to determine whether two
868 /// types are "similar enough" when adjusting priorities.
869 SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
870   switch (T->getTypeClass()) {
871   case Type::Builtin:
872     switch (cast<BuiltinType>(T)->getKind()) {
873     case BuiltinType::Void:
874       return STC_Void;
875 
876     case BuiltinType::NullPtr:
877       return STC_Pointer;
878 
879     case BuiltinType::Overload:
880     case BuiltinType::Dependent:
881       return STC_Other;
882 
883     case BuiltinType::ObjCId:
884     case BuiltinType::ObjCClass:
885     case BuiltinType::ObjCSel:
886       return STC_ObjectiveC;
887 
888     default:
889       return STC_Arithmetic;
890     }
891 
892   case Type::Complex:
893     return STC_Arithmetic;
894 
895   case Type::Pointer:
896     return STC_Pointer;
897 
898   case Type::BlockPointer:
899     return STC_Block;
900 
901   case Type::LValueReference:
902   case Type::RValueReference:
903     return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
904 
905   case Type::ConstantArray:
906   case Type::IncompleteArray:
907   case Type::VariableArray:
908   case Type::DependentSizedArray:
909     return STC_Array;
910 
911   case Type::DependentSizedExtVector:
912   case Type::Vector:
913   case Type::ExtVector:
914     return STC_Arithmetic;
915 
916   case Type::FunctionProto:
917   case Type::FunctionNoProto:
918     return STC_Function;
919 
920   case Type::Record:
921     return STC_Record;
922 
923   case Type::Enum:
924     return STC_Arithmetic;
925 
926   case Type::ObjCObject:
927   case Type::ObjCInterface:
928   case Type::ObjCObjectPointer:
929     return STC_ObjectiveC;
930 
931   default:
932     return STC_Other;
933   }
934 }
935 
936 /// Get the type that a given expression will have if this declaration
937 /// is used as an expression in its "typical" code-completion form.
938 QualType clang::getDeclUsageType(ASTContext &C, const NamedDecl *ND) {
939   ND = ND->getUnderlyingDecl();
940 
941   if (const auto *Type = dyn_cast<TypeDecl>(ND))
942     return C.getTypeDeclType(Type);
943   if (const auto *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
944     return C.getObjCInterfaceType(Iface);
945 
946   QualType T;
947   if (const FunctionDecl *Function = ND->getAsFunction())
948     T = Function->getCallResultType();
949   else if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND))
950     T = Method->getSendResultType();
951   else if (const auto *Enumerator = dyn_cast<EnumConstantDecl>(ND))
952     T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
953   else if (const auto *Property = dyn_cast<ObjCPropertyDecl>(ND))
954     T = Property->getType();
955   else if (const auto *Value = dyn_cast<ValueDecl>(ND))
956     T = Value->getType();
957 
958   if (T.isNull())
959     return QualType();
960 
961   // Dig through references, function pointers, and block pointers to
962   // get down to the likely type of an expression when the entity is
963   // used.
964   do {
965     if (const auto *Ref = T->getAs<ReferenceType>()) {
966       T = Ref->getPointeeType();
967       continue;
968     }
969 
970     if (const auto *Pointer = T->getAs<PointerType>()) {
971       if (Pointer->getPointeeType()->isFunctionType()) {
972         T = Pointer->getPointeeType();
973         continue;
974       }
975 
976       break;
977     }
978 
979     if (const auto *Block = T->getAs<BlockPointerType>()) {
980       T = Block->getPointeeType();
981       continue;
982     }
983 
984     if (const auto *Function = T->getAs<FunctionType>()) {
985       T = Function->getReturnType();
986       continue;
987     }
988 
989     break;
990   } while (true);
991 
992   return T;
993 }
994 
995 unsigned ResultBuilder::getBasePriority(const NamedDecl *ND) {
996   if (!ND)
997     return CCP_Unlikely;
998 
999   // Context-based decisions.
1000   const DeclContext *LexicalDC = ND->getLexicalDeclContext();
1001   if (LexicalDC->isFunctionOrMethod()) {
1002     // _cmd is relatively rare
1003     if (const auto *ImplicitParam = dyn_cast<ImplicitParamDecl>(ND))
1004       if (ImplicitParam->getIdentifier() &&
1005           ImplicitParam->getIdentifier()->isStr("_cmd"))
1006         return CCP_ObjC_cmd;
1007 
1008     return CCP_LocalDeclaration;
1009   }
1010 
1011   const DeclContext *DC = ND->getDeclContext()->getRedeclContext();
1012   if (DC->isRecord() || isa<ObjCContainerDecl>(DC)) {
1013     // Explicit destructor calls are very rare.
1014     if (isa<CXXDestructorDecl>(ND))
1015       return CCP_Unlikely;
1016     // Explicit operator and conversion function calls are also very rare.
1017     auto DeclNameKind = ND->getDeclName().getNameKind();
1018     if (DeclNameKind == DeclarationName::CXXOperatorName ||
1019         DeclNameKind == DeclarationName::CXXLiteralOperatorName ||
1020         DeclNameKind == DeclarationName::CXXConversionFunctionName)
1021       return CCP_Unlikely;
1022     return CCP_MemberDeclaration;
1023   }
1024 
1025   // Content-based decisions.
1026   if (isa<EnumConstantDecl>(ND))
1027     return CCP_Constant;
1028 
1029   // Use CCP_Type for type declarations unless we're in a statement, Objective-C
1030   // message receiver, or parenthesized expression context. There, it's as
1031   // likely that the user will want to write a type as other declarations.
1032   if ((isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
1033       !(CompletionContext.getKind() == CodeCompletionContext::CCC_Statement ||
1034         CompletionContext.getKind() ==
1035             CodeCompletionContext::CCC_ObjCMessageReceiver ||
1036         CompletionContext.getKind() ==
1037             CodeCompletionContext::CCC_ParenthesizedExpression))
1038     return CCP_Type;
1039 
1040   return CCP_Declaration;
1041 }
1042 
1043 void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
1044   // If this is an Objective-C method declaration whose selector matches our
1045   // preferred selector, give it a priority boost.
1046   if (!PreferredSelector.isNull())
1047     if (const auto *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
1048       if (PreferredSelector == Method->getSelector())
1049         R.Priority += CCD_SelectorMatch;
1050 
1051   // If we have a preferred type, adjust the priority for results with exactly-
1052   // matching or nearly-matching types.
1053   if (!PreferredType.isNull()) {
1054     QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
1055     if (!T.isNull()) {
1056       CanQualType TC = SemaRef.Context.getCanonicalType(T);
1057       // Check for exactly-matching types (modulo qualifiers).
1058       if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
1059         R.Priority /= CCF_ExactTypeMatch;
1060       // Check for nearly-matching types, based on classification of each.
1061       else if ((getSimplifiedTypeClass(PreferredType) ==
1062                 getSimplifiedTypeClass(TC)) &&
1063                !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
1064         R.Priority /= CCF_SimilarTypeMatch;
1065     }
1066   }
1067 }
1068 
1069 static DeclContext::lookup_result getConstructors(ASTContext &Context,
1070                                                   const CXXRecordDecl *Record) {
1071   QualType RecordTy = Context.getTypeDeclType(Record);
1072   DeclarationName ConstructorName =
1073       Context.DeclarationNames.getCXXConstructorName(
1074           Context.getCanonicalType(RecordTy));
1075   return Record->lookup(ConstructorName);
1076 }
1077 
1078 void ResultBuilder::MaybeAddConstructorResults(Result R) {
1079   if (!SemaRef.getLangOpts().CPlusPlus || !R.Declaration ||
1080       !CompletionContext.wantConstructorResults())
1081     return;
1082 
1083   const NamedDecl *D = R.Declaration;
1084   const CXXRecordDecl *Record = nullptr;
1085   if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
1086     Record = ClassTemplate->getTemplatedDecl();
1087   else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
1088     // Skip specializations and partial specializations.
1089     if (isa<ClassTemplateSpecializationDecl>(Record))
1090       return;
1091   } else {
1092     // There are no constructors here.
1093     return;
1094   }
1095 
1096   Record = Record->getDefinition();
1097   if (!Record)
1098     return;
1099 
1100   for (NamedDecl *Ctor : getConstructors(SemaRef.Context, Record)) {
1101     R.Declaration = Ctor;
1102     R.CursorKind = getCursorKindForDecl(R.Declaration);
1103     Results.push_back(R);
1104   }
1105 }
1106 
1107 static bool isConstructor(const Decl *ND) {
1108   if (const auto *Tmpl = dyn_cast<FunctionTemplateDecl>(ND))
1109     ND = Tmpl->getTemplatedDecl();
1110   return isa<CXXConstructorDecl>(ND);
1111 }
1112 
1113 void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
1114   assert(!ShadowMaps.empty() && "Must enter into a results scope");
1115 
1116   if (R.Kind != Result::RK_Declaration) {
1117     // For non-declaration results, just add the result.
1118     Results.push_back(R);
1119     return;
1120   }
1121 
1122   // Look through using declarations.
1123   if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
1124     CodeCompletionResult Result(Using->getTargetDecl(),
1125                                 getBasePriority(Using->getTargetDecl()),
1126                                 R.Qualifier, false,
1127                                 (R.Availability == CXAvailability_Available ||
1128                                  R.Availability == CXAvailability_Deprecated),
1129                                 std::move(R.FixIts));
1130     Result.ShadowDecl = Using;
1131     MaybeAddResult(Result, CurContext);
1132     return;
1133   }
1134 
1135   const Decl *CanonDecl = R.Declaration->getCanonicalDecl();
1136   unsigned IDNS = CanonDecl->getIdentifierNamespace();
1137 
1138   bool AsNestedNameSpecifier = false;
1139   if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
1140     return;
1141 
1142   // C++ constructors are never found by name lookup.
1143   if (isConstructor(R.Declaration))
1144     return;
1145 
1146   ShadowMap &SMap = ShadowMaps.back();
1147   ShadowMapEntry::iterator I, IEnd;
1148   ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
1149   if (NamePos != SMap.end()) {
1150     I = NamePos->second.begin();
1151     IEnd = NamePos->second.end();
1152   }
1153 
1154   for (; I != IEnd; ++I) {
1155     const NamedDecl *ND = I->first;
1156     unsigned Index = I->second;
1157     if (ND->getCanonicalDecl() == CanonDecl) {
1158       // This is a redeclaration. Always pick the newer declaration.
1159       Results[Index].Declaration = R.Declaration;
1160 
1161       // We're done.
1162       return;
1163     }
1164   }
1165 
1166   // This is a new declaration in this scope. However, check whether this
1167   // declaration name is hidden by a similarly-named declaration in an outer
1168   // scope.
1169   std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
1170   --SMEnd;
1171   for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
1172     ShadowMapEntry::iterator I, IEnd;
1173     ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
1174     if (NamePos != SM->end()) {
1175       I = NamePos->second.begin();
1176       IEnd = NamePos->second.end();
1177     }
1178     for (; I != IEnd; ++I) {
1179       // A tag declaration does not hide a non-tag declaration.
1180       if (I->first->hasTagIdentifierNamespace() &&
1181           (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
1182                    Decl::IDNS_LocalExtern | Decl::IDNS_ObjCProtocol)))
1183         continue;
1184 
1185       // Protocols are in distinct namespaces from everything else.
1186       if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol) ||
1187            (IDNS & Decl::IDNS_ObjCProtocol)) &&
1188           I->first->getIdentifierNamespace() != IDNS)
1189         continue;
1190 
1191       // The newly-added result is hidden by an entry in the shadow map.
1192       if (CheckHiddenResult(R, CurContext, I->first))
1193         return;
1194 
1195       break;
1196     }
1197   }
1198 
1199   // Make sure that any given declaration only shows up in the result set once.
1200   if (!AllDeclsFound.insert(CanonDecl).second)
1201     return;
1202 
1203   // If the filter is for nested-name-specifiers, then this result starts a
1204   // nested-name-specifier.
1205   if (AsNestedNameSpecifier) {
1206     R.StartsNestedNameSpecifier = true;
1207     R.Priority = CCP_NestedNameSpecifier;
1208   } else
1209     AdjustResultPriorityForDecl(R);
1210 
1211   // If this result is supposed to have an informative qualifier, add one.
1212   if (R.QualifierIsInformative && !R.Qualifier &&
1213       !R.StartsNestedNameSpecifier) {
1214     const DeclContext *Ctx = R.Declaration->getDeclContext();
1215     if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
1216       R.Qualifier =
1217           NestedNameSpecifier::Create(SemaRef.Context, nullptr, Namespace);
1218     else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
1219       R.Qualifier = NestedNameSpecifier::Create(
1220           SemaRef.Context, nullptr, false,
1221           SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
1222     else
1223       R.QualifierIsInformative = false;
1224   }
1225 
1226   // Insert this result into the set of results and into the current shadow
1227   // map.
1228   SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
1229   Results.push_back(R);
1230 
1231   if (!AsNestedNameSpecifier)
1232     MaybeAddConstructorResults(R);
1233 }
1234 
1235 static void setInBaseClass(ResultBuilder::Result &R) {
1236   R.Priority += CCD_InBaseClass;
1237   R.InBaseClass = true;
1238 }
1239 
1240 enum class OverloadCompare { BothViable, Dominates, Dominated };
1241 // Will Candidate ever be called on the object, when overloaded with Incumbent?
1242 // Returns Dominates if Candidate is always called, Dominated if Incumbent is
1243 // always called, BothViable if either may be called depending on arguments.
1244 // Precondition: must actually be overloads!
1245 static OverloadCompare compareOverloads(const CXXMethodDecl &Candidate,
1246                                         const CXXMethodDecl &Incumbent,
1247                                         const Qualifiers &ObjectQuals,
1248                                         ExprValueKind ObjectKind) {
1249   // Base/derived shadowing is handled elsewhere.
1250   if (Candidate.getDeclContext() != Incumbent.getDeclContext())
1251     return OverloadCompare::BothViable;
1252   if (Candidate.isVariadic() != Incumbent.isVariadic() ||
1253       Candidate.getNumParams() != Incumbent.getNumParams() ||
1254       Candidate.getMinRequiredArguments() !=
1255           Incumbent.getMinRequiredArguments())
1256     return OverloadCompare::BothViable;
1257   for (unsigned I = 0, E = Candidate.getNumParams(); I != E; ++I)
1258     if (Candidate.parameters()[I]->getType().getCanonicalType() !=
1259         Incumbent.parameters()[I]->getType().getCanonicalType())
1260       return OverloadCompare::BothViable;
1261   if (!Candidate.specific_attrs<EnableIfAttr>().empty() ||
1262       !Incumbent.specific_attrs<EnableIfAttr>().empty())
1263     return OverloadCompare::BothViable;
1264   // At this point, we know calls can't pick one or the other based on
1265   // arguments, so one of the two must win. (Or both fail, handled elsewhere).
1266   RefQualifierKind CandidateRef = Candidate.getRefQualifier();
1267   RefQualifierKind IncumbentRef = Incumbent.getRefQualifier();
1268   if (CandidateRef != IncumbentRef) {
1269     // If the object kind is LValue/RValue, there's one acceptable ref-qualifier
1270     // and it can't be mixed with ref-unqualified overloads (in valid code).
1271 
1272     // For xvalue objects, we prefer the rvalue overload even if we have to
1273     // add qualifiers (which is rare, because const&& is rare).
1274     if (ObjectKind == clang::VK_XValue)
1275       return CandidateRef == RQ_RValue ? OverloadCompare::Dominates
1276                                        : OverloadCompare::Dominated;
1277   }
1278   // Now the ref qualifiers are the same (or we're in some invalid state).
1279   // So make some decision based on the qualifiers.
1280   Qualifiers CandidateQual = Candidate.getMethodQualifiers();
1281   Qualifiers IncumbentQual = Incumbent.getMethodQualifiers();
1282   bool CandidateSuperset = CandidateQual.compatiblyIncludes(IncumbentQual);
1283   bool IncumbentSuperset = IncumbentQual.compatiblyIncludes(CandidateQual);
1284   if (CandidateSuperset == IncumbentSuperset)
1285     return OverloadCompare::BothViable;
1286   return IncumbentSuperset ? OverloadCompare::Dominates
1287                            : OverloadCompare::Dominated;
1288 }
1289 
1290 bool ResultBuilder::canCxxMethodBeCalled(const CXXMethodDecl *Method,
1291                                          QualType BaseExprType) const {
1292   // Find the class scope that we're currently in.
1293   // We could e.g. be inside a lambda, so walk up the DeclContext until we
1294   // find a CXXMethodDecl.
1295   DeclContext *CurContext = SemaRef.CurContext;
1296   const auto *CurrentClassScope = [&]() -> const CXXRecordDecl * {
1297     for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getParent()) {
1298       const auto *CtxMethod = llvm::dyn_cast<CXXMethodDecl>(Ctx);
1299       if (CtxMethod && !CtxMethod->getParent()->isLambda()) {
1300         return CtxMethod->getParent();
1301       }
1302     }
1303     return nullptr;
1304   }();
1305 
1306   // If we're not inside the scope of the method's class, it can't be a call.
1307   bool FunctionCanBeCall =
1308       CurrentClassScope &&
1309       (CurrentClassScope == Method->getParent() ||
1310        CurrentClassScope->isDerivedFrom(Method->getParent()));
1311 
1312   // We skip the following calculation for exceptions if it's already true.
1313   if (FunctionCanBeCall)
1314     return true;
1315 
1316   // Exception: foo->FooBase::bar() or foo->Foo::bar() *is* a call.
1317   if (const CXXRecordDecl *MaybeDerived =
1318           BaseExprType.isNull() ? nullptr
1319                                 : BaseExprType->getAsCXXRecordDecl()) {
1320     auto *MaybeBase = Method->getParent();
1321     FunctionCanBeCall =
1322         MaybeDerived == MaybeBase || MaybeDerived->isDerivedFrom(MaybeBase);
1323   }
1324 
1325   return FunctionCanBeCall;
1326 }
1327 
1328 bool ResultBuilder::canFunctionBeCalled(const NamedDecl *ND,
1329                                         QualType BaseExprType) const {
1330   // We apply heuristics only to CCC_Symbol:
1331   // * CCC_{Arrow,Dot}MemberAccess reflect member access expressions:
1332   //   f.method() and f->method(). These are always calls.
1333   // * A qualified name to a member function may *not* be a call. We have to
1334   //   subdivide the cases: For example, f.Base::method(), which is regarded as
1335   //   CCC_Symbol, should be a call.
1336   // * Non-member functions and static member functions are always considered
1337   //   calls.
1338   if (CompletionContext.getKind() == clang::CodeCompletionContext::CCC_Symbol) {
1339     if (const auto *FuncTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
1340       ND = FuncTmpl->getTemplatedDecl();
1341     }
1342     const auto *Method = dyn_cast<CXXMethodDecl>(ND);
1343     if (Method && !Method->isStatic()) {
1344       return canCxxMethodBeCalled(Method, BaseExprType);
1345     }
1346   }
1347   return true;
1348 }
1349 
1350 void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
1351                               NamedDecl *Hiding, bool InBaseClass = false,
1352                               QualType BaseExprType = QualType()) {
1353   if (R.Kind != Result::RK_Declaration) {
1354     // For non-declaration results, just add the result.
1355     Results.push_back(R);
1356     return;
1357   }
1358 
1359   // Look through using declarations.
1360   if (const auto *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
1361     CodeCompletionResult Result(Using->getTargetDecl(),
1362                                 getBasePriority(Using->getTargetDecl()),
1363                                 R.Qualifier, false,
1364                                 (R.Availability == CXAvailability_Available ||
1365                                  R.Availability == CXAvailability_Deprecated),
1366                                 std::move(R.FixIts));
1367     Result.ShadowDecl = Using;
1368     AddResult(Result, CurContext, Hiding, /*InBaseClass=*/false,
1369               /*BaseExprType=*/BaseExprType);
1370     return;
1371   }
1372 
1373   bool AsNestedNameSpecifier = false;
1374   if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
1375     return;
1376 
1377   // C++ constructors are never found by name lookup.
1378   if (isConstructor(R.Declaration))
1379     return;
1380 
1381   if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
1382     return;
1383 
1384   // Make sure that any given declaration only shows up in the result set once.
1385   if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()).second)
1386     return;
1387 
1388   // If the filter is for nested-name-specifiers, then this result starts a
1389   // nested-name-specifier.
1390   if (AsNestedNameSpecifier) {
1391     R.StartsNestedNameSpecifier = true;
1392     R.Priority = CCP_NestedNameSpecifier;
1393   } else if (Filter == &ResultBuilder::IsMember && !R.Qualifier &&
1394              InBaseClass &&
1395              isa<CXXRecordDecl>(
1396                  R.Declaration->getDeclContext()->getRedeclContext()))
1397     R.QualifierIsInformative = true;
1398 
1399   // If this result is supposed to have an informative qualifier, add one.
1400   if (R.QualifierIsInformative && !R.Qualifier &&
1401       !R.StartsNestedNameSpecifier) {
1402     const DeclContext *Ctx = R.Declaration->getDeclContext();
1403     if (const auto *Namespace = dyn_cast<NamespaceDecl>(Ctx))
1404       R.Qualifier =
1405           NestedNameSpecifier::Create(SemaRef.Context, nullptr, Namespace);
1406     else if (const auto *Tag = dyn_cast<TagDecl>(Ctx))
1407       R.Qualifier = NestedNameSpecifier::Create(
1408           SemaRef.Context, nullptr, false,
1409           SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
1410     else
1411       R.QualifierIsInformative = false;
1412   }
1413 
1414   // Adjust the priority if this result comes from a base class.
1415   if (InBaseClass)
1416     setInBaseClass(R);
1417 
1418   AdjustResultPriorityForDecl(R);
1419 
1420   if (HasObjectTypeQualifiers)
1421     if (const auto *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
1422       if (Method->isInstance()) {
1423         Qualifiers MethodQuals = Method->getMethodQualifiers();
1424         if (ObjectTypeQualifiers == MethodQuals)
1425           R.Priority += CCD_ObjectQualifierMatch;
1426         else if (ObjectTypeQualifiers - MethodQuals) {
1427           // The method cannot be invoked, because doing so would drop
1428           // qualifiers.
1429           return;
1430         }
1431         // Detect cases where a ref-qualified method cannot be invoked.
1432         switch (Method->getRefQualifier()) {
1433           case RQ_LValue:
1434             if (ObjectKind != VK_LValue && !MethodQuals.hasConst())
1435               return;
1436             break;
1437           case RQ_RValue:
1438             if (ObjectKind == VK_LValue)
1439               return;
1440             break;
1441           case RQ_None:
1442             break;
1443         }
1444 
1445         /// Check whether this dominates another overloaded method, which should
1446         /// be suppressed (or vice versa).
1447         /// Motivating case is const_iterator begin() const vs iterator begin().
1448         auto &OverloadSet = OverloadMap[std::make_pair(
1449             CurContext, Method->getDeclName().getAsOpaqueInteger())];
1450         for (const DeclIndexPair Entry : OverloadSet) {
1451           Result &Incumbent = Results[Entry.second];
1452           switch (compareOverloads(*Method,
1453                                    *cast<CXXMethodDecl>(Incumbent.Declaration),
1454                                    ObjectTypeQualifiers, ObjectKind)) {
1455           case OverloadCompare::Dominates:
1456             // Replace the dominated overload with this one.
1457             // FIXME: if the overload dominates multiple incumbents then we
1458             // should remove all. But two overloads is by far the common case.
1459             Incumbent = std::move(R);
1460             return;
1461           case OverloadCompare::Dominated:
1462             // This overload can't be called, drop it.
1463             return;
1464           case OverloadCompare::BothViable:
1465             break;
1466           }
1467         }
1468         OverloadSet.Add(Method, Results.size());
1469       }
1470 
1471   R.FunctionCanBeCall = canFunctionBeCalled(R.getDeclaration(), BaseExprType);
1472 
1473   // Insert this result into the set of results.
1474   Results.push_back(R);
1475 
1476   if (!AsNestedNameSpecifier)
1477     MaybeAddConstructorResults(R);
1478 }
1479 
1480 void ResultBuilder::AddResult(Result R) {
1481   assert(R.Kind != Result::RK_Declaration &&
1482          "Declaration results need more context");
1483   Results.push_back(R);
1484 }
1485 
1486 /// Enter into a new scope.
1487 void ResultBuilder::EnterNewScope() { ShadowMaps.emplace_back(); }
1488 
1489 /// Exit from the current scope.
1490 void ResultBuilder::ExitScope() {
1491   ShadowMaps.pop_back();
1492 }
1493 
1494 /// Determines whether this given declaration will be found by
1495 /// ordinary name lookup.
1496 bool ResultBuilder::IsOrdinaryName(const NamedDecl *ND) const {
1497   ND = ND->getUnderlyingDecl();
1498 
1499   // If name lookup finds a local extern declaration, then we are in a
1500   // context where it behaves like an ordinary name.
1501   unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1502   if (SemaRef.getLangOpts().CPlusPlus)
1503     IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
1504   else if (SemaRef.getLangOpts().ObjC) {
1505     if (isa<ObjCIvarDecl>(ND))
1506       return true;
1507   }
1508 
1509   return ND->getIdentifierNamespace() & IDNS;
1510 }
1511 
1512 /// Determines whether this given declaration will be found by
1513 /// ordinary name lookup but is not a type name.
1514 bool ResultBuilder::IsOrdinaryNonTypeName(const NamedDecl *ND) const {
1515   ND = ND->getUnderlyingDecl();
1516   if (isa<TypeDecl>(ND))
1517     return false;
1518   // Objective-C interfaces names are not filtered by this method because they
1519   // can be used in a class property expression. We can still filter out
1520   // @class declarations though.
1521   if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND)) {
1522     if (!ID->getDefinition())
1523       return false;
1524   }
1525 
1526   unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1527   if (SemaRef.getLangOpts().CPlusPlus)
1528     IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
1529   else if (SemaRef.getLangOpts().ObjC) {
1530     if (isa<ObjCIvarDecl>(ND))
1531       return true;
1532   }
1533 
1534   return ND->getIdentifierNamespace() & IDNS;
1535 }
1536 
1537 bool ResultBuilder::IsIntegralConstantValue(const NamedDecl *ND) const {
1538   if (!IsOrdinaryNonTypeName(ND))
1539     return false;
1540 
1541   if (const auto *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
1542     if (VD->getType()->isIntegralOrEnumerationType())
1543       return true;
1544 
1545   return false;
1546 }
1547 
1548 /// Determines whether this given declaration will be found by
1549 /// ordinary name lookup.
1550 bool ResultBuilder::IsOrdinaryNonValueName(const NamedDecl *ND) const {
1551   ND = ND->getUnderlyingDecl();
1552 
1553   unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1554   if (SemaRef.getLangOpts().CPlusPlus)
1555     IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
1556 
1557   return (ND->getIdentifierNamespace() & IDNS) && !isa<ValueDecl>(ND) &&
1558          !isa<FunctionTemplateDecl>(ND) && !isa<ObjCPropertyDecl>(ND);
1559 }
1560 
1561 /// Determines whether the given declaration is suitable as the
1562 /// start of a C++ nested-name-specifier, e.g., a class or namespace.
1563 bool ResultBuilder::IsNestedNameSpecifier(const NamedDecl *ND) const {
1564   // Allow us to find class templates, too.
1565   if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1566     ND = ClassTemplate->getTemplatedDecl();
1567 
1568   return SemaRef.isAcceptableNestedNameSpecifier(ND);
1569 }
1570 
1571 /// Determines whether the given declaration is an enumeration.
1572 bool ResultBuilder::IsEnum(const NamedDecl *ND) const {
1573   return isa<EnumDecl>(ND);
1574 }
1575 
1576 /// Determines whether the given declaration is a class or struct.
1577 bool ResultBuilder::IsClassOrStruct(const NamedDecl *ND) const {
1578   // Allow us to find class templates, too.
1579   if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1580     ND = ClassTemplate->getTemplatedDecl();
1581 
1582   // For purposes of this check, interfaces match too.
1583   if (const auto *RD = dyn_cast<RecordDecl>(ND))
1584     return RD->getTagKind() == TagTypeKind::Class ||
1585            RD->getTagKind() == TagTypeKind::Struct ||
1586            RD->getTagKind() == TagTypeKind::Interface;
1587 
1588   return false;
1589 }
1590 
1591 /// Determines whether the given declaration is a union.
1592 bool ResultBuilder::IsUnion(const NamedDecl *ND) const {
1593   // Allow us to find class templates, too.
1594   if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1595     ND = ClassTemplate->getTemplatedDecl();
1596 
1597   if (const auto *RD = dyn_cast<RecordDecl>(ND))
1598     return RD->getTagKind() == TagTypeKind::Union;
1599 
1600   return false;
1601 }
1602 
1603 /// Determines whether the given declaration is a namespace.
1604 bool ResultBuilder::IsNamespace(const NamedDecl *ND) const {
1605   return isa<NamespaceDecl>(ND);
1606 }
1607 
1608 /// Determines whether the given declaration is a namespace or
1609 /// namespace alias.
1610 bool ResultBuilder::IsNamespaceOrAlias(const NamedDecl *ND) const {
1611   return isa<NamespaceDecl>(ND->getUnderlyingDecl());
1612 }
1613 
1614 /// Determines whether the given declaration is a type.
1615 bool ResultBuilder::IsType(const NamedDecl *ND) const {
1616   ND = ND->getUnderlyingDecl();
1617   return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1618 }
1619 
1620 /// Determines which members of a class should be visible via
1621 /// "." or "->".  Only value declarations, nested name specifiers, and
1622 /// using declarations thereof should show up.
1623 bool ResultBuilder::IsMember(const NamedDecl *ND) const {
1624   ND = ND->getUnderlyingDecl();
1625   return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
1626          isa<ObjCPropertyDecl>(ND);
1627 }
1628 
1629 static bool isObjCReceiverType(ASTContext &C, QualType T) {
1630   T = C.getCanonicalType(T);
1631   switch (T->getTypeClass()) {
1632   case Type::ObjCObject:
1633   case Type::ObjCInterface:
1634   case Type::ObjCObjectPointer:
1635     return true;
1636 
1637   case Type::Builtin:
1638     switch (cast<BuiltinType>(T)->getKind()) {
1639     case BuiltinType::ObjCId:
1640     case BuiltinType::ObjCClass:
1641     case BuiltinType::ObjCSel:
1642       return true;
1643 
1644     default:
1645       break;
1646     }
1647     return false;
1648 
1649   default:
1650     break;
1651   }
1652 
1653   if (!C.getLangOpts().CPlusPlus)
1654     return false;
1655 
1656   // FIXME: We could perform more analysis here to determine whether a
1657   // particular class type has any conversions to Objective-C types. For now,
1658   // just accept all class types.
1659   return T->isDependentType() || T->isRecordType();
1660 }
1661 
1662 bool ResultBuilder::IsObjCMessageReceiver(const NamedDecl *ND) const {
1663   QualType T = getDeclUsageType(SemaRef.Context, ND);
1664   if (T.isNull())
1665     return false;
1666 
1667   T = SemaRef.Context.getBaseElementType(T);
1668   return isObjCReceiverType(SemaRef.Context, T);
1669 }
1670 
1671 bool ResultBuilder::IsObjCMessageReceiverOrLambdaCapture(
1672     const NamedDecl *ND) const {
1673   if (IsObjCMessageReceiver(ND))
1674     return true;
1675 
1676   const auto *Var = dyn_cast<VarDecl>(ND);
1677   if (!Var)
1678     return false;
1679 
1680   return Var->hasLocalStorage() && !Var->hasAttr<BlocksAttr>();
1681 }
1682 
1683 bool ResultBuilder::IsObjCCollection(const NamedDecl *ND) const {
1684   if ((SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryName(ND)) ||
1685       (!SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1686     return false;
1687 
1688   QualType T = getDeclUsageType(SemaRef.Context, ND);
1689   if (T.isNull())
1690     return false;
1691 
1692   T = SemaRef.Context.getBaseElementType(T);
1693   return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1694          T->isObjCIdType() ||
1695          (SemaRef.getLangOpts().CPlusPlus && T->isRecordType());
1696 }
1697 
1698 bool ResultBuilder::IsImpossibleToSatisfy(const NamedDecl *ND) const {
1699   return false;
1700 }
1701 
1702 /// Determines whether the given declaration is an Objective-C
1703 /// instance variable.
1704 bool ResultBuilder::IsObjCIvar(const NamedDecl *ND) const {
1705   return isa<ObjCIvarDecl>(ND);
1706 }
1707 
1708 namespace {
1709 
1710 /// Visible declaration consumer that adds a code-completion result
1711 /// for each visible declaration.
1712 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1713   ResultBuilder &Results;
1714   DeclContext *InitialLookupCtx;
1715   // NamingClass and BaseType are used for access-checking. See
1716   // Sema::IsSimplyAccessible for details.
1717   CXXRecordDecl *NamingClass;
1718   QualType BaseType;
1719   std::vector<FixItHint> FixIts;
1720 
1721 public:
1722   CodeCompletionDeclConsumer(
1723       ResultBuilder &Results, DeclContext *InitialLookupCtx,
1724       QualType BaseType = QualType(),
1725       std::vector<FixItHint> FixIts = std::vector<FixItHint>())
1726       : Results(Results), InitialLookupCtx(InitialLookupCtx),
1727         FixIts(std::move(FixIts)) {
1728     NamingClass = llvm::dyn_cast<CXXRecordDecl>(InitialLookupCtx);
1729     // If BaseType was not provided explicitly, emulate implicit 'this->'.
1730     if (BaseType.isNull()) {
1731       auto ThisType = Results.getSema().getCurrentThisType();
1732       if (!ThisType.isNull()) {
1733         assert(ThisType->isPointerType());
1734         BaseType = ThisType->getPointeeType();
1735         if (!NamingClass)
1736           NamingClass = BaseType->getAsCXXRecordDecl();
1737       }
1738     }
1739     this->BaseType = BaseType;
1740   }
1741 
1742   void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
1743                  bool InBaseClass) override {
1744     ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr,
1745                                  false, IsAccessible(ND, Ctx), FixIts);
1746     Results.AddResult(Result, InitialLookupCtx, Hiding, InBaseClass, BaseType);
1747   }
1748 
1749   void EnteredContext(DeclContext *Ctx) override {
1750     Results.addVisitedContext(Ctx);
1751   }
1752 
1753 private:
1754   bool IsAccessible(NamedDecl *ND, DeclContext *Ctx) {
1755     // Naming class to use for access check. In most cases it was provided
1756     // explicitly (e.g. member access (lhs.foo) or qualified lookup (X::)),
1757     // for unqualified lookup we fallback to the \p Ctx in which we found the
1758     // member.
1759     auto *NamingClass = this->NamingClass;
1760     QualType BaseType = this->BaseType;
1761     if (auto *Cls = llvm::dyn_cast_or_null<CXXRecordDecl>(Ctx)) {
1762       if (!NamingClass)
1763         NamingClass = Cls;
1764       // When we emulate implicit 'this->' in an unqualified lookup, we might
1765       // end up with an invalid naming class. In that case, we avoid emulating
1766       // 'this->' qualifier to satisfy preconditions of the access checking.
1767       if (NamingClass->getCanonicalDecl() != Cls->getCanonicalDecl() &&
1768           !NamingClass->isDerivedFrom(Cls)) {
1769         NamingClass = Cls;
1770         BaseType = QualType();
1771       }
1772     } else {
1773       // The decl was found outside the C++ class, so only ObjC access checks
1774       // apply. Those do not rely on NamingClass and BaseType, so we clear them
1775       // out.
1776       NamingClass = nullptr;
1777       BaseType = QualType();
1778     }
1779     return Results.getSema().IsSimplyAccessible(ND, NamingClass, BaseType);
1780   }
1781 };
1782 } // namespace
1783 
1784 /// Add type specifiers for the current language as keyword results.
1785 static void AddTypeSpecifierResults(const LangOptions &LangOpts,
1786                                     ResultBuilder &Results) {
1787   typedef CodeCompletionResult Result;
1788   Results.AddResult(Result("short", CCP_Type));
1789   Results.AddResult(Result("long", CCP_Type));
1790   Results.AddResult(Result("signed", CCP_Type));
1791   Results.AddResult(Result("unsigned", CCP_Type));
1792   Results.AddResult(Result("void", CCP_Type));
1793   Results.AddResult(Result("char", CCP_Type));
1794   Results.AddResult(Result("int", CCP_Type));
1795   Results.AddResult(Result("float", CCP_Type));
1796   Results.AddResult(Result("double", CCP_Type));
1797   Results.AddResult(Result("enum", CCP_Type));
1798   Results.AddResult(Result("struct", CCP_Type));
1799   Results.AddResult(Result("union", CCP_Type));
1800   Results.AddResult(Result("const", CCP_Type));
1801   Results.AddResult(Result("volatile", CCP_Type));
1802 
1803   if (LangOpts.C99) {
1804     // C99-specific
1805     Results.AddResult(Result("_Complex", CCP_Type));
1806     Results.AddResult(Result("_Imaginary", CCP_Type));
1807     Results.AddResult(Result("_Bool", CCP_Type));
1808     Results.AddResult(Result("restrict", CCP_Type));
1809   }
1810 
1811   CodeCompletionBuilder Builder(Results.getAllocator(),
1812                                 Results.getCodeCompletionTUInfo());
1813   if (LangOpts.CPlusPlus) {
1814     // C++-specific
1815     Results.AddResult(
1816         Result("bool", CCP_Type + (LangOpts.ObjC ? CCD_bool_in_ObjC : 0)));
1817     Results.AddResult(Result("class", CCP_Type));
1818     Results.AddResult(Result("wchar_t", CCP_Type));
1819 
1820     // typename name
1821     Builder.AddTypedTextChunk("typename");
1822     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1823     Builder.AddPlaceholderChunk("name");
1824     Results.AddResult(Result(Builder.TakeString()));
1825 
1826     if (LangOpts.CPlusPlus11) {
1827       Results.AddResult(Result("auto", CCP_Type));
1828       Results.AddResult(Result("char16_t", CCP_Type));
1829       Results.AddResult(Result("char32_t", CCP_Type));
1830 
1831       Builder.AddTypedTextChunk("decltype");
1832       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1833       Builder.AddPlaceholderChunk("expression");
1834       Builder.AddChunk(CodeCompletionString::CK_RightParen);
1835       Results.AddResult(Result(Builder.TakeString()));
1836     }
1837   } else
1838     Results.AddResult(Result("__auto_type", CCP_Type));
1839 
1840   // GNU keywords
1841   if (LangOpts.GNUKeywords) {
1842     // FIXME: Enable when we actually support decimal floating point.
1843     //    Results.AddResult(Result("_Decimal32"));
1844     //    Results.AddResult(Result("_Decimal64"));
1845     //    Results.AddResult(Result("_Decimal128"));
1846 
1847     Builder.AddTypedTextChunk("typeof");
1848     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1849     Builder.AddPlaceholderChunk("expression");
1850     Results.AddResult(Result(Builder.TakeString()));
1851 
1852     Builder.AddTypedTextChunk("typeof");
1853     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1854     Builder.AddPlaceholderChunk("type");
1855     Builder.AddChunk(CodeCompletionString::CK_RightParen);
1856     Results.AddResult(Result(Builder.TakeString()));
1857   }
1858 
1859   // Nullability
1860   Results.AddResult(Result("_Nonnull", CCP_Type));
1861   Results.AddResult(Result("_Null_unspecified", CCP_Type));
1862   Results.AddResult(Result("_Nullable", CCP_Type));
1863 }
1864 
1865 static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
1866                                  const LangOptions &LangOpts,
1867                                  ResultBuilder &Results) {
1868   typedef CodeCompletionResult Result;
1869   // Note: we don't suggest either "auto" or "register", because both
1870   // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1871   // in C++0x as a type specifier.
1872   Results.AddResult(Result("extern"));
1873   Results.AddResult(Result("static"));
1874 
1875   if (LangOpts.CPlusPlus11) {
1876     CodeCompletionAllocator &Allocator = Results.getAllocator();
1877     CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
1878 
1879     // alignas
1880     Builder.AddTypedTextChunk("alignas");
1881     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1882     Builder.AddPlaceholderChunk("expression");
1883     Builder.AddChunk(CodeCompletionString::CK_RightParen);
1884     Results.AddResult(Result(Builder.TakeString()));
1885 
1886     Results.AddResult(Result("constexpr"));
1887     Results.AddResult(Result("thread_local"));
1888   }
1889 }
1890 
1891 static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
1892                                   const LangOptions &LangOpts,
1893                                   ResultBuilder &Results) {
1894   typedef CodeCompletionResult Result;
1895   switch (CCC) {
1896   case Sema::PCC_Class:
1897   case Sema::PCC_MemberTemplate:
1898     if (LangOpts.CPlusPlus) {
1899       Results.AddResult(Result("explicit"));
1900       Results.AddResult(Result("friend"));
1901       Results.AddResult(Result("mutable"));
1902       Results.AddResult(Result("virtual"));
1903     }
1904     [[fallthrough]];
1905 
1906   case Sema::PCC_ObjCInterface:
1907   case Sema::PCC_ObjCImplementation:
1908   case Sema::PCC_Namespace:
1909   case Sema::PCC_Template:
1910     if (LangOpts.CPlusPlus || LangOpts.C99)
1911       Results.AddResult(Result("inline"));
1912     break;
1913 
1914   case Sema::PCC_ObjCInstanceVariableList:
1915   case Sema::PCC_Expression:
1916   case Sema::PCC_Statement:
1917   case Sema::PCC_TopLevelOrExpression:
1918   case Sema::PCC_ForInit:
1919   case Sema::PCC_Condition:
1920   case Sema::PCC_RecoveryInFunction:
1921   case Sema::PCC_Type:
1922   case Sema::PCC_ParenthesizedExpression:
1923   case Sema::PCC_LocalDeclarationSpecifiers:
1924     break;
1925   }
1926 }
1927 
1928 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1929 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1930 static void AddObjCVisibilityResults(const LangOptions &LangOpts,
1931                                      ResultBuilder &Results, bool NeedAt);
1932 static void AddObjCImplementationResults(const LangOptions &LangOpts,
1933                                          ResultBuilder &Results, bool NeedAt);
1934 static void AddObjCInterfaceResults(const LangOptions &LangOpts,
1935                                     ResultBuilder &Results, bool NeedAt);
1936 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
1937 
1938 static void AddTypedefResult(ResultBuilder &Results) {
1939   CodeCompletionBuilder Builder(Results.getAllocator(),
1940                                 Results.getCodeCompletionTUInfo());
1941   Builder.AddTypedTextChunk("typedef");
1942   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1943   Builder.AddPlaceholderChunk("type");
1944   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1945   Builder.AddPlaceholderChunk("name");
1946   Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1947   Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1948 }
1949 
1950 // using name = type
1951 static void AddUsingAliasResult(CodeCompletionBuilder &Builder,
1952                                 ResultBuilder &Results) {
1953   Builder.AddTypedTextChunk("using");
1954   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1955   Builder.AddPlaceholderChunk("name");
1956   Builder.AddChunk(CodeCompletionString::CK_Equal);
1957   Builder.AddPlaceholderChunk("type");
1958   Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1959   Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1960 }
1961 
1962 static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
1963                                const LangOptions &LangOpts) {
1964   switch (CCC) {
1965   case Sema::PCC_Namespace:
1966   case Sema::PCC_Class:
1967   case Sema::PCC_ObjCInstanceVariableList:
1968   case Sema::PCC_Template:
1969   case Sema::PCC_MemberTemplate:
1970   case Sema::PCC_Statement:
1971   case Sema::PCC_RecoveryInFunction:
1972   case Sema::PCC_Type:
1973   case Sema::PCC_ParenthesizedExpression:
1974   case Sema::PCC_LocalDeclarationSpecifiers:
1975   case Sema::PCC_TopLevelOrExpression:
1976     return true;
1977 
1978   case Sema::PCC_Expression:
1979   case Sema::PCC_Condition:
1980     return LangOpts.CPlusPlus;
1981 
1982   case Sema::PCC_ObjCInterface:
1983   case Sema::PCC_ObjCImplementation:
1984     return false;
1985 
1986   case Sema::PCC_ForInit:
1987     return LangOpts.CPlusPlus || LangOpts.ObjC || LangOpts.C99;
1988   }
1989 
1990   llvm_unreachable("Invalid ParserCompletionContext!");
1991 }
1992 
1993 static PrintingPolicy getCompletionPrintingPolicy(const ASTContext &Context,
1994                                                   const Preprocessor &PP) {
1995   PrintingPolicy Policy = Sema::getPrintingPolicy(Context, PP);
1996   Policy.AnonymousTagLocations = false;
1997   Policy.SuppressStrongLifetime = true;
1998   Policy.SuppressUnwrittenScope = true;
1999   Policy.SuppressScope = true;
2000   Policy.CleanUglifiedParameters = true;
2001   return Policy;
2002 }
2003 
2004 /// Retrieve a printing policy suitable for code completion.
2005 static PrintingPolicy getCompletionPrintingPolicy(Sema &S) {
2006   return getCompletionPrintingPolicy(S.Context, S.PP);
2007 }
2008 
2009 /// Retrieve the string representation of the given type as a string
2010 /// that has the appropriate lifetime for code completion.
2011 ///
2012 /// This routine provides a fast path where we provide constant strings for
2013 /// common type names.
2014 static const char *GetCompletionTypeString(QualType T, ASTContext &Context,
2015                                            const PrintingPolicy &Policy,
2016                                            CodeCompletionAllocator &Allocator) {
2017   if (!T.getLocalQualifiers()) {
2018     // Built-in type names are constant strings.
2019     if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
2020       return BT->getNameAsCString(Policy);
2021 
2022     // Anonymous tag types are constant strings.
2023     if (const TagType *TagT = dyn_cast<TagType>(T))
2024       if (TagDecl *Tag = TagT->getDecl())
2025         if (!Tag->hasNameForLinkage()) {
2026           switch (Tag->getTagKind()) {
2027           case TagTypeKind::Struct:
2028             return "struct <anonymous>";
2029           case TagTypeKind::Interface:
2030             return "__interface <anonymous>";
2031           case TagTypeKind::Class:
2032             return "class <anonymous>";
2033           case TagTypeKind::Union:
2034             return "union <anonymous>";
2035           case TagTypeKind::Enum:
2036             return "enum <anonymous>";
2037           }
2038         }
2039   }
2040 
2041   // Slow path: format the type as a string.
2042   std::string Result;
2043   T.getAsStringInternal(Result, Policy);
2044   return Allocator.CopyString(Result);
2045 }
2046 
2047 /// Add a completion for "this", if we're in a member function.
2048 static void addThisCompletion(Sema &S, ResultBuilder &Results) {
2049   QualType ThisTy = S.getCurrentThisType();
2050   if (ThisTy.isNull())
2051     return;
2052 
2053   CodeCompletionAllocator &Allocator = Results.getAllocator();
2054   CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
2055   PrintingPolicy Policy = getCompletionPrintingPolicy(S);
2056   Builder.AddResultTypeChunk(
2057       GetCompletionTypeString(ThisTy, S.Context, Policy, Allocator));
2058   Builder.AddTypedTextChunk("this");
2059   Results.AddResult(CodeCompletionResult(Builder.TakeString()));
2060 }
2061 
2062 static void AddStaticAssertResult(CodeCompletionBuilder &Builder,
2063                                   ResultBuilder &Results,
2064                                   const LangOptions &LangOpts) {
2065   if (!LangOpts.CPlusPlus11)
2066     return;
2067 
2068   Builder.AddTypedTextChunk("static_assert");
2069   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2070   Builder.AddPlaceholderChunk("expression");
2071   Builder.AddChunk(CodeCompletionString::CK_Comma);
2072   Builder.AddPlaceholderChunk("message");
2073   Builder.AddChunk(CodeCompletionString::CK_RightParen);
2074   Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2075   Results.AddResult(CodeCompletionResult(Builder.TakeString()));
2076 }
2077 
2078 static void AddOverrideResults(ResultBuilder &Results,
2079                                const CodeCompletionContext &CCContext,
2080                                CodeCompletionBuilder &Builder) {
2081   Sema &S = Results.getSema();
2082   const auto *CR = llvm::dyn_cast<CXXRecordDecl>(S.CurContext);
2083   // If not inside a class/struct/union return empty.
2084   if (!CR)
2085     return;
2086   // First store overrides within current class.
2087   // These are stored by name to make querying fast in the later step.
2088   llvm::StringMap<std::vector<FunctionDecl *>> Overrides;
2089   for (auto *Method : CR->methods()) {
2090     if (!Method->isVirtual() || !Method->getIdentifier())
2091       continue;
2092     Overrides[Method->getName()].push_back(Method);
2093   }
2094 
2095   for (const auto &Base : CR->bases()) {
2096     const auto *BR = Base.getType().getTypePtr()->getAsCXXRecordDecl();
2097     if (!BR)
2098       continue;
2099     for (auto *Method : BR->methods()) {
2100       if (!Method->isVirtual() || !Method->getIdentifier())
2101         continue;
2102       const auto it = Overrides.find(Method->getName());
2103       bool IsOverriden = false;
2104       if (it != Overrides.end()) {
2105         for (auto *MD : it->second) {
2106           // If the method in current body is not an overload of this virtual
2107           // function, then it overrides this one.
2108           if (!S.IsOverload(MD, Method, false)) {
2109             IsOverriden = true;
2110             break;
2111           }
2112         }
2113       }
2114       if (!IsOverriden) {
2115         // Generates a new CodeCompletionResult by taking this function and
2116         // converting it into an override declaration with only one chunk in the
2117         // final CodeCompletionString as a TypedTextChunk.
2118         std::string OverrideSignature;
2119         llvm::raw_string_ostream OS(OverrideSignature);
2120         CodeCompletionResult CCR(Method, 0);
2121         PrintingPolicy Policy =
2122             getCompletionPrintingPolicy(S.getASTContext(), S.getPreprocessor());
2123         auto *CCS = CCR.createCodeCompletionStringForOverride(
2124             S.getPreprocessor(), S.getASTContext(), Builder,
2125             /*IncludeBriefComments=*/false, CCContext, Policy);
2126         Results.AddResult(CodeCompletionResult(CCS, Method, CCP_CodePattern));
2127       }
2128     }
2129   }
2130 }
2131 
2132 /// Add language constructs that show up for "ordinary" names.
2133 static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, Scope *S,
2134                                    Sema &SemaRef, ResultBuilder &Results) {
2135   CodeCompletionAllocator &Allocator = Results.getAllocator();
2136   CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
2137 
2138   typedef CodeCompletionResult Result;
2139   switch (CCC) {
2140   case Sema::PCC_Namespace:
2141     if (SemaRef.getLangOpts().CPlusPlus) {
2142       if (Results.includeCodePatterns()) {
2143         // namespace <identifier> { declarations }
2144         Builder.AddTypedTextChunk("namespace");
2145         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2146         Builder.AddPlaceholderChunk("identifier");
2147         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2148         Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2149         Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2150         Builder.AddPlaceholderChunk("declarations");
2151         Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2152         Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2153         Results.AddResult(Result(Builder.TakeString()));
2154       }
2155 
2156       // namespace identifier = identifier ;
2157       Builder.AddTypedTextChunk("namespace");
2158       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2159       Builder.AddPlaceholderChunk("name");
2160       Builder.AddChunk(CodeCompletionString::CK_Equal);
2161       Builder.AddPlaceholderChunk("namespace");
2162       Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2163       Results.AddResult(Result(Builder.TakeString()));
2164 
2165       // Using directives
2166       Builder.AddTypedTextChunk("using namespace");
2167       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2168       Builder.AddPlaceholderChunk("identifier");
2169       Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2170       Results.AddResult(Result(Builder.TakeString()));
2171 
2172       // asm(string-literal)
2173       Builder.AddTypedTextChunk("asm");
2174       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2175       Builder.AddPlaceholderChunk("string-literal");
2176       Builder.AddChunk(CodeCompletionString::CK_RightParen);
2177       Results.AddResult(Result(Builder.TakeString()));
2178 
2179       if (Results.includeCodePatterns()) {
2180         // Explicit template instantiation
2181         Builder.AddTypedTextChunk("template");
2182         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2183         Builder.AddPlaceholderChunk("declaration");
2184         Results.AddResult(Result(Builder.TakeString()));
2185       } else {
2186         Results.AddResult(Result("template", CodeCompletionResult::RK_Keyword));
2187       }
2188     }
2189 
2190     if (SemaRef.getLangOpts().ObjC)
2191       AddObjCTopLevelResults(Results, true);
2192 
2193     AddTypedefResult(Results);
2194     [[fallthrough]];
2195 
2196   case Sema::PCC_Class:
2197     if (SemaRef.getLangOpts().CPlusPlus) {
2198       // Using declaration
2199       Builder.AddTypedTextChunk("using");
2200       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2201       Builder.AddPlaceholderChunk("qualifier");
2202       Builder.AddTextChunk("::");
2203       Builder.AddPlaceholderChunk("name");
2204       Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2205       Results.AddResult(Result(Builder.TakeString()));
2206 
2207       if (SemaRef.getLangOpts().CPlusPlus11)
2208         AddUsingAliasResult(Builder, Results);
2209 
2210       // using typename qualifier::name (only in a dependent context)
2211       if (SemaRef.CurContext->isDependentContext()) {
2212         Builder.AddTypedTextChunk("using typename");
2213         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2214         Builder.AddPlaceholderChunk("qualifier");
2215         Builder.AddTextChunk("::");
2216         Builder.AddPlaceholderChunk("name");
2217         Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2218         Results.AddResult(Result(Builder.TakeString()));
2219       }
2220 
2221       AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts());
2222 
2223       if (CCC == Sema::PCC_Class) {
2224         AddTypedefResult(Results);
2225 
2226         bool IsNotInheritanceScope = !S->isClassInheritanceScope();
2227         // public:
2228         Builder.AddTypedTextChunk("public");
2229         if (IsNotInheritanceScope && Results.includeCodePatterns())
2230           Builder.AddChunk(CodeCompletionString::CK_Colon);
2231         Results.AddResult(Result(Builder.TakeString()));
2232 
2233         // protected:
2234         Builder.AddTypedTextChunk("protected");
2235         if (IsNotInheritanceScope && Results.includeCodePatterns())
2236           Builder.AddChunk(CodeCompletionString::CK_Colon);
2237         Results.AddResult(Result(Builder.TakeString()));
2238 
2239         // private:
2240         Builder.AddTypedTextChunk("private");
2241         if (IsNotInheritanceScope && Results.includeCodePatterns())
2242           Builder.AddChunk(CodeCompletionString::CK_Colon);
2243         Results.AddResult(Result(Builder.TakeString()));
2244 
2245         // FIXME: This adds override results only if we are at the first word of
2246         // the declaration/definition. Also call this from other sides to have
2247         // more use-cases.
2248         AddOverrideResults(Results, CodeCompletionContext::CCC_ClassStructUnion,
2249                            Builder);
2250       }
2251     }
2252     [[fallthrough]];
2253 
2254   case Sema::PCC_Template:
2255   case Sema::PCC_MemberTemplate:
2256     if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns()) {
2257       // template < parameters >
2258       Builder.AddTypedTextChunk("template");
2259       Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2260       Builder.AddPlaceholderChunk("parameters");
2261       Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2262       Results.AddResult(Result(Builder.TakeString()));
2263     } else {
2264       Results.AddResult(Result("template", CodeCompletionResult::RK_Keyword));
2265     }
2266 
2267     AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2268     AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2269     break;
2270 
2271   case Sema::PCC_ObjCInterface:
2272     AddObjCInterfaceResults(SemaRef.getLangOpts(), Results, true);
2273     AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2274     AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2275     break;
2276 
2277   case Sema::PCC_ObjCImplementation:
2278     AddObjCImplementationResults(SemaRef.getLangOpts(), Results, true);
2279     AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2280     AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2281     break;
2282 
2283   case Sema::PCC_ObjCInstanceVariableList:
2284     AddObjCVisibilityResults(SemaRef.getLangOpts(), Results, true);
2285     break;
2286 
2287   case Sema::PCC_RecoveryInFunction:
2288   case Sema::PCC_TopLevelOrExpression:
2289   case Sema::PCC_Statement: {
2290     if (SemaRef.getLangOpts().CPlusPlus11)
2291       AddUsingAliasResult(Builder, Results);
2292 
2293     AddTypedefResult(Results);
2294 
2295     if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns() &&
2296         SemaRef.getLangOpts().CXXExceptions) {
2297       Builder.AddTypedTextChunk("try");
2298       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2299       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2300       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2301       Builder.AddPlaceholderChunk("statements");
2302       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2303       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2304       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2305       Builder.AddTextChunk("catch");
2306       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2307       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2308       Builder.AddPlaceholderChunk("declaration");
2309       Builder.AddChunk(CodeCompletionString::CK_RightParen);
2310       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2311       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2312       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2313       Builder.AddPlaceholderChunk("statements");
2314       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2315       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2316       Results.AddResult(Result(Builder.TakeString()));
2317     }
2318     if (SemaRef.getLangOpts().ObjC)
2319       AddObjCStatementResults(Results, true);
2320 
2321     if (Results.includeCodePatterns()) {
2322       // if (condition) { statements }
2323       Builder.AddTypedTextChunk("if");
2324       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2325       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2326       if (SemaRef.getLangOpts().CPlusPlus)
2327         Builder.AddPlaceholderChunk("condition");
2328       else
2329         Builder.AddPlaceholderChunk("expression");
2330       Builder.AddChunk(CodeCompletionString::CK_RightParen);
2331       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2332       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2333       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2334       Builder.AddPlaceholderChunk("statements");
2335       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2336       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2337       Results.AddResult(Result(Builder.TakeString()));
2338 
2339       // switch (condition) { }
2340       Builder.AddTypedTextChunk("switch");
2341       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2342       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2343       if (SemaRef.getLangOpts().CPlusPlus)
2344         Builder.AddPlaceholderChunk("condition");
2345       else
2346         Builder.AddPlaceholderChunk("expression");
2347       Builder.AddChunk(CodeCompletionString::CK_RightParen);
2348       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2349       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2350       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2351       Builder.AddPlaceholderChunk("cases");
2352       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2353       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2354       Results.AddResult(Result(Builder.TakeString()));
2355     }
2356 
2357     // Switch-specific statements.
2358     if (SemaRef.getCurFunction() &&
2359         !SemaRef.getCurFunction()->SwitchStack.empty()) {
2360       // case expression:
2361       Builder.AddTypedTextChunk("case");
2362       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2363       Builder.AddPlaceholderChunk("expression");
2364       Builder.AddChunk(CodeCompletionString::CK_Colon);
2365       Results.AddResult(Result(Builder.TakeString()));
2366 
2367       // default:
2368       Builder.AddTypedTextChunk("default");
2369       Builder.AddChunk(CodeCompletionString::CK_Colon);
2370       Results.AddResult(Result(Builder.TakeString()));
2371     }
2372 
2373     if (Results.includeCodePatterns()) {
2374       /// while (condition) { statements }
2375       Builder.AddTypedTextChunk("while");
2376       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2377       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2378       if (SemaRef.getLangOpts().CPlusPlus)
2379         Builder.AddPlaceholderChunk("condition");
2380       else
2381         Builder.AddPlaceholderChunk("expression");
2382       Builder.AddChunk(CodeCompletionString::CK_RightParen);
2383       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2384       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2385       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2386       Builder.AddPlaceholderChunk("statements");
2387       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2388       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2389       Results.AddResult(Result(Builder.TakeString()));
2390 
2391       // do { statements } while ( expression );
2392       Builder.AddTypedTextChunk("do");
2393       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2394       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2395       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2396       Builder.AddPlaceholderChunk("statements");
2397       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2398       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2399       Builder.AddTextChunk("while");
2400       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2401       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2402       Builder.AddPlaceholderChunk("expression");
2403       Builder.AddChunk(CodeCompletionString::CK_RightParen);
2404       Results.AddResult(Result(Builder.TakeString()));
2405 
2406       // for ( for-init-statement ; condition ; expression ) { statements }
2407       Builder.AddTypedTextChunk("for");
2408       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2409       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2410       if (SemaRef.getLangOpts().CPlusPlus || SemaRef.getLangOpts().C99)
2411         Builder.AddPlaceholderChunk("init-statement");
2412       else
2413         Builder.AddPlaceholderChunk("init-expression");
2414       Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2415       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2416       Builder.AddPlaceholderChunk("condition");
2417       Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2418       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2419       Builder.AddPlaceholderChunk("inc-expression");
2420       Builder.AddChunk(CodeCompletionString::CK_RightParen);
2421       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2422       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2423       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2424       Builder.AddPlaceholderChunk("statements");
2425       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2426       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2427       Results.AddResult(Result(Builder.TakeString()));
2428 
2429       if (SemaRef.getLangOpts().CPlusPlus11 || SemaRef.getLangOpts().ObjC) {
2430         // for ( range_declaration (:|in) range_expression ) { statements }
2431         Builder.AddTypedTextChunk("for");
2432         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2433         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2434         Builder.AddPlaceholderChunk("range-declaration");
2435         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2436         if (SemaRef.getLangOpts().ObjC)
2437           Builder.AddTextChunk("in");
2438         else
2439           Builder.AddChunk(CodeCompletionString::CK_Colon);
2440         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2441         Builder.AddPlaceholderChunk("range-expression");
2442         Builder.AddChunk(CodeCompletionString::CK_RightParen);
2443         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2444         Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2445         Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2446         Builder.AddPlaceholderChunk("statements");
2447         Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2448         Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2449         Results.AddResult(Result(Builder.TakeString()));
2450       }
2451     }
2452 
2453     if (S->getContinueParent()) {
2454       // continue ;
2455       Builder.AddTypedTextChunk("continue");
2456       Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2457       Results.AddResult(Result(Builder.TakeString()));
2458     }
2459 
2460     if (S->getBreakParent()) {
2461       // break ;
2462       Builder.AddTypedTextChunk("break");
2463       Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2464       Results.AddResult(Result(Builder.TakeString()));
2465     }
2466 
2467     // "return expression ;" or "return ;", depending on the return type.
2468     QualType ReturnType;
2469     if (const auto *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
2470       ReturnType = Function->getReturnType();
2471     else if (const auto *Method = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
2472       ReturnType = Method->getReturnType();
2473     else if (SemaRef.getCurBlock() &&
2474              !SemaRef.getCurBlock()->ReturnType.isNull())
2475       ReturnType = SemaRef.getCurBlock()->ReturnType;;
2476     if (ReturnType.isNull() || ReturnType->isVoidType()) {
2477       Builder.AddTypedTextChunk("return");
2478       Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2479       Results.AddResult(Result(Builder.TakeString()));
2480     } else {
2481       assert(!ReturnType.isNull());
2482       // "return expression ;"
2483       Builder.AddTypedTextChunk("return");
2484       Builder.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace);
2485       Builder.AddPlaceholderChunk("expression");
2486       Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2487       Results.AddResult(Result(Builder.TakeString()));
2488       // When boolean, also add 'return true;' and 'return false;'.
2489       if (ReturnType->isBooleanType()) {
2490         Builder.AddTypedTextChunk("return true");
2491         Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2492         Results.AddResult(Result(Builder.TakeString()));
2493 
2494         Builder.AddTypedTextChunk("return false");
2495         Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2496         Results.AddResult(Result(Builder.TakeString()));
2497       }
2498       // For pointers, suggest 'return nullptr' in C++.
2499       if (SemaRef.getLangOpts().CPlusPlus11 &&
2500           (ReturnType->isPointerType() || ReturnType->isMemberPointerType())) {
2501         Builder.AddTypedTextChunk("return nullptr");
2502         Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2503         Results.AddResult(Result(Builder.TakeString()));
2504       }
2505     }
2506 
2507     // goto identifier ;
2508     Builder.AddTypedTextChunk("goto");
2509     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2510     Builder.AddPlaceholderChunk("label");
2511     Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2512     Results.AddResult(Result(Builder.TakeString()));
2513 
2514     // Using directives
2515     Builder.AddTypedTextChunk("using namespace");
2516     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2517     Builder.AddPlaceholderChunk("identifier");
2518     Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2519     Results.AddResult(Result(Builder.TakeString()));
2520 
2521     AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts());
2522   }
2523     [[fallthrough]];
2524 
2525   // Fall through (for statement expressions).
2526   case Sema::PCC_ForInit:
2527   case Sema::PCC_Condition:
2528     AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2529     // Fall through: conditions and statements can have expressions.
2530     [[fallthrough]];
2531 
2532   case Sema::PCC_ParenthesizedExpression:
2533     if (SemaRef.getLangOpts().ObjCAutoRefCount &&
2534         CCC == Sema::PCC_ParenthesizedExpression) {
2535       // (__bridge <type>)<expression>
2536       Builder.AddTypedTextChunk("__bridge");
2537       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2538       Builder.AddPlaceholderChunk("type");
2539       Builder.AddChunk(CodeCompletionString::CK_RightParen);
2540       Builder.AddPlaceholderChunk("expression");
2541       Results.AddResult(Result(Builder.TakeString()));
2542 
2543       // (__bridge_transfer <Objective-C type>)<expression>
2544       Builder.AddTypedTextChunk("__bridge_transfer");
2545       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2546       Builder.AddPlaceholderChunk("Objective-C type");
2547       Builder.AddChunk(CodeCompletionString::CK_RightParen);
2548       Builder.AddPlaceholderChunk("expression");
2549       Results.AddResult(Result(Builder.TakeString()));
2550 
2551       // (__bridge_retained <CF type>)<expression>
2552       Builder.AddTypedTextChunk("__bridge_retained");
2553       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2554       Builder.AddPlaceholderChunk("CF type");
2555       Builder.AddChunk(CodeCompletionString::CK_RightParen);
2556       Builder.AddPlaceholderChunk("expression");
2557       Results.AddResult(Result(Builder.TakeString()));
2558     }
2559     // Fall through
2560     [[fallthrough]];
2561 
2562   case Sema::PCC_Expression: {
2563     if (SemaRef.getLangOpts().CPlusPlus) {
2564       // 'this', if we're in a non-static member function.
2565       addThisCompletion(SemaRef, Results);
2566 
2567       // true
2568       Builder.AddResultTypeChunk("bool");
2569       Builder.AddTypedTextChunk("true");
2570       Results.AddResult(Result(Builder.TakeString()));
2571 
2572       // false
2573       Builder.AddResultTypeChunk("bool");
2574       Builder.AddTypedTextChunk("false");
2575       Results.AddResult(Result(Builder.TakeString()));
2576 
2577       if (SemaRef.getLangOpts().RTTI) {
2578         // dynamic_cast < type-id > ( expression )
2579         Builder.AddTypedTextChunk("dynamic_cast");
2580         Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2581         Builder.AddPlaceholderChunk("type");
2582         Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2583         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2584         Builder.AddPlaceholderChunk("expression");
2585         Builder.AddChunk(CodeCompletionString::CK_RightParen);
2586         Results.AddResult(Result(Builder.TakeString()));
2587       }
2588 
2589       // static_cast < type-id > ( expression )
2590       Builder.AddTypedTextChunk("static_cast");
2591       Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2592       Builder.AddPlaceholderChunk("type");
2593       Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2594       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2595       Builder.AddPlaceholderChunk("expression");
2596       Builder.AddChunk(CodeCompletionString::CK_RightParen);
2597       Results.AddResult(Result(Builder.TakeString()));
2598 
2599       // reinterpret_cast < type-id > ( expression )
2600       Builder.AddTypedTextChunk("reinterpret_cast");
2601       Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2602       Builder.AddPlaceholderChunk("type");
2603       Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2604       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2605       Builder.AddPlaceholderChunk("expression");
2606       Builder.AddChunk(CodeCompletionString::CK_RightParen);
2607       Results.AddResult(Result(Builder.TakeString()));
2608 
2609       // const_cast < type-id > ( expression )
2610       Builder.AddTypedTextChunk("const_cast");
2611       Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2612       Builder.AddPlaceholderChunk("type");
2613       Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2614       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2615       Builder.AddPlaceholderChunk("expression");
2616       Builder.AddChunk(CodeCompletionString::CK_RightParen);
2617       Results.AddResult(Result(Builder.TakeString()));
2618 
2619       if (SemaRef.getLangOpts().RTTI) {
2620         // typeid ( expression-or-type )
2621         Builder.AddResultTypeChunk("std::type_info");
2622         Builder.AddTypedTextChunk("typeid");
2623         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2624         Builder.AddPlaceholderChunk("expression-or-type");
2625         Builder.AddChunk(CodeCompletionString::CK_RightParen);
2626         Results.AddResult(Result(Builder.TakeString()));
2627       }
2628 
2629       // new T ( ... )
2630       Builder.AddTypedTextChunk("new");
2631       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2632       Builder.AddPlaceholderChunk("type");
2633       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2634       Builder.AddPlaceholderChunk("expressions");
2635       Builder.AddChunk(CodeCompletionString::CK_RightParen);
2636       Results.AddResult(Result(Builder.TakeString()));
2637 
2638       // new T [ ] ( ... )
2639       Builder.AddTypedTextChunk("new");
2640       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2641       Builder.AddPlaceholderChunk("type");
2642       Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
2643       Builder.AddPlaceholderChunk("size");
2644       Builder.AddChunk(CodeCompletionString::CK_RightBracket);
2645       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2646       Builder.AddPlaceholderChunk("expressions");
2647       Builder.AddChunk(CodeCompletionString::CK_RightParen);
2648       Results.AddResult(Result(Builder.TakeString()));
2649 
2650       // delete expression
2651       Builder.AddResultTypeChunk("void");
2652       Builder.AddTypedTextChunk("delete");
2653       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2654       Builder.AddPlaceholderChunk("expression");
2655       Results.AddResult(Result(Builder.TakeString()));
2656 
2657       // delete [] expression
2658       Builder.AddResultTypeChunk("void");
2659       Builder.AddTypedTextChunk("delete");
2660       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2661       Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
2662       Builder.AddChunk(CodeCompletionString::CK_RightBracket);
2663       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2664       Builder.AddPlaceholderChunk("expression");
2665       Results.AddResult(Result(Builder.TakeString()));
2666 
2667       if (SemaRef.getLangOpts().CXXExceptions) {
2668         // throw expression
2669         Builder.AddResultTypeChunk("void");
2670         Builder.AddTypedTextChunk("throw");
2671         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2672         Builder.AddPlaceholderChunk("expression");
2673         Results.AddResult(Result(Builder.TakeString()));
2674       }
2675 
2676       // FIXME: Rethrow?
2677 
2678       if (SemaRef.getLangOpts().CPlusPlus11) {
2679         // nullptr
2680         Builder.AddResultTypeChunk("std::nullptr_t");
2681         Builder.AddTypedTextChunk("nullptr");
2682         Results.AddResult(Result(Builder.TakeString()));
2683 
2684         // alignof
2685         Builder.AddResultTypeChunk("size_t");
2686         Builder.AddTypedTextChunk("alignof");
2687         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2688         Builder.AddPlaceholderChunk("type");
2689         Builder.AddChunk(CodeCompletionString::CK_RightParen);
2690         Results.AddResult(Result(Builder.TakeString()));
2691 
2692         // noexcept
2693         Builder.AddResultTypeChunk("bool");
2694         Builder.AddTypedTextChunk("noexcept");
2695         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2696         Builder.AddPlaceholderChunk("expression");
2697         Builder.AddChunk(CodeCompletionString::CK_RightParen);
2698         Results.AddResult(Result(Builder.TakeString()));
2699 
2700         // sizeof... expression
2701         Builder.AddResultTypeChunk("size_t");
2702         Builder.AddTypedTextChunk("sizeof...");
2703         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2704         Builder.AddPlaceholderChunk("parameter-pack");
2705         Builder.AddChunk(CodeCompletionString::CK_RightParen);
2706         Results.AddResult(Result(Builder.TakeString()));
2707       }
2708     }
2709 
2710     if (SemaRef.getLangOpts().ObjC) {
2711       // Add "super", if we're in an Objective-C class with a superclass.
2712       if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
2713         // The interface can be NULL.
2714         if (ObjCInterfaceDecl *ID = Method->getClassInterface())
2715           if (ID->getSuperClass()) {
2716             std::string SuperType;
2717             SuperType = ID->getSuperClass()->getNameAsString();
2718             if (Method->isInstanceMethod())
2719               SuperType += " *";
2720 
2721             Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
2722             Builder.AddTypedTextChunk("super");
2723             Results.AddResult(Result(Builder.TakeString()));
2724           }
2725       }
2726 
2727       AddObjCExpressionResults(Results, true);
2728     }
2729 
2730     if (SemaRef.getLangOpts().C11) {
2731       // _Alignof
2732       Builder.AddResultTypeChunk("size_t");
2733       if (SemaRef.PP.isMacroDefined("alignof"))
2734         Builder.AddTypedTextChunk("alignof");
2735       else
2736         Builder.AddTypedTextChunk("_Alignof");
2737       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2738       Builder.AddPlaceholderChunk("type");
2739       Builder.AddChunk(CodeCompletionString::CK_RightParen);
2740       Results.AddResult(Result(Builder.TakeString()));
2741     }
2742 
2743     if (SemaRef.getLangOpts().C23) {
2744       // nullptr
2745       Builder.AddResultTypeChunk("nullptr_t");
2746       Builder.AddTypedTextChunk("nullptr");
2747       Results.AddResult(Result(Builder.TakeString()));
2748     }
2749 
2750     // sizeof expression
2751     Builder.AddResultTypeChunk("size_t");
2752     Builder.AddTypedTextChunk("sizeof");
2753     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2754     Builder.AddPlaceholderChunk("expression-or-type");
2755     Builder.AddChunk(CodeCompletionString::CK_RightParen);
2756     Results.AddResult(Result(Builder.TakeString()));
2757     break;
2758   }
2759 
2760   case Sema::PCC_Type:
2761   case Sema::PCC_LocalDeclarationSpecifiers:
2762     break;
2763   }
2764 
2765   if (WantTypesInContext(CCC, SemaRef.getLangOpts()))
2766     AddTypeSpecifierResults(SemaRef.getLangOpts(), Results);
2767 
2768   if (SemaRef.getLangOpts().CPlusPlus && CCC != Sema::PCC_Type)
2769     Results.AddResult(Result("operator"));
2770 }
2771 
2772 /// If the given declaration has an associated type, add it as a result
2773 /// type chunk.
2774 static void AddResultTypeChunk(ASTContext &Context,
2775                                const PrintingPolicy &Policy,
2776                                const NamedDecl *ND, QualType BaseType,
2777                                CodeCompletionBuilder &Result) {
2778   if (!ND)
2779     return;
2780 
2781   // Skip constructors and conversion functions, which have their return types
2782   // built into their names.
2783   if (isConstructor(ND) || isa<CXXConversionDecl>(ND))
2784     return;
2785 
2786   // Determine the type of the declaration (if it has a type).
2787   QualType T;
2788   if (const FunctionDecl *Function = ND->getAsFunction())
2789     T = Function->getReturnType();
2790   else if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND)) {
2791     if (!BaseType.isNull())
2792       T = Method->getSendResultType(BaseType);
2793     else
2794       T = Method->getReturnType();
2795   } else if (const auto *Enumerator = dyn_cast<EnumConstantDecl>(ND)) {
2796     T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
2797     T = clang::TypeName::getFullyQualifiedType(T, Context);
2798   } else if (isa<UnresolvedUsingValueDecl>(ND)) {
2799     /* Do nothing: ignore unresolved using declarations*/
2800   } else if (const auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
2801     if (!BaseType.isNull())
2802       T = Ivar->getUsageType(BaseType);
2803     else
2804       T = Ivar->getType();
2805   } else if (const auto *Value = dyn_cast<ValueDecl>(ND)) {
2806     T = Value->getType();
2807   } else if (const auto *Property = dyn_cast<ObjCPropertyDecl>(ND)) {
2808     if (!BaseType.isNull())
2809       T = Property->getUsageType(BaseType);
2810     else
2811       T = Property->getType();
2812   }
2813 
2814   if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
2815     return;
2816 
2817   Result.AddResultTypeChunk(
2818       GetCompletionTypeString(T, Context, Policy, Result.getAllocator()));
2819 }
2820 
2821 static void MaybeAddSentinel(Preprocessor &PP,
2822                              const NamedDecl *FunctionOrMethod,
2823                              CodeCompletionBuilder &Result) {
2824   if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
2825     if (Sentinel->getSentinel() == 0) {
2826       if (PP.getLangOpts().ObjC && PP.isMacroDefined("nil"))
2827         Result.AddTextChunk(", nil");
2828       else if (PP.isMacroDefined("NULL"))
2829         Result.AddTextChunk(", NULL");
2830       else
2831         Result.AddTextChunk(", (void*)0");
2832     }
2833 }
2834 
2835 static std::string formatObjCParamQualifiers(unsigned ObjCQuals,
2836                                              QualType &Type) {
2837   std::string Result;
2838   if (ObjCQuals & Decl::OBJC_TQ_In)
2839     Result += "in ";
2840   else if (ObjCQuals & Decl::OBJC_TQ_Inout)
2841     Result += "inout ";
2842   else if (ObjCQuals & Decl::OBJC_TQ_Out)
2843     Result += "out ";
2844   if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
2845     Result += "bycopy ";
2846   else if (ObjCQuals & Decl::OBJC_TQ_Byref)
2847     Result += "byref ";
2848   if (ObjCQuals & Decl::OBJC_TQ_Oneway)
2849     Result += "oneway ";
2850   if (ObjCQuals & Decl::OBJC_TQ_CSNullability) {
2851     if (auto nullability = AttributedType::stripOuterNullability(Type)) {
2852       switch (*nullability) {
2853       case NullabilityKind::NonNull:
2854         Result += "nonnull ";
2855         break;
2856 
2857       case NullabilityKind::Nullable:
2858         Result += "nullable ";
2859         break;
2860 
2861       case NullabilityKind::Unspecified:
2862         Result += "null_unspecified ";
2863         break;
2864 
2865       case NullabilityKind::NullableResult:
2866         llvm_unreachable("Not supported as a context-sensitive keyword!");
2867         break;
2868       }
2869     }
2870   }
2871   return Result;
2872 }
2873 
2874 /// Tries to find the most appropriate type location for an Objective-C
2875 /// block placeholder.
2876 ///
2877 /// This function ignores things like typedefs and qualifiers in order to
2878 /// present the most relevant and accurate block placeholders in code completion
2879 /// results.
2880 static void findTypeLocationForBlockDecl(const TypeSourceInfo *TSInfo,
2881                                          FunctionTypeLoc &Block,
2882                                          FunctionProtoTypeLoc &BlockProto,
2883                                          bool SuppressBlock = false) {
2884   if (!TSInfo)
2885     return;
2886   TypeLoc TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
2887   while (true) {
2888     // Look through typedefs.
2889     if (!SuppressBlock) {
2890       if (TypedefTypeLoc TypedefTL = TL.getAsAdjusted<TypedefTypeLoc>()) {
2891         if (TypeSourceInfo *InnerTSInfo =
2892                 TypedefTL.getTypedefNameDecl()->getTypeSourceInfo()) {
2893           TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2894           continue;
2895         }
2896       }
2897 
2898       // Look through qualified types
2899       if (QualifiedTypeLoc QualifiedTL = TL.getAs<QualifiedTypeLoc>()) {
2900         TL = QualifiedTL.getUnqualifiedLoc();
2901         continue;
2902       }
2903 
2904       if (AttributedTypeLoc AttrTL = TL.getAs<AttributedTypeLoc>()) {
2905         TL = AttrTL.getModifiedLoc();
2906         continue;
2907       }
2908     }
2909 
2910     // Try to get the function prototype behind the block pointer type,
2911     // then we're done.
2912     if (BlockPointerTypeLoc BlockPtr = TL.getAs<BlockPointerTypeLoc>()) {
2913       TL = BlockPtr.getPointeeLoc().IgnoreParens();
2914       Block = TL.getAs<FunctionTypeLoc>();
2915       BlockProto = TL.getAs<FunctionProtoTypeLoc>();
2916     }
2917     break;
2918   }
2919 }
2920 
2921 static std::string formatBlockPlaceholder(
2922     const PrintingPolicy &Policy, const NamedDecl *BlockDecl,
2923     FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto,
2924     bool SuppressBlockName = false, bool SuppressBlock = false,
2925     std::optional<ArrayRef<QualType>> ObjCSubsts = std::nullopt);
2926 
2927 static std::string FormatFunctionParameter(
2928     const PrintingPolicy &Policy, const DeclaratorDecl *Param,
2929     bool SuppressName = false, bool SuppressBlock = false,
2930     std::optional<ArrayRef<QualType>> ObjCSubsts = std::nullopt) {
2931   // Params are unavailable in FunctionTypeLoc if the FunctionType is invalid.
2932   // It would be better to pass in the param Type, which is usually available.
2933   // But this case is rare, so just pretend we fell back to int as elsewhere.
2934   if (!Param)
2935     return "int";
2936   Decl::ObjCDeclQualifier ObjCQual = Decl::OBJC_TQ_None;
2937   if (const auto *PVD = dyn_cast<ParmVarDecl>(Param))
2938     ObjCQual = PVD->getObjCDeclQualifier();
2939   bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
2940   if (Param->getType()->isDependentType() ||
2941       !Param->getType()->isBlockPointerType()) {
2942     // The argument for a dependent or non-block parameter is a placeholder
2943     // containing that parameter's type.
2944     std::string Result;
2945 
2946     if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
2947       Result = std::string(Param->getIdentifier()->deuglifiedName());
2948 
2949     QualType Type = Param->getType();
2950     if (ObjCSubsts)
2951       Type = Type.substObjCTypeArgs(Param->getASTContext(), *ObjCSubsts,
2952                                     ObjCSubstitutionContext::Parameter);
2953     if (ObjCMethodParam) {
2954       Result = "(" + formatObjCParamQualifiers(ObjCQual, Type);
2955       Result += Type.getAsString(Policy) + ")";
2956       if (Param->getIdentifier() && !SuppressName)
2957         Result += Param->getIdentifier()->deuglifiedName();
2958     } else {
2959       Type.getAsStringInternal(Result, Policy);
2960     }
2961     return Result;
2962   }
2963 
2964   // The argument for a block pointer parameter is a block literal with
2965   // the appropriate type.
2966   FunctionTypeLoc Block;
2967   FunctionProtoTypeLoc BlockProto;
2968   findTypeLocationForBlockDecl(Param->getTypeSourceInfo(), Block, BlockProto,
2969                                SuppressBlock);
2970   // Try to retrieve the block type information from the property if this is a
2971   // parameter in a setter.
2972   if (!Block && ObjCMethodParam &&
2973       cast<ObjCMethodDecl>(Param->getDeclContext())->isPropertyAccessor()) {
2974     if (const auto *PD = cast<ObjCMethodDecl>(Param->getDeclContext())
2975                              ->findPropertyDecl(/*CheckOverrides=*/false))
2976       findTypeLocationForBlockDecl(PD->getTypeSourceInfo(), Block, BlockProto,
2977                                    SuppressBlock);
2978   }
2979 
2980   if (!Block) {
2981     // We were unable to find a FunctionProtoTypeLoc with parameter names
2982     // for the block; just use the parameter type as a placeholder.
2983     std::string Result;
2984     if (!ObjCMethodParam && Param->getIdentifier())
2985       Result = std::string(Param->getIdentifier()->deuglifiedName());
2986 
2987     QualType Type = Param->getType().getUnqualifiedType();
2988 
2989     if (ObjCMethodParam) {
2990       Result = Type.getAsString(Policy);
2991       std::string Quals = formatObjCParamQualifiers(ObjCQual, Type);
2992       if (!Quals.empty())
2993         Result = "(" + Quals + " " + Result + ")";
2994       if (Result.back() != ')')
2995         Result += " ";
2996       if (Param->getIdentifier())
2997         Result += Param->getIdentifier()->deuglifiedName();
2998     } else {
2999       Type.getAsStringInternal(Result, Policy);
3000     }
3001 
3002     return Result;
3003   }
3004 
3005   // We have the function prototype behind the block pointer type, as it was
3006   // written in the source.
3007   return formatBlockPlaceholder(Policy, Param, Block, BlockProto,
3008                                 /*SuppressBlockName=*/false, SuppressBlock,
3009                                 ObjCSubsts);
3010 }
3011 
3012 /// Returns a placeholder string that corresponds to an Objective-C block
3013 /// declaration.
3014 ///
3015 /// \param BlockDecl A declaration with an Objective-C block type.
3016 ///
3017 /// \param Block The most relevant type location for that block type.
3018 ///
3019 /// \param SuppressBlockName Determines whether or not the name of the block
3020 /// declaration is included in the resulting string.
3021 static std::string
3022 formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl,
3023                        FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto,
3024                        bool SuppressBlockName, bool SuppressBlock,
3025                        std::optional<ArrayRef<QualType>> ObjCSubsts) {
3026   std::string Result;
3027   QualType ResultType = Block.getTypePtr()->getReturnType();
3028   if (ObjCSubsts)
3029     ResultType =
3030         ResultType.substObjCTypeArgs(BlockDecl->getASTContext(), *ObjCSubsts,
3031                                      ObjCSubstitutionContext::Result);
3032   if (!ResultType->isVoidType() || SuppressBlock)
3033     ResultType.getAsStringInternal(Result, Policy);
3034 
3035   // Format the parameter list.
3036   std::string Params;
3037   if (!BlockProto || Block.getNumParams() == 0) {
3038     if (BlockProto && BlockProto.getTypePtr()->isVariadic())
3039       Params = "(...)";
3040     else
3041       Params = "(void)";
3042   } else {
3043     Params += "(";
3044     for (unsigned I = 0, N = Block.getNumParams(); I != N; ++I) {
3045       if (I)
3046         Params += ", ";
3047       Params += FormatFunctionParameter(Policy, Block.getParam(I),
3048                                         /*SuppressName=*/false,
3049                                         /*SuppressBlock=*/true, ObjCSubsts);
3050 
3051       if (I == N - 1 && BlockProto.getTypePtr()->isVariadic())
3052         Params += ", ...";
3053     }
3054     Params += ")";
3055   }
3056 
3057   if (SuppressBlock) {
3058     // Format as a parameter.
3059     Result = Result + " (^";
3060     if (!SuppressBlockName && BlockDecl->getIdentifier())
3061       Result += BlockDecl->getIdentifier()->getName();
3062     Result += ")";
3063     Result += Params;
3064   } else {
3065     // Format as a block literal argument.
3066     Result = '^' + Result;
3067     Result += Params;
3068 
3069     if (!SuppressBlockName && BlockDecl->getIdentifier())
3070       Result += BlockDecl->getIdentifier()->getName();
3071   }
3072 
3073   return Result;
3074 }
3075 
3076 static std::string GetDefaultValueString(const ParmVarDecl *Param,
3077                                          const SourceManager &SM,
3078                                          const LangOptions &LangOpts) {
3079   const SourceRange SrcRange = Param->getDefaultArgRange();
3080   CharSourceRange CharSrcRange = CharSourceRange::getTokenRange(SrcRange);
3081   bool Invalid = CharSrcRange.isInvalid();
3082   if (Invalid)
3083     return "";
3084   StringRef srcText =
3085       Lexer::getSourceText(CharSrcRange, SM, LangOpts, &Invalid);
3086   if (Invalid)
3087     return "";
3088 
3089   if (srcText.empty() || srcText == "=") {
3090     // Lexer can't determine the value.
3091     // This happens if the code is incorrect (for example class is forward
3092     // declared).
3093     return "";
3094   }
3095   std::string DefValue(srcText.str());
3096   // FIXME: remove this check if the Lexer::getSourceText value is fixed and
3097   // this value always has (or always does not have) '=' in front of it
3098   if (DefValue.at(0) != '=') {
3099     // If we don't have '=' in front of value.
3100     // Lexer returns built-in types values without '=' and user-defined types
3101     // values with it.
3102     return " = " + DefValue;
3103   }
3104   return " " + DefValue;
3105 }
3106 
3107 /// Add function parameter chunks to the given code completion string.
3108 static void AddFunctionParameterChunks(Preprocessor &PP,
3109                                        const PrintingPolicy &Policy,
3110                                        const FunctionDecl *Function,
3111                                        CodeCompletionBuilder &Result,
3112                                        unsigned Start = 0,
3113                                        bool InOptional = false) {
3114   bool FirstParameter = true;
3115 
3116   for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
3117     const ParmVarDecl *Param = Function->getParamDecl(P);
3118 
3119     if (Param->hasDefaultArg() && !InOptional) {
3120       // When we see an optional default argument, put that argument and
3121       // the remaining default arguments into a new, optional string.
3122       CodeCompletionBuilder Opt(Result.getAllocator(),
3123                                 Result.getCodeCompletionTUInfo());
3124       if (!FirstParameter)
3125         Opt.AddChunk(CodeCompletionString::CK_Comma);
3126       AddFunctionParameterChunks(PP, Policy, Function, Opt, P, true);
3127       Result.AddOptionalChunk(Opt.TakeString());
3128       break;
3129     }
3130 
3131     if (FirstParameter)
3132       FirstParameter = false;
3133     else
3134       Result.AddChunk(CodeCompletionString::CK_Comma);
3135 
3136     InOptional = false;
3137 
3138     // Format the placeholder string.
3139     std::string PlaceholderStr = FormatFunctionParameter(Policy, Param);
3140     if (Param->hasDefaultArg())
3141       PlaceholderStr +=
3142           GetDefaultValueString(Param, PP.getSourceManager(), PP.getLangOpts());
3143 
3144     if (Function->isVariadic() && P == N - 1)
3145       PlaceholderStr += ", ...";
3146 
3147     // Add the placeholder string.
3148     Result.AddPlaceholderChunk(
3149         Result.getAllocator().CopyString(PlaceholderStr));
3150   }
3151 
3152   if (const auto *Proto = Function->getType()->getAs<FunctionProtoType>())
3153     if (Proto->isVariadic()) {
3154       if (Proto->getNumParams() == 0)
3155         Result.AddPlaceholderChunk("...");
3156 
3157       MaybeAddSentinel(PP, Function, Result);
3158     }
3159 }
3160 
3161 /// Add template parameter chunks to the given code completion string.
3162 static void AddTemplateParameterChunks(
3163     ASTContext &Context, const PrintingPolicy &Policy,
3164     const TemplateDecl *Template, CodeCompletionBuilder &Result,
3165     unsigned MaxParameters = 0, unsigned Start = 0, bool InDefaultArg = false) {
3166   bool FirstParameter = true;
3167 
3168   // Prefer to take the template parameter names from the first declaration of
3169   // the template.
3170   Template = cast<TemplateDecl>(Template->getCanonicalDecl());
3171 
3172   TemplateParameterList *Params = Template->getTemplateParameters();
3173   TemplateParameterList::iterator PEnd = Params->end();
3174   if (MaxParameters)
3175     PEnd = Params->begin() + MaxParameters;
3176   for (TemplateParameterList::iterator P = Params->begin() + Start; P != PEnd;
3177        ++P) {
3178     bool HasDefaultArg = false;
3179     std::string PlaceholderStr;
3180     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
3181       if (TTP->wasDeclaredWithTypename())
3182         PlaceholderStr = "typename";
3183       else if (const auto *TC = TTP->getTypeConstraint()) {
3184         llvm::raw_string_ostream OS(PlaceholderStr);
3185         TC->print(OS, Policy);
3186         OS.flush();
3187       } else
3188         PlaceholderStr = "class";
3189 
3190       if (TTP->getIdentifier()) {
3191         PlaceholderStr += ' ';
3192         PlaceholderStr += TTP->getIdentifier()->deuglifiedName();
3193       }
3194 
3195       HasDefaultArg = TTP->hasDefaultArgument();
3196     } else if (NonTypeTemplateParmDecl *NTTP =
3197                    dyn_cast<NonTypeTemplateParmDecl>(*P)) {
3198       if (NTTP->getIdentifier())
3199         PlaceholderStr = std::string(NTTP->getIdentifier()->deuglifiedName());
3200       NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
3201       HasDefaultArg = NTTP->hasDefaultArgument();
3202     } else {
3203       assert(isa<TemplateTemplateParmDecl>(*P));
3204       TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
3205 
3206       // Since putting the template argument list into the placeholder would
3207       // be very, very long, we just use an abbreviation.
3208       PlaceholderStr = "template<...> class";
3209       if (TTP->getIdentifier()) {
3210         PlaceholderStr += ' ';
3211         PlaceholderStr += TTP->getIdentifier()->deuglifiedName();
3212       }
3213 
3214       HasDefaultArg = TTP->hasDefaultArgument();
3215     }
3216 
3217     if (HasDefaultArg && !InDefaultArg) {
3218       // When we see an optional default argument, put that argument and
3219       // the remaining default arguments into a new, optional string.
3220       CodeCompletionBuilder Opt(Result.getAllocator(),
3221                                 Result.getCodeCompletionTUInfo());
3222       if (!FirstParameter)
3223         Opt.AddChunk(CodeCompletionString::CK_Comma);
3224       AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
3225                                  P - Params->begin(), true);
3226       Result.AddOptionalChunk(Opt.TakeString());
3227       break;
3228     }
3229 
3230     InDefaultArg = false;
3231 
3232     if (FirstParameter)
3233       FirstParameter = false;
3234     else
3235       Result.AddChunk(CodeCompletionString::CK_Comma);
3236 
3237     // Add the placeholder string.
3238     Result.AddPlaceholderChunk(
3239         Result.getAllocator().CopyString(PlaceholderStr));
3240   }
3241 }
3242 
3243 /// Add a qualifier to the given code-completion string, if the
3244 /// provided nested-name-specifier is non-NULL.
3245 static void AddQualifierToCompletionString(CodeCompletionBuilder &Result,
3246                                            NestedNameSpecifier *Qualifier,
3247                                            bool QualifierIsInformative,
3248                                            ASTContext &Context,
3249                                            const PrintingPolicy &Policy) {
3250   if (!Qualifier)
3251     return;
3252 
3253   std::string PrintedNNS;
3254   {
3255     llvm::raw_string_ostream OS(PrintedNNS);
3256     Qualifier->print(OS, Policy);
3257   }
3258   if (QualifierIsInformative)
3259     Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
3260   else
3261     Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
3262 }
3263 
3264 static void
3265 AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
3266                                        const FunctionDecl *Function) {
3267   const auto *Proto = Function->getType()->getAs<FunctionProtoType>();
3268   if (!Proto || !Proto->getMethodQuals())
3269     return;
3270 
3271   // FIXME: Add ref-qualifier!
3272 
3273   // Handle single qualifiers without copying
3274   if (Proto->getMethodQuals().hasOnlyConst()) {
3275     Result.AddInformativeChunk(" const");
3276     return;
3277   }
3278 
3279   if (Proto->getMethodQuals().hasOnlyVolatile()) {
3280     Result.AddInformativeChunk(" volatile");
3281     return;
3282   }
3283 
3284   if (Proto->getMethodQuals().hasOnlyRestrict()) {
3285     Result.AddInformativeChunk(" restrict");
3286     return;
3287   }
3288 
3289   // Handle multiple qualifiers.
3290   std::string QualsStr;
3291   if (Proto->isConst())
3292     QualsStr += " const";
3293   if (Proto->isVolatile())
3294     QualsStr += " volatile";
3295   if (Proto->isRestrict())
3296     QualsStr += " restrict";
3297   Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
3298 }
3299 
3300 /// Add the name of the given declaration
3301 static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
3302                               const NamedDecl *ND,
3303                               CodeCompletionBuilder &Result) {
3304   DeclarationName Name = ND->getDeclName();
3305   if (!Name)
3306     return;
3307 
3308   switch (Name.getNameKind()) {
3309   case DeclarationName::CXXOperatorName: {
3310     const char *OperatorName = nullptr;
3311     switch (Name.getCXXOverloadedOperator()) {
3312     case OO_None:
3313     case OO_Conditional:
3314     case NUM_OVERLOADED_OPERATORS:
3315       OperatorName = "operator";
3316       break;
3317 
3318 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly)  \
3319   case OO_##Name:                                                              \
3320     OperatorName = "operator" Spelling;                                        \
3321     break;
3322 #define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemberOnly)
3323 #include "clang/Basic/OperatorKinds.def"
3324 
3325     case OO_New:
3326       OperatorName = "operator new";
3327       break;
3328     case OO_Delete:
3329       OperatorName = "operator delete";
3330       break;
3331     case OO_Array_New:
3332       OperatorName = "operator new[]";
3333       break;
3334     case OO_Array_Delete:
3335       OperatorName = "operator delete[]";
3336       break;
3337     case OO_Call:
3338       OperatorName = "operator()";
3339       break;
3340     case OO_Subscript:
3341       OperatorName = "operator[]";
3342       break;
3343     }
3344     Result.AddTypedTextChunk(OperatorName);
3345     break;
3346   }
3347 
3348   case DeclarationName::Identifier:
3349   case DeclarationName::CXXConversionFunctionName:
3350   case DeclarationName::CXXDestructorName:
3351   case DeclarationName::CXXLiteralOperatorName:
3352     Result.AddTypedTextChunk(
3353         Result.getAllocator().CopyString(ND->getNameAsString()));
3354     break;
3355 
3356   case DeclarationName::CXXDeductionGuideName:
3357   case DeclarationName::CXXUsingDirective:
3358   case DeclarationName::ObjCZeroArgSelector:
3359   case DeclarationName::ObjCOneArgSelector:
3360   case DeclarationName::ObjCMultiArgSelector:
3361     break;
3362 
3363   case DeclarationName::CXXConstructorName: {
3364     CXXRecordDecl *Record = nullptr;
3365     QualType Ty = Name.getCXXNameType();
3366     if (const auto *RecordTy = Ty->getAs<RecordType>())
3367       Record = cast<CXXRecordDecl>(RecordTy->getDecl());
3368     else if (const auto *InjectedTy = Ty->getAs<InjectedClassNameType>())
3369       Record = InjectedTy->getDecl();
3370     else {
3371       Result.AddTypedTextChunk(
3372           Result.getAllocator().CopyString(ND->getNameAsString()));
3373       break;
3374     }
3375 
3376     Result.AddTypedTextChunk(
3377         Result.getAllocator().CopyString(Record->getNameAsString()));
3378     if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
3379       Result.AddChunk(CodeCompletionString::CK_LeftAngle);
3380       AddTemplateParameterChunks(Context, Policy, Template, Result);
3381       Result.AddChunk(CodeCompletionString::CK_RightAngle);
3382     }
3383     break;
3384   }
3385   }
3386 }
3387 
3388 CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(
3389     Sema &S, const CodeCompletionContext &CCContext,
3390     CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo,
3391     bool IncludeBriefComments) {
3392   return CreateCodeCompletionString(S.Context, S.PP, CCContext, Allocator,
3393                                     CCTUInfo, IncludeBriefComments);
3394 }
3395 
3396 CodeCompletionString *CodeCompletionResult::CreateCodeCompletionStringForMacro(
3397     Preprocessor &PP, CodeCompletionAllocator &Allocator,
3398     CodeCompletionTUInfo &CCTUInfo) {
3399   assert(Kind == RK_Macro);
3400   CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
3401   const MacroInfo *MI = PP.getMacroInfo(Macro);
3402   Result.AddTypedTextChunk(Result.getAllocator().CopyString(Macro->getName()));
3403 
3404   if (!MI || !MI->isFunctionLike())
3405     return Result.TakeString();
3406 
3407   // Format a function-like macro with placeholders for the arguments.
3408   Result.AddChunk(CodeCompletionString::CK_LeftParen);
3409   MacroInfo::param_iterator A = MI->param_begin(), AEnd = MI->param_end();
3410 
3411   // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
3412   if (MI->isC99Varargs()) {
3413     --AEnd;
3414 
3415     if (A == AEnd) {
3416       Result.AddPlaceholderChunk("...");
3417     }
3418   }
3419 
3420   for (MacroInfo::param_iterator A = MI->param_begin(); A != AEnd; ++A) {
3421     if (A != MI->param_begin())
3422       Result.AddChunk(CodeCompletionString::CK_Comma);
3423 
3424     if (MI->isVariadic() && (A + 1) == AEnd) {
3425       SmallString<32> Arg = (*A)->getName();
3426       if (MI->isC99Varargs())
3427         Arg += ", ...";
3428       else
3429         Arg += "...";
3430       Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
3431       break;
3432     }
3433 
3434     // Non-variadic macros are simple.
3435     Result.AddPlaceholderChunk(
3436         Result.getAllocator().CopyString((*A)->getName()));
3437   }
3438   Result.AddChunk(CodeCompletionString::CK_RightParen);
3439   return Result.TakeString();
3440 }
3441 
3442 /// If possible, create a new code completion string for the given
3443 /// result.
3444 ///
3445 /// \returns Either a new, heap-allocated code completion string describing
3446 /// how to use this result, or NULL to indicate that the string or name of the
3447 /// result is all that is needed.
3448 CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(
3449     ASTContext &Ctx, Preprocessor &PP, const CodeCompletionContext &CCContext,
3450     CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo,
3451     bool IncludeBriefComments) {
3452   if (Kind == RK_Macro)
3453     return CreateCodeCompletionStringForMacro(PP, Allocator, CCTUInfo);
3454 
3455   CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
3456 
3457   PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP);
3458   if (Kind == RK_Pattern) {
3459     Pattern->Priority = Priority;
3460     Pattern->Availability = Availability;
3461 
3462     if (Declaration) {
3463       Result.addParentContext(Declaration->getDeclContext());
3464       Pattern->ParentName = Result.getParentName();
3465       if (const RawComment *RC =
3466               getPatternCompletionComment(Ctx, Declaration)) {
3467         Result.addBriefComment(RC->getBriefText(Ctx));
3468         Pattern->BriefComment = Result.getBriefComment();
3469       }
3470     }
3471 
3472     return Pattern;
3473   }
3474 
3475   if (Kind == RK_Keyword) {
3476     Result.AddTypedTextChunk(Keyword);
3477     return Result.TakeString();
3478   }
3479   assert(Kind == RK_Declaration && "Missed a result kind?");
3480   return createCodeCompletionStringForDecl(
3481       PP, Ctx, Result, IncludeBriefComments, CCContext, Policy);
3482 }
3483 
3484 static void printOverrideString(const CodeCompletionString &CCS,
3485                                 std::string &BeforeName,
3486                                 std::string &NameAndSignature) {
3487   bool SeenTypedChunk = false;
3488   for (auto &Chunk : CCS) {
3489     if (Chunk.Kind == CodeCompletionString::CK_Optional) {
3490       assert(SeenTypedChunk && "optional parameter before name");
3491       // Note that we put all chunks inside into NameAndSignature.
3492       printOverrideString(*Chunk.Optional, NameAndSignature, NameAndSignature);
3493       continue;
3494     }
3495     SeenTypedChunk |= Chunk.Kind == CodeCompletionString::CK_TypedText;
3496     if (SeenTypedChunk)
3497       NameAndSignature += Chunk.Text;
3498     else
3499       BeforeName += Chunk.Text;
3500   }
3501 }
3502 
3503 CodeCompletionString *
3504 CodeCompletionResult::createCodeCompletionStringForOverride(
3505     Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result,
3506     bool IncludeBriefComments, const CodeCompletionContext &CCContext,
3507     PrintingPolicy &Policy) {
3508   auto *CCS = createCodeCompletionStringForDecl(PP, Ctx, Result,
3509                                                 /*IncludeBriefComments=*/false,
3510                                                 CCContext, Policy);
3511   std::string BeforeName;
3512   std::string NameAndSignature;
3513   // For overrides all chunks go into the result, none are informative.
3514   printOverrideString(*CCS, BeforeName, NameAndSignature);
3515   NameAndSignature += " override";
3516 
3517   Result.AddTextChunk(Result.getAllocator().CopyString(BeforeName));
3518   Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3519   Result.AddTypedTextChunk(Result.getAllocator().CopyString(NameAndSignature));
3520   return Result.TakeString();
3521 }
3522 
3523 // FIXME: Right now this works well with lambdas. Add support for other functor
3524 // types like std::function.
3525 static const NamedDecl *extractFunctorCallOperator(const NamedDecl *ND) {
3526   const auto *VD = dyn_cast<VarDecl>(ND);
3527   if (!VD)
3528     return nullptr;
3529   const auto *RecordDecl = VD->getType()->getAsCXXRecordDecl();
3530   if (!RecordDecl || !RecordDecl->isLambda())
3531     return nullptr;
3532   return RecordDecl->getLambdaCallOperator();
3533 }
3534 
3535 CodeCompletionString *CodeCompletionResult::createCodeCompletionStringForDecl(
3536     Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result,
3537     bool IncludeBriefComments, const CodeCompletionContext &CCContext,
3538     PrintingPolicy &Policy) {
3539   const NamedDecl *ND = Declaration;
3540   Result.addParentContext(ND->getDeclContext());
3541 
3542   if (IncludeBriefComments) {
3543     // Add documentation comment, if it exists.
3544     if (const RawComment *RC = getCompletionComment(Ctx, Declaration)) {
3545       Result.addBriefComment(RC->getBriefText(Ctx));
3546     }
3547   }
3548 
3549   if (StartsNestedNameSpecifier) {
3550     Result.AddTypedTextChunk(
3551         Result.getAllocator().CopyString(ND->getNameAsString()));
3552     Result.AddTextChunk("::");
3553     return Result.TakeString();
3554   }
3555 
3556   for (const auto *I : ND->specific_attrs<AnnotateAttr>())
3557     Result.AddAnnotation(Result.getAllocator().CopyString(I->getAnnotation()));
3558 
3559   auto AddFunctionTypeAndResult = [&](const FunctionDecl *Function) {
3560     AddResultTypeChunk(Ctx, Policy, Function, CCContext.getBaseType(), Result);
3561     AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
3562                                    Ctx, Policy);
3563     AddTypedNameChunk(Ctx, Policy, ND, Result);
3564     Result.AddChunk(CodeCompletionString::CK_LeftParen);
3565     AddFunctionParameterChunks(PP, Policy, Function, Result);
3566     Result.AddChunk(CodeCompletionString::CK_RightParen);
3567     AddFunctionTypeQualsToCompletionString(Result, Function);
3568   };
3569 
3570   if (const auto *Function = dyn_cast<FunctionDecl>(ND)) {
3571     AddFunctionTypeAndResult(Function);
3572     return Result.TakeString();
3573   }
3574 
3575   if (const auto *CallOperator =
3576           dyn_cast_or_null<FunctionDecl>(extractFunctorCallOperator(ND))) {
3577     AddFunctionTypeAndResult(CallOperator);
3578     return Result.TakeString();
3579   }
3580 
3581   AddResultTypeChunk(Ctx, Policy, ND, CCContext.getBaseType(), Result);
3582 
3583   if (const FunctionTemplateDecl *FunTmpl =
3584           dyn_cast<FunctionTemplateDecl>(ND)) {
3585     AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
3586                                    Ctx, Policy);
3587     FunctionDecl *Function = FunTmpl->getTemplatedDecl();
3588     AddTypedNameChunk(Ctx, Policy, Function, Result);
3589 
3590     // Figure out which template parameters are deduced (or have default
3591     // arguments).
3592     // Note that we're creating a non-empty bit vector so that we can go
3593     // through the loop below to omit default template parameters for non-call
3594     // cases.
3595     llvm::SmallBitVector Deduced(FunTmpl->getTemplateParameters()->size());
3596     // Avoid running it if this is not a call: We should emit *all* template
3597     // parameters.
3598     if (FunctionCanBeCall)
3599       Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced);
3600     unsigned LastDeducibleArgument;
3601     for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
3602          --LastDeducibleArgument) {
3603       if (!Deduced[LastDeducibleArgument - 1]) {
3604         // C++0x: Figure out if the template argument has a default. If so,
3605         // the user doesn't need to type this argument.
3606         // FIXME: We need to abstract template parameters better!
3607         bool HasDefaultArg = false;
3608         NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
3609             LastDeducibleArgument - 1);
3610         if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3611           HasDefaultArg = TTP->hasDefaultArgument();
3612         else if (NonTypeTemplateParmDecl *NTTP =
3613                      dyn_cast<NonTypeTemplateParmDecl>(Param))
3614           HasDefaultArg = NTTP->hasDefaultArgument();
3615         else {
3616           assert(isa<TemplateTemplateParmDecl>(Param));
3617           HasDefaultArg =
3618               cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
3619         }
3620 
3621         if (!HasDefaultArg)
3622           break;
3623       }
3624     }
3625 
3626     if (LastDeducibleArgument || !FunctionCanBeCall) {
3627       // Some of the function template arguments cannot be deduced from a
3628       // function call, so we introduce an explicit template argument list
3629       // containing all of the arguments up to the first deducible argument.
3630       //
3631       // Or, if this isn't a call, emit all the template arguments
3632       // to disambiguate the (potential) overloads.
3633       //
3634       // FIXME: Detect cases where the function parameters can be deduced from
3635       // the surrounding context, as per [temp.deduct.funcaddr].
3636       // e.g.,
3637       // template <class T> void foo(T);
3638       // void (*f)(int) = foo;
3639       Result.AddChunk(CodeCompletionString::CK_LeftAngle);
3640       AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result,
3641                                  LastDeducibleArgument);
3642       Result.AddChunk(CodeCompletionString::CK_RightAngle);
3643     }
3644 
3645     // Add the function parameters
3646     Result.AddChunk(CodeCompletionString::CK_LeftParen);
3647     AddFunctionParameterChunks(PP, Policy, Function, Result);
3648     Result.AddChunk(CodeCompletionString::CK_RightParen);
3649     AddFunctionTypeQualsToCompletionString(Result, Function);
3650     return Result.TakeString();
3651   }
3652 
3653   if (const auto *Template = dyn_cast<TemplateDecl>(ND)) {
3654     AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
3655                                    Ctx, Policy);
3656     Result.AddTypedTextChunk(
3657         Result.getAllocator().CopyString(Template->getNameAsString()));
3658     Result.AddChunk(CodeCompletionString::CK_LeftAngle);
3659     AddTemplateParameterChunks(Ctx, Policy, Template, Result);
3660     Result.AddChunk(CodeCompletionString::CK_RightAngle);
3661     return Result.TakeString();
3662   }
3663 
3664   if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND)) {
3665     Selector Sel = Method->getSelector();
3666     if (Sel.isUnarySelector()) {
3667       Result.AddTypedTextChunk(
3668           Result.getAllocator().CopyString(Sel.getNameForSlot(0)));
3669       return Result.TakeString();
3670     }
3671 
3672     std::string SelName = Sel.getNameForSlot(0).str();
3673     SelName += ':';
3674     if (StartParameter == 0)
3675       Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
3676     else {
3677       Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
3678 
3679       // If there is only one parameter, and we're past it, add an empty
3680       // typed-text chunk since there is nothing to type.
3681       if (Method->param_size() == 1)
3682         Result.AddTypedTextChunk("");
3683     }
3684     unsigned Idx = 0;
3685     // The extra Idx < Sel.getNumArgs() check is needed due to legacy C-style
3686     // method parameters.
3687     for (ObjCMethodDecl::param_const_iterator P = Method->param_begin(),
3688                                               PEnd = Method->param_end();
3689          P != PEnd && Idx < Sel.getNumArgs(); (void)++P, ++Idx) {
3690       if (Idx > 0) {
3691         std::string Keyword;
3692         if (Idx > StartParameter)
3693           Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3694         if (const IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
3695           Keyword += II->getName();
3696         Keyword += ":";
3697         if (Idx < StartParameter || AllParametersAreInformative)
3698           Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
3699         else
3700           Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
3701       }
3702 
3703       // If we're before the starting parameter, skip the placeholder.
3704       if (Idx < StartParameter)
3705         continue;
3706 
3707       std::string Arg;
3708       QualType ParamType = (*P)->getType();
3709       std::optional<ArrayRef<QualType>> ObjCSubsts;
3710       if (!CCContext.getBaseType().isNull())
3711         ObjCSubsts = CCContext.getBaseType()->getObjCSubstitutions(Method);
3712 
3713       if (ParamType->isBlockPointerType() && !DeclaringEntity)
3714         Arg = FormatFunctionParameter(Policy, *P, true,
3715                                       /*SuppressBlock=*/false, ObjCSubsts);
3716       else {
3717         if (ObjCSubsts)
3718           ParamType = ParamType.substObjCTypeArgs(
3719               Ctx, *ObjCSubsts, ObjCSubstitutionContext::Parameter);
3720         Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier(),
3721                                               ParamType);
3722         Arg += ParamType.getAsString(Policy) + ")";
3723         if (const IdentifierInfo *II = (*P)->getIdentifier())
3724           if (DeclaringEntity || AllParametersAreInformative)
3725             Arg += II->getName();
3726       }
3727 
3728       if (Method->isVariadic() && (P + 1) == PEnd)
3729         Arg += ", ...";
3730 
3731       if (DeclaringEntity)
3732         Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
3733       else if (AllParametersAreInformative)
3734         Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
3735       else
3736         Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
3737     }
3738 
3739     if (Method->isVariadic()) {
3740       if (Method->param_size() == 0) {
3741         if (DeclaringEntity)
3742           Result.AddTextChunk(", ...");
3743         else if (AllParametersAreInformative)
3744           Result.AddInformativeChunk(", ...");
3745         else
3746           Result.AddPlaceholderChunk(", ...");
3747       }
3748 
3749       MaybeAddSentinel(PP, Method, Result);
3750     }
3751 
3752     return Result.TakeString();
3753   }
3754 
3755   if (Qualifier)
3756     AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
3757                                    Ctx, Policy);
3758 
3759   Result.AddTypedTextChunk(
3760       Result.getAllocator().CopyString(ND->getNameAsString()));
3761   return Result.TakeString();
3762 }
3763 
3764 const RawComment *clang::getCompletionComment(const ASTContext &Ctx,
3765                                               const NamedDecl *ND) {
3766   if (!ND)
3767     return nullptr;
3768   if (auto *RC = Ctx.getRawCommentForAnyRedecl(ND))
3769     return RC;
3770 
3771   // Try to find comment from a property for ObjC methods.
3772   const auto *M = dyn_cast<ObjCMethodDecl>(ND);
3773   if (!M)
3774     return nullptr;
3775   const ObjCPropertyDecl *PDecl = M->findPropertyDecl();
3776   if (!PDecl)
3777     return nullptr;
3778 
3779   return Ctx.getRawCommentForAnyRedecl(PDecl);
3780 }
3781 
3782 const RawComment *clang::getPatternCompletionComment(const ASTContext &Ctx,
3783                                                      const NamedDecl *ND) {
3784   const auto *M = dyn_cast_or_null<ObjCMethodDecl>(ND);
3785   if (!M || !M->isPropertyAccessor())
3786     return nullptr;
3787 
3788   // Provide code completion comment for self.GetterName where
3789   // GetterName is the getter method for a property with name
3790   // different from the property name (declared via a property
3791   // getter attribute.
3792   const ObjCPropertyDecl *PDecl = M->findPropertyDecl();
3793   if (!PDecl)
3794     return nullptr;
3795   if (PDecl->getGetterName() == M->getSelector() &&
3796       PDecl->getIdentifier() != M->getIdentifier()) {
3797     if (auto *RC = Ctx.getRawCommentForAnyRedecl(M))
3798       return RC;
3799     if (auto *RC = Ctx.getRawCommentForAnyRedecl(PDecl))
3800       return RC;
3801   }
3802   return nullptr;
3803 }
3804 
3805 const RawComment *clang::getParameterComment(
3806     const ASTContext &Ctx,
3807     const CodeCompleteConsumer::OverloadCandidate &Result, unsigned ArgIndex) {
3808   auto FDecl = Result.getFunction();
3809   if (!FDecl)
3810     return nullptr;
3811   if (ArgIndex < FDecl->getNumParams())
3812     return Ctx.getRawCommentForAnyRedecl(FDecl->getParamDecl(ArgIndex));
3813   return nullptr;
3814 }
3815 
3816 static void AddOverloadAggregateChunks(const RecordDecl *RD,
3817                                        const PrintingPolicy &Policy,
3818                                        CodeCompletionBuilder &Result,
3819                                        unsigned CurrentArg) {
3820   unsigned ChunkIndex = 0;
3821   auto AddChunk = [&](llvm::StringRef Placeholder) {
3822     if (ChunkIndex > 0)
3823       Result.AddChunk(CodeCompletionString::CK_Comma);
3824     const char *Copy = Result.getAllocator().CopyString(Placeholder);
3825     if (ChunkIndex == CurrentArg)
3826       Result.AddCurrentParameterChunk(Copy);
3827     else
3828       Result.AddPlaceholderChunk(Copy);
3829     ++ChunkIndex;
3830   };
3831   // Aggregate initialization has all bases followed by all fields.
3832   // (Bases are not legal in C++11 but in that case we never get here).
3833   if (auto *CRD = llvm::dyn_cast<CXXRecordDecl>(RD)) {
3834     for (const auto &Base : CRD->bases())
3835       AddChunk(Base.getType().getAsString(Policy));
3836   }
3837   for (const auto &Field : RD->fields())
3838     AddChunk(FormatFunctionParameter(Policy, Field));
3839 }
3840 
3841 /// Add function overload parameter chunks to the given code completion
3842 /// string.
3843 static void AddOverloadParameterChunks(
3844     ASTContext &Context, const PrintingPolicy &Policy,
3845     const FunctionDecl *Function, const FunctionProtoType *Prototype,
3846     FunctionProtoTypeLoc PrototypeLoc, CodeCompletionBuilder &Result,
3847     unsigned CurrentArg, unsigned Start = 0, bool InOptional = false) {
3848   if (!Function && !Prototype) {
3849     Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "...");
3850     return;
3851   }
3852 
3853   bool FirstParameter = true;
3854   unsigned NumParams =
3855       Function ? Function->getNumParams() : Prototype->getNumParams();
3856 
3857   for (unsigned P = Start; P != NumParams; ++P) {
3858     if (Function && Function->getParamDecl(P)->hasDefaultArg() && !InOptional) {
3859       // When we see an optional default argument, put that argument and
3860       // the remaining default arguments into a new, optional string.
3861       CodeCompletionBuilder Opt(Result.getAllocator(),
3862                                 Result.getCodeCompletionTUInfo());
3863       if (!FirstParameter)
3864         Opt.AddChunk(CodeCompletionString::CK_Comma);
3865       // Optional sections are nested.
3866       AddOverloadParameterChunks(Context, Policy, Function, Prototype,
3867                                  PrototypeLoc, Opt, CurrentArg, P,
3868                                  /*InOptional=*/true);
3869       Result.AddOptionalChunk(Opt.TakeString());
3870       return;
3871     }
3872 
3873     if (FirstParameter)
3874       FirstParameter = false;
3875     else
3876       Result.AddChunk(CodeCompletionString::CK_Comma);
3877 
3878     InOptional = false;
3879 
3880     // Format the placeholder string.
3881     std::string Placeholder;
3882     assert(P < Prototype->getNumParams());
3883     if (Function || PrototypeLoc) {
3884       const ParmVarDecl *Param =
3885           Function ? Function->getParamDecl(P) : PrototypeLoc.getParam(P);
3886       Placeholder = FormatFunctionParameter(Policy, Param);
3887       if (Param->hasDefaultArg())
3888         Placeholder += GetDefaultValueString(Param, Context.getSourceManager(),
3889                                              Context.getLangOpts());
3890     } else {
3891       Placeholder = Prototype->getParamType(P).getAsString(Policy);
3892     }
3893 
3894     if (P == CurrentArg)
3895       Result.AddCurrentParameterChunk(
3896           Result.getAllocator().CopyString(Placeholder));
3897     else
3898       Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Placeholder));
3899   }
3900 
3901   if (Prototype && Prototype->isVariadic()) {
3902     CodeCompletionBuilder Opt(Result.getAllocator(),
3903                               Result.getCodeCompletionTUInfo());
3904     if (!FirstParameter)
3905       Opt.AddChunk(CodeCompletionString::CK_Comma);
3906 
3907     if (CurrentArg < NumParams)
3908       Opt.AddPlaceholderChunk("...");
3909     else
3910       Opt.AddCurrentParameterChunk("...");
3911 
3912     Result.AddOptionalChunk(Opt.TakeString());
3913   }
3914 }
3915 
3916 static std::string
3917 formatTemplateParameterPlaceholder(const NamedDecl *Param, bool &Optional,
3918                                    const PrintingPolicy &Policy) {
3919   if (const auto *Type = dyn_cast<TemplateTypeParmDecl>(Param)) {
3920     Optional = Type->hasDefaultArgument();
3921   } else if (const auto *NonType = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3922     Optional = NonType->hasDefaultArgument();
3923   } else if (const auto *Template = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3924     Optional = Template->hasDefaultArgument();
3925   }
3926   std::string Result;
3927   llvm::raw_string_ostream OS(Result);
3928   Param->print(OS, Policy);
3929   return Result;
3930 }
3931 
3932 static std::string templateResultType(const TemplateDecl *TD,
3933                                       const PrintingPolicy &Policy) {
3934   if (const auto *CTD = dyn_cast<ClassTemplateDecl>(TD))
3935     return CTD->getTemplatedDecl()->getKindName().str();
3936   if (const auto *VTD = dyn_cast<VarTemplateDecl>(TD))
3937     return VTD->getTemplatedDecl()->getType().getAsString(Policy);
3938   if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(TD))
3939     return FTD->getTemplatedDecl()->getReturnType().getAsString(Policy);
3940   if (isa<TypeAliasTemplateDecl>(TD))
3941     return "type";
3942   if (isa<TemplateTemplateParmDecl>(TD))
3943     return "class";
3944   if (isa<ConceptDecl>(TD))
3945     return "concept";
3946   return "";
3947 }
3948 
3949 static CodeCompletionString *createTemplateSignatureString(
3950     const TemplateDecl *TD, CodeCompletionBuilder &Builder, unsigned CurrentArg,
3951     const PrintingPolicy &Policy) {
3952   llvm::ArrayRef<NamedDecl *> Params = TD->getTemplateParameters()->asArray();
3953   CodeCompletionBuilder OptionalBuilder(Builder.getAllocator(),
3954                                         Builder.getCodeCompletionTUInfo());
3955   std::string ResultType = templateResultType(TD, Policy);
3956   if (!ResultType.empty())
3957     Builder.AddResultTypeChunk(Builder.getAllocator().CopyString(ResultType));
3958   Builder.AddTextChunk(
3959       Builder.getAllocator().CopyString(TD->getNameAsString()));
3960   Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
3961   // Initially we're writing into the main string. Once we see an optional arg
3962   // (with default), we're writing into the nested optional chunk.
3963   CodeCompletionBuilder *Current = &Builder;
3964   for (unsigned I = 0; I < Params.size(); ++I) {
3965     bool Optional = false;
3966     std::string Placeholder =
3967         formatTemplateParameterPlaceholder(Params[I], Optional, Policy);
3968     if (Optional)
3969       Current = &OptionalBuilder;
3970     if (I > 0)
3971       Current->AddChunk(CodeCompletionString::CK_Comma);
3972     Current->AddChunk(I == CurrentArg
3973                           ? CodeCompletionString::CK_CurrentParameter
3974                           : CodeCompletionString::CK_Placeholder,
3975                       Current->getAllocator().CopyString(Placeholder));
3976   }
3977   // Add the optional chunk to the main string if we ever used it.
3978   if (Current == &OptionalBuilder)
3979     Builder.AddOptionalChunk(OptionalBuilder.TakeString());
3980   Builder.AddChunk(CodeCompletionString::CK_RightAngle);
3981   // For function templates, ResultType was the function's return type.
3982   // Give some clue this is a function. (Don't show the possibly-bulky params).
3983   if (isa<FunctionTemplateDecl>(TD))
3984     Builder.AddInformativeChunk("()");
3985   return Builder.TakeString();
3986 }
3987 
3988 CodeCompletionString *
3989 CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
3990     unsigned CurrentArg, Sema &S, CodeCompletionAllocator &Allocator,
3991     CodeCompletionTUInfo &CCTUInfo, bool IncludeBriefComments,
3992     bool Braced) const {
3993   PrintingPolicy Policy = getCompletionPrintingPolicy(S);
3994   // Show signatures of constructors as they are declared:
3995   //   vector(int n) rather than vector<string>(int n)
3996   // This is less noisy without being less clear, and avoids tricky cases.
3997   Policy.SuppressTemplateArgsInCXXConstructors = true;
3998 
3999   // FIXME: Set priority, availability appropriately.
4000   CodeCompletionBuilder Result(Allocator, CCTUInfo, 1,
4001                                CXAvailability_Available);
4002 
4003   if (getKind() == CK_Template)
4004     return createTemplateSignatureString(getTemplate(), Result, CurrentArg,
4005                                          Policy);
4006 
4007   FunctionDecl *FDecl = getFunction();
4008   const FunctionProtoType *Proto =
4009       dyn_cast_or_null<FunctionProtoType>(getFunctionType());
4010 
4011   // First, the name/type of the callee.
4012   if (getKind() == CK_Aggregate) {
4013     Result.AddTextChunk(
4014         Result.getAllocator().CopyString(getAggregate()->getName()));
4015   } else if (FDecl) {
4016     if (IncludeBriefComments) {
4017       if (auto RC = getParameterComment(S.getASTContext(), *this, CurrentArg))
4018         Result.addBriefComment(RC->getBriefText(S.getASTContext()));
4019     }
4020     AddResultTypeChunk(S.Context, Policy, FDecl, QualType(), Result);
4021 
4022     std::string Name;
4023     llvm::raw_string_ostream OS(Name);
4024     FDecl->getDeclName().print(OS, Policy);
4025     Result.AddTextChunk(Result.getAllocator().CopyString(OS.str()));
4026   } else {
4027     // Function without a declaration. Just give the return type.
4028     Result.AddResultTypeChunk(Result.getAllocator().CopyString(
4029         getFunctionType()->getReturnType().getAsString(Policy)));
4030   }
4031 
4032   // Next, the brackets and parameters.
4033   Result.AddChunk(Braced ? CodeCompletionString::CK_LeftBrace
4034                          : CodeCompletionString::CK_LeftParen);
4035   if (getKind() == CK_Aggregate)
4036     AddOverloadAggregateChunks(getAggregate(), Policy, Result, CurrentArg);
4037   else
4038     AddOverloadParameterChunks(S.getASTContext(), Policy, FDecl, Proto,
4039                                getFunctionProtoTypeLoc(), Result, CurrentArg);
4040   Result.AddChunk(Braced ? CodeCompletionString::CK_RightBrace
4041                          : CodeCompletionString::CK_RightParen);
4042 
4043   return Result.TakeString();
4044 }
4045 
4046 unsigned clang::getMacroUsagePriority(StringRef MacroName,
4047                                       const LangOptions &LangOpts,
4048                                       bool PreferredTypeIsPointer) {
4049   unsigned Priority = CCP_Macro;
4050 
4051   // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
4052   if (MacroName == "nil" || MacroName == "NULL" || MacroName == "Nil") {
4053     Priority = CCP_Constant;
4054     if (PreferredTypeIsPointer)
4055       Priority = Priority / CCF_SimilarTypeMatch;
4056   }
4057   // Treat "YES", "NO", "true", and "false" as constants.
4058   else if (MacroName == "YES" || MacroName == "NO" || MacroName == "true" ||
4059            MacroName == "false")
4060     Priority = CCP_Constant;
4061   // Treat "bool" as a type.
4062   else if (MacroName == "bool")
4063     Priority = CCP_Type + (LangOpts.ObjC ? CCD_bool_in_ObjC : 0);
4064 
4065   return Priority;
4066 }
4067 
4068 CXCursorKind clang::getCursorKindForDecl(const Decl *D) {
4069   if (!D)
4070     return CXCursor_UnexposedDecl;
4071 
4072   switch (D->getKind()) {
4073   case Decl::Enum:
4074     return CXCursor_EnumDecl;
4075   case Decl::EnumConstant:
4076     return CXCursor_EnumConstantDecl;
4077   case Decl::Field:
4078     return CXCursor_FieldDecl;
4079   case Decl::Function:
4080     return CXCursor_FunctionDecl;
4081   case Decl::ObjCCategory:
4082     return CXCursor_ObjCCategoryDecl;
4083   case Decl::ObjCCategoryImpl:
4084     return CXCursor_ObjCCategoryImplDecl;
4085   case Decl::ObjCImplementation:
4086     return CXCursor_ObjCImplementationDecl;
4087 
4088   case Decl::ObjCInterface:
4089     return CXCursor_ObjCInterfaceDecl;
4090   case Decl::ObjCIvar:
4091     return CXCursor_ObjCIvarDecl;
4092   case Decl::ObjCMethod:
4093     return cast<ObjCMethodDecl>(D)->isInstanceMethod()
4094                ? CXCursor_ObjCInstanceMethodDecl
4095                : CXCursor_ObjCClassMethodDecl;
4096   case Decl::CXXMethod:
4097     return CXCursor_CXXMethod;
4098   case Decl::CXXConstructor:
4099     return CXCursor_Constructor;
4100   case Decl::CXXDestructor:
4101     return CXCursor_Destructor;
4102   case Decl::CXXConversion:
4103     return CXCursor_ConversionFunction;
4104   case Decl::ObjCProperty:
4105     return CXCursor_ObjCPropertyDecl;
4106   case Decl::ObjCProtocol:
4107     return CXCursor_ObjCProtocolDecl;
4108   case Decl::ParmVar:
4109     return CXCursor_ParmDecl;
4110   case Decl::Typedef:
4111     return CXCursor_TypedefDecl;
4112   case Decl::TypeAlias:
4113     return CXCursor_TypeAliasDecl;
4114   case Decl::TypeAliasTemplate:
4115     return CXCursor_TypeAliasTemplateDecl;
4116   case Decl::Var:
4117     return CXCursor_VarDecl;
4118   case Decl::Namespace:
4119     return CXCursor_Namespace;
4120   case Decl::NamespaceAlias:
4121     return CXCursor_NamespaceAlias;
4122   case Decl::TemplateTypeParm:
4123     return CXCursor_TemplateTypeParameter;
4124   case Decl::NonTypeTemplateParm:
4125     return CXCursor_NonTypeTemplateParameter;
4126   case Decl::TemplateTemplateParm:
4127     return CXCursor_TemplateTemplateParameter;
4128   case Decl::FunctionTemplate:
4129     return CXCursor_FunctionTemplate;
4130   case Decl::ClassTemplate:
4131     return CXCursor_ClassTemplate;
4132   case Decl::AccessSpec:
4133     return CXCursor_CXXAccessSpecifier;
4134   case Decl::ClassTemplatePartialSpecialization:
4135     return CXCursor_ClassTemplatePartialSpecialization;
4136   case Decl::UsingDirective:
4137     return CXCursor_UsingDirective;
4138   case Decl::StaticAssert:
4139     return CXCursor_StaticAssert;
4140   case Decl::Friend:
4141     return CXCursor_FriendDecl;
4142   case Decl::TranslationUnit:
4143     return CXCursor_TranslationUnit;
4144 
4145   case Decl::Using:
4146   case Decl::UnresolvedUsingValue:
4147   case Decl::UnresolvedUsingTypename:
4148     return CXCursor_UsingDeclaration;
4149 
4150   case Decl::UsingEnum:
4151     return CXCursor_EnumDecl;
4152 
4153   case Decl::ObjCPropertyImpl:
4154     switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
4155     case ObjCPropertyImplDecl::Dynamic:
4156       return CXCursor_ObjCDynamicDecl;
4157 
4158     case ObjCPropertyImplDecl::Synthesize:
4159       return CXCursor_ObjCSynthesizeDecl;
4160     }
4161     llvm_unreachable("Unexpected Kind!");
4162 
4163   case Decl::Import:
4164     return CXCursor_ModuleImportDecl;
4165 
4166   case Decl::ObjCTypeParam:
4167     return CXCursor_TemplateTypeParameter;
4168 
4169   case Decl::Concept:
4170     return CXCursor_ConceptDecl;
4171 
4172   case Decl::LinkageSpec:
4173     return CXCursor_LinkageSpec;
4174 
4175   default:
4176     if (const auto *TD = dyn_cast<TagDecl>(D)) {
4177       switch (TD->getTagKind()) {
4178       case TagTypeKind::Interface: // fall through
4179       case TagTypeKind::Struct:
4180         return CXCursor_StructDecl;
4181       case TagTypeKind::Class:
4182         return CXCursor_ClassDecl;
4183       case TagTypeKind::Union:
4184         return CXCursor_UnionDecl;
4185       case TagTypeKind::Enum:
4186         return CXCursor_EnumDecl;
4187       }
4188     }
4189   }
4190 
4191   return CXCursor_UnexposedDecl;
4192 }
4193 
4194 static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
4195                             bool LoadExternal, bool IncludeUndefined,
4196                             bool TargetTypeIsPointer = false) {
4197   typedef CodeCompletionResult Result;
4198 
4199   Results.EnterNewScope();
4200 
4201   for (Preprocessor::macro_iterator M = PP.macro_begin(LoadExternal),
4202                                     MEnd = PP.macro_end(LoadExternal);
4203        M != MEnd; ++M) {
4204     auto MD = PP.getMacroDefinition(M->first);
4205     if (IncludeUndefined || MD) {
4206       MacroInfo *MI = MD.getMacroInfo();
4207       if (MI && MI->isUsedForHeaderGuard())
4208         continue;
4209 
4210       Results.AddResult(
4211           Result(M->first, MI,
4212                  getMacroUsagePriority(M->first->getName(), PP.getLangOpts(),
4213                                        TargetTypeIsPointer)));
4214     }
4215   }
4216 
4217   Results.ExitScope();
4218 }
4219 
4220 static void AddPrettyFunctionResults(const LangOptions &LangOpts,
4221                                      ResultBuilder &Results) {
4222   typedef CodeCompletionResult Result;
4223 
4224   Results.EnterNewScope();
4225 
4226   Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
4227   Results.AddResult(Result("__FUNCTION__", CCP_Constant));
4228   if (LangOpts.C99 || LangOpts.CPlusPlus11)
4229     Results.AddResult(Result("__func__", CCP_Constant));
4230   Results.ExitScope();
4231 }
4232 
4233 static void HandleCodeCompleteResults(Sema *S,
4234                                       CodeCompleteConsumer *CodeCompleter,
4235                                       const CodeCompletionContext &Context,
4236                                       CodeCompletionResult *Results,
4237                                       unsigned NumResults) {
4238   if (CodeCompleter)
4239     CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
4240 }
4241 
4242 static CodeCompletionContext
4243 mapCodeCompletionContext(Sema &S, Sema::ParserCompletionContext PCC) {
4244   switch (PCC) {
4245   case Sema::PCC_Namespace:
4246     return CodeCompletionContext::CCC_TopLevel;
4247 
4248   case Sema::PCC_Class:
4249     return CodeCompletionContext::CCC_ClassStructUnion;
4250 
4251   case Sema::PCC_ObjCInterface:
4252     return CodeCompletionContext::CCC_ObjCInterface;
4253 
4254   case Sema::PCC_ObjCImplementation:
4255     return CodeCompletionContext::CCC_ObjCImplementation;
4256 
4257   case Sema::PCC_ObjCInstanceVariableList:
4258     return CodeCompletionContext::CCC_ObjCIvarList;
4259 
4260   case Sema::PCC_Template:
4261   case Sema::PCC_MemberTemplate:
4262     if (S.CurContext->isFileContext())
4263       return CodeCompletionContext::CCC_TopLevel;
4264     if (S.CurContext->isRecord())
4265       return CodeCompletionContext::CCC_ClassStructUnion;
4266     return CodeCompletionContext::CCC_Other;
4267 
4268   case Sema::PCC_RecoveryInFunction:
4269     return CodeCompletionContext::CCC_Recovery;
4270 
4271   case Sema::PCC_ForInit:
4272     if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 ||
4273         S.getLangOpts().ObjC)
4274       return CodeCompletionContext::CCC_ParenthesizedExpression;
4275     else
4276       return CodeCompletionContext::CCC_Expression;
4277 
4278   case Sema::PCC_Expression:
4279     return CodeCompletionContext::CCC_Expression;
4280   case Sema::PCC_Condition:
4281     return CodeCompletionContext(CodeCompletionContext::CCC_Expression,
4282                                  S.getASTContext().BoolTy);
4283 
4284   case Sema::PCC_Statement:
4285     return CodeCompletionContext::CCC_Statement;
4286 
4287   case Sema::PCC_Type:
4288     return CodeCompletionContext::CCC_Type;
4289 
4290   case Sema::PCC_ParenthesizedExpression:
4291     return CodeCompletionContext::CCC_ParenthesizedExpression;
4292 
4293   case Sema::PCC_LocalDeclarationSpecifiers:
4294     return CodeCompletionContext::CCC_Type;
4295   case Sema::PCC_TopLevelOrExpression:
4296     return CodeCompletionContext::CCC_TopLevelOrExpression;
4297   }
4298 
4299   llvm_unreachable("Invalid ParserCompletionContext!");
4300 }
4301 
4302 /// If we're in a C++ virtual member function, add completion results
4303 /// that invoke the functions we override, since it's common to invoke the
4304 /// overridden function as well as adding new functionality.
4305 ///
4306 /// \param S The semantic analysis object for which we are generating results.
4307 ///
4308 /// \param InContext This context in which the nested-name-specifier preceding
4309 /// the code-completion point
4310 static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
4311                                   ResultBuilder &Results) {
4312   // Look through blocks.
4313   DeclContext *CurContext = S.CurContext;
4314   while (isa<BlockDecl>(CurContext))
4315     CurContext = CurContext->getParent();
4316 
4317   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
4318   if (!Method || !Method->isVirtual())
4319     return;
4320 
4321   // We need to have names for all of the parameters, if we're going to
4322   // generate a forwarding call.
4323   for (auto *P : Method->parameters())
4324     if (!P->getDeclName())
4325       return;
4326 
4327   PrintingPolicy Policy = getCompletionPrintingPolicy(S);
4328   for (const CXXMethodDecl *Overridden : Method->overridden_methods()) {
4329     CodeCompletionBuilder Builder(Results.getAllocator(),
4330                                   Results.getCodeCompletionTUInfo());
4331     if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
4332       continue;
4333 
4334     // If we need a nested-name-specifier, add one now.
4335     if (!InContext) {
4336       NestedNameSpecifier *NNS = getRequiredQualification(
4337           S.Context, CurContext, Overridden->getDeclContext());
4338       if (NNS) {
4339         std::string Str;
4340         llvm::raw_string_ostream OS(Str);
4341         NNS->print(OS, Policy);
4342         Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
4343       }
4344     } else if (!InContext->Equals(Overridden->getDeclContext()))
4345       continue;
4346 
4347     Builder.AddTypedTextChunk(
4348         Results.getAllocator().CopyString(Overridden->getNameAsString()));
4349     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4350     bool FirstParam = true;
4351     for (auto *P : Method->parameters()) {
4352       if (FirstParam)
4353         FirstParam = false;
4354       else
4355         Builder.AddChunk(CodeCompletionString::CK_Comma);
4356 
4357       Builder.AddPlaceholderChunk(
4358           Results.getAllocator().CopyString(P->getIdentifier()->getName()));
4359     }
4360     Builder.AddChunk(CodeCompletionString::CK_RightParen);
4361     Results.AddResult(CodeCompletionResult(
4362         Builder.TakeString(), CCP_SuperCompletion, CXCursor_CXXMethod,
4363         CXAvailability_Available, Overridden));
4364     Results.Ignore(Overridden);
4365   }
4366 }
4367 
4368 void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc,
4369                                     ModuleIdPath Path) {
4370   typedef CodeCompletionResult Result;
4371   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4372                         CodeCompleter->getCodeCompletionTUInfo(),
4373                         CodeCompletionContext::CCC_Other);
4374   Results.EnterNewScope();
4375 
4376   CodeCompletionAllocator &Allocator = Results.getAllocator();
4377   CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
4378   typedef CodeCompletionResult Result;
4379   if (Path.empty()) {
4380     // Enumerate all top-level modules.
4381     SmallVector<Module *, 8> Modules;
4382     PP.getHeaderSearchInfo().collectAllModules(Modules);
4383     for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
4384       Builder.AddTypedTextChunk(
4385           Builder.getAllocator().CopyString(Modules[I]->Name));
4386       Results.AddResult(Result(
4387           Builder.TakeString(), CCP_Declaration, CXCursor_ModuleImportDecl,
4388           Modules[I]->isAvailable() ? CXAvailability_Available
4389                                     : CXAvailability_NotAvailable));
4390     }
4391   } else if (getLangOpts().Modules) {
4392     // Load the named module.
4393     Module *Mod =
4394         PP.getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
4395                                         /*IsInclusionDirective=*/false);
4396     // Enumerate submodules.
4397     if (Mod) {
4398       for (auto *Submodule : Mod->submodules()) {
4399         Builder.AddTypedTextChunk(
4400             Builder.getAllocator().CopyString(Submodule->Name));
4401         Results.AddResult(Result(
4402             Builder.TakeString(), CCP_Declaration, CXCursor_ModuleImportDecl,
4403             Submodule->isAvailable() ? CXAvailability_Available
4404                                      : CXAvailability_NotAvailable));
4405       }
4406     }
4407   }
4408   Results.ExitScope();
4409   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4410                             Results.data(), Results.size());
4411 }
4412 
4413 void Sema::CodeCompleteOrdinaryName(Scope *S,
4414                                     ParserCompletionContext CompletionContext) {
4415   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4416                         CodeCompleter->getCodeCompletionTUInfo(),
4417                         mapCodeCompletionContext(*this, CompletionContext));
4418   Results.EnterNewScope();
4419 
4420   // Determine how to filter results, e.g., so that the names of
4421   // values (functions, enumerators, function templates, etc.) are
4422   // only allowed where we can have an expression.
4423   switch (CompletionContext) {
4424   case PCC_Namespace:
4425   case PCC_Class:
4426   case PCC_ObjCInterface:
4427   case PCC_ObjCImplementation:
4428   case PCC_ObjCInstanceVariableList:
4429   case PCC_Template:
4430   case PCC_MemberTemplate:
4431   case PCC_Type:
4432   case PCC_LocalDeclarationSpecifiers:
4433     Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4434     break;
4435 
4436   case PCC_Statement:
4437   case PCC_TopLevelOrExpression:
4438   case PCC_ParenthesizedExpression:
4439   case PCC_Expression:
4440   case PCC_ForInit:
4441   case PCC_Condition:
4442     if (WantTypesInContext(CompletionContext, getLangOpts()))
4443       Results.setFilter(&ResultBuilder::IsOrdinaryName);
4444     else
4445       Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
4446 
4447     if (getLangOpts().CPlusPlus)
4448       MaybeAddOverrideCalls(*this, /*InContext=*/nullptr, Results);
4449     break;
4450 
4451   case PCC_RecoveryInFunction:
4452     // Unfiltered
4453     break;
4454   }
4455 
4456   // If we are in a C++ non-static member function, check the qualifiers on
4457   // the member function to filter/prioritize the results list.
4458   auto ThisType = getCurrentThisType();
4459   if (!ThisType.isNull())
4460     Results.setObjectTypeQualifiers(ThisType->getPointeeType().getQualifiers(),
4461                                     VK_LValue);
4462 
4463   CodeCompletionDeclConsumer Consumer(Results, CurContext);
4464   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4465                      CodeCompleter->includeGlobals(),
4466                      CodeCompleter->loadExternal());
4467 
4468   AddOrdinaryNameResults(CompletionContext, S, *this, Results);
4469   Results.ExitScope();
4470 
4471   switch (CompletionContext) {
4472   case PCC_ParenthesizedExpression:
4473   case PCC_Expression:
4474   case PCC_Statement:
4475   case PCC_TopLevelOrExpression:
4476   case PCC_RecoveryInFunction:
4477     if (S->getFnParent())
4478       AddPrettyFunctionResults(getLangOpts(), Results);
4479     break;
4480 
4481   case PCC_Namespace:
4482   case PCC_Class:
4483   case PCC_ObjCInterface:
4484   case PCC_ObjCImplementation:
4485   case PCC_ObjCInstanceVariableList:
4486   case PCC_Template:
4487   case PCC_MemberTemplate:
4488   case PCC_ForInit:
4489   case PCC_Condition:
4490   case PCC_Type:
4491   case PCC_LocalDeclarationSpecifiers:
4492     break;
4493   }
4494 
4495   if (CodeCompleter->includeMacros())
4496     AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
4497 
4498   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4499                             Results.data(), Results.size());
4500 }
4501 
4502 static void
4503 AddClassMessageCompletions(Sema &SemaRef, Scope *S, ParsedType Receiver,
4504                            ArrayRef<const IdentifierInfo *> SelIdents,
4505                            bool AtArgumentExpression, bool IsSuper,
4506                            ResultBuilder &Results);
4507 
4508 void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
4509                                 bool AllowNonIdentifiers,
4510                                 bool AllowNestedNameSpecifiers) {
4511   typedef CodeCompletionResult Result;
4512   ResultBuilder Results(
4513       *this, CodeCompleter->getAllocator(),
4514       CodeCompleter->getCodeCompletionTUInfo(),
4515       AllowNestedNameSpecifiers
4516           // FIXME: Try to separate codepath leading here to deduce whether we
4517           // need an existing symbol or a new one.
4518           ? CodeCompletionContext::CCC_SymbolOrNewName
4519           : CodeCompletionContext::CCC_NewName);
4520   Results.EnterNewScope();
4521 
4522   // Type qualifiers can come after names.
4523   Results.AddResult(Result("const"));
4524   Results.AddResult(Result("volatile"));
4525   if (getLangOpts().C99)
4526     Results.AddResult(Result("restrict"));
4527 
4528   if (getLangOpts().CPlusPlus) {
4529     if (getLangOpts().CPlusPlus11 &&
4530         (DS.getTypeSpecType() == DeclSpec::TST_class ||
4531          DS.getTypeSpecType() == DeclSpec::TST_struct))
4532       Results.AddResult("final");
4533 
4534     if (AllowNonIdentifiers) {
4535       Results.AddResult(Result("operator"));
4536     }
4537 
4538     // Add nested-name-specifiers.
4539     if (AllowNestedNameSpecifiers) {
4540       Results.allowNestedNameSpecifiers();
4541       Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
4542       CodeCompletionDeclConsumer Consumer(Results, CurContext);
4543       LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
4544                          CodeCompleter->includeGlobals(),
4545                          CodeCompleter->loadExternal());
4546       Results.setFilter(nullptr);
4547     }
4548   }
4549   Results.ExitScope();
4550 
4551   // If we're in a context where we might have an expression (rather than a
4552   // declaration), and what we've seen so far is an Objective-C type that could
4553   // be a receiver of a class message, this may be a class message send with
4554   // the initial opening bracket '[' missing. Add appropriate completions.
4555   if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
4556       DS.getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
4557       DS.getTypeSpecType() == DeclSpec::TST_typename &&
4558       DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
4559       DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
4560       !DS.isTypeAltiVecVector() && S &&
4561       (S->getFlags() & Scope::DeclScope) != 0 &&
4562       (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
4563                         Scope::FunctionPrototypeScope | Scope::AtCatchScope)) ==
4564           0) {
4565     ParsedType T = DS.getRepAsType();
4566     if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
4567       AddClassMessageCompletions(*this, S, T, std::nullopt, false, false,
4568                                  Results);
4569   }
4570 
4571   // Note that we intentionally suppress macro results here, since we do not
4572   // encourage using macros to produce the names of entities.
4573 
4574   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4575                             Results.data(), Results.size());
4576 }
4577 
4578 static const char *underscoreAttrScope(llvm::StringRef Scope) {
4579   if (Scope == "clang")
4580     return "_Clang";
4581   if (Scope == "gnu")
4582     return "__gnu__";
4583   return nullptr;
4584 }
4585 
4586 static const char *noUnderscoreAttrScope(llvm::StringRef Scope) {
4587   if (Scope == "_Clang")
4588     return "clang";
4589   if (Scope == "__gnu__")
4590     return "gnu";
4591   return nullptr;
4592 }
4593 
4594 void Sema::CodeCompleteAttribute(AttributeCommonInfo::Syntax Syntax,
4595                                  AttributeCompletion Completion,
4596                                  const IdentifierInfo *InScope) {
4597   if (Completion == AttributeCompletion::None)
4598     return;
4599   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4600                         CodeCompleter->getCodeCompletionTUInfo(),
4601                         CodeCompletionContext::CCC_Attribute);
4602 
4603   // We're going to iterate over the normalized spellings of the attribute.
4604   // These don't include "underscore guarding": the normalized spelling is
4605   // clang::foo but you can also write _Clang::__foo__.
4606   //
4607   // (Clang supports a mix like clang::__foo__ but we won't suggest it: either
4608   // you care about clashing with macros or you don't).
4609   //
4610   // So if we're already in a scope, we determine its canonical spellings
4611   // (for comparison with normalized attr spelling) and remember whether it was
4612   // underscore-guarded (so we know how to spell contained attributes).
4613   llvm::StringRef InScopeName;
4614   bool InScopeUnderscore = false;
4615   if (InScope) {
4616     InScopeName = InScope->getName();
4617     if (const char *NoUnderscore = noUnderscoreAttrScope(InScopeName)) {
4618       InScopeName = NoUnderscore;
4619       InScopeUnderscore = true;
4620     }
4621   }
4622   bool SyntaxSupportsGuards = Syntax == AttributeCommonInfo::AS_GNU ||
4623                               Syntax == AttributeCommonInfo::AS_CXX11 ||
4624                               Syntax == AttributeCommonInfo::AS_C23;
4625 
4626   llvm::DenseSet<llvm::StringRef> FoundScopes;
4627   auto AddCompletions = [&](const ParsedAttrInfo &A) {
4628     if (A.IsTargetSpecific && !A.existsInTarget(Context.getTargetInfo()))
4629       return;
4630     if (!A.acceptsLangOpts(getLangOpts()))
4631       return;
4632     for (const auto &S : A.Spellings) {
4633       if (S.Syntax != Syntax)
4634         continue;
4635       llvm::StringRef Name = S.NormalizedFullName;
4636       llvm::StringRef Scope;
4637       if ((Syntax == AttributeCommonInfo::AS_CXX11 ||
4638            Syntax == AttributeCommonInfo::AS_C23)) {
4639         std::tie(Scope, Name) = Name.split("::");
4640         if (Name.empty()) // oops, unscoped
4641           std::swap(Name, Scope);
4642       }
4643 
4644       // Do we just want a list of scopes rather than attributes?
4645       if (Completion == AttributeCompletion::Scope) {
4646         // Make sure to emit each scope only once.
4647         if (!Scope.empty() && FoundScopes.insert(Scope).second) {
4648           Results.AddResult(
4649               CodeCompletionResult(Results.getAllocator().CopyString(Scope)));
4650           // Include alternate form (__gnu__ instead of gnu).
4651           if (const char *Scope2 = underscoreAttrScope(Scope))
4652             Results.AddResult(CodeCompletionResult(Scope2));
4653         }
4654         continue;
4655       }
4656 
4657       // If a scope was specified, it must match but we don't need to print it.
4658       if (!InScopeName.empty()) {
4659         if (Scope != InScopeName)
4660           continue;
4661         Scope = "";
4662       }
4663 
4664       auto Add = [&](llvm::StringRef Scope, llvm::StringRef Name,
4665                      bool Underscores) {
4666         CodeCompletionBuilder Builder(Results.getAllocator(),
4667                                       Results.getCodeCompletionTUInfo());
4668         llvm::SmallString<32> Text;
4669         if (!Scope.empty()) {
4670           Text.append(Scope);
4671           Text.append("::");
4672         }
4673         if (Underscores)
4674           Text.append("__");
4675         Text.append(Name);
4676         if (Underscores)
4677           Text.append("__");
4678         Builder.AddTypedTextChunk(Results.getAllocator().CopyString(Text));
4679 
4680         if (!A.ArgNames.empty()) {
4681           Builder.AddChunk(CodeCompletionString::CK_LeftParen, "(");
4682           bool First = true;
4683           for (const char *Arg : A.ArgNames) {
4684             if (!First)
4685               Builder.AddChunk(CodeCompletionString::CK_Comma, ", ");
4686             First = false;
4687             Builder.AddPlaceholderChunk(Arg);
4688           }
4689           Builder.AddChunk(CodeCompletionString::CK_RightParen, ")");
4690         }
4691 
4692         Results.AddResult(Builder.TakeString());
4693       };
4694 
4695       // Generate the non-underscore-guarded result.
4696       // Note this is (a suffix of) the NormalizedFullName, no need to copy.
4697       // If an underscore-guarded scope was specified, only the
4698       // underscore-guarded attribute name is relevant.
4699       if (!InScopeUnderscore)
4700         Add(Scope, Name, /*Underscores=*/false);
4701 
4702       // Generate the underscore-guarded version, for syntaxes that support it.
4703       // We skip this if the scope was already spelled and not guarded, or
4704       // we must spell it and can't guard it.
4705       if (!(InScope && !InScopeUnderscore) && SyntaxSupportsGuards) {
4706         llvm::SmallString<32> Guarded;
4707         if (Scope.empty()) {
4708           Add(Scope, Name, /*Underscores=*/true);
4709         } else {
4710           const char *GuardedScope = underscoreAttrScope(Scope);
4711           if (!GuardedScope)
4712             continue;
4713           Add(GuardedScope, Name, /*Underscores=*/true);
4714         }
4715       }
4716 
4717       // It may be nice to include the Kind so we can look up the docs later.
4718     }
4719   };
4720 
4721   for (const auto *A : ParsedAttrInfo::getAllBuiltin())
4722     AddCompletions(*A);
4723   for (const auto &Entry : ParsedAttrInfoRegistry::entries())
4724     AddCompletions(*Entry.instantiate());
4725 
4726   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4727                             Results.data(), Results.size());
4728 }
4729 
4730 struct Sema::CodeCompleteExpressionData {
4731   CodeCompleteExpressionData(QualType PreferredType = QualType(),
4732                              bool IsParenthesized = false)
4733       : PreferredType(PreferredType), IntegralConstantExpression(false),
4734         ObjCCollection(false), IsParenthesized(IsParenthesized) {}
4735 
4736   QualType PreferredType;
4737   bool IntegralConstantExpression;
4738   bool ObjCCollection;
4739   bool IsParenthesized;
4740   SmallVector<Decl *, 4> IgnoreDecls;
4741 };
4742 
4743 namespace {
4744 /// Information that allows to avoid completing redundant enumerators.
4745 struct CoveredEnumerators {
4746   llvm::SmallPtrSet<EnumConstantDecl *, 8> Seen;
4747   NestedNameSpecifier *SuggestedQualifier = nullptr;
4748 };
4749 } // namespace
4750 
4751 static void AddEnumerators(ResultBuilder &Results, ASTContext &Context,
4752                            EnumDecl *Enum, DeclContext *CurContext,
4753                            const CoveredEnumerators &Enumerators) {
4754   NestedNameSpecifier *Qualifier = Enumerators.SuggestedQualifier;
4755   if (Context.getLangOpts().CPlusPlus && !Qualifier && Enumerators.Seen.empty()) {
4756     // If there are no prior enumerators in C++, check whether we have to
4757     // qualify the names of the enumerators that we suggest, because they
4758     // may not be visible in this scope.
4759     Qualifier = getRequiredQualification(Context, CurContext, Enum);
4760   }
4761 
4762   Results.EnterNewScope();
4763   for (auto *E : Enum->enumerators()) {
4764     if (Enumerators.Seen.count(E))
4765       continue;
4766 
4767     CodeCompletionResult R(E, CCP_EnumInCase, Qualifier);
4768     Results.AddResult(R, CurContext, nullptr, false);
4769   }
4770   Results.ExitScope();
4771 }
4772 
4773 /// Try to find a corresponding FunctionProtoType for function-like types (e.g.
4774 /// function pointers, std::function, etc).
4775 static const FunctionProtoType *TryDeconstructFunctionLike(QualType T) {
4776   assert(!T.isNull());
4777   // Try to extract first template argument from std::function<> and similar.
4778   // Note we only handle the sugared types, they closely match what users wrote.
4779   // We explicitly choose to not handle ClassTemplateSpecializationDecl.
4780   if (auto *Specialization = T->getAs<TemplateSpecializationType>()) {
4781     if (Specialization->template_arguments().size() != 1)
4782       return nullptr;
4783     const TemplateArgument &Argument = Specialization->template_arguments()[0];
4784     if (Argument.getKind() != TemplateArgument::Type)
4785       return nullptr;
4786     return Argument.getAsType()->getAs<FunctionProtoType>();
4787   }
4788   // Handle other cases.
4789   if (T->isPointerType())
4790     T = T->getPointeeType();
4791   return T->getAs<FunctionProtoType>();
4792 }
4793 
4794 /// Adds a pattern completion for a lambda expression with the specified
4795 /// parameter types and placeholders for parameter names.
4796 static void AddLambdaCompletion(ResultBuilder &Results,
4797                                 llvm::ArrayRef<QualType> Parameters,
4798                                 const LangOptions &LangOpts) {
4799   if (!Results.includeCodePatterns())
4800     return;
4801   CodeCompletionBuilder Completion(Results.getAllocator(),
4802                                    Results.getCodeCompletionTUInfo());
4803   // [](<parameters>) {}
4804   Completion.AddChunk(CodeCompletionString::CK_LeftBracket);
4805   Completion.AddPlaceholderChunk("=");
4806   Completion.AddChunk(CodeCompletionString::CK_RightBracket);
4807   if (!Parameters.empty()) {
4808     Completion.AddChunk(CodeCompletionString::CK_LeftParen);
4809     bool First = true;
4810     for (auto Parameter : Parameters) {
4811       if (!First)
4812         Completion.AddChunk(CodeCompletionString::ChunkKind::CK_Comma);
4813       else
4814         First = false;
4815 
4816       constexpr llvm::StringLiteral NamePlaceholder = "!#!NAME_GOES_HERE!#!";
4817       std::string Type = std::string(NamePlaceholder);
4818       Parameter.getAsStringInternal(Type, PrintingPolicy(LangOpts));
4819       llvm::StringRef Prefix, Suffix;
4820       std::tie(Prefix, Suffix) = llvm::StringRef(Type).split(NamePlaceholder);
4821       Prefix = Prefix.rtrim();
4822       Suffix = Suffix.ltrim();
4823 
4824       Completion.AddTextChunk(Completion.getAllocator().CopyString(Prefix));
4825       Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4826       Completion.AddPlaceholderChunk("parameter");
4827       Completion.AddTextChunk(Completion.getAllocator().CopyString(Suffix));
4828     };
4829     Completion.AddChunk(CodeCompletionString::CK_RightParen);
4830   }
4831   Completion.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace);
4832   Completion.AddChunk(CodeCompletionString::CK_LeftBrace);
4833   Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4834   Completion.AddPlaceholderChunk("body");
4835   Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4836   Completion.AddChunk(CodeCompletionString::CK_RightBrace);
4837 
4838   Results.AddResult(Completion.TakeString());
4839 }
4840 
4841 /// Perform code-completion in an expression context when we know what
4842 /// type we're looking for.
4843 void Sema::CodeCompleteExpression(Scope *S,
4844                                   const CodeCompleteExpressionData &Data) {
4845   ResultBuilder Results(
4846       *this, CodeCompleter->getAllocator(),
4847       CodeCompleter->getCodeCompletionTUInfo(),
4848       CodeCompletionContext(
4849           Data.IsParenthesized
4850               ? CodeCompletionContext::CCC_ParenthesizedExpression
4851               : CodeCompletionContext::CCC_Expression,
4852           Data.PreferredType));
4853   auto PCC =
4854       Data.IsParenthesized ? PCC_ParenthesizedExpression : PCC_Expression;
4855   if (Data.ObjCCollection)
4856     Results.setFilter(&ResultBuilder::IsObjCCollection);
4857   else if (Data.IntegralConstantExpression)
4858     Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
4859   else if (WantTypesInContext(PCC, getLangOpts()))
4860     Results.setFilter(&ResultBuilder::IsOrdinaryName);
4861   else
4862     Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
4863 
4864   if (!Data.PreferredType.isNull())
4865     Results.setPreferredType(Data.PreferredType.getNonReferenceType());
4866 
4867   // Ignore any declarations that we were told that we don't care about.
4868   for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
4869     Results.Ignore(Data.IgnoreDecls[I]);
4870 
4871   CodeCompletionDeclConsumer Consumer(Results, CurContext);
4872   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4873                      CodeCompleter->includeGlobals(),
4874                      CodeCompleter->loadExternal());
4875 
4876   Results.EnterNewScope();
4877   AddOrdinaryNameResults(PCC, S, *this, Results);
4878   Results.ExitScope();
4879 
4880   bool PreferredTypeIsPointer = false;
4881   if (!Data.PreferredType.isNull()) {
4882     PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType() ||
4883                              Data.PreferredType->isMemberPointerType() ||
4884                              Data.PreferredType->isBlockPointerType();
4885     if (Data.PreferredType->isEnumeralType()) {
4886       EnumDecl *Enum = Data.PreferredType->castAs<EnumType>()->getDecl();
4887       if (auto *Def = Enum->getDefinition())
4888         Enum = Def;
4889       // FIXME: collect covered enumerators in cases like:
4890       //        if (x == my_enum::one) { ... } else if (x == ^) {}
4891       AddEnumerators(Results, Context, Enum, CurContext, CoveredEnumerators());
4892     }
4893   }
4894 
4895   if (S->getFnParent() && !Data.ObjCCollection &&
4896       !Data.IntegralConstantExpression)
4897     AddPrettyFunctionResults(getLangOpts(), Results);
4898 
4899   if (CodeCompleter->includeMacros())
4900     AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false,
4901                     PreferredTypeIsPointer);
4902 
4903   // Complete a lambda expression when preferred type is a function.
4904   if (!Data.PreferredType.isNull() && getLangOpts().CPlusPlus11) {
4905     if (const FunctionProtoType *F =
4906             TryDeconstructFunctionLike(Data.PreferredType))
4907       AddLambdaCompletion(Results, F->getParamTypes(), getLangOpts());
4908   }
4909 
4910   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4911                             Results.data(), Results.size());
4912 }
4913 
4914 void Sema::CodeCompleteExpression(Scope *S, QualType PreferredType,
4915                                   bool IsParenthesized) {
4916   return CodeCompleteExpression(
4917       S, CodeCompleteExpressionData(PreferredType, IsParenthesized));
4918 }
4919 
4920 void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E,
4921                                          QualType PreferredType) {
4922   if (E.isInvalid())
4923     CodeCompleteExpression(S, PreferredType);
4924   else if (getLangOpts().ObjC)
4925     CodeCompleteObjCInstanceMessage(S, E.get(), std::nullopt, false);
4926 }
4927 
4928 /// The set of properties that have already been added, referenced by
4929 /// property name.
4930 typedef llvm::SmallPtrSet<const IdentifierInfo *, 16> AddedPropertiesSet;
4931 
4932 /// Retrieve the container definition, if any?
4933 static ObjCContainerDecl *getContainerDef(ObjCContainerDecl *Container) {
4934   if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4935     if (Interface->hasDefinition())
4936       return Interface->getDefinition();
4937 
4938     return Interface;
4939   }
4940 
4941   if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4942     if (Protocol->hasDefinition())
4943       return Protocol->getDefinition();
4944 
4945     return Protocol;
4946   }
4947   return Container;
4948 }
4949 
4950 /// Adds a block invocation code completion result for the given block
4951 /// declaration \p BD.
4952 static void AddObjCBlockCall(ASTContext &Context, const PrintingPolicy &Policy,
4953                              CodeCompletionBuilder &Builder,
4954                              const NamedDecl *BD,
4955                              const FunctionTypeLoc &BlockLoc,
4956                              const FunctionProtoTypeLoc &BlockProtoLoc) {
4957   Builder.AddResultTypeChunk(
4958       GetCompletionTypeString(BlockLoc.getReturnLoc().getType(), Context,
4959                               Policy, Builder.getAllocator()));
4960 
4961   AddTypedNameChunk(Context, Policy, BD, Builder);
4962   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4963 
4964   if (BlockProtoLoc && BlockProtoLoc.getTypePtr()->isVariadic()) {
4965     Builder.AddPlaceholderChunk("...");
4966   } else {
4967     for (unsigned I = 0, N = BlockLoc.getNumParams(); I != N; ++I) {
4968       if (I)
4969         Builder.AddChunk(CodeCompletionString::CK_Comma);
4970 
4971       // Format the placeholder string.
4972       std::string PlaceholderStr =
4973           FormatFunctionParameter(Policy, BlockLoc.getParam(I));
4974 
4975       if (I == N - 1 && BlockProtoLoc &&
4976           BlockProtoLoc.getTypePtr()->isVariadic())
4977         PlaceholderStr += ", ...";
4978 
4979       // Add the placeholder string.
4980       Builder.AddPlaceholderChunk(
4981           Builder.getAllocator().CopyString(PlaceholderStr));
4982     }
4983   }
4984 
4985   Builder.AddChunk(CodeCompletionString::CK_RightParen);
4986 }
4987 
4988 static void
4989 AddObjCProperties(const CodeCompletionContext &CCContext,
4990                   ObjCContainerDecl *Container, bool AllowCategories,
4991                   bool AllowNullaryMethods, DeclContext *CurContext,
4992                   AddedPropertiesSet &AddedProperties, ResultBuilder &Results,
4993                   bool IsBaseExprStatement = false,
4994                   bool IsClassProperty = false, bool InOriginalClass = true) {
4995   typedef CodeCompletionResult Result;
4996 
4997   // Retrieve the definition.
4998   Container = getContainerDef(Container);
4999 
5000   // Add properties in this container.
5001   const auto AddProperty = [&](const ObjCPropertyDecl *P) {
5002     if (!AddedProperties.insert(P->getIdentifier()).second)
5003       return;
5004 
5005     // FIXME: Provide block invocation completion for non-statement
5006     // expressions.
5007     if (!P->getType().getTypePtr()->isBlockPointerType() ||
5008         !IsBaseExprStatement) {
5009       Result R = Result(P, Results.getBasePriority(P), nullptr);
5010       if (!InOriginalClass)
5011         setInBaseClass(R);
5012       Results.MaybeAddResult(R, CurContext);
5013       return;
5014     }
5015 
5016     // Block setter and invocation completion is provided only when we are able
5017     // to find the FunctionProtoTypeLoc with parameter names for the block.
5018     FunctionTypeLoc BlockLoc;
5019     FunctionProtoTypeLoc BlockProtoLoc;
5020     findTypeLocationForBlockDecl(P->getTypeSourceInfo(), BlockLoc,
5021                                  BlockProtoLoc);
5022     if (!BlockLoc) {
5023       Result R = Result(P, Results.getBasePriority(P), nullptr);
5024       if (!InOriginalClass)
5025         setInBaseClass(R);
5026       Results.MaybeAddResult(R, CurContext);
5027       return;
5028     }
5029 
5030     // The default completion result for block properties should be the block
5031     // invocation completion when the base expression is a statement.
5032     CodeCompletionBuilder Builder(Results.getAllocator(),
5033                                   Results.getCodeCompletionTUInfo());
5034     AddObjCBlockCall(Container->getASTContext(),
5035                      getCompletionPrintingPolicy(Results.getSema()), Builder, P,
5036                      BlockLoc, BlockProtoLoc);
5037     Result R = Result(Builder.TakeString(), P, Results.getBasePriority(P));
5038     if (!InOriginalClass)
5039       setInBaseClass(R);
5040     Results.MaybeAddResult(R, CurContext);
5041 
5042     // Provide additional block setter completion iff the base expression is a
5043     // statement and the block property is mutable.
5044     if (!P->isReadOnly()) {
5045       CodeCompletionBuilder Builder(Results.getAllocator(),
5046                                     Results.getCodeCompletionTUInfo());
5047       AddResultTypeChunk(Container->getASTContext(),
5048                          getCompletionPrintingPolicy(Results.getSema()), P,
5049                          CCContext.getBaseType(), Builder);
5050       Builder.AddTypedTextChunk(
5051           Results.getAllocator().CopyString(P->getName()));
5052       Builder.AddChunk(CodeCompletionString::CK_Equal);
5053 
5054       std::string PlaceholderStr = formatBlockPlaceholder(
5055           getCompletionPrintingPolicy(Results.getSema()), P, BlockLoc,
5056           BlockProtoLoc, /*SuppressBlockName=*/true);
5057       // Add the placeholder string.
5058       Builder.AddPlaceholderChunk(
5059           Builder.getAllocator().CopyString(PlaceholderStr));
5060 
5061       // When completing blocks properties that return void the default
5062       // property completion result should show up before the setter,
5063       // otherwise the setter completion should show up before the default
5064       // property completion, as we normally want to use the result of the
5065       // call.
5066       Result R =
5067           Result(Builder.TakeString(), P,
5068                  Results.getBasePriority(P) +
5069                      (BlockLoc.getTypePtr()->getReturnType()->isVoidType()
5070                           ? CCD_BlockPropertySetter
5071                           : -CCD_BlockPropertySetter));
5072       if (!InOriginalClass)
5073         setInBaseClass(R);
5074       Results.MaybeAddResult(R, CurContext);
5075     }
5076   };
5077 
5078   if (IsClassProperty) {
5079     for (const auto *P : Container->class_properties())
5080       AddProperty(P);
5081   } else {
5082     for (const auto *P : Container->instance_properties())
5083       AddProperty(P);
5084   }
5085 
5086   // Add nullary methods or implicit class properties
5087   if (AllowNullaryMethods) {
5088     ASTContext &Context = Container->getASTContext();
5089     PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
5090     // Adds a method result
5091     const auto AddMethod = [&](const ObjCMethodDecl *M) {
5092       const IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0);
5093       if (!Name)
5094         return;
5095       if (!AddedProperties.insert(Name).second)
5096         return;
5097       CodeCompletionBuilder Builder(Results.getAllocator(),
5098                                     Results.getCodeCompletionTUInfo());
5099       AddResultTypeChunk(Context, Policy, M, CCContext.getBaseType(), Builder);
5100       Builder.AddTypedTextChunk(
5101           Results.getAllocator().CopyString(Name->getName()));
5102       Result R = Result(Builder.TakeString(), M,
5103                         CCP_MemberDeclaration + CCD_MethodAsProperty);
5104       if (!InOriginalClass)
5105         setInBaseClass(R);
5106       Results.MaybeAddResult(R, CurContext);
5107     };
5108 
5109     if (IsClassProperty) {
5110       for (const auto *M : Container->methods()) {
5111         // Gather the class method that can be used as implicit property
5112         // getters. Methods with arguments or methods that return void aren't
5113         // added to the results as they can't be used as a getter.
5114         if (!M->getSelector().isUnarySelector() ||
5115             M->getReturnType()->isVoidType() || M->isInstanceMethod())
5116           continue;
5117         AddMethod(M);
5118       }
5119     } else {
5120       for (auto *M : Container->methods()) {
5121         if (M->getSelector().isUnarySelector())
5122           AddMethod(M);
5123       }
5124     }
5125   }
5126 
5127   // Add properties in referenced protocols.
5128   if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5129     for (auto *P : Protocol->protocols())
5130       AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
5131                         CurContext, AddedProperties, Results,
5132                         IsBaseExprStatement, IsClassProperty,
5133                         /*InOriginalClass*/ false);
5134   } else if (ObjCInterfaceDecl *IFace =
5135                  dyn_cast<ObjCInterfaceDecl>(Container)) {
5136     if (AllowCategories) {
5137       // Look through categories.
5138       for (auto *Cat : IFace->known_categories())
5139         AddObjCProperties(CCContext, Cat, AllowCategories, AllowNullaryMethods,
5140                           CurContext, AddedProperties, Results,
5141                           IsBaseExprStatement, IsClassProperty,
5142                           InOriginalClass);
5143     }
5144 
5145     // Look through protocols.
5146     for (auto *I : IFace->all_referenced_protocols())
5147       AddObjCProperties(CCContext, I, AllowCategories, AllowNullaryMethods,
5148                         CurContext, AddedProperties, Results,
5149                         IsBaseExprStatement, IsClassProperty,
5150                         /*InOriginalClass*/ false);
5151 
5152     // Look in the superclass.
5153     if (IFace->getSuperClass())
5154       AddObjCProperties(CCContext, IFace->getSuperClass(), AllowCategories,
5155                         AllowNullaryMethods, CurContext, AddedProperties,
5156                         Results, IsBaseExprStatement, IsClassProperty,
5157                         /*InOriginalClass*/ false);
5158   } else if (const auto *Category =
5159                  dyn_cast<ObjCCategoryDecl>(Container)) {
5160     // Look through protocols.
5161     for (auto *P : Category->protocols())
5162       AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
5163                         CurContext, AddedProperties, Results,
5164                         IsBaseExprStatement, IsClassProperty,
5165                         /*InOriginalClass*/ false);
5166   }
5167 }
5168 
5169 static void
5170 AddRecordMembersCompletionResults(Sema &SemaRef, ResultBuilder &Results,
5171                                   Scope *S, QualType BaseType,
5172                                   ExprValueKind BaseKind, RecordDecl *RD,
5173                                   std::optional<FixItHint> AccessOpFixIt) {
5174   // Indicate that we are performing a member access, and the cv-qualifiers
5175   // for the base object type.
5176   Results.setObjectTypeQualifiers(BaseType.getQualifiers(), BaseKind);
5177 
5178   // Access to a C/C++ class, struct, or union.
5179   Results.allowNestedNameSpecifiers();
5180   std::vector<FixItHint> FixIts;
5181   if (AccessOpFixIt)
5182     FixIts.emplace_back(*AccessOpFixIt);
5183   CodeCompletionDeclConsumer Consumer(Results, RD, BaseType, std::move(FixIts));
5184   SemaRef.LookupVisibleDecls(RD, Sema::LookupMemberName, Consumer,
5185                              SemaRef.CodeCompleter->includeGlobals(),
5186                              /*IncludeDependentBases=*/true,
5187                              SemaRef.CodeCompleter->loadExternal());
5188 
5189   if (SemaRef.getLangOpts().CPlusPlus) {
5190     if (!Results.empty()) {
5191       // The "template" keyword can follow "->" or "." in the grammar.
5192       // However, we only want to suggest the template keyword if something
5193       // is dependent.
5194       bool IsDependent = BaseType->isDependentType();
5195       if (!IsDependent) {
5196         for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
5197           if (DeclContext *Ctx = DepScope->getEntity()) {
5198             IsDependent = Ctx->isDependentContext();
5199             break;
5200           }
5201       }
5202 
5203       if (IsDependent)
5204         Results.AddResult(CodeCompletionResult("template"));
5205     }
5206   }
5207 }
5208 
5209 // Returns the RecordDecl inside the BaseType, falling back to primary template
5210 // in case of specializations. Since we might not have a decl for the
5211 // instantiation/specialization yet, e.g. dependent code.
5212 static RecordDecl *getAsRecordDecl(QualType BaseType) {
5213   BaseType = BaseType.getNonReferenceType();
5214   if (auto *RD = BaseType->getAsRecordDecl()) {
5215     if (const auto *CTSD =
5216             llvm::dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
5217       // Template might not be instantiated yet, fall back to primary template
5218       // in such cases.
5219       if (CTSD->getTemplateSpecializationKind() == TSK_Undeclared)
5220         RD = CTSD->getSpecializedTemplate()->getTemplatedDecl();
5221     }
5222     return RD;
5223   }
5224 
5225   if (const auto *TST = BaseType->getAs<TemplateSpecializationType>()) {
5226     if (const auto *TD = dyn_cast_or_null<ClassTemplateDecl>(
5227             TST->getTemplateName().getAsTemplateDecl())) {
5228       return TD->getTemplatedDecl();
5229     }
5230   }
5231 
5232   return nullptr;
5233 }
5234 
5235 namespace {
5236 // Collects completion-relevant information about a concept-constrainted type T.
5237 // In particular, examines the constraint expressions to find members of T.
5238 //
5239 // The design is very simple: we walk down each constraint looking for
5240 // expressions of the form T.foo().
5241 // If we're extra lucky, the return type is specified.
5242 // We don't do any clever handling of && or || in constraint expressions, we
5243 // take members from both branches.
5244 //
5245 // For example, given:
5246 //   template <class T> concept X = requires (T t, string& s) { t.print(s); };
5247 //   template <X U> void foo(U u) { u.^ }
5248 // We want to suggest the inferred member function 'print(string)'.
5249 // We see that u has type U, so X<U> holds.
5250 // X<U> requires t.print(s) to be valid, where t has type U (substituted for T).
5251 // By looking at the CallExpr we find the signature of print().
5252 //
5253 // While we tend to know in advance which kind of members (access via . -> ::)
5254 // we want, it's simpler just to gather them all and post-filter.
5255 //
5256 // FIXME: some of this machinery could be used for non-concept type-parms too,
5257 // enabling completion for type parameters based on other uses of that param.
5258 //
5259 // FIXME: there are other cases where a type can be constrained by a concept,
5260 // e.g. inside `if constexpr(ConceptSpecializationExpr) { ... }`
5261 class ConceptInfo {
5262 public:
5263   // Describes a likely member of a type, inferred by concept constraints.
5264   // Offered as a code completion for T. T-> and T:: contexts.
5265   struct Member {
5266     // Always non-null: we only handle members with ordinary identifier names.
5267     const IdentifierInfo *Name = nullptr;
5268     // Set for functions we've seen called.
5269     // We don't have the declared parameter types, only the actual types of
5270     // arguments we've seen. These are still valuable, as it's hard to render
5271     // a useful function completion with neither parameter types nor names!
5272     std::optional<SmallVector<QualType, 1>> ArgTypes;
5273     // Whether this is accessed as T.member, T->member, or T::member.
5274     enum AccessOperator {
5275       Colons,
5276       Arrow,
5277       Dot,
5278     } Operator = Dot;
5279     // What's known about the type of a variable or return type of a function.
5280     const TypeConstraint *ResultType = nullptr;
5281     // FIXME: also track:
5282     //   - kind of entity (function/variable/type), to expose structured results
5283     //   - template args kinds/types, as a proxy for template params
5284 
5285     // For now we simply return these results as "pattern" strings.
5286     CodeCompletionString *render(Sema &S, CodeCompletionAllocator &Alloc,
5287                                  CodeCompletionTUInfo &Info) const {
5288       CodeCompletionBuilder B(Alloc, Info);
5289       // Result type
5290       if (ResultType) {
5291         std::string AsString;
5292         {
5293           llvm::raw_string_ostream OS(AsString);
5294           QualType ExactType = deduceType(*ResultType);
5295           if (!ExactType.isNull())
5296             ExactType.print(OS, getCompletionPrintingPolicy(S));
5297           else
5298             ResultType->print(OS, getCompletionPrintingPolicy(S));
5299         }
5300         B.AddResultTypeChunk(Alloc.CopyString(AsString));
5301       }
5302       // Member name
5303       B.AddTypedTextChunk(Alloc.CopyString(Name->getName()));
5304       // Function argument list
5305       if (ArgTypes) {
5306         B.AddChunk(clang::CodeCompletionString::CK_LeftParen);
5307         bool First = true;
5308         for (QualType Arg : *ArgTypes) {
5309           if (First)
5310             First = false;
5311           else {
5312             B.AddChunk(clang::CodeCompletionString::CK_Comma);
5313             B.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace);
5314           }
5315           B.AddPlaceholderChunk(Alloc.CopyString(
5316               Arg.getAsString(getCompletionPrintingPolicy(S))));
5317         }
5318         B.AddChunk(clang::CodeCompletionString::CK_RightParen);
5319       }
5320       return B.TakeString();
5321     }
5322   };
5323 
5324   // BaseType is the type parameter T to infer members from.
5325   // T must be accessible within S, as we use it to find the template entity
5326   // that T is attached to in order to gather the relevant constraints.
5327   ConceptInfo(const TemplateTypeParmType &BaseType, Scope *S) {
5328     auto *TemplatedEntity = getTemplatedEntity(BaseType.getDecl(), S);
5329     for (const Expr *E : constraintsForTemplatedEntity(TemplatedEntity))
5330       believe(E, &BaseType);
5331   }
5332 
5333   std::vector<Member> members() {
5334     std::vector<Member> Results;
5335     for (const auto &E : this->Results)
5336       Results.push_back(E.second);
5337     llvm::sort(Results, [](const Member &L, const Member &R) {
5338       return L.Name->getName() < R.Name->getName();
5339     });
5340     return Results;
5341   }
5342 
5343 private:
5344   // Infer members of T, given that the expression E (dependent on T) is true.
5345   void believe(const Expr *E, const TemplateTypeParmType *T) {
5346     if (!E || !T)
5347       return;
5348     if (auto *CSE = dyn_cast<ConceptSpecializationExpr>(E)) {
5349       // If the concept is
5350       //   template <class A, class B> concept CD = f<A, B>();
5351       // And the concept specialization is
5352       //   CD<int, T>
5353       // Then we're substituting T for B, so we want to make f<A, B>() true
5354       // by adding members to B - i.e. believe(f<A, B>(), B);
5355       //
5356       // For simplicity:
5357       // - we don't attempt to substitute int for A
5358       // - when T is used in other ways (like CD<T*>) we ignore it
5359       ConceptDecl *CD = CSE->getNamedConcept();
5360       TemplateParameterList *Params = CD->getTemplateParameters();
5361       unsigned Index = 0;
5362       for (const auto &Arg : CSE->getTemplateArguments()) {
5363         if (Index >= Params->size())
5364           break; // Won't happen in valid code.
5365         if (isApprox(Arg, T)) {
5366           auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Params->getParam(Index));
5367           if (!TTPD)
5368             continue;
5369           // T was used as an argument, and bound to the parameter TT.
5370           auto *TT = cast<TemplateTypeParmType>(TTPD->getTypeForDecl());
5371           // So now we know the constraint as a function of TT is true.
5372           believe(CD->getConstraintExpr(), TT);
5373           // (concepts themselves have no associated constraints to require)
5374         }
5375 
5376         ++Index;
5377       }
5378     } else if (auto *BO = dyn_cast<BinaryOperator>(E)) {
5379       // For A && B, we can infer members from both branches.
5380       // For A || B, the union is still more useful than the intersection.
5381       if (BO->getOpcode() == BO_LAnd || BO->getOpcode() == BO_LOr) {
5382         believe(BO->getLHS(), T);
5383         believe(BO->getRHS(), T);
5384       }
5385     } else if (auto *RE = dyn_cast<RequiresExpr>(E)) {
5386       // A requires(){...} lets us infer members from each requirement.
5387       for (const concepts::Requirement *Req : RE->getRequirements()) {
5388         if (!Req->isDependent())
5389           continue; // Can't tell us anything about T.
5390         // Now Req cannot a substitution-error: those aren't dependent.
5391 
5392         if (auto *TR = dyn_cast<concepts::TypeRequirement>(Req)) {
5393           // Do a full traversal so we get `foo` from `typename T::foo::bar`.
5394           QualType AssertedType = TR->getType()->getType();
5395           ValidVisitor(this, T).TraverseType(AssertedType);
5396         } else if (auto *ER = dyn_cast<concepts::ExprRequirement>(Req)) {
5397           ValidVisitor Visitor(this, T);
5398           // If we have a type constraint on the value of the expression,
5399           // AND the whole outer expression describes a member, then we'll
5400           // be able to use the constraint to provide the return type.
5401           if (ER->getReturnTypeRequirement().isTypeConstraint()) {
5402             Visitor.OuterType =
5403                 ER->getReturnTypeRequirement().getTypeConstraint();
5404             Visitor.OuterExpr = ER->getExpr();
5405           }
5406           Visitor.TraverseStmt(ER->getExpr());
5407         } else if (auto *NR = dyn_cast<concepts::NestedRequirement>(Req)) {
5408           believe(NR->getConstraintExpr(), T);
5409         }
5410       }
5411     }
5412   }
5413 
5414   // This visitor infers members of T based on traversing expressions/types
5415   // that involve T. It is invoked with code known to be valid for T.
5416   class ValidVisitor : public RecursiveASTVisitor<ValidVisitor> {
5417     ConceptInfo *Outer;
5418     const TemplateTypeParmType *T;
5419 
5420     CallExpr *Caller = nullptr;
5421     Expr *Callee = nullptr;
5422 
5423   public:
5424     // If set, OuterExpr is constrained by OuterType.
5425     Expr *OuterExpr = nullptr;
5426     const TypeConstraint *OuterType = nullptr;
5427 
5428     ValidVisitor(ConceptInfo *Outer, const TemplateTypeParmType *T)
5429         : Outer(Outer), T(T) {
5430       assert(T);
5431     }
5432 
5433     // In T.foo or T->foo, `foo` is a member function/variable.
5434     bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
5435       const Type *Base = E->getBaseType().getTypePtr();
5436       bool IsArrow = E->isArrow();
5437       if (Base->isPointerType() && IsArrow) {
5438         IsArrow = false;
5439         Base = Base->getPointeeType().getTypePtr();
5440       }
5441       if (isApprox(Base, T))
5442         addValue(E, E->getMember(), IsArrow ? Member::Arrow : Member::Dot);
5443       return true;
5444     }
5445 
5446     // In T::foo, `foo` is a static member function/variable.
5447     bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
5448       if (E->getQualifier() && isApprox(E->getQualifier()->getAsType(), T))
5449         addValue(E, E->getDeclName(), Member::Colons);
5450       return true;
5451     }
5452 
5453     // In T::typename foo, `foo` is a type.
5454     bool VisitDependentNameType(DependentNameType *DNT) {
5455       const auto *Q = DNT->getQualifier();
5456       if (Q && isApprox(Q->getAsType(), T))
5457         addType(DNT->getIdentifier());
5458       return true;
5459     }
5460 
5461     // In T::foo::bar, `foo` must be a type.
5462     // VisitNNS() doesn't exist, and TraverseNNS isn't always called :-(
5463     bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSL) {
5464       if (NNSL) {
5465         NestedNameSpecifier *NNS = NNSL.getNestedNameSpecifier();
5466         const auto *Q = NNS->getPrefix();
5467         if (Q && isApprox(Q->getAsType(), T))
5468           addType(NNS->getAsIdentifier());
5469       }
5470       // FIXME: also handle T::foo<X>::bar
5471       return RecursiveASTVisitor::TraverseNestedNameSpecifierLoc(NNSL);
5472     }
5473 
5474     // FIXME also handle T::foo<X>
5475 
5476     // Track the innermost caller/callee relationship so we can tell if a
5477     // nested expr is being called as a function.
5478     bool VisitCallExpr(CallExpr *CE) {
5479       Caller = CE;
5480       Callee = CE->getCallee();
5481       return true;
5482     }
5483 
5484   private:
5485     void addResult(Member &&M) {
5486       auto R = Outer->Results.try_emplace(M.Name);
5487       Member &O = R.first->second;
5488       // Overwrite existing if the new member has more info.
5489       // The preference of . vs :: vs -> is fairly arbitrary.
5490       if (/*Inserted*/ R.second ||
5491           std::make_tuple(M.ArgTypes.has_value(), M.ResultType != nullptr,
5492                           M.Operator) > std::make_tuple(O.ArgTypes.has_value(),
5493                                                         O.ResultType != nullptr,
5494                                                         O.Operator))
5495         O = std::move(M);
5496     }
5497 
5498     void addType(const IdentifierInfo *Name) {
5499       if (!Name)
5500         return;
5501       Member M;
5502       M.Name = Name;
5503       M.Operator = Member::Colons;
5504       addResult(std::move(M));
5505     }
5506 
5507     void addValue(Expr *E, DeclarationName Name,
5508                   Member::AccessOperator Operator) {
5509       if (!Name.isIdentifier())
5510         return;
5511       Member Result;
5512       Result.Name = Name.getAsIdentifierInfo();
5513       Result.Operator = Operator;
5514       // If this is the callee of an immediately-enclosing CallExpr, then
5515       // treat it as a method, otherwise it's a variable.
5516       if (Caller != nullptr && Callee == E) {
5517         Result.ArgTypes.emplace();
5518         for (const auto *Arg : Caller->arguments())
5519           Result.ArgTypes->push_back(Arg->getType());
5520         if (Caller == OuterExpr) {
5521           Result.ResultType = OuterType;
5522         }
5523       } else {
5524         if (E == OuterExpr)
5525           Result.ResultType = OuterType;
5526       }
5527       addResult(std::move(Result));
5528     }
5529   };
5530 
5531   static bool isApprox(const TemplateArgument &Arg, const Type *T) {
5532     return Arg.getKind() == TemplateArgument::Type &&
5533            isApprox(Arg.getAsType().getTypePtr(), T);
5534   }
5535 
5536   static bool isApprox(const Type *T1, const Type *T2) {
5537     return T1 && T2 &&
5538            T1->getCanonicalTypeUnqualified() ==
5539                T2->getCanonicalTypeUnqualified();
5540   }
5541 
5542   // Returns the DeclContext immediately enclosed by the template parameter
5543   // scope. For primary templates, this is the templated (e.g.) CXXRecordDecl.
5544   // For specializations, this is e.g. ClassTemplatePartialSpecializationDecl.
5545   static DeclContext *getTemplatedEntity(const TemplateTypeParmDecl *D,
5546                                          Scope *S) {
5547     if (D == nullptr)
5548       return nullptr;
5549     Scope *Inner = nullptr;
5550     while (S) {
5551       if (S->isTemplateParamScope() && S->isDeclScope(D))
5552         return Inner ? Inner->getEntity() : nullptr;
5553       Inner = S;
5554       S = S->getParent();
5555     }
5556     return nullptr;
5557   }
5558 
5559   // Gets all the type constraint expressions that might apply to the type
5560   // variables associated with DC (as returned by getTemplatedEntity()).
5561   static SmallVector<const Expr *, 1>
5562   constraintsForTemplatedEntity(DeclContext *DC) {
5563     SmallVector<const Expr *, 1> Result;
5564     if (DC == nullptr)
5565       return Result;
5566     // Primary templates can have constraints.
5567     if (const auto *TD = cast<Decl>(DC)->getDescribedTemplate())
5568       TD->getAssociatedConstraints(Result);
5569     // Partial specializations may have constraints.
5570     if (const auto *CTPSD =
5571             dyn_cast<ClassTemplatePartialSpecializationDecl>(DC))
5572       CTPSD->getAssociatedConstraints(Result);
5573     if (const auto *VTPSD = dyn_cast<VarTemplatePartialSpecializationDecl>(DC))
5574       VTPSD->getAssociatedConstraints(Result);
5575     return Result;
5576   }
5577 
5578   // Attempt to find the unique type satisfying a constraint.
5579   // This lets us show e.g. `int` instead of `std::same_as<int>`.
5580   static QualType deduceType(const TypeConstraint &T) {
5581     // Assume a same_as<T> return type constraint is std::same_as or equivalent.
5582     // In this case the return type is T.
5583     DeclarationName DN = T.getNamedConcept()->getDeclName();
5584     if (DN.isIdentifier() && DN.getAsIdentifierInfo()->isStr("same_as"))
5585       if (const auto *Args = T.getTemplateArgsAsWritten())
5586         if (Args->getNumTemplateArgs() == 1) {
5587           const auto &Arg = Args->arguments().front().getArgument();
5588           if (Arg.getKind() == TemplateArgument::Type)
5589             return Arg.getAsType();
5590         }
5591     return {};
5592   }
5593 
5594   llvm::DenseMap<const IdentifierInfo *, Member> Results;
5595 };
5596 
5597 // Returns a type for E that yields acceptable member completions.
5598 // In particular, when E->getType() is DependentTy, try to guess a likely type.
5599 // We accept some lossiness (like dropping parameters).
5600 // We only try to handle common expressions on the LHS of MemberExpr.
5601 QualType getApproximateType(const Expr *E) {
5602   if (E->getType().isNull())
5603     return QualType();
5604   E = E->IgnoreParenImpCasts();
5605   QualType Unresolved = E->getType();
5606   // We only resolve DependentTy, or undeduced autos (including auto* etc).
5607   if (!Unresolved->isSpecificBuiltinType(BuiltinType::Dependent)) {
5608     AutoType *Auto = Unresolved->getContainedAutoType();
5609     if (!Auto || !Auto->isUndeducedAutoType())
5610       return Unresolved;
5611   }
5612   // A call: approximate-resolve callee to a function type, get its return type
5613   if (const CallExpr *CE = llvm::dyn_cast<CallExpr>(E)) {
5614     QualType Callee = getApproximateType(CE->getCallee());
5615     if (Callee.isNull() ||
5616         Callee->isSpecificPlaceholderType(BuiltinType::BoundMember))
5617       Callee = Expr::findBoundMemberType(CE->getCallee());
5618     if (Callee.isNull())
5619       return Unresolved;
5620 
5621     if (const auto *FnTypePtr = Callee->getAs<PointerType>()) {
5622       Callee = FnTypePtr->getPointeeType();
5623     } else if (const auto *BPT = Callee->getAs<BlockPointerType>()) {
5624       Callee = BPT->getPointeeType();
5625     }
5626     if (const FunctionType *FnType = Callee->getAs<FunctionType>())
5627       return FnType->getReturnType().getNonReferenceType();
5628 
5629     // Unresolved call: try to guess the return type.
5630     if (const auto *OE = llvm::dyn_cast<OverloadExpr>(CE->getCallee())) {
5631       // If all candidates have the same approximate return type, use it.
5632       // Discard references and const to allow more to be "the same".
5633       // (In particular, if there's one candidate + ADL, resolve it).
5634       const Type *Common = nullptr;
5635       for (const auto *D : OE->decls()) {
5636         QualType ReturnType;
5637         if (const auto *FD = llvm::dyn_cast<FunctionDecl>(D))
5638           ReturnType = FD->getReturnType();
5639         else if (const auto *FTD = llvm::dyn_cast<FunctionTemplateDecl>(D))
5640           ReturnType = FTD->getTemplatedDecl()->getReturnType();
5641         if (ReturnType.isNull())
5642           continue;
5643         const Type *Candidate =
5644             ReturnType.getNonReferenceType().getCanonicalType().getTypePtr();
5645         if (Common && Common != Candidate)
5646           return Unresolved; // Multiple candidates.
5647         Common = Candidate;
5648       }
5649       if (Common != nullptr)
5650         return QualType(Common, 0);
5651     }
5652   }
5653   // A dependent member: approximate-resolve the base, then lookup.
5654   if (const auto *CDSME = llvm::dyn_cast<CXXDependentScopeMemberExpr>(E)) {
5655     QualType Base = CDSME->isImplicitAccess()
5656                         ? CDSME->getBaseType()
5657                         : getApproximateType(CDSME->getBase());
5658     if (CDSME->isArrow() && !Base.isNull())
5659       Base = Base->getPointeeType(); // could handle unique_ptr etc here?
5660     auto *RD =
5661         Base.isNull()
5662             ? nullptr
5663             : llvm::dyn_cast_or_null<CXXRecordDecl>(getAsRecordDecl(Base));
5664     if (RD && RD->isCompleteDefinition()) {
5665       // Look up member heuristically, including in bases.
5666       for (const auto *Member : RD->lookupDependentName(
5667                CDSME->getMember(), [](const NamedDecl *Member) {
5668                  return llvm::isa<ValueDecl>(Member);
5669                })) {
5670         return llvm::cast<ValueDecl>(Member)->getType().getNonReferenceType();
5671       }
5672     }
5673   }
5674   // A reference to an `auto` variable: approximate-resolve its initializer.
5675   if (const auto *DRE = llvm::dyn_cast<DeclRefExpr>(E)) {
5676     if (const auto *VD = llvm::dyn_cast<VarDecl>(DRE->getDecl())) {
5677       if (VD->hasInit())
5678         return getApproximateType(VD->getInit());
5679     }
5680   }
5681   if (const auto *UO = llvm::dyn_cast<UnaryOperator>(E)) {
5682     if (UO->getOpcode() == UnaryOperatorKind::UO_Deref)
5683       return UO->getSubExpr()->getType()->getPointeeType();
5684   }
5685   return Unresolved;
5686 }
5687 
5688 // If \p Base is ParenListExpr, assume a chain of comma operators and pick the
5689 // last expr. We expect other ParenListExprs to be resolved to e.g. constructor
5690 // calls before here. (So the ParenListExpr should be nonempty, but check just
5691 // in case)
5692 Expr *unwrapParenList(Expr *Base) {
5693   if (auto *PLE = llvm::dyn_cast_or_null<ParenListExpr>(Base)) {
5694     if (PLE->getNumExprs() == 0)
5695       return nullptr;
5696     Base = PLE->getExpr(PLE->getNumExprs() - 1);
5697   }
5698   return Base;
5699 }
5700 
5701 } // namespace
5702 
5703 void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
5704                                            Expr *OtherOpBase,
5705                                            SourceLocation OpLoc, bool IsArrow,
5706                                            bool IsBaseExprStatement,
5707                                            QualType PreferredType) {
5708   Base = unwrapParenList(Base);
5709   OtherOpBase = unwrapParenList(OtherOpBase);
5710   if (!Base || !CodeCompleter)
5711     return;
5712 
5713   ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
5714   if (ConvertedBase.isInvalid())
5715     return;
5716   QualType ConvertedBaseType = getApproximateType(ConvertedBase.get());
5717 
5718   enum CodeCompletionContext::Kind contextKind;
5719 
5720   if (IsArrow) {
5721     if (const auto *Ptr = ConvertedBaseType->getAs<PointerType>())
5722       ConvertedBaseType = Ptr->getPointeeType();
5723   }
5724 
5725   if (IsArrow) {
5726     contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
5727   } else {
5728     if (ConvertedBaseType->isObjCObjectPointerType() ||
5729         ConvertedBaseType->isObjCObjectOrInterfaceType()) {
5730       contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
5731     } else {
5732       contextKind = CodeCompletionContext::CCC_DotMemberAccess;
5733     }
5734   }
5735 
5736   CodeCompletionContext CCContext(contextKind, ConvertedBaseType);
5737   CCContext.setPreferredType(PreferredType);
5738   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5739                         CodeCompleter->getCodeCompletionTUInfo(), CCContext,
5740                         &ResultBuilder::IsMember);
5741 
5742   auto DoCompletion = [&](Expr *Base, bool IsArrow,
5743                           std::optional<FixItHint> AccessOpFixIt) -> bool {
5744     if (!Base)
5745       return false;
5746 
5747     ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
5748     if (ConvertedBase.isInvalid())
5749       return false;
5750     Base = ConvertedBase.get();
5751 
5752     QualType BaseType = getApproximateType(Base);
5753     if (BaseType.isNull())
5754       return false;
5755     ExprValueKind BaseKind = Base->getValueKind();
5756 
5757     if (IsArrow) {
5758       if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
5759         BaseType = Ptr->getPointeeType();
5760         BaseKind = VK_LValue;
5761       } else if (BaseType->isObjCObjectPointerType() ||
5762                  BaseType->isTemplateTypeParmType()) {
5763         // Both cases (dot/arrow) handled below.
5764       } else {
5765         return false;
5766       }
5767     }
5768 
5769     if (RecordDecl *RD = getAsRecordDecl(BaseType)) {
5770       AddRecordMembersCompletionResults(*this, Results, S, BaseType, BaseKind,
5771                                         RD, std::move(AccessOpFixIt));
5772     } else if (const auto *TTPT =
5773                    dyn_cast<TemplateTypeParmType>(BaseType.getTypePtr())) {
5774       auto Operator =
5775           IsArrow ? ConceptInfo::Member::Arrow : ConceptInfo::Member::Dot;
5776       for (const auto &R : ConceptInfo(*TTPT, S).members()) {
5777         if (R.Operator != Operator)
5778           continue;
5779         CodeCompletionResult Result(
5780             R.render(*this, CodeCompleter->getAllocator(),
5781                      CodeCompleter->getCodeCompletionTUInfo()));
5782         if (AccessOpFixIt)
5783           Result.FixIts.push_back(*AccessOpFixIt);
5784         Results.AddResult(std::move(Result));
5785       }
5786     } else if (!IsArrow && BaseType->isObjCObjectPointerType()) {
5787       // Objective-C property reference. Bail if we're performing fix-it code
5788       // completion since Objective-C properties are normally backed by ivars,
5789       // most Objective-C fix-its here would have little value.
5790       if (AccessOpFixIt) {
5791         return false;
5792       }
5793       AddedPropertiesSet AddedProperties;
5794 
5795       if (const ObjCObjectPointerType *ObjCPtr =
5796               BaseType->getAsObjCInterfacePointerType()) {
5797         // Add property results based on our interface.
5798         assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
5799         AddObjCProperties(CCContext, ObjCPtr->getInterfaceDecl(), true,
5800                           /*AllowNullaryMethods=*/true, CurContext,
5801                           AddedProperties, Results, IsBaseExprStatement);
5802       }
5803 
5804       // Add properties from the protocols in a qualified interface.
5805       for (auto *I : BaseType->castAs<ObjCObjectPointerType>()->quals())
5806         AddObjCProperties(CCContext, I, true, /*AllowNullaryMethods=*/true,
5807                           CurContext, AddedProperties, Results,
5808                           IsBaseExprStatement, /*IsClassProperty*/ false,
5809                           /*InOriginalClass*/ false);
5810     } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
5811                (!IsArrow && BaseType->isObjCObjectType())) {
5812       // Objective-C instance variable access. Bail if we're performing fix-it
5813       // code completion since Objective-C properties are normally backed by
5814       // ivars, most Objective-C fix-its here would have little value.
5815       if (AccessOpFixIt) {
5816         return false;
5817       }
5818       ObjCInterfaceDecl *Class = nullptr;
5819       if (const ObjCObjectPointerType *ObjCPtr =
5820               BaseType->getAs<ObjCObjectPointerType>())
5821         Class = ObjCPtr->getInterfaceDecl();
5822       else
5823         Class = BaseType->castAs<ObjCObjectType>()->getInterface();
5824 
5825       // Add all ivars from this class and its superclasses.
5826       if (Class) {
5827         CodeCompletionDeclConsumer Consumer(Results, Class, BaseType);
5828         Results.setFilter(&ResultBuilder::IsObjCIvar);
5829         LookupVisibleDecls(
5830             Class, LookupMemberName, Consumer, CodeCompleter->includeGlobals(),
5831             /*IncludeDependentBases=*/false, CodeCompleter->loadExternal());
5832       }
5833     }
5834 
5835     // FIXME: How do we cope with isa?
5836     return true;
5837   };
5838 
5839   Results.EnterNewScope();
5840 
5841   bool CompletionSucceded = DoCompletion(Base, IsArrow, std::nullopt);
5842   if (CodeCompleter->includeFixIts()) {
5843     const CharSourceRange OpRange =
5844         CharSourceRange::getTokenRange(OpLoc, OpLoc);
5845     CompletionSucceded |= DoCompletion(
5846         OtherOpBase, !IsArrow,
5847         FixItHint::CreateReplacement(OpRange, IsArrow ? "." : "->"));
5848   }
5849 
5850   Results.ExitScope();
5851 
5852   if (!CompletionSucceded)
5853     return;
5854 
5855   // Hand off the results found for code completion.
5856   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5857                             Results.data(), Results.size());
5858 }
5859 
5860 void Sema::CodeCompleteObjCClassPropertyRefExpr(Scope *S,
5861                                                 const IdentifierInfo &ClassName,
5862                                                 SourceLocation ClassNameLoc,
5863                                                 bool IsBaseExprStatement) {
5864   const IdentifierInfo *ClassNamePtr = &ClassName;
5865   ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(ClassNamePtr, ClassNameLoc);
5866   if (!IFace)
5867     return;
5868   CodeCompletionContext CCContext(
5869       CodeCompletionContext::CCC_ObjCPropertyAccess);
5870   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5871                         CodeCompleter->getCodeCompletionTUInfo(), CCContext,
5872                         &ResultBuilder::IsMember);
5873   Results.EnterNewScope();
5874   AddedPropertiesSet AddedProperties;
5875   AddObjCProperties(CCContext, IFace, true,
5876                     /*AllowNullaryMethods=*/true, CurContext, AddedProperties,
5877                     Results, IsBaseExprStatement,
5878                     /*IsClassProperty=*/true);
5879   Results.ExitScope();
5880   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5881                             Results.data(), Results.size());
5882 }
5883 
5884 void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
5885   if (!CodeCompleter)
5886     return;
5887 
5888   ResultBuilder::LookupFilter Filter = nullptr;
5889   enum CodeCompletionContext::Kind ContextKind =
5890       CodeCompletionContext::CCC_Other;
5891   switch ((DeclSpec::TST)TagSpec) {
5892   case DeclSpec::TST_enum:
5893     Filter = &ResultBuilder::IsEnum;
5894     ContextKind = CodeCompletionContext::CCC_EnumTag;
5895     break;
5896 
5897   case DeclSpec::TST_union:
5898     Filter = &ResultBuilder::IsUnion;
5899     ContextKind = CodeCompletionContext::CCC_UnionTag;
5900     break;
5901 
5902   case DeclSpec::TST_struct:
5903   case DeclSpec::TST_class:
5904   case DeclSpec::TST_interface:
5905     Filter = &ResultBuilder::IsClassOrStruct;
5906     ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
5907     break;
5908 
5909   default:
5910     llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
5911   }
5912 
5913   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5914                         CodeCompleter->getCodeCompletionTUInfo(), ContextKind);
5915   CodeCompletionDeclConsumer Consumer(Results, CurContext);
5916 
5917   // First pass: look for tags.
5918   Results.setFilter(Filter);
5919   LookupVisibleDecls(S, LookupTagName, Consumer,
5920                      CodeCompleter->includeGlobals(),
5921                      CodeCompleter->loadExternal());
5922 
5923   if (CodeCompleter->includeGlobals()) {
5924     // Second pass: look for nested name specifiers.
5925     Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
5926     LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
5927                        CodeCompleter->includeGlobals(),
5928                        CodeCompleter->loadExternal());
5929   }
5930 
5931   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5932                             Results.data(), Results.size());
5933 }
5934 
5935 static void AddTypeQualifierResults(DeclSpec &DS, ResultBuilder &Results,
5936                                     const LangOptions &LangOpts) {
5937   if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
5938     Results.AddResult("const");
5939   if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
5940     Results.AddResult("volatile");
5941   if (LangOpts.C99 && !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
5942     Results.AddResult("restrict");
5943   if (LangOpts.C11 && !(DS.getTypeQualifiers() & DeclSpec::TQ_atomic))
5944     Results.AddResult("_Atomic");
5945   if (LangOpts.MSVCCompat && !(DS.getTypeQualifiers() & DeclSpec::TQ_unaligned))
5946     Results.AddResult("__unaligned");
5947 }
5948 
5949 void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
5950   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5951                         CodeCompleter->getCodeCompletionTUInfo(),
5952                         CodeCompletionContext::CCC_TypeQualifiers);
5953   Results.EnterNewScope();
5954   AddTypeQualifierResults(DS, Results, LangOpts);
5955   Results.ExitScope();
5956   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5957                             Results.data(), Results.size());
5958 }
5959 
5960 void Sema::CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
5961                                           const VirtSpecifiers *VS) {
5962   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5963                         CodeCompleter->getCodeCompletionTUInfo(),
5964                         CodeCompletionContext::CCC_TypeQualifiers);
5965   Results.EnterNewScope();
5966   AddTypeQualifierResults(DS, Results, LangOpts);
5967   if (LangOpts.CPlusPlus11) {
5968     Results.AddResult("noexcept");
5969     if (D.getContext() == DeclaratorContext::Member && !D.isCtorOrDtor() &&
5970         !D.isStaticMember()) {
5971       if (!VS || !VS->isFinalSpecified())
5972         Results.AddResult("final");
5973       if (!VS || !VS->isOverrideSpecified())
5974         Results.AddResult("override");
5975     }
5976   }
5977   Results.ExitScope();
5978   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5979                             Results.data(), Results.size());
5980 }
5981 
5982 void Sema::CodeCompleteBracketDeclarator(Scope *S) {
5983   CodeCompleteExpression(S, QualType(getASTContext().getSizeType()));
5984 }
5985 
5986 void Sema::CodeCompleteCase(Scope *S) {
5987   if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
5988     return;
5989 
5990   SwitchStmt *Switch = getCurFunction()->SwitchStack.back().getPointer();
5991   // Condition expression might be invalid, do not continue in this case.
5992   if (!Switch->getCond())
5993     return;
5994   QualType type = Switch->getCond()->IgnoreImplicit()->getType();
5995   if (!type->isEnumeralType()) {
5996     CodeCompleteExpressionData Data(type);
5997     Data.IntegralConstantExpression = true;
5998     CodeCompleteExpression(S, Data);
5999     return;
6000   }
6001 
6002   // Code-complete the cases of a switch statement over an enumeration type
6003   // by providing the list of
6004   EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
6005   if (EnumDecl *Def = Enum->getDefinition())
6006     Enum = Def;
6007 
6008   // Determine which enumerators we have already seen in the switch statement.
6009   // FIXME: Ideally, we would also be able to look *past* the code-completion
6010   // token, in case we are code-completing in the middle of the switch and not
6011   // at the end. However, we aren't able to do so at the moment.
6012   CoveredEnumerators Enumerators;
6013   for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
6014        SC = SC->getNextSwitchCase()) {
6015     CaseStmt *Case = dyn_cast<CaseStmt>(SC);
6016     if (!Case)
6017       continue;
6018 
6019     Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
6020     if (auto *DRE = dyn_cast<DeclRefExpr>(CaseVal))
6021       if (auto *Enumerator =
6022               dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6023         // We look into the AST of the case statement to determine which
6024         // enumerator was named. Alternatively, we could compute the value of
6025         // the integral constant expression, then compare it against the
6026         // values of each enumerator. However, value-based approach would not
6027         // work as well with C++ templates where enumerators declared within a
6028         // template are type- and value-dependent.
6029         Enumerators.Seen.insert(Enumerator);
6030 
6031         // If this is a qualified-id, keep track of the nested-name-specifier
6032         // so that we can reproduce it as part of code completion, e.g.,
6033         //
6034         //   switch (TagD.getKind()) {
6035         //     case TagDecl::TK_enum:
6036         //       break;
6037         //     case XXX
6038         //
6039         // At the XXX, our completions are TagDecl::TK_union,
6040         // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
6041         // TK_struct, and TK_class.
6042         Enumerators.SuggestedQualifier = DRE->getQualifier();
6043       }
6044   }
6045 
6046   // Add any enumerators that have not yet been mentioned.
6047   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6048                         CodeCompleter->getCodeCompletionTUInfo(),
6049                         CodeCompletionContext::CCC_Expression);
6050   AddEnumerators(Results, Context, Enum, CurContext, Enumerators);
6051 
6052   if (CodeCompleter->includeMacros()) {
6053     AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
6054   }
6055   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6056                             Results.data(), Results.size());
6057 }
6058 
6059 static bool anyNullArguments(ArrayRef<Expr *> Args) {
6060   if (Args.size() && !Args.data())
6061     return true;
6062 
6063   for (unsigned I = 0; I != Args.size(); ++I)
6064     if (!Args[I])
6065       return true;
6066 
6067   return false;
6068 }
6069 
6070 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
6071 
6072 static void mergeCandidatesWithResults(
6073     Sema &SemaRef, SmallVectorImpl<ResultCandidate> &Results,
6074     OverloadCandidateSet &CandidateSet, SourceLocation Loc, size_t ArgSize) {
6075   // Sort the overload candidate set by placing the best overloads first.
6076   llvm::stable_sort(CandidateSet, [&](const OverloadCandidate &X,
6077                                       const OverloadCandidate &Y) {
6078     return isBetterOverloadCandidate(SemaRef, X, Y, Loc,
6079                                      CandidateSet.getKind());
6080   });
6081 
6082   // Add the remaining viable overload candidates as code-completion results.
6083   for (OverloadCandidate &Candidate : CandidateSet) {
6084     if (Candidate.Function) {
6085       if (Candidate.Function->isDeleted())
6086         continue;
6087       if (shouldEnforceArgLimit(/*PartialOverloading=*/true,
6088                                 Candidate.Function) &&
6089           Candidate.Function->getNumParams() <= ArgSize &&
6090           // Having zero args is annoying, normally we don't surface a function
6091           // with 2 params, if you already have 2 params, because you are
6092           // inserting the 3rd now. But with zero, it helps the user to figure
6093           // out there are no overloads that take any arguments. Hence we are
6094           // keeping the overload.
6095           ArgSize > 0)
6096         continue;
6097     }
6098     if (Candidate.Viable)
6099       Results.push_back(ResultCandidate(Candidate.Function));
6100   }
6101 }
6102 
6103 /// Get the type of the Nth parameter from a given set of overload
6104 /// candidates.
6105 static QualType getParamType(Sema &SemaRef,
6106                              ArrayRef<ResultCandidate> Candidates, unsigned N) {
6107 
6108   // Given the overloads 'Candidates' for a function call matching all arguments
6109   // up to N, return the type of the Nth parameter if it is the same for all
6110   // overload candidates.
6111   QualType ParamType;
6112   for (auto &Candidate : Candidates) {
6113     QualType CandidateParamType = Candidate.getParamType(N);
6114     if (CandidateParamType.isNull())
6115       continue;
6116     if (ParamType.isNull()) {
6117       ParamType = CandidateParamType;
6118       continue;
6119     }
6120     if (!SemaRef.Context.hasSameUnqualifiedType(
6121             ParamType.getNonReferenceType(),
6122             CandidateParamType.getNonReferenceType()))
6123       // Two conflicting types, give up.
6124       return QualType();
6125   }
6126 
6127   return ParamType;
6128 }
6129 
6130 static QualType
6131 ProduceSignatureHelp(Sema &SemaRef, MutableArrayRef<ResultCandidate> Candidates,
6132                      unsigned CurrentArg, SourceLocation OpenParLoc,
6133                      bool Braced) {
6134   if (Candidates.empty())
6135     return QualType();
6136   if (SemaRef.getPreprocessor().isCodeCompletionReached())
6137     SemaRef.CodeCompleter->ProcessOverloadCandidates(
6138         SemaRef, CurrentArg, Candidates.data(), Candidates.size(), OpenParLoc,
6139         Braced);
6140   return getParamType(SemaRef, Candidates, CurrentArg);
6141 }
6142 
6143 // Given a callee expression `Fn`, if the call is through a function pointer,
6144 // try to find the declaration of the corresponding function pointer type,
6145 // so that we can recover argument names from it.
6146 static FunctionProtoTypeLoc GetPrototypeLoc(Expr *Fn) {
6147   TypeLoc Target;
6148 
6149   if (const auto *T = Fn->getType().getTypePtr()->getAs<TypedefType>()) {
6150     Target = T->getDecl()->getTypeSourceInfo()->getTypeLoc();
6151 
6152   } else if (const auto *DR = dyn_cast<DeclRefExpr>(Fn)) {
6153     const auto *D = DR->getDecl();
6154     if (const auto *const VD = dyn_cast<VarDecl>(D)) {
6155       Target = VD->getTypeSourceInfo()->getTypeLoc();
6156     }
6157   } else if (const auto *ME = dyn_cast<MemberExpr>(Fn)) {
6158     const auto *MD = ME->getMemberDecl();
6159     if (const auto *FD = dyn_cast<FieldDecl>(MD)) {
6160       Target = FD->getTypeSourceInfo()->getTypeLoc();
6161     }
6162   }
6163 
6164   if (!Target)
6165     return {};
6166 
6167   // Unwrap types that may be wrapping the function type
6168   while (true) {
6169     if (auto P = Target.getAs<PointerTypeLoc>()) {
6170       Target = P.getPointeeLoc();
6171       continue;
6172     }
6173     if (auto A = Target.getAs<AttributedTypeLoc>()) {
6174       Target = A.getModifiedLoc();
6175       continue;
6176     }
6177     if (auto P = Target.getAs<ParenTypeLoc>()) {
6178       Target = P.getInnerLoc();
6179       continue;
6180     }
6181     break;
6182   }
6183 
6184   if (auto F = Target.getAs<FunctionProtoTypeLoc>()) {
6185     return F;
6186   }
6187 
6188   return {};
6189 }
6190 
6191 QualType Sema::ProduceCallSignatureHelp(Expr *Fn, ArrayRef<Expr *> Args,
6192                                         SourceLocation OpenParLoc) {
6193   Fn = unwrapParenList(Fn);
6194   if (!CodeCompleter || !Fn)
6195     return QualType();
6196 
6197   // FIXME: Provide support for variadic template functions.
6198   // Ignore type-dependent call expressions entirely.
6199   if (Fn->isTypeDependent() || anyNullArguments(Args))
6200     return QualType();
6201   // In presence of dependent args we surface all possible signatures using the
6202   // non-dependent args in the prefix. Afterwards we do a post filtering to make
6203   // sure provided candidates satisfy parameter count restrictions.
6204   auto ArgsWithoutDependentTypes =
6205       Args.take_while([](Expr *Arg) { return !Arg->isTypeDependent(); });
6206 
6207   SmallVector<ResultCandidate, 8> Results;
6208 
6209   Expr *NakedFn = Fn->IgnoreParenCasts();
6210   // Build an overload candidate set based on the functions we find.
6211   SourceLocation Loc = Fn->getExprLoc();
6212   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6213 
6214   if (auto ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn)) {
6215     AddOverloadedCallCandidates(ULE, ArgsWithoutDependentTypes, CandidateSet,
6216                                 /*PartialOverloading=*/true);
6217   } else if (auto UME = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
6218     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
6219     if (UME->hasExplicitTemplateArgs()) {
6220       UME->copyTemplateArgumentsInto(TemplateArgsBuffer);
6221       TemplateArgs = &TemplateArgsBuffer;
6222     }
6223 
6224     // Add the base as first argument (use a nullptr if the base is implicit).
6225     SmallVector<Expr *, 12> ArgExprs(
6226         1, UME->isImplicitAccess() ? nullptr : UME->getBase());
6227     ArgExprs.append(ArgsWithoutDependentTypes.begin(),
6228                     ArgsWithoutDependentTypes.end());
6229     UnresolvedSet<8> Decls;
6230     Decls.append(UME->decls_begin(), UME->decls_end());
6231     const bool FirstArgumentIsBase = !UME->isImplicitAccess() && UME->getBase();
6232     AddFunctionCandidates(Decls, ArgExprs, CandidateSet, TemplateArgs,
6233                           /*SuppressUserConversions=*/false,
6234                           /*PartialOverloading=*/true, FirstArgumentIsBase);
6235   } else {
6236     FunctionDecl *FD = nullptr;
6237     if (auto *MCE = dyn_cast<MemberExpr>(NakedFn))
6238       FD = dyn_cast<FunctionDecl>(MCE->getMemberDecl());
6239     else if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn))
6240       FD = dyn_cast<FunctionDecl>(DRE->getDecl());
6241     if (FD) { // We check whether it's a resolved function declaration.
6242       if (!getLangOpts().CPlusPlus ||
6243           !FD->getType()->getAs<FunctionProtoType>())
6244         Results.push_back(ResultCandidate(FD));
6245       else
6246         AddOverloadCandidate(FD, DeclAccessPair::make(FD, FD->getAccess()),
6247                              ArgsWithoutDependentTypes, CandidateSet,
6248                              /*SuppressUserConversions=*/false,
6249                              /*PartialOverloading=*/true);
6250 
6251     } else if (auto DC = NakedFn->getType()->getAsCXXRecordDecl()) {
6252       // If expression's type is CXXRecordDecl, it may overload the function
6253       // call operator, so we check if it does and add them as candidates.
6254       // A complete type is needed to lookup for member function call operators.
6255       if (isCompleteType(Loc, NakedFn->getType())) {
6256         DeclarationName OpName =
6257             Context.DeclarationNames.getCXXOperatorName(OO_Call);
6258         LookupResult R(*this, OpName, Loc, LookupOrdinaryName);
6259         LookupQualifiedName(R, DC);
6260         R.suppressDiagnostics();
6261         SmallVector<Expr *, 12> ArgExprs(1, NakedFn);
6262         ArgExprs.append(ArgsWithoutDependentTypes.begin(),
6263                         ArgsWithoutDependentTypes.end());
6264         AddFunctionCandidates(R.asUnresolvedSet(), ArgExprs, CandidateSet,
6265                               /*ExplicitArgs=*/nullptr,
6266                               /*SuppressUserConversions=*/false,
6267                               /*PartialOverloading=*/true);
6268       }
6269     } else {
6270       // Lastly we check whether expression's type is function pointer or
6271       // function.
6272 
6273       FunctionProtoTypeLoc P = GetPrototypeLoc(NakedFn);
6274       QualType T = NakedFn->getType();
6275       if (!T->getPointeeType().isNull())
6276         T = T->getPointeeType();
6277 
6278       if (auto FP = T->getAs<FunctionProtoType>()) {
6279         if (!TooManyArguments(FP->getNumParams(),
6280                               ArgsWithoutDependentTypes.size(),
6281                               /*PartialOverloading=*/true) ||
6282             FP->isVariadic()) {
6283           if (P) {
6284             Results.push_back(ResultCandidate(P));
6285           } else {
6286             Results.push_back(ResultCandidate(FP));
6287           }
6288         }
6289       } else if (auto FT = T->getAs<FunctionType>())
6290         // No prototype and declaration, it may be a K & R style function.
6291         Results.push_back(ResultCandidate(FT));
6292     }
6293   }
6294   mergeCandidatesWithResults(*this, Results, CandidateSet, Loc, Args.size());
6295   QualType ParamType = ProduceSignatureHelp(*this, Results, Args.size(),
6296                                             OpenParLoc, /*Braced=*/false);
6297   return !CandidateSet.empty() ? ParamType : QualType();
6298 }
6299 
6300 // Determine which param to continue aggregate initialization from after
6301 // a designated initializer.
6302 //
6303 // Given struct S { int a,b,c,d,e; }:
6304 //   after `S{.b=1,`       we want to suggest c to continue
6305 //   after `S{.b=1, 2,`    we continue with d (this is legal C and ext in C++)
6306 //   after `S{.b=1, .a=2,` we continue with b (this is legal C and ext in C++)
6307 //
6308 // Possible outcomes:
6309 //   - we saw a designator for a field, and continue from the returned index.
6310 //     Only aggregate initialization is allowed.
6311 //   - we saw a designator, but it was complex or we couldn't find the field.
6312 //     Only aggregate initialization is possible, but we can't assist with it.
6313 //     Returns an out-of-range index.
6314 //   - we saw no designators, just positional arguments.
6315 //     Returns std::nullopt.
6316 static std::optional<unsigned>
6317 getNextAggregateIndexAfterDesignatedInit(const ResultCandidate &Aggregate,
6318                                          ArrayRef<Expr *> Args) {
6319   static constexpr unsigned Invalid = std::numeric_limits<unsigned>::max();
6320   assert(Aggregate.getKind() == ResultCandidate::CK_Aggregate);
6321 
6322   // Look for designated initializers.
6323   // They're in their syntactic form, not yet resolved to fields.
6324   const IdentifierInfo *DesignatedFieldName = nullptr;
6325   unsigned ArgsAfterDesignator = 0;
6326   for (const Expr *Arg : Args) {
6327     if (const auto *DIE = dyn_cast<DesignatedInitExpr>(Arg)) {
6328       if (DIE->size() == 1 && DIE->getDesignator(0)->isFieldDesignator()) {
6329         DesignatedFieldName = DIE->getDesignator(0)->getFieldName();
6330         ArgsAfterDesignator = 0;
6331       } else {
6332         return Invalid; // Complicated designator.
6333       }
6334     } else if (isa<DesignatedInitUpdateExpr>(Arg)) {
6335       return Invalid; // Unsupported.
6336     } else {
6337       ++ArgsAfterDesignator;
6338     }
6339   }
6340   if (!DesignatedFieldName)
6341     return std::nullopt;
6342 
6343   // Find the index within the class's fields.
6344   // (Probing getParamDecl() directly would be quadratic in number of fields).
6345   unsigned DesignatedIndex = 0;
6346   const FieldDecl *DesignatedField = nullptr;
6347   for (const auto *Field : Aggregate.getAggregate()->fields()) {
6348     if (Field->getIdentifier() == DesignatedFieldName) {
6349       DesignatedField = Field;
6350       break;
6351     }
6352     ++DesignatedIndex;
6353   }
6354   if (!DesignatedField)
6355     return Invalid; // Designator referred to a missing field, give up.
6356 
6357   // Find the index within the aggregate (which may have leading bases).
6358   unsigned AggregateSize = Aggregate.getNumParams();
6359   while (DesignatedIndex < AggregateSize &&
6360          Aggregate.getParamDecl(DesignatedIndex) != DesignatedField)
6361     ++DesignatedIndex;
6362 
6363   // Continue from the index after the last named field.
6364   return DesignatedIndex + ArgsAfterDesignator + 1;
6365 }
6366 
6367 QualType Sema::ProduceConstructorSignatureHelp(QualType Type,
6368                                                SourceLocation Loc,
6369                                                ArrayRef<Expr *> Args,
6370                                                SourceLocation OpenParLoc,
6371                                                bool Braced) {
6372   if (!CodeCompleter)
6373     return QualType();
6374   SmallVector<ResultCandidate, 8> Results;
6375 
6376   // A complete type is needed to lookup for constructors.
6377   RecordDecl *RD =
6378       isCompleteType(Loc, Type) ? Type->getAsRecordDecl() : nullptr;
6379   if (!RD)
6380     return Type;
6381   CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD);
6382 
6383   // Consider aggregate initialization.
6384   // We don't check that types so far are correct.
6385   // We also don't handle C99/C++17 brace-elision, we assume init-list elements
6386   // are 1:1 with fields.
6387   // FIXME: it would be nice to support "unwrapping" aggregates that contain
6388   // a single subaggregate, like std::array<T, N> -> T __elements[N].
6389   if (Braced && !RD->isUnion() &&
6390       (!LangOpts.CPlusPlus || (CRD && CRD->isAggregate()))) {
6391     ResultCandidate AggregateSig(RD);
6392     unsigned AggregateSize = AggregateSig.getNumParams();
6393 
6394     if (auto NextIndex =
6395             getNextAggregateIndexAfterDesignatedInit(AggregateSig, Args)) {
6396       // A designator was used, only aggregate init is possible.
6397       if (*NextIndex >= AggregateSize)
6398         return Type;
6399       Results.push_back(AggregateSig);
6400       return ProduceSignatureHelp(*this, Results, *NextIndex, OpenParLoc,
6401                                   Braced);
6402     }
6403 
6404     // Describe aggregate initialization, but also constructors below.
6405     if (Args.size() < AggregateSize)
6406       Results.push_back(AggregateSig);
6407   }
6408 
6409   // FIXME: Provide support for member initializers.
6410   // FIXME: Provide support for variadic template constructors.
6411 
6412   if (CRD) {
6413     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6414     for (NamedDecl *C : LookupConstructors(CRD)) {
6415       if (auto *FD = dyn_cast<FunctionDecl>(C)) {
6416         // FIXME: we can't yet provide correct signature help for initializer
6417         //        list constructors, so skip them entirely.
6418         if (Braced && LangOpts.CPlusPlus && isInitListConstructor(FD))
6419           continue;
6420         AddOverloadCandidate(FD, DeclAccessPair::make(FD, C->getAccess()), Args,
6421                              CandidateSet,
6422                              /*SuppressUserConversions=*/false,
6423                              /*PartialOverloading=*/true,
6424                              /*AllowExplicit*/ true);
6425       } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(C)) {
6426         if (Braced && LangOpts.CPlusPlus &&
6427             isInitListConstructor(FTD->getTemplatedDecl()))
6428           continue;
6429 
6430         AddTemplateOverloadCandidate(
6431             FTD, DeclAccessPair::make(FTD, C->getAccess()),
6432             /*ExplicitTemplateArgs=*/nullptr, Args, CandidateSet,
6433             /*SuppressUserConversions=*/false,
6434             /*PartialOverloading=*/true);
6435       }
6436     }
6437     mergeCandidatesWithResults(*this, Results, CandidateSet, Loc, Args.size());
6438   }
6439 
6440   return ProduceSignatureHelp(*this, Results, Args.size(), OpenParLoc, Braced);
6441 }
6442 
6443 QualType Sema::ProduceCtorInitMemberSignatureHelp(
6444     Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy,
6445     ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc,
6446     bool Braced) {
6447   if (!CodeCompleter)
6448     return QualType();
6449 
6450   CXXConstructorDecl *Constructor =
6451       dyn_cast<CXXConstructorDecl>(ConstructorDecl);
6452   if (!Constructor)
6453     return QualType();
6454   // FIXME: Add support for Base class constructors as well.
6455   if (ValueDecl *MemberDecl = tryLookupCtorInitMemberDecl(
6456           Constructor->getParent(), SS, TemplateTypeTy, II))
6457     return ProduceConstructorSignatureHelp(MemberDecl->getType(),
6458                                            MemberDecl->getLocation(), ArgExprs,
6459                                            OpenParLoc, Braced);
6460   return QualType();
6461 }
6462 
6463 static bool argMatchesTemplateParams(const ParsedTemplateArgument &Arg,
6464                                      unsigned Index,
6465                                      const TemplateParameterList &Params) {
6466   const NamedDecl *Param;
6467   if (Index < Params.size())
6468     Param = Params.getParam(Index);
6469   else if (Params.hasParameterPack())
6470     Param = Params.asArray().back();
6471   else
6472     return false; // too many args
6473 
6474   switch (Arg.getKind()) {
6475   case ParsedTemplateArgument::Type:
6476     return llvm::isa<TemplateTypeParmDecl>(Param); // constraints not checked
6477   case ParsedTemplateArgument::NonType:
6478     return llvm::isa<NonTypeTemplateParmDecl>(Param); // type not checked
6479   case ParsedTemplateArgument::Template:
6480     return llvm::isa<TemplateTemplateParmDecl>(Param); // signature not checked
6481   }
6482   llvm_unreachable("Unhandled switch case");
6483 }
6484 
6485 QualType Sema::ProduceTemplateArgumentSignatureHelp(
6486     TemplateTy ParsedTemplate, ArrayRef<ParsedTemplateArgument> Args,
6487     SourceLocation LAngleLoc) {
6488   if (!CodeCompleter || !ParsedTemplate)
6489     return QualType();
6490 
6491   SmallVector<ResultCandidate, 8> Results;
6492   auto Consider = [&](const TemplateDecl *TD) {
6493     // Only add if the existing args are compatible with the template.
6494     bool Matches = true;
6495     for (unsigned I = 0; I < Args.size(); ++I) {
6496       if (!argMatchesTemplateParams(Args[I], I, *TD->getTemplateParameters())) {
6497         Matches = false;
6498         break;
6499       }
6500     }
6501     if (Matches)
6502       Results.emplace_back(TD);
6503   };
6504 
6505   TemplateName Template = ParsedTemplate.get();
6506   if (const auto *TD = Template.getAsTemplateDecl()) {
6507     Consider(TD);
6508   } else if (const auto *OTS = Template.getAsOverloadedTemplate()) {
6509     for (const NamedDecl *ND : *OTS)
6510       if (const auto *TD = llvm::dyn_cast<TemplateDecl>(ND))
6511         Consider(TD);
6512   }
6513   return ProduceSignatureHelp(*this, Results, Args.size(), LAngleLoc,
6514                               /*Braced=*/false);
6515 }
6516 
6517 static QualType getDesignatedType(QualType BaseType, const Designation &Desig) {
6518   for (unsigned I = 0; I < Desig.getNumDesignators(); ++I) {
6519     if (BaseType.isNull())
6520       break;
6521     QualType NextType;
6522     const auto &D = Desig.getDesignator(I);
6523     if (D.isArrayDesignator() || D.isArrayRangeDesignator()) {
6524       if (BaseType->isArrayType())
6525         NextType = BaseType->getAsArrayTypeUnsafe()->getElementType();
6526     } else {
6527       assert(D.isFieldDesignator());
6528       auto *RD = getAsRecordDecl(BaseType);
6529       if (RD && RD->isCompleteDefinition()) {
6530         for (const auto *Member : RD->lookup(D.getFieldDecl()))
6531           if (const FieldDecl *FD = llvm::dyn_cast<FieldDecl>(Member)) {
6532             NextType = FD->getType();
6533             break;
6534           }
6535       }
6536     }
6537     BaseType = NextType;
6538   }
6539   return BaseType;
6540 }
6541 
6542 void Sema::CodeCompleteDesignator(QualType BaseType,
6543                                   llvm::ArrayRef<Expr *> InitExprs,
6544                                   const Designation &D) {
6545   BaseType = getDesignatedType(BaseType, D);
6546   if (BaseType.isNull())
6547     return;
6548   const auto *RD = getAsRecordDecl(BaseType);
6549   if (!RD || RD->fields().empty())
6550     return;
6551 
6552   CodeCompletionContext CCC(CodeCompletionContext::CCC_DotMemberAccess,
6553                             BaseType);
6554   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6555                         CodeCompleter->getCodeCompletionTUInfo(), CCC);
6556 
6557   Results.EnterNewScope();
6558   for (const Decl *D : RD->decls()) {
6559     const FieldDecl *FD;
6560     if (auto *IFD = dyn_cast<IndirectFieldDecl>(D))
6561       FD = IFD->getAnonField();
6562     else if (auto *DFD = dyn_cast<FieldDecl>(D))
6563       FD = DFD;
6564     else
6565       continue;
6566 
6567     // FIXME: Make use of previous designators to mark any fields before those
6568     // inaccessible, and also compute the next initializer priority.
6569     ResultBuilder::Result Result(FD, Results.getBasePriority(FD));
6570     Results.AddResult(Result, CurContext, /*Hiding=*/nullptr);
6571   }
6572   Results.ExitScope();
6573   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6574                             Results.data(), Results.size());
6575 }
6576 
6577 void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
6578   ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
6579   if (!VD) {
6580     CodeCompleteOrdinaryName(S, PCC_Expression);
6581     return;
6582   }
6583 
6584   CodeCompleteExpressionData Data;
6585   Data.PreferredType = VD->getType();
6586   // Ignore VD to avoid completing the variable itself, e.g. in 'int foo = ^'.
6587   Data.IgnoreDecls.push_back(VD);
6588 
6589   CodeCompleteExpression(S, Data);
6590 }
6591 
6592 void Sema::CodeCompleteAfterIf(Scope *S, bool IsBracedThen) {
6593   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6594                         CodeCompleter->getCodeCompletionTUInfo(),
6595                         mapCodeCompletionContext(*this, PCC_Statement));
6596   Results.setFilter(&ResultBuilder::IsOrdinaryName);
6597   Results.EnterNewScope();
6598 
6599   CodeCompletionDeclConsumer Consumer(Results, CurContext);
6600   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
6601                      CodeCompleter->includeGlobals(),
6602                      CodeCompleter->loadExternal());
6603 
6604   AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
6605 
6606   // "else" block
6607   CodeCompletionBuilder Builder(Results.getAllocator(),
6608                                 Results.getCodeCompletionTUInfo());
6609 
6610   auto AddElseBodyPattern = [&] {
6611     if (IsBracedThen) {
6612       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6613       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
6614       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6615       Builder.AddPlaceholderChunk("statements");
6616       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6617       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
6618     } else {
6619       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6620       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6621       Builder.AddPlaceholderChunk("statement");
6622       Builder.AddChunk(CodeCompletionString::CK_SemiColon);
6623     }
6624   };
6625   Builder.AddTypedTextChunk("else");
6626   if (Results.includeCodePatterns())
6627     AddElseBodyPattern();
6628   Results.AddResult(Builder.TakeString());
6629 
6630   // "else if" block
6631   Builder.AddTypedTextChunk("else if");
6632   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6633   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6634   if (getLangOpts().CPlusPlus)
6635     Builder.AddPlaceholderChunk("condition");
6636   else
6637     Builder.AddPlaceholderChunk("expression");
6638   Builder.AddChunk(CodeCompletionString::CK_RightParen);
6639   if (Results.includeCodePatterns()) {
6640     AddElseBodyPattern();
6641   }
6642   Results.AddResult(Builder.TakeString());
6643 
6644   Results.ExitScope();
6645 
6646   if (S->getFnParent())
6647     AddPrettyFunctionResults(getLangOpts(), Results);
6648 
6649   if (CodeCompleter->includeMacros())
6650     AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
6651 
6652   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6653                             Results.data(), Results.size());
6654 }
6655 
6656 void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
6657                                    bool EnteringContext,
6658                                    bool IsUsingDeclaration, QualType BaseType,
6659                                    QualType PreferredType) {
6660   if (SS.isEmpty() || !CodeCompleter)
6661     return;
6662 
6663   CodeCompletionContext CC(CodeCompletionContext::CCC_Symbol, PreferredType);
6664   CC.setIsUsingDeclaration(IsUsingDeclaration);
6665   CC.setCXXScopeSpecifier(SS);
6666 
6667   // We want to keep the scope specifier even if it's invalid (e.g. the scope
6668   // "a::b::" is not corresponding to any context/namespace in the AST), since
6669   // it can be useful for global code completion which have information about
6670   // contexts/symbols that are not in the AST.
6671   if (SS.isInvalid()) {
6672     // As SS is invalid, we try to collect accessible contexts from the current
6673     // scope with a dummy lookup so that the completion consumer can try to
6674     // guess what the specified scope is.
6675     ResultBuilder DummyResults(*this, CodeCompleter->getAllocator(),
6676                                CodeCompleter->getCodeCompletionTUInfo(), CC);
6677     if (!PreferredType.isNull())
6678       DummyResults.setPreferredType(PreferredType);
6679     if (S->getEntity()) {
6680       CodeCompletionDeclConsumer Consumer(DummyResults, S->getEntity(),
6681                                           BaseType);
6682       LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
6683                          /*IncludeGlobalScope=*/false,
6684                          /*LoadExternal=*/false);
6685     }
6686     HandleCodeCompleteResults(this, CodeCompleter,
6687                               DummyResults.getCompletionContext(), nullptr, 0);
6688     return;
6689   }
6690   // Always pretend to enter a context to ensure that a dependent type
6691   // resolves to a dependent record.
6692   DeclContext *Ctx = computeDeclContext(SS, /*EnteringContext=*/true);
6693 
6694   // Try to instantiate any non-dependent declaration contexts before
6695   // we look in them. Bail out if we fail.
6696   NestedNameSpecifier *NNS = SS.getScopeRep();
6697   if (NNS != nullptr && SS.isValid() && !NNS->isDependent()) {
6698     if (Ctx == nullptr || RequireCompleteDeclContext(SS, Ctx))
6699       return;
6700   }
6701 
6702   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6703                         CodeCompleter->getCodeCompletionTUInfo(), CC);
6704   if (!PreferredType.isNull())
6705     Results.setPreferredType(PreferredType);
6706   Results.EnterNewScope();
6707 
6708   // The "template" keyword can follow "::" in the grammar, but only
6709   // put it into the grammar if the nested-name-specifier is dependent.
6710   // FIXME: results is always empty, this appears to be dead.
6711   if (!Results.empty() && NNS && NNS->isDependent())
6712     Results.AddResult("template");
6713 
6714   // If the scope is a concept-constrained type parameter, infer nested
6715   // members based on the constraints.
6716   if (NNS) {
6717     if (const auto *TTPT =
6718             dyn_cast_or_null<TemplateTypeParmType>(NNS->getAsType())) {
6719       for (const auto &R : ConceptInfo(*TTPT, S).members()) {
6720         if (R.Operator != ConceptInfo::Member::Colons)
6721           continue;
6722         Results.AddResult(CodeCompletionResult(
6723             R.render(*this, CodeCompleter->getAllocator(),
6724                      CodeCompleter->getCodeCompletionTUInfo())));
6725       }
6726     }
6727   }
6728 
6729   // Add calls to overridden virtual functions, if there are any.
6730   //
6731   // FIXME: This isn't wonderful, because we don't know whether we're actually
6732   // in a context that permits expressions. This is a general issue with
6733   // qualified-id completions.
6734   if (Ctx && !EnteringContext)
6735     MaybeAddOverrideCalls(*this, Ctx, Results);
6736   Results.ExitScope();
6737 
6738   if (Ctx &&
6739       (CodeCompleter->includeNamespaceLevelDecls() || !Ctx->isFileContext())) {
6740     CodeCompletionDeclConsumer Consumer(Results, Ctx, BaseType);
6741     LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer,
6742                        /*IncludeGlobalScope=*/true,
6743                        /*IncludeDependentBases=*/true,
6744                        CodeCompleter->loadExternal());
6745   }
6746 
6747   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6748                             Results.data(), Results.size());
6749 }
6750 
6751 void Sema::CodeCompleteUsing(Scope *S) {
6752   if (!CodeCompleter)
6753     return;
6754 
6755   // This can be both a using alias or using declaration, in the former we
6756   // expect a new name and a symbol in the latter case.
6757   CodeCompletionContext Context(CodeCompletionContext::CCC_SymbolOrNewName);
6758   Context.setIsUsingDeclaration(true);
6759 
6760   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6761                         CodeCompleter->getCodeCompletionTUInfo(), Context,
6762                         &ResultBuilder::IsNestedNameSpecifier);
6763   Results.EnterNewScope();
6764 
6765   // If we aren't in class scope, we could see the "namespace" keyword.
6766   if (!S->isClassScope())
6767     Results.AddResult(CodeCompletionResult("namespace"));
6768 
6769   // After "using", we can see anything that would start a
6770   // nested-name-specifier.
6771   CodeCompletionDeclConsumer Consumer(Results, CurContext);
6772   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
6773                      CodeCompleter->includeGlobals(),
6774                      CodeCompleter->loadExternal());
6775   Results.ExitScope();
6776 
6777   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6778                             Results.data(), Results.size());
6779 }
6780 
6781 void Sema::CodeCompleteUsingDirective(Scope *S) {
6782   if (!CodeCompleter)
6783     return;
6784 
6785   // After "using namespace", we expect to see a namespace name or namespace
6786   // alias.
6787   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6788                         CodeCompleter->getCodeCompletionTUInfo(),
6789                         CodeCompletionContext::CCC_Namespace,
6790                         &ResultBuilder::IsNamespaceOrAlias);
6791   Results.EnterNewScope();
6792   CodeCompletionDeclConsumer Consumer(Results, CurContext);
6793   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
6794                      CodeCompleter->includeGlobals(),
6795                      CodeCompleter->loadExternal());
6796   Results.ExitScope();
6797   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6798                             Results.data(), Results.size());
6799 }
6800 
6801 void Sema::CodeCompleteNamespaceDecl(Scope *S) {
6802   if (!CodeCompleter)
6803     return;
6804 
6805   DeclContext *Ctx = S->getEntity();
6806   if (!S->getParent())
6807     Ctx = Context.getTranslationUnitDecl();
6808 
6809   bool SuppressedGlobalResults =
6810       Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
6811 
6812   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6813                         CodeCompleter->getCodeCompletionTUInfo(),
6814                         SuppressedGlobalResults
6815                             ? CodeCompletionContext::CCC_Namespace
6816                             : CodeCompletionContext::CCC_Other,
6817                         &ResultBuilder::IsNamespace);
6818 
6819   if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
6820     // We only want to see those namespaces that have already been defined
6821     // within this scope, because its likely that the user is creating an
6822     // extended namespace declaration. Keep track of the most recent
6823     // definition of each namespace.
6824     std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
6825     for (DeclContext::specific_decl_iterator<NamespaceDecl>
6826              NS(Ctx->decls_begin()),
6827          NSEnd(Ctx->decls_end());
6828          NS != NSEnd; ++NS)
6829       OrigToLatest[NS->getOriginalNamespace()] = *NS;
6830 
6831     // Add the most recent definition (or extended definition) of each
6832     // namespace to the list of results.
6833     Results.EnterNewScope();
6834     for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
6835              NS = OrigToLatest.begin(),
6836              NSEnd = OrigToLatest.end();
6837          NS != NSEnd; ++NS)
6838       Results.AddResult(
6839           CodeCompletionResult(NS->second, Results.getBasePriority(NS->second),
6840                                nullptr),
6841           CurContext, nullptr, false);
6842     Results.ExitScope();
6843   }
6844 
6845   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6846                             Results.data(), Results.size());
6847 }
6848 
6849 void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
6850   if (!CodeCompleter)
6851     return;
6852 
6853   // After "namespace", we expect to see a namespace or alias.
6854   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6855                         CodeCompleter->getCodeCompletionTUInfo(),
6856                         CodeCompletionContext::CCC_Namespace,
6857                         &ResultBuilder::IsNamespaceOrAlias);
6858   CodeCompletionDeclConsumer Consumer(Results, CurContext);
6859   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
6860                      CodeCompleter->includeGlobals(),
6861                      CodeCompleter->loadExternal());
6862   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6863                             Results.data(), Results.size());
6864 }
6865 
6866 void Sema::CodeCompleteOperatorName(Scope *S) {
6867   if (!CodeCompleter)
6868     return;
6869 
6870   typedef CodeCompletionResult Result;
6871   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6872                         CodeCompleter->getCodeCompletionTUInfo(),
6873                         CodeCompletionContext::CCC_Type,
6874                         &ResultBuilder::IsType);
6875   Results.EnterNewScope();
6876 
6877   // Add the names of overloadable operators. Note that OO_Conditional is not
6878   // actually overloadable.
6879 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly)  \
6880   if (OO_##Name != OO_Conditional)                                             \
6881     Results.AddResult(Result(Spelling));
6882 #include "clang/Basic/OperatorKinds.def"
6883 
6884   // Add any type names visible from the current scope
6885   Results.allowNestedNameSpecifiers();
6886   CodeCompletionDeclConsumer Consumer(Results, CurContext);
6887   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
6888                      CodeCompleter->includeGlobals(),
6889                      CodeCompleter->loadExternal());
6890 
6891   // Add any type specifiers
6892   AddTypeSpecifierResults(getLangOpts(), Results);
6893   Results.ExitScope();
6894 
6895   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6896                             Results.data(), Results.size());
6897 }
6898 
6899 void Sema::CodeCompleteConstructorInitializer(
6900     Decl *ConstructorD, ArrayRef<CXXCtorInitializer *> Initializers) {
6901   if (!ConstructorD)
6902     return;
6903 
6904   AdjustDeclIfTemplate(ConstructorD);
6905 
6906   auto *Constructor = dyn_cast<CXXConstructorDecl>(ConstructorD);
6907   if (!Constructor)
6908     return;
6909 
6910   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6911                         CodeCompleter->getCodeCompletionTUInfo(),
6912                         CodeCompletionContext::CCC_Symbol);
6913   Results.EnterNewScope();
6914 
6915   // Fill in any already-initialized fields or base classes.
6916   llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
6917   llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
6918   for (unsigned I = 0, E = Initializers.size(); I != E; ++I) {
6919     if (Initializers[I]->isBaseInitializer())
6920       InitializedBases.insert(Context.getCanonicalType(
6921           QualType(Initializers[I]->getBaseClass(), 0)));
6922     else
6923       InitializedFields.insert(
6924           cast<FieldDecl>(Initializers[I]->getAnyMember()));
6925   }
6926 
6927   // Add completions for base classes.
6928   PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
6929   bool SawLastInitializer = Initializers.empty();
6930   CXXRecordDecl *ClassDecl = Constructor->getParent();
6931 
6932   auto GenerateCCS = [&](const NamedDecl *ND, const char *Name) {
6933     CodeCompletionBuilder Builder(Results.getAllocator(),
6934                                   Results.getCodeCompletionTUInfo());
6935     Builder.AddTypedTextChunk(Name);
6936     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6937     if (const auto *Function = dyn_cast<FunctionDecl>(ND))
6938       AddFunctionParameterChunks(PP, Policy, Function, Builder);
6939     else if (const auto *FunTemplDecl = dyn_cast<FunctionTemplateDecl>(ND))
6940       AddFunctionParameterChunks(PP, Policy, FunTemplDecl->getTemplatedDecl(),
6941                                  Builder);
6942     Builder.AddChunk(CodeCompletionString::CK_RightParen);
6943     return Builder.TakeString();
6944   };
6945   auto AddDefaultCtorInit = [&](const char *Name, const char *Type,
6946                                 const NamedDecl *ND) {
6947     CodeCompletionBuilder Builder(Results.getAllocator(),
6948                                   Results.getCodeCompletionTUInfo());
6949     Builder.AddTypedTextChunk(Name);
6950     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6951     Builder.AddPlaceholderChunk(Type);
6952     Builder.AddChunk(CodeCompletionString::CK_RightParen);
6953     if (ND) {
6954       auto CCR = CodeCompletionResult(
6955           Builder.TakeString(), ND,
6956           SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration);
6957       if (isa<FieldDecl>(ND))
6958         CCR.CursorKind = CXCursor_MemberRef;
6959       return Results.AddResult(CCR);
6960     }
6961     return Results.AddResult(CodeCompletionResult(
6962         Builder.TakeString(),
6963         SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration));
6964   };
6965   auto AddCtorsWithName = [&](const CXXRecordDecl *RD, unsigned int Priority,
6966                               const char *Name, const FieldDecl *FD) {
6967     if (!RD)
6968       return AddDefaultCtorInit(Name,
6969                                 FD ? Results.getAllocator().CopyString(
6970                                          FD->getType().getAsString(Policy))
6971                                    : Name,
6972                                 FD);
6973     auto Ctors = getConstructors(Context, RD);
6974     if (Ctors.begin() == Ctors.end())
6975       return AddDefaultCtorInit(Name, Name, RD);
6976     for (const NamedDecl *Ctor : Ctors) {
6977       auto CCR = CodeCompletionResult(GenerateCCS(Ctor, Name), RD, Priority);
6978       CCR.CursorKind = getCursorKindForDecl(Ctor);
6979       Results.AddResult(CCR);
6980     }
6981   };
6982   auto AddBase = [&](const CXXBaseSpecifier &Base) {
6983     const char *BaseName =
6984         Results.getAllocator().CopyString(Base.getType().getAsString(Policy));
6985     const auto *RD = Base.getType()->getAsCXXRecordDecl();
6986     AddCtorsWithName(
6987         RD, SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration,
6988         BaseName, nullptr);
6989   };
6990   auto AddField = [&](const FieldDecl *FD) {
6991     const char *FieldName =
6992         Results.getAllocator().CopyString(FD->getIdentifier()->getName());
6993     const CXXRecordDecl *RD = FD->getType()->getAsCXXRecordDecl();
6994     AddCtorsWithName(
6995         RD, SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration,
6996         FieldName, FD);
6997   };
6998 
6999   for (const auto &Base : ClassDecl->bases()) {
7000     if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
7001              .second) {
7002       SawLastInitializer =
7003           !Initializers.empty() && Initializers.back()->isBaseInitializer() &&
7004           Context.hasSameUnqualifiedType(
7005               Base.getType(), QualType(Initializers.back()->getBaseClass(), 0));
7006       continue;
7007     }
7008 
7009     AddBase(Base);
7010     SawLastInitializer = false;
7011   }
7012 
7013   // Add completions for virtual base classes.
7014   for (const auto &Base : ClassDecl->vbases()) {
7015     if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
7016              .second) {
7017       SawLastInitializer =
7018           !Initializers.empty() && Initializers.back()->isBaseInitializer() &&
7019           Context.hasSameUnqualifiedType(
7020               Base.getType(), QualType(Initializers.back()->getBaseClass(), 0));
7021       continue;
7022     }
7023 
7024     AddBase(Base);
7025     SawLastInitializer = false;
7026   }
7027 
7028   // Add completions for members.
7029   for (auto *Field : ClassDecl->fields()) {
7030     if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))
7031              .second) {
7032       SawLastInitializer = !Initializers.empty() &&
7033                            Initializers.back()->isAnyMemberInitializer() &&
7034                            Initializers.back()->getAnyMember() == Field;
7035       continue;
7036     }
7037 
7038     if (!Field->getDeclName())
7039       continue;
7040 
7041     AddField(Field);
7042     SawLastInitializer = false;
7043   }
7044   Results.ExitScope();
7045 
7046   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7047                             Results.data(), Results.size());
7048 }
7049 
7050 /// Determine whether this scope denotes a namespace.
7051 static bool isNamespaceScope(Scope *S) {
7052   DeclContext *DC = S->getEntity();
7053   if (!DC)
7054     return false;
7055 
7056   return DC->isFileContext();
7057 }
7058 
7059 void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
7060                                         bool AfterAmpersand) {
7061   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7062                         CodeCompleter->getCodeCompletionTUInfo(),
7063                         CodeCompletionContext::CCC_Other);
7064   Results.EnterNewScope();
7065 
7066   // Note what has already been captured.
7067   llvm::SmallPtrSet<IdentifierInfo *, 4> Known;
7068   bool IncludedThis = false;
7069   for (const auto &C : Intro.Captures) {
7070     if (C.Kind == LCK_This) {
7071       IncludedThis = true;
7072       continue;
7073     }
7074 
7075     Known.insert(C.Id);
7076   }
7077 
7078   // Look for other capturable variables.
7079   for (; S && !isNamespaceScope(S); S = S->getParent()) {
7080     for (const auto *D : S->decls()) {
7081       const auto *Var = dyn_cast<VarDecl>(D);
7082       if (!Var || !Var->hasLocalStorage() || Var->hasAttr<BlocksAttr>())
7083         continue;
7084 
7085       if (Known.insert(Var->getIdentifier()).second)
7086         Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration),
7087                           CurContext, nullptr, false);
7088     }
7089   }
7090 
7091   // Add 'this', if it would be valid.
7092   if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy)
7093     addThisCompletion(*this, Results);
7094 
7095   Results.ExitScope();
7096 
7097   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7098                             Results.data(), Results.size());
7099 }
7100 
7101 void Sema::CodeCompleteAfterFunctionEquals(Declarator &D) {
7102   if (!LangOpts.CPlusPlus11)
7103     return;
7104   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7105                         CodeCompleter->getCodeCompletionTUInfo(),
7106                         CodeCompletionContext::CCC_Other);
7107   auto ShouldAddDefault = [&D, this]() {
7108     if (!D.isFunctionDeclarator())
7109       return false;
7110     auto &Id = D.getName();
7111     if (Id.getKind() == UnqualifiedIdKind::IK_DestructorName)
7112       return true;
7113     // FIXME(liuhui): Ideally, we should check the constructor parameter list to
7114     // verify that it is the default, copy or move constructor?
7115     if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName &&
7116         D.getFunctionTypeInfo().NumParams <= 1)
7117       return true;
7118     if (Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId) {
7119       auto Op = Id.OperatorFunctionId.Operator;
7120       // FIXME(liuhui): Ideally, we should check the function parameter list to
7121       // verify that it is the copy or move assignment?
7122       if (Op == OverloadedOperatorKind::OO_Equal)
7123         return true;
7124       if (LangOpts.CPlusPlus20 &&
7125           (Op == OverloadedOperatorKind::OO_EqualEqual ||
7126            Op == OverloadedOperatorKind::OO_ExclaimEqual ||
7127            Op == OverloadedOperatorKind::OO_Less ||
7128            Op == OverloadedOperatorKind::OO_LessEqual ||
7129            Op == OverloadedOperatorKind::OO_Greater ||
7130            Op == OverloadedOperatorKind::OO_GreaterEqual ||
7131            Op == OverloadedOperatorKind::OO_Spaceship))
7132         return true;
7133     }
7134     return false;
7135   };
7136 
7137   Results.EnterNewScope();
7138   if (ShouldAddDefault())
7139     Results.AddResult("default");
7140   // FIXME(liuhui): Ideally, we should only provide `delete` completion for the
7141   // first function declaration.
7142   Results.AddResult("delete");
7143   Results.ExitScope();
7144   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7145                             Results.data(), Results.size());
7146 }
7147 
7148 /// Macro that optionally prepends an "@" to the string literal passed in via
7149 /// Keyword, depending on whether NeedAt is true or false.
7150 #define OBJC_AT_KEYWORD_NAME(NeedAt, Keyword) ((NeedAt) ? "@" Keyword : Keyword)
7151 
7152 static void AddObjCImplementationResults(const LangOptions &LangOpts,
7153                                          ResultBuilder &Results, bool NeedAt) {
7154   typedef CodeCompletionResult Result;
7155   // Since we have an implementation, we can end it.
7156   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "end")));
7157 
7158   CodeCompletionBuilder Builder(Results.getAllocator(),
7159                                 Results.getCodeCompletionTUInfo());
7160   if (LangOpts.ObjC) {
7161     // @dynamic
7162     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "dynamic"));
7163     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7164     Builder.AddPlaceholderChunk("property");
7165     Results.AddResult(Result(Builder.TakeString()));
7166 
7167     // @synthesize
7168     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "synthesize"));
7169     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7170     Builder.AddPlaceholderChunk("property");
7171     Results.AddResult(Result(Builder.TakeString()));
7172   }
7173 }
7174 
7175 static void AddObjCInterfaceResults(const LangOptions &LangOpts,
7176                                     ResultBuilder &Results, bool NeedAt) {
7177   typedef CodeCompletionResult Result;
7178 
7179   // Since we have an interface or protocol, we can end it.
7180   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "end")));
7181 
7182   if (LangOpts.ObjC) {
7183     // @property
7184     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "property")));
7185 
7186     // @required
7187     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "required")));
7188 
7189     // @optional
7190     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "optional")));
7191   }
7192 }
7193 
7194 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
7195   typedef CodeCompletionResult Result;
7196   CodeCompletionBuilder Builder(Results.getAllocator(),
7197                                 Results.getCodeCompletionTUInfo());
7198 
7199   // @class name ;
7200   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "class"));
7201   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7202   Builder.AddPlaceholderChunk("name");
7203   Results.AddResult(Result(Builder.TakeString()));
7204 
7205   if (Results.includeCodePatterns()) {
7206     // @interface name
7207     // FIXME: Could introduce the whole pattern, including superclasses and
7208     // such.
7209     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "interface"));
7210     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7211     Builder.AddPlaceholderChunk("class");
7212     Results.AddResult(Result(Builder.TakeString()));
7213 
7214     // @protocol name
7215     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "protocol"));
7216     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7217     Builder.AddPlaceholderChunk("protocol");
7218     Results.AddResult(Result(Builder.TakeString()));
7219 
7220     // @implementation name
7221     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "implementation"));
7222     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7223     Builder.AddPlaceholderChunk("class");
7224     Results.AddResult(Result(Builder.TakeString()));
7225   }
7226 
7227   // @compatibility_alias name
7228   Builder.AddTypedTextChunk(
7229       OBJC_AT_KEYWORD_NAME(NeedAt, "compatibility_alias"));
7230   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7231   Builder.AddPlaceholderChunk("alias");
7232   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7233   Builder.AddPlaceholderChunk("class");
7234   Results.AddResult(Result(Builder.TakeString()));
7235 
7236   if (Results.getSema().getLangOpts().Modules) {
7237     // @import name
7238     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import"));
7239     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7240     Builder.AddPlaceholderChunk("module");
7241     Results.AddResult(Result(Builder.TakeString()));
7242   }
7243 }
7244 
7245 void Sema::CodeCompleteObjCAtDirective(Scope *S) {
7246   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7247                         CodeCompleter->getCodeCompletionTUInfo(),
7248                         CodeCompletionContext::CCC_Other);
7249   Results.EnterNewScope();
7250   if (isa<ObjCImplDecl>(CurContext))
7251     AddObjCImplementationResults(getLangOpts(), Results, false);
7252   else if (CurContext->isObjCContainer())
7253     AddObjCInterfaceResults(getLangOpts(), Results, false);
7254   else
7255     AddObjCTopLevelResults(Results, false);
7256   Results.ExitScope();
7257   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7258                             Results.data(), Results.size());
7259 }
7260 
7261 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
7262   typedef CodeCompletionResult Result;
7263   CodeCompletionBuilder Builder(Results.getAllocator(),
7264                                 Results.getCodeCompletionTUInfo());
7265 
7266   // @encode ( type-name )
7267   const char *EncodeType = "char[]";
7268   if (Results.getSema().getLangOpts().CPlusPlus ||
7269       Results.getSema().getLangOpts().ConstStrings)
7270     EncodeType = "const char[]";
7271   Builder.AddResultTypeChunk(EncodeType);
7272   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "encode"));
7273   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7274   Builder.AddPlaceholderChunk("type-name");
7275   Builder.AddChunk(CodeCompletionString::CK_RightParen);
7276   Results.AddResult(Result(Builder.TakeString()));
7277 
7278   // @protocol ( protocol-name )
7279   Builder.AddResultTypeChunk("Protocol *");
7280   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "protocol"));
7281   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7282   Builder.AddPlaceholderChunk("protocol-name");
7283   Builder.AddChunk(CodeCompletionString::CK_RightParen);
7284   Results.AddResult(Result(Builder.TakeString()));
7285 
7286   // @selector ( selector )
7287   Builder.AddResultTypeChunk("SEL");
7288   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "selector"));
7289   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7290   Builder.AddPlaceholderChunk("selector");
7291   Builder.AddChunk(CodeCompletionString::CK_RightParen);
7292   Results.AddResult(Result(Builder.TakeString()));
7293 
7294   // @"string"
7295   Builder.AddResultTypeChunk("NSString *");
7296   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "\""));
7297   Builder.AddPlaceholderChunk("string");
7298   Builder.AddTextChunk("\"");
7299   Results.AddResult(Result(Builder.TakeString()));
7300 
7301   // @[objects, ...]
7302   Builder.AddResultTypeChunk("NSArray *");
7303   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "["));
7304   Builder.AddPlaceholderChunk("objects, ...");
7305   Builder.AddChunk(CodeCompletionString::CK_RightBracket);
7306   Results.AddResult(Result(Builder.TakeString()));
7307 
7308   // @{key : object, ...}
7309   Builder.AddResultTypeChunk("NSDictionary *");
7310   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "{"));
7311   Builder.AddPlaceholderChunk("key");
7312   Builder.AddChunk(CodeCompletionString::CK_Colon);
7313   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7314   Builder.AddPlaceholderChunk("object, ...");
7315   Builder.AddChunk(CodeCompletionString::CK_RightBrace);
7316   Results.AddResult(Result(Builder.TakeString()));
7317 
7318   // @(expression)
7319   Builder.AddResultTypeChunk("id");
7320   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "("));
7321   Builder.AddPlaceholderChunk("expression");
7322   Builder.AddChunk(CodeCompletionString::CK_RightParen);
7323   Results.AddResult(Result(Builder.TakeString()));
7324 }
7325 
7326 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
7327   typedef CodeCompletionResult Result;
7328   CodeCompletionBuilder Builder(Results.getAllocator(),
7329                                 Results.getCodeCompletionTUInfo());
7330 
7331   if (Results.includeCodePatterns()) {
7332     // @try { statements } @catch ( declaration ) { statements } @finally
7333     //   { statements }
7334     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "try"));
7335     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
7336     Builder.AddPlaceholderChunk("statements");
7337     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
7338     Builder.AddTextChunk("@catch");
7339     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7340     Builder.AddPlaceholderChunk("parameter");
7341     Builder.AddChunk(CodeCompletionString::CK_RightParen);
7342     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
7343     Builder.AddPlaceholderChunk("statements");
7344     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
7345     Builder.AddTextChunk("@finally");
7346     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
7347     Builder.AddPlaceholderChunk("statements");
7348     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
7349     Results.AddResult(Result(Builder.TakeString()));
7350   }
7351 
7352   // @throw
7353   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "throw"));
7354   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7355   Builder.AddPlaceholderChunk("expression");
7356   Results.AddResult(Result(Builder.TakeString()));
7357 
7358   if (Results.includeCodePatterns()) {
7359     // @synchronized ( expression ) { statements }
7360     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "synchronized"));
7361     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7362     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7363     Builder.AddPlaceholderChunk("expression");
7364     Builder.AddChunk(CodeCompletionString::CK_RightParen);
7365     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
7366     Builder.AddPlaceholderChunk("statements");
7367     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
7368     Results.AddResult(Result(Builder.TakeString()));
7369   }
7370 }
7371 
7372 static void AddObjCVisibilityResults(const LangOptions &LangOpts,
7373                                      ResultBuilder &Results, bool NeedAt) {
7374   typedef CodeCompletionResult Result;
7375   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "private")));
7376   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "protected")));
7377   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "public")));
7378   if (LangOpts.ObjC)
7379     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "package")));
7380 }
7381 
7382 void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
7383   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7384                         CodeCompleter->getCodeCompletionTUInfo(),
7385                         CodeCompletionContext::CCC_Other);
7386   Results.EnterNewScope();
7387   AddObjCVisibilityResults(getLangOpts(), Results, false);
7388   Results.ExitScope();
7389   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7390                             Results.data(), Results.size());
7391 }
7392 
7393 void Sema::CodeCompleteObjCAtStatement(Scope *S) {
7394   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7395                         CodeCompleter->getCodeCompletionTUInfo(),
7396                         CodeCompletionContext::CCC_Other);
7397   Results.EnterNewScope();
7398   AddObjCStatementResults(Results, false);
7399   AddObjCExpressionResults(Results, false);
7400   Results.ExitScope();
7401   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7402                             Results.data(), Results.size());
7403 }
7404 
7405 void Sema::CodeCompleteObjCAtExpression(Scope *S) {
7406   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7407                         CodeCompleter->getCodeCompletionTUInfo(),
7408                         CodeCompletionContext::CCC_Other);
7409   Results.EnterNewScope();
7410   AddObjCExpressionResults(Results, false);
7411   Results.ExitScope();
7412   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7413                             Results.data(), Results.size());
7414 }
7415 
7416 /// Determine whether the addition of the given flag to an Objective-C
7417 /// property's attributes will cause a conflict.
7418 static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
7419   // Check if we've already added this flag.
7420   if (Attributes & NewFlag)
7421     return true;
7422 
7423   Attributes |= NewFlag;
7424 
7425   // Check for collisions with "readonly".
7426   if ((Attributes & ObjCPropertyAttribute::kind_readonly) &&
7427       (Attributes & ObjCPropertyAttribute::kind_readwrite))
7428     return true;
7429 
7430   // Check for more than one of { assign, copy, retain, strong, weak }.
7431   unsigned AssignCopyRetMask =
7432       Attributes &
7433       (ObjCPropertyAttribute::kind_assign |
7434        ObjCPropertyAttribute::kind_unsafe_unretained |
7435        ObjCPropertyAttribute::kind_copy | ObjCPropertyAttribute::kind_retain |
7436        ObjCPropertyAttribute::kind_strong | ObjCPropertyAttribute::kind_weak);
7437   if (AssignCopyRetMask &&
7438       AssignCopyRetMask != ObjCPropertyAttribute::kind_assign &&
7439       AssignCopyRetMask != ObjCPropertyAttribute::kind_unsafe_unretained &&
7440       AssignCopyRetMask != ObjCPropertyAttribute::kind_copy &&
7441       AssignCopyRetMask != ObjCPropertyAttribute::kind_retain &&
7442       AssignCopyRetMask != ObjCPropertyAttribute::kind_strong &&
7443       AssignCopyRetMask != ObjCPropertyAttribute::kind_weak)
7444     return true;
7445 
7446   return false;
7447 }
7448 
7449 void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
7450   if (!CodeCompleter)
7451     return;
7452 
7453   unsigned Attributes = ODS.getPropertyAttributes();
7454 
7455   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7456                         CodeCompleter->getCodeCompletionTUInfo(),
7457                         CodeCompletionContext::CCC_Other);
7458   Results.EnterNewScope();
7459   if (!ObjCPropertyFlagConflicts(Attributes,
7460                                  ObjCPropertyAttribute::kind_readonly))
7461     Results.AddResult(CodeCompletionResult("readonly"));
7462   if (!ObjCPropertyFlagConflicts(Attributes,
7463                                  ObjCPropertyAttribute::kind_assign))
7464     Results.AddResult(CodeCompletionResult("assign"));
7465   if (!ObjCPropertyFlagConflicts(Attributes,
7466                                  ObjCPropertyAttribute::kind_unsafe_unretained))
7467     Results.AddResult(CodeCompletionResult("unsafe_unretained"));
7468   if (!ObjCPropertyFlagConflicts(Attributes,
7469                                  ObjCPropertyAttribute::kind_readwrite))
7470     Results.AddResult(CodeCompletionResult("readwrite"));
7471   if (!ObjCPropertyFlagConflicts(Attributes,
7472                                  ObjCPropertyAttribute::kind_retain))
7473     Results.AddResult(CodeCompletionResult("retain"));
7474   if (!ObjCPropertyFlagConflicts(Attributes,
7475                                  ObjCPropertyAttribute::kind_strong))
7476     Results.AddResult(CodeCompletionResult("strong"));
7477   if (!ObjCPropertyFlagConflicts(Attributes, ObjCPropertyAttribute::kind_copy))
7478     Results.AddResult(CodeCompletionResult("copy"));
7479   if (!ObjCPropertyFlagConflicts(Attributes,
7480                                  ObjCPropertyAttribute::kind_nonatomic))
7481     Results.AddResult(CodeCompletionResult("nonatomic"));
7482   if (!ObjCPropertyFlagConflicts(Attributes,
7483                                  ObjCPropertyAttribute::kind_atomic))
7484     Results.AddResult(CodeCompletionResult("atomic"));
7485 
7486   // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC.
7487   if (getLangOpts().ObjCWeak || getLangOpts().getGC() != LangOptions::NonGC)
7488     if (!ObjCPropertyFlagConflicts(Attributes,
7489                                    ObjCPropertyAttribute::kind_weak))
7490       Results.AddResult(CodeCompletionResult("weak"));
7491 
7492   if (!ObjCPropertyFlagConflicts(Attributes,
7493                                  ObjCPropertyAttribute::kind_setter)) {
7494     CodeCompletionBuilder Setter(Results.getAllocator(),
7495                                  Results.getCodeCompletionTUInfo());
7496     Setter.AddTypedTextChunk("setter");
7497     Setter.AddTextChunk("=");
7498     Setter.AddPlaceholderChunk("method");
7499     Results.AddResult(CodeCompletionResult(Setter.TakeString()));
7500   }
7501   if (!ObjCPropertyFlagConflicts(Attributes,
7502                                  ObjCPropertyAttribute::kind_getter)) {
7503     CodeCompletionBuilder Getter(Results.getAllocator(),
7504                                  Results.getCodeCompletionTUInfo());
7505     Getter.AddTypedTextChunk("getter");
7506     Getter.AddTextChunk("=");
7507     Getter.AddPlaceholderChunk("method");
7508     Results.AddResult(CodeCompletionResult(Getter.TakeString()));
7509   }
7510   if (!ObjCPropertyFlagConflicts(Attributes,
7511                                  ObjCPropertyAttribute::kind_nullability)) {
7512     Results.AddResult(CodeCompletionResult("nonnull"));
7513     Results.AddResult(CodeCompletionResult("nullable"));
7514     Results.AddResult(CodeCompletionResult("null_unspecified"));
7515     Results.AddResult(CodeCompletionResult("null_resettable"));
7516   }
7517   Results.ExitScope();
7518   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7519                             Results.data(), Results.size());
7520 }
7521 
7522 /// Describes the kind of Objective-C method that we want to find
7523 /// via code completion.
7524 enum ObjCMethodKind {
7525   MK_Any, ///< Any kind of method, provided it means other specified criteria.
7526   MK_ZeroArgSelector, ///< Zero-argument (unary) selector.
7527   MK_OneArgSelector   ///< One-argument selector.
7528 };
7529 
7530 static bool isAcceptableObjCSelector(Selector Sel, ObjCMethodKind WantKind,
7531                                      ArrayRef<const IdentifierInfo *> SelIdents,
7532                                      bool AllowSameLength = true) {
7533   unsigned NumSelIdents = SelIdents.size();
7534   if (NumSelIdents > Sel.getNumArgs())
7535     return false;
7536 
7537   switch (WantKind) {
7538   case MK_Any:
7539     break;
7540   case MK_ZeroArgSelector:
7541     return Sel.isUnarySelector();
7542   case MK_OneArgSelector:
7543     return Sel.getNumArgs() == 1;
7544   }
7545 
7546   if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
7547     return false;
7548 
7549   for (unsigned I = 0; I != NumSelIdents; ++I)
7550     if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
7551       return false;
7552 
7553   return true;
7554 }
7555 
7556 static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
7557                                    ObjCMethodKind WantKind,
7558                                    ArrayRef<const IdentifierInfo *> SelIdents,
7559                                    bool AllowSameLength = true) {
7560   return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
7561                                   AllowSameLength);
7562 }
7563 
7564 /// A set of selectors, which is used to avoid introducing multiple
7565 /// completions with the same selector into the result set.
7566 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
7567 
7568 /// Add all of the Objective-C methods in the given Objective-C
7569 /// container to the set of results.
7570 ///
7571 /// The container will be a class, protocol, category, or implementation of
7572 /// any of the above. This mether will recurse to include methods from
7573 /// the superclasses of classes along with their categories, protocols, and
7574 /// implementations.
7575 ///
7576 /// \param Container the container in which we'll look to find methods.
7577 ///
7578 /// \param WantInstanceMethods Whether to add instance methods (only); if
7579 /// false, this routine will add factory methods (only).
7580 ///
7581 /// \param CurContext the context in which we're performing the lookup that
7582 /// finds methods.
7583 ///
7584 /// \param AllowSameLength Whether we allow a method to be added to the list
7585 /// when it has the same number of parameters as we have selector identifiers.
7586 ///
7587 /// \param Results the structure into which we'll add results.
7588 static void AddObjCMethods(ObjCContainerDecl *Container,
7589                            bool WantInstanceMethods, ObjCMethodKind WantKind,
7590                            ArrayRef<const IdentifierInfo *> SelIdents,
7591                            DeclContext *CurContext,
7592                            VisitedSelectorSet &Selectors, bool AllowSameLength,
7593                            ResultBuilder &Results, bool InOriginalClass = true,
7594                            bool IsRootClass = false) {
7595   typedef CodeCompletionResult Result;
7596   Container = getContainerDef(Container);
7597   ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
7598   IsRootClass = IsRootClass || (IFace && !IFace->getSuperClass());
7599   for (ObjCMethodDecl *M : Container->methods()) {
7600     // The instance methods on the root class can be messaged via the
7601     // metaclass.
7602     if (M->isInstanceMethod() == WantInstanceMethods ||
7603         (IsRootClass && !WantInstanceMethods)) {
7604       // Check whether the selector identifiers we've been given are a
7605       // subset of the identifiers for this particular method.
7606       if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength))
7607         continue;
7608 
7609       if (!Selectors.insert(M->getSelector()).second)
7610         continue;
7611 
7612       Result R = Result(M, Results.getBasePriority(M), nullptr);
7613       R.StartParameter = SelIdents.size();
7614       R.AllParametersAreInformative = (WantKind != MK_Any);
7615       if (!InOriginalClass)
7616         setInBaseClass(R);
7617       Results.MaybeAddResult(R, CurContext);
7618     }
7619   }
7620 
7621   // Visit the protocols of protocols.
7622   if (const auto *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
7623     if (Protocol->hasDefinition()) {
7624       const ObjCList<ObjCProtocolDecl> &Protocols =
7625           Protocol->getReferencedProtocols();
7626       for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7627                                                 E = Protocols.end();
7628            I != E; ++I)
7629         AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext,
7630                        Selectors, AllowSameLength, Results, false, IsRootClass);
7631     }
7632   }
7633 
7634   if (!IFace || !IFace->hasDefinition())
7635     return;
7636 
7637   // Add methods in protocols.
7638   for (ObjCProtocolDecl *I : IFace->protocols())
7639     AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents, CurContext,
7640                    Selectors, AllowSameLength, Results, false, IsRootClass);
7641 
7642   // Add methods in categories.
7643   for (ObjCCategoryDecl *CatDecl : IFace->known_categories()) {
7644     AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
7645                    CurContext, Selectors, AllowSameLength, Results,
7646                    InOriginalClass, IsRootClass);
7647 
7648     // Add a categories protocol methods.
7649     const ObjCList<ObjCProtocolDecl> &Protocols =
7650         CatDecl->getReferencedProtocols();
7651     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7652                                               E = Protocols.end();
7653          I != E; ++I)
7654       AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext,
7655                      Selectors, AllowSameLength, Results, false, IsRootClass);
7656 
7657     // Add methods in category implementations.
7658     if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
7659       AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext,
7660                      Selectors, AllowSameLength, Results, InOriginalClass,
7661                      IsRootClass);
7662   }
7663 
7664   // Add methods in superclass.
7665   // Avoid passing in IsRootClass since root classes won't have super classes.
7666   if (IFace->getSuperClass())
7667     AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
7668                    SelIdents, CurContext, Selectors, AllowSameLength, Results,
7669                    /*IsRootClass=*/false);
7670 
7671   // Add methods in our implementation, if any.
7672   if (ObjCImplementationDecl *Impl = IFace->getImplementation())
7673     AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext,
7674                    Selectors, AllowSameLength, Results, InOriginalClass,
7675                    IsRootClass);
7676 }
7677 
7678 void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
7679   // Try to find the interface where getters might live.
7680   ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
7681   if (!Class) {
7682     if (ObjCCategoryDecl *Category =
7683             dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
7684       Class = Category->getClassInterface();
7685 
7686     if (!Class)
7687       return;
7688   }
7689 
7690   // Find all of the potential getters.
7691   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7692                         CodeCompleter->getCodeCompletionTUInfo(),
7693                         CodeCompletionContext::CCC_Other);
7694   Results.EnterNewScope();
7695 
7696   VisitedSelectorSet Selectors;
7697   AddObjCMethods(Class, true, MK_ZeroArgSelector, std::nullopt, CurContext,
7698                  Selectors,
7699                  /*AllowSameLength=*/true, Results);
7700   Results.ExitScope();
7701   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7702                             Results.data(), Results.size());
7703 }
7704 
7705 void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
7706   // Try to find the interface where setters might live.
7707   ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
7708   if (!Class) {
7709     if (ObjCCategoryDecl *Category =
7710             dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
7711       Class = Category->getClassInterface();
7712 
7713     if (!Class)
7714       return;
7715   }
7716 
7717   // Find all of the potential getters.
7718   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7719                         CodeCompleter->getCodeCompletionTUInfo(),
7720                         CodeCompletionContext::CCC_Other);
7721   Results.EnterNewScope();
7722 
7723   VisitedSelectorSet Selectors;
7724   AddObjCMethods(Class, true, MK_OneArgSelector, std::nullopt, CurContext,
7725                  Selectors,
7726                  /*AllowSameLength=*/true, Results);
7727 
7728   Results.ExitScope();
7729   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7730                             Results.data(), Results.size());
7731 }
7732 
7733 void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
7734                                        bool IsParameter) {
7735   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7736                         CodeCompleter->getCodeCompletionTUInfo(),
7737                         CodeCompletionContext::CCC_Type);
7738   Results.EnterNewScope();
7739 
7740   // Add context-sensitive, Objective-C parameter-passing keywords.
7741   bool AddedInOut = false;
7742   if ((DS.getObjCDeclQualifier() &
7743        (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
7744     Results.AddResult("in");
7745     Results.AddResult("inout");
7746     AddedInOut = true;
7747   }
7748   if ((DS.getObjCDeclQualifier() &
7749        (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
7750     Results.AddResult("out");
7751     if (!AddedInOut)
7752       Results.AddResult("inout");
7753   }
7754   if ((DS.getObjCDeclQualifier() &
7755        (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
7756         ObjCDeclSpec::DQ_Oneway)) == 0) {
7757     Results.AddResult("bycopy");
7758     Results.AddResult("byref");
7759     Results.AddResult("oneway");
7760   }
7761   if ((DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability) == 0) {
7762     Results.AddResult("nonnull");
7763     Results.AddResult("nullable");
7764     Results.AddResult("null_unspecified");
7765   }
7766 
7767   // If we're completing the return type of an Objective-C method and the
7768   // identifier IBAction refers to a macro, provide a completion item for
7769   // an action, e.g.,
7770   //   IBAction)<#selector#>:(id)sender
7771   if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
7772       PP.isMacroDefined("IBAction")) {
7773     CodeCompletionBuilder Builder(Results.getAllocator(),
7774                                   Results.getCodeCompletionTUInfo(),
7775                                   CCP_CodePattern, CXAvailability_Available);
7776     Builder.AddTypedTextChunk("IBAction");
7777     Builder.AddChunk(CodeCompletionString::CK_RightParen);
7778     Builder.AddPlaceholderChunk("selector");
7779     Builder.AddChunk(CodeCompletionString::CK_Colon);
7780     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7781     Builder.AddTextChunk("id");
7782     Builder.AddChunk(CodeCompletionString::CK_RightParen);
7783     Builder.AddTextChunk("sender");
7784     Results.AddResult(CodeCompletionResult(Builder.TakeString()));
7785   }
7786 
7787   // If we're completing the return type, provide 'instancetype'.
7788   if (!IsParameter) {
7789     Results.AddResult(CodeCompletionResult("instancetype"));
7790   }
7791 
7792   // Add various builtin type names and specifiers.
7793   AddOrdinaryNameResults(PCC_Type, S, *this, Results);
7794   Results.ExitScope();
7795 
7796   // Add the various type names
7797   Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
7798   CodeCompletionDeclConsumer Consumer(Results, CurContext);
7799   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
7800                      CodeCompleter->includeGlobals(),
7801                      CodeCompleter->loadExternal());
7802 
7803   if (CodeCompleter->includeMacros())
7804     AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
7805 
7806   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7807                             Results.data(), Results.size());
7808 }
7809 
7810 /// When we have an expression with type "id", we may assume
7811 /// that it has some more-specific class type based on knowledge of
7812 /// common uses of Objective-C. This routine returns that class type,
7813 /// or NULL if no better result could be determined.
7814 static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
7815   auto *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
7816   if (!Msg)
7817     return nullptr;
7818 
7819   Selector Sel = Msg->getSelector();
7820   if (Sel.isNull())
7821     return nullptr;
7822 
7823   const IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
7824   if (!Id)
7825     return nullptr;
7826 
7827   ObjCMethodDecl *Method = Msg->getMethodDecl();
7828   if (!Method)
7829     return nullptr;
7830 
7831   // Determine the class that we're sending the message to.
7832   ObjCInterfaceDecl *IFace = nullptr;
7833   switch (Msg->getReceiverKind()) {
7834   case ObjCMessageExpr::Class:
7835     if (const ObjCObjectType *ObjType =
7836             Msg->getClassReceiver()->getAs<ObjCObjectType>())
7837       IFace = ObjType->getInterface();
7838     break;
7839 
7840   case ObjCMessageExpr::Instance: {
7841     QualType T = Msg->getInstanceReceiver()->getType();
7842     if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
7843       IFace = Ptr->getInterfaceDecl();
7844     break;
7845   }
7846 
7847   case ObjCMessageExpr::SuperInstance:
7848   case ObjCMessageExpr::SuperClass:
7849     break;
7850   }
7851 
7852   if (!IFace)
7853     return nullptr;
7854 
7855   ObjCInterfaceDecl *Super = IFace->getSuperClass();
7856   if (Method->isInstanceMethod())
7857     return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
7858         .Case("retain", IFace)
7859         .Case("strong", IFace)
7860         .Case("autorelease", IFace)
7861         .Case("copy", IFace)
7862         .Case("copyWithZone", IFace)
7863         .Case("mutableCopy", IFace)
7864         .Case("mutableCopyWithZone", IFace)
7865         .Case("awakeFromCoder", IFace)
7866         .Case("replacementObjectFromCoder", IFace)
7867         .Case("class", IFace)
7868         .Case("classForCoder", IFace)
7869         .Case("superclass", Super)
7870         .Default(nullptr);
7871 
7872   return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
7873       .Case("new", IFace)
7874       .Case("alloc", IFace)
7875       .Case("allocWithZone", IFace)
7876       .Case("class", IFace)
7877       .Case("superclass", Super)
7878       .Default(nullptr);
7879 }
7880 
7881 // Add a special completion for a message send to "super", which fills in the
7882 // most likely case of forwarding all of our arguments to the superclass
7883 // function.
7884 ///
7885 /// \param S The semantic analysis object.
7886 ///
7887 /// \param NeedSuperKeyword Whether we need to prefix this completion with
7888 /// the "super" keyword. Otherwise, we just need to provide the arguments.
7889 ///
7890 /// \param SelIdents The identifiers in the selector that have already been
7891 /// provided as arguments for a send to "super".
7892 ///
7893 /// \param Results The set of results to augment.
7894 ///
7895 /// \returns the Objective-C method declaration that would be invoked by
7896 /// this "super" completion. If NULL, no completion was added.
7897 static ObjCMethodDecl *
7898 AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
7899                        ArrayRef<const IdentifierInfo *> SelIdents,
7900                        ResultBuilder &Results) {
7901   ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
7902   if (!CurMethod)
7903     return nullptr;
7904 
7905   ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
7906   if (!Class)
7907     return nullptr;
7908 
7909   // Try to find a superclass method with the same selector.
7910   ObjCMethodDecl *SuperMethod = nullptr;
7911   while ((Class = Class->getSuperClass()) && !SuperMethod) {
7912     // Check in the class
7913     SuperMethod = Class->getMethod(CurMethod->getSelector(),
7914                                    CurMethod->isInstanceMethod());
7915 
7916     // Check in categories or class extensions.
7917     if (!SuperMethod) {
7918       for (const auto *Cat : Class->known_categories()) {
7919         if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(),
7920                                           CurMethod->isInstanceMethod())))
7921           break;
7922       }
7923     }
7924   }
7925 
7926   if (!SuperMethod)
7927     return nullptr;
7928 
7929   // Check whether the superclass method has the same signature.
7930   if (CurMethod->param_size() != SuperMethod->param_size() ||
7931       CurMethod->isVariadic() != SuperMethod->isVariadic())
7932     return nullptr;
7933 
7934   for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
7935                                       CurPEnd = CurMethod->param_end(),
7936                                       SuperP = SuperMethod->param_begin();
7937        CurP != CurPEnd; ++CurP, ++SuperP) {
7938     // Make sure the parameter types are compatible.
7939     if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
7940                                           (*SuperP)->getType()))
7941       return nullptr;
7942 
7943     // Make sure we have a parameter name to forward!
7944     if (!(*CurP)->getIdentifier())
7945       return nullptr;
7946   }
7947 
7948   // We have a superclass method. Now, form the send-to-super completion.
7949   CodeCompletionBuilder Builder(Results.getAllocator(),
7950                                 Results.getCodeCompletionTUInfo());
7951 
7952   // Give this completion a return type.
7953   AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
7954                      Results.getCompletionContext().getBaseType(), Builder);
7955 
7956   // If we need the "super" keyword, add it (plus some spacing).
7957   if (NeedSuperKeyword) {
7958     Builder.AddTypedTextChunk("super");
7959     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7960   }
7961 
7962   Selector Sel = CurMethod->getSelector();
7963   if (Sel.isUnarySelector()) {
7964     if (NeedSuperKeyword)
7965       Builder.AddTextChunk(
7966           Builder.getAllocator().CopyString(Sel.getNameForSlot(0)));
7967     else
7968       Builder.AddTypedTextChunk(
7969           Builder.getAllocator().CopyString(Sel.getNameForSlot(0)));
7970   } else {
7971     ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
7972     for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
7973       if (I > SelIdents.size())
7974         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7975 
7976       if (I < SelIdents.size())
7977         Builder.AddInformativeChunk(
7978             Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
7979       else if (NeedSuperKeyword || I > SelIdents.size()) {
7980         Builder.AddTextChunk(
7981             Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
7982         Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
7983             (*CurP)->getIdentifier()->getName()));
7984       } else {
7985         Builder.AddTypedTextChunk(
7986             Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
7987         Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
7988             (*CurP)->getIdentifier()->getName()));
7989       }
7990     }
7991   }
7992 
7993   Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod,
7994                                          CCP_SuperCompletion));
7995   return SuperMethod;
7996 }
7997 
7998 void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
7999   typedef CodeCompletionResult Result;
8000   ResultBuilder Results(
8001       *this, CodeCompleter->getAllocator(),
8002       CodeCompleter->getCodeCompletionTUInfo(),
8003       CodeCompletionContext::CCC_ObjCMessageReceiver,
8004       getLangOpts().CPlusPlus11
8005           ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture
8006           : &ResultBuilder::IsObjCMessageReceiver);
8007 
8008   CodeCompletionDeclConsumer Consumer(Results, CurContext);
8009   Results.EnterNewScope();
8010   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
8011                      CodeCompleter->includeGlobals(),
8012                      CodeCompleter->loadExternal());
8013 
8014   // If we are in an Objective-C method inside a class that has a superclass,
8015   // add "super" as an option.
8016   if (ObjCMethodDecl *Method = getCurMethodDecl())
8017     if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
8018       if (Iface->getSuperClass()) {
8019         Results.AddResult(Result("super"));
8020 
8021         AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, std::nullopt,
8022                                Results);
8023       }
8024 
8025   if (getLangOpts().CPlusPlus11)
8026     addThisCompletion(*this, Results);
8027 
8028   Results.ExitScope();
8029 
8030   if (CodeCompleter->includeMacros())
8031     AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
8032   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8033                             Results.data(), Results.size());
8034 }
8035 
8036 void Sema::CodeCompleteObjCSuperMessage(
8037     Scope *S, SourceLocation SuperLoc,
8038     ArrayRef<const IdentifierInfo *> SelIdents, bool AtArgumentExpression) {
8039   ObjCInterfaceDecl *CDecl = nullptr;
8040   if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
8041     // Figure out which interface we're in.
8042     CDecl = CurMethod->getClassInterface();
8043     if (!CDecl)
8044       return;
8045 
8046     // Find the superclass of this class.
8047     CDecl = CDecl->getSuperClass();
8048     if (!CDecl)
8049       return;
8050 
8051     if (CurMethod->isInstanceMethod()) {
8052       // We are inside an instance method, which means that the message
8053       // send [super ...] is actually calling an instance method on the
8054       // current object.
8055       return CodeCompleteObjCInstanceMessage(S, nullptr, SelIdents,
8056                                              AtArgumentExpression, CDecl);
8057     }
8058 
8059     // Fall through to send to the superclass in CDecl.
8060   } else {
8061     // "super" may be the name of a type or variable. Figure out which
8062     // it is.
8063     const IdentifierInfo *Super = getSuperIdentifier();
8064     NamedDecl *ND = LookupSingleName(S, Super, SuperLoc, LookupOrdinaryName);
8065     if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
8066       // "super" names an interface. Use it.
8067     } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
8068       if (const ObjCObjectType *Iface =
8069               Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
8070         CDecl = Iface->getInterface();
8071     } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
8072       // "super" names an unresolved type; we can't be more specific.
8073     } else {
8074       // Assume that "super" names some kind of value and parse that way.
8075       CXXScopeSpec SS;
8076       SourceLocation TemplateKWLoc;
8077       UnqualifiedId id;
8078       id.setIdentifier(Super, SuperLoc);
8079       ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id,
8080                                                /*HasTrailingLParen=*/false,
8081                                                /*IsAddressOfOperand=*/false);
8082       return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
8083                                              SelIdents, AtArgumentExpression);
8084     }
8085 
8086     // Fall through
8087   }
8088 
8089   ParsedType Receiver;
8090   if (CDecl)
8091     Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
8092   return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
8093                                       AtArgumentExpression,
8094                                       /*IsSuper=*/true);
8095 }
8096 
8097 /// Given a set of code-completion results for the argument of a message
8098 /// send, determine the preferred type (if any) for that argument expression.
8099 static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
8100                                                        unsigned NumSelIdents) {
8101   typedef CodeCompletionResult Result;
8102   ASTContext &Context = Results.getSema().Context;
8103 
8104   QualType PreferredType;
8105   unsigned BestPriority = CCP_Unlikely * 2;
8106   Result *ResultsData = Results.data();
8107   for (unsigned I = 0, N = Results.size(); I != N; ++I) {
8108     Result &R = ResultsData[I];
8109     if (R.Kind == Result::RK_Declaration &&
8110         isa<ObjCMethodDecl>(R.Declaration)) {
8111       if (R.Priority <= BestPriority) {
8112         const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
8113         if (NumSelIdents <= Method->param_size()) {
8114           QualType MyPreferredType =
8115               Method->parameters()[NumSelIdents - 1]->getType();
8116           if (R.Priority < BestPriority || PreferredType.isNull()) {
8117             BestPriority = R.Priority;
8118             PreferredType = MyPreferredType;
8119           } else if (!Context.hasSameUnqualifiedType(PreferredType,
8120                                                      MyPreferredType)) {
8121             PreferredType = QualType();
8122           }
8123         }
8124       }
8125     }
8126   }
8127 
8128   return PreferredType;
8129 }
8130 
8131 static void
8132 AddClassMessageCompletions(Sema &SemaRef, Scope *S, ParsedType Receiver,
8133                            ArrayRef<const IdentifierInfo *> SelIdents,
8134                            bool AtArgumentExpression, bool IsSuper,
8135                            ResultBuilder &Results) {
8136   typedef CodeCompletionResult Result;
8137   ObjCInterfaceDecl *CDecl = nullptr;
8138 
8139   // If the given name refers to an interface type, retrieve the
8140   // corresponding declaration.
8141   if (Receiver) {
8142     QualType T = SemaRef.GetTypeFromParser(Receiver, nullptr);
8143     if (!T.isNull())
8144       if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
8145         CDecl = Interface->getInterface();
8146   }
8147 
8148   // Add all of the factory methods in this Objective-C class, its protocols,
8149   // superclasses, categories, implementation, etc.
8150   Results.EnterNewScope();
8151 
8152   // If this is a send-to-super, try to add the special "super" send
8153   // completion.
8154   if (IsSuper) {
8155     if (ObjCMethodDecl *SuperMethod =
8156             AddSuperSendCompletion(SemaRef, false, SelIdents, Results))
8157       Results.Ignore(SuperMethod);
8158   }
8159 
8160   // If we're inside an Objective-C method definition, prefer its selector to
8161   // others.
8162   if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
8163     Results.setPreferredSelector(CurMethod->getSelector());
8164 
8165   VisitedSelectorSet Selectors;
8166   if (CDecl)
8167     AddObjCMethods(CDecl, false, MK_Any, SelIdents, SemaRef.CurContext,
8168                    Selectors, AtArgumentExpression, Results);
8169   else {
8170     // We're messaging "id" as a type; provide all class/factory methods.
8171 
8172     // If we have an external source, load the entire class method
8173     // pool from the AST file.
8174     if (SemaRef.getExternalSource()) {
8175       for (uint32_t I = 0,
8176                     N = SemaRef.getExternalSource()->GetNumExternalSelectors();
8177            I != N; ++I) {
8178         Selector Sel = SemaRef.getExternalSource()->GetExternalSelector(I);
8179         if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
8180           continue;
8181 
8182         SemaRef.ReadMethodPool(Sel);
8183       }
8184     }
8185 
8186     for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
8187                                           MEnd = SemaRef.MethodPool.end();
8188          M != MEnd; ++M) {
8189       for (ObjCMethodList *MethList = &M->second.second;
8190            MethList && MethList->getMethod(); MethList = MethList->getNext()) {
8191         if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
8192           continue;
8193 
8194         Result R(MethList->getMethod(),
8195                  Results.getBasePriority(MethList->getMethod()), nullptr);
8196         R.StartParameter = SelIdents.size();
8197         R.AllParametersAreInformative = false;
8198         Results.MaybeAddResult(R, SemaRef.CurContext);
8199       }
8200     }
8201   }
8202 
8203   Results.ExitScope();
8204 }
8205 
8206 void Sema::CodeCompleteObjCClassMessage(
8207     Scope *S, ParsedType Receiver, ArrayRef<const IdentifierInfo *> SelIdents,
8208     bool AtArgumentExpression, bool IsSuper) {
8209 
8210   QualType T = this->GetTypeFromParser(Receiver);
8211 
8212   ResultBuilder Results(
8213       *this, CodeCompleter->getAllocator(),
8214       CodeCompleter->getCodeCompletionTUInfo(),
8215       CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage, T,
8216                             SelIdents));
8217 
8218   AddClassMessageCompletions(*this, S, Receiver, SelIdents,
8219                              AtArgumentExpression, IsSuper, Results);
8220 
8221   // If we're actually at the argument expression (rather than prior to the
8222   // selector), we're actually performing code completion for an expression.
8223   // Determine whether we have a single, best method. If so, we can
8224   // code-complete the expression using the corresponding parameter type as
8225   // our preferred type, improving completion results.
8226   if (AtArgumentExpression) {
8227     QualType PreferredType =
8228         getPreferredArgumentTypeForMessageSend(Results, SelIdents.size());
8229     if (PreferredType.isNull())
8230       CodeCompleteOrdinaryName(S, PCC_Expression);
8231     else
8232       CodeCompleteExpression(S, PreferredType);
8233     return;
8234   }
8235 
8236   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8237                             Results.data(), Results.size());
8238 }
8239 
8240 void Sema::CodeCompleteObjCInstanceMessage(
8241     Scope *S, Expr *Receiver, ArrayRef<const IdentifierInfo *> SelIdents,
8242     bool AtArgumentExpression, ObjCInterfaceDecl *Super) {
8243   typedef CodeCompletionResult Result;
8244 
8245   Expr *RecExpr = static_cast<Expr *>(Receiver);
8246 
8247   // If necessary, apply function/array conversion to the receiver.
8248   // C99 6.7.5.3p[7,8].
8249   if (RecExpr) {
8250     ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
8251     if (Conv.isInvalid()) // conversion failed. bail.
8252       return;
8253     RecExpr = Conv.get();
8254   }
8255   QualType ReceiverType = RecExpr
8256                               ? RecExpr->getType()
8257                               : Super ? Context.getObjCObjectPointerType(
8258                                             Context.getObjCInterfaceType(Super))
8259                                       : Context.getObjCIdType();
8260 
8261   // If we're messaging an expression with type "id" or "Class", check
8262   // whether we know something special about the receiver that allows
8263   // us to assume a more-specific receiver type.
8264   if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) {
8265     if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
8266       if (ReceiverType->isObjCClassType())
8267         return CodeCompleteObjCClassMessage(
8268             S, ParsedType::make(Context.getObjCInterfaceType(IFace)), SelIdents,
8269             AtArgumentExpression, Super);
8270 
8271       ReceiverType =
8272           Context.getObjCObjectPointerType(Context.getObjCInterfaceType(IFace));
8273     }
8274   } else if (RecExpr && getLangOpts().CPlusPlus) {
8275     ExprResult Conv = PerformContextuallyConvertToObjCPointer(RecExpr);
8276     if (Conv.isUsable()) {
8277       RecExpr = Conv.get();
8278       ReceiverType = RecExpr->getType();
8279     }
8280   }
8281 
8282   // Build the set of methods we can see.
8283   ResultBuilder Results(
8284       *this, CodeCompleter->getAllocator(),
8285       CodeCompleter->getCodeCompletionTUInfo(),
8286       CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
8287                             ReceiverType, SelIdents));
8288 
8289   Results.EnterNewScope();
8290 
8291   // If this is a send-to-super, try to add the special "super" send
8292   // completion.
8293   if (Super) {
8294     if (ObjCMethodDecl *SuperMethod =
8295             AddSuperSendCompletion(*this, false, SelIdents, Results))
8296       Results.Ignore(SuperMethod);
8297   }
8298 
8299   // If we're inside an Objective-C method definition, prefer its selector to
8300   // others.
8301   if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
8302     Results.setPreferredSelector(CurMethod->getSelector());
8303 
8304   // Keep track of the selectors we've already added.
8305   VisitedSelectorSet Selectors;
8306 
8307   // Handle messages to Class. This really isn't a message to an instance
8308   // method, so we treat it the same way we would treat a message send to a
8309   // class method.
8310   if (ReceiverType->isObjCClassType() ||
8311       ReceiverType->isObjCQualifiedClassType()) {
8312     if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
8313       if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
8314         AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, CurContext,
8315                        Selectors, AtArgumentExpression, Results);
8316     }
8317   }
8318   // Handle messages to a qualified ID ("id<foo>").
8319   else if (const ObjCObjectPointerType *QualID =
8320                ReceiverType->getAsObjCQualifiedIdType()) {
8321     // Search protocols for instance methods.
8322     for (auto *I : QualID->quals())
8323       AddObjCMethods(I, true, MK_Any, SelIdents, CurContext, Selectors,
8324                      AtArgumentExpression, Results);
8325   }
8326   // Handle messages to a pointer to interface type.
8327   else if (const ObjCObjectPointerType *IFacePtr =
8328                ReceiverType->getAsObjCInterfacePointerType()) {
8329     // Search the class, its superclasses, etc., for instance methods.
8330     AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
8331                    CurContext, Selectors, AtArgumentExpression, Results);
8332 
8333     // Search protocols for instance methods.
8334     for (auto *I : IFacePtr->quals())
8335       AddObjCMethods(I, true, MK_Any, SelIdents, CurContext, Selectors,
8336                      AtArgumentExpression, Results);
8337   }
8338   // Handle messages to "id".
8339   else if (ReceiverType->isObjCIdType()) {
8340     // We're messaging "id", so provide all instance methods we know
8341     // about as code-completion results.
8342 
8343     // If we have an external source, load the entire class method
8344     // pool from the AST file.
8345     if (ExternalSource) {
8346       for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
8347            I != N; ++I) {
8348         Selector Sel = ExternalSource->GetExternalSelector(I);
8349         if (Sel.isNull() || MethodPool.count(Sel))
8350           continue;
8351 
8352         ReadMethodPool(Sel);
8353       }
8354     }
8355 
8356     for (GlobalMethodPool::iterator M = MethodPool.begin(),
8357                                     MEnd = MethodPool.end();
8358          M != MEnd; ++M) {
8359       for (ObjCMethodList *MethList = &M->second.first;
8360            MethList && MethList->getMethod(); MethList = MethList->getNext()) {
8361         if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
8362           continue;
8363 
8364         if (!Selectors.insert(MethList->getMethod()->getSelector()).second)
8365           continue;
8366 
8367         Result R(MethList->getMethod(),
8368                  Results.getBasePriority(MethList->getMethod()), nullptr);
8369         R.StartParameter = SelIdents.size();
8370         R.AllParametersAreInformative = false;
8371         Results.MaybeAddResult(R, CurContext);
8372       }
8373     }
8374   }
8375   Results.ExitScope();
8376 
8377   // If we're actually at the argument expression (rather than prior to the
8378   // selector), we're actually performing code completion for an expression.
8379   // Determine whether we have a single, best method. If so, we can
8380   // code-complete the expression using the corresponding parameter type as
8381   // our preferred type, improving completion results.
8382   if (AtArgumentExpression) {
8383     QualType PreferredType =
8384         getPreferredArgumentTypeForMessageSend(Results, SelIdents.size());
8385     if (PreferredType.isNull())
8386       CodeCompleteOrdinaryName(S, PCC_Expression);
8387     else
8388       CodeCompleteExpression(S, PreferredType);
8389     return;
8390   }
8391 
8392   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8393                             Results.data(), Results.size());
8394 }
8395 
8396 void Sema::CodeCompleteObjCForCollection(Scope *S,
8397                                          DeclGroupPtrTy IterationVar) {
8398   CodeCompleteExpressionData Data;
8399   Data.ObjCCollection = true;
8400 
8401   if (IterationVar.getAsOpaquePtr()) {
8402     DeclGroupRef DG = IterationVar.get();
8403     for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
8404       if (*I)
8405         Data.IgnoreDecls.push_back(*I);
8406     }
8407   }
8408 
8409   CodeCompleteExpression(S, Data);
8410 }
8411 
8412 void Sema::CodeCompleteObjCSelector(
8413     Scope *S, ArrayRef<const IdentifierInfo *> SelIdents) {
8414   // If we have an external source, load the entire class method
8415   // pool from the AST file.
8416   if (ExternalSource) {
8417     for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); I != N;
8418          ++I) {
8419       Selector Sel = ExternalSource->GetExternalSelector(I);
8420       if (Sel.isNull() || MethodPool.count(Sel))
8421         continue;
8422 
8423       ReadMethodPool(Sel);
8424     }
8425   }
8426 
8427   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8428                         CodeCompleter->getCodeCompletionTUInfo(),
8429                         CodeCompletionContext::CCC_SelectorName);
8430   Results.EnterNewScope();
8431   for (GlobalMethodPool::iterator M = MethodPool.begin(),
8432                                   MEnd = MethodPool.end();
8433        M != MEnd; ++M) {
8434 
8435     Selector Sel = M->first;
8436     if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents))
8437       continue;
8438 
8439     CodeCompletionBuilder Builder(Results.getAllocator(),
8440                                   Results.getCodeCompletionTUInfo());
8441     if (Sel.isUnarySelector()) {
8442       Builder.AddTypedTextChunk(
8443           Builder.getAllocator().CopyString(Sel.getNameForSlot(0)));
8444       Results.AddResult(Builder.TakeString());
8445       continue;
8446     }
8447 
8448     std::string Accumulator;
8449     for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
8450       if (I == SelIdents.size()) {
8451         if (!Accumulator.empty()) {
8452           Builder.AddInformativeChunk(
8453               Builder.getAllocator().CopyString(Accumulator));
8454           Accumulator.clear();
8455         }
8456       }
8457 
8458       Accumulator += Sel.getNameForSlot(I);
8459       Accumulator += ':';
8460     }
8461     Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(Accumulator));
8462     Results.AddResult(Builder.TakeString());
8463   }
8464   Results.ExitScope();
8465 
8466   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8467                             Results.data(), Results.size());
8468 }
8469 
8470 /// Add all of the protocol declarations that we find in the given
8471 /// (translation unit) context.
8472 static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
8473                                bool OnlyForwardDeclarations,
8474                                ResultBuilder &Results) {
8475   typedef CodeCompletionResult Result;
8476 
8477   for (const auto *D : Ctx->decls()) {
8478     // Record any protocols we find.
8479     if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(D))
8480       if (!OnlyForwardDeclarations || !Proto->hasDefinition())
8481         Results.AddResult(
8482             Result(Proto, Results.getBasePriority(Proto), nullptr), CurContext,
8483             nullptr, false);
8484   }
8485 }
8486 
8487 void Sema::CodeCompleteObjCProtocolReferences(
8488     ArrayRef<IdentifierLocPair> Protocols) {
8489   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8490                         CodeCompleter->getCodeCompletionTUInfo(),
8491                         CodeCompletionContext::CCC_ObjCProtocolName);
8492 
8493   if (CodeCompleter->includeGlobals()) {
8494     Results.EnterNewScope();
8495 
8496     // Tell the result set to ignore all of the protocols we have
8497     // already seen.
8498     // FIXME: This doesn't work when caching code-completion results.
8499     for (const IdentifierLocPair &Pair : Protocols)
8500       if (ObjCProtocolDecl *Protocol = LookupProtocol(Pair.first, Pair.second))
8501         Results.Ignore(Protocol);
8502 
8503     // Add all protocols.
8504     AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
8505                        Results);
8506 
8507     Results.ExitScope();
8508   }
8509 
8510   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8511                             Results.data(), Results.size());
8512 }
8513 
8514 void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
8515   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8516                         CodeCompleter->getCodeCompletionTUInfo(),
8517                         CodeCompletionContext::CCC_ObjCProtocolName);
8518 
8519   if (CodeCompleter->includeGlobals()) {
8520     Results.EnterNewScope();
8521 
8522     // Add all protocols.
8523     AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
8524                        Results);
8525 
8526     Results.ExitScope();
8527   }
8528 
8529   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8530                             Results.data(), Results.size());
8531 }
8532 
8533 /// Add all of the Objective-C interface declarations that we find in
8534 /// the given (translation unit) context.
8535 static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
8536                                 bool OnlyForwardDeclarations,
8537                                 bool OnlyUnimplemented,
8538                                 ResultBuilder &Results) {
8539   typedef CodeCompletionResult Result;
8540 
8541   for (const auto *D : Ctx->decls()) {
8542     // Record any interfaces we find.
8543     if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
8544       if ((!OnlyForwardDeclarations || !Class->hasDefinition()) &&
8545           (!OnlyUnimplemented || !Class->getImplementation()))
8546         Results.AddResult(
8547             Result(Class, Results.getBasePriority(Class), nullptr), CurContext,
8548             nullptr, false);
8549   }
8550 }
8551 
8552 void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
8553   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8554                         CodeCompleter->getCodeCompletionTUInfo(),
8555                         CodeCompletionContext::CCC_ObjCInterfaceName);
8556   Results.EnterNewScope();
8557 
8558   if (CodeCompleter->includeGlobals()) {
8559     // Add all classes.
8560     AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
8561                         false, Results);
8562   }
8563 
8564   Results.ExitScope();
8565 
8566   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8567                             Results.data(), Results.size());
8568 }
8569 
8570 void Sema::CodeCompleteObjCClassForwardDecl(Scope *S) {
8571   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8572                         CodeCompleter->getCodeCompletionTUInfo(),
8573                         CodeCompletionContext::CCC_ObjCClassForwardDecl);
8574   Results.EnterNewScope();
8575 
8576   if (CodeCompleter->includeGlobals()) {
8577     // Add all classes.
8578     AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
8579                         false, Results);
8580   }
8581 
8582   Results.ExitScope();
8583 
8584   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8585                             Results.data(), Results.size());
8586 }
8587 
8588 void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
8589                                       SourceLocation ClassNameLoc) {
8590   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8591                         CodeCompleter->getCodeCompletionTUInfo(),
8592                         CodeCompletionContext::CCC_ObjCInterfaceName);
8593   Results.EnterNewScope();
8594 
8595   // Make sure that we ignore the class we're currently defining.
8596   NamedDecl *CurClass =
8597       LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
8598   if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
8599     Results.Ignore(CurClass);
8600 
8601   if (CodeCompleter->includeGlobals()) {
8602     // Add all classes.
8603     AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
8604                         false, Results);
8605   }
8606 
8607   Results.ExitScope();
8608 
8609   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8610                             Results.data(), Results.size());
8611 }
8612 
8613 void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
8614   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8615                         CodeCompleter->getCodeCompletionTUInfo(),
8616                         CodeCompletionContext::CCC_ObjCImplementation);
8617   Results.EnterNewScope();
8618 
8619   if (CodeCompleter->includeGlobals()) {
8620     // Add all unimplemented classes.
8621     AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
8622                         true, Results);
8623   }
8624 
8625   Results.ExitScope();
8626 
8627   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8628                             Results.data(), Results.size());
8629 }
8630 
8631 void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
8632                                              IdentifierInfo *ClassName,
8633                                              SourceLocation ClassNameLoc) {
8634   typedef CodeCompletionResult Result;
8635 
8636   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8637                         CodeCompleter->getCodeCompletionTUInfo(),
8638                         CodeCompletionContext::CCC_ObjCCategoryName);
8639 
8640   // Ignore any categories we find that have already been implemented by this
8641   // interface.
8642   llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
8643   NamedDecl *CurClass =
8644       LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
8645   if (ObjCInterfaceDecl *Class =
8646           dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)) {
8647     for (const auto *Cat : Class->visible_categories())
8648       CategoryNames.insert(Cat->getIdentifier());
8649   }
8650 
8651   // Add all of the categories we know about.
8652   Results.EnterNewScope();
8653   TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
8654   for (const auto *D : TU->decls())
8655     if (const auto *Category = dyn_cast<ObjCCategoryDecl>(D))
8656       if (CategoryNames.insert(Category->getIdentifier()).second)
8657         Results.AddResult(
8658             Result(Category, Results.getBasePriority(Category), nullptr),
8659             CurContext, nullptr, false);
8660   Results.ExitScope();
8661 
8662   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8663                             Results.data(), Results.size());
8664 }
8665 
8666 void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
8667                                                   IdentifierInfo *ClassName,
8668                                                   SourceLocation ClassNameLoc) {
8669   typedef CodeCompletionResult Result;
8670 
8671   // Find the corresponding interface. If we couldn't find the interface, the
8672   // program itself is ill-formed. However, we'll try to be helpful still by
8673   // providing the list of all of the categories we know about.
8674   NamedDecl *CurClass =
8675       LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
8676   ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
8677   if (!Class)
8678     return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
8679 
8680   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8681                         CodeCompleter->getCodeCompletionTUInfo(),
8682                         CodeCompletionContext::CCC_ObjCCategoryName);
8683 
8684   // Add all of the categories that have corresponding interface
8685   // declarations in this class and any of its superclasses, except for
8686   // already-implemented categories in the class itself.
8687   llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
8688   Results.EnterNewScope();
8689   bool IgnoreImplemented = true;
8690   while (Class) {
8691     for (const auto *Cat : Class->visible_categories()) {
8692       if ((!IgnoreImplemented || !Cat->getImplementation()) &&
8693           CategoryNames.insert(Cat->getIdentifier()).second)
8694         Results.AddResult(Result(Cat, Results.getBasePriority(Cat), nullptr),
8695                           CurContext, nullptr, false);
8696     }
8697 
8698     Class = Class->getSuperClass();
8699     IgnoreImplemented = false;
8700   }
8701   Results.ExitScope();
8702 
8703   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8704                             Results.data(), Results.size());
8705 }
8706 
8707 void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
8708   CodeCompletionContext CCContext(CodeCompletionContext::CCC_Other);
8709   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8710                         CodeCompleter->getCodeCompletionTUInfo(), CCContext);
8711 
8712   // Figure out where this @synthesize lives.
8713   ObjCContainerDecl *Container =
8714       dyn_cast_or_null<ObjCContainerDecl>(CurContext);
8715   if (!Container || (!isa<ObjCImplementationDecl>(Container) &&
8716                      !isa<ObjCCategoryImplDecl>(Container)))
8717     return;
8718 
8719   // Ignore any properties that have already been implemented.
8720   Container = getContainerDef(Container);
8721   for (const auto *D : Container->decls())
8722     if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D))
8723       Results.Ignore(PropertyImpl->getPropertyDecl());
8724 
8725   // Add any properties that we find.
8726   AddedPropertiesSet AddedProperties;
8727   Results.EnterNewScope();
8728   if (ObjCImplementationDecl *ClassImpl =
8729           dyn_cast<ObjCImplementationDecl>(Container))
8730     AddObjCProperties(CCContext, ClassImpl->getClassInterface(), false,
8731                       /*AllowNullaryMethods=*/false, CurContext,
8732                       AddedProperties, Results);
8733   else
8734     AddObjCProperties(CCContext,
8735                       cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
8736                       false, /*AllowNullaryMethods=*/false, CurContext,
8737                       AddedProperties, Results);
8738   Results.ExitScope();
8739 
8740   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8741                             Results.data(), Results.size());
8742 }
8743 
8744 void Sema::CodeCompleteObjCPropertySynthesizeIvar(
8745     Scope *S, IdentifierInfo *PropertyName) {
8746   typedef CodeCompletionResult Result;
8747   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8748                         CodeCompleter->getCodeCompletionTUInfo(),
8749                         CodeCompletionContext::CCC_Other);
8750 
8751   // Figure out where this @synthesize lives.
8752   ObjCContainerDecl *Container =
8753       dyn_cast_or_null<ObjCContainerDecl>(CurContext);
8754   if (!Container || (!isa<ObjCImplementationDecl>(Container) &&
8755                      !isa<ObjCCategoryImplDecl>(Container)))
8756     return;
8757 
8758   // Figure out which interface we're looking into.
8759   ObjCInterfaceDecl *Class = nullptr;
8760   if (ObjCImplementationDecl *ClassImpl =
8761           dyn_cast<ObjCImplementationDecl>(Container))
8762     Class = ClassImpl->getClassInterface();
8763   else
8764     Class = cast<ObjCCategoryImplDecl>(Container)
8765                 ->getCategoryDecl()
8766                 ->getClassInterface();
8767 
8768   // Determine the type of the property we're synthesizing.
8769   QualType PropertyType = Context.getObjCIdType();
8770   if (Class) {
8771     if (ObjCPropertyDecl *Property = Class->FindPropertyDeclaration(
8772             PropertyName, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
8773       PropertyType =
8774           Property->getType().getNonReferenceType().getUnqualifiedType();
8775 
8776       // Give preference to ivars
8777       Results.setPreferredType(PropertyType);
8778     }
8779   }
8780 
8781   // Add all of the instance variables in this class and its superclasses.
8782   Results.EnterNewScope();
8783   bool SawSimilarlyNamedIvar = false;
8784   std::string NameWithPrefix;
8785   NameWithPrefix += '_';
8786   NameWithPrefix += PropertyName->getName();
8787   std::string NameWithSuffix = PropertyName->getName().str();
8788   NameWithSuffix += '_';
8789   for (; Class; Class = Class->getSuperClass()) {
8790     for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
8791          Ivar = Ivar->getNextIvar()) {
8792       Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), nullptr),
8793                         CurContext, nullptr, false);
8794 
8795       // Determine whether we've seen an ivar with a name similar to the
8796       // property.
8797       if ((PropertyName == Ivar->getIdentifier() ||
8798            NameWithPrefix == Ivar->getName() ||
8799            NameWithSuffix == Ivar->getName())) {
8800         SawSimilarlyNamedIvar = true;
8801 
8802         // Reduce the priority of this result by one, to give it a slight
8803         // advantage over other results whose names don't match so closely.
8804         if (Results.size() &&
8805             Results.data()[Results.size() - 1].Kind ==
8806                 CodeCompletionResult::RK_Declaration &&
8807             Results.data()[Results.size() - 1].Declaration == Ivar)
8808           Results.data()[Results.size() - 1].Priority--;
8809       }
8810     }
8811   }
8812 
8813   if (!SawSimilarlyNamedIvar) {
8814     // Create ivar result _propName, that the user can use to synthesize
8815     // an ivar of the appropriate type.
8816     unsigned Priority = CCP_MemberDeclaration + 1;
8817     typedef CodeCompletionResult Result;
8818     CodeCompletionAllocator &Allocator = Results.getAllocator();
8819     CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(),
8820                                   Priority, CXAvailability_Available);
8821 
8822     PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
8823     Builder.AddResultTypeChunk(
8824         GetCompletionTypeString(PropertyType, Context, Policy, Allocator));
8825     Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
8826     Results.AddResult(
8827         Result(Builder.TakeString(), Priority, CXCursor_ObjCIvarDecl));
8828   }
8829 
8830   Results.ExitScope();
8831 
8832   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8833                             Results.data(), Results.size());
8834 }
8835 
8836 // Mapping from selectors to the methods that implement that selector, along
8837 // with the "in original class" flag.
8838 typedef llvm::DenseMap<Selector,
8839                        llvm::PointerIntPair<ObjCMethodDecl *, 1, bool>>
8840     KnownMethodsMap;
8841 
8842 /// Find all of the methods that reside in the given container
8843 /// (and its superclasses, protocols, etc.) that meet the given
8844 /// criteria. Insert those methods into the map of known methods,
8845 /// indexed by selector so they can be easily found.
8846 static void FindImplementableMethods(ASTContext &Context,
8847                                      ObjCContainerDecl *Container,
8848                                      std::optional<bool> WantInstanceMethods,
8849                                      QualType ReturnType,
8850                                      KnownMethodsMap &KnownMethods,
8851                                      bool InOriginalClass = true) {
8852   if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
8853     // Make sure we have a definition; that's what we'll walk.
8854     if (!IFace->hasDefinition())
8855       return;
8856 
8857     IFace = IFace->getDefinition();
8858     Container = IFace;
8859 
8860     const ObjCList<ObjCProtocolDecl> &Protocols =
8861         IFace->getReferencedProtocols();
8862     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
8863                                               E = Protocols.end();
8864          I != E; ++I)
8865       FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
8866                                KnownMethods, InOriginalClass);
8867 
8868     // Add methods from any class extensions and categories.
8869     for (auto *Cat : IFace->visible_categories()) {
8870       FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType,
8871                                KnownMethods, false);
8872     }
8873 
8874     // Visit the superclass.
8875     if (IFace->getSuperClass())
8876       FindImplementableMethods(Context, IFace->getSuperClass(),
8877                                WantInstanceMethods, ReturnType, KnownMethods,
8878                                false);
8879   }
8880 
8881   if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
8882     // Recurse into protocols.
8883     const ObjCList<ObjCProtocolDecl> &Protocols =
8884         Category->getReferencedProtocols();
8885     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
8886                                               E = Protocols.end();
8887          I != E; ++I)
8888       FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
8889                                KnownMethods, InOriginalClass);
8890 
8891     // If this category is the original class, jump to the interface.
8892     if (InOriginalClass && Category->getClassInterface())
8893       FindImplementableMethods(Context, Category->getClassInterface(),
8894                                WantInstanceMethods, ReturnType, KnownMethods,
8895                                false);
8896   }
8897 
8898   if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
8899     // Make sure we have a definition; that's what we'll walk.
8900     if (!Protocol->hasDefinition())
8901       return;
8902     Protocol = Protocol->getDefinition();
8903     Container = Protocol;
8904 
8905     // Recurse into protocols.
8906     const ObjCList<ObjCProtocolDecl> &Protocols =
8907         Protocol->getReferencedProtocols();
8908     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
8909                                               E = Protocols.end();
8910          I != E; ++I)
8911       FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
8912                                KnownMethods, false);
8913   }
8914 
8915   // Add methods in this container. This operation occurs last because
8916   // we want the methods from this container to override any methods
8917   // we've previously seen with the same selector.
8918   for (auto *M : Container->methods()) {
8919     if (!WantInstanceMethods || M->isInstanceMethod() == *WantInstanceMethods) {
8920       if (!ReturnType.isNull() &&
8921           !Context.hasSameUnqualifiedType(ReturnType, M->getReturnType()))
8922         continue;
8923 
8924       KnownMethods[M->getSelector()] =
8925           KnownMethodsMap::mapped_type(M, InOriginalClass);
8926     }
8927   }
8928 }
8929 
8930 /// Add the parenthesized return or parameter type chunk to a code
8931 /// completion string.
8932 static void AddObjCPassingTypeChunk(QualType Type, unsigned ObjCDeclQuals,
8933                                     ASTContext &Context,
8934                                     const PrintingPolicy &Policy,
8935                                     CodeCompletionBuilder &Builder) {
8936   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
8937   std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals, Type);
8938   if (!Quals.empty())
8939     Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals));
8940   Builder.AddTextChunk(
8941       GetCompletionTypeString(Type, Context, Policy, Builder.getAllocator()));
8942   Builder.AddChunk(CodeCompletionString::CK_RightParen);
8943 }
8944 
8945 /// Determine whether the given class is or inherits from a class by
8946 /// the given name.
8947 static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class, StringRef Name) {
8948   if (!Class)
8949     return false;
8950 
8951   if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
8952     return true;
8953 
8954   return InheritsFromClassNamed(Class->getSuperClass(), Name);
8955 }
8956 
8957 /// Add code completions for Objective-C Key-Value Coding (KVC) and
8958 /// Key-Value Observing (KVO).
8959 static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
8960                                        bool IsInstanceMethod,
8961                                        QualType ReturnType, ASTContext &Context,
8962                                        VisitedSelectorSet &KnownSelectors,
8963                                        ResultBuilder &Results) {
8964   IdentifierInfo *PropName = Property->getIdentifier();
8965   if (!PropName || PropName->getLength() == 0)
8966     return;
8967 
8968   PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
8969 
8970   // Builder that will create each code completion.
8971   typedef CodeCompletionResult Result;
8972   CodeCompletionAllocator &Allocator = Results.getAllocator();
8973   CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
8974 
8975   // The selector table.
8976   SelectorTable &Selectors = Context.Selectors;
8977 
8978   // The property name, copied into the code completion allocation region
8979   // on demand.
8980   struct KeyHolder {
8981     CodeCompletionAllocator &Allocator;
8982     StringRef Key;
8983     const char *CopiedKey;
8984 
8985     KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
8986         : Allocator(Allocator), Key(Key), CopiedKey(nullptr) {}
8987 
8988     operator const char *() {
8989       if (CopiedKey)
8990         return CopiedKey;
8991 
8992       return CopiedKey = Allocator.CopyString(Key);
8993     }
8994   } Key(Allocator, PropName->getName());
8995 
8996   // The uppercased name of the property name.
8997   std::string UpperKey = std::string(PropName->getName());
8998   if (!UpperKey.empty())
8999     UpperKey[0] = toUppercase(UpperKey[0]);
9000 
9001   bool ReturnTypeMatchesProperty =
9002       ReturnType.isNull() ||
9003       Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
9004                                      Property->getType());
9005   bool ReturnTypeMatchesVoid = ReturnType.isNull() || ReturnType->isVoidType();
9006 
9007   // Add the normal accessor -(type)key.
9008   if (IsInstanceMethod &&
9009       KnownSelectors.insert(Selectors.getNullarySelector(PropName)).second &&
9010       ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
9011     if (ReturnType.isNull())
9012       AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, Context, Policy,
9013                               Builder);
9014 
9015     Builder.AddTypedTextChunk(Key);
9016     Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
9017                              CXCursor_ObjCInstanceMethodDecl));
9018   }
9019 
9020   // If we have an integral or boolean property (or the user has provided
9021   // an integral or boolean return type), add the accessor -(type)isKey.
9022   if (IsInstanceMethod &&
9023       ((!ReturnType.isNull() &&
9024         (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
9025        (ReturnType.isNull() && (Property->getType()->isIntegerType() ||
9026                                 Property->getType()->isBooleanType())))) {
9027     std::string SelectorName = (Twine("is") + UpperKey).str();
9028     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9029     if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
9030             .second) {
9031       if (ReturnType.isNull()) {
9032         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9033         Builder.AddTextChunk("BOOL");
9034         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9035       }
9036 
9037       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorId->getName()));
9038       Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
9039                                CXCursor_ObjCInstanceMethodDecl));
9040     }
9041   }
9042 
9043   // Add the normal mutator.
9044   if (IsInstanceMethod && ReturnTypeMatchesVoid &&
9045       !Property->getSetterMethodDecl()) {
9046     std::string SelectorName = (Twine("set") + UpperKey).str();
9047     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9048     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9049       if (ReturnType.isNull()) {
9050         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9051         Builder.AddTextChunk("void");
9052         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9053       }
9054 
9055       Builder.AddTypedTextChunk(
9056           Allocator.CopyString(SelectorId->getName() + ":"));
9057       AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, Context, Policy,
9058                               Builder);
9059       Builder.AddTextChunk(Key);
9060       Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
9061                                CXCursor_ObjCInstanceMethodDecl));
9062     }
9063   }
9064 
9065   // Indexed and unordered accessors
9066   unsigned IndexedGetterPriority = CCP_CodePattern;
9067   unsigned IndexedSetterPriority = CCP_CodePattern;
9068   unsigned UnorderedGetterPriority = CCP_CodePattern;
9069   unsigned UnorderedSetterPriority = CCP_CodePattern;
9070   if (const auto *ObjCPointer =
9071           Property->getType()->getAs<ObjCObjectPointerType>()) {
9072     if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
9073       // If this interface type is not provably derived from a known
9074       // collection, penalize the corresponding completions.
9075       if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
9076         IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
9077         if (!InheritsFromClassNamed(IFace, "NSArray"))
9078           IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
9079       }
9080 
9081       if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
9082         UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
9083         if (!InheritsFromClassNamed(IFace, "NSSet"))
9084           UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
9085       }
9086     }
9087   } else {
9088     IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
9089     IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
9090     UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
9091     UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
9092   }
9093 
9094   // Add -(NSUInteger)countOf<key>
9095   if (IsInstanceMethod &&
9096       (ReturnType.isNull() || ReturnType->isIntegerType())) {
9097     std::string SelectorName = (Twine("countOf") + UpperKey).str();
9098     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9099     if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
9100             .second) {
9101       if (ReturnType.isNull()) {
9102         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9103         Builder.AddTextChunk("NSUInteger");
9104         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9105       }
9106 
9107       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorId->getName()));
9108       Results.AddResult(
9109           Result(Builder.TakeString(),
9110                  std::min(IndexedGetterPriority, UnorderedGetterPriority),
9111                  CXCursor_ObjCInstanceMethodDecl));
9112     }
9113   }
9114 
9115   // Indexed getters
9116   // Add -(id)objectInKeyAtIndex:(NSUInteger)index
9117   if (IsInstanceMethod &&
9118       (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
9119     std::string SelectorName = (Twine("objectIn") + UpperKey + "AtIndex").str();
9120     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9121     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9122       if (ReturnType.isNull()) {
9123         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9124         Builder.AddTextChunk("id");
9125         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9126       }
9127 
9128       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9129       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9130       Builder.AddTextChunk("NSUInteger");
9131       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9132       Builder.AddTextChunk("index");
9133       Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
9134                                CXCursor_ObjCInstanceMethodDecl));
9135     }
9136   }
9137 
9138   // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
9139   if (IsInstanceMethod &&
9140       (ReturnType.isNull() ||
9141        (ReturnType->isObjCObjectPointerType() &&
9142         ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
9143         ReturnType->castAs<ObjCObjectPointerType>()
9144                 ->getInterfaceDecl()
9145                 ->getName() == "NSArray"))) {
9146     std::string SelectorName = (Twine(Property->getName()) + "AtIndexes").str();
9147     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9148     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9149       if (ReturnType.isNull()) {
9150         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9151         Builder.AddTextChunk("NSArray *");
9152         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9153       }
9154 
9155       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9156       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9157       Builder.AddTextChunk("NSIndexSet *");
9158       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9159       Builder.AddTextChunk("indexes");
9160       Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
9161                                CXCursor_ObjCInstanceMethodDecl));
9162     }
9163   }
9164 
9165   // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
9166   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9167     std::string SelectorName = (Twine("get") + UpperKey).str();
9168     const IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName),
9169                                             &Context.Idents.get("range")};
9170 
9171     if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
9172       if (ReturnType.isNull()) {
9173         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9174         Builder.AddTextChunk("void");
9175         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9176       }
9177 
9178       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9179       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9180       Builder.AddPlaceholderChunk("object-type");
9181       Builder.AddTextChunk(" **");
9182       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9183       Builder.AddTextChunk("buffer");
9184       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9185       Builder.AddTypedTextChunk("range:");
9186       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9187       Builder.AddTextChunk("NSRange");
9188       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9189       Builder.AddTextChunk("inRange");
9190       Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
9191                                CXCursor_ObjCInstanceMethodDecl));
9192     }
9193   }
9194 
9195   // Mutable indexed accessors
9196 
9197   // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
9198   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9199     std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
9200     const IdentifierInfo *SelectorIds[2] = {&Context.Idents.get("insertObject"),
9201                                             &Context.Idents.get(SelectorName)};
9202 
9203     if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
9204       if (ReturnType.isNull()) {
9205         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9206         Builder.AddTextChunk("void");
9207         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9208       }
9209 
9210       Builder.AddTypedTextChunk("insertObject:");
9211       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9212       Builder.AddPlaceholderChunk("object-type");
9213       Builder.AddTextChunk(" *");
9214       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9215       Builder.AddTextChunk("object");
9216       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9217       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9218       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9219       Builder.AddPlaceholderChunk("NSUInteger");
9220       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9221       Builder.AddTextChunk("index");
9222       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
9223                                CXCursor_ObjCInstanceMethodDecl));
9224     }
9225   }
9226 
9227   // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
9228   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9229     std::string SelectorName = (Twine("insert") + UpperKey).str();
9230     const IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName),
9231                                             &Context.Idents.get("atIndexes")};
9232 
9233     if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
9234       if (ReturnType.isNull()) {
9235         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9236         Builder.AddTextChunk("void");
9237         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9238       }
9239 
9240       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9241       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9242       Builder.AddTextChunk("NSArray *");
9243       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9244       Builder.AddTextChunk("array");
9245       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9246       Builder.AddTypedTextChunk("atIndexes:");
9247       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9248       Builder.AddPlaceholderChunk("NSIndexSet *");
9249       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9250       Builder.AddTextChunk("indexes");
9251       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
9252                                CXCursor_ObjCInstanceMethodDecl));
9253     }
9254   }
9255 
9256   // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
9257   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9258     std::string SelectorName =
9259         (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
9260     const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9261     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9262       if (ReturnType.isNull()) {
9263         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9264         Builder.AddTextChunk("void");
9265         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9266       }
9267 
9268       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9269       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9270       Builder.AddTextChunk("NSUInteger");
9271       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9272       Builder.AddTextChunk("index");
9273       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
9274                                CXCursor_ObjCInstanceMethodDecl));
9275     }
9276   }
9277 
9278   // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
9279   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9280     std::string SelectorName = (Twine("remove") + UpperKey + "AtIndexes").str();
9281     const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9282     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9283       if (ReturnType.isNull()) {
9284         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9285         Builder.AddTextChunk("void");
9286         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9287       }
9288 
9289       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9290       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9291       Builder.AddTextChunk("NSIndexSet *");
9292       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9293       Builder.AddTextChunk("indexes");
9294       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
9295                                CXCursor_ObjCInstanceMethodDecl));
9296     }
9297   }
9298 
9299   // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
9300   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9301     std::string SelectorName =
9302         (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
9303     const IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName),
9304                                             &Context.Idents.get("withObject")};
9305 
9306     if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
9307       if (ReturnType.isNull()) {
9308         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9309         Builder.AddTextChunk("void");
9310         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9311       }
9312 
9313       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9314       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9315       Builder.AddPlaceholderChunk("NSUInteger");
9316       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9317       Builder.AddTextChunk("index");
9318       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9319       Builder.AddTypedTextChunk("withObject:");
9320       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9321       Builder.AddTextChunk("id");
9322       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9323       Builder.AddTextChunk("object");
9324       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
9325                                CXCursor_ObjCInstanceMethodDecl));
9326     }
9327   }
9328 
9329   // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
9330   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9331     std::string SelectorName1 =
9332         (Twine("replace") + UpperKey + "AtIndexes").str();
9333     std::string SelectorName2 = (Twine("with") + UpperKey).str();
9334     const IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName1),
9335                                             &Context.Idents.get(SelectorName2)};
9336 
9337     if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
9338       if (ReturnType.isNull()) {
9339         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9340         Builder.AddTextChunk("void");
9341         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9342       }
9343 
9344       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
9345       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9346       Builder.AddPlaceholderChunk("NSIndexSet *");
9347       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9348       Builder.AddTextChunk("indexes");
9349       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9350       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
9351       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9352       Builder.AddTextChunk("NSArray *");
9353       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9354       Builder.AddTextChunk("array");
9355       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
9356                                CXCursor_ObjCInstanceMethodDecl));
9357     }
9358   }
9359 
9360   // Unordered getters
9361   // - (NSEnumerator *)enumeratorOfKey
9362   if (IsInstanceMethod &&
9363       (ReturnType.isNull() ||
9364        (ReturnType->isObjCObjectPointerType() &&
9365         ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
9366         ReturnType->castAs<ObjCObjectPointerType>()
9367                 ->getInterfaceDecl()
9368                 ->getName() == "NSEnumerator"))) {
9369     std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
9370     const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9371     if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
9372             .second) {
9373       if (ReturnType.isNull()) {
9374         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9375         Builder.AddTextChunk("NSEnumerator *");
9376         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9377       }
9378 
9379       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
9380       Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
9381                                CXCursor_ObjCInstanceMethodDecl));
9382     }
9383   }
9384 
9385   // - (type *)memberOfKey:(type *)object
9386   if (IsInstanceMethod &&
9387       (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
9388     std::string SelectorName = (Twine("memberOf") + UpperKey).str();
9389     const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9390     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9391       if (ReturnType.isNull()) {
9392         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9393         Builder.AddPlaceholderChunk("object-type");
9394         Builder.AddTextChunk(" *");
9395         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9396       }
9397 
9398       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9399       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9400       if (ReturnType.isNull()) {
9401         Builder.AddPlaceholderChunk("object-type");
9402         Builder.AddTextChunk(" *");
9403       } else {
9404         Builder.AddTextChunk(GetCompletionTypeString(
9405             ReturnType, Context, Policy, Builder.getAllocator()));
9406       }
9407       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9408       Builder.AddTextChunk("object");
9409       Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
9410                                CXCursor_ObjCInstanceMethodDecl));
9411     }
9412   }
9413 
9414   // Mutable unordered accessors
9415   // - (void)addKeyObject:(type *)object
9416   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9417     std::string SelectorName =
9418         (Twine("add") + UpperKey + Twine("Object")).str();
9419     const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9420     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9421       if (ReturnType.isNull()) {
9422         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9423         Builder.AddTextChunk("void");
9424         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9425       }
9426 
9427       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9428       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9429       Builder.AddPlaceholderChunk("object-type");
9430       Builder.AddTextChunk(" *");
9431       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9432       Builder.AddTextChunk("object");
9433       Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
9434                                CXCursor_ObjCInstanceMethodDecl));
9435     }
9436   }
9437 
9438   // - (void)addKey:(NSSet *)objects
9439   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9440     std::string SelectorName = (Twine("add") + UpperKey).str();
9441     const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9442     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9443       if (ReturnType.isNull()) {
9444         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9445         Builder.AddTextChunk("void");
9446         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9447       }
9448 
9449       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9450       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9451       Builder.AddTextChunk("NSSet *");
9452       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9453       Builder.AddTextChunk("objects");
9454       Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
9455                                CXCursor_ObjCInstanceMethodDecl));
9456     }
9457   }
9458 
9459   // - (void)removeKeyObject:(type *)object
9460   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9461     std::string SelectorName =
9462         (Twine("remove") + UpperKey + Twine("Object")).str();
9463     const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9464     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9465       if (ReturnType.isNull()) {
9466         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9467         Builder.AddTextChunk("void");
9468         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9469       }
9470 
9471       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9472       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9473       Builder.AddPlaceholderChunk("object-type");
9474       Builder.AddTextChunk(" *");
9475       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9476       Builder.AddTextChunk("object");
9477       Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
9478                                CXCursor_ObjCInstanceMethodDecl));
9479     }
9480   }
9481 
9482   // - (void)removeKey:(NSSet *)objects
9483   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9484     std::string SelectorName = (Twine("remove") + UpperKey).str();
9485     const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9486     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9487       if (ReturnType.isNull()) {
9488         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9489         Builder.AddTextChunk("void");
9490         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9491       }
9492 
9493       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9494       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9495       Builder.AddTextChunk("NSSet *");
9496       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9497       Builder.AddTextChunk("objects");
9498       Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
9499                                CXCursor_ObjCInstanceMethodDecl));
9500     }
9501   }
9502 
9503   // - (void)intersectKey:(NSSet *)objects
9504   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9505     std::string SelectorName = (Twine("intersect") + UpperKey).str();
9506     const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9507     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9508       if (ReturnType.isNull()) {
9509         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9510         Builder.AddTextChunk("void");
9511         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9512       }
9513 
9514       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9515       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9516       Builder.AddTextChunk("NSSet *");
9517       Builder.AddChunk(CodeCompletionString::CK_RightParen);
9518       Builder.AddTextChunk("objects");
9519       Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
9520                                CXCursor_ObjCInstanceMethodDecl));
9521     }
9522   }
9523 
9524   // Key-Value Observing
9525   // + (NSSet *)keyPathsForValuesAffectingKey
9526   if (!IsInstanceMethod &&
9527       (ReturnType.isNull() ||
9528        (ReturnType->isObjCObjectPointerType() &&
9529         ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
9530         ReturnType->castAs<ObjCObjectPointerType>()
9531                 ->getInterfaceDecl()
9532                 ->getName() == "NSSet"))) {
9533     std::string SelectorName =
9534         (Twine("keyPathsForValuesAffecting") + UpperKey).str();
9535     const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9536     if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
9537             .second) {
9538       if (ReturnType.isNull()) {
9539         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9540         Builder.AddTextChunk("NSSet<NSString *> *");
9541         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9542       }
9543 
9544       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
9545       Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
9546                                CXCursor_ObjCClassMethodDecl));
9547     }
9548   }
9549 
9550   // + (BOOL)automaticallyNotifiesObserversForKey
9551   if (!IsInstanceMethod &&
9552       (ReturnType.isNull() || ReturnType->isIntegerType() ||
9553        ReturnType->isBooleanType())) {
9554     std::string SelectorName =
9555         (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
9556     const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9557     if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
9558             .second) {
9559       if (ReturnType.isNull()) {
9560         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9561         Builder.AddTextChunk("BOOL");
9562         Builder.AddChunk(CodeCompletionString::CK_RightParen);
9563       }
9564 
9565       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
9566       Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
9567                                CXCursor_ObjCClassMethodDecl));
9568     }
9569   }
9570 }
9571 
9572 void Sema::CodeCompleteObjCMethodDecl(Scope *S,
9573                                       std::optional<bool> IsInstanceMethod,
9574                                       ParsedType ReturnTy) {
9575   // Determine the return type of the method we're declaring, if
9576   // provided.
9577   QualType ReturnType = GetTypeFromParser(ReturnTy);
9578   Decl *IDecl = nullptr;
9579   if (CurContext->isObjCContainer()) {
9580     ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
9581     IDecl = OCD;
9582   }
9583   // Determine where we should start searching for methods.
9584   ObjCContainerDecl *SearchDecl = nullptr;
9585   bool IsInImplementation = false;
9586   if (Decl *D = IDecl) {
9587     if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
9588       SearchDecl = Impl->getClassInterface();
9589       IsInImplementation = true;
9590     } else if (ObjCCategoryImplDecl *CatImpl =
9591                    dyn_cast<ObjCCategoryImplDecl>(D)) {
9592       SearchDecl = CatImpl->getCategoryDecl();
9593       IsInImplementation = true;
9594     } else
9595       SearchDecl = dyn_cast<ObjCContainerDecl>(D);
9596   }
9597 
9598   if (!SearchDecl && S) {
9599     if (DeclContext *DC = S->getEntity())
9600       SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
9601   }
9602 
9603   if (!SearchDecl) {
9604     HandleCodeCompleteResults(this, CodeCompleter,
9605                               CodeCompletionContext::CCC_Other, nullptr, 0);
9606     return;
9607   }
9608 
9609   // Find all of the methods that we could declare/implement here.
9610   KnownMethodsMap KnownMethods;
9611   FindImplementableMethods(Context, SearchDecl, IsInstanceMethod, ReturnType,
9612                            KnownMethods);
9613 
9614   // Add declarations or definitions for each of the known methods.
9615   typedef CodeCompletionResult Result;
9616   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
9617                         CodeCompleter->getCodeCompletionTUInfo(),
9618                         CodeCompletionContext::CCC_Other);
9619   Results.EnterNewScope();
9620   PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
9621   for (KnownMethodsMap::iterator M = KnownMethods.begin(),
9622                                  MEnd = KnownMethods.end();
9623        M != MEnd; ++M) {
9624     ObjCMethodDecl *Method = M->second.getPointer();
9625     CodeCompletionBuilder Builder(Results.getAllocator(),
9626                                   Results.getCodeCompletionTUInfo());
9627 
9628     // Add the '-'/'+' prefix if it wasn't provided yet.
9629     if (!IsInstanceMethod) {
9630       Builder.AddTextChunk(Method->isInstanceMethod() ? "-" : "+");
9631       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9632     }
9633 
9634     // If the result type was not already provided, add it to the
9635     // pattern as (type).
9636     if (ReturnType.isNull()) {
9637       QualType ResTy = Method->getSendResultType().stripObjCKindOfType(Context);
9638       AttributedType::stripOuterNullability(ResTy);
9639       AddObjCPassingTypeChunk(ResTy, Method->getObjCDeclQualifier(), Context,
9640                               Policy, Builder);
9641     }
9642 
9643     Selector Sel = Method->getSelector();
9644 
9645     if (Sel.isUnarySelector()) {
9646       // Unary selectors have no arguments.
9647       Builder.AddTypedTextChunk(
9648           Builder.getAllocator().CopyString(Sel.getNameForSlot(0)));
9649     } else {
9650       // Add all parameters to the pattern.
9651       unsigned I = 0;
9652       for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
9653                                           PEnd = Method->param_end();
9654            P != PEnd; (void)++P, ++I) {
9655         // Add the part of the selector name.
9656         if (I == 0)
9657           Builder.AddTypedTextChunk(
9658               Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
9659         else if (I < Sel.getNumArgs()) {
9660           Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9661           Builder.AddTypedTextChunk(
9662               Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
9663         } else
9664           break;
9665 
9666         // Add the parameter type.
9667         QualType ParamType;
9668         if ((*P)->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
9669           ParamType = (*P)->getType();
9670         else
9671           ParamType = (*P)->getOriginalType();
9672         ParamType = ParamType.substObjCTypeArgs(
9673             Context, {}, ObjCSubstitutionContext::Parameter);
9674         AttributedType::stripOuterNullability(ParamType);
9675         AddObjCPassingTypeChunk(ParamType, (*P)->getObjCDeclQualifier(),
9676                                 Context, Policy, Builder);
9677 
9678         if (IdentifierInfo *Id = (*P)->getIdentifier())
9679           Builder.AddTextChunk(
9680               Builder.getAllocator().CopyString(Id->getName()));
9681       }
9682     }
9683 
9684     if (Method->isVariadic()) {
9685       if (Method->param_size() > 0)
9686         Builder.AddChunk(CodeCompletionString::CK_Comma);
9687       Builder.AddTextChunk("...");
9688     }
9689 
9690     if (IsInImplementation && Results.includeCodePatterns()) {
9691       // We will be defining the method here, so add a compound statement.
9692       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9693       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
9694       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
9695       if (!Method->getReturnType()->isVoidType()) {
9696         // If the result type is not void, add a return clause.
9697         Builder.AddTextChunk("return");
9698         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9699         Builder.AddPlaceholderChunk("expression");
9700         Builder.AddChunk(CodeCompletionString::CK_SemiColon);
9701       } else
9702         Builder.AddPlaceholderChunk("statements");
9703 
9704       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
9705       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
9706     }
9707 
9708     unsigned Priority = CCP_CodePattern;
9709     auto R = Result(Builder.TakeString(), Method, Priority);
9710     if (!M->second.getInt())
9711       setInBaseClass(R);
9712     Results.AddResult(std::move(R));
9713   }
9714 
9715   // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
9716   // the properties in this class and its categories.
9717   if (Context.getLangOpts().ObjC) {
9718     SmallVector<ObjCContainerDecl *, 4> Containers;
9719     Containers.push_back(SearchDecl);
9720 
9721     VisitedSelectorSet KnownSelectors;
9722     for (KnownMethodsMap::iterator M = KnownMethods.begin(),
9723                                    MEnd = KnownMethods.end();
9724          M != MEnd; ++M)
9725       KnownSelectors.insert(M->first);
9726 
9727     ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
9728     if (!IFace)
9729       if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
9730         IFace = Category->getClassInterface();
9731 
9732     if (IFace)
9733       llvm::append_range(Containers, IFace->visible_categories());
9734 
9735     if (IsInstanceMethod) {
9736       for (unsigned I = 0, N = Containers.size(); I != N; ++I)
9737         for (auto *P : Containers[I]->instance_properties())
9738           AddObjCKeyValueCompletions(P, *IsInstanceMethod, ReturnType, Context,
9739                                      KnownSelectors, Results);
9740     }
9741   }
9742 
9743   Results.ExitScope();
9744 
9745   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
9746                             Results.data(), Results.size());
9747 }
9748 
9749 void Sema::CodeCompleteObjCMethodDeclSelector(
9750     Scope *S, bool IsInstanceMethod, bool AtParameterName, ParsedType ReturnTy,
9751     ArrayRef<const IdentifierInfo *> SelIdents) {
9752   // If we have an external source, load the entire class method
9753   // pool from the AST file.
9754   if (ExternalSource) {
9755     for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); I != N;
9756          ++I) {
9757       Selector Sel = ExternalSource->GetExternalSelector(I);
9758       if (Sel.isNull() || MethodPool.count(Sel))
9759         continue;
9760 
9761       ReadMethodPool(Sel);
9762     }
9763   }
9764 
9765   // Build the set of methods we can see.
9766   typedef CodeCompletionResult Result;
9767   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
9768                         CodeCompleter->getCodeCompletionTUInfo(),
9769                         CodeCompletionContext::CCC_Other);
9770 
9771   if (ReturnTy)
9772     Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
9773 
9774   Results.EnterNewScope();
9775   for (GlobalMethodPool::iterator M = MethodPool.begin(),
9776                                   MEnd = MethodPool.end();
9777        M != MEnd; ++M) {
9778     for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first
9779                                                      : &M->second.second;
9780          MethList && MethList->getMethod(); MethList = MethList->getNext()) {
9781       if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
9782         continue;
9783 
9784       if (AtParameterName) {
9785         // Suggest parameter names we've seen before.
9786         unsigned NumSelIdents = SelIdents.size();
9787         if (NumSelIdents &&
9788             NumSelIdents <= MethList->getMethod()->param_size()) {
9789           ParmVarDecl *Param =
9790               MethList->getMethod()->parameters()[NumSelIdents - 1];
9791           if (Param->getIdentifier()) {
9792             CodeCompletionBuilder Builder(Results.getAllocator(),
9793                                           Results.getCodeCompletionTUInfo());
9794             Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
9795                 Param->getIdentifier()->getName()));
9796             Results.AddResult(Builder.TakeString());
9797           }
9798         }
9799 
9800         continue;
9801       }
9802 
9803       Result R(MethList->getMethod(),
9804                Results.getBasePriority(MethList->getMethod()), nullptr);
9805       R.StartParameter = SelIdents.size();
9806       R.AllParametersAreInformative = false;
9807       R.DeclaringEntity = true;
9808       Results.MaybeAddResult(R, CurContext);
9809     }
9810   }
9811 
9812   Results.ExitScope();
9813 
9814   if (!AtParameterName && !SelIdents.empty() &&
9815       SelIdents.front()->getName().starts_with("init")) {
9816     for (const auto &M : PP.macros()) {
9817       if (M.first->getName() != "NS_DESIGNATED_INITIALIZER")
9818         continue;
9819       Results.EnterNewScope();
9820       CodeCompletionBuilder Builder(Results.getAllocator(),
9821                                     Results.getCodeCompletionTUInfo());
9822       Builder.AddTypedTextChunk(
9823           Builder.getAllocator().CopyString(M.first->getName()));
9824       Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_Macro,
9825                                              CXCursor_MacroDefinition));
9826       Results.ExitScope();
9827     }
9828   }
9829 
9830   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
9831                             Results.data(), Results.size());
9832 }
9833 
9834 void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
9835   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
9836                         CodeCompleter->getCodeCompletionTUInfo(),
9837                         CodeCompletionContext::CCC_PreprocessorDirective);
9838   Results.EnterNewScope();
9839 
9840   // #if <condition>
9841   CodeCompletionBuilder Builder(Results.getAllocator(),
9842                                 Results.getCodeCompletionTUInfo());
9843   Builder.AddTypedTextChunk("if");
9844   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9845   Builder.AddPlaceholderChunk("condition");
9846   Results.AddResult(Builder.TakeString());
9847 
9848   // #ifdef <macro>
9849   Builder.AddTypedTextChunk("ifdef");
9850   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9851   Builder.AddPlaceholderChunk("macro");
9852   Results.AddResult(Builder.TakeString());
9853 
9854   // #ifndef <macro>
9855   Builder.AddTypedTextChunk("ifndef");
9856   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9857   Builder.AddPlaceholderChunk("macro");
9858   Results.AddResult(Builder.TakeString());
9859 
9860   if (InConditional) {
9861     // #elif <condition>
9862     Builder.AddTypedTextChunk("elif");
9863     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9864     Builder.AddPlaceholderChunk("condition");
9865     Results.AddResult(Builder.TakeString());
9866 
9867     // #elifdef <macro>
9868     Builder.AddTypedTextChunk("elifdef");
9869     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9870     Builder.AddPlaceholderChunk("macro");
9871     Results.AddResult(Builder.TakeString());
9872 
9873     // #elifndef <macro>
9874     Builder.AddTypedTextChunk("elifndef");
9875     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9876     Builder.AddPlaceholderChunk("macro");
9877     Results.AddResult(Builder.TakeString());
9878 
9879     // #else
9880     Builder.AddTypedTextChunk("else");
9881     Results.AddResult(Builder.TakeString());
9882 
9883     // #endif
9884     Builder.AddTypedTextChunk("endif");
9885     Results.AddResult(Builder.TakeString());
9886   }
9887 
9888   // #include "header"
9889   Builder.AddTypedTextChunk("include");
9890   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9891   Builder.AddTextChunk("\"");
9892   Builder.AddPlaceholderChunk("header");
9893   Builder.AddTextChunk("\"");
9894   Results.AddResult(Builder.TakeString());
9895 
9896   // #include <header>
9897   Builder.AddTypedTextChunk("include");
9898   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9899   Builder.AddTextChunk("<");
9900   Builder.AddPlaceholderChunk("header");
9901   Builder.AddTextChunk(">");
9902   Results.AddResult(Builder.TakeString());
9903 
9904   // #define <macro>
9905   Builder.AddTypedTextChunk("define");
9906   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9907   Builder.AddPlaceholderChunk("macro");
9908   Results.AddResult(Builder.TakeString());
9909 
9910   // #define <macro>(<args>)
9911   Builder.AddTypedTextChunk("define");
9912   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9913   Builder.AddPlaceholderChunk("macro");
9914   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9915   Builder.AddPlaceholderChunk("args");
9916   Builder.AddChunk(CodeCompletionString::CK_RightParen);
9917   Results.AddResult(Builder.TakeString());
9918 
9919   // #undef <macro>
9920   Builder.AddTypedTextChunk("undef");
9921   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9922   Builder.AddPlaceholderChunk("macro");
9923   Results.AddResult(Builder.TakeString());
9924 
9925   // #line <number>
9926   Builder.AddTypedTextChunk("line");
9927   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9928   Builder.AddPlaceholderChunk("number");
9929   Results.AddResult(Builder.TakeString());
9930 
9931   // #line <number> "filename"
9932   Builder.AddTypedTextChunk("line");
9933   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9934   Builder.AddPlaceholderChunk("number");
9935   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9936   Builder.AddTextChunk("\"");
9937   Builder.AddPlaceholderChunk("filename");
9938   Builder.AddTextChunk("\"");
9939   Results.AddResult(Builder.TakeString());
9940 
9941   // #error <message>
9942   Builder.AddTypedTextChunk("error");
9943   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9944   Builder.AddPlaceholderChunk("message");
9945   Results.AddResult(Builder.TakeString());
9946 
9947   // #pragma <arguments>
9948   Builder.AddTypedTextChunk("pragma");
9949   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9950   Builder.AddPlaceholderChunk("arguments");
9951   Results.AddResult(Builder.TakeString());
9952 
9953   if (getLangOpts().ObjC) {
9954     // #import "header"
9955     Builder.AddTypedTextChunk("import");
9956     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9957     Builder.AddTextChunk("\"");
9958     Builder.AddPlaceholderChunk("header");
9959     Builder.AddTextChunk("\"");
9960     Results.AddResult(Builder.TakeString());
9961 
9962     // #import <header>
9963     Builder.AddTypedTextChunk("import");
9964     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9965     Builder.AddTextChunk("<");
9966     Builder.AddPlaceholderChunk("header");
9967     Builder.AddTextChunk(">");
9968     Results.AddResult(Builder.TakeString());
9969   }
9970 
9971   // #include_next "header"
9972   Builder.AddTypedTextChunk("include_next");
9973   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9974   Builder.AddTextChunk("\"");
9975   Builder.AddPlaceholderChunk("header");
9976   Builder.AddTextChunk("\"");
9977   Results.AddResult(Builder.TakeString());
9978 
9979   // #include_next <header>
9980   Builder.AddTypedTextChunk("include_next");
9981   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9982   Builder.AddTextChunk("<");
9983   Builder.AddPlaceholderChunk("header");
9984   Builder.AddTextChunk(">");
9985   Results.AddResult(Builder.TakeString());
9986 
9987   // #warning <message>
9988   Builder.AddTypedTextChunk("warning");
9989   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9990   Builder.AddPlaceholderChunk("message");
9991   Results.AddResult(Builder.TakeString());
9992 
9993   // Note: #ident and #sccs are such crazy anachronisms that we don't provide
9994   // completions for them. And __include_macros is a Clang-internal extension
9995   // that we don't want to encourage anyone to use.
9996 
9997   // FIXME: we don't support #assert or #unassert, so don't suggest them.
9998   Results.ExitScope();
9999 
10000   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
10001                             Results.data(), Results.size());
10002 }
10003 
10004 void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
10005   CodeCompleteOrdinaryName(S, S->getFnParent() ? Sema::PCC_RecoveryInFunction
10006                                                : Sema::PCC_Namespace);
10007 }
10008 
10009 void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
10010   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
10011                         CodeCompleter->getCodeCompletionTUInfo(),
10012                         IsDefinition ? CodeCompletionContext::CCC_MacroName
10013                                      : CodeCompletionContext::CCC_MacroNameUse);
10014   if (!IsDefinition && CodeCompleter->includeMacros()) {
10015     // Add just the names of macros, not their arguments.
10016     CodeCompletionBuilder Builder(Results.getAllocator(),
10017                                   Results.getCodeCompletionTUInfo());
10018     Results.EnterNewScope();
10019     for (Preprocessor::macro_iterator M = PP.macro_begin(),
10020                                       MEnd = PP.macro_end();
10021          M != MEnd; ++M) {
10022       Builder.AddTypedTextChunk(
10023           Builder.getAllocator().CopyString(M->first->getName()));
10024       Results.AddResult(CodeCompletionResult(
10025           Builder.TakeString(), CCP_CodePattern, CXCursor_MacroDefinition));
10026     }
10027     Results.ExitScope();
10028   } else if (IsDefinition) {
10029     // FIXME: Can we detect when the user just wrote an include guard above?
10030   }
10031 
10032   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
10033                             Results.data(), Results.size());
10034 }
10035 
10036 void Sema::CodeCompletePreprocessorExpression() {
10037   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
10038                         CodeCompleter->getCodeCompletionTUInfo(),
10039                         CodeCompletionContext::CCC_PreprocessorExpression);
10040 
10041   if (CodeCompleter->includeMacros())
10042     AddMacroResults(PP, Results, CodeCompleter->loadExternal(), true);
10043 
10044   // defined (<macro>)
10045   Results.EnterNewScope();
10046   CodeCompletionBuilder Builder(Results.getAllocator(),
10047                                 Results.getCodeCompletionTUInfo());
10048   Builder.AddTypedTextChunk("defined");
10049   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
10050   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
10051   Builder.AddPlaceholderChunk("macro");
10052   Builder.AddChunk(CodeCompletionString::CK_RightParen);
10053   Results.AddResult(Builder.TakeString());
10054   Results.ExitScope();
10055 
10056   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
10057                             Results.data(), Results.size());
10058 }
10059 
10060 void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
10061                                                  IdentifierInfo *Macro,
10062                                                  MacroInfo *MacroInfo,
10063                                                  unsigned Argument) {
10064   // FIXME: In the future, we could provide "overload" results, much like we
10065   // do for function calls.
10066 
10067   // Now just ignore this. There will be another code-completion callback
10068   // for the expanded tokens.
10069 }
10070 
10071 // This handles completion inside an #include filename, e.g. #include <foo/ba
10072 // We look for the directory "foo" under each directory on the include path,
10073 // list its files, and reassemble the appropriate #include.
10074 void Sema::CodeCompleteIncludedFile(llvm::StringRef Dir, bool Angled) {
10075   // RelDir should use /, but unescaped \ is possible on windows!
10076   // Our completions will normalize to / for simplicity, this case is rare.
10077   std::string RelDir = llvm::sys::path::convert_to_slash(Dir);
10078   // We need the native slashes for the actual file system interactions.
10079   SmallString<128> NativeRelDir = StringRef(RelDir);
10080   llvm::sys::path::native(NativeRelDir);
10081   llvm::vfs::FileSystem &FS =
10082       getSourceManager().getFileManager().getVirtualFileSystem();
10083 
10084   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
10085                         CodeCompleter->getCodeCompletionTUInfo(),
10086                         CodeCompletionContext::CCC_IncludedFile);
10087   llvm::DenseSet<StringRef> SeenResults; // To deduplicate results.
10088 
10089   // Helper: adds one file or directory completion result.
10090   auto AddCompletion = [&](StringRef Filename, bool IsDirectory) {
10091     SmallString<64> TypedChunk = Filename;
10092     // Directory completion is up to the slash, e.g. <sys/
10093     TypedChunk.push_back(IsDirectory ? '/' : Angled ? '>' : '"');
10094     auto R = SeenResults.insert(TypedChunk);
10095     if (R.second) { // New completion
10096       const char *InternedTyped = Results.getAllocator().CopyString(TypedChunk);
10097       *R.first = InternedTyped; // Avoid dangling StringRef.
10098       CodeCompletionBuilder Builder(CodeCompleter->getAllocator(),
10099                                     CodeCompleter->getCodeCompletionTUInfo());
10100       Builder.AddTypedTextChunk(InternedTyped);
10101       // The result is a "Pattern", which is pretty opaque.
10102       // We may want to include the real filename to allow smart ranking.
10103       Results.AddResult(CodeCompletionResult(Builder.TakeString()));
10104     }
10105   };
10106 
10107   // Helper: scans IncludeDir for nice files, and adds results for each.
10108   auto AddFilesFromIncludeDir = [&](StringRef IncludeDir,
10109                                     bool IsSystem,
10110                                     DirectoryLookup::LookupType_t LookupType) {
10111     llvm::SmallString<128> Dir = IncludeDir;
10112     if (!NativeRelDir.empty()) {
10113       if (LookupType == DirectoryLookup::LT_Framework) {
10114         // For a framework dir, #include <Foo/Bar/> actually maps to
10115         // a path of Foo.framework/Headers/Bar/.
10116         auto Begin = llvm::sys::path::begin(NativeRelDir);
10117         auto End = llvm::sys::path::end(NativeRelDir);
10118 
10119         llvm::sys::path::append(Dir, *Begin + ".framework", "Headers");
10120         llvm::sys::path::append(Dir, ++Begin, End);
10121       } else {
10122         llvm::sys::path::append(Dir, NativeRelDir);
10123       }
10124     }
10125 
10126     const StringRef &Dirname = llvm::sys::path::filename(Dir);
10127     const bool isQt = Dirname.starts_with("Qt") || Dirname == "ActiveQt";
10128     const bool ExtensionlessHeaders =
10129         IsSystem || isQt || Dir.ends_with(".framework/Headers");
10130     std::error_code EC;
10131     unsigned Count = 0;
10132     for (auto It = FS.dir_begin(Dir, EC);
10133          !EC && It != llvm::vfs::directory_iterator(); It.increment(EC)) {
10134       if (++Count == 2500) // If we happen to hit a huge directory,
10135         break;             // bail out early so we're not too slow.
10136       StringRef Filename = llvm::sys::path::filename(It->path());
10137 
10138       // To know whether a symlink should be treated as file or a directory, we
10139       // have to stat it. This should be cheap enough as there shouldn't be many
10140       // symlinks.
10141       llvm::sys::fs::file_type Type = It->type();
10142       if (Type == llvm::sys::fs::file_type::symlink_file) {
10143         if (auto FileStatus = FS.status(It->path()))
10144           Type = FileStatus->getType();
10145       }
10146       switch (Type) {
10147       case llvm::sys::fs::file_type::directory_file:
10148         // All entries in a framework directory must have a ".framework" suffix,
10149         // but the suffix does not appear in the source code's include/import.
10150         if (LookupType == DirectoryLookup::LT_Framework &&
10151             NativeRelDir.empty() && !Filename.consume_back(".framework"))
10152           break;
10153 
10154         AddCompletion(Filename, /*IsDirectory=*/true);
10155         break;
10156       case llvm::sys::fs::file_type::regular_file: {
10157         // Only files that really look like headers. (Except in special dirs).
10158         const bool IsHeader = Filename.ends_with_insensitive(".h") ||
10159                               Filename.ends_with_insensitive(".hh") ||
10160                               Filename.ends_with_insensitive(".hpp") ||
10161                               Filename.ends_with_insensitive(".hxx") ||
10162                               Filename.ends_with_insensitive(".inc") ||
10163                               (ExtensionlessHeaders && !Filename.contains('.'));
10164         if (!IsHeader)
10165           break;
10166         AddCompletion(Filename, /*IsDirectory=*/false);
10167         break;
10168       }
10169       default:
10170         break;
10171       }
10172     }
10173   };
10174 
10175   // Helper: adds results relative to IncludeDir, if possible.
10176   auto AddFilesFromDirLookup = [&](const DirectoryLookup &IncludeDir,
10177                                    bool IsSystem) {
10178     switch (IncludeDir.getLookupType()) {
10179     case DirectoryLookup::LT_HeaderMap:
10180       // header maps are not (currently) enumerable.
10181       break;
10182     case DirectoryLookup::LT_NormalDir:
10183       AddFilesFromIncludeDir(IncludeDir.getDirRef()->getName(), IsSystem,
10184                              DirectoryLookup::LT_NormalDir);
10185       break;
10186     case DirectoryLookup::LT_Framework:
10187       AddFilesFromIncludeDir(IncludeDir.getFrameworkDirRef()->getName(),
10188                              IsSystem, DirectoryLookup::LT_Framework);
10189       break;
10190     }
10191   };
10192 
10193   // Finally with all our helpers, we can scan the include path.
10194   // Do this in standard order so deduplication keeps the right file.
10195   // (In case we decide to add more details to the results later).
10196   const auto &S = PP.getHeaderSearchInfo();
10197   using llvm::make_range;
10198   if (!Angled) {
10199     // The current directory is on the include path for "quoted" includes.
10200     if (auto CurFile = PP.getCurrentFileLexer()->getFileEntry())
10201       AddFilesFromIncludeDir(CurFile->getDir().getName(), false,
10202                              DirectoryLookup::LT_NormalDir);
10203     for (const auto &D : make_range(S.quoted_dir_begin(), S.quoted_dir_end()))
10204       AddFilesFromDirLookup(D, false);
10205   }
10206   for (const auto &D : make_range(S.angled_dir_begin(), S.angled_dir_end()))
10207     AddFilesFromDirLookup(D, false);
10208   for (const auto &D : make_range(S.system_dir_begin(), S.system_dir_end()))
10209     AddFilesFromDirLookup(D, true);
10210 
10211   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
10212                             Results.data(), Results.size());
10213 }
10214 
10215 void Sema::CodeCompleteNaturalLanguage() {
10216   HandleCodeCompleteResults(this, CodeCompleter,
10217                             CodeCompletionContext::CCC_NaturalLanguage, nullptr,
10218                             0);
10219 }
10220 
10221 void Sema::CodeCompleteAvailabilityPlatformName() {
10222   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
10223                         CodeCompleter->getCodeCompletionTUInfo(),
10224                         CodeCompletionContext::CCC_Other);
10225   Results.EnterNewScope();
10226   static const char *Platforms[] = {"macOS", "iOS", "watchOS", "tvOS"};
10227   for (const char *Platform : llvm::ArrayRef(Platforms)) {
10228     Results.AddResult(CodeCompletionResult(Platform));
10229     Results.AddResult(CodeCompletionResult(Results.getAllocator().CopyString(
10230         Twine(Platform) + "ApplicationExtension")));
10231   }
10232   Results.ExitScope();
10233   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
10234                             Results.data(), Results.size());
10235 }
10236 
10237 void Sema::GatherGlobalCodeCompletions(
10238     CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo,
10239     SmallVectorImpl<CodeCompletionResult> &Results) {
10240   ResultBuilder Builder(*this, Allocator, CCTUInfo,
10241                         CodeCompletionContext::CCC_Recovery);
10242   if (!CodeCompleter || CodeCompleter->includeGlobals()) {
10243     CodeCompletionDeclConsumer Consumer(Builder,
10244                                         Context.getTranslationUnitDecl());
10245     LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
10246                        Consumer,
10247                        !CodeCompleter || CodeCompleter->loadExternal());
10248   }
10249 
10250   if (!CodeCompleter || CodeCompleter->includeMacros())
10251     AddMacroResults(PP, Builder,
10252                     !CodeCompleter || CodeCompleter->loadExternal(), true);
10253 
10254   Results.clear();
10255   Results.insert(Results.end(), Builder.data(),
10256                  Builder.data() + Builder.size());
10257 }
10258