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