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