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