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