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