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