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