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