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