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