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