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