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