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