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