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 static 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     // As SS is invalid, we try to collect accessible contexts from the current
5065     // scope with a dummy lookup so that the completion consumer can try to
5066     // guess what the specified scope is.
5067     ResultBuilder DummyResults(*this, CodeCompleter->getAllocator(),
5068                                CodeCompleter->getCodeCompletionTUInfo(), CC);
5069     if (S->getEntity()) {
5070       CodeCompletionDeclConsumer Consumer(DummyResults, S->getEntity(),
5071                                           BaseType);
5072       LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5073                          /*IncludeGlobalScope=*/false,
5074                          /*LoadExternal=*/false);
5075     }
5076     HandleCodeCompleteResults(this, CodeCompleter,
5077                               DummyResults.getCompletionContext(), nullptr, 0);
5078     return;
5079   }
5080   // Always pretend to enter a context to ensure that a dependent type
5081   // resolves to a dependent record.
5082   DeclContext *Ctx = computeDeclContext(SS, /*EnteringContext=*/true);
5083   if (!Ctx)
5084     return;
5085 
5086   // Try to instantiate any non-dependent declaration contexts before
5087   // we look in them.
5088   if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
5089     return;
5090 
5091   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5092                         CodeCompleter->getCodeCompletionTUInfo(),
5093                         CodeCompletionContext::CCC_Symbol);
5094   Results.EnterNewScope();
5095 
5096   // The "template" keyword can follow "::" in the grammar, but only
5097   // put it into the grammar if the nested-name-specifier is dependent.
5098   NestedNameSpecifier *NNS = SS.getScopeRep();
5099   if (!Results.empty() && NNS->isDependent())
5100     Results.AddResult("template");
5101 
5102   // Add calls to overridden virtual functions, if there are any.
5103   //
5104   // FIXME: This isn't wonderful, because we don't know whether we're actually
5105   // in a context that permits expressions. This is a general issue with
5106   // qualified-id completions.
5107   if (!EnteringContext)
5108     MaybeAddOverrideCalls(*this, Ctx, Results);
5109   Results.ExitScope();
5110 
5111   if (CodeCompleter->includeNamespaceLevelDecls() ||
5112       (!Ctx->isNamespace() && !Ctx->isTranslationUnit())) {
5113     CodeCompletionDeclConsumer Consumer(Results, Ctx, BaseType);
5114     LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer,
5115                        /*IncludeGlobalScope=*/true,
5116                        /*IncludeDependentBases=*/true,
5117                        CodeCompleter->loadExternal());
5118   }
5119 
5120   auto CC = Results.getCompletionContext();
5121   CC.setCXXScopeSpecifier(SS);
5122 
5123   HandleCodeCompleteResults(this, CodeCompleter, CC, Results.data(),
5124                             Results.size());
5125 }
5126 
5127 void Sema::CodeCompleteUsing(Scope *S) {
5128   if (!CodeCompleter)
5129     return;
5130 
5131   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5132                         CodeCompleter->getCodeCompletionTUInfo(),
5133                         // This can be both a using alias or using
5134                         // declaration, in the former we expect a new name and a
5135                         // symbol in the latter case.
5136                         CodeCompletionContext::CCC_SymbolOrNewName,
5137                         &ResultBuilder::IsNestedNameSpecifier);
5138   Results.EnterNewScope();
5139 
5140   // If we aren't in class scope, we could see the "namespace" keyword.
5141   if (!S->isClassScope())
5142     Results.AddResult(CodeCompletionResult("namespace"));
5143 
5144   // After "using", we can see anything that would start a
5145   // nested-name-specifier.
5146   CodeCompletionDeclConsumer Consumer(Results, CurContext);
5147   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5148                      CodeCompleter->includeGlobals(),
5149                      CodeCompleter->loadExternal());
5150   Results.ExitScope();
5151 
5152   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5153                             Results.data(), Results.size());
5154 }
5155 
5156 void Sema::CodeCompleteUsingDirective(Scope *S) {
5157   if (!CodeCompleter)
5158     return;
5159 
5160   // After "using namespace", we expect to see a namespace name or namespace
5161   // alias.
5162   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5163                         CodeCompleter->getCodeCompletionTUInfo(),
5164                         CodeCompletionContext::CCC_Namespace,
5165                         &ResultBuilder::IsNamespaceOrAlias);
5166   Results.EnterNewScope();
5167   CodeCompletionDeclConsumer Consumer(Results, CurContext);
5168   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5169                      CodeCompleter->includeGlobals(),
5170                      CodeCompleter->loadExternal());
5171   Results.ExitScope();
5172   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5173                             Results.data(), Results.size());
5174 }
5175 
5176 void Sema::CodeCompleteNamespaceDecl(Scope *S) {
5177   if (!CodeCompleter)
5178     return;
5179 
5180   DeclContext *Ctx = S->getEntity();
5181   if (!S->getParent())
5182     Ctx = Context.getTranslationUnitDecl();
5183 
5184   bool SuppressedGlobalResults =
5185       Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
5186 
5187   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5188                         CodeCompleter->getCodeCompletionTUInfo(),
5189                         SuppressedGlobalResults
5190                             ? CodeCompletionContext::CCC_Namespace
5191                             : CodeCompletionContext::CCC_Other,
5192                         &ResultBuilder::IsNamespace);
5193 
5194   if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
5195     // We only want to see those namespaces that have already been defined
5196     // within this scope, because its likely that the user is creating an
5197     // extended namespace declaration. Keep track of the most recent
5198     // definition of each namespace.
5199     std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
5200     for (DeclContext::specific_decl_iterator<NamespaceDecl>
5201              NS(Ctx->decls_begin()),
5202          NSEnd(Ctx->decls_end());
5203          NS != NSEnd; ++NS)
5204       OrigToLatest[NS->getOriginalNamespace()] = *NS;
5205 
5206     // Add the most recent definition (or extended definition) of each
5207     // namespace to the list of results.
5208     Results.EnterNewScope();
5209     for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
5210              NS = OrigToLatest.begin(),
5211              NSEnd = OrigToLatest.end();
5212          NS != NSEnd; ++NS)
5213       Results.AddResult(
5214           CodeCompletionResult(NS->second, Results.getBasePriority(NS->second),
5215                                nullptr),
5216           CurContext, nullptr, false);
5217     Results.ExitScope();
5218   }
5219 
5220   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5221                             Results.data(), Results.size());
5222 }
5223 
5224 void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
5225   if (!CodeCompleter)
5226     return;
5227 
5228   // After "namespace", we expect to see a namespace or alias.
5229   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5230                         CodeCompleter->getCodeCompletionTUInfo(),
5231                         CodeCompletionContext::CCC_Namespace,
5232                         &ResultBuilder::IsNamespaceOrAlias);
5233   CodeCompletionDeclConsumer Consumer(Results, CurContext);
5234   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5235                      CodeCompleter->includeGlobals(),
5236                      CodeCompleter->loadExternal());
5237   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5238                             Results.data(), Results.size());
5239 }
5240 
5241 void Sema::CodeCompleteOperatorName(Scope *S) {
5242   if (!CodeCompleter)
5243     return;
5244 
5245   typedef CodeCompletionResult Result;
5246   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5247                         CodeCompleter->getCodeCompletionTUInfo(),
5248                         CodeCompletionContext::CCC_Type,
5249                         &ResultBuilder::IsType);
5250   Results.EnterNewScope();
5251 
5252   // Add the names of overloadable operators.
5253 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly)  \
5254   if (std::strcmp(Spelling, "?"))                                              \
5255     Results.AddResult(Result(Spelling));
5256 #include "clang/Basic/OperatorKinds.def"
5257 
5258   // Add any type names visible from the current scope
5259   Results.allowNestedNameSpecifiers();
5260   CodeCompletionDeclConsumer Consumer(Results, CurContext);
5261   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5262                      CodeCompleter->includeGlobals(),
5263                      CodeCompleter->loadExternal());
5264 
5265   // Add any type specifiers
5266   AddTypeSpecifierResults(getLangOpts(), Results);
5267   Results.ExitScope();
5268 
5269   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5270                             Results.data(), Results.size());
5271 }
5272 
5273 void Sema::CodeCompleteConstructorInitializer(
5274     Decl *ConstructorD, ArrayRef<CXXCtorInitializer *> Initializers) {
5275   if (!ConstructorD)
5276     return;
5277 
5278   AdjustDeclIfTemplate(ConstructorD);
5279 
5280   auto *Constructor = dyn_cast<CXXConstructorDecl>(ConstructorD);
5281   if (!Constructor)
5282     return;
5283 
5284   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5285                         CodeCompleter->getCodeCompletionTUInfo(),
5286                         CodeCompletionContext::CCC_Symbol);
5287   Results.EnterNewScope();
5288 
5289   // Fill in any already-initialized fields or base classes.
5290   llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
5291   llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
5292   for (unsigned I = 0, E = Initializers.size(); I != E; ++I) {
5293     if (Initializers[I]->isBaseInitializer())
5294       InitializedBases.insert(Context.getCanonicalType(
5295           QualType(Initializers[I]->getBaseClass(), 0)));
5296     else
5297       InitializedFields.insert(
5298           cast<FieldDecl>(Initializers[I]->getAnyMember()));
5299   }
5300 
5301   // Add completions for base classes.
5302   PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
5303   bool SawLastInitializer = Initializers.empty();
5304   CXXRecordDecl *ClassDecl = Constructor->getParent();
5305 
5306   auto GenerateCCS = [&](const NamedDecl *ND, const char *Name) {
5307     CodeCompletionBuilder Builder(Results.getAllocator(),
5308                                   Results.getCodeCompletionTUInfo());
5309     Builder.AddTypedTextChunk(Name);
5310     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5311     if (const auto *Function = dyn_cast<FunctionDecl>(ND))
5312       AddFunctionParameterChunks(PP, Policy, Function, Builder);
5313     else if (const auto *FunTemplDecl = dyn_cast<FunctionTemplateDecl>(ND))
5314       AddFunctionParameterChunks(PP, Policy, FunTemplDecl->getTemplatedDecl(),
5315                                  Builder);
5316     Builder.AddChunk(CodeCompletionString::CK_RightParen);
5317     return Builder.TakeString();
5318   };
5319   auto AddDefaultCtorInit = [&](const char *Name, const char *Type,
5320                                 const NamedDecl *ND) {
5321     CodeCompletionBuilder Builder(Results.getAllocator(),
5322                                   Results.getCodeCompletionTUInfo());
5323     Builder.AddTypedTextChunk(Name);
5324     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5325     Builder.AddPlaceholderChunk(Type);
5326     Builder.AddChunk(CodeCompletionString::CK_RightParen);
5327     if (ND) {
5328       auto CCR = CodeCompletionResult(
5329           Builder.TakeString(), ND,
5330           SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration);
5331       if (isa<FieldDecl>(ND))
5332         CCR.CursorKind = CXCursor_MemberRef;
5333       return Results.AddResult(CCR);
5334     }
5335     return Results.AddResult(CodeCompletionResult(
5336         Builder.TakeString(),
5337         SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration));
5338   };
5339   auto AddCtorsWithName = [&](const CXXRecordDecl *RD, unsigned int Priority,
5340                               const char *Name, const FieldDecl *FD) {
5341     if (!RD)
5342       return AddDefaultCtorInit(Name,
5343                                 FD ? Results.getAllocator().CopyString(
5344                                          FD->getType().getAsString(Policy))
5345                                    : Name,
5346                                 FD);
5347     auto Ctors = getConstructors(Context, RD);
5348     if (Ctors.begin() == Ctors.end())
5349       return AddDefaultCtorInit(Name, Name, RD);
5350     for (const NamedDecl *Ctor : Ctors) {
5351       auto CCR = CodeCompletionResult(GenerateCCS(Ctor, Name), RD, Priority);
5352       CCR.CursorKind = getCursorKindForDecl(Ctor);
5353       Results.AddResult(CCR);
5354     }
5355   };
5356   auto AddBase = [&](const CXXBaseSpecifier &Base) {
5357     const char *BaseName =
5358         Results.getAllocator().CopyString(Base.getType().getAsString(Policy));
5359     const auto *RD = Base.getType()->getAsCXXRecordDecl();
5360     AddCtorsWithName(
5361         RD, SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration,
5362         BaseName, nullptr);
5363   };
5364   auto AddField = [&](const FieldDecl *FD) {
5365     const char *FieldName =
5366         Results.getAllocator().CopyString(FD->getIdentifier()->getName());
5367     const CXXRecordDecl *RD = FD->getType()->getAsCXXRecordDecl();
5368     AddCtorsWithName(
5369         RD, SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration,
5370         FieldName, FD);
5371   };
5372 
5373   for (const auto &Base : ClassDecl->bases()) {
5374     if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
5375              .second) {
5376       SawLastInitializer =
5377           !Initializers.empty() && Initializers.back()->isBaseInitializer() &&
5378           Context.hasSameUnqualifiedType(
5379               Base.getType(), QualType(Initializers.back()->getBaseClass(), 0));
5380       continue;
5381     }
5382 
5383     AddBase(Base);
5384     SawLastInitializer = false;
5385   }
5386 
5387   // Add completions for virtual base classes.
5388   for (const auto &Base : ClassDecl->vbases()) {
5389     if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
5390              .second) {
5391       SawLastInitializer =
5392           !Initializers.empty() && Initializers.back()->isBaseInitializer() &&
5393           Context.hasSameUnqualifiedType(
5394               Base.getType(), QualType(Initializers.back()->getBaseClass(), 0));
5395       continue;
5396     }
5397 
5398     AddBase(Base);
5399     SawLastInitializer = false;
5400   }
5401 
5402   // Add completions for members.
5403   for (auto *Field : ClassDecl->fields()) {
5404     if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))
5405              .second) {
5406       SawLastInitializer = !Initializers.empty() &&
5407                            Initializers.back()->isAnyMemberInitializer() &&
5408                            Initializers.back()->getAnyMember() == Field;
5409       continue;
5410     }
5411 
5412     if (!Field->getDeclName())
5413       continue;
5414 
5415     AddField(Field);
5416     SawLastInitializer = false;
5417   }
5418   Results.ExitScope();
5419 
5420   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5421                             Results.data(), Results.size());
5422 }
5423 
5424 /// Determine whether this scope denotes a namespace.
5425 static bool isNamespaceScope(Scope *S) {
5426   DeclContext *DC = S->getEntity();
5427   if (!DC)
5428     return false;
5429 
5430   return DC->isFileContext();
5431 }
5432 
5433 void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
5434                                         bool AfterAmpersand) {
5435   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5436                         CodeCompleter->getCodeCompletionTUInfo(),
5437                         CodeCompletionContext::CCC_Other);
5438   Results.EnterNewScope();
5439 
5440   // Note what has already been captured.
5441   llvm::SmallPtrSet<IdentifierInfo *, 4> Known;
5442   bool IncludedThis = false;
5443   for (const auto &C : Intro.Captures) {
5444     if (C.Kind == LCK_This) {
5445       IncludedThis = true;
5446       continue;
5447     }
5448 
5449     Known.insert(C.Id);
5450   }
5451 
5452   // Look for other capturable variables.
5453   for (; S && !isNamespaceScope(S); S = S->getParent()) {
5454     for (const auto *D : S->decls()) {
5455       const auto *Var = dyn_cast<VarDecl>(D);
5456       if (!Var || !Var->hasLocalStorage() || Var->hasAttr<BlocksAttr>())
5457         continue;
5458 
5459       if (Known.insert(Var->getIdentifier()).second)
5460         Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration),
5461                           CurContext, nullptr, false);
5462     }
5463   }
5464 
5465   // Add 'this', if it would be valid.
5466   if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy)
5467     addThisCompletion(*this, Results);
5468 
5469   Results.ExitScope();
5470 
5471   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5472                             Results.data(), Results.size());
5473 }
5474 
5475 /// Macro that optionally prepends an "@" to the string literal passed in via
5476 /// Keyword, depending on whether NeedAt is true or false.
5477 #define OBJC_AT_KEYWORD_NAME(NeedAt, Keyword) ((NeedAt) ? "@" Keyword : Keyword)
5478 
5479 static void AddObjCImplementationResults(const LangOptions &LangOpts,
5480                                          ResultBuilder &Results, bool NeedAt) {
5481   typedef CodeCompletionResult Result;
5482   // Since we have an implementation, we can end it.
5483   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "end")));
5484 
5485   CodeCompletionBuilder Builder(Results.getAllocator(),
5486                                 Results.getCodeCompletionTUInfo());
5487   if (LangOpts.ObjC) {
5488     // @dynamic
5489     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "dynamic"));
5490     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5491     Builder.AddPlaceholderChunk("property");
5492     Results.AddResult(Result(Builder.TakeString()));
5493 
5494     // @synthesize
5495     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "synthesize"));
5496     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5497     Builder.AddPlaceholderChunk("property");
5498     Results.AddResult(Result(Builder.TakeString()));
5499   }
5500 }
5501 
5502 static void AddObjCInterfaceResults(const LangOptions &LangOpts,
5503                                     ResultBuilder &Results, bool NeedAt) {
5504   typedef CodeCompletionResult Result;
5505 
5506   // Since we have an interface or protocol, we can end it.
5507   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "end")));
5508 
5509   if (LangOpts.ObjC) {
5510     // @property
5511     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "property")));
5512 
5513     // @required
5514     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "required")));
5515 
5516     // @optional
5517     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "optional")));
5518   }
5519 }
5520 
5521 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
5522   typedef CodeCompletionResult Result;
5523   CodeCompletionBuilder Builder(Results.getAllocator(),
5524                                 Results.getCodeCompletionTUInfo());
5525 
5526   // @class name ;
5527   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "class"));
5528   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5529   Builder.AddPlaceholderChunk("name");
5530   Results.AddResult(Result(Builder.TakeString()));
5531 
5532   if (Results.includeCodePatterns()) {
5533     // @interface name
5534     // FIXME: Could introduce the whole pattern, including superclasses and
5535     // such.
5536     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "interface"));
5537     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5538     Builder.AddPlaceholderChunk("class");
5539     Results.AddResult(Result(Builder.TakeString()));
5540 
5541     // @protocol name
5542     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "protocol"));
5543     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5544     Builder.AddPlaceholderChunk("protocol");
5545     Results.AddResult(Result(Builder.TakeString()));
5546 
5547     // @implementation name
5548     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "implementation"));
5549     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5550     Builder.AddPlaceholderChunk("class");
5551     Results.AddResult(Result(Builder.TakeString()));
5552   }
5553 
5554   // @compatibility_alias name
5555   Builder.AddTypedTextChunk(
5556       OBJC_AT_KEYWORD_NAME(NeedAt, "compatibility_alias"));
5557   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5558   Builder.AddPlaceholderChunk("alias");
5559   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5560   Builder.AddPlaceholderChunk("class");
5561   Results.AddResult(Result(Builder.TakeString()));
5562 
5563   if (Results.getSema().getLangOpts().Modules) {
5564     // @import name
5565     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import"));
5566     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5567     Builder.AddPlaceholderChunk("module");
5568     Results.AddResult(Result(Builder.TakeString()));
5569   }
5570 }
5571 
5572 void Sema::CodeCompleteObjCAtDirective(Scope *S) {
5573   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5574                         CodeCompleter->getCodeCompletionTUInfo(),
5575                         CodeCompletionContext::CCC_Other);
5576   Results.EnterNewScope();
5577   if (isa<ObjCImplDecl>(CurContext))
5578     AddObjCImplementationResults(getLangOpts(), Results, false);
5579   else if (CurContext->isObjCContainer())
5580     AddObjCInterfaceResults(getLangOpts(), Results, false);
5581   else
5582     AddObjCTopLevelResults(Results, false);
5583   Results.ExitScope();
5584   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5585                             Results.data(), Results.size());
5586 }
5587 
5588 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
5589   typedef CodeCompletionResult Result;
5590   CodeCompletionBuilder Builder(Results.getAllocator(),
5591                                 Results.getCodeCompletionTUInfo());
5592 
5593   // @encode ( type-name )
5594   const char *EncodeType = "char[]";
5595   if (Results.getSema().getLangOpts().CPlusPlus ||
5596       Results.getSema().getLangOpts().ConstStrings)
5597     EncodeType = "const char[]";
5598   Builder.AddResultTypeChunk(EncodeType);
5599   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "encode"));
5600   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5601   Builder.AddPlaceholderChunk("type-name");
5602   Builder.AddChunk(CodeCompletionString::CK_RightParen);
5603   Results.AddResult(Result(Builder.TakeString()));
5604 
5605   // @protocol ( protocol-name )
5606   Builder.AddResultTypeChunk("Protocol *");
5607   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "protocol"));
5608   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5609   Builder.AddPlaceholderChunk("protocol-name");
5610   Builder.AddChunk(CodeCompletionString::CK_RightParen);
5611   Results.AddResult(Result(Builder.TakeString()));
5612 
5613   // @selector ( selector )
5614   Builder.AddResultTypeChunk("SEL");
5615   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "selector"));
5616   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5617   Builder.AddPlaceholderChunk("selector");
5618   Builder.AddChunk(CodeCompletionString::CK_RightParen);
5619   Results.AddResult(Result(Builder.TakeString()));
5620 
5621   // @"string"
5622   Builder.AddResultTypeChunk("NSString *");
5623   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "\""));
5624   Builder.AddPlaceholderChunk("string");
5625   Builder.AddTextChunk("\"");
5626   Results.AddResult(Result(Builder.TakeString()));
5627 
5628   // @[objects, ...]
5629   Builder.AddResultTypeChunk("NSArray *");
5630   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "["));
5631   Builder.AddPlaceholderChunk("objects, ...");
5632   Builder.AddChunk(CodeCompletionString::CK_RightBracket);
5633   Results.AddResult(Result(Builder.TakeString()));
5634 
5635   // @{key : object, ...}
5636   Builder.AddResultTypeChunk("NSDictionary *");
5637   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "{"));
5638   Builder.AddPlaceholderChunk("key");
5639   Builder.AddChunk(CodeCompletionString::CK_Colon);
5640   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5641   Builder.AddPlaceholderChunk("object, ...");
5642   Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5643   Results.AddResult(Result(Builder.TakeString()));
5644 
5645   // @(expression)
5646   Builder.AddResultTypeChunk("id");
5647   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "("));
5648   Builder.AddPlaceholderChunk("expression");
5649   Builder.AddChunk(CodeCompletionString::CK_RightParen);
5650   Results.AddResult(Result(Builder.TakeString()));
5651 }
5652 
5653 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
5654   typedef CodeCompletionResult Result;
5655   CodeCompletionBuilder Builder(Results.getAllocator(),
5656                                 Results.getCodeCompletionTUInfo());
5657 
5658   if (Results.includeCodePatterns()) {
5659     // @try { statements } @catch ( declaration ) { statements } @finally
5660     //   { statements }
5661     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "try"));
5662     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5663     Builder.AddPlaceholderChunk("statements");
5664     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5665     Builder.AddTextChunk("@catch");
5666     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5667     Builder.AddPlaceholderChunk("parameter");
5668     Builder.AddChunk(CodeCompletionString::CK_RightParen);
5669     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5670     Builder.AddPlaceholderChunk("statements");
5671     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5672     Builder.AddTextChunk("@finally");
5673     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5674     Builder.AddPlaceholderChunk("statements");
5675     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5676     Results.AddResult(Result(Builder.TakeString()));
5677   }
5678 
5679   // @throw
5680   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "throw"));
5681   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5682   Builder.AddPlaceholderChunk("expression");
5683   Results.AddResult(Result(Builder.TakeString()));
5684 
5685   if (Results.includeCodePatterns()) {
5686     // @synchronized ( expression ) { statements }
5687     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "synchronized"));
5688     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5689     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5690     Builder.AddPlaceholderChunk("expression");
5691     Builder.AddChunk(CodeCompletionString::CK_RightParen);
5692     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5693     Builder.AddPlaceholderChunk("statements");
5694     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5695     Results.AddResult(Result(Builder.TakeString()));
5696   }
5697 }
5698 
5699 static void AddObjCVisibilityResults(const LangOptions &LangOpts,
5700                                      ResultBuilder &Results, bool NeedAt) {
5701   typedef CodeCompletionResult Result;
5702   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "private")));
5703   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "protected")));
5704   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "public")));
5705   if (LangOpts.ObjC)
5706     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "package")));
5707 }
5708 
5709 void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
5710   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5711                         CodeCompleter->getCodeCompletionTUInfo(),
5712                         CodeCompletionContext::CCC_Other);
5713   Results.EnterNewScope();
5714   AddObjCVisibilityResults(getLangOpts(), Results, false);
5715   Results.ExitScope();
5716   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5717                             Results.data(), Results.size());
5718 }
5719 
5720 void Sema::CodeCompleteObjCAtStatement(Scope *S) {
5721   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5722                         CodeCompleter->getCodeCompletionTUInfo(),
5723                         CodeCompletionContext::CCC_Other);
5724   Results.EnterNewScope();
5725   AddObjCStatementResults(Results, false);
5726   AddObjCExpressionResults(Results, false);
5727   Results.ExitScope();
5728   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5729                             Results.data(), Results.size());
5730 }
5731 
5732 void Sema::CodeCompleteObjCAtExpression(Scope *S) {
5733   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5734                         CodeCompleter->getCodeCompletionTUInfo(),
5735                         CodeCompletionContext::CCC_Other);
5736   Results.EnterNewScope();
5737   AddObjCExpressionResults(Results, false);
5738   Results.ExitScope();
5739   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5740                             Results.data(), Results.size());
5741 }
5742 
5743 /// Determine whether the addition of the given flag to an Objective-C
5744 /// property's attributes will cause a conflict.
5745 static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
5746   // Check if we've already added this flag.
5747   if (Attributes & NewFlag)
5748     return true;
5749 
5750   Attributes |= NewFlag;
5751 
5752   // Check for collisions with "readonly".
5753   if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
5754       (Attributes & ObjCDeclSpec::DQ_PR_readwrite))
5755     return true;
5756 
5757   // Check for more than one of { assign, copy, retain, strong, weak }.
5758   unsigned AssignCopyRetMask =
5759       Attributes &
5760       (ObjCDeclSpec::DQ_PR_assign | ObjCDeclSpec::DQ_PR_unsafe_unretained |
5761        ObjCDeclSpec::DQ_PR_copy | ObjCDeclSpec::DQ_PR_retain |
5762        ObjCDeclSpec::DQ_PR_strong | ObjCDeclSpec::DQ_PR_weak);
5763   if (AssignCopyRetMask && AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
5764       AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
5765       AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
5766       AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
5767       AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong &&
5768       AssignCopyRetMask != ObjCDeclSpec::DQ_PR_weak)
5769     return true;
5770 
5771   return false;
5772 }
5773 
5774 void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
5775   if (!CodeCompleter)
5776     return;
5777 
5778   unsigned Attributes = ODS.getPropertyAttributes();
5779 
5780   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5781                         CodeCompleter->getCodeCompletionTUInfo(),
5782                         CodeCompletionContext::CCC_Other);
5783   Results.EnterNewScope();
5784   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
5785     Results.AddResult(CodeCompletionResult("readonly"));
5786   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
5787     Results.AddResult(CodeCompletionResult("assign"));
5788   if (!ObjCPropertyFlagConflicts(Attributes,
5789                                  ObjCDeclSpec::DQ_PR_unsafe_unretained))
5790     Results.AddResult(CodeCompletionResult("unsafe_unretained"));
5791   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
5792     Results.AddResult(CodeCompletionResult("readwrite"));
5793   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
5794     Results.AddResult(CodeCompletionResult("retain"));
5795   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
5796     Results.AddResult(CodeCompletionResult("strong"));
5797   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
5798     Results.AddResult(CodeCompletionResult("copy"));
5799   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
5800     Results.AddResult(CodeCompletionResult("nonatomic"));
5801   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
5802     Results.AddResult(CodeCompletionResult("atomic"));
5803 
5804   // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC.
5805   if (getLangOpts().ObjCWeak || getLangOpts().getGC() != LangOptions::NonGC)
5806     if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_weak))
5807       Results.AddResult(CodeCompletionResult("weak"));
5808 
5809   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
5810     CodeCompletionBuilder Setter(Results.getAllocator(),
5811                                  Results.getCodeCompletionTUInfo());
5812     Setter.AddTypedTextChunk("setter");
5813     Setter.AddTextChunk("=");
5814     Setter.AddPlaceholderChunk("method");
5815     Results.AddResult(CodeCompletionResult(Setter.TakeString()));
5816   }
5817   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
5818     CodeCompletionBuilder Getter(Results.getAllocator(),
5819                                  Results.getCodeCompletionTUInfo());
5820     Getter.AddTypedTextChunk("getter");
5821     Getter.AddTextChunk("=");
5822     Getter.AddPlaceholderChunk("method");
5823     Results.AddResult(CodeCompletionResult(Getter.TakeString()));
5824   }
5825   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nullability)) {
5826     Results.AddResult(CodeCompletionResult("nonnull"));
5827     Results.AddResult(CodeCompletionResult("nullable"));
5828     Results.AddResult(CodeCompletionResult("null_unspecified"));
5829     Results.AddResult(CodeCompletionResult("null_resettable"));
5830   }
5831   Results.ExitScope();
5832   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5833                             Results.data(), Results.size());
5834 }
5835 
5836 /// Describes the kind of Objective-C method that we want to find
5837 /// via code completion.
5838 enum ObjCMethodKind {
5839   MK_Any, ///< Any kind of method, provided it means other specified criteria.
5840   MK_ZeroArgSelector, ///< Zero-argument (unary) selector.
5841   MK_OneArgSelector   ///< One-argument selector.
5842 };
5843 
5844 static bool isAcceptableObjCSelector(Selector Sel, ObjCMethodKind WantKind,
5845                                      ArrayRef<IdentifierInfo *> SelIdents,
5846                                      bool AllowSameLength = true) {
5847   unsigned NumSelIdents = SelIdents.size();
5848   if (NumSelIdents > Sel.getNumArgs())
5849     return false;
5850 
5851   switch (WantKind) {
5852   case MK_Any:
5853     break;
5854   case MK_ZeroArgSelector:
5855     return Sel.isUnarySelector();
5856   case MK_OneArgSelector:
5857     return Sel.getNumArgs() == 1;
5858   }
5859 
5860   if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
5861     return false;
5862 
5863   for (unsigned I = 0; I != NumSelIdents; ++I)
5864     if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
5865       return false;
5866 
5867   return true;
5868 }
5869 
5870 static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
5871                                    ObjCMethodKind WantKind,
5872                                    ArrayRef<IdentifierInfo *> SelIdents,
5873                                    bool AllowSameLength = true) {
5874   return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
5875                                   AllowSameLength);
5876 }
5877 
5878 /// A set of selectors, which is used to avoid introducing multiple
5879 /// completions with the same selector into the result set.
5880 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
5881 
5882 /// Add all of the Objective-C methods in the given Objective-C
5883 /// container to the set of results.
5884 ///
5885 /// The container will be a class, protocol, category, or implementation of
5886 /// any of the above. This mether will recurse to include methods from
5887 /// the superclasses of classes along with their categories, protocols, and
5888 /// implementations.
5889 ///
5890 /// \param Container the container in which we'll look to find methods.
5891 ///
5892 /// \param WantInstanceMethods Whether to add instance methods (only); if
5893 /// false, this routine will add factory methods (only).
5894 ///
5895 /// \param CurContext the context in which we're performing the lookup that
5896 /// finds methods.
5897 ///
5898 /// \param AllowSameLength Whether we allow a method to be added to the list
5899 /// when it has the same number of parameters as we have selector identifiers.
5900 ///
5901 /// \param Results the structure into which we'll add results.
5902 static void AddObjCMethods(ObjCContainerDecl *Container,
5903                            bool WantInstanceMethods, ObjCMethodKind WantKind,
5904                            ArrayRef<IdentifierInfo *> SelIdents,
5905                            DeclContext *CurContext,
5906                            VisitedSelectorSet &Selectors, bool AllowSameLength,
5907                            ResultBuilder &Results, bool InOriginalClass = true,
5908                            bool IsRootClass = false) {
5909   typedef CodeCompletionResult Result;
5910   Container = getContainerDef(Container);
5911   ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
5912   IsRootClass = IsRootClass || (IFace && !IFace->getSuperClass());
5913   for (ObjCMethodDecl *M : Container->methods()) {
5914     // The instance methods on the root class can be messaged via the
5915     // metaclass.
5916     if (M->isInstanceMethod() == WantInstanceMethods ||
5917         (IsRootClass && !WantInstanceMethods)) {
5918       // Check whether the selector identifiers we've been given are a
5919       // subset of the identifiers for this particular method.
5920       if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength))
5921         continue;
5922 
5923       if (!Selectors.insert(M->getSelector()).second)
5924         continue;
5925 
5926       Result R = Result(M, Results.getBasePriority(M), nullptr);
5927       R.StartParameter = SelIdents.size();
5928       R.AllParametersAreInformative = (WantKind != MK_Any);
5929       if (!InOriginalClass)
5930         setInBaseClass(R);
5931       Results.MaybeAddResult(R, CurContext);
5932     }
5933   }
5934 
5935   // Visit the protocols of protocols.
5936   if (const auto *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5937     if (Protocol->hasDefinition()) {
5938       const ObjCList<ObjCProtocolDecl> &Protocols =
5939           Protocol->getReferencedProtocols();
5940       for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5941                                                 E = Protocols.end();
5942            I != E; ++I)
5943         AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext,
5944                        Selectors, AllowSameLength, Results, false, IsRootClass);
5945     }
5946   }
5947 
5948   if (!IFace || !IFace->hasDefinition())
5949     return;
5950 
5951   // Add methods in protocols.
5952   for (ObjCProtocolDecl *I : IFace->protocols())
5953     AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents, CurContext,
5954                    Selectors, AllowSameLength, Results, false, IsRootClass);
5955 
5956   // Add methods in categories.
5957   for (ObjCCategoryDecl *CatDecl : IFace->known_categories()) {
5958     AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
5959                    CurContext, Selectors, AllowSameLength, Results,
5960                    InOriginalClass, IsRootClass);
5961 
5962     // Add a categories protocol methods.
5963     const ObjCList<ObjCProtocolDecl> &Protocols =
5964         CatDecl->getReferencedProtocols();
5965     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5966                                               E = Protocols.end();
5967          I != E; ++I)
5968       AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext,
5969                      Selectors, AllowSameLength, Results, false, IsRootClass);
5970 
5971     // Add methods in category implementations.
5972     if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
5973       AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext,
5974                      Selectors, AllowSameLength, Results, InOriginalClass,
5975                      IsRootClass);
5976   }
5977 
5978   // Add methods in superclass.
5979   // Avoid passing in IsRootClass since root classes won't have super classes.
5980   if (IFace->getSuperClass())
5981     AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
5982                    SelIdents, CurContext, Selectors, AllowSameLength, Results,
5983                    /*IsRootClass=*/false);
5984 
5985   // Add methods in our implementation, if any.
5986   if (ObjCImplementationDecl *Impl = IFace->getImplementation())
5987     AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext,
5988                    Selectors, AllowSameLength, Results, InOriginalClass,
5989                    IsRootClass);
5990 }
5991 
5992 void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
5993   // Try to find the interface where getters might live.
5994   ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
5995   if (!Class) {
5996     if (ObjCCategoryDecl *Category =
5997             dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
5998       Class = Category->getClassInterface();
5999 
6000     if (!Class)
6001       return;
6002   }
6003 
6004   // Find all of the potential getters.
6005   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6006                         CodeCompleter->getCodeCompletionTUInfo(),
6007                         CodeCompletionContext::CCC_Other);
6008   Results.EnterNewScope();
6009 
6010   VisitedSelectorSet Selectors;
6011   AddObjCMethods(Class, true, MK_ZeroArgSelector, None, CurContext, Selectors,
6012                  /*AllowSameLength=*/true, Results);
6013   Results.ExitScope();
6014   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6015                             Results.data(), Results.size());
6016 }
6017 
6018 void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
6019   // Try to find the interface where setters might live.
6020   ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
6021   if (!Class) {
6022     if (ObjCCategoryDecl *Category =
6023             dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
6024       Class = Category->getClassInterface();
6025 
6026     if (!Class)
6027       return;
6028   }
6029 
6030   // Find all of the potential getters.
6031   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6032                         CodeCompleter->getCodeCompletionTUInfo(),
6033                         CodeCompletionContext::CCC_Other);
6034   Results.EnterNewScope();
6035 
6036   VisitedSelectorSet Selectors;
6037   AddObjCMethods(Class, true, MK_OneArgSelector, None, CurContext, Selectors,
6038                  /*AllowSameLength=*/true, Results);
6039 
6040   Results.ExitScope();
6041   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6042                             Results.data(), Results.size());
6043 }
6044 
6045 void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
6046                                        bool IsParameter) {
6047   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6048                         CodeCompleter->getCodeCompletionTUInfo(),
6049                         CodeCompletionContext::CCC_Type);
6050   Results.EnterNewScope();
6051 
6052   // Add context-sensitive, Objective-C parameter-passing keywords.
6053   bool AddedInOut = false;
6054   if ((DS.getObjCDeclQualifier() &
6055        (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
6056     Results.AddResult("in");
6057     Results.AddResult("inout");
6058     AddedInOut = true;
6059   }
6060   if ((DS.getObjCDeclQualifier() &
6061        (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
6062     Results.AddResult("out");
6063     if (!AddedInOut)
6064       Results.AddResult("inout");
6065   }
6066   if ((DS.getObjCDeclQualifier() &
6067        (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
6068         ObjCDeclSpec::DQ_Oneway)) == 0) {
6069     Results.AddResult("bycopy");
6070     Results.AddResult("byref");
6071     Results.AddResult("oneway");
6072   }
6073   if ((DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability) == 0) {
6074     Results.AddResult("nonnull");
6075     Results.AddResult("nullable");
6076     Results.AddResult("null_unspecified");
6077   }
6078 
6079   // If we're completing the return type of an Objective-C method and the
6080   // identifier IBAction refers to a macro, provide a completion item for
6081   // an action, e.g.,
6082   //   IBAction)<#selector#>:(id)sender
6083   if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
6084       PP.isMacroDefined("IBAction")) {
6085     CodeCompletionBuilder Builder(Results.getAllocator(),
6086                                   Results.getCodeCompletionTUInfo(),
6087                                   CCP_CodePattern, CXAvailability_Available);
6088     Builder.AddTypedTextChunk("IBAction");
6089     Builder.AddChunk(CodeCompletionString::CK_RightParen);
6090     Builder.AddPlaceholderChunk("selector");
6091     Builder.AddChunk(CodeCompletionString::CK_Colon);
6092     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6093     Builder.AddTextChunk("id");
6094     Builder.AddChunk(CodeCompletionString::CK_RightParen);
6095     Builder.AddTextChunk("sender");
6096     Results.AddResult(CodeCompletionResult(Builder.TakeString()));
6097   }
6098 
6099   // If we're completing the return type, provide 'instancetype'.
6100   if (!IsParameter) {
6101     Results.AddResult(CodeCompletionResult("instancetype"));
6102   }
6103 
6104   // Add various builtin type names and specifiers.
6105   AddOrdinaryNameResults(PCC_Type, S, *this, Results);
6106   Results.ExitScope();
6107 
6108   // Add the various type names
6109   Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
6110   CodeCompletionDeclConsumer Consumer(Results, CurContext);
6111   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
6112                      CodeCompleter->includeGlobals(),
6113                      CodeCompleter->loadExternal());
6114 
6115   if (CodeCompleter->includeMacros())
6116     AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
6117 
6118   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6119                             Results.data(), Results.size());
6120 }
6121 
6122 /// When we have an expression with type "id", we may assume
6123 /// that it has some more-specific class type based on knowledge of
6124 /// common uses of Objective-C. This routine returns that class type,
6125 /// or NULL if no better result could be determined.
6126 static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
6127   auto *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
6128   if (!Msg)
6129     return nullptr;
6130 
6131   Selector Sel = Msg->getSelector();
6132   if (Sel.isNull())
6133     return nullptr;
6134 
6135   IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
6136   if (!Id)
6137     return nullptr;
6138 
6139   ObjCMethodDecl *Method = Msg->getMethodDecl();
6140   if (!Method)
6141     return nullptr;
6142 
6143   // Determine the class that we're sending the message to.
6144   ObjCInterfaceDecl *IFace = nullptr;
6145   switch (Msg->getReceiverKind()) {
6146   case ObjCMessageExpr::Class:
6147     if (const ObjCObjectType *ObjType =
6148             Msg->getClassReceiver()->getAs<ObjCObjectType>())
6149       IFace = ObjType->getInterface();
6150     break;
6151 
6152   case ObjCMessageExpr::Instance: {
6153     QualType T = Msg->getInstanceReceiver()->getType();
6154     if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
6155       IFace = Ptr->getInterfaceDecl();
6156     break;
6157   }
6158 
6159   case ObjCMessageExpr::SuperInstance:
6160   case ObjCMessageExpr::SuperClass:
6161     break;
6162   }
6163 
6164   if (!IFace)
6165     return nullptr;
6166 
6167   ObjCInterfaceDecl *Super = IFace->getSuperClass();
6168   if (Method->isInstanceMethod())
6169     return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
6170         .Case("retain", IFace)
6171         .Case("strong", IFace)
6172         .Case("autorelease", IFace)
6173         .Case("copy", IFace)
6174         .Case("copyWithZone", IFace)
6175         .Case("mutableCopy", IFace)
6176         .Case("mutableCopyWithZone", IFace)
6177         .Case("awakeFromCoder", IFace)
6178         .Case("replacementObjectFromCoder", IFace)
6179         .Case("class", IFace)
6180         .Case("classForCoder", IFace)
6181         .Case("superclass", Super)
6182         .Default(nullptr);
6183 
6184   return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
6185       .Case("new", IFace)
6186       .Case("alloc", IFace)
6187       .Case("allocWithZone", IFace)
6188       .Case("class", IFace)
6189       .Case("superclass", Super)
6190       .Default(nullptr);
6191 }
6192 
6193 // Add a special completion for a message send to "super", which fills in the
6194 // most likely case of forwarding all of our arguments to the superclass
6195 // function.
6196 ///
6197 /// \param S The semantic analysis object.
6198 ///
6199 /// \param NeedSuperKeyword Whether we need to prefix this completion with
6200 /// the "super" keyword. Otherwise, we just need to provide the arguments.
6201 ///
6202 /// \param SelIdents The identifiers in the selector that have already been
6203 /// provided as arguments for a send to "super".
6204 ///
6205 /// \param Results The set of results to augment.
6206 ///
6207 /// \returns the Objective-C method declaration that would be invoked by
6208 /// this "super" completion. If NULL, no completion was added.
6209 static ObjCMethodDecl *
6210 AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
6211                        ArrayRef<IdentifierInfo *> SelIdents,
6212                        ResultBuilder &Results) {
6213   ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
6214   if (!CurMethod)
6215     return nullptr;
6216 
6217   ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
6218   if (!Class)
6219     return nullptr;
6220 
6221   // Try to find a superclass method with the same selector.
6222   ObjCMethodDecl *SuperMethod = nullptr;
6223   while ((Class = Class->getSuperClass()) && !SuperMethod) {
6224     // Check in the class
6225     SuperMethod = Class->getMethod(CurMethod->getSelector(),
6226                                    CurMethod->isInstanceMethod());
6227 
6228     // Check in categories or class extensions.
6229     if (!SuperMethod) {
6230       for (const auto *Cat : Class->known_categories()) {
6231         if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(),
6232                                           CurMethod->isInstanceMethod())))
6233           break;
6234       }
6235     }
6236   }
6237 
6238   if (!SuperMethod)
6239     return nullptr;
6240 
6241   // Check whether the superclass method has the same signature.
6242   if (CurMethod->param_size() != SuperMethod->param_size() ||
6243       CurMethod->isVariadic() != SuperMethod->isVariadic())
6244     return nullptr;
6245 
6246   for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
6247                                       CurPEnd = CurMethod->param_end(),
6248                                       SuperP = SuperMethod->param_begin();
6249        CurP != CurPEnd; ++CurP, ++SuperP) {
6250     // Make sure the parameter types are compatible.
6251     if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
6252                                           (*SuperP)->getType()))
6253       return nullptr;
6254 
6255     // Make sure we have a parameter name to forward!
6256     if (!(*CurP)->getIdentifier())
6257       return nullptr;
6258   }
6259 
6260   // We have a superclass method. Now, form the send-to-super completion.
6261   CodeCompletionBuilder Builder(Results.getAllocator(),
6262                                 Results.getCodeCompletionTUInfo());
6263 
6264   // Give this completion a return type.
6265   AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
6266                      Results.getCompletionContext().getBaseType(), Builder);
6267 
6268   // If we need the "super" keyword, add it (plus some spacing).
6269   if (NeedSuperKeyword) {
6270     Builder.AddTypedTextChunk("super");
6271     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6272   }
6273 
6274   Selector Sel = CurMethod->getSelector();
6275   if (Sel.isUnarySelector()) {
6276     if (NeedSuperKeyword)
6277       Builder.AddTextChunk(
6278           Builder.getAllocator().CopyString(Sel.getNameForSlot(0)));
6279     else
6280       Builder.AddTypedTextChunk(
6281           Builder.getAllocator().CopyString(Sel.getNameForSlot(0)));
6282   } else {
6283     ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
6284     for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
6285       if (I > SelIdents.size())
6286         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6287 
6288       if (I < SelIdents.size())
6289         Builder.AddInformativeChunk(
6290             Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
6291       else if (NeedSuperKeyword || I > SelIdents.size()) {
6292         Builder.AddTextChunk(
6293             Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
6294         Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
6295             (*CurP)->getIdentifier()->getName()));
6296       } else {
6297         Builder.AddTypedTextChunk(
6298             Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
6299         Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
6300             (*CurP)->getIdentifier()->getName()));
6301       }
6302     }
6303   }
6304 
6305   Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod,
6306                                          CCP_SuperCompletion));
6307   return SuperMethod;
6308 }
6309 
6310 void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
6311   typedef CodeCompletionResult Result;
6312   ResultBuilder Results(
6313       *this, CodeCompleter->getAllocator(),
6314       CodeCompleter->getCodeCompletionTUInfo(),
6315       CodeCompletionContext::CCC_ObjCMessageReceiver,
6316       getLangOpts().CPlusPlus11
6317           ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture
6318           : &ResultBuilder::IsObjCMessageReceiver);
6319 
6320   CodeCompletionDeclConsumer Consumer(Results, CurContext);
6321   Results.EnterNewScope();
6322   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
6323                      CodeCompleter->includeGlobals(),
6324                      CodeCompleter->loadExternal());
6325 
6326   // If we are in an Objective-C method inside a class that has a superclass,
6327   // add "super" as an option.
6328   if (ObjCMethodDecl *Method = getCurMethodDecl())
6329     if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
6330       if (Iface->getSuperClass()) {
6331         Results.AddResult(Result("super"));
6332 
6333         AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, None, Results);
6334       }
6335 
6336   if (getLangOpts().CPlusPlus11)
6337     addThisCompletion(*this, Results);
6338 
6339   Results.ExitScope();
6340 
6341   if (CodeCompleter->includeMacros())
6342     AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
6343   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6344                             Results.data(), Results.size());
6345 }
6346 
6347 void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
6348                                         ArrayRef<IdentifierInfo *> SelIdents,
6349                                         bool AtArgumentExpression) {
6350   ObjCInterfaceDecl *CDecl = nullptr;
6351   if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
6352     // Figure out which interface we're in.
6353     CDecl = CurMethod->getClassInterface();
6354     if (!CDecl)
6355       return;
6356 
6357     // Find the superclass of this class.
6358     CDecl = CDecl->getSuperClass();
6359     if (!CDecl)
6360       return;
6361 
6362     if (CurMethod->isInstanceMethod()) {
6363       // We are inside an instance method, which means that the message
6364       // send [super ...] is actually calling an instance method on the
6365       // current object.
6366       return CodeCompleteObjCInstanceMessage(S, nullptr, SelIdents,
6367                                              AtArgumentExpression, CDecl);
6368     }
6369 
6370     // Fall through to send to the superclass in CDecl.
6371   } else {
6372     // "super" may be the name of a type or variable. Figure out which
6373     // it is.
6374     IdentifierInfo *Super = getSuperIdentifier();
6375     NamedDecl *ND = LookupSingleName(S, Super, SuperLoc, LookupOrdinaryName);
6376     if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
6377       // "super" names an interface. Use it.
6378     } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
6379       if (const ObjCObjectType *Iface =
6380               Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
6381         CDecl = Iface->getInterface();
6382     } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
6383       // "super" names an unresolved type; we can't be more specific.
6384     } else {
6385       // Assume that "super" names some kind of value and parse that way.
6386       CXXScopeSpec SS;
6387       SourceLocation TemplateKWLoc;
6388       UnqualifiedId id;
6389       id.setIdentifier(Super, SuperLoc);
6390       ExprResult SuperExpr =
6391           ActOnIdExpression(S, SS, TemplateKWLoc, id, false, false);
6392       return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
6393                                              SelIdents, AtArgumentExpression);
6394     }
6395 
6396     // Fall through
6397   }
6398 
6399   ParsedType Receiver;
6400   if (CDecl)
6401     Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
6402   return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
6403                                       AtArgumentExpression,
6404                                       /*IsSuper=*/true);
6405 }
6406 
6407 /// Given a set of code-completion results for the argument of a message
6408 /// send, determine the preferred type (if any) for that argument expression.
6409 static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
6410                                                        unsigned NumSelIdents) {
6411   typedef CodeCompletionResult Result;
6412   ASTContext &Context = Results.getSema().Context;
6413 
6414   QualType PreferredType;
6415   unsigned BestPriority = CCP_Unlikely * 2;
6416   Result *ResultsData = Results.data();
6417   for (unsigned I = 0, N = Results.size(); I != N; ++I) {
6418     Result &R = ResultsData[I];
6419     if (R.Kind == Result::RK_Declaration &&
6420         isa<ObjCMethodDecl>(R.Declaration)) {
6421       if (R.Priority <= BestPriority) {
6422         const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
6423         if (NumSelIdents <= Method->param_size()) {
6424           QualType MyPreferredType =
6425               Method->parameters()[NumSelIdents - 1]->getType();
6426           if (R.Priority < BestPriority || PreferredType.isNull()) {
6427             BestPriority = R.Priority;
6428             PreferredType = MyPreferredType;
6429           } else if (!Context.hasSameUnqualifiedType(PreferredType,
6430                                                      MyPreferredType)) {
6431             PreferredType = QualType();
6432           }
6433         }
6434       }
6435     }
6436   }
6437 
6438   return PreferredType;
6439 }
6440 
6441 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
6442                                        ParsedType Receiver,
6443                                        ArrayRef<IdentifierInfo *> SelIdents,
6444                                        bool AtArgumentExpression, bool IsSuper,
6445                                        ResultBuilder &Results) {
6446   typedef CodeCompletionResult Result;
6447   ObjCInterfaceDecl *CDecl = nullptr;
6448 
6449   // If the given name refers to an interface type, retrieve the
6450   // corresponding declaration.
6451   if (Receiver) {
6452     QualType T = SemaRef.GetTypeFromParser(Receiver, nullptr);
6453     if (!T.isNull())
6454       if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
6455         CDecl = Interface->getInterface();
6456   }
6457 
6458   // Add all of the factory methods in this Objective-C class, its protocols,
6459   // superclasses, categories, implementation, etc.
6460   Results.EnterNewScope();
6461 
6462   // If this is a send-to-super, try to add the special "super" send
6463   // completion.
6464   if (IsSuper) {
6465     if (ObjCMethodDecl *SuperMethod =
6466             AddSuperSendCompletion(SemaRef, false, SelIdents, Results))
6467       Results.Ignore(SuperMethod);
6468   }
6469 
6470   // If we're inside an Objective-C method definition, prefer its selector to
6471   // others.
6472   if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
6473     Results.setPreferredSelector(CurMethod->getSelector());
6474 
6475   VisitedSelectorSet Selectors;
6476   if (CDecl)
6477     AddObjCMethods(CDecl, false, MK_Any, SelIdents, SemaRef.CurContext,
6478                    Selectors, AtArgumentExpression, Results);
6479   else {
6480     // We're messaging "id" as a type; provide all class/factory methods.
6481 
6482     // If we have an external source, load the entire class method
6483     // pool from the AST file.
6484     if (SemaRef.getExternalSource()) {
6485       for (uint32_t I = 0,
6486                     N = SemaRef.getExternalSource()->GetNumExternalSelectors();
6487            I != N; ++I) {
6488         Selector Sel = SemaRef.getExternalSource()->GetExternalSelector(I);
6489         if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
6490           continue;
6491 
6492         SemaRef.ReadMethodPool(Sel);
6493       }
6494     }
6495 
6496     for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
6497                                           MEnd = SemaRef.MethodPool.end();
6498          M != MEnd; ++M) {
6499       for (ObjCMethodList *MethList = &M->second.second;
6500            MethList && MethList->getMethod(); MethList = MethList->getNext()) {
6501         if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
6502           continue;
6503 
6504         Result R(MethList->getMethod(),
6505                  Results.getBasePriority(MethList->getMethod()), nullptr);
6506         R.StartParameter = SelIdents.size();
6507         R.AllParametersAreInformative = false;
6508         Results.MaybeAddResult(R, SemaRef.CurContext);
6509       }
6510     }
6511   }
6512 
6513   Results.ExitScope();
6514 }
6515 
6516 void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
6517                                         ArrayRef<IdentifierInfo *> SelIdents,
6518                                         bool AtArgumentExpression,
6519                                         bool IsSuper) {
6520 
6521   QualType T = this->GetTypeFromParser(Receiver);
6522 
6523   ResultBuilder Results(
6524       *this, CodeCompleter->getAllocator(),
6525       CodeCompleter->getCodeCompletionTUInfo(),
6526       CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage, T,
6527                             SelIdents));
6528 
6529   AddClassMessageCompletions(*this, S, Receiver, SelIdents,
6530                              AtArgumentExpression, IsSuper, Results);
6531 
6532   // If we're actually at the argument expression (rather than prior to the
6533   // selector), we're actually performing code completion for an expression.
6534   // Determine whether we have a single, best method. If so, we can
6535   // code-complete the expression using the corresponding parameter type as
6536   // our preferred type, improving completion results.
6537   if (AtArgumentExpression) {
6538     QualType PreferredType =
6539         getPreferredArgumentTypeForMessageSend(Results, SelIdents.size());
6540     if (PreferredType.isNull())
6541       CodeCompleteOrdinaryName(S, PCC_Expression);
6542     else
6543       CodeCompleteExpression(S, PreferredType);
6544     return;
6545   }
6546 
6547   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6548                             Results.data(), Results.size());
6549 }
6550 
6551 void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
6552                                            ArrayRef<IdentifierInfo *> SelIdents,
6553                                            bool AtArgumentExpression,
6554                                            ObjCInterfaceDecl *Super) {
6555   typedef CodeCompletionResult Result;
6556 
6557   Expr *RecExpr = static_cast<Expr *>(Receiver);
6558 
6559   // If necessary, apply function/array conversion to the receiver.
6560   // C99 6.7.5.3p[7,8].
6561   if (RecExpr) {
6562     ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
6563     if (Conv.isInvalid()) // conversion failed. bail.
6564       return;
6565     RecExpr = Conv.get();
6566   }
6567   QualType ReceiverType = RecExpr
6568                               ? RecExpr->getType()
6569                               : Super ? Context.getObjCObjectPointerType(
6570                                             Context.getObjCInterfaceType(Super))
6571                                       : Context.getObjCIdType();
6572 
6573   // If we're messaging an expression with type "id" or "Class", check
6574   // whether we know something special about the receiver that allows
6575   // us to assume a more-specific receiver type.
6576   if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) {
6577     if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
6578       if (ReceiverType->isObjCClassType())
6579         return CodeCompleteObjCClassMessage(
6580             S, ParsedType::make(Context.getObjCInterfaceType(IFace)), SelIdents,
6581             AtArgumentExpression, Super);
6582 
6583       ReceiverType =
6584           Context.getObjCObjectPointerType(Context.getObjCInterfaceType(IFace));
6585     }
6586   } else if (RecExpr && getLangOpts().CPlusPlus) {
6587     ExprResult Conv = PerformContextuallyConvertToObjCPointer(RecExpr);
6588     if (Conv.isUsable()) {
6589       RecExpr = Conv.get();
6590       ReceiverType = RecExpr->getType();
6591     }
6592   }
6593 
6594   // Build the set of methods we can see.
6595   ResultBuilder Results(
6596       *this, CodeCompleter->getAllocator(),
6597       CodeCompleter->getCodeCompletionTUInfo(),
6598       CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
6599                             ReceiverType, SelIdents));
6600 
6601   Results.EnterNewScope();
6602 
6603   // If this is a send-to-super, try to add the special "super" send
6604   // completion.
6605   if (Super) {
6606     if (ObjCMethodDecl *SuperMethod =
6607             AddSuperSendCompletion(*this, false, SelIdents, Results))
6608       Results.Ignore(SuperMethod);
6609   }
6610 
6611   // If we're inside an Objective-C method definition, prefer its selector to
6612   // others.
6613   if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
6614     Results.setPreferredSelector(CurMethod->getSelector());
6615 
6616   // Keep track of the selectors we've already added.
6617   VisitedSelectorSet Selectors;
6618 
6619   // Handle messages to Class. This really isn't a message to an instance
6620   // method, so we treat it the same way we would treat a message send to a
6621   // class method.
6622   if (ReceiverType->isObjCClassType() ||
6623       ReceiverType->isObjCQualifiedClassType()) {
6624     if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
6625       if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
6626         AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, CurContext,
6627                        Selectors, AtArgumentExpression, Results);
6628     }
6629   }
6630   // Handle messages to a qualified ID ("id<foo>").
6631   else if (const ObjCObjectPointerType *QualID =
6632                ReceiverType->getAsObjCQualifiedIdType()) {
6633     // Search protocols for instance methods.
6634     for (auto *I : QualID->quals())
6635       AddObjCMethods(I, true, MK_Any, SelIdents, CurContext, Selectors,
6636                      AtArgumentExpression, Results);
6637   }
6638   // Handle messages to a pointer to interface type.
6639   else if (const ObjCObjectPointerType *IFacePtr =
6640                ReceiverType->getAsObjCInterfacePointerType()) {
6641     // Search the class, its superclasses, etc., for instance methods.
6642     AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
6643                    CurContext, Selectors, AtArgumentExpression, Results);
6644 
6645     // Search protocols for instance methods.
6646     for (auto *I : IFacePtr->quals())
6647       AddObjCMethods(I, true, MK_Any, SelIdents, CurContext, Selectors,
6648                      AtArgumentExpression, Results);
6649   }
6650   // Handle messages to "id".
6651   else if (ReceiverType->isObjCIdType()) {
6652     // We're messaging "id", so provide all instance methods we know
6653     // about as code-completion results.
6654 
6655     // If we have an external source, load the entire class method
6656     // pool from the AST file.
6657     if (ExternalSource) {
6658       for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6659            I != N; ++I) {
6660         Selector Sel = ExternalSource->GetExternalSelector(I);
6661         if (Sel.isNull() || MethodPool.count(Sel))
6662           continue;
6663 
6664         ReadMethodPool(Sel);
6665       }
6666     }
6667 
6668     for (GlobalMethodPool::iterator M = MethodPool.begin(),
6669                                     MEnd = MethodPool.end();
6670          M != MEnd; ++M) {
6671       for (ObjCMethodList *MethList = &M->second.first;
6672            MethList && MethList->getMethod(); MethList = MethList->getNext()) {
6673         if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
6674           continue;
6675 
6676         if (!Selectors.insert(MethList->getMethod()->getSelector()).second)
6677           continue;
6678 
6679         Result R(MethList->getMethod(),
6680                  Results.getBasePriority(MethList->getMethod()), nullptr);
6681         R.StartParameter = SelIdents.size();
6682         R.AllParametersAreInformative = false;
6683         Results.MaybeAddResult(R, CurContext);
6684       }
6685     }
6686   }
6687   Results.ExitScope();
6688 
6689   // If we're actually at the argument expression (rather than prior to the
6690   // selector), we're actually performing code completion for an expression.
6691   // Determine whether we have a single, best method. If so, we can
6692   // code-complete the expression using the corresponding parameter type as
6693   // our preferred type, improving completion results.
6694   if (AtArgumentExpression) {
6695     QualType PreferredType =
6696         getPreferredArgumentTypeForMessageSend(Results, SelIdents.size());
6697     if (PreferredType.isNull())
6698       CodeCompleteOrdinaryName(S, PCC_Expression);
6699     else
6700       CodeCompleteExpression(S, PreferredType);
6701     return;
6702   }
6703 
6704   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6705                             Results.data(), Results.size());
6706 }
6707 
6708 void Sema::CodeCompleteObjCForCollection(Scope *S,
6709                                          DeclGroupPtrTy IterationVar) {
6710   CodeCompleteExpressionData Data;
6711   Data.ObjCCollection = true;
6712 
6713   if (IterationVar.getAsOpaquePtr()) {
6714     DeclGroupRef DG = IterationVar.get();
6715     for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
6716       if (*I)
6717         Data.IgnoreDecls.push_back(*I);
6718     }
6719   }
6720 
6721   CodeCompleteExpression(S, Data);
6722 }
6723 
6724 void Sema::CodeCompleteObjCSelector(Scope *S,
6725                                     ArrayRef<IdentifierInfo *> SelIdents) {
6726   // If we have an external source, load the entire class method
6727   // pool from the AST file.
6728   if (ExternalSource) {
6729     for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); I != N;
6730          ++I) {
6731       Selector Sel = ExternalSource->GetExternalSelector(I);
6732       if (Sel.isNull() || MethodPool.count(Sel))
6733         continue;
6734 
6735       ReadMethodPool(Sel);
6736     }
6737   }
6738 
6739   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6740                         CodeCompleter->getCodeCompletionTUInfo(),
6741                         CodeCompletionContext::CCC_SelectorName);
6742   Results.EnterNewScope();
6743   for (GlobalMethodPool::iterator M = MethodPool.begin(),
6744                                   MEnd = MethodPool.end();
6745        M != MEnd; ++M) {
6746 
6747     Selector Sel = M->first;
6748     if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents))
6749       continue;
6750 
6751     CodeCompletionBuilder Builder(Results.getAllocator(),
6752                                   Results.getCodeCompletionTUInfo());
6753     if (Sel.isUnarySelector()) {
6754       Builder.AddTypedTextChunk(
6755           Builder.getAllocator().CopyString(Sel.getNameForSlot(0)));
6756       Results.AddResult(Builder.TakeString());
6757       continue;
6758     }
6759 
6760     std::string Accumulator;
6761     for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
6762       if (I == SelIdents.size()) {
6763         if (!Accumulator.empty()) {
6764           Builder.AddInformativeChunk(
6765               Builder.getAllocator().CopyString(Accumulator));
6766           Accumulator.clear();
6767         }
6768       }
6769 
6770       Accumulator += Sel.getNameForSlot(I);
6771       Accumulator += ':';
6772     }
6773     Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(Accumulator));
6774     Results.AddResult(Builder.TakeString());
6775   }
6776   Results.ExitScope();
6777 
6778   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6779                             Results.data(), Results.size());
6780 }
6781 
6782 /// Add all of the protocol declarations that we find in the given
6783 /// (translation unit) context.
6784 static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
6785                                bool OnlyForwardDeclarations,
6786                                ResultBuilder &Results) {
6787   typedef CodeCompletionResult Result;
6788 
6789   for (const auto *D : Ctx->decls()) {
6790     // Record any protocols we find.
6791     if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(D))
6792       if (!OnlyForwardDeclarations || !Proto->hasDefinition())
6793         Results.AddResult(
6794             Result(Proto, Results.getBasePriority(Proto), nullptr), CurContext,
6795             nullptr, false);
6796   }
6797 }
6798 
6799 void Sema::CodeCompleteObjCProtocolReferences(
6800     ArrayRef<IdentifierLocPair> Protocols) {
6801   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6802                         CodeCompleter->getCodeCompletionTUInfo(),
6803                         CodeCompletionContext::CCC_ObjCProtocolName);
6804 
6805   if (CodeCompleter->includeGlobals()) {
6806     Results.EnterNewScope();
6807 
6808     // Tell the result set to ignore all of the protocols we have
6809     // already seen.
6810     // FIXME: This doesn't work when caching code-completion results.
6811     for (const IdentifierLocPair &Pair : Protocols)
6812       if (ObjCProtocolDecl *Protocol = LookupProtocol(Pair.first, Pair.second))
6813         Results.Ignore(Protocol);
6814 
6815     // Add all protocols.
6816     AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
6817                        Results);
6818 
6819     Results.ExitScope();
6820   }
6821 
6822   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6823                             Results.data(), Results.size());
6824 }
6825 
6826 void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
6827   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6828                         CodeCompleter->getCodeCompletionTUInfo(),
6829                         CodeCompletionContext::CCC_ObjCProtocolName);
6830 
6831   if (CodeCompleter->includeGlobals()) {
6832     Results.EnterNewScope();
6833 
6834     // Add all protocols.
6835     AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
6836                        Results);
6837 
6838     Results.ExitScope();
6839   }
6840 
6841   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6842                             Results.data(), Results.size());
6843 }
6844 
6845 /// Add all of the Objective-C interface declarations that we find in
6846 /// the given (translation unit) context.
6847 static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
6848                                 bool OnlyForwardDeclarations,
6849                                 bool OnlyUnimplemented,
6850                                 ResultBuilder &Results) {
6851   typedef CodeCompletionResult Result;
6852 
6853   for (const auto *D : Ctx->decls()) {
6854     // Record any interfaces we find.
6855     if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
6856       if ((!OnlyForwardDeclarations || !Class->hasDefinition()) &&
6857           (!OnlyUnimplemented || !Class->getImplementation()))
6858         Results.AddResult(
6859             Result(Class, Results.getBasePriority(Class), nullptr), CurContext,
6860             nullptr, false);
6861   }
6862 }
6863 
6864 void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
6865   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6866                         CodeCompleter->getCodeCompletionTUInfo(),
6867                         CodeCompletionContext::CCC_ObjCInterfaceName);
6868   Results.EnterNewScope();
6869 
6870   if (CodeCompleter->includeGlobals()) {
6871     // Add all classes.
6872     AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6873                         false, Results);
6874   }
6875 
6876   Results.ExitScope();
6877 
6878   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6879                             Results.data(), Results.size());
6880 }
6881 
6882 void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
6883                                       SourceLocation ClassNameLoc) {
6884   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6885                         CodeCompleter->getCodeCompletionTUInfo(),
6886                         CodeCompletionContext::CCC_ObjCInterfaceName);
6887   Results.EnterNewScope();
6888 
6889   // Make sure that we ignore the class we're currently defining.
6890   NamedDecl *CurClass =
6891       LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
6892   if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
6893     Results.Ignore(CurClass);
6894 
6895   if (CodeCompleter->includeGlobals()) {
6896     // Add all classes.
6897     AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6898                         false, Results);
6899   }
6900 
6901   Results.ExitScope();
6902 
6903   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6904                             Results.data(), Results.size());
6905 }
6906 
6907 void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
6908   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6909                         CodeCompleter->getCodeCompletionTUInfo(),
6910                         CodeCompletionContext::CCC_ObjCImplementation);
6911   Results.EnterNewScope();
6912 
6913   if (CodeCompleter->includeGlobals()) {
6914     // Add all unimplemented classes.
6915     AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6916                         true, Results);
6917   }
6918 
6919   Results.ExitScope();
6920 
6921   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6922                             Results.data(), Results.size());
6923 }
6924 
6925 void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
6926                                              IdentifierInfo *ClassName,
6927                                              SourceLocation ClassNameLoc) {
6928   typedef CodeCompletionResult Result;
6929 
6930   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6931                         CodeCompleter->getCodeCompletionTUInfo(),
6932                         CodeCompletionContext::CCC_ObjCCategoryName);
6933 
6934   // Ignore any categories we find that have already been implemented by this
6935   // interface.
6936   llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
6937   NamedDecl *CurClass =
6938       LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
6939   if (ObjCInterfaceDecl *Class =
6940           dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)) {
6941     for (const auto *Cat : Class->visible_categories())
6942       CategoryNames.insert(Cat->getIdentifier());
6943   }
6944 
6945   // Add all of the categories we know about.
6946   Results.EnterNewScope();
6947   TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
6948   for (const auto *D : TU->decls())
6949     if (const auto *Category = dyn_cast<ObjCCategoryDecl>(D))
6950       if (CategoryNames.insert(Category->getIdentifier()).second)
6951         Results.AddResult(
6952             Result(Category, Results.getBasePriority(Category), nullptr),
6953             CurContext, nullptr, false);
6954   Results.ExitScope();
6955 
6956   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6957                             Results.data(), Results.size());
6958 }
6959 
6960 void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
6961                                                   IdentifierInfo *ClassName,
6962                                                   SourceLocation ClassNameLoc) {
6963   typedef CodeCompletionResult Result;
6964 
6965   // Find the corresponding interface. If we couldn't find the interface, the
6966   // program itself is ill-formed. However, we'll try to be helpful still by
6967   // providing the list of all of the categories we know about.
6968   NamedDecl *CurClass =
6969       LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
6970   ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
6971   if (!Class)
6972     return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
6973 
6974   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6975                         CodeCompleter->getCodeCompletionTUInfo(),
6976                         CodeCompletionContext::CCC_ObjCCategoryName);
6977 
6978   // Add all of the categories that have have corresponding interface
6979   // declarations in this class and any of its superclasses, except for
6980   // already-implemented categories in the class itself.
6981   llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
6982   Results.EnterNewScope();
6983   bool IgnoreImplemented = true;
6984   while (Class) {
6985     for (const auto *Cat : Class->visible_categories()) {
6986       if ((!IgnoreImplemented || !Cat->getImplementation()) &&
6987           CategoryNames.insert(Cat->getIdentifier()).second)
6988         Results.AddResult(Result(Cat, Results.getBasePriority(Cat), nullptr),
6989                           CurContext, nullptr, false);
6990     }
6991 
6992     Class = Class->getSuperClass();
6993     IgnoreImplemented = false;
6994   }
6995   Results.ExitScope();
6996 
6997   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6998                             Results.data(), Results.size());
6999 }
7000 
7001 void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
7002   CodeCompletionContext CCContext(CodeCompletionContext::CCC_Other);
7003   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7004                         CodeCompleter->getCodeCompletionTUInfo(), CCContext);
7005 
7006   // Figure out where this @synthesize lives.
7007   ObjCContainerDecl *Container =
7008       dyn_cast_or_null<ObjCContainerDecl>(CurContext);
7009   if (!Container || (!isa<ObjCImplementationDecl>(Container) &&
7010                      !isa<ObjCCategoryImplDecl>(Container)))
7011     return;
7012 
7013   // Ignore any properties that have already been implemented.
7014   Container = getContainerDef(Container);
7015   for (const auto *D : Container->decls())
7016     if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D))
7017       Results.Ignore(PropertyImpl->getPropertyDecl());
7018 
7019   // Add any properties that we find.
7020   AddedPropertiesSet AddedProperties;
7021   Results.EnterNewScope();
7022   if (ObjCImplementationDecl *ClassImpl =
7023           dyn_cast<ObjCImplementationDecl>(Container))
7024     AddObjCProperties(CCContext, ClassImpl->getClassInterface(), false,
7025                       /*AllowNullaryMethods=*/false, CurContext,
7026                       AddedProperties, Results);
7027   else
7028     AddObjCProperties(CCContext,
7029                       cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
7030                       false, /*AllowNullaryMethods=*/false, CurContext,
7031                       AddedProperties, Results);
7032   Results.ExitScope();
7033 
7034   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7035                             Results.data(), Results.size());
7036 }
7037 
7038 void Sema::CodeCompleteObjCPropertySynthesizeIvar(
7039     Scope *S, IdentifierInfo *PropertyName) {
7040   typedef CodeCompletionResult Result;
7041   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7042                         CodeCompleter->getCodeCompletionTUInfo(),
7043                         CodeCompletionContext::CCC_Other);
7044 
7045   // Figure out where this @synthesize lives.
7046   ObjCContainerDecl *Container =
7047       dyn_cast_or_null<ObjCContainerDecl>(CurContext);
7048   if (!Container || (!isa<ObjCImplementationDecl>(Container) &&
7049                      !isa<ObjCCategoryImplDecl>(Container)))
7050     return;
7051 
7052   // Figure out which interface we're looking into.
7053   ObjCInterfaceDecl *Class = nullptr;
7054   if (ObjCImplementationDecl *ClassImpl =
7055           dyn_cast<ObjCImplementationDecl>(Container))
7056     Class = ClassImpl->getClassInterface();
7057   else
7058     Class = cast<ObjCCategoryImplDecl>(Container)
7059                 ->getCategoryDecl()
7060                 ->getClassInterface();
7061 
7062   // Determine the type of the property we're synthesizing.
7063   QualType PropertyType = Context.getObjCIdType();
7064   if (Class) {
7065     if (ObjCPropertyDecl *Property = Class->FindPropertyDeclaration(
7066             PropertyName, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
7067       PropertyType =
7068           Property->getType().getNonReferenceType().getUnqualifiedType();
7069 
7070       // Give preference to ivars
7071       Results.setPreferredType(PropertyType);
7072     }
7073   }
7074 
7075   // Add all of the instance variables in this class and its superclasses.
7076   Results.EnterNewScope();
7077   bool SawSimilarlyNamedIvar = false;
7078   std::string NameWithPrefix;
7079   NameWithPrefix += '_';
7080   NameWithPrefix += PropertyName->getName();
7081   std::string NameWithSuffix = PropertyName->getName().str();
7082   NameWithSuffix += '_';
7083   for (; Class; Class = Class->getSuperClass()) {
7084     for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
7085          Ivar = Ivar->getNextIvar()) {
7086       Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), nullptr),
7087                         CurContext, nullptr, false);
7088 
7089       // Determine whether we've seen an ivar with a name similar to the
7090       // property.
7091       if ((PropertyName == Ivar->getIdentifier() ||
7092            NameWithPrefix == Ivar->getName() ||
7093            NameWithSuffix == Ivar->getName())) {
7094         SawSimilarlyNamedIvar = true;
7095 
7096         // Reduce the priority of this result by one, to give it a slight
7097         // advantage over other results whose names don't match so closely.
7098         if (Results.size() &&
7099             Results.data()[Results.size() - 1].Kind ==
7100                 CodeCompletionResult::RK_Declaration &&
7101             Results.data()[Results.size() - 1].Declaration == Ivar)
7102           Results.data()[Results.size() - 1].Priority--;
7103       }
7104     }
7105   }
7106 
7107   if (!SawSimilarlyNamedIvar) {
7108     // Create ivar result _propName, that the user can use to synthesize
7109     // an ivar of the appropriate type.
7110     unsigned Priority = CCP_MemberDeclaration + 1;
7111     typedef CodeCompletionResult Result;
7112     CodeCompletionAllocator &Allocator = Results.getAllocator();
7113     CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(),
7114                                   Priority, CXAvailability_Available);
7115 
7116     PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
7117     Builder.AddResultTypeChunk(
7118         GetCompletionTypeString(PropertyType, Context, Policy, Allocator));
7119     Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
7120     Results.AddResult(
7121         Result(Builder.TakeString(), Priority, CXCursor_ObjCIvarDecl));
7122   }
7123 
7124   Results.ExitScope();
7125 
7126   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7127                             Results.data(), Results.size());
7128 }
7129 
7130 // Mapping from selectors to the methods that implement that selector, along
7131 // with the "in original class" flag.
7132 typedef llvm::DenseMap<Selector,
7133                        llvm::PointerIntPair<ObjCMethodDecl *, 1, bool>>
7134     KnownMethodsMap;
7135 
7136 /// Find all of the methods that reside in the given container
7137 /// (and its superclasses, protocols, etc.) that meet the given
7138 /// criteria. Insert those methods into the map of known methods,
7139 /// indexed by selector so they can be easily found.
7140 static void FindImplementableMethods(ASTContext &Context,
7141                                      ObjCContainerDecl *Container,
7142                                      Optional<bool> WantInstanceMethods,
7143                                      QualType ReturnType,
7144                                      KnownMethodsMap &KnownMethods,
7145                                      bool InOriginalClass = true) {
7146   if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
7147     // Make sure we have a definition; that's what we'll walk.
7148     if (!IFace->hasDefinition())
7149       return;
7150 
7151     IFace = IFace->getDefinition();
7152     Container = IFace;
7153 
7154     const ObjCList<ObjCProtocolDecl> &Protocols =
7155         IFace->getReferencedProtocols();
7156     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7157                                               E = Protocols.end();
7158          I != E; ++I)
7159       FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
7160                                KnownMethods, InOriginalClass);
7161 
7162     // Add methods from any class extensions and categories.
7163     for (auto *Cat : IFace->visible_categories()) {
7164       FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType,
7165                                KnownMethods, false);
7166     }
7167 
7168     // Visit the superclass.
7169     if (IFace->getSuperClass())
7170       FindImplementableMethods(Context, IFace->getSuperClass(),
7171                                WantInstanceMethods, ReturnType, KnownMethods,
7172                                false);
7173   }
7174 
7175   if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
7176     // Recurse into protocols.
7177     const ObjCList<ObjCProtocolDecl> &Protocols =
7178         Category->getReferencedProtocols();
7179     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7180                                               E = Protocols.end();
7181          I != E; ++I)
7182       FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
7183                                KnownMethods, InOriginalClass);
7184 
7185     // If this category is the original class, jump to the interface.
7186     if (InOriginalClass && Category->getClassInterface())
7187       FindImplementableMethods(Context, Category->getClassInterface(),
7188                                WantInstanceMethods, ReturnType, KnownMethods,
7189                                false);
7190   }
7191 
7192   if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
7193     // Make sure we have a definition; that's what we'll walk.
7194     if (!Protocol->hasDefinition())
7195       return;
7196     Protocol = Protocol->getDefinition();
7197     Container = Protocol;
7198 
7199     // Recurse into protocols.
7200     const ObjCList<ObjCProtocolDecl> &Protocols =
7201         Protocol->getReferencedProtocols();
7202     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7203                                               E = Protocols.end();
7204          I != E; ++I)
7205       FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
7206                                KnownMethods, false);
7207   }
7208 
7209   // Add methods in this container. This operation occurs last because
7210   // we want the methods from this container to override any methods
7211   // we've previously seen with the same selector.
7212   for (auto *M : Container->methods()) {
7213     if (!WantInstanceMethods || M->isInstanceMethod() == *WantInstanceMethods) {
7214       if (!ReturnType.isNull() &&
7215           !Context.hasSameUnqualifiedType(ReturnType, M->getReturnType()))
7216         continue;
7217 
7218       KnownMethods[M->getSelector()] =
7219           KnownMethodsMap::mapped_type(M, InOriginalClass);
7220     }
7221   }
7222 }
7223 
7224 /// Add the parenthesized return or parameter type chunk to a code
7225 /// completion string.
7226 static void AddObjCPassingTypeChunk(QualType Type, unsigned ObjCDeclQuals,
7227                                     ASTContext &Context,
7228                                     const PrintingPolicy &Policy,
7229                                     CodeCompletionBuilder &Builder) {
7230   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7231   std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals, Type);
7232   if (!Quals.empty())
7233     Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals));
7234   Builder.AddTextChunk(
7235       GetCompletionTypeString(Type, Context, Policy, Builder.getAllocator()));
7236   Builder.AddChunk(CodeCompletionString::CK_RightParen);
7237 }
7238 
7239 /// Determine whether the given class is or inherits from a class by
7240 /// the given name.
7241 static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class, StringRef Name) {
7242   if (!Class)
7243     return false;
7244 
7245   if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
7246     return true;
7247 
7248   return InheritsFromClassNamed(Class->getSuperClass(), Name);
7249 }
7250 
7251 /// Add code completions for Objective-C Key-Value Coding (KVC) and
7252 /// Key-Value Observing (KVO).
7253 static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
7254                                        bool IsInstanceMethod,
7255                                        QualType ReturnType, ASTContext &Context,
7256                                        VisitedSelectorSet &KnownSelectors,
7257                                        ResultBuilder &Results) {
7258   IdentifierInfo *PropName = Property->getIdentifier();
7259   if (!PropName || PropName->getLength() == 0)
7260     return;
7261 
7262   PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
7263 
7264   // Builder that will create each code completion.
7265   typedef CodeCompletionResult Result;
7266   CodeCompletionAllocator &Allocator = Results.getAllocator();
7267   CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
7268 
7269   // The selector table.
7270   SelectorTable &Selectors = Context.Selectors;
7271 
7272   // The property name, copied into the code completion allocation region
7273   // on demand.
7274   struct KeyHolder {
7275     CodeCompletionAllocator &Allocator;
7276     StringRef Key;
7277     const char *CopiedKey;
7278 
7279     KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
7280         : Allocator(Allocator), Key(Key), CopiedKey(nullptr) {}
7281 
7282     operator const char *() {
7283       if (CopiedKey)
7284         return CopiedKey;
7285 
7286       return CopiedKey = Allocator.CopyString(Key);
7287     }
7288   } Key(Allocator, PropName->getName());
7289 
7290   // The uppercased name of the property name.
7291   std::string UpperKey = PropName->getName();
7292   if (!UpperKey.empty())
7293     UpperKey[0] = toUppercase(UpperKey[0]);
7294 
7295   bool ReturnTypeMatchesProperty =
7296       ReturnType.isNull() ||
7297       Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
7298                                      Property->getType());
7299   bool ReturnTypeMatchesVoid = ReturnType.isNull() || ReturnType->isVoidType();
7300 
7301   // Add the normal accessor -(type)key.
7302   if (IsInstanceMethod &&
7303       KnownSelectors.insert(Selectors.getNullarySelector(PropName)).second &&
7304       ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
7305     if (ReturnType.isNull())
7306       AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, Context, Policy,
7307                               Builder);
7308 
7309     Builder.AddTypedTextChunk(Key);
7310     Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
7311                              CXCursor_ObjCInstanceMethodDecl));
7312   }
7313 
7314   // If we have an integral or boolean property (or the user has provided
7315   // an integral or boolean return type), add the accessor -(type)isKey.
7316   if (IsInstanceMethod &&
7317       ((!ReturnType.isNull() &&
7318         (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
7319        (ReturnType.isNull() && (Property->getType()->isIntegerType() ||
7320                                 Property->getType()->isBooleanType())))) {
7321     std::string SelectorName = (Twine("is") + UpperKey).str();
7322     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7323     if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
7324             .second) {
7325       if (ReturnType.isNull()) {
7326         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7327         Builder.AddTextChunk("BOOL");
7328         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7329       }
7330 
7331       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorId->getName()));
7332       Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
7333                                CXCursor_ObjCInstanceMethodDecl));
7334     }
7335   }
7336 
7337   // Add the normal mutator.
7338   if (IsInstanceMethod && ReturnTypeMatchesVoid &&
7339       !Property->getSetterMethodDecl()) {
7340     std::string SelectorName = (Twine("set") + UpperKey).str();
7341     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7342     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
7343       if (ReturnType.isNull()) {
7344         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7345         Builder.AddTextChunk("void");
7346         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7347       }
7348 
7349       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorId->getName()));
7350       Builder.AddTypedTextChunk(":");
7351       AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, Context, Policy,
7352                               Builder);
7353       Builder.AddTextChunk(Key);
7354       Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
7355                                CXCursor_ObjCInstanceMethodDecl));
7356     }
7357   }
7358 
7359   // Indexed and unordered accessors
7360   unsigned IndexedGetterPriority = CCP_CodePattern;
7361   unsigned IndexedSetterPriority = CCP_CodePattern;
7362   unsigned UnorderedGetterPriority = CCP_CodePattern;
7363   unsigned UnorderedSetterPriority = CCP_CodePattern;
7364   if (const auto *ObjCPointer =
7365           Property->getType()->getAs<ObjCObjectPointerType>()) {
7366     if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
7367       // If this interface type is not provably derived from a known
7368       // collection, penalize the corresponding completions.
7369       if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
7370         IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
7371         if (!InheritsFromClassNamed(IFace, "NSArray"))
7372           IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
7373       }
7374 
7375       if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
7376         UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
7377         if (!InheritsFromClassNamed(IFace, "NSSet"))
7378           UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
7379       }
7380     }
7381   } else {
7382     IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
7383     IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
7384     UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
7385     UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
7386   }
7387 
7388   // Add -(NSUInteger)countOf<key>
7389   if (IsInstanceMethod &&
7390       (ReturnType.isNull() || ReturnType->isIntegerType())) {
7391     std::string SelectorName = (Twine("countOf") + UpperKey).str();
7392     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7393     if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
7394             .second) {
7395       if (ReturnType.isNull()) {
7396         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7397         Builder.AddTextChunk("NSUInteger");
7398         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7399       }
7400 
7401       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorId->getName()));
7402       Results.AddResult(
7403           Result(Builder.TakeString(),
7404                  std::min(IndexedGetterPriority, UnorderedGetterPriority),
7405                  CXCursor_ObjCInstanceMethodDecl));
7406     }
7407   }
7408 
7409   // Indexed getters
7410   // Add -(id)objectInKeyAtIndex:(NSUInteger)index
7411   if (IsInstanceMethod &&
7412       (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
7413     std::string SelectorName = (Twine("objectIn") + UpperKey + "AtIndex").str();
7414     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7415     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
7416       if (ReturnType.isNull()) {
7417         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7418         Builder.AddTextChunk("id");
7419         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7420       }
7421 
7422       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7423       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7424       Builder.AddTextChunk("NSUInteger");
7425       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7426       Builder.AddTextChunk("index");
7427       Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
7428                                CXCursor_ObjCInstanceMethodDecl));
7429     }
7430   }
7431 
7432   // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
7433   if (IsInstanceMethod &&
7434       (ReturnType.isNull() ||
7435        (ReturnType->isObjCObjectPointerType() &&
7436         ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
7437         ReturnType->getAs<ObjCObjectPointerType>()
7438                 ->getInterfaceDecl()
7439                 ->getName() == "NSArray"))) {
7440     std::string SelectorName = (Twine(Property->getName()) + "AtIndexes").str();
7441     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7442     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
7443       if (ReturnType.isNull()) {
7444         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7445         Builder.AddTextChunk("NSArray *");
7446         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7447       }
7448 
7449       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7450       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7451       Builder.AddTextChunk("NSIndexSet *");
7452       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7453       Builder.AddTextChunk("indexes");
7454       Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
7455                                CXCursor_ObjCInstanceMethodDecl));
7456     }
7457   }
7458 
7459   // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
7460   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7461     std::string SelectorName = (Twine("get") + UpperKey).str();
7462     IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName),
7463                                       &Context.Idents.get("range")};
7464 
7465     if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
7466       if (ReturnType.isNull()) {
7467         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7468         Builder.AddTextChunk("void");
7469         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7470       }
7471 
7472       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7473       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7474       Builder.AddPlaceholderChunk("object-type");
7475       Builder.AddTextChunk(" **");
7476       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7477       Builder.AddTextChunk("buffer");
7478       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7479       Builder.AddTypedTextChunk("range:");
7480       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7481       Builder.AddTextChunk("NSRange");
7482       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7483       Builder.AddTextChunk("inRange");
7484       Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
7485                                CXCursor_ObjCInstanceMethodDecl));
7486     }
7487   }
7488 
7489   // Mutable indexed accessors
7490 
7491   // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
7492   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7493     std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
7494     IdentifierInfo *SelectorIds[2] = {&Context.Idents.get("insertObject"),
7495                                       &Context.Idents.get(SelectorName)};
7496 
7497     if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
7498       if (ReturnType.isNull()) {
7499         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7500         Builder.AddTextChunk("void");
7501         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7502       }
7503 
7504       Builder.AddTypedTextChunk("insertObject:");
7505       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7506       Builder.AddPlaceholderChunk("object-type");
7507       Builder.AddTextChunk(" *");
7508       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7509       Builder.AddTextChunk("object");
7510       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7511       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7512       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7513       Builder.AddPlaceholderChunk("NSUInteger");
7514       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7515       Builder.AddTextChunk("index");
7516       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7517                                CXCursor_ObjCInstanceMethodDecl));
7518     }
7519   }
7520 
7521   // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
7522   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7523     std::string SelectorName = (Twine("insert") + UpperKey).str();
7524     IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName),
7525                                       &Context.Idents.get("atIndexes")};
7526 
7527     if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
7528       if (ReturnType.isNull()) {
7529         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7530         Builder.AddTextChunk("void");
7531         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7532       }
7533 
7534       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7535       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7536       Builder.AddTextChunk("NSArray *");
7537       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7538       Builder.AddTextChunk("array");
7539       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7540       Builder.AddTypedTextChunk("atIndexes:");
7541       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7542       Builder.AddPlaceholderChunk("NSIndexSet *");
7543       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7544       Builder.AddTextChunk("indexes");
7545       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7546                                CXCursor_ObjCInstanceMethodDecl));
7547     }
7548   }
7549 
7550   // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
7551   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7552     std::string SelectorName =
7553         (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
7554     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7555     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
7556       if (ReturnType.isNull()) {
7557         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7558         Builder.AddTextChunk("void");
7559         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7560       }
7561 
7562       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7563       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7564       Builder.AddTextChunk("NSUInteger");
7565       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7566       Builder.AddTextChunk("index");
7567       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7568                                CXCursor_ObjCInstanceMethodDecl));
7569     }
7570   }
7571 
7572   // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
7573   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7574     std::string SelectorName = (Twine("remove") + UpperKey + "AtIndexes").str();
7575     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7576     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
7577       if (ReturnType.isNull()) {
7578         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7579         Builder.AddTextChunk("void");
7580         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7581       }
7582 
7583       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7584       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7585       Builder.AddTextChunk("NSIndexSet *");
7586       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7587       Builder.AddTextChunk("indexes");
7588       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7589                                CXCursor_ObjCInstanceMethodDecl));
7590     }
7591   }
7592 
7593   // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
7594   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7595     std::string SelectorName =
7596         (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
7597     IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName),
7598                                       &Context.Idents.get("withObject")};
7599 
7600     if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
7601       if (ReturnType.isNull()) {
7602         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7603         Builder.AddTextChunk("void");
7604         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7605       }
7606 
7607       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7608       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7609       Builder.AddPlaceholderChunk("NSUInteger");
7610       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7611       Builder.AddTextChunk("index");
7612       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7613       Builder.AddTypedTextChunk("withObject:");
7614       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7615       Builder.AddTextChunk("id");
7616       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7617       Builder.AddTextChunk("object");
7618       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7619                                CXCursor_ObjCInstanceMethodDecl));
7620     }
7621   }
7622 
7623   // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
7624   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7625     std::string SelectorName1 =
7626         (Twine("replace") + UpperKey + "AtIndexes").str();
7627     std::string SelectorName2 = (Twine("with") + UpperKey).str();
7628     IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName1),
7629                                       &Context.Idents.get(SelectorName2)};
7630 
7631     if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
7632       if (ReturnType.isNull()) {
7633         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7634         Builder.AddTextChunk("void");
7635         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7636       }
7637 
7638       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
7639       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7640       Builder.AddPlaceholderChunk("NSIndexSet *");
7641       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7642       Builder.AddTextChunk("indexes");
7643       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7644       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
7645       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7646       Builder.AddTextChunk("NSArray *");
7647       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7648       Builder.AddTextChunk("array");
7649       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7650                                CXCursor_ObjCInstanceMethodDecl));
7651     }
7652   }
7653 
7654   // Unordered getters
7655   // - (NSEnumerator *)enumeratorOfKey
7656   if (IsInstanceMethod &&
7657       (ReturnType.isNull() ||
7658        (ReturnType->isObjCObjectPointerType() &&
7659         ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
7660         ReturnType->getAs<ObjCObjectPointerType>()
7661                 ->getInterfaceDecl()
7662                 ->getName() == "NSEnumerator"))) {
7663     std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
7664     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7665     if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
7666             .second) {
7667       if (ReturnType.isNull()) {
7668         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7669         Builder.AddTextChunk("NSEnumerator *");
7670         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7671       }
7672 
7673       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
7674       Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
7675                                CXCursor_ObjCInstanceMethodDecl));
7676     }
7677   }
7678 
7679   // - (type *)memberOfKey:(type *)object
7680   if (IsInstanceMethod &&
7681       (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
7682     std::string SelectorName = (Twine("memberOf") + UpperKey).str();
7683     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7684     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
7685       if (ReturnType.isNull()) {
7686         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7687         Builder.AddPlaceholderChunk("object-type");
7688         Builder.AddTextChunk(" *");
7689         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7690       }
7691 
7692       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7693       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7694       if (ReturnType.isNull()) {
7695         Builder.AddPlaceholderChunk("object-type");
7696         Builder.AddTextChunk(" *");
7697       } else {
7698         Builder.AddTextChunk(GetCompletionTypeString(
7699             ReturnType, Context, Policy, Builder.getAllocator()));
7700       }
7701       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7702       Builder.AddTextChunk("object");
7703       Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
7704                                CXCursor_ObjCInstanceMethodDecl));
7705     }
7706   }
7707 
7708   // Mutable unordered accessors
7709   // - (void)addKeyObject:(type *)object
7710   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7711     std::string SelectorName =
7712         (Twine("add") + UpperKey + Twine("Object")).str();
7713     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7714     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
7715       if (ReturnType.isNull()) {
7716         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7717         Builder.AddTextChunk("void");
7718         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7719       }
7720 
7721       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7722       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7723       Builder.AddPlaceholderChunk("object-type");
7724       Builder.AddTextChunk(" *");
7725       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7726       Builder.AddTextChunk("object");
7727       Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7728                                CXCursor_ObjCInstanceMethodDecl));
7729     }
7730   }
7731 
7732   // - (void)addKey:(NSSet *)objects
7733   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7734     std::string SelectorName = (Twine("add") + UpperKey).str();
7735     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7736     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
7737       if (ReturnType.isNull()) {
7738         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7739         Builder.AddTextChunk("void");
7740         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7741       }
7742 
7743       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7744       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7745       Builder.AddTextChunk("NSSet *");
7746       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7747       Builder.AddTextChunk("objects");
7748       Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7749                                CXCursor_ObjCInstanceMethodDecl));
7750     }
7751   }
7752 
7753   // - (void)removeKeyObject:(type *)object
7754   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7755     std::string SelectorName =
7756         (Twine("remove") + UpperKey + Twine("Object")).str();
7757     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7758     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
7759       if (ReturnType.isNull()) {
7760         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7761         Builder.AddTextChunk("void");
7762         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7763       }
7764 
7765       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7766       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7767       Builder.AddPlaceholderChunk("object-type");
7768       Builder.AddTextChunk(" *");
7769       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7770       Builder.AddTextChunk("object");
7771       Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7772                                CXCursor_ObjCInstanceMethodDecl));
7773     }
7774   }
7775 
7776   // - (void)removeKey:(NSSet *)objects
7777   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7778     std::string SelectorName = (Twine("remove") + UpperKey).str();
7779     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7780     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
7781       if (ReturnType.isNull()) {
7782         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7783         Builder.AddTextChunk("void");
7784         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7785       }
7786 
7787       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7788       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7789       Builder.AddTextChunk("NSSet *");
7790       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7791       Builder.AddTextChunk("objects");
7792       Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7793                                CXCursor_ObjCInstanceMethodDecl));
7794     }
7795   }
7796 
7797   // - (void)intersectKey:(NSSet *)objects
7798   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7799     std::string SelectorName = (Twine("intersect") + UpperKey).str();
7800     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7801     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
7802       if (ReturnType.isNull()) {
7803         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7804         Builder.AddTextChunk("void");
7805         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7806       }
7807 
7808       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7809       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7810       Builder.AddTextChunk("NSSet *");
7811       Builder.AddChunk(CodeCompletionString::CK_RightParen);
7812       Builder.AddTextChunk("objects");
7813       Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7814                                CXCursor_ObjCInstanceMethodDecl));
7815     }
7816   }
7817 
7818   // Key-Value Observing
7819   // + (NSSet *)keyPathsForValuesAffectingKey
7820   if (!IsInstanceMethod &&
7821       (ReturnType.isNull() ||
7822        (ReturnType->isObjCObjectPointerType() &&
7823         ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
7824         ReturnType->getAs<ObjCObjectPointerType>()
7825                 ->getInterfaceDecl()
7826                 ->getName() == "NSSet"))) {
7827     std::string SelectorName =
7828         (Twine("keyPathsForValuesAffecting") + UpperKey).str();
7829     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7830     if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
7831             .second) {
7832       if (ReturnType.isNull()) {
7833         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7834         Builder.AddTextChunk("NSSet<NSString *> *");
7835         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7836       }
7837 
7838       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
7839       Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
7840                                CXCursor_ObjCClassMethodDecl));
7841     }
7842   }
7843 
7844   // + (BOOL)automaticallyNotifiesObserversForKey
7845   if (!IsInstanceMethod &&
7846       (ReturnType.isNull() || ReturnType->isIntegerType() ||
7847        ReturnType->isBooleanType())) {
7848     std::string SelectorName =
7849         (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
7850     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7851     if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
7852             .second) {
7853       if (ReturnType.isNull()) {
7854         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7855         Builder.AddTextChunk("BOOL");
7856         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7857       }
7858 
7859       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
7860       Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
7861                                CXCursor_ObjCClassMethodDecl));
7862     }
7863   }
7864 }
7865 
7866 void Sema::CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod,
7867                                       ParsedType ReturnTy) {
7868   // Determine the return type of the method we're declaring, if
7869   // provided.
7870   QualType ReturnType = GetTypeFromParser(ReturnTy);
7871   Decl *IDecl = nullptr;
7872   if (CurContext->isObjCContainer()) {
7873     ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
7874     IDecl = OCD;
7875   }
7876   // Determine where we should start searching for methods.
7877   ObjCContainerDecl *SearchDecl = nullptr;
7878   bool IsInImplementation = false;
7879   if (Decl *D = IDecl) {
7880     if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
7881       SearchDecl = Impl->getClassInterface();
7882       IsInImplementation = true;
7883     } else if (ObjCCategoryImplDecl *CatImpl =
7884                    dyn_cast<ObjCCategoryImplDecl>(D)) {
7885       SearchDecl = CatImpl->getCategoryDecl();
7886       IsInImplementation = true;
7887     } else
7888       SearchDecl = dyn_cast<ObjCContainerDecl>(D);
7889   }
7890 
7891   if (!SearchDecl && S) {
7892     if (DeclContext *DC = S->getEntity())
7893       SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
7894   }
7895 
7896   if (!SearchDecl) {
7897     HandleCodeCompleteResults(this, CodeCompleter,
7898                               CodeCompletionContext::CCC_Other, nullptr, 0);
7899     return;
7900   }
7901 
7902   // Find all of the methods that we could declare/implement here.
7903   KnownMethodsMap KnownMethods;
7904   FindImplementableMethods(Context, SearchDecl, IsInstanceMethod, ReturnType,
7905                            KnownMethods);
7906 
7907   // Add declarations or definitions for each of the known methods.
7908   typedef CodeCompletionResult Result;
7909   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7910                         CodeCompleter->getCodeCompletionTUInfo(),
7911                         CodeCompletionContext::CCC_Other);
7912   Results.EnterNewScope();
7913   PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
7914   for (KnownMethodsMap::iterator M = KnownMethods.begin(),
7915                                  MEnd = KnownMethods.end();
7916        M != MEnd; ++M) {
7917     ObjCMethodDecl *Method = M->second.getPointer();
7918     CodeCompletionBuilder Builder(Results.getAllocator(),
7919                                   Results.getCodeCompletionTUInfo());
7920 
7921     // Add the '-'/'+' prefix if it wasn't provided yet.
7922     if (!IsInstanceMethod) {
7923       Builder.AddTextChunk(Method->isInstanceMethod() ? "-" : "+");
7924       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7925     }
7926 
7927     // If the result type was not already provided, add it to the
7928     // pattern as (type).
7929     if (ReturnType.isNull()) {
7930       QualType ResTy = Method->getSendResultType().stripObjCKindOfType(Context);
7931       AttributedType::stripOuterNullability(ResTy);
7932       AddObjCPassingTypeChunk(ResTy, Method->getObjCDeclQualifier(), Context,
7933                               Policy, Builder);
7934     }
7935 
7936     Selector Sel = Method->getSelector();
7937 
7938     // Add the first part of the selector to the pattern.
7939     Builder.AddTypedTextChunk(
7940         Builder.getAllocator().CopyString(Sel.getNameForSlot(0)));
7941 
7942     // Add parameters to the pattern.
7943     unsigned I = 0;
7944     for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
7945                                         PEnd = Method->param_end();
7946          P != PEnd; (void)++P, ++I) {
7947       // Add the part of the selector name.
7948       if (I == 0)
7949         Builder.AddTypedTextChunk(":");
7950       else if (I < Sel.getNumArgs()) {
7951         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7952         Builder.AddTypedTextChunk(
7953             Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
7954       } else
7955         break;
7956 
7957       // Add the parameter type.
7958       QualType ParamType;
7959       if ((*P)->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
7960         ParamType = (*P)->getType();
7961       else
7962         ParamType = (*P)->getOriginalType();
7963       ParamType = ParamType.substObjCTypeArgs(
7964           Context, {}, ObjCSubstitutionContext::Parameter);
7965       AttributedType::stripOuterNullability(ParamType);
7966       AddObjCPassingTypeChunk(ParamType, (*P)->getObjCDeclQualifier(), Context,
7967                               Policy, Builder);
7968 
7969       if (IdentifierInfo *Id = (*P)->getIdentifier())
7970         Builder.AddTextChunk(Builder.getAllocator().CopyString(Id->getName()));
7971     }
7972 
7973     if (Method->isVariadic()) {
7974       if (Method->param_size() > 0)
7975         Builder.AddChunk(CodeCompletionString::CK_Comma);
7976       Builder.AddTextChunk("...");
7977     }
7978 
7979     if (IsInImplementation && Results.includeCodePatterns()) {
7980       // We will be defining the method here, so add a compound statement.
7981       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7982       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
7983       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
7984       if (!Method->getReturnType()->isVoidType()) {
7985         // If the result type is not void, add a return clause.
7986         Builder.AddTextChunk("return");
7987         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7988         Builder.AddPlaceholderChunk("expression");
7989         Builder.AddChunk(CodeCompletionString::CK_SemiColon);
7990       } else
7991         Builder.AddPlaceholderChunk("statements");
7992 
7993       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
7994       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
7995     }
7996 
7997     unsigned Priority = CCP_CodePattern;
7998     auto R = Result(Builder.TakeString(), Method, Priority);
7999     if (!M->second.getInt())
8000       setInBaseClass(R);
8001     Results.AddResult(std::move(R));
8002   }
8003 
8004   // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
8005   // the properties in this class and its categories.
8006   if (Context.getLangOpts().ObjC) {
8007     SmallVector<ObjCContainerDecl *, 4> Containers;
8008     Containers.push_back(SearchDecl);
8009 
8010     VisitedSelectorSet KnownSelectors;
8011     for (KnownMethodsMap::iterator M = KnownMethods.begin(),
8012                                    MEnd = KnownMethods.end();
8013          M != MEnd; ++M)
8014       KnownSelectors.insert(M->first);
8015 
8016     ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
8017     if (!IFace)
8018       if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
8019         IFace = Category->getClassInterface();
8020 
8021     if (IFace)
8022       for (auto *Cat : IFace->visible_categories())
8023         Containers.push_back(Cat);
8024 
8025     if (IsInstanceMethod) {
8026       for (unsigned I = 0, N = Containers.size(); I != N; ++I)
8027         for (auto *P : Containers[I]->instance_properties())
8028           AddObjCKeyValueCompletions(P, *IsInstanceMethod, ReturnType, Context,
8029                                      KnownSelectors, Results);
8030     }
8031   }
8032 
8033   Results.ExitScope();
8034 
8035   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8036                             Results.data(), Results.size());
8037 }
8038 
8039 void Sema::CodeCompleteObjCMethodDeclSelector(
8040     Scope *S, bool IsInstanceMethod, bool AtParameterName, ParsedType ReturnTy,
8041     ArrayRef<IdentifierInfo *> SelIdents) {
8042   // If we have an external source, load the entire class method
8043   // pool from the AST file.
8044   if (ExternalSource) {
8045     for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); I != N;
8046          ++I) {
8047       Selector Sel = ExternalSource->GetExternalSelector(I);
8048       if (Sel.isNull() || MethodPool.count(Sel))
8049         continue;
8050 
8051       ReadMethodPool(Sel);
8052     }
8053   }
8054 
8055   // Build the set of methods we can see.
8056   typedef CodeCompletionResult Result;
8057   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8058                         CodeCompleter->getCodeCompletionTUInfo(),
8059                         CodeCompletionContext::CCC_Other);
8060 
8061   if (ReturnTy)
8062     Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
8063 
8064   Results.EnterNewScope();
8065   for (GlobalMethodPool::iterator M = MethodPool.begin(),
8066                                   MEnd = MethodPool.end();
8067        M != MEnd; ++M) {
8068     for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first
8069                                                      : &M->second.second;
8070          MethList && MethList->getMethod(); MethList = MethList->getNext()) {
8071       if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
8072         continue;
8073 
8074       if (AtParameterName) {
8075         // Suggest parameter names we've seen before.
8076         unsigned NumSelIdents = SelIdents.size();
8077         if (NumSelIdents &&
8078             NumSelIdents <= MethList->getMethod()->param_size()) {
8079           ParmVarDecl *Param =
8080               MethList->getMethod()->parameters()[NumSelIdents - 1];
8081           if (Param->getIdentifier()) {
8082             CodeCompletionBuilder Builder(Results.getAllocator(),
8083                                           Results.getCodeCompletionTUInfo());
8084             Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
8085                 Param->getIdentifier()->getName()));
8086             Results.AddResult(Builder.TakeString());
8087           }
8088         }
8089 
8090         continue;
8091       }
8092 
8093       Result R(MethList->getMethod(),
8094                Results.getBasePriority(MethList->getMethod()), nullptr);
8095       R.StartParameter = SelIdents.size();
8096       R.AllParametersAreInformative = false;
8097       R.DeclaringEntity = true;
8098       Results.MaybeAddResult(R, CurContext);
8099     }
8100   }
8101 
8102   Results.ExitScope();
8103 
8104   if (!AtParameterName && !SelIdents.empty() &&
8105       SelIdents.front()->getName().startswith("init")) {
8106     for (const auto &M : PP.macros()) {
8107       if (M.first->getName() != "NS_DESIGNATED_INITIALIZER")
8108         continue;
8109       Results.EnterNewScope();
8110       CodeCompletionBuilder Builder(Results.getAllocator(),
8111                                     Results.getCodeCompletionTUInfo());
8112       Builder.AddTypedTextChunk(
8113           Builder.getAllocator().CopyString(M.first->getName()));
8114       Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_Macro,
8115                                              CXCursor_MacroDefinition));
8116       Results.ExitScope();
8117     }
8118   }
8119 
8120   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8121                             Results.data(), Results.size());
8122 }
8123 
8124 void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
8125   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8126                         CodeCompleter->getCodeCompletionTUInfo(),
8127                         CodeCompletionContext::CCC_PreprocessorDirective);
8128   Results.EnterNewScope();
8129 
8130   // #if <condition>
8131   CodeCompletionBuilder Builder(Results.getAllocator(),
8132                                 Results.getCodeCompletionTUInfo());
8133   Builder.AddTypedTextChunk("if");
8134   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
8135   Builder.AddPlaceholderChunk("condition");
8136   Results.AddResult(Builder.TakeString());
8137 
8138   // #ifdef <macro>
8139   Builder.AddTypedTextChunk("ifdef");
8140   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
8141   Builder.AddPlaceholderChunk("macro");
8142   Results.AddResult(Builder.TakeString());
8143 
8144   // #ifndef <macro>
8145   Builder.AddTypedTextChunk("ifndef");
8146   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
8147   Builder.AddPlaceholderChunk("macro");
8148   Results.AddResult(Builder.TakeString());
8149 
8150   if (InConditional) {
8151     // #elif <condition>
8152     Builder.AddTypedTextChunk("elif");
8153     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
8154     Builder.AddPlaceholderChunk("condition");
8155     Results.AddResult(Builder.TakeString());
8156 
8157     // #else
8158     Builder.AddTypedTextChunk("else");
8159     Results.AddResult(Builder.TakeString());
8160 
8161     // #endif
8162     Builder.AddTypedTextChunk("endif");
8163     Results.AddResult(Builder.TakeString());
8164   }
8165 
8166   // #include "header"
8167   Builder.AddTypedTextChunk("include");
8168   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
8169   Builder.AddTextChunk("\"");
8170   Builder.AddPlaceholderChunk("header");
8171   Builder.AddTextChunk("\"");
8172   Results.AddResult(Builder.TakeString());
8173 
8174   // #include <header>
8175   Builder.AddTypedTextChunk("include");
8176   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
8177   Builder.AddTextChunk("<");
8178   Builder.AddPlaceholderChunk("header");
8179   Builder.AddTextChunk(">");
8180   Results.AddResult(Builder.TakeString());
8181 
8182   // #define <macro>
8183   Builder.AddTypedTextChunk("define");
8184   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
8185   Builder.AddPlaceholderChunk("macro");
8186   Results.AddResult(Builder.TakeString());
8187 
8188   // #define <macro>(<args>)
8189   Builder.AddTypedTextChunk("define");
8190   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
8191   Builder.AddPlaceholderChunk("macro");
8192   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
8193   Builder.AddPlaceholderChunk("args");
8194   Builder.AddChunk(CodeCompletionString::CK_RightParen);
8195   Results.AddResult(Builder.TakeString());
8196 
8197   // #undef <macro>
8198   Builder.AddTypedTextChunk("undef");
8199   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
8200   Builder.AddPlaceholderChunk("macro");
8201   Results.AddResult(Builder.TakeString());
8202 
8203   // #line <number>
8204   Builder.AddTypedTextChunk("line");
8205   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
8206   Builder.AddPlaceholderChunk("number");
8207   Results.AddResult(Builder.TakeString());
8208 
8209   // #line <number> "filename"
8210   Builder.AddTypedTextChunk("line");
8211   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
8212   Builder.AddPlaceholderChunk("number");
8213   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
8214   Builder.AddTextChunk("\"");
8215   Builder.AddPlaceholderChunk("filename");
8216   Builder.AddTextChunk("\"");
8217   Results.AddResult(Builder.TakeString());
8218 
8219   // #error <message>
8220   Builder.AddTypedTextChunk("error");
8221   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
8222   Builder.AddPlaceholderChunk("message");
8223   Results.AddResult(Builder.TakeString());
8224 
8225   // #pragma <arguments>
8226   Builder.AddTypedTextChunk("pragma");
8227   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
8228   Builder.AddPlaceholderChunk("arguments");
8229   Results.AddResult(Builder.TakeString());
8230 
8231   if (getLangOpts().ObjC) {
8232     // #import "header"
8233     Builder.AddTypedTextChunk("import");
8234     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
8235     Builder.AddTextChunk("\"");
8236     Builder.AddPlaceholderChunk("header");
8237     Builder.AddTextChunk("\"");
8238     Results.AddResult(Builder.TakeString());
8239 
8240     // #import <header>
8241     Builder.AddTypedTextChunk("import");
8242     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
8243     Builder.AddTextChunk("<");
8244     Builder.AddPlaceholderChunk("header");
8245     Builder.AddTextChunk(">");
8246     Results.AddResult(Builder.TakeString());
8247   }
8248 
8249   // #include_next "header"
8250   Builder.AddTypedTextChunk("include_next");
8251   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
8252   Builder.AddTextChunk("\"");
8253   Builder.AddPlaceholderChunk("header");
8254   Builder.AddTextChunk("\"");
8255   Results.AddResult(Builder.TakeString());
8256 
8257   // #include_next <header>
8258   Builder.AddTypedTextChunk("include_next");
8259   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
8260   Builder.AddTextChunk("<");
8261   Builder.AddPlaceholderChunk("header");
8262   Builder.AddTextChunk(">");
8263   Results.AddResult(Builder.TakeString());
8264 
8265   // #warning <message>
8266   Builder.AddTypedTextChunk("warning");
8267   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
8268   Builder.AddPlaceholderChunk("message");
8269   Results.AddResult(Builder.TakeString());
8270 
8271   // Note: #ident and #sccs are such crazy anachronisms that we don't provide
8272   // completions for them. And __include_macros is a Clang-internal extension
8273   // that we don't want to encourage anyone to use.
8274 
8275   // FIXME: we don't support #assert or #unassert, so don't suggest them.
8276   Results.ExitScope();
8277 
8278   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8279                             Results.data(), Results.size());
8280 }
8281 
8282 void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
8283   CodeCompleteOrdinaryName(S, S->getFnParent() ? Sema::PCC_RecoveryInFunction
8284                                                : Sema::PCC_Namespace);
8285 }
8286 
8287 void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
8288   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8289                         CodeCompleter->getCodeCompletionTUInfo(),
8290                         IsDefinition ? CodeCompletionContext::CCC_MacroName
8291                                      : CodeCompletionContext::CCC_MacroNameUse);
8292   if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
8293     // Add just the names of macros, not their arguments.
8294     CodeCompletionBuilder Builder(Results.getAllocator(),
8295                                   Results.getCodeCompletionTUInfo());
8296     Results.EnterNewScope();
8297     for (Preprocessor::macro_iterator M = PP.macro_begin(),
8298                                       MEnd = PP.macro_end();
8299          M != MEnd; ++M) {
8300       Builder.AddTypedTextChunk(
8301           Builder.getAllocator().CopyString(M->first->getName()));
8302       Results.AddResult(CodeCompletionResult(
8303           Builder.TakeString(), CCP_CodePattern, CXCursor_MacroDefinition));
8304     }
8305     Results.ExitScope();
8306   } else if (IsDefinition) {
8307     // FIXME: Can we detect when the user just wrote an include guard above?
8308   }
8309 
8310   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8311                             Results.data(), Results.size());
8312 }
8313 
8314 void Sema::CodeCompletePreprocessorExpression() {
8315   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8316                         CodeCompleter->getCodeCompletionTUInfo(),
8317                         CodeCompletionContext::CCC_PreprocessorExpression);
8318 
8319   if (!CodeCompleter || CodeCompleter->includeMacros())
8320     AddMacroResults(PP, Results,
8321                     CodeCompleter ? CodeCompleter->loadExternal() : false,
8322                     true);
8323 
8324   // defined (<macro>)
8325   Results.EnterNewScope();
8326   CodeCompletionBuilder Builder(Results.getAllocator(),
8327                                 Results.getCodeCompletionTUInfo());
8328   Builder.AddTypedTextChunk("defined");
8329   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
8330   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
8331   Builder.AddPlaceholderChunk("macro");
8332   Builder.AddChunk(CodeCompletionString::CK_RightParen);
8333   Results.AddResult(Builder.TakeString());
8334   Results.ExitScope();
8335 
8336   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8337                             Results.data(), Results.size());
8338 }
8339 
8340 void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
8341                                                  IdentifierInfo *Macro,
8342                                                  MacroInfo *MacroInfo,
8343                                                  unsigned Argument) {
8344   // FIXME: In the future, we could provide "overload" results, much like we
8345   // do for function calls.
8346 
8347   // Now just ignore this. There will be another code-completion callback
8348   // for the expanded tokens.
8349 }
8350 
8351 // This handles completion inside an #include filename, e.g. #include <foo/ba
8352 // We look for the directory "foo" under each directory on the include path,
8353 // list its files, and reassemble the appropriate #include.
8354 void Sema::CodeCompleteIncludedFile(llvm::StringRef Dir, bool Angled) {
8355   // RelDir should use /, but unescaped \ is possible on windows!
8356   // Our completions will normalize to / for simplicity, this case is rare.
8357   std::string RelDir = llvm::sys::path::convert_to_slash(Dir);
8358   // We need the native slashes for the actual file system interactions.
8359   SmallString<128> NativeRelDir = StringRef(RelDir);
8360   llvm::sys::path::native(NativeRelDir);
8361   auto FS = getSourceManager().getFileManager().getVirtualFileSystem();
8362 
8363   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8364                         CodeCompleter->getCodeCompletionTUInfo(),
8365                         CodeCompletionContext::CCC_IncludedFile);
8366   llvm::DenseSet<StringRef> SeenResults; // To deduplicate results.
8367 
8368   // Helper: adds one file or directory completion result.
8369   auto AddCompletion = [&](StringRef Filename, bool IsDirectory) {
8370     SmallString<64> TypedChunk = Filename;
8371     // Directory completion is up to the slash, e.g. <sys/
8372     TypedChunk.push_back(IsDirectory ? '/' : Angled ? '>' : '"');
8373     auto R = SeenResults.insert(TypedChunk);
8374     if (R.second) { // New completion
8375       const char *InternedTyped = Results.getAllocator().CopyString(TypedChunk);
8376       *R.first = InternedTyped; // Avoid dangling StringRef.
8377       CodeCompletionBuilder Builder(CodeCompleter->getAllocator(),
8378                                     CodeCompleter->getCodeCompletionTUInfo());
8379       Builder.AddTypedTextChunk(InternedTyped);
8380       // The result is a "Pattern", which is pretty opaque.
8381       // We may want to include the real filename to allow smart ranking.
8382       Results.AddResult(CodeCompletionResult(Builder.TakeString()));
8383     }
8384   };
8385 
8386   // Helper: scans IncludeDir for nice files, and adds results for each.
8387   auto AddFilesFromIncludeDir = [&](StringRef IncludeDir, bool IsSystem) {
8388     llvm::SmallString<128> Dir = IncludeDir;
8389     if (!NativeRelDir.empty())
8390       llvm::sys::path::append(Dir, NativeRelDir);
8391 
8392     std::error_code EC;
8393     unsigned Count = 0;
8394     for (auto It = FS->dir_begin(Dir, EC);
8395          !EC && It != llvm::vfs::directory_iterator(); It.increment(EC)) {
8396       if (++Count == 2500) // If we happen to hit a huge directory,
8397         break;             // bail out early so we're not too slow.
8398       StringRef Filename = llvm::sys::path::filename(It->path());
8399       switch (It->type()) {
8400       case llvm::sys::fs::file_type::directory_file:
8401         AddCompletion(Filename, /*IsDirectory=*/true);
8402         break;
8403       case llvm::sys::fs::file_type::regular_file:
8404         // Only files that really look like headers. (Except in system dirs).
8405         if (!IsSystem) {
8406           // Header extensions from Types.def, which we can't depend on here.
8407           if (!(Filename.endswith_lower(".h") ||
8408                 Filename.endswith_lower(".hh") ||
8409                 Filename.endswith_lower(".hpp") ||
8410                 Filename.endswith_lower(".inc")))
8411             break;
8412         }
8413         AddCompletion(Filename, /*IsDirectory=*/false);
8414         break;
8415       default:
8416         break;
8417       }
8418     }
8419   };
8420 
8421   // Helper: adds results relative to IncludeDir, if possible.
8422   auto AddFilesFromDirLookup = [&](const DirectoryLookup &IncludeDir,
8423                                    bool IsSystem) {
8424     switch (IncludeDir.getLookupType()) {
8425     case DirectoryLookup::LT_HeaderMap:
8426       // header maps are not (currently) enumerable.
8427       break;
8428     case DirectoryLookup::LT_NormalDir:
8429       AddFilesFromIncludeDir(IncludeDir.getDir()->getName(), IsSystem);
8430       break;
8431     case DirectoryLookup::LT_Framework:
8432       AddFilesFromIncludeDir(IncludeDir.getFrameworkDir()->getName(), IsSystem);
8433       break;
8434     }
8435   };
8436 
8437   // Finally with all our helpers, we can scan the include path.
8438   // Do this in standard order so deduplication keeps the right file.
8439   // (In case we decide to add more details to the results later).
8440   const auto &S = PP.getHeaderSearchInfo();
8441   using llvm::make_range;
8442   if (!Angled) {
8443     // The current directory is on the include path for "quoted" includes.
8444     auto *CurFile = PP.getCurrentFileLexer()->getFileEntry();
8445     if (CurFile && CurFile->getDir())
8446       AddFilesFromIncludeDir(CurFile->getDir()->getName(), false);
8447     for (const auto &D : make_range(S.quoted_dir_begin(), S.quoted_dir_end()))
8448       AddFilesFromDirLookup(D, false);
8449   }
8450   for (const auto &D : make_range(S.angled_dir_begin(), S.angled_dir_end()))
8451     AddFilesFromDirLookup(D, false);
8452   for (const auto &D : make_range(S.system_dir_begin(), S.system_dir_end()))
8453     AddFilesFromDirLookup(D, true);
8454 
8455   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8456                             Results.data(), Results.size());
8457 }
8458 
8459 void Sema::CodeCompleteNaturalLanguage() {
8460   HandleCodeCompleteResults(this, CodeCompleter,
8461                             CodeCompletionContext::CCC_NaturalLanguage, nullptr,
8462                             0);
8463 }
8464 
8465 void Sema::CodeCompleteAvailabilityPlatformName() {
8466   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8467                         CodeCompleter->getCodeCompletionTUInfo(),
8468                         CodeCompletionContext::CCC_Other);
8469   Results.EnterNewScope();
8470   static const char *Platforms[] = {"macOS", "iOS", "watchOS", "tvOS"};
8471   for (const char *Platform : llvm::makeArrayRef(Platforms)) {
8472     Results.AddResult(CodeCompletionResult(Platform));
8473     Results.AddResult(CodeCompletionResult(Results.getAllocator().CopyString(
8474         Twine(Platform) + "ApplicationExtension")));
8475   }
8476   Results.ExitScope();
8477   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8478                             Results.data(), Results.size());
8479 }
8480 
8481 void Sema::GatherGlobalCodeCompletions(
8482     CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo,
8483     SmallVectorImpl<CodeCompletionResult> &Results) {
8484   ResultBuilder Builder(*this, Allocator, CCTUInfo,
8485                         CodeCompletionContext::CCC_Recovery);
8486   if (!CodeCompleter || CodeCompleter->includeGlobals()) {
8487     CodeCompletionDeclConsumer Consumer(Builder,
8488                                         Context.getTranslationUnitDecl());
8489     LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
8490                        Consumer,
8491                        !CodeCompleter || CodeCompleter->loadExternal());
8492   }
8493 
8494   if (!CodeCompleter || CodeCompleter->includeMacros())
8495     AddMacroResults(PP, Builder,
8496                     CodeCompleter ? CodeCompleter->loadExternal() : false,
8497                     true);
8498 
8499   Results.clear();
8500   Results.insert(Results.end(), Builder.data(),
8501                  Builder.data() + Builder.size());
8502 }
8503