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