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