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