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