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