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