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