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