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