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