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::TranslationUnit:    return CXCursor_TranslationUnit;
3048 
3049     case Decl::Using:
3050     case Decl::UnresolvedUsingValue:
3051     case Decl::UnresolvedUsingTypename:
3052       return CXCursor_UsingDeclaration;
3053 
3054     case Decl::ObjCPropertyImpl:
3055       switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
3056       case ObjCPropertyImplDecl::Dynamic:
3057         return CXCursor_ObjCDynamicDecl;
3058 
3059       case ObjCPropertyImplDecl::Synthesize:
3060         return CXCursor_ObjCSynthesizeDecl;
3061       }
3062 
3063       case Decl::Import:
3064         return CXCursor_ModuleImportDecl;
3065 
3066     case Decl::ObjCTypeParam:   return CXCursor_TemplateTypeParameter;
3067 
3068     default:
3069       if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
3070         switch (TD->getTagKind()) {
3071           case TTK_Interface:  // fall through
3072           case TTK_Struct: return CXCursor_StructDecl;
3073           case TTK_Class:  return CXCursor_ClassDecl;
3074           case TTK_Union:  return CXCursor_UnionDecl;
3075           case TTK_Enum:   return CXCursor_EnumDecl;
3076         }
3077       }
3078   }
3079 
3080   return CXCursor_UnexposedDecl;
3081 }
3082 
3083 static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
3084                             bool IncludeUndefined,
3085                             bool TargetTypeIsPointer = false) {
3086   typedef CodeCompletionResult Result;
3087 
3088   Results.EnterNewScope();
3089 
3090   for (Preprocessor::macro_iterator M = PP.macro_begin(),
3091                                  MEnd = PP.macro_end();
3092        M != MEnd; ++M) {
3093     auto MD = PP.getMacroDefinition(M->first);
3094     if (IncludeUndefined || MD) {
3095       if (MacroInfo *MI = MD.getMacroInfo())
3096         if (MI->isUsedForHeaderGuard())
3097           continue;
3098 
3099       Results.AddResult(Result(M->first,
3100                              getMacroUsagePriority(M->first->getName(),
3101                                                    PP.getLangOpts(),
3102                                                    TargetTypeIsPointer)));
3103     }
3104   }
3105 
3106   Results.ExitScope();
3107 
3108 }
3109 
3110 static void AddPrettyFunctionResults(const LangOptions &LangOpts,
3111                                      ResultBuilder &Results) {
3112   typedef CodeCompletionResult Result;
3113 
3114   Results.EnterNewScope();
3115 
3116   Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
3117   Results.AddResult(Result("__FUNCTION__", CCP_Constant));
3118   if (LangOpts.C99 || LangOpts.CPlusPlus11)
3119     Results.AddResult(Result("__func__", CCP_Constant));
3120   Results.ExitScope();
3121 }
3122 
3123 static void HandleCodeCompleteResults(Sema *S,
3124                                       CodeCompleteConsumer *CodeCompleter,
3125                                       CodeCompletionContext Context,
3126                                       CodeCompletionResult *Results,
3127                                       unsigned NumResults) {
3128   if (CodeCompleter)
3129     CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
3130 }
3131 
3132 static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
3133                                             Sema::ParserCompletionContext PCC) {
3134   switch (PCC) {
3135   case Sema::PCC_Namespace:
3136     return CodeCompletionContext::CCC_TopLevel;
3137 
3138   case Sema::PCC_Class:
3139     return CodeCompletionContext::CCC_ClassStructUnion;
3140 
3141   case Sema::PCC_ObjCInterface:
3142     return CodeCompletionContext::CCC_ObjCInterface;
3143 
3144   case Sema::PCC_ObjCImplementation:
3145     return CodeCompletionContext::CCC_ObjCImplementation;
3146 
3147   case Sema::PCC_ObjCInstanceVariableList:
3148     return CodeCompletionContext::CCC_ObjCIvarList;
3149 
3150   case Sema::PCC_Template:
3151   case Sema::PCC_MemberTemplate:
3152     if (S.CurContext->isFileContext())
3153       return CodeCompletionContext::CCC_TopLevel;
3154     if (S.CurContext->isRecord())
3155       return CodeCompletionContext::CCC_ClassStructUnion;
3156     return CodeCompletionContext::CCC_Other;
3157 
3158   case Sema::PCC_RecoveryInFunction:
3159     return CodeCompletionContext::CCC_Recovery;
3160 
3161   case Sema::PCC_ForInit:
3162     if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 ||
3163         S.getLangOpts().ObjC1)
3164       return CodeCompletionContext::CCC_ParenthesizedExpression;
3165     else
3166       return CodeCompletionContext::CCC_Expression;
3167 
3168   case Sema::PCC_Expression:
3169   case Sema::PCC_Condition:
3170     return CodeCompletionContext::CCC_Expression;
3171 
3172   case Sema::PCC_Statement:
3173     return CodeCompletionContext::CCC_Statement;
3174 
3175   case Sema::PCC_Type:
3176     return CodeCompletionContext::CCC_Type;
3177 
3178   case Sema::PCC_ParenthesizedExpression:
3179     return CodeCompletionContext::CCC_ParenthesizedExpression;
3180 
3181   case Sema::PCC_LocalDeclarationSpecifiers:
3182     return CodeCompletionContext::CCC_Type;
3183   }
3184 
3185   llvm_unreachable("Invalid ParserCompletionContext!");
3186 }
3187 
3188 /// \brief If we're in a C++ virtual member function, add completion results
3189 /// that invoke the functions we override, since it's common to invoke the
3190 /// overridden function as well as adding new functionality.
3191 ///
3192 /// \param S The semantic analysis object for which we are generating results.
3193 ///
3194 /// \param InContext This context in which the nested-name-specifier preceding
3195 /// the code-completion point
3196 static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
3197                                   ResultBuilder &Results) {
3198   // Look through blocks.
3199   DeclContext *CurContext = S.CurContext;
3200   while (isa<BlockDecl>(CurContext))
3201     CurContext = CurContext->getParent();
3202 
3203 
3204   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
3205   if (!Method || !Method->isVirtual())
3206     return;
3207 
3208   // We need to have names for all of the parameters, if we're going to
3209   // generate a forwarding call.
3210   for (auto P : Method->params())
3211     if (!P->getDeclName())
3212       return;
3213 
3214   PrintingPolicy Policy = getCompletionPrintingPolicy(S);
3215   for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
3216                                    MEnd = Method->end_overridden_methods();
3217        M != MEnd; ++M) {
3218     CodeCompletionBuilder Builder(Results.getAllocator(),
3219                                   Results.getCodeCompletionTUInfo());
3220     const CXXMethodDecl *Overridden = *M;
3221     if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
3222       continue;
3223 
3224     // If we need a nested-name-specifier, add one now.
3225     if (!InContext) {
3226       NestedNameSpecifier *NNS
3227         = getRequiredQualification(S.Context, CurContext,
3228                                    Overridden->getDeclContext());
3229       if (NNS) {
3230         std::string Str;
3231         llvm::raw_string_ostream OS(Str);
3232         NNS->print(OS, Policy);
3233         Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
3234       }
3235     } else if (!InContext->Equals(Overridden->getDeclContext()))
3236       continue;
3237 
3238     Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
3239                                          Overridden->getNameAsString()));
3240     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3241     bool FirstParam = true;
3242     for (auto P : Method->params()) {
3243       if (FirstParam)
3244         FirstParam = false;
3245       else
3246         Builder.AddChunk(CodeCompletionString::CK_Comma);
3247 
3248       Builder.AddPlaceholderChunk(
3249           Results.getAllocator().CopyString(P->getIdentifier()->getName()));
3250     }
3251     Builder.AddChunk(CodeCompletionString::CK_RightParen);
3252     Results.AddResult(CodeCompletionResult(Builder.TakeString(),
3253                                            CCP_SuperCompletion,
3254                                            CXCursor_CXXMethod,
3255                                            CXAvailability_Available,
3256                                            Overridden));
3257     Results.Ignore(Overridden);
3258   }
3259 }
3260 
3261 void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc,
3262                                     ModuleIdPath Path) {
3263   typedef CodeCompletionResult Result;
3264   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3265                         CodeCompleter->getCodeCompletionTUInfo(),
3266                         CodeCompletionContext::CCC_Other);
3267   Results.EnterNewScope();
3268 
3269   CodeCompletionAllocator &Allocator = Results.getAllocator();
3270   CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
3271   typedef CodeCompletionResult Result;
3272   if (Path.empty()) {
3273     // Enumerate all top-level modules.
3274     SmallVector<Module *, 8> Modules;
3275     PP.getHeaderSearchInfo().collectAllModules(Modules);
3276     for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
3277       Builder.AddTypedTextChunk(
3278         Builder.getAllocator().CopyString(Modules[I]->Name));
3279       Results.AddResult(Result(Builder.TakeString(),
3280                                CCP_Declaration,
3281                                CXCursor_ModuleImportDecl,
3282                                Modules[I]->isAvailable()
3283                                  ? CXAvailability_Available
3284                                   : CXAvailability_NotAvailable));
3285     }
3286   } else if (getLangOpts().Modules) {
3287     // Load the named module.
3288     Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
3289                                                   Module::AllVisible,
3290                                                 /*IsInclusionDirective=*/false);
3291     // Enumerate submodules.
3292     if (Mod) {
3293       for (Module::submodule_iterator Sub = Mod->submodule_begin(),
3294                                    SubEnd = Mod->submodule_end();
3295            Sub != SubEnd; ++Sub) {
3296 
3297         Builder.AddTypedTextChunk(
3298           Builder.getAllocator().CopyString((*Sub)->Name));
3299         Results.AddResult(Result(Builder.TakeString(),
3300                                  CCP_Declaration,
3301                                  CXCursor_ModuleImportDecl,
3302                                  (*Sub)->isAvailable()
3303                                    ? CXAvailability_Available
3304                                    : CXAvailability_NotAvailable));
3305       }
3306     }
3307   }
3308   Results.ExitScope();
3309   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3310                             Results.data(),Results.size());
3311 }
3312 
3313 void Sema::CodeCompleteOrdinaryName(Scope *S,
3314                                     ParserCompletionContext CompletionContext) {
3315   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3316                         CodeCompleter->getCodeCompletionTUInfo(),
3317                         mapCodeCompletionContext(*this, CompletionContext));
3318   Results.EnterNewScope();
3319 
3320   // Determine how to filter results, e.g., so that the names of
3321   // values (functions, enumerators, function templates, etc.) are
3322   // only allowed where we can have an expression.
3323   switch (CompletionContext) {
3324   case PCC_Namespace:
3325   case PCC_Class:
3326   case PCC_ObjCInterface:
3327   case PCC_ObjCImplementation:
3328   case PCC_ObjCInstanceVariableList:
3329   case PCC_Template:
3330   case PCC_MemberTemplate:
3331   case PCC_Type:
3332   case PCC_LocalDeclarationSpecifiers:
3333     Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
3334     break;
3335 
3336   case PCC_Statement:
3337   case PCC_ParenthesizedExpression:
3338   case PCC_Expression:
3339   case PCC_ForInit:
3340   case PCC_Condition:
3341     if (WantTypesInContext(CompletionContext, getLangOpts()))
3342       Results.setFilter(&ResultBuilder::IsOrdinaryName);
3343     else
3344       Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
3345 
3346     if (getLangOpts().CPlusPlus)
3347       MaybeAddOverrideCalls(*this, /*InContext=*/nullptr, Results);
3348     break;
3349 
3350   case PCC_RecoveryInFunction:
3351     // Unfiltered
3352     break;
3353   }
3354 
3355   // If we are in a C++ non-static member function, check the qualifiers on
3356   // the member function to filter/prioritize the results list.
3357   if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
3358     if (CurMethod->isInstance())
3359       Results.setObjectTypeQualifiers(
3360                       Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
3361 
3362   CodeCompletionDeclConsumer Consumer(Results, CurContext);
3363   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3364                      CodeCompleter->includeGlobals());
3365 
3366   AddOrdinaryNameResults(CompletionContext, S, *this, Results);
3367   Results.ExitScope();
3368 
3369   switch (CompletionContext) {
3370   case PCC_ParenthesizedExpression:
3371   case PCC_Expression:
3372   case PCC_Statement:
3373   case PCC_RecoveryInFunction:
3374     if (S->getFnParent())
3375       AddPrettyFunctionResults(getLangOpts(), Results);
3376     break;
3377 
3378   case PCC_Namespace:
3379   case PCC_Class:
3380   case PCC_ObjCInterface:
3381   case PCC_ObjCImplementation:
3382   case PCC_ObjCInstanceVariableList:
3383   case PCC_Template:
3384   case PCC_MemberTemplate:
3385   case PCC_ForInit:
3386   case PCC_Condition:
3387   case PCC_Type:
3388   case PCC_LocalDeclarationSpecifiers:
3389     break;
3390   }
3391 
3392   if (CodeCompleter->includeMacros())
3393     AddMacroResults(PP, Results, false);
3394 
3395   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3396                             Results.data(),Results.size());
3397 }
3398 
3399 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3400                                        ParsedType Receiver,
3401                                        ArrayRef<IdentifierInfo *> SelIdents,
3402                                        bool AtArgumentExpression,
3403                                        bool IsSuper,
3404                                        ResultBuilder &Results);
3405 
3406 void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3407                                 bool AllowNonIdentifiers,
3408                                 bool AllowNestedNameSpecifiers) {
3409   typedef CodeCompletionResult Result;
3410   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3411                         CodeCompleter->getCodeCompletionTUInfo(),
3412                         AllowNestedNameSpecifiers
3413                           ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3414                           : CodeCompletionContext::CCC_Name);
3415   Results.EnterNewScope();
3416 
3417   // Type qualifiers can come after names.
3418   Results.AddResult(Result("const"));
3419   Results.AddResult(Result("volatile"));
3420   if (getLangOpts().C99)
3421     Results.AddResult(Result("restrict"));
3422 
3423   if (getLangOpts().CPlusPlus) {
3424     if (AllowNonIdentifiers) {
3425       Results.AddResult(Result("operator"));
3426     }
3427 
3428     // Add nested-name-specifiers.
3429     if (AllowNestedNameSpecifiers) {
3430       Results.allowNestedNameSpecifiers();
3431       Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
3432       CodeCompletionDeclConsumer Consumer(Results, CurContext);
3433       LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3434                          CodeCompleter->includeGlobals());
3435       Results.setFilter(nullptr);
3436     }
3437   }
3438   Results.ExitScope();
3439 
3440   // If we're in a context where we might have an expression (rather than a
3441   // declaration), and what we've seen so far is an Objective-C type that could
3442   // be a receiver of a class message, this may be a class message send with
3443   // the initial opening bracket '[' missing. Add appropriate completions.
3444   if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
3445       DS.getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
3446       DS.getTypeSpecType() == DeclSpec::TST_typename &&
3447       DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3448       DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
3449       !DS.isTypeAltiVecVector() &&
3450       S &&
3451       (S->getFlags() & Scope::DeclScope) != 0 &&
3452       (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3453                         Scope::FunctionPrototypeScope |
3454                         Scope::AtCatchScope)) == 0) {
3455     ParsedType T = DS.getRepAsType();
3456     if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
3457       AddClassMessageCompletions(*this, S, T, None, false, false, Results);
3458   }
3459 
3460   // Note that we intentionally suppress macro results here, since we do not
3461   // encourage using macros to produce the names of entities.
3462 
3463   HandleCodeCompleteResults(this, CodeCompleter,
3464                             Results.getCompletionContext(),
3465                             Results.data(), Results.size());
3466 }
3467 
3468 struct Sema::CodeCompleteExpressionData {
3469   CodeCompleteExpressionData(QualType PreferredType = QualType())
3470     : PreferredType(PreferredType), IntegralConstantExpression(false),
3471       ObjCCollection(false) { }
3472 
3473   QualType PreferredType;
3474   bool IntegralConstantExpression;
3475   bool ObjCCollection;
3476   SmallVector<Decl *, 4> IgnoreDecls;
3477 };
3478 
3479 /// \brief Perform code-completion in an expression context when we know what
3480 /// type we're looking for.
3481 void Sema::CodeCompleteExpression(Scope *S,
3482                                   const CodeCompleteExpressionData &Data) {
3483   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3484                         CodeCompleter->getCodeCompletionTUInfo(),
3485                         CodeCompletionContext::CCC_Expression);
3486   if (Data.ObjCCollection)
3487     Results.setFilter(&ResultBuilder::IsObjCCollection);
3488   else if (Data.IntegralConstantExpression)
3489     Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
3490   else if (WantTypesInContext(PCC_Expression, getLangOpts()))
3491     Results.setFilter(&ResultBuilder::IsOrdinaryName);
3492   else
3493     Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
3494 
3495   if (!Data.PreferredType.isNull())
3496     Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3497 
3498   // Ignore any declarations that we were told that we don't care about.
3499   for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3500     Results.Ignore(Data.IgnoreDecls[I]);
3501 
3502   CodeCompletionDeclConsumer Consumer(Results, CurContext);
3503   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3504                      CodeCompleter->includeGlobals());
3505 
3506   Results.EnterNewScope();
3507   AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
3508   Results.ExitScope();
3509 
3510   bool PreferredTypeIsPointer = false;
3511   if (!Data.PreferredType.isNull())
3512     PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3513       || Data.PreferredType->isMemberPointerType()
3514       || Data.PreferredType->isBlockPointerType();
3515 
3516   if (S->getFnParent() &&
3517       !Data.ObjCCollection &&
3518       !Data.IntegralConstantExpression)
3519     AddPrettyFunctionResults(getLangOpts(), Results);
3520 
3521   if (CodeCompleter->includeMacros())
3522     AddMacroResults(PP, Results, false, PreferredTypeIsPointer);
3523   HandleCodeCompleteResults(this, CodeCompleter,
3524                 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3525                                       Data.PreferredType),
3526                             Results.data(),Results.size());
3527 }
3528 
3529 void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3530   if (E.isInvalid())
3531     CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
3532   else if (getLangOpts().ObjC1)
3533     CodeCompleteObjCInstanceMessage(S, E.get(), None, false);
3534 }
3535 
3536 /// \brief The set of properties that have already been added, referenced by
3537 /// property name.
3538 typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3539 
3540 /// \brief Retrieve the container definition, if any?
3541 static ObjCContainerDecl *getContainerDef(ObjCContainerDecl *Container) {
3542   if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
3543     if (Interface->hasDefinition())
3544       return Interface->getDefinition();
3545 
3546     return Interface;
3547   }
3548 
3549   if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3550     if (Protocol->hasDefinition())
3551       return Protocol->getDefinition();
3552 
3553     return Protocol;
3554   }
3555   return Container;
3556 }
3557 
3558 static void AddObjCProperties(const CodeCompletionContext &CCContext,
3559                               ObjCContainerDecl *Container,
3560                               bool AllowCategories,
3561                               bool AllowNullaryMethods,
3562                               DeclContext *CurContext,
3563                               AddedPropertiesSet &AddedProperties,
3564                               ResultBuilder &Results) {
3565   typedef CodeCompletionResult Result;
3566 
3567   // Retrieve the definition.
3568   Container = getContainerDef(Container);
3569 
3570   // Add properties in this container.
3571   for (const auto *P : Container->instance_properties())
3572     if (AddedProperties.insert(P->getIdentifier()).second)
3573       Results.MaybeAddResult(Result(P, Results.getBasePriority(P), nullptr),
3574                              CurContext);
3575 
3576   // Add nullary methods
3577   if (AllowNullaryMethods) {
3578     ASTContext &Context = Container->getASTContext();
3579     PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
3580     for (auto *M : Container->methods()) {
3581       if (M->getSelector().isUnarySelector())
3582         if (IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0))
3583           if (AddedProperties.insert(Name).second) {
3584             CodeCompletionBuilder Builder(Results.getAllocator(),
3585                                           Results.getCodeCompletionTUInfo());
3586             AddResultTypeChunk(Context, Policy, M, CCContext.getBaseType(),
3587                                Builder);
3588             Builder.AddTypedTextChunk(
3589                             Results.getAllocator().CopyString(Name->getName()));
3590 
3591             Results.MaybeAddResult(Result(Builder.TakeString(), M,
3592                                   CCP_MemberDeclaration + CCD_MethodAsProperty),
3593                                           CurContext);
3594           }
3595     }
3596   }
3597 
3598 
3599   // Add properties in referenced protocols.
3600   if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3601     for (auto *P : Protocol->protocols())
3602       AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
3603                         CurContext, AddedProperties, Results);
3604   } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
3605     if (AllowCategories) {
3606       // Look through categories.
3607       for (auto *Cat : IFace->known_categories())
3608         AddObjCProperties(CCContext, Cat, AllowCategories, AllowNullaryMethods,
3609                           CurContext, AddedProperties, Results);
3610     }
3611 
3612     // Look through protocols.
3613     for (auto *I : IFace->all_referenced_protocols())
3614       AddObjCProperties(CCContext, I, AllowCategories, AllowNullaryMethods,
3615                         CurContext, AddedProperties, Results);
3616 
3617     // Look in the superclass.
3618     if (IFace->getSuperClass())
3619       AddObjCProperties(CCContext, IFace->getSuperClass(), AllowCategories,
3620                         AllowNullaryMethods, CurContext,
3621                         AddedProperties, Results);
3622   } else if (const ObjCCategoryDecl *Category
3623                                     = dyn_cast<ObjCCategoryDecl>(Container)) {
3624     // Look through protocols.
3625     for (auto *P : Category->protocols())
3626       AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
3627                         CurContext, AddedProperties, Results);
3628   }
3629 }
3630 
3631 void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
3632                                            SourceLocation OpLoc,
3633                                            bool IsArrow) {
3634   if (!Base || !CodeCompleter)
3635     return;
3636 
3637   ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
3638   if (ConvertedBase.isInvalid())
3639     return;
3640   Base = ConvertedBase.get();
3641 
3642   typedef CodeCompletionResult Result;
3643 
3644   QualType BaseType = Base->getType();
3645 
3646   if (IsArrow) {
3647     if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3648       BaseType = Ptr->getPointeeType();
3649     else if (BaseType->isObjCObjectPointerType())
3650       /*Do nothing*/ ;
3651     else
3652       return;
3653   }
3654 
3655   enum CodeCompletionContext::Kind contextKind;
3656 
3657   if (IsArrow) {
3658     contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3659   }
3660   else {
3661     if (BaseType->isObjCObjectPointerType() ||
3662         BaseType->isObjCObjectOrInterfaceType()) {
3663       contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3664     }
3665     else {
3666       contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3667     }
3668   }
3669 
3670   CodeCompletionContext CCContext(contextKind, BaseType);
3671   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3672                         CodeCompleter->getCodeCompletionTUInfo(),
3673                         CCContext,
3674                         &ResultBuilder::IsMember);
3675   Results.EnterNewScope();
3676   if (const RecordType *Record = BaseType->getAs<RecordType>()) {
3677     // Indicate that we are performing a member access, and the cv-qualifiers
3678     // for the base object type.
3679     Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3680 
3681     // Access to a C/C++ class, struct, or union.
3682     Results.allowNestedNameSpecifiers();
3683     CodeCompletionDeclConsumer Consumer(Results, CurContext);
3684     LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3685                        CodeCompleter->includeGlobals());
3686 
3687     if (getLangOpts().CPlusPlus) {
3688       if (!Results.empty()) {
3689         // The "template" keyword can follow "->" or "." in the grammar.
3690         // However, we only want to suggest the template keyword if something
3691         // is dependent.
3692         bool IsDependent = BaseType->isDependentType();
3693         if (!IsDependent) {
3694           for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3695             if (DeclContext *Ctx = DepScope->getEntity()) {
3696               IsDependent = Ctx->isDependentContext();
3697               break;
3698             }
3699         }
3700 
3701         if (IsDependent)
3702           Results.AddResult(Result("template"));
3703       }
3704     }
3705   } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3706     // Objective-C property reference.
3707     AddedPropertiesSet AddedProperties;
3708 
3709     // Add property results based on our interface.
3710     const ObjCObjectPointerType *ObjCPtr
3711       = BaseType->getAsObjCInterfacePointerType();
3712     assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
3713     AddObjCProperties(CCContext, ObjCPtr->getInterfaceDecl(), true,
3714                       /*AllowNullaryMethods=*/true, CurContext,
3715                       AddedProperties, Results);
3716 
3717     // Add properties from the protocols in a qualified interface.
3718     for (auto *I : ObjCPtr->quals())
3719       AddObjCProperties(CCContext, I, true, /*AllowNullaryMethods=*/true,
3720                         CurContext, AddedProperties, Results);
3721   } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
3722              (!IsArrow && BaseType->isObjCObjectType())) {
3723     // Objective-C instance variable access.
3724     ObjCInterfaceDecl *Class = nullptr;
3725     if (const ObjCObjectPointerType *ObjCPtr
3726                                     = BaseType->getAs<ObjCObjectPointerType>())
3727       Class = ObjCPtr->getInterfaceDecl();
3728     else
3729       Class = BaseType->getAs<ObjCObjectType>()->getInterface();
3730 
3731     // Add all ivars from this class and its superclasses.
3732     if (Class) {
3733       CodeCompletionDeclConsumer Consumer(Results, CurContext);
3734       Results.setFilter(&ResultBuilder::IsObjCIvar);
3735       LookupVisibleDecls(Class, LookupMemberName, Consumer,
3736                          CodeCompleter->includeGlobals());
3737     }
3738   }
3739 
3740   // FIXME: How do we cope with isa?
3741 
3742   Results.ExitScope();
3743 
3744   // Hand off the results found for code completion.
3745   HandleCodeCompleteResults(this, CodeCompleter,
3746                             Results.getCompletionContext(),
3747                             Results.data(),Results.size());
3748 }
3749 
3750 void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3751   if (!CodeCompleter)
3752     return;
3753 
3754   ResultBuilder::LookupFilter Filter = nullptr;
3755   enum CodeCompletionContext::Kind ContextKind
3756     = CodeCompletionContext::CCC_Other;
3757   switch ((DeclSpec::TST)TagSpec) {
3758   case DeclSpec::TST_enum:
3759     Filter = &ResultBuilder::IsEnum;
3760     ContextKind = CodeCompletionContext::CCC_EnumTag;
3761     break;
3762 
3763   case DeclSpec::TST_union:
3764     Filter = &ResultBuilder::IsUnion;
3765     ContextKind = CodeCompletionContext::CCC_UnionTag;
3766     break;
3767 
3768   case DeclSpec::TST_struct:
3769   case DeclSpec::TST_class:
3770   case DeclSpec::TST_interface:
3771     Filter = &ResultBuilder::IsClassOrStruct;
3772     ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
3773     break;
3774 
3775   default:
3776     llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
3777   }
3778 
3779   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3780                         CodeCompleter->getCodeCompletionTUInfo(), ContextKind);
3781   CodeCompletionDeclConsumer Consumer(Results, CurContext);
3782 
3783   // First pass: look for tags.
3784   Results.setFilter(Filter);
3785   LookupVisibleDecls(S, LookupTagName, Consumer,
3786                      CodeCompleter->includeGlobals());
3787 
3788   if (CodeCompleter->includeGlobals()) {
3789     // Second pass: look for nested name specifiers.
3790     Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3791     LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3792   }
3793 
3794   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3795                             Results.data(),Results.size());
3796 }
3797 
3798 void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
3799   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3800                         CodeCompleter->getCodeCompletionTUInfo(),
3801                         CodeCompletionContext::CCC_TypeQualifiers);
3802   Results.EnterNewScope();
3803   if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3804     Results.AddResult("const");
3805   if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3806     Results.AddResult("volatile");
3807   if (getLangOpts().C99 &&
3808       !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3809     Results.AddResult("restrict");
3810   if (getLangOpts().C11 &&
3811       !(DS.getTypeQualifiers() & DeclSpec::TQ_atomic))
3812     Results.AddResult("_Atomic");
3813   if (getLangOpts().MSVCCompat &&
3814       !(DS.getTypeQualifiers() & DeclSpec::TQ_unaligned))
3815     Results.AddResult("__unaligned");
3816   Results.ExitScope();
3817   HandleCodeCompleteResults(this, CodeCompleter,
3818                             Results.getCompletionContext(),
3819                             Results.data(), Results.size());
3820 }
3821 
3822 void Sema::CodeCompleteBracketDeclarator(Scope *S) {
3823   CodeCompleteExpression(S, QualType(getASTContext().getSizeType()));
3824 }
3825 
3826 void Sema::CodeCompleteCase(Scope *S) {
3827   if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
3828     return;
3829 
3830   SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
3831   QualType type = Switch->getCond()->IgnoreImplicit()->getType();
3832   if (!type->isEnumeralType()) {
3833     CodeCompleteExpressionData Data(type);
3834     Data.IntegralConstantExpression = true;
3835     CodeCompleteExpression(S, Data);
3836     return;
3837   }
3838 
3839   // Code-complete the cases of a switch statement over an enumeration type
3840   // by providing the list of
3841   EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
3842   if (EnumDecl *Def = Enum->getDefinition())
3843     Enum = Def;
3844 
3845   // Determine which enumerators we have already seen in the switch statement.
3846   // FIXME: Ideally, we would also be able to look *past* the code-completion
3847   // token, in case we are code-completing in the middle of the switch and not
3848   // at the end. However, we aren't able to do so at the moment.
3849   llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
3850   NestedNameSpecifier *Qualifier = nullptr;
3851   for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3852        SC = SC->getNextSwitchCase()) {
3853     CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3854     if (!Case)
3855       continue;
3856 
3857     Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3858     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3859       if (EnumConstantDecl *Enumerator
3860             = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3861         // We look into the AST of the case statement to determine which
3862         // enumerator was named. Alternatively, we could compute the value of
3863         // the integral constant expression, then compare it against the
3864         // values of each enumerator. However, value-based approach would not
3865         // work as well with C++ templates where enumerators declared within a
3866         // template are type- and value-dependent.
3867         EnumeratorsSeen.insert(Enumerator);
3868 
3869         // If this is a qualified-id, keep track of the nested-name-specifier
3870         // so that we can reproduce it as part of code completion, e.g.,
3871         //
3872         //   switch (TagD.getKind()) {
3873         //     case TagDecl::TK_enum:
3874         //       break;
3875         //     case XXX
3876         //
3877         // At the XXX, our completions are TagDecl::TK_union,
3878         // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3879         // TK_struct, and TK_class.
3880         Qualifier = DRE->getQualifier();
3881       }
3882   }
3883 
3884   if (getLangOpts().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
3885     // If there are no prior enumerators in C++, check whether we have to
3886     // qualify the names of the enumerators that we suggest, because they
3887     // may not be visible in this scope.
3888     Qualifier = getRequiredQualification(Context, CurContext, Enum);
3889   }
3890 
3891   // Add any enumerators that have not yet been mentioned.
3892   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3893                         CodeCompleter->getCodeCompletionTUInfo(),
3894                         CodeCompletionContext::CCC_Expression);
3895   Results.EnterNewScope();
3896   for (auto *E : Enum->enumerators()) {
3897     if (EnumeratorsSeen.count(E))
3898       continue;
3899 
3900     CodeCompletionResult R(E, CCP_EnumInCase, Qualifier);
3901     Results.AddResult(R, CurContext, nullptr, false);
3902   }
3903   Results.ExitScope();
3904 
3905   //We need to make sure we're setting the right context,
3906   //so only say we include macros if the code completer says we do
3907   enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
3908   if (CodeCompleter->includeMacros()) {
3909     AddMacroResults(PP, Results, false);
3910     kind = CodeCompletionContext::CCC_OtherWithMacros;
3911   }
3912 
3913   HandleCodeCompleteResults(this, CodeCompleter,
3914                             kind,
3915                             Results.data(),Results.size());
3916 }
3917 
3918 static bool anyNullArguments(ArrayRef<Expr *> Args) {
3919   if (Args.size() && !Args.data())
3920     return true;
3921 
3922   for (unsigned I = 0; I != Args.size(); ++I)
3923     if (!Args[I])
3924       return true;
3925 
3926   return false;
3927 }
3928 
3929 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
3930 
3931 static void mergeCandidatesWithResults(Sema &SemaRef,
3932                                       SmallVectorImpl<ResultCandidate> &Results,
3933                                        OverloadCandidateSet &CandidateSet,
3934                                        SourceLocation Loc) {
3935   if (!CandidateSet.empty()) {
3936     // Sort the overload candidate set by placing the best overloads first.
3937     std::stable_sort(
3938         CandidateSet.begin(), CandidateSet.end(),
3939         [&](const OverloadCandidate &X, const OverloadCandidate &Y) {
3940           return isBetterOverloadCandidate(SemaRef, X, Y, Loc);
3941         });
3942 
3943     // Add the remaining viable overload candidates as code-completion results.
3944     for (auto &Candidate : CandidateSet)
3945       if (Candidate.Viable)
3946         Results.push_back(ResultCandidate(Candidate.Function));
3947   }
3948 }
3949 
3950 /// \brief Get the type of the Nth parameter from a given set of overload
3951 /// candidates.
3952 static QualType getParamType(Sema &SemaRef,
3953                              ArrayRef<ResultCandidate> Candidates,
3954                              unsigned N) {
3955 
3956   // Given the overloads 'Candidates' for a function call matching all arguments
3957   // up to N, return the type of the Nth parameter if it is the same for all
3958   // overload candidates.
3959   QualType ParamType;
3960   for (auto &Candidate : Candidates) {
3961     if (auto FType = Candidate.getFunctionType())
3962       if (auto Proto = dyn_cast<FunctionProtoType>(FType))
3963         if (N < Proto->getNumParams()) {
3964           if (ParamType.isNull())
3965             ParamType = Proto->getParamType(N);
3966           else if (!SemaRef.Context.hasSameUnqualifiedType(
3967                         ParamType.getNonReferenceType(),
3968                         Proto->getParamType(N).getNonReferenceType()))
3969             // Otherwise return a default-constructed QualType.
3970             return QualType();
3971         }
3972   }
3973 
3974   return ParamType;
3975 }
3976 
3977 static void CodeCompleteOverloadResults(Sema &SemaRef, Scope *S,
3978                                     MutableArrayRef<ResultCandidate> Candidates,
3979                                         unsigned CurrentArg,
3980                                  bool CompleteExpressionWithCurrentArg = true) {
3981   QualType ParamType;
3982   if (CompleteExpressionWithCurrentArg)
3983     ParamType = getParamType(SemaRef, Candidates, CurrentArg);
3984 
3985   if (ParamType.isNull())
3986     SemaRef.CodeCompleteOrdinaryName(S, Sema::PCC_Expression);
3987   else
3988     SemaRef.CodeCompleteExpression(S, ParamType);
3989 
3990   if (!Candidates.empty())
3991     SemaRef.CodeCompleter->ProcessOverloadCandidates(SemaRef, CurrentArg,
3992                                                      Candidates.data(),
3993                                                      Candidates.size());
3994 }
3995 
3996 void Sema::CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args) {
3997   if (!CodeCompleter)
3998     return;
3999 
4000   // When we're code-completing for a call, we fall back to ordinary
4001   // name code-completion whenever we can't produce specific
4002   // results. We may want to revisit this strategy in the future,
4003   // e.g., by merging the two kinds of results.
4004 
4005   // FIXME: Provide support for variadic template functions.
4006 
4007   // Ignore type-dependent call expressions entirely.
4008   if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args) ||
4009       Expr::hasAnyTypeDependentArguments(Args)) {
4010     CodeCompleteOrdinaryName(S, PCC_Expression);
4011     return;
4012   }
4013 
4014   // Build an overload candidate set based on the functions we find.
4015   SourceLocation Loc = Fn->getExprLoc();
4016   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
4017 
4018   SmallVector<ResultCandidate, 8> Results;
4019 
4020   Expr *NakedFn = Fn->IgnoreParenCasts();
4021   if (auto ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
4022     AddOverloadedCallCandidates(ULE, Args, CandidateSet,
4023                                 /*PartialOverloading=*/true);
4024   else if (auto UME = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4025     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
4026     if (UME->hasExplicitTemplateArgs()) {
4027       UME->copyTemplateArgumentsInto(TemplateArgsBuffer);
4028       TemplateArgs = &TemplateArgsBuffer;
4029     }
4030     SmallVector<Expr *, 12> ArgExprs(1, UME->getBase());
4031     ArgExprs.append(Args.begin(), Args.end());
4032     UnresolvedSet<8> Decls;
4033     Decls.append(UME->decls_begin(), UME->decls_end());
4034     AddFunctionCandidates(Decls, ArgExprs, CandidateSet, TemplateArgs,
4035                           /*SuppressUsedConversions=*/false,
4036                           /*PartialOverloading=*/true);
4037   } else {
4038     FunctionDecl *FD = nullptr;
4039     if (auto MCE = dyn_cast<MemberExpr>(NakedFn))
4040       FD = dyn_cast<FunctionDecl>(MCE->getMemberDecl());
4041     else if (auto DRE = dyn_cast<DeclRefExpr>(NakedFn))
4042       FD = dyn_cast<FunctionDecl>(DRE->getDecl());
4043     if (FD) { // We check whether it's a resolved function declaration.
4044       if (!getLangOpts().CPlusPlus ||
4045           !FD->getType()->getAs<FunctionProtoType>())
4046         Results.push_back(ResultCandidate(FD));
4047       else
4048         AddOverloadCandidate(FD, DeclAccessPair::make(FD, FD->getAccess()),
4049                              Args, CandidateSet,
4050                              /*SuppressUsedConversions=*/false,
4051                              /*PartialOverloading=*/true);
4052 
4053     } else if (auto DC = NakedFn->getType()->getAsCXXRecordDecl()) {
4054       // If expression's type is CXXRecordDecl, it may overload the function
4055       // call operator, so we check if it does and add them as candidates.
4056       // A complete type is needed to lookup for member function call operators.
4057       if (isCompleteType(Loc, NakedFn->getType())) {
4058         DeclarationName OpName = Context.DeclarationNames
4059                                  .getCXXOperatorName(OO_Call);
4060         LookupResult R(*this, OpName, Loc, LookupOrdinaryName);
4061         LookupQualifiedName(R, DC);
4062         R.suppressDiagnostics();
4063         SmallVector<Expr *, 12> ArgExprs(1, NakedFn);
4064         ArgExprs.append(Args.begin(), Args.end());
4065         AddFunctionCandidates(R.asUnresolvedSet(), ArgExprs, CandidateSet,
4066                               /*ExplicitArgs=*/nullptr,
4067                               /*SuppressUsedConversions=*/false,
4068                               /*PartialOverloading=*/true);
4069       }
4070     } else {
4071       // Lastly we check whether expression's type is function pointer or
4072       // function.
4073       QualType T = NakedFn->getType();
4074       if (!T->getPointeeType().isNull())
4075         T = T->getPointeeType();
4076 
4077       if (auto FP = T->getAs<FunctionProtoType>()) {
4078         if (!TooManyArguments(FP->getNumParams(), Args.size(),
4079                              /*PartialOverloading=*/true) ||
4080             FP->isVariadic())
4081           Results.push_back(ResultCandidate(FP));
4082       } else if (auto FT = T->getAs<FunctionType>())
4083         // No prototype and declaration, it may be a K & R style function.
4084         Results.push_back(ResultCandidate(FT));
4085     }
4086   }
4087 
4088   mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
4089   CodeCompleteOverloadResults(*this, S, Results, Args.size(),
4090                               !CandidateSet.empty());
4091 }
4092 
4093 void Sema::CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
4094                                    ArrayRef<Expr *> Args) {
4095   if (!CodeCompleter)
4096     return;
4097 
4098   // A complete type is needed to lookup for constructors.
4099   if (!isCompleteType(Loc, Type))
4100     return;
4101 
4102   CXXRecordDecl *RD = Type->getAsCXXRecordDecl();
4103   if (!RD) {
4104     CodeCompleteExpression(S, Type);
4105     return;
4106   }
4107 
4108   // FIXME: Provide support for member initializers.
4109   // FIXME: Provide support for variadic template constructors.
4110 
4111   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
4112 
4113   for (auto C : LookupConstructors(RD)) {
4114     if (auto FD = dyn_cast<FunctionDecl>(C)) {
4115       AddOverloadCandidate(FD, DeclAccessPair::make(FD, C->getAccess()),
4116                            Args, CandidateSet,
4117                            /*SuppressUsedConversions=*/false,
4118                            /*PartialOverloading=*/true);
4119     } else if (auto FTD = dyn_cast<FunctionTemplateDecl>(C)) {
4120       AddTemplateOverloadCandidate(FTD,
4121                                    DeclAccessPair::make(FTD, C->getAccess()),
4122                                    /*ExplicitTemplateArgs=*/nullptr,
4123                                    Args, CandidateSet,
4124                                    /*SuppressUsedConversions=*/false,
4125                                    /*PartialOverloading=*/true);
4126     }
4127   }
4128 
4129   SmallVector<ResultCandidate, 8> Results;
4130   mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
4131   CodeCompleteOverloadResults(*this, S, Results, Args.size());
4132 }
4133 
4134 void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
4135   ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
4136   if (!VD) {
4137     CodeCompleteOrdinaryName(S, PCC_Expression);
4138     return;
4139   }
4140 
4141   CodeCompleteExpression(S, VD->getType());
4142 }
4143 
4144 void Sema::CodeCompleteReturn(Scope *S) {
4145   QualType ResultType;
4146   if (isa<BlockDecl>(CurContext)) {
4147     if (BlockScopeInfo *BSI = getCurBlock())
4148       ResultType = BSI->ReturnType;
4149   } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
4150     ResultType = Function->getReturnType();
4151   else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
4152     ResultType = Method->getReturnType();
4153 
4154   if (ResultType.isNull())
4155     CodeCompleteOrdinaryName(S, PCC_Expression);
4156   else
4157     CodeCompleteExpression(S, ResultType);
4158 }
4159 
4160 void Sema::CodeCompleteAfterIf(Scope *S) {
4161   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4162                         CodeCompleter->getCodeCompletionTUInfo(),
4163                         mapCodeCompletionContext(*this, PCC_Statement));
4164   Results.setFilter(&ResultBuilder::IsOrdinaryName);
4165   Results.EnterNewScope();
4166 
4167   CodeCompletionDeclConsumer Consumer(Results, CurContext);
4168   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4169                      CodeCompleter->includeGlobals());
4170 
4171   AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
4172 
4173   // "else" block
4174   CodeCompletionBuilder Builder(Results.getAllocator(),
4175                                 Results.getCodeCompletionTUInfo());
4176   Builder.AddTypedTextChunk("else");
4177   if (Results.includeCodePatterns()) {
4178     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4179     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4180     Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4181     Builder.AddPlaceholderChunk("statements");
4182     Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4183     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4184   }
4185   Results.AddResult(Builder.TakeString());
4186 
4187   // "else if" block
4188   Builder.AddTypedTextChunk("else");
4189   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4190   Builder.AddTextChunk("if");
4191   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4192   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4193   if (getLangOpts().CPlusPlus)
4194     Builder.AddPlaceholderChunk("condition");
4195   else
4196     Builder.AddPlaceholderChunk("expression");
4197   Builder.AddChunk(CodeCompletionString::CK_RightParen);
4198   if (Results.includeCodePatterns()) {
4199     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4200     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4201     Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4202     Builder.AddPlaceholderChunk("statements");
4203     Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4204     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4205   }
4206   Results.AddResult(Builder.TakeString());
4207 
4208   Results.ExitScope();
4209 
4210   if (S->getFnParent())
4211     AddPrettyFunctionResults(getLangOpts(), Results);
4212 
4213   if (CodeCompleter->includeMacros())
4214     AddMacroResults(PP, Results, false);
4215 
4216   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4217                             Results.data(),Results.size());
4218 }
4219 
4220 void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) {
4221   if (LHS)
4222     CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
4223   else
4224     CodeCompleteOrdinaryName(S, PCC_Expression);
4225 }
4226 
4227 void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
4228                                    bool EnteringContext) {
4229   if (!SS.getScopeRep() || !CodeCompleter)
4230     return;
4231 
4232   DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
4233   if (!Ctx)
4234     return;
4235 
4236   // Try to instantiate any non-dependent declaration contexts before
4237   // we look in them.
4238   if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
4239     return;
4240 
4241   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4242                         CodeCompleter->getCodeCompletionTUInfo(),
4243                         CodeCompletionContext::CCC_Name);
4244   Results.EnterNewScope();
4245 
4246   // The "template" keyword can follow "::" in the grammar, but only
4247   // put it into the grammar if the nested-name-specifier is dependent.
4248   NestedNameSpecifier *NNS = SS.getScopeRep();
4249   if (!Results.empty() && NNS->isDependent())
4250     Results.AddResult("template");
4251 
4252   // Add calls to overridden virtual functions, if there are any.
4253   //
4254   // FIXME: This isn't wonderful, because we don't know whether we're actually
4255   // in a context that permits expressions. This is a general issue with
4256   // qualified-id completions.
4257   if (!EnteringContext)
4258     MaybeAddOverrideCalls(*this, Ctx, Results);
4259   Results.ExitScope();
4260 
4261   CodeCompletionDeclConsumer Consumer(Results, CurContext);
4262   LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
4263 
4264   HandleCodeCompleteResults(this, CodeCompleter,
4265                             Results.getCompletionContext(),
4266                             Results.data(),Results.size());
4267 }
4268 
4269 void Sema::CodeCompleteUsing(Scope *S) {
4270   if (!CodeCompleter)
4271     return;
4272 
4273   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4274                         CodeCompleter->getCodeCompletionTUInfo(),
4275                         CodeCompletionContext::CCC_PotentiallyQualifiedName,
4276                         &ResultBuilder::IsNestedNameSpecifier);
4277   Results.EnterNewScope();
4278 
4279   // If we aren't in class scope, we could see the "namespace" keyword.
4280   if (!S->isClassScope())
4281     Results.AddResult(CodeCompletionResult("namespace"));
4282 
4283   // After "using", we can see anything that would start a
4284   // nested-name-specifier.
4285   CodeCompletionDeclConsumer Consumer(Results, CurContext);
4286   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4287                      CodeCompleter->includeGlobals());
4288   Results.ExitScope();
4289 
4290   HandleCodeCompleteResults(this, CodeCompleter,
4291                             CodeCompletionContext::CCC_PotentiallyQualifiedName,
4292                             Results.data(),Results.size());
4293 }
4294 
4295 void Sema::CodeCompleteUsingDirective(Scope *S) {
4296   if (!CodeCompleter)
4297     return;
4298 
4299   // After "using namespace", we expect to see a namespace name or namespace
4300   // alias.
4301   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4302                         CodeCompleter->getCodeCompletionTUInfo(),
4303                         CodeCompletionContext::CCC_Namespace,
4304                         &ResultBuilder::IsNamespaceOrAlias);
4305   Results.EnterNewScope();
4306   CodeCompletionDeclConsumer Consumer(Results, CurContext);
4307   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4308                      CodeCompleter->includeGlobals());
4309   Results.ExitScope();
4310   HandleCodeCompleteResults(this, CodeCompleter,
4311                             CodeCompletionContext::CCC_Namespace,
4312                             Results.data(),Results.size());
4313 }
4314 
4315 void Sema::CodeCompleteNamespaceDecl(Scope *S)  {
4316   if (!CodeCompleter)
4317     return;
4318 
4319   DeclContext *Ctx = S->getEntity();
4320   if (!S->getParent())
4321     Ctx = Context.getTranslationUnitDecl();
4322 
4323   bool SuppressedGlobalResults
4324     = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
4325 
4326   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4327                         CodeCompleter->getCodeCompletionTUInfo(),
4328                         SuppressedGlobalResults
4329                           ? CodeCompletionContext::CCC_Namespace
4330                           : CodeCompletionContext::CCC_Other,
4331                         &ResultBuilder::IsNamespace);
4332 
4333   if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
4334     // We only want to see those namespaces that have already been defined
4335     // within this scope, because its likely that the user is creating an
4336     // extended namespace declaration. Keep track of the most recent
4337     // definition of each namespace.
4338     std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
4339     for (DeclContext::specific_decl_iterator<NamespaceDecl>
4340          NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
4341          NS != NSEnd; ++NS)
4342       OrigToLatest[NS->getOriginalNamespace()] = *NS;
4343 
4344     // Add the most recent definition (or extended definition) of each
4345     // namespace to the list of results.
4346     Results.EnterNewScope();
4347     for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
4348               NS = OrigToLatest.begin(),
4349            NSEnd = OrigToLatest.end();
4350          NS != NSEnd; ++NS)
4351       Results.AddResult(CodeCompletionResult(
4352                           NS->second, Results.getBasePriority(NS->second),
4353                           nullptr),
4354                         CurContext, nullptr, false);
4355     Results.ExitScope();
4356   }
4357 
4358   HandleCodeCompleteResults(this, CodeCompleter,
4359                             Results.getCompletionContext(),
4360                             Results.data(),Results.size());
4361 }
4362 
4363 void Sema::CodeCompleteNamespaceAliasDecl(Scope *S)  {
4364   if (!CodeCompleter)
4365     return;
4366 
4367   // After "namespace", we expect to see a namespace or alias.
4368   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4369                         CodeCompleter->getCodeCompletionTUInfo(),
4370                         CodeCompletionContext::CCC_Namespace,
4371                         &ResultBuilder::IsNamespaceOrAlias);
4372   CodeCompletionDeclConsumer Consumer(Results, CurContext);
4373   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4374                      CodeCompleter->includeGlobals());
4375   HandleCodeCompleteResults(this, CodeCompleter,
4376                             Results.getCompletionContext(),
4377                             Results.data(),Results.size());
4378 }
4379 
4380 void Sema::CodeCompleteOperatorName(Scope *S) {
4381   if (!CodeCompleter)
4382     return;
4383 
4384   typedef CodeCompletionResult Result;
4385   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4386                         CodeCompleter->getCodeCompletionTUInfo(),
4387                         CodeCompletionContext::CCC_Type,
4388                         &ResultBuilder::IsType);
4389   Results.EnterNewScope();
4390 
4391   // Add the names of overloadable operators.
4392 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly)      \
4393   if (std::strcmp(Spelling, "?"))                                                  \
4394     Results.AddResult(Result(Spelling));
4395 #include "clang/Basic/OperatorKinds.def"
4396 
4397   // Add any type names visible from the current scope
4398   Results.allowNestedNameSpecifiers();
4399   CodeCompletionDeclConsumer Consumer(Results, CurContext);
4400   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4401                      CodeCompleter->includeGlobals());
4402 
4403   // Add any type specifiers
4404   AddTypeSpecifierResults(getLangOpts(), Results);
4405   Results.ExitScope();
4406 
4407   HandleCodeCompleteResults(this, CodeCompleter,
4408                             CodeCompletionContext::CCC_Type,
4409                             Results.data(),Results.size());
4410 }
4411 
4412 void Sema::CodeCompleteConstructorInitializer(
4413                               Decl *ConstructorD,
4414                               ArrayRef <CXXCtorInitializer *> Initializers) {
4415   if (!ConstructorD)
4416     return;
4417 
4418   AdjustDeclIfTemplate(ConstructorD);
4419 
4420   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ConstructorD);
4421   if (!Constructor)
4422     return;
4423 
4424   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4425                         CodeCompleter->getCodeCompletionTUInfo(),
4426                         CodeCompletionContext::CCC_PotentiallyQualifiedName);
4427   Results.EnterNewScope();
4428 
4429   // Fill in any already-initialized fields or base classes.
4430   llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
4431   llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
4432   for (unsigned I = 0, E = Initializers.size(); I != E; ++I) {
4433     if (Initializers[I]->isBaseInitializer())
4434       InitializedBases.insert(
4435         Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
4436     else
4437       InitializedFields.insert(cast<FieldDecl>(
4438                                Initializers[I]->getAnyMember()));
4439   }
4440 
4441   // Add completions for base classes.
4442   CodeCompletionBuilder Builder(Results.getAllocator(),
4443                                 Results.getCodeCompletionTUInfo());
4444   PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
4445   bool SawLastInitializer = Initializers.empty();
4446   CXXRecordDecl *ClassDecl = Constructor->getParent();
4447   for (const auto &Base : ClassDecl->bases()) {
4448     if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
4449              .second) {
4450       SawLastInitializer
4451         = !Initializers.empty() &&
4452           Initializers.back()->isBaseInitializer() &&
4453           Context.hasSameUnqualifiedType(Base.getType(),
4454                QualType(Initializers.back()->getBaseClass(), 0));
4455       continue;
4456     }
4457 
4458     Builder.AddTypedTextChunk(
4459                Results.getAllocator().CopyString(
4460                           Base.getType().getAsString(Policy)));
4461     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4462     Builder.AddPlaceholderChunk("args");
4463     Builder.AddChunk(CodeCompletionString::CK_RightParen);
4464     Results.AddResult(CodeCompletionResult(Builder.TakeString(),
4465                                    SawLastInitializer? CCP_NextInitializer
4466                                                      : CCP_MemberDeclaration));
4467     SawLastInitializer = false;
4468   }
4469 
4470   // Add completions for virtual base classes.
4471   for (const auto &Base : ClassDecl->vbases()) {
4472     if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
4473              .second) {
4474       SawLastInitializer
4475         = !Initializers.empty() &&
4476           Initializers.back()->isBaseInitializer() &&
4477           Context.hasSameUnqualifiedType(Base.getType(),
4478                QualType(Initializers.back()->getBaseClass(), 0));
4479       continue;
4480     }
4481 
4482     Builder.AddTypedTextChunk(
4483                Builder.getAllocator().CopyString(
4484                           Base.getType().getAsString(Policy)));
4485     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4486     Builder.AddPlaceholderChunk("args");
4487     Builder.AddChunk(CodeCompletionString::CK_RightParen);
4488     Results.AddResult(CodeCompletionResult(Builder.TakeString(),
4489                                    SawLastInitializer? CCP_NextInitializer
4490                                                      : CCP_MemberDeclaration));
4491     SawLastInitializer = false;
4492   }
4493 
4494   // Add completions for members.
4495   for (auto *Field : ClassDecl->fields()) {
4496     if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))
4497              .second) {
4498       SawLastInitializer
4499         = !Initializers.empty() &&
4500           Initializers.back()->isAnyMemberInitializer() &&
4501           Initializers.back()->getAnyMember() == Field;
4502       continue;
4503     }
4504 
4505     if (!Field->getDeclName())
4506       continue;
4507 
4508     Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
4509                                          Field->getIdentifier()->getName()));
4510     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4511     Builder.AddPlaceholderChunk("args");
4512     Builder.AddChunk(CodeCompletionString::CK_RightParen);
4513     Results.AddResult(CodeCompletionResult(Builder.TakeString(),
4514                                    SawLastInitializer? CCP_NextInitializer
4515                                                      : CCP_MemberDeclaration,
4516                                            CXCursor_MemberRef,
4517                                            CXAvailability_Available,
4518                                            Field));
4519     SawLastInitializer = false;
4520   }
4521   Results.ExitScope();
4522 
4523   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4524                             Results.data(), Results.size());
4525 }
4526 
4527 /// \brief Determine whether this scope denotes a namespace.
4528 static bool isNamespaceScope(Scope *S) {
4529   DeclContext *DC = S->getEntity();
4530   if (!DC)
4531     return false;
4532 
4533   return DC->isFileContext();
4534 }
4535 
4536 void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
4537                                         bool AfterAmpersand) {
4538   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4539                         CodeCompleter->getCodeCompletionTUInfo(),
4540                         CodeCompletionContext::CCC_Other);
4541   Results.EnterNewScope();
4542 
4543   // Note what has already been captured.
4544   llvm::SmallPtrSet<IdentifierInfo *, 4> Known;
4545   bool IncludedThis = false;
4546   for (const auto &C : Intro.Captures) {
4547     if (C.Kind == LCK_This) {
4548       IncludedThis = true;
4549       continue;
4550     }
4551 
4552     Known.insert(C.Id);
4553   }
4554 
4555   // Look for other capturable variables.
4556   for (; S && !isNamespaceScope(S); S = S->getParent()) {
4557     for (const auto *D : S->decls()) {
4558       const auto *Var = dyn_cast<VarDecl>(D);
4559       if (!Var ||
4560           !Var->hasLocalStorage() ||
4561           Var->hasAttr<BlocksAttr>())
4562         continue;
4563 
4564       if (Known.insert(Var->getIdentifier()).second)
4565         Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration),
4566                           CurContext, nullptr, false);
4567     }
4568   }
4569 
4570   // Add 'this', if it would be valid.
4571   if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy)
4572     addThisCompletion(*this, Results);
4573 
4574   Results.ExitScope();
4575 
4576   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4577                             Results.data(), Results.size());
4578 }
4579 
4580 /// Macro that optionally prepends an "@" to the string literal passed in via
4581 /// Keyword, depending on whether NeedAt is true or false.
4582 #define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) ((NeedAt)? "@" Keyword : Keyword)
4583 
4584 static void AddObjCImplementationResults(const LangOptions &LangOpts,
4585                                          ResultBuilder &Results,
4586                                          bool NeedAt) {
4587   typedef CodeCompletionResult Result;
4588   // Since we have an implementation, we can end it.
4589   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
4590 
4591   CodeCompletionBuilder Builder(Results.getAllocator(),
4592                                 Results.getCodeCompletionTUInfo());
4593   if (LangOpts.ObjC2) {
4594     // @dynamic
4595     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"dynamic"));
4596     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4597     Builder.AddPlaceholderChunk("property");
4598     Results.AddResult(Result(Builder.TakeString()));
4599 
4600     // @synthesize
4601     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synthesize"));
4602     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4603     Builder.AddPlaceholderChunk("property");
4604     Results.AddResult(Result(Builder.TakeString()));
4605   }
4606 }
4607 
4608 static void AddObjCInterfaceResults(const LangOptions &LangOpts,
4609                                     ResultBuilder &Results,
4610                                     bool NeedAt) {
4611   typedef CodeCompletionResult Result;
4612 
4613   // Since we have an interface or protocol, we can end it.
4614   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
4615 
4616   if (LangOpts.ObjC2) {
4617     // @property
4618     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"property")));
4619 
4620     // @required
4621     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"required")));
4622 
4623     // @optional
4624     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"optional")));
4625   }
4626 }
4627 
4628 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
4629   typedef CodeCompletionResult Result;
4630   CodeCompletionBuilder Builder(Results.getAllocator(),
4631                                 Results.getCodeCompletionTUInfo());
4632 
4633   // @class name ;
4634   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"class"));
4635   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4636   Builder.AddPlaceholderChunk("name");
4637   Results.AddResult(Result(Builder.TakeString()));
4638 
4639   if (Results.includeCodePatterns()) {
4640     // @interface name
4641     // FIXME: Could introduce the whole pattern, including superclasses and
4642     // such.
4643     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"interface"));
4644     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4645     Builder.AddPlaceholderChunk("class");
4646     Results.AddResult(Result(Builder.TakeString()));
4647 
4648     // @protocol name
4649     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
4650     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4651     Builder.AddPlaceholderChunk("protocol");
4652     Results.AddResult(Result(Builder.TakeString()));
4653 
4654     // @implementation name
4655     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"implementation"));
4656     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4657     Builder.AddPlaceholderChunk("class");
4658     Results.AddResult(Result(Builder.TakeString()));
4659   }
4660 
4661   // @compatibility_alias name
4662   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"compatibility_alias"));
4663   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4664   Builder.AddPlaceholderChunk("alias");
4665   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4666   Builder.AddPlaceholderChunk("class");
4667   Results.AddResult(Result(Builder.TakeString()));
4668 
4669   if (Results.getSema().getLangOpts().Modules) {
4670     // @import name
4671     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import"));
4672     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4673     Builder.AddPlaceholderChunk("module");
4674     Results.AddResult(Result(Builder.TakeString()));
4675   }
4676 }
4677 
4678 void Sema::CodeCompleteObjCAtDirective(Scope *S) {
4679   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4680                         CodeCompleter->getCodeCompletionTUInfo(),
4681                         CodeCompletionContext::CCC_Other);
4682   Results.EnterNewScope();
4683   if (isa<ObjCImplDecl>(CurContext))
4684     AddObjCImplementationResults(getLangOpts(), Results, false);
4685   else if (CurContext->isObjCContainer())
4686     AddObjCInterfaceResults(getLangOpts(), Results, false);
4687   else
4688     AddObjCTopLevelResults(Results, false);
4689   Results.ExitScope();
4690   HandleCodeCompleteResults(this, CodeCompleter,
4691                             CodeCompletionContext::CCC_Other,
4692                             Results.data(),Results.size());
4693 }
4694 
4695 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
4696   typedef CodeCompletionResult Result;
4697   CodeCompletionBuilder Builder(Results.getAllocator(),
4698                                 Results.getCodeCompletionTUInfo());
4699 
4700   // @encode ( type-name )
4701   const char *EncodeType = "char[]";
4702   if (Results.getSema().getLangOpts().CPlusPlus ||
4703       Results.getSema().getLangOpts().ConstStrings)
4704     EncodeType = "const char[]";
4705   Builder.AddResultTypeChunk(EncodeType);
4706   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"encode"));
4707   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4708   Builder.AddPlaceholderChunk("type-name");
4709   Builder.AddChunk(CodeCompletionString::CK_RightParen);
4710   Results.AddResult(Result(Builder.TakeString()));
4711 
4712   // @protocol ( protocol-name )
4713   Builder.AddResultTypeChunk("Protocol *");
4714   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
4715   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4716   Builder.AddPlaceholderChunk("protocol-name");
4717   Builder.AddChunk(CodeCompletionString::CK_RightParen);
4718   Results.AddResult(Result(Builder.TakeString()));
4719 
4720   // @selector ( selector )
4721   Builder.AddResultTypeChunk("SEL");
4722   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"selector"));
4723   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4724   Builder.AddPlaceholderChunk("selector");
4725   Builder.AddChunk(CodeCompletionString::CK_RightParen);
4726   Results.AddResult(Result(Builder.TakeString()));
4727 
4728   // @"string"
4729   Builder.AddResultTypeChunk("NSString *");
4730   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"\""));
4731   Builder.AddPlaceholderChunk("string");
4732   Builder.AddTextChunk("\"");
4733   Results.AddResult(Result(Builder.TakeString()));
4734 
4735   // @[objects, ...]
4736   Builder.AddResultTypeChunk("NSArray *");
4737   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"["));
4738   Builder.AddPlaceholderChunk("objects, ...");
4739   Builder.AddChunk(CodeCompletionString::CK_RightBracket);
4740   Results.AddResult(Result(Builder.TakeString()));
4741 
4742   // @{key : object, ...}
4743   Builder.AddResultTypeChunk("NSDictionary *");
4744   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"{"));
4745   Builder.AddPlaceholderChunk("key");
4746   Builder.AddChunk(CodeCompletionString::CK_Colon);
4747   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4748   Builder.AddPlaceholderChunk("object, ...");
4749   Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4750   Results.AddResult(Result(Builder.TakeString()));
4751 
4752   // @(expression)
4753   Builder.AddResultTypeChunk("id");
4754   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "("));
4755   Builder.AddPlaceholderChunk("expression");
4756   Builder.AddChunk(CodeCompletionString::CK_RightParen);
4757   Results.AddResult(Result(Builder.TakeString()));
4758 }
4759 
4760 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
4761   typedef CodeCompletionResult Result;
4762   CodeCompletionBuilder Builder(Results.getAllocator(),
4763                                 Results.getCodeCompletionTUInfo());
4764 
4765   if (Results.includeCodePatterns()) {
4766     // @try { statements } @catch ( declaration ) { statements } @finally
4767     //   { statements }
4768     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"try"));
4769     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4770     Builder.AddPlaceholderChunk("statements");
4771     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4772     Builder.AddTextChunk("@catch");
4773     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4774     Builder.AddPlaceholderChunk("parameter");
4775     Builder.AddChunk(CodeCompletionString::CK_RightParen);
4776     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4777     Builder.AddPlaceholderChunk("statements");
4778     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4779     Builder.AddTextChunk("@finally");
4780     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4781     Builder.AddPlaceholderChunk("statements");
4782     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4783     Results.AddResult(Result(Builder.TakeString()));
4784   }
4785 
4786   // @throw
4787   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"throw"));
4788   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4789   Builder.AddPlaceholderChunk("expression");
4790   Results.AddResult(Result(Builder.TakeString()));
4791 
4792   if (Results.includeCodePatterns()) {
4793     // @synchronized ( expression ) { statements }
4794     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synchronized"));
4795     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4796     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4797     Builder.AddPlaceholderChunk("expression");
4798     Builder.AddChunk(CodeCompletionString::CK_RightParen);
4799     Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4800     Builder.AddPlaceholderChunk("statements");
4801     Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4802     Results.AddResult(Result(Builder.TakeString()));
4803   }
4804 }
4805 
4806 static void AddObjCVisibilityResults(const LangOptions &LangOpts,
4807                                      ResultBuilder &Results,
4808                                      bool NeedAt) {
4809   typedef CodeCompletionResult Result;
4810   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"private")));
4811   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"protected")));
4812   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"public")));
4813   if (LangOpts.ObjC2)
4814     Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"package")));
4815 }
4816 
4817 void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
4818   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4819                         CodeCompleter->getCodeCompletionTUInfo(),
4820                         CodeCompletionContext::CCC_Other);
4821   Results.EnterNewScope();
4822   AddObjCVisibilityResults(getLangOpts(), Results, false);
4823   Results.ExitScope();
4824   HandleCodeCompleteResults(this, CodeCompleter,
4825                             CodeCompletionContext::CCC_Other,
4826                             Results.data(),Results.size());
4827 }
4828 
4829 void Sema::CodeCompleteObjCAtStatement(Scope *S) {
4830   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4831                         CodeCompleter->getCodeCompletionTUInfo(),
4832                         CodeCompletionContext::CCC_Other);
4833   Results.EnterNewScope();
4834   AddObjCStatementResults(Results, false);
4835   AddObjCExpressionResults(Results, false);
4836   Results.ExitScope();
4837   HandleCodeCompleteResults(this, CodeCompleter,
4838                             CodeCompletionContext::CCC_Other,
4839                             Results.data(),Results.size());
4840 }
4841 
4842 void Sema::CodeCompleteObjCAtExpression(Scope *S) {
4843   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4844                         CodeCompleter->getCodeCompletionTUInfo(),
4845                         CodeCompletionContext::CCC_Other);
4846   Results.EnterNewScope();
4847   AddObjCExpressionResults(Results, false);
4848   Results.ExitScope();
4849   HandleCodeCompleteResults(this, CodeCompleter,
4850                             CodeCompletionContext::CCC_Other,
4851                             Results.data(),Results.size());
4852 }
4853 
4854 /// \brief Determine whether the addition of the given flag to an Objective-C
4855 /// property's attributes will cause a conflict.
4856 static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
4857   // Check if we've already added this flag.
4858   if (Attributes & NewFlag)
4859     return true;
4860 
4861   Attributes |= NewFlag;
4862 
4863   // Check for collisions with "readonly".
4864   if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
4865       (Attributes & ObjCDeclSpec::DQ_PR_readwrite))
4866     return true;
4867 
4868   // Check for more than one of { assign, copy, retain, strong, weak }.
4869   unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
4870                                          ObjCDeclSpec::DQ_PR_unsafe_unretained |
4871                                              ObjCDeclSpec::DQ_PR_copy |
4872                                              ObjCDeclSpec::DQ_PR_retain |
4873                                              ObjCDeclSpec::DQ_PR_strong |
4874                                              ObjCDeclSpec::DQ_PR_weak);
4875   if (AssignCopyRetMask &&
4876       AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
4877       AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
4878       AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
4879       AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
4880       AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong &&
4881       AssignCopyRetMask != ObjCDeclSpec::DQ_PR_weak)
4882     return true;
4883 
4884   return false;
4885 }
4886 
4887 void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
4888   if (!CodeCompleter)
4889     return;
4890 
4891   unsigned Attributes = ODS.getPropertyAttributes();
4892 
4893   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4894                         CodeCompleter->getCodeCompletionTUInfo(),
4895                         CodeCompletionContext::CCC_Other);
4896   Results.EnterNewScope();
4897   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
4898     Results.AddResult(CodeCompletionResult("readonly"));
4899   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
4900     Results.AddResult(CodeCompletionResult("assign"));
4901   if (!ObjCPropertyFlagConflicts(Attributes,
4902                                  ObjCDeclSpec::DQ_PR_unsafe_unretained))
4903     Results.AddResult(CodeCompletionResult("unsafe_unretained"));
4904   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
4905     Results.AddResult(CodeCompletionResult("readwrite"));
4906   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
4907     Results.AddResult(CodeCompletionResult("retain"));
4908   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
4909     Results.AddResult(CodeCompletionResult("strong"));
4910   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
4911     Results.AddResult(CodeCompletionResult("copy"));
4912   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
4913     Results.AddResult(CodeCompletionResult("nonatomic"));
4914   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
4915     Results.AddResult(CodeCompletionResult("atomic"));
4916 
4917   // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC.
4918   if (getLangOpts().ObjCWeak || getLangOpts().getGC() != LangOptions::NonGC)
4919     if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_weak))
4920       Results.AddResult(CodeCompletionResult("weak"));
4921 
4922   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
4923     CodeCompletionBuilder Setter(Results.getAllocator(),
4924                                  Results.getCodeCompletionTUInfo());
4925     Setter.AddTypedTextChunk("setter");
4926     Setter.AddTextChunk("=");
4927     Setter.AddPlaceholderChunk("method");
4928     Results.AddResult(CodeCompletionResult(Setter.TakeString()));
4929   }
4930   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
4931     CodeCompletionBuilder Getter(Results.getAllocator(),
4932                                  Results.getCodeCompletionTUInfo());
4933     Getter.AddTypedTextChunk("getter");
4934     Getter.AddTextChunk("=");
4935     Getter.AddPlaceholderChunk("method");
4936     Results.AddResult(CodeCompletionResult(Getter.TakeString()));
4937   }
4938   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nullability)) {
4939     Results.AddResult(CodeCompletionResult("nonnull"));
4940     Results.AddResult(CodeCompletionResult("nullable"));
4941     Results.AddResult(CodeCompletionResult("null_unspecified"));
4942     Results.AddResult(CodeCompletionResult("null_resettable"));
4943   }
4944   Results.ExitScope();
4945   HandleCodeCompleteResults(this, CodeCompleter,
4946                             CodeCompletionContext::CCC_Other,
4947                             Results.data(),Results.size());
4948 }
4949 
4950 /// \brief Describes the kind of Objective-C method that we want to find
4951 /// via code completion.
4952 enum ObjCMethodKind {
4953   MK_Any, ///< Any kind of method, provided it means other specified criteria.
4954   MK_ZeroArgSelector, ///< Zero-argument (unary) selector.
4955   MK_OneArgSelector ///< One-argument selector.
4956 };
4957 
4958 static bool isAcceptableObjCSelector(Selector Sel,
4959                                      ObjCMethodKind WantKind,
4960                                      ArrayRef<IdentifierInfo *> SelIdents,
4961                                      bool AllowSameLength = true) {
4962   unsigned NumSelIdents = SelIdents.size();
4963   if (NumSelIdents > Sel.getNumArgs())
4964     return false;
4965 
4966   switch (WantKind) {
4967     case MK_Any:             break;
4968     case MK_ZeroArgSelector: return Sel.isUnarySelector();
4969     case MK_OneArgSelector:  return Sel.getNumArgs() == 1;
4970   }
4971 
4972   if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4973     return false;
4974 
4975   for (unsigned I = 0; I != NumSelIdents; ++I)
4976     if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4977       return false;
4978 
4979   return true;
4980 }
4981 
4982 static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4983                                    ObjCMethodKind WantKind,
4984                                    ArrayRef<IdentifierInfo *> SelIdents,
4985                                    bool AllowSameLength = true) {
4986   return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
4987                                   AllowSameLength);
4988 }
4989 
4990 namespace {
4991   /// \brief A set of selectors, which is used to avoid introducing multiple
4992   /// completions with the same selector into the result set.
4993   typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4994 }
4995 
4996 /// \brief Add all of the Objective-C methods in the given Objective-C
4997 /// container to the set of results.
4998 ///
4999 /// The container will be a class, protocol, category, or implementation of
5000 /// any of the above. This mether will recurse to include methods from
5001 /// the superclasses of classes along with their categories, protocols, and
5002 /// implementations.
5003 ///
5004 /// \param Container the container in which we'll look to find methods.
5005 ///
5006 /// \param WantInstanceMethods Whether to add instance methods (only); if
5007 /// false, this routine will add factory methods (only).
5008 ///
5009 /// \param CurContext the context in which we're performing the lookup that
5010 /// finds methods.
5011 ///
5012 /// \param AllowSameLength Whether we allow a method to be added to the list
5013 /// when it has the same number of parameters as we have selector identifiers.
5014 ///
5015 /// \param Results the structure into which we'll add results.
5016 static void AddObjCMethods(ObjCContainerDecl *Container,
5017                            bool WantInstanceMethods,
5018                            ObjCMethodKind WantKind,
5019                            ArrayRef<IdentifierInfo *> SelIdents,
5020                            DeclContext *CurContext,
5021                            VisitedSelectorSet &Selectors,
5022                            bool AllowSameLength,
5023                            ResultBuilder &Results,
5024                            bool InOriginalClass = true) {
5025   typedef CodeCompletionResult Result;
5026   Container = getContainerDef(Container);
5027   ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
5028   bool isRootClass = IFace && !IFace->getSuperClass();
5029   for (auto *M : Container->methods()) {
5030     // The instance methods on the root class can be messaged via the
5031     // metaclass.
5032     if (M->isInstanceMethod() == WantInstanceMethods ||
5033         (isRootClass && !WantInstanceMethods)) {
5034       // Check whether the selector identifiers we've been given are a
5035       // subset of the identifiers for this particular method.
5036       if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength))
5037         continue;
5038 
5039       if (!Selectors.insert(M->getSelector()).second)
5040         continue;
5041 
5042       Result R = Result(M, Results.getBasePriority(M), nullptr);
5043       R.StartParameter = SelIdents.size();
5044       R.AllParametersAreInformative = (WantKind != MK_Any);
5045       if (!InOriginalClass)
5046         R.Priority += CCD_InBaseClass;
5047       Results.MaybeAddResult(R, CurContext);
5048     }
5049   }
5050 
5051   // Visit the protocols of protocols.
5052   if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5053     if (Protocol->hasDefinition()) {
5054       const ObjCList<ObjCProtocolDecl> &Protocols
5055         = Protocol->getReferencedProtocols();
5056       for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5057                                                 E = Protocols.end();
5058            I != E; ++I)
5059         AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
5060                        CurContext, Selectors, AllowSameLength, Results, false);
5061     }
5062   }
5063 
5064   if (!IFace || !IFace->hasDefinition())
5065     return;
5066 
5067   // Add methods in protocols.
5068   for (auto *I : IFace->protocols())
5069     AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents,
5070                    CurContext, Selectors, AllowSameLength, Results, false);
5071 
5072   // Add methods in categories.
5073   for (auto *CatDecl : IFace->known_categories()) {
5074     AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
5075                    CurContext, Selectors, AllowSameLength,
5076                    Results, InOriginalClass);
5077 
5078     // Add a categories protocol methods.
5079     const ObjCList<ObjCProtocolDecl> &Protocols
5080       = CatDecl->getReferencedProtocols();
5081     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5082                                               E = Protocols.end();
5083          I != E; ++I)
5084       AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
5085                      CurContext, Selectors, AllowSameLength,
5086                      Results, false);
5087 
5088     // Add methods in category implementations.
5089     if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
5090       AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
5091                      CurContext, Selectors, AllowSameLength,
5092                      Results, InOriginalClass);
5093   }
5094 
5095   // Add methods in superclass.
5096   if (IFace->getSuperClass())
5097     AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
5098                    SelIdents, CurContext, Selectors,
5099                    AllowSameLength, Results, false);
5100 
5101   // Add methods in our implementation, if any.
5102   if (ObjCImplementationDecl *Impl = IFace->getImplementation())
5103     AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
5104                    CurContext, Selectors, AllowSameLength,
5105                    Results, InOriginalClass);
5106 }
5107 
5108 
5109 void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
5110   // Try to find the interface where getters might live.
5111   ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
5112   if (!Class) {
5113     if (ObjCCategoryDecl *Category
5114           = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
5115       Class = Category->getClassInterface();
5116 
5117     if (!Class)
5118       return;
5119   }
5120 
5121   // Find all of the potential getters.
5122   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5123                         CodeCompleter->getCodeCompletionTUInfo(),
5124                         CodeCompletionContext::CCC_Other);
5125   Results.EnterNewScope();
5126 
5127   VisitedSelectorSet Selectors;
5128   AddObjCMethods(Class, true, MK_ZeroArgSelector, None, CurContext, Selectors,
5129                  /*AllowSameLength=*/true, Results);
5130   Results.ExitScope();
5131   HandleCodeCompleteResults(this, CodeCompleter,
5132                             CodeCompletionContext::CCC_Other,
5133                             Results.data(),Results.size());
5134 }
5135 
5136 void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
5137   // Try to find the interface where setters might live.
5138   ObjCInterfaceDecl *Class
5139     = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
5140   if (!Class) {
5141     if (ObjCCategoryDecl *Category
5142           = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
5143       Class = Category->getClassInterface();
5144 
5145     if (!Class)
5146       return;
5147   }
5148 
5149   // Find all of the potential getters.
5150   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5151                         CodeCompleter->getCodeCompletionTUInfo(),
5152                         CodeCompletionContext::CCC_Other);
5153   Results.EnterNewScope();
5154 
5155   VisitedSelectorSet Selectors;
5156   AddObjCMethods(Class, true, MK_OneArgSelector, None, CurContext,
5157                  Selectors, /*AllowSameLength=*/true, Results);
5158 
5159   Results.ExitScope();
5160   HandleCodeCompleteResults(this, CodeCompleter,
5161                             CodeCompletionContext::CCC_Other,
5162                             Results.data(),Results.size());
5163 }
5164 
5165 void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
5166                                        bool IsParameter) {
5167   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5168                         CodeCompleter->getCodeCompletionTUInfo(),
5169                         CodeCompletionContext::CCC_Type);
5170   Results.EnterNewScope();
5171 
5172   // Add context-sensitive, Objective-C parameter-passing keywords.
5173   bool AddedInOut = false;
5174   if ((DS.getObjCDeclQualifier() &
5175        (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
5176     Results.AddResult("in");
5177     Results.AddResult("inout");
5178     AddedInOut = true;
5179   }
5180   if ((DS.getObjCDeclQualifier() &
5181        (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
5182     Results.AddResult("out");
5183     if (!AddedInOut)
5184       Results.AddResult("inout");
5185   }
5186   if ((DS.getObjCDeclQualifier() &
5187        (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
5188         ObjCDeclSpec::DQ_Oneway)) == 0) {
5189      Results.AddResult("bycopy");
5190      Results.AddResult("byref");
5191      Results.AddResult("oneway");
5192   }
5193   if ((DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability) == 0) {
5194     Results.AddResult("nonnull");
5195     Results.AddResult("nullable");
5196     Results.AddResult("null_unspecified");
5197   }
5198 
5199   // If we're completing the return type of an Objective-C method and the
5200   // identifier IBAction refers to a macro, provide a completion item for
5201   // an action, e.g.,
5202   //   IBAction)<#selector#>:(id)sender
5203   if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
5204       PP.isMacroDefined("IBAction")) {
5205     CodeCompletionBuilder Builder(Results.getAllocator(),
5206                                   Results.getCodeCompletionTUInfo(),
5207                                   CCP_CodePattern, CXAvailability_Available);
5208     Builder.AddTypedTextChunk("IBAction");
5209     Builder.AddChunk(CodeCompletionString::CK_RightParen);
5210     Builder.AddPlaceholderChunk("selector");
5211     Builder.AddChunk(CodeCompletionString::CK_Colon);
5212     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5213     Builder.AddTextChunk("id");
5214     Builder.AddChunk(CodeCompletionString::CK_RightParen);
5215     Builder.AddTextChunk("sender");
5216     Results.AddResult(CodeCompletionResult(Builder.TakeString()));
5217   }
5218 
5219   // If we're completing the return type, provide 'instancetype'.
5220   if (!IsParameter) {
5221     Results.AddResult(CodeCompletionResult("instancetype"));
5222   }
5223 
5224   // Add various builtin type names and specifiers.
5225   AddOrdinaryNameResults(PCC_Type, S, *this, Results);
5226   Results.ExitScope();
5227 
5228   // Add the various type names
5229   Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
5230   CodeCompletionDeclConsumer Consumer(Results, CurContext);
5231   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5232                      CodeCompleter->includeGlobals());
5233 
5234   if (CodeCompleter->includeMacros())
5235     AddMacroResults(PP, Results, false);
5236 
5237   HandleCodeCompleteResults(this, CodeCompleter,
5238                             CodeCompletionContext::CCC_Type,
5239                             Results.data(), Results.size());
5240 }
5241 
5242 /// \brief When we have an expression with type "id", we may assume
5243 /// that it has some more-specific class type based on knowledge of
5244 /// common uses of Objective-C. This routine returns that class type,
5245 /// or NULL if no better result could be determined.
5246 static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
5247   ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
5248   if (!Msg)
5249     return nullptr;
5250 
5251   Selector Sel = Msg->getSelector();
5252   if (Sel.isNull())
5253     return nullptr;
5254 
5255   IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
5256   if (!Id)
5257     return nullptr;
5258 
5259   ObjCMethodDecl *Method = Msg->getMethodDecl();
5260   if (!Method)
5261     return nullptr;
5262 
5263   // Determine the class that we're sending the message to.
5264   ObjCInterfaceDecl *IFace = nullptr;
5265   switch (Msg->getReceiverKind()) {
5266   case ObjCMessageExpr::Class:
5267     if (const ObjCObjectType *ObjType
5268                            = Msg->getClassReceiver()->getAs<ObjCObjectType>())
5269       IFace = ObjType->getInterface();
5270     break;
5271 
5272   case ObjCMessageExpr::Instance: {
5273     QualType T = Msg->getInstanceReceiver()->getType();
5274     if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
5275       IFace = Ptr->getInterfaceDecl();
5276     break;
5277   }
5278 
5279   case ObjCMessageExpr::SuperInstance:
5280   case ObjCMessageExpr::SuperClass:
5281     break;
5282   }
5283 
5284   if (!IFace)
5285     return nullptr;
5286 
5287   ObjCInterfaceDecl *Super = IFace->getSuperClass();
5288   if (Method->isInstanceMethod())
5289     return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5290       .Case("retain", IFace)
5291       .Case("strong", IFace)
5292       .Case("autorelease", IFace)
5293       .Case("copy", IFace)
5294       .Case("copyWithZone", IFace)
5295       .Case("mutableCopy", IFace)
5296       .Case("mutableCopyWithZone", IFace)
5297       .Case("awakeFromCoder", IFace)
5298       .Case("replacementObjectFromCoder", IFace)
5299       .Case("class", IFace)
5300       .Case("classForCoder", IFace)
5301       .Case("superclass", Super)
5302       .Default(nullptr);
5303 
5304   return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5305     .Case("new", IFace)
5306     .Case("alloc", IFace)
5307     .Case("allocWithZone", IFace)
5308     .Case("class", IFace)
5309     .Case("superclass", Super)
5310     .Default(nullptr);
5311 }
5312 
5313 // Add a special completion for a message send to "super", which fills in the
5314 // most likely case of forwarding all of our arguments to the superclass
5315 // function.
5316 ///
5317 /// \param S The semantic analysis object.
5318 ///
5319 /// \param NeedSuperKeyword Whether we need to prefix this completion with
5320 /// the "super" keyword. Otherwise, we just need to provide the arguments.
5321 ///
5322 /// \param SelIdents The identifiers in the selector that have already been
5323 /// provided as arguments for a send to "super".
5324 ///
5325 /// \param Results The set of results to augment.
5326 ///
5327 /// \returns the Objective-C method declaration that would be invoked by
5328 /// this "super" completion. If NULL, no completion was added.
5329 static ObjCMethodDecl *AddSuperSendCompletion(
5330                                           Sema &S, bool NeedSuperKeyword,
5331                                           ArrayRef<IdentifierInfo *> SelIdents,
5332                                           ResultBuilder &Results) {
5333   ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
5334   if (!CurMethod)
5335     return nullptr;
5336 
5337   ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
5338   if (!Class)
5339     return nullptr;
5340 
5341   // Try to find a superclass method with the same selector.
5342   ObjCMethodDecl *SuperMethod = nullptr;
5343   while ((Class = Class->getSuperClass()) && !SuperMethod) {
5344     // Check in the class
5345     SuperMethod = Class->getMethod(CurMethod->getSelector(),
5346                                    CurMethod->isInstanceMethod());
5347 
5348     // Check in categories or class extensions.
5349     if (!SuperMethod) {
5350       for (const auto *Cat : Class->known_categories()) {
5351         if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(),
5352                                                CurMethod->isInstanceMethod())))
5353           break;
5354       }
5355     }
5356   }
5357 
5358   if (!SuperMethod)
5359     return nullptr;
5360 
5361   // Check whether the superclass method has the same signature.
5362   if (CurMethod->param_size() != SuperMethod->param_size() ||
5363       CurMethod->isVariadic() != SuperMethod->isVariadic())
5364     return nullptr;
5365 
5366   for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
5367                                    CurPEnd = CurMethod->param_end(),
5368                                     SuperP = SuperMethod->param_begin();
5369        CurP != CurPEnd; ++CurP, ++SuperP) {
5370     // Make sure the parameter types are compatible.
5371     if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
5372                                           (*SuperP)->getType()))
5373       return nullptr;
5374 
5375     // Make sure we have a parameter name to forward!
5376     if (!(*CurP)->getIdentifier())
5377       return nullptr;
5378   }
5379 
5380   // We have a superclass method. Now, form the send-to-super completion.
5381   CodeCompletionBuilder Builder(Results.getAllocator(),
5382                                 Results.getCodeCompletionTUInfo());
5383 
5384   // Give this completion a return type.
5385   AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
5386                      Results.getCompletionContext().getBaseType(),
5387                      Builder);
5388 
5389   // If we need the "super" keyword, add it (plus some spacing).
5390   if (NeedSuperKeyword) {
5391     Builder.AddTypedTextChunk("super");
5392     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5393   }
5394 
5395   Selector Sel = CurMethod->getSelector();
5396   if (Sel.isUnarySelector()) {
5397     if (NeedSuperKeyword)
5398       Builder.AddTextChunk(Builder.getAllocator().CopyString(
5399                                   Sel.getNameForSlot(0)));
5400     else
5401       Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
5402                                    Sel.getNameForSlot(0)));
5403   } else {
5404     ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
5405     for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
5406       if (I > SelIdents.size())
5407         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5408 
5409       if (I < SelIdents.size())
5410         Builder.AddInformativeChunk(
5411                    Builder.getAllocator().CopyString(
5412                                                  Sel.getNameForSlot(I) + ":"));
5413       else if (NeedSuperKeyword || I > SelIdents.size()) {
5414         Builder.AddTextChunk(
5415                  Builder.getAllocator().CopyString(
5416                                                   Sel.getNameForSlot(I) + ":"));
5417         Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
5418                                          (*CurP)->getIdentifier()->getName()));
5419       } else {
5420         Builder.AddTypedTextChunk(
5421                   Builder.getAllocator().CopyString(
5422                                                   Sel.getNameForSlot(I) + ":"));
5423         Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
5424                                          (*CurP)->getIdentifier()->getName()));
5425       }
5426     }
5427   }
5428 
5429   Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod,
5430                                          CCP_SuperCompletion));
5431   return SuperMethod;
5432 }
5433 
5434 void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
5435   typedef CodeCompletionResult Result;
5436   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5437                         CodeCompleter->getCodeCompletionTUInfo(),
5438                         CodeCompletionContext::CCC_ObjCMessageReceiver,
5439                         getLangOpts().CPlusPlus11
5440                           ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture
5441                           : &ResultBuilder::IsObjCMessageReceiver);
5442 
5443   CodeCompletionDeclConsumer Consumer(Results, CurContext);
5444   Results.EnterNewScope();
5445   LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5446                      CodeCompleter->includeGlobals());
5447 
5448   // If we are in an Objective-C method inside a class that has a superclass,
5449   // add "super" as an option.
5450   if (ObjCMethodDecl *Method = getCurMethodDecl())
5451     if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
5452       if (Iface->getSuperClass()) {
5453         Results.AddResult(Result("super"));
5454 
5455         AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, None, Results);
5456       }
5457 
5458   if (getLangOpts().CPlusPlus11)
5459     addThisCompletion(*this, Results);
5460 
5461   Results.ExitScope();
5462 
5463   if (CodeCompleter->includeMacros())
5464     AddMacroResults(PP, Results, false);
5465   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5466                             Results.data(), Results.size());
5467 
5468 }
5469 
5470 void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
5471                                         ArrayRef<IdentifierInfo *> SelIdents,
5472                                         bool AtArgumentExpression) {
5473   ObjCInterfaceDecl *CDecl = nullptr;
5474   if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5475     // Figure out which interface we're in.
5476     CDecl = CurMethod->getClassInterface();
5477     if (!CDecl)
5478       return;
5479 
5480     // Find the superclass of this class.
5481     CDecl = CDecl->getSuperClass();
5482     if (!CDecl)
5483       return;
5484 
5485     if (CurMethod->isInstanceMethod()) {
5486       // We are inside an instance method, which means that the message
5487       // send [super ...] is actually calling an instance method on the
5488       // current object.
5489       return CodeCompleteObjCInstanceMessage(S, nullptr, SelIdents,
5490                                              AtArgumentExpression,
5491                                              CDecl);
5492     }
5493 
5494     // Fall through to send to the superclass in CDecl.
5495   } else {
5496     // "super" may be the name of a type or variable. Figure out which
5497     // it is.
5498     IdentifierInfo *Super = getSuperIdentifier();
5499     NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
5500                                      LookupOrdinaryName);
5501     if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
5502       // "super" names an interface. Use it.
5503     } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
5504       if (const ObjCObjectType *Iface
5505             = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
5506         CDecl = Iface->getInterface();
5507     } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
5508       // "super" names an unresolved type; we can't be more specific.
5509     } else {
5510       // Assume that "super" names some kind of value and parse that way.
5511       CXXScopeSpec SS;
5512       SourceLocation TemplateKWLoc;
5513       UnqualifiedId id;
5514       id.setIdentifier(Super, SuperLoc);
5515       ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id,
5516                                                false, false);
5517       return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
5518                                              SelIdents,
5519                                              AtArgumentExpression);
5520     }
5521 
5522     // Fall through
5523   }
5524 
5525   ParsedType Receiver;
5526   if (CDecl)
5527     Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
5528   return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
5529                                       AtArgumentExpression,
5530                                       /*IsSuper=*/true);
5531 }
5532 
5533 /// \brief Given a set of code-completion results for the argument of a message
5534 /// send, determine the preferred type (if any) for that argument expression.
5535 static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
5536                                                        unsigned NumSelIdents) {
5537   typedef CodeCompletionResult Result;
5538   ASTContext &Context = Results.getSema().Context;
5539 
5540   QualType PreferredType;
5541   unsigned BestPriority = CCP_Unlikely * 2;
5542   Result *ResultsData = Results.data();
5543   for (unsigned I = 0, N = Results.size(); I != N; ++I) {
5544     Result &R = ResultsData[I];
5545     if (R.Kind == Result::RK_Declaration &&
5546         isa<ObjCMethodDecl>(R.Declaration)) {
5547       if (R.Priority <= BestPriority) {
5548         const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
5549         if (NumSelIdents <= Method->param_size()) {
5550           QualType MyPreferredType = Method->parameters()[NumSelIdents - 1]
5551                                        ->getType();
5552           if (R.Priority < BestPriority || PreferredType.isNull()) {
5553             BestPriority = R.Priority;
5554             PreferredType = MyPreferredType;
5555           } else if (!Context.hasSameUnqualifiedType(PreferredType,
5556                                                      MyPreferredType)) {
5557             PreferredType = QualType();
5558           }
5559         }
5560       }
5561     }
5562   }
5563 
5564   return PreferredType;
5565 }
5566 
5567 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
5568                                        ParsedType Receiver,
5569                                        ArrayRef<IdentifierInfo *> SelIdents,
5570                                        bool AtArgumentExpression,
5571                                        bool IsSuper,
5572                                        ResultBuilder &Results) {
5573   typedef CodeCompletionResult Result;
5574   ObjCInterfaceDecl *CDecl = nullptr;
5575 
5576   // If the given name refers to an interface type, retrieve the
5577   // corresponding declaration.
5578   if (Receiver) {
5579     QualType T = SemaRef.GetTypeFromParser(Receiver, nullptr);
5580     if (!T.isNull())
5581       if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
5582         CDecl = Interface->getInterface();
5583   }
5584 
5585   // Add all of the factory methods in this Objective-C class, its protocols,
5586   // superclasses, categories, implementation, etc.
5587   Results.EnterNewScope();
5588 
5589   // If this is a send-to-super, try to add the special "super" send
5590   // completion.
5591   if (IsSuper) {
5592     if (ObjCMethodDecl *SuperMethod
5593         = AddSuperSendCompletion(SemaRef, false, SelIdents, Results))
5594       Results.Ignore(SuperMethod);
5595   }
5596 
5597   // If we're inside an Objective-C method definition, prefer its selector to
5598   // others.
5599   if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
5600     Results.setPreferredSelector(CurMethod->getSelector());
5601 
5602   VisitedSelectorSet Selectors;
5603   if (CDecl)
5604     AddObjCMethods(CDecl, false, MK_Any, SelIdents,
5605                    SemaRef.CurContext, Selectors, AtArgumentExpression,
5606                    Results);
5607   else {
5608     // We're messaging "id" as a type; provide all class/factory methods.
5609 
5610     // If we have an external source, load the entire class method
5611     // pool from the AST file.
5612     if (SemaRef.getExternalSource()) {
5613       for (uint32_t I = 0,
5614                     N = SemaRef.getExternalSource()->GetNumExternalSelectors();
5615            I != N; ++I) {
5616         Selector Sel = SemaRef.getExternalSource()->GetExternalSelector(I);
5617         if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
5618           continue;
5619 
5620         SemaRef.ReadMethodPool(Sel);
5621       }
5622     }
5623 
5624     for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
5625                                        MEnd = SemaRef.MethodPool.end();
5626          M != MEnd; ++M) {
5627       for (ObjCMethodList *MethList = &M->second.second;
5628            MethList && MethList->getMethod();
5629            MethList = MethList->getNext()) {
5630         if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
5631           continue;
5632 
5633         Result R(MethList->getMethod(),
5634                  Results.getBasePriority(MethList->getMethod()), nullptr);
5635         R.StartParameter = SelIdents.size();
5636         R.AllParametersAreInformative = false;
5637         Results.MaybeAddResult(R, SemaRef.CurContext);
5638       }
5639     }
5640   }
5641 
5642   Results.ExitScope();
5643 }
5644 
5645 void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
5646                                         ArrayRef<IdentifierInfo *> SelIdents,
5647                                         bool AtArgumentExpression,
5648                                         bool IsSuper) {
5649 
5650   QualType T = this->GetTypeFromParser(Receiver);
5651 
5652   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5653                         CodeCompleter->getCodeCompletionTUInfo(),
5654               CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
5655                                     T, SelIdents));
5656 
5657   AddClassMessageCompletions(*this, S, Receiver, SelIdents,
5658                              AtArgumentExpression, IsSuper, Results);
5659 
5660   // If we're actually at the argument expression (rather than prior to the
5661   // selector), we're actually performing code completion for an expression.
5662   // Determine whether we have a single, best method. If so, we can
5663   // code-complete the expression using the corresponding parameter type as
5664   // our preferred type, improving completion results.
5665   if (AtArgumentExpression) {
5666     QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
5667                                                               SelIdents.size());
5668     if (PreferredType.isNull())
5669       CodeCompleteOrdinaryName(S, PCC_Expression);
5670     else
5671       CodeCompleteExpression(S, PreferredType);
5672     return;
5673   }
5674 
5675   HandleCodeCompleteResults(this, CodeCompleter,
5676                             Results.getCompletionContext(),
5677                             Results.data(), Results.size());
5678 }
5679 
5680 void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
5681                                            ArrayRef<IdentifierInfo *> SelIdents,
5682                                            bool AtArgumentExpression,
5683                                            ObjCInterfaceDecl *Super) {
5684   typedef CodeCompletionResult Result;
5685 
5686   Expr *RecExpr = static_cast<Expr *>(Receiver);
5687 
5688   // If necessary, apply function/array conversion to the receiver.
5689   // C99 6.7.5.3p[7,8].
5690   if (RecExpr) {
5691     ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
5692     if (Conv.isInvalid()) // conversion failed. bail.
5693       return;
5694     RecExpr = Conv.get();
5695   }
5696   QualType ReceiverType = RecExpr? RecExpr->getType()
5697                           : Super? Context.getObjCObjectPointerType(
5698                                             Context.getObjCInterfaceType(Super))
5699                                  : Context.getObjCIdType();
5700 
5701   // If we're messaging an expression with type "id" or "Class", check
5702   // whether we know something special about the receiver that allows
5703   // us to assume a more-specific receiver type.
5704   if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) {
5705     if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
5706       if (ReceiverType->isObjCClassType())
5707         return CodeCompleteObjCClassMessage(S,
5708                        ParsedType::make(Context.getObjCInterfaceType(IFace)),
5709                                             SelIdents,
5710                                             AtArgumentExpression, Super);
5711 
5712       ReceiverType = Context.getObjCObjectPointerType(
5713                                           Context.getObjCInterfaceType(IFace));
5714     }
5715   } else if (RecExpr && getLangOpts().CPlusPlus) {
5716     ExprResult Conv = PerformContextuallyConvertToObjCPointer(RecExpr);
5717     if (Conv.isUsable()) {
5718       RecExpr = Conv.get();
5719       ReceiverType = RecExpr->getType();
5720     }
5721   }
5722 
5723   // Build the set of methods we can see.
5724   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5725                         CodeCompleter->getCodeCompletionTUInfo(),
5726            CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
5727                                  ReceiverType, SelIdents));
5728 
5729   Results.EnterNewScope();
5730 
5731   // If this is a send-to-super, try to add the special "super" send
5732   // completion.
5733   if (Super) {
5734     if (ObjCMethodDecl *SuperMethod
5735           = AddSuperSendCompletion(*this, false, SelIdents, Results))
5736       Results.Ignore(SuperMethod);
5737   }
5738 
5739   // If we're inside an Objective-C method definition, prefer its selector to
5740   // others.
5741   if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
5742     Results.setPreferredSelector(CurMethod->getSelector());
5743 
5744   // Keep track of the selectors we've already added.
5745   VisitedSelectorSet Selectors;
5746 
5747   // Handle messages to Class. This really isn't a message to an instance
5748   // method, so we treat it the same way we would treat a message send to a
5749   // class method.
5750   if (ReceiverType->isObjCClassType() ||
5751       ReceiverType->isObjCQualifiedClassType()) {
5752     if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5753       if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
5754         AddObjCMethods(ClassDecl, false, MK_Any, SelIdents,
5755                        CurContext, Selectors, AtArgumentExpression, Results);
5756     }
5757   }
5758   // Handle messages to a qualified ID ("id<foo>").
5759   else if (const ObjCObjectPointerType *QualID
5760              = ReceiverType->getAsObjCQualifiedIdType()) {
5761     // Search protocols for instance methods.
5762     for (auto *I : QualID->quals())
5763       AddObjCMethods(I, true, MK_Any, SelIdents, CurContext,
5764                      Selectors, AtArgumentExpression, Results);
5765   }
5766   // Handle messages to a pointer to interface type.
5767   else if (const ObjCObjectPointerType *IFacePtr
5768                               = ReceiverType->getAsObjCInterfacePointerType()) {
5769     // Search the class, its superclasses, etc., for instance methods.
5770     AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
5771                    CurContext, Selectors, AtArgumentExpression,
5772                    Results);
5773 
5774     // Search protocols for instance methods.
5775     for (auto *I : IFacePtr->quals())
5776       AddObjCMethods(I, true, MK_Any, SelIdents, CurContext,
5777                      Selectors, AtArgumentExpression, Results);
5778   }
5779   // Handle messages to "id".
5780   else if (ReceiverType->isObjCIdType()) {
5781     // We're messaging "id", so provide all instance methods we know
5782     // about as code-completion results.
5783 
5784     // If we have an external source, load the entire class method
5785     // pool from the AST file.
5786     if (ExternalSource) {
5787       for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5788            I != N; ++I) {
5789         Selector Sel = ExternalSource->GetExternalSelector(I);
5790         if (Sel.isNull() || MethodPool.count(Sel))
5791           continue;
5792 
5793         ReadMethodPool(Sel);
5794       }
5795     }
5796 
5797     for (GlobalMethodPool::iterator M = MethodPool.begin(),
5798                                     MEnd = MethodPool.end();
5799          M != MEnd; ++M) {
5800       for (ObjCMethodList *MethList = &M->second.first;
5801            MethList && MethList->getMethod();
5802            MethList = MethList->getNext()) {
5803         if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
5804           continue;
5805 
5806         if (!Selectors.insert(MethList->getMethod()->getSelector()).second)
5807           continue;
5808 
5809         Result R(MethList->getMethod(),
5810                  Results.getBasePriority(MethList->getMethod()), nullptr);
5811         R.StartParameter = SelIdents.size();
5812         R.AllParametersAreInformative = false;
5813         Results.MaybeAddResult(R, CurContext);
5814       }
5815     }
5816   }
5817   Results.ExitScope();
5818 
5819 
5820   // If we're actually at the argument expression (rather than prior to the
5821   // selector), we're actually performing code completion for an expression.
5822   // Determine whether we have a single, best method. If so, we can
5823   // code-complete the expression using the corresponding parameter type as
5824   // our preferred type, improving completion results.
5825   if (AtArgumentExpression) {
5826     QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
5827                                                               SelIdents.size());
5828     if (PreferredType.isNull())
5829       CodeCompleteOrdinaryName(S, PCC_Expression);
5830     else
5831       CodeCompleteExpression(S, PreferredType);
5832     return;
5833   }
5834 
5835   HandleCodeCompleteResults(this, CodeCompleter,
5836                             Results.getCompletionContext(),
5837                             Results.data(),Results.size());
5838 }
5839 
5840 void Sema::CodeCompleteObjCForCollection(Scope *S,
5841                                          DeclGroupPtrTy IterationVar) {
5842   CodeCompleteExpressionData Data;
5843   Data.ObjCCollection = true;
5844 
5845   if (IterationVar.getAsOpaquePtr()) {
5846     DeclGroupRef DG = IterationVar.get();
5847     for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
5848       if (*I)
5849         Data.IgnoreDecls.push_back(*I);
5850     }
5851   }
5852 
5853   CodeCompleteExpression(S, Data);
5854 }
5855 
5856 void Sema::CodeCompleteObjCSelector(Scope *S,
5857                                     ArrayRef<IdentifierInfo *> SelIdents) {
5858   // If we have an external source, load the entire class method
5859   // pool from the AST file.
5860   if (ExternalSource) {
5861     for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5862          I != N; ++I) {
5863       Selector Sel = ExternalSource->GetExternalSelector(I);
5864       if (Sel.isNull() || MethodPool.count(Sel))
5865         continue;
5866 
5867       ReadMethodPool(Sel);
5868     }
5869   }
5870 
5871   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5872                         CodeCompleter->getCodeCompletionTUInfo(),
5873                         CodeCompletionContext::CCC_SelectorName);
5874   Results.EnterNewScope();
5875   for (GlobalMethodPool::iterator M = MethodPool.begin(),
5876                                MEnd = MethodPool.end();
5877        M != MEnd; ++M) {
5878 
5879     Selector Sel = M->first;
5880     if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents))
5881       continue;
5882 
5883     CodeCompletionBuilder Builder(Results.getAllocator(),
5884                                   Results.getCodeCompletionTUInfo());
5885     if (Sel.isUnarySelector()) {
5886       Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
5887                                                        Sel.getNameForSlot(0)));
5888       Results.AddResult(Builder.TakeString());
5889       continue;
5890     }
5891 
5892     std::string Accumulator;
5893     for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
5894       if (I == SelIdents.size()) {
5895         if (!Accumulator.empty()) {
5896           Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
5897                                                  Accumulator));
5898           Accumulator.clear();
5899         }
5900       }
5901 
5902       Accumulator += Sel.getNameForSlot(I);
5903       Accumulator += ':';
5904     }
5905     Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
5906     Results.AddResult(Builder.TakeString());
5907   }
5908   Results.ExitScope();
5909 
5910   HandleCodeCompleteResults(this, CodeCompleter,
5911                             CodeCompletionContext::CCC_SelectorName,
5912                             Results.data(), Results.size());
5913 }
5914 
5915 /// \brief Add all of the protocol declarations that we find in the given
5916 /// (translation unit) context.
5917 static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
5918                                bool OnlyForwardDeclarations,
5919                                ResultBuilder &Results) {
5920   typedef CodeCompletionResult Result;
5921 
5922   for (const auto *D : Ctx->decls()) {
5923     // Record any protocols we find.
5924     if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(D))
5925       if (!OnlyForwardDeclarations || !Proto->hasDefinition())
5926         Results.AddResult(Result(Proto, Results.getBasePriority(Proto),nullptr),
5927                           CurContext, nullptr, false);
5928   }
5929 }
5930 
5931 void Sema::CodeCompleteObjCProtocolReferences(
5932                                         ArrayRef<IdentifierLocPair> Protocols) {
5933   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5934                         CodeCompleter->getCodeCompletionTUInfo(),
5935                         CodeCompletionContext::CCC_ObjCProtocolName);
5936 
5937   if (CodeCompleter && CodeCompleter->includeGlobals()) {
5938     Results.EnterNewScope();
5939 
5940     // Tell the result set to ignore all of the protocols we have
5941     // already seen.
5942     // FIXME: This doesn't work when caching code-completion results.
5943     for (const IdentifierLocPair &Pair : Protocols)
5944       if (ObjCProtocolDecl *Protocol = LookupProtocol(Pair.first,
5945                                                       Pair.second))
5946         Results.Ignore(Protocol);
5947 
5948     // Add all protocols.
5949     AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
5950                        Results);
5951 
5952     Results.ExitScope();
5953   }
5954 
5955   HandleCodeCompleteResults(this, CodeCompleter,
5956                             CodeCompletionContext::CCC_ObjCProtocolName,
5957                             Results.data(),Results.size());
5958 }
5959 
5960 void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
5961   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5962                         CodeCompleter->getCodeCompletionTUInfo(),
5963                         CodeCompletionContext::CCC_ObjCProtocolName);
5964 
5965   if (CodeCompleter && CodeCompleter->includeGlobals()) {
5966     Results.EnterNewScope();
5967 
5968     // Add all protocols.
5969     AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5970                        Results);
5971 
5972     Results.ExitScope();
5973   }
5974 
5975   HandleCodeCompleteResults(this, CodeCompleter,
5976                             CodeCompletionContext::CCC_ObjCProtocolName,
5977                             Results.data(),Results.size());
5978 }
5979 
5980 /// \brief Add all of the Objective-C interface declarations that we find in
5981 /// the given (translation unit) context.
5982 static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5983                                 bool OnlyForwardDeclarations,
5984                                 bool OnlyUnimplemented,
5985                                 ResultBuilder &Results) {
5986   typedef CodeCompletionResult Result;
5987 
5988   for (const auto *D : Ctx->decls()) {
5989     // Record any interfaces we find.
5990     if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
5991       if ((!OnlyForwardDeclarations || !Class->hasDefinition()) &&
5992           (!OnlyUnimplemented || !Class->getImplementation()))
5993         Results.AddResult(Result(Class, Results.getBasePriority(Class),nullptr),
5994                           CurContext, nullptr, false);
5995   }
5996 }
5997 
5998 void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
5999   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6000                         CodeCompleter->getCodeCompletionTUInfo(),
6001                         CodeCompletionContext::CCC_Other);
6002   Results.EnterNewScope();
6003 
6004   if (CodeCompleter->includeGlobals()) {
6005     // Add all classes.
6006     AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6007                         false, Results);
6008   }
6009 
6010   Results.ExitScope();
6011 
6012   HandleCodeCompleteResults(this, CodeCompleter,
6013                             CodeCompletionContext::CCC_ObjCInterfaceName,
6014                             Results.data(),Results.size());
6015 }
6016 
6017 void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
6018                                       SourceLocation ClassNameLoc) {
6019   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6020                         CodeCompleter->getCodeCompletionTUInfo(),
6021                         CodeCompletionContext::CCC_ObjCInterfaceName);
6022   Results.EnterNewScope();
6023 
6024   // Make sure that we ignore the class we're currently defining.
6025   NamedDecl *CurClass
6026     = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
6027   if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
6028     Results.Ignore(CurClass);
6029 
6030   if (CodeCompleter->includeGlobals()) {
6031     // Add all classes.
6032     AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6033                         false, Results);
6034   }
6035 
6036   Results.ExitScope();
6037 
6038   HandleCodeCompleteResults(this, CodeCompleter,
6039                             CodeCompletionContext::CCC_ObjCInterfaceName,
6040                             Results.data(),Results.size());
6041 }
6042 
6043 void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
6044   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6045                         CodeCompleter->getCodeCompletionTUInfo(),
6046                         CodeCompletionContext::CCC_Other);
6047   Results.EnterNewScope();
6048 
6049   if (CodeCompleter->includeGlobals()) {
6050     // Add all unimplemented classes.
6051     AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6052                         true, Results);
6053   }
6054 
6055   Results.ExitScope();
6056 
6057   HandleCodeCompleteResults(this, CodeCompleter,
6058                             CodeCompletionContext::CCC_ObjCInterfaceName,
6059                             Results.data(),Results.size());
6060 }
6061 
6062 void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
6063                                              IdentifierInfo *ClassName,
6064                                              SourceLocation ClassNameLoc) {
6065   typedef CodeCompletionResult Result;
6066 
6067   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6068                         CodeCompleter->getCodeCompletionTUInfo(),
6069                         CodeCompletionContext::CCC_ObjCCategoryName);
6070 
6071   // Ignore any categories we find that have already been implemented by this
6072   // interface.
6073   llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
6074   NamedDecl *CurClass
6075     = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
6076   if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)){
6077     for (const auto *Cat : Class->visible_categories())
6078       CategoryNames.insert(Cat->getIdentifier());
6079   }
6080 
6081   // Add all of the categories we know about.
6082   Results.EnterNewScope();
6083   TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
6084   for (const auto *D : TU->decls())
6085     if (const auto *Category = dyn_cast<ObjCCategoryDecl>(D))
6086       if (CategoryNames.insert(Category->getIdentifier()).second)
6087         Results.AddResult(Result(Category, Results.getBasePriority(Category),
6088                                  nullptr),
6089                           CurContext, nullptr, false);
6090   Results.ExitScope();
6091 
6092   HandleCodeCompleteResults(this, CodeCompleter,
6093                             CodeCompletionContext::CCC_ObjCCategoryName,
6094                             Results.data(),Results.size());
6095 }
6096 
6097 void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
6098                                                   IdentifierInfo *ClassName,
6099                                                   SourceLocation ClassNameLoc) {
6100   typedef CodeCompletionResult Result;
6101 
6102   // Find the corresponding interface. If we couldn't find the interface, the
6103   // program itself is ill-formed. However, we'll try to be helpful still by
6104   // providing the list of all of the categories we know about.
6105   NamedDecl *CurClass
6106     = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
6107   ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
6108   if (!Class)
6109     return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
6110 
6111   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6112                         CodeCompleter->getCodeCompletionTUInfo(),
6113                         CodeCompletionContext::CCC_ObjCCategoryName);
6114 
6115   // Add all of the categories that have have corresponding interface
6116   // declarations in this class and any of its superclasses, except for
6117   // already-implemented categories in the class itself.
6118   llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
6119   Results.EnterNewScope();
6120   bool IgnoreImplemented = true;
6121   while (Class) {
6122     for (const auto *Cat : Class->visible_categories()) {
6123       if ((!IgnoreImplemented || !Cat->getImplementation()) &&
6124           CategoryNames.insert(Cat->getIdentifier()).second)
6125         Results.AddResult(Result(Cat, Results.getBasePriority(Cat), nullptr),
6126                           CurContext, nullptr, false);
6127     }
6128 
6129     Class = Class->getSuperClass();
6130     IgnoreImplemented = false;
6131   }
6132   Results.ExitScope();
6133 
6134   HandleCodeCompleteResults(this, CodeCompleter,
6135                             CodeCompletionContext::CCC_ObjCCategoryName,
6136                             Results.data(),Results.size());
6137 }
6138 
6139 void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
6140   CodeCompletionContext CCContext(CodeCompletionContext::CCC_Other);
6141   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6142                         CodeCompleter->getCodeCompletionTUInfo(),
6143                         CCContext);
6144 
6145   // Figure out where this @synthesize lives.
6146   ObjCContainerDecl *Container
6147     = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
6148   if (!Container ||
6149       (!isa<ObjCImplementationDecl>(Container) &&
6150        !isa<ObjCCategoryImplDecl>(Container)))
6151     return;
6152 
6153   // Ignore any properties that have already been implemented.
6154   Container = getContainerDef(Container);
6155   for (const auto *D : Container->decls())
6156     if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D))
6157       Results.Ignore(PropertyImpl->getPropertyDecl());
6158 
6159   // Add any properties that we find.
6160   AddedPropertiesSet AddedProperties;
6161   Results.EnterNewScope();
6162   if (ObjCImplementationDecl *ClassImpl
6163         = dyn_cast<ObjCImplementationDecl>(Container))
6164     AddObjCProperties(CCContext, ClassImpl->getClassInterface(), false,
6165                       /*AllowNullaryMethods=*/false, CurContext,
6166                       AddedProperties, Results);
6167   else
6168     AddObjCProperties(CCContext,
6169                       cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
6170                       false, /*AllowNullaryMethods=*/false, CurContext,
6171                       AddedProperties, Results);
6172   Results.ExitScope();
6173 
6174   HandleCodeCompleteResults(this, CodeCompleter,
6175                             CodeCompletionContext::CCC_Other,
6176                             Results.data(),Results.size());
6177 }
6178 
6179 void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
6180                                                   IdentifierInfo *PropertyName) {
6181   typedef CodeCompletionResult Result;
6182   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6183                         CodeCompleter->getCodeCompletionTUInfo(),
6184                         CodeCompletionContext::CCC_Other);
6185 
6186   // Figure out where this @synthesize lives.
6187   ObjCContainerDecl *Container
6188     = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
6189   if (!Container ||
6190       (!isa<ObjCImplementationDecl>(Container) &&
6191        !isa<ObjCCategoryImplDecl>(Container)))
6192     return;
6193 
6194   // Figure out which interface we're looking into.
6195   ObjCInterfaceDecl *Class = nullptr;
6196   if (ObjCImplementationDecl *ClassImpl
6197                                  = dyn_cast<ObjCImplementationDecl>(Container))
6198     Class = ClassImpl->getClassInterface();
6199   else
6200     Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
6201                                                           ->getClassInterface();
6202 
6203   // Determine the type of the property we're synthesizing.
6204   QualType PropertyType = Context.getObjCIdType();
6205   if (Class) {
6206     if (ObjCPropertyDecl *Property = Class->FindPropertyDeclaration(
6207             PropertyName, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
6208       PropertyType
6209         = Property->getType().getNonReferenceType().getUnqualifiedType();
6210 
6211       // Give preference to ivars
6212       Results.setPreferredType(PropertyType);
6213     }
6214   }
6215 
6216   // Add all of the instance variables in this class and its superclasses.
6217   Results.EnterNewScope();
6218   bool SawSimilarlyNamedIvar = false;
6219   std::string NameWithPrefix;
6220   NameWithPrefix += '_';
6221   NameWithPrefix += PropertyName->getName();
6222   std::string NameWithSuffix = PropertyName->getName().str();
6223   NameWithSuffix += '_';
6224   for(; Class; Class = Class->getSuperClass()) {
6225     for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
6226          Ivar = Ivar->getNextIvar()) {
6227       Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), nullptr),
6228                         CurContext, nullptr, false);
6229 
6230       // Determine whether we've seen an ivar with a name similar to the
6231       // property.
6232       if ((PropertyName == Ivar->getIdentifier() ||
6233            NameWithPrefix == Ivar->getName() ||
6234            NameWithSuffix == Ivar->getName())) {
6235         SawSimilarlyNamedIvar = true;
6236 
6237         // Reduce the priority of this result by one, to give it a slight
6238         // advantage over other results whose names don't match so closely.
6239         if (Results.size() &&
6240             Results.data()[Results.size() - 1].Kind
6241                                       == CodeCompletionResult::RK_Declaration &&
6242             Results.data()[Results.size() - 1].Declaration == Ivar)
6243           Results.data()[Results.size() - 1].Priority--;
6244       }
6245     }
6246   }
6247 
6248   if (!SawSimilarlyNamedIvar) {
6249     // Create ivar result _propName, that the user can use to synthesize
6250     // an ivar of the appropriate type.
6251     unsigned Priority = CCP_MemberDeclaration + 1;
6252     typedef CodeCompletionResult Result;
6253     CodeCompletionAllocator &Allocator = Results.getAllocator();
6254     CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(),
6255                                   Priority,CXAvailability_Available);
6256 
6257     PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
6258     Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
6259                                                        Policy, Allocator));
6260     Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
6261     Results.AddResult(Result(Builder.TakeString(), Priority,
6262                              CXCursor_ObjCIvarDecl));
6263   }
6264 
6265   Results.ExitScope();
6266 
6267   HandleCodeCompleteResults(this, CodeCompleter,
6268                             CodeCompletionContext::CCC_Other,
6269                             Results.data(),Results.size());
6270 }
6271 
6272 // Mapping from selectors to the methods that implement that selector, along
6273 // with the "in original class" flag.
6274 typedef llvm::DenseMap<
6275     Selector, llvm::PointerIntPair<ObjCMethodDecl *, 1, bool> > KnownMethodsMap;
6276 
6277 /// \brief Find all of the methods that reside in the given container
6278 /// (and its superclasses, protocols, etc.) that meet the given
6279 /// criteria. Insert those methods into the map of known methods,
6280 /// indexed by selector so they can be easily found.
6281 static void FindImplementableMethods(ASTContext &Context,
6282                                      ObjCContainerDecl *Container,
6283                                      bool WantInstanceMethods,
6284                                      QualType ReturnType,
6285                                      KnownMethodsMap &KnownMethods,
6286                                      bool InOriginalClass = true) {
6287   if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
6288     // Make sure we have a definition; that's what we'll walk.
6289     if (!IFace->hasDefinition())
6290       return;
6291 
6292     IFace = IFace->getDefinition();
6293     Container = IFace;
6294 
6295     const ObjCList<ObjCProtocolDecl> &Protocols
6296       = IFace->getReferencedProtocols();
6297     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6298                                               E = Protocols.end();
6299          I != E; ++I)
6300       FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
6301                                KnownMethods, InOriginalClass);
6302 
6303     // Add methods from any class extensions and categories.
6304     for (auto *Cat : IFace->visible_categories()) {
6305       FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType,
6306                                KnownMethods, false);
6307     }
6308 
6309     // Visit the superclass.
6310     if (IFace->getSuperClass())
6311       FindImplementableMethods(Context, IFace->getSuperClass(),
6312                                WantInstanceMethods, ReturnType,
6313                                KnownMethods, false);
6314   }
6315 
6316   if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
6317     // Recurse into protocols.
6318     const ObjCList<ObjCProtocolDecl> &Protocols
6319       = Category->getReferencedProtocols();
6320     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6321                                               E = Protocols.end();
6322          I != E; ++I)
6323       FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
6324                                KnownMethods, InOriginalClass);
6325 
6326     // If this category is the original class, jump to the interface.
6327     if (InOriginalClass && Category->getClassInterface())
6328       FindImplementableMethods(Context, Category->getClassInterface(),
6329                                WantInstanceMethods, ReturnType, KnownMethods,
6330                                false);
6331   }
6332 
6333   if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
6334     // Make sure we have a definition; that's what we'll walk.
6335     if (!Protocol->hasDefinition())
6336       return;
6337     Protocol = Protocol->getDefinition();
6338     Container = Protocol;
6339 
6340     // Recurse into protocols.
6341     const ObjCList<ObjCProtocolDecl> &Protocols
6342       = Protocol->getReferencedProtocols();
6343     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6344            E = Protocols.end();
6345          I != E; ++I)
6346       FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
6347                                KnownMethods, false);
6348   }
6349 
6350   // Add methods in this container. This operation occurs last because
6351   // we want the methods from this container to override any methods
6352   // we've previously seen with the same selector.
6353   for (auto *M : Container->methods()) {
6354     if (M->isInstanceMethod() == WantInstanceMethods) {
6355       if (!ReturnType.isNull() &&
6356           !Context.hasSameUnqualifiedType(ReturnType, M->getReturnType()))
6357         continue;
6358 
6359       KnownMethods[M->getSelector()] =
6360           KnownMethodsMap::mapped_type(M, InOriginalClass);
6361     }
6362   }
6363 }
6364 
6365 /// \brief Add the parenthesized return or parameter type chunk to a code
6366 /// completion string.
6367 static void AddObjCPassingTypeChunk(QualType Type,
6368                                     unsigned ObjCDeclQuals,
6369                                     ASTContext &Context,
6370                                     const PrintingPolicy &Policy,
6371                                     CodeCompletionBuilder &Builder) {
6372   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6373   std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals, Type);
6374   if (!Quals.empty())
6375     Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals));
6376   Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy,
6377                                                Builder.getAllocator()));
6378   Builder.AddChunk(CodeCompletionString::CK_RightParen);
6379 }
6380 
6381 /// \brief Determine whether the given class is or inherits from a class by
6382 /// the given name.
6383 static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
6384                                    StringRef Name) {
6385   if (!Class)
6386     return false;
6387 
6388   if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
6389     return true;
6390 
6391   return InheritsFromClassNamed(Class->getSuperClass(), Name);
6392 }
6393 
6394 /// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
6395 /// Key-Value Observing (KVO).
6396 static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
6397                                        bool IsInstanceMethod,
6398                                        QualType ReturnType,
6399                                        ASTContext &Context,
6400                                        VisitedSelectorSet &KnownSelectors,
6401                                        ResultBuilder &Results) {
6402   IdentifierInfo *PropName = Property->getIdentifier();
6403   if (!PropName || PropName->getLength() == 0)
6404     return;
6405 
6406   PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
6407 
6408   // Builder that will create each code completion.
6409   typedef CodeCompletionResult Result;
6410   CodeCompletionAllocator &Allocator = Results.getAllocator();
6411   CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
6412 
6413   // The selector table.
6414   SelectorTable &Selectors = Context.Selectors;
6415 
6416   // The property name, copied into the code completion allocation region
6417   // on demand.
6418   struct KeyHolder {
6419     CodeCompletionAllocator &Allocator;
6420     StringRef Key;
6421     const char *CopiedKey;
6422 
6423     KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
6424     : Allocator(Allocator), Key(Key), CopiedKey(nullptr) {}
6425 
6426     operator const char *() {
6427       if (CopiedKey)
6428         return CopiedKey;
6429 
6430       return CopiedKey = Allocator.CopyString(Key);
6431     }
6432   } Key(Allocator, PropName->getName());
6433 
6434   // The uppercased name of the property name.
6435   std::string UpperKey = PropName->getName();
6436   if (!UpperKey.empty())
6437     UpperKey[0] = toUppercase(UpperKey[0]);
6438 
6439   bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
6440     Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
6441                                    Property->getType());
6442   bool ReturnTypeMatchesVoid
6443     = ReturnType.isNull() || ReturnType->isVoidType();
6444 
6445   // Add the normal accessor -(type)key.
6446   if (IsInstanceMethod &&
6447       KnownSelectors.insert(Selectors.getNullarySelector(PropName)).second &&
6448       ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
6449     if (ReturnType.isNull())
6450       AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6451                               Context, Policy, Builder);
6452 
6453     Builder.AddTypedTextChunk(Key);
6454     Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6455                              CXCursor_ObjCInstanceMethodDecl));
6456   }
6457 
6458   // If we have an integral or boolean property (or the user has provided
6459   // an integral or boolean return type), add the accessor -(type)isKey.
6460   if (IsInstanceMethod &&
6461       ((!ReturnType.isNull() &&
6462         (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
6463        (ReturnType.isNull() &&
6464         (Property->getType()->isIntegerType() ||
6465          Property->getType()->isBooleanType())))) {
6466     std::string SelectorName = (Twine("is") + UpperKey).str();
6467     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6468     if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6469             .second) {
6470       if (ReturnType.isNull()) {
6471         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6472         Builder.AddTextChunk("BOOL");
6473         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6474       }
6475 
6476       Builder.AddTypedTextChunk(
6477                                 Allocator.CopyString(SelectorId->getName()));
6478       Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6479                                CXCursor_ObjCInstanceMethodDecl));
6480     }
6481   }
6482 
6483   // Add the normal mutator.
6484   if (IsInstanceMethod && ReturnTypeMatchesVoid &&
6485       !Property->getSetterMethodDecl()) {
6486     std::string SelectorName = (Twine("set") + UpperKey).str();
6487     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6488     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
6489       if (ReturnType.isNull()) {
6490         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6491         Builder.AddTextChunk("void");
6492         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6493       }
6494 
6495       Builder.AddTypedTextChunk(
6496                                 Allocator.CopyString(SelectorId->getName()));
6497       Builder.AddTypedTextChunk(":");
6498       AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6499                               Context, Policy, Builder);
6500       Builder.AddTextChunk(Key);
6501       Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6502                                CXCursor_ObjCInstanceMethodDecl));
6503     }
6504   }
6505 
6506   // Indexed and unordered accessors
6507   unsigned IndexedGetterPriority = CCP_CodePattern;
6508   unsigned IndexedSetterPriority = CCP_CodePattern;
6509   unsigned UnorderedGetterPriority = CCP_CodePattern;
6510   unsigned UnorderedSetterPriority = CCP_CodePattern;
6511   if (const ObjCObjectPointerType *ObjCPointer
6512                     = Property->getType()->getAs<ObjCObjectPointerType>()) {
6513     if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
6514       // If this interface type is not provably derived from a known
6515       // collection, penalize the corresponding completions.
6516       if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
6517         IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6518         if (!InheritsFromClassNamed(IFace, "NSArray"))
6519           IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6520       }
6521 
6522       if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
6523         UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6524         if (!InheritsFromClassNamed(IFace, "NSSet"))
6525           UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6526       }
6527     }
6528   } else {
6529     IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6530     IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6531     UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6532     UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6533   }
6534 
6535   // Add -(NSUInteger)countOf<key>
6536   if (IsInstanceMethod &&
6537       (ReturnType.isNull() || ReturnType->isIntegerType())) {
6538     std::string SelectorName = (Twine("countOf") + UpperKey).str();
6539     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6540     if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6541             .second) {
6542       if (ReturnType.isNull()) {
6543         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6544         Builder.AddTextChunk("NSUInteger");
6545         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6546       }
6547 
6548       Builder.AddTypedTextChunk(
6549                                 Allocator.CopyString(SelectorId->getName()));
6550       Results.AddResult(Result(Builder.TakeString(),
6551                                std::min(IndexedGetterPriority,
6552                                         UnorderedGetterPriority),
6553                                CXCursor_ObjCInstanceMethodDecl));
6554     }
6555   }
6556 
6557   // Indexed getters
6558   // Add -(id)objectInKeyAtIndex:(NSUInteger)index
6559   if (IsInstanceMethod &&
6560       (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
6561     std::string SelectorName
6562       = (Twine("objectIn") + UpperKey + "AtIndex").str();
6563     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6564     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
6565       if (ReturnType.isNull()) {
6566         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6567         Builder.AddTextChunk("id");
6568         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6569       }
6570 
6571       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6572       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6573       Builder.AddTextChunk("NSUInteger");
6574       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6575       Builder.AddTextChunk("index");
6576       Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6577                                CXCursor_ObjCInstanceMethodDecl));
6578     }
6579   }
6580 
6581   // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
6582   if (IsInstanceMethod &&
6583       (ReturnType.isNull() ||
6584        (ReturnType->isObjCObjectPointerType() &&
6585         ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6586         ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6587                                                 ->getName() == "NSArray"))) {
6588     std::string SelectorName
6589       = (Twine(Property->getName()) + "AtIndexes").str();
6590     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6591     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
6592       if (ReturnType.isNull()) {
6593         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6594         Builder.AddTextChunk("NSArray *");
6595         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6596       }
6597 
6598       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6599       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6600       Builder.AddTextChunk("NSIndexSet *");
6601       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6602       Builder.AddTextChunk("indexes");
6603       Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6604                                CXCursor_ObjCInstanceMethodDecl));
6605     }
6606   }
6607 
6608   // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
6609   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6610     std::string SelectorName = (Twine("get") + UpperKey).str();
6611     IdentifierInfo *SelectorIds[2] = {
6612       &Context.Idents.get(SelectorName),
6613       &Context.Idents.get("range")
6614     };
6615 
6616     if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
6617       if (ReturnType.isNull()) {
6618         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6619         Builder.AddTextChunk("void");
6620         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6621       }
6622 
6623       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6624       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6625       Builder.AddPlaceholderChunk("object-type");
6626       Builder.AddTextChunk(" **");
6627       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6628       Builder.AddTextChunk("buffer");
6629       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6630       Builder.AddTypedTextChunk("range:");
6631       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6632       Builder.AddTextChunk("NSRange");
6633       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6634       Builder.AddTextChunk("inRange");
6635       Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6636                                CXCursor_ObjCInstanceMethodDecl));
6637     }
6638   }
6639 
6640   // Mutable indexed accessors
6641 
6642   // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
6643   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6644     std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
6645     IdentifierInfo *SelectorIds[2] = {
6646       &Context.Idents.get("insertObject"),
6647       &Context.Idents.get(SelectorName)
6648     };
6649 
6650     if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
6651       if (ReturnType.isNull()) {
6652         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6653         Builder.AddTextChunk("void");
6654         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6655       }
6656 
6657       Builder.AddTypedTextChunk("insertObject:");
6658       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6659       Builder.AddPlaceholderChunk("object-type");
6660       Builder.AddTextChunk(" *");
6661       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6662       Builder.AddTextChunk("object");
6663       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6664       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6665       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6666       Builder.AddPlaceholderChunk("NSUInteger");
6667       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6668       Builder.AddTextChunk("index");
6669       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6670                                CXCursor_ObjCInstanceMethodDecl));
6671     }
6672   }
6673 
6674   // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
6675   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6676     std::string SelectorName = (Twine("insert") + UpperKey).str();
6677     IdentifierInfo *SelectorIds[2] = {
6678       &Context.Idents.get(SelectorName),
6679       &Context.Idents.get("atIndexes")
6680     };
6681 
6682     if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
6683       if (ReturnType.isNull()) {
6684         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6685         Builder.AddTextChunk("void");
6686         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6687       }
6688 
6689       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6690       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6691       Builder.AddTextChunk("NSArray *");
6692       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6693       Builder.AddTextChunk("array");
6694       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6695       Builder.AddTypedTextChunk("atIndexes:");
6696       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6697       Builder.AddPlaceholderChunk("NSIndexSet *");
6698       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6699       Builder.AddTextChunk("indexes");
6700       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6701                                CXCursor_ObjCInstanceMethodDecl));
6702     }
6703   }
6704 
6705   // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
6706   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6707     std::string SelectorName
6708       = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
6709     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6710     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
6711       if (ReturnType.isNull()) {
6712         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6713         Builder.AddTextChunk("void");
6714         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6715       }
6716 
6717       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6718       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6719       Builder.AddTextChunk("NSUInteger");
6720       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6721       Builder.AddTextChunk("index");
6722       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6723                                CXCursor_ObjCInstanceMethodDecl));
6724     }
6725   }
6726 
6727   // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
6728   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6729     std::string SelectorName
6730       = (Twine("remove") + UpperKey + "AtIndexes").str();
6731     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6732     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
6733       if (ReturnType.isNull()) {
6734         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6735         Builder.AddTextChunk("void");
6736         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6737       }
6738 
6739       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6740       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6741       Builder.AddTextChunk("NSIndexSet *");
6742       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6743       Builder.AddTextChunk("indexes");
6744       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6745                                CXCursor_ObjCInstanceMethodDecl));
6746     }
6747   }
6748 
6749   // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
6750   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6751     std::string SelectorName
6752       = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
6753     IdentifierInfo *SelectorIds[2] = {
6754       &Context.Idents.get(SelectorName),
6755       &Context.Idents.get("withObject")
6756     };
6757 
6758     if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
6759       if (ReturnType.isNull()) {
6760         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6761         Builder.AddTextChunk("void");
6762         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6763       }
6764 
6765       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6766       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6767       Builder.AddPlaceholderChunk("NSUInteger");
6768       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6769       Builder.AddTextChunk("index");
6770       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6771       Builder.AddTypedTextChunk("withObject:");
6772       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6773       Builder.AddTextChunk("id");
6774       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6775       Builder.AddTextChunk("object");
6776       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6777                                CXCursor_ObjCInstanceMethodDecl));
6778     }
6779   }
6780 
6781   // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
6782   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6783     std::string SelectorName1
6784       = (Twine("replace") + UpperKey + "AtIndexes").str();
6785     std::string SelectorName2 = (Twine("with") + UpperKey).str();
6786     IdentifierInfo *SelectorIds[2] = {
6787       &Context.Idents.get(SelectorName1),
6788       &Context.Idents.get(SelectorName2)
6789     };
6790 
6791     if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
6792       if (ReturnType.isNull()) {
6793         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6794         Builder.AddTextChunk("void");
6795         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6796       }
6797 
6798       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
6799       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6800       Builder.AddPlaceholderChunk("NSIndexSet *");
6801       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6802       Builder.AddTextChunk("indexes");
6803       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6804       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
6805       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6806       Builder.AddTextChunk("NSArray *");
6807       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6808       Builder.AddTextChunk("array");
6809       Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6810                                CXCursor_ObjCInstanceMethodDecl));
6811     }
6812   }
6813 
6814   // Unordered getters
6815   // - (NSEnumerator *)enumeratorOfKey
6816   if (IsInstanceMethod &&
6817       (ReturnType.isNull() ||
6818        (ReturnType->isObjCObjectPointerType() &&
6819         ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6820         ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6821           ->getName() == "NSEnumerator"))) {
6822     std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
6823     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6824     if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6825             .second) {
6826       if (ReturnType.isNull()) {
6827         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6828         Builder.AddTextChunk("NSEnumerator *");
6829         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6830       }
6831 
6832       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6833       Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6834                               CXCursor_ObjCInstanceMethodDecl));
6835     }
6836   }
6837 
6838   // - (type *)memberOfKey:(type *)object
6839   if (IsInstanceMethod &&
6840       (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
6841     std::string SelectorName = (Twine("memberOf") + UpperKey).str();
6842     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6843     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
6844       if (ReturnType.isNull()) {
6845         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6846         Builder.AddPlaceholderChunk("object-type");
6847         Builder.AddTextChunk(" *");
6848         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6849       }
6850 
6851       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6852       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6853       if (ReturnType.isNull()) {
6854         Builder.AddPlaceholderChunk("object-type");
6855         Builder.AddTextChunk(" *");
6856       } else {
6857         Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
6858                                                      Policy,
6859                                                      Builder.getAllocator()));
6860       }
6861       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6862       Builder.AddTextChunk("object");
6863       Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6864                                CXCursor_ObjCInstanceMethodDecl));
6865     }
6866   }
6867 
6868   // Mutable unordered accessors
6869   // - (void)addKeyObject:(type *)object
6870   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6871     std::string SelectorName
6872       = (Twine("add") + UpperKey + Twine("Object")).str();
6873     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6874     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
6875       if (ReturnType.isNull()) {
6876         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6877         Builder.AddTextChunk("void");
6878         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6879       }
6880 
6881       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6882       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6883       Builder.AddPlaceholderChunk("object-type");
6884       Builder.AddTextChunk(" *");
6885       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6886       Builder.AddTextChunk("object");
6887       Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6888                                CXCursor_ObjCInstanceMethodDecl));
6889     }
6890   }
6891 
6892   // - (void)addKey:(NSSet *)objects
6893   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6894     std::string SelectorName = (Twine("add") + UpperKey).str();
6895     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6896     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
6897       if (ReturnType.isNull()) {
6898         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6899         Builder.AddTextChunk("void");
6900         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6901       }
6902 
6903       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6904       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6905       Builder.AddTextChunk("NSSet *");
6906       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6907       Builder.AddTextChunk("objects");
6908       Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6909                                CXCursor_ObjCInstanceMethodDecl));
6910     }
6911   }
6912 
6913   // - (void)removeKeyObject:(type *)object
6914   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6915     std::string SelectorName
6916       = (Twine("remove") + UpperKey + Twine("Object")).str();
6917     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6918     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
6919       if (ReturnType.isNull()) {
6920         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6921         Builder.AddTextChunk("void");
6922         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6923       }
6924 
6925       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6926       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6927       Builder.AddPlaceholderChunk("object-type");
6928       Builder.AddTextChunk(" *");
6929       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6930       Builder.AddTextChunk("object");
6931       Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6932                                CXCursor_ObjCInstanceMethodDecl));
6933     }
6934   }
6935 
6936   // - (void)removeKey:(NSSet *)objects
6937   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6938     std::string SelectorName = (Twine("remove") + UpperKey).str();
6939     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6940     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
6941       if (ReturnType.isNull()) {
6942         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6943         Builder.AddTextChunk("void");
6944         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6945       }
6946 
6947       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6948       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6949       Builder.AddTextChunk("NSSet *");
6950       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6951       Builder.AddTextChunk("objects");
6952       Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6953                                CXCursor_ObjCInstanceMethodDecl));
6954     }
6955   }
6956 
6957   // - (void)intersectKey:(NSSet *)objects
6958   if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6959     std::string SelectorName = (Twine("intersect") + UpperKey).str();
6960     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6961     if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
6962       if (ReturnType.isNull()) {
6963         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6964         Builder.AddTextChunk("void");
6965         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6966       }
6967 
6968       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6969       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6970       Builder.AddTextChunk("NSSet *");
6971       Builder.AddChunk(CodeCompletionString::CK_RightParen);
6972       Builder.AddTextChunk("objects");
6973       Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6974                                CXCursor_ObjCInstanceMethodDecl));
6975     }
6976   }
6977 
6978   // Key-Value Observing
6979   // + (NSSet *)keyPathsForValuesAffectingKey
6980   if (!IsInstanceMethod &&
6981       (ReturnType.isNull() ||
6982        (ReturnType->isObjCObjectPointerType() &&
6983         ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6984         ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6985                                                     ->getName() == "NSSet"))) {
6986     std::string SelectorName
6987       = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
6988     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6989     if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6990             .second) {
6991       if (ReturnType.isNull()) {
6992         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6993         Builder.AddTextChunk("NSSet *");
6994         Builder.AddChunk(CodeCompletionString::CK_RightParen);
6995       }
6996 
6997       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6998       Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6999                               CXCursor_ObjCClassMethodDecl));
7000     }
7001   }
7002 
7003   // + (BOOL)automaticallyNotifiesObserversForKey
7004   if (!IsInstanceMethod &&
7005       (ReturnType.isNull() ||
7006        ReturnType->isIntegerType() ||
7007        ReturnType->isBooleanType())) {
7008     std::string SelectorName
7009       = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
7010     IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7011     if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
7012             .second) {
7013       if (ReturnType.isNull()) {
7014         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7015         Builder.AddTextChunk("BOOL");
7016         Builder.AddChunk(CodeCompletionString::CK_RightParen);
7017       }
7018 
7019       Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
7020       Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
7021                               CXCursor_ObjCClassMethodDecl));
7022     }
7023   }
7024 }
7025 
7026 void Sema::CodeCompleteObjCMethodDecl(Scope *S,
7027                                       bool IsInstanceMethod,
7028                                       ParsedType ReturnTy) {
7029   // Determine the return type of the method we're declaring, if
7030   // provided.
7031   QualType ReturnType = GetTypeFromParser(ReturnTy);
7032   Decl *IDecl = nullptr;
7033   if (CurContext->isObjCContainer()) {
7034       ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
7035       IDecl = cast<Decl>(OCD);
7036   }
7037   // Determine where we should start searching for methods.
7038   ObjCContainerDecl *SearchDecl = nullptr;
7039   bool IsInImplementation = false;
7040   if (Decl *D = IDecl) {
7041     if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
7042       SearchDecl = Impl->getClassInterface();
7043       IsInImplementation = true;
7044     } else if (ObjCCategoryImplDecl *CatImpl
7045                                          = dyn_cast<ObjCCategoryImplDecl>(D)) {
7046       SearchDecl = CatImpl->getCategoryDecl();
7047       IsInImplementation = true;
7048     } else
7049       SearchDecl = dyn_cast<ObjCContainerDecl>(D);
7050   }
7051 
7052   if (!SearchDecl && S) {
7053     if (DeclContext *DC = S->getEntity())
7054       SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
7055   }
7056 
7057   if (!SearchDecl) {
7058     HandleCodeCompleteResults(this, CodeCompleter,
7059                               CodeCompletionContext::CCC_Other,
7060                               nullptr, 0);
7061     return;
7062   }
7063 
7064   // Find all of the methods that we could declare/implement here.
7065   KnownMethodsMap KnownMethods;
7066   FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
7067                            ReturnType, KnownMethods);
7068 
7069   // Add declarations or definitions for each of the known methods.
7070   typedef CodeCompletionResult Result;
7071   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7072                         CodeCompleter->getCodeCompletionTUInfo(),
7073                         CodeCompletionContext::CCC_Other);
7074   Results.EnterNewScope();
7075   PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
7076   for (KnownMethodsMap::iterator M = KnownMethods.begin(),
7077                               MEnd = KnownMethods.end();
7078        M != MEnd; ++M) {
7079     ObjCMethodDecl *Method = M->second.getPointer();
7080     CodeCompletionBuilder Builder(Results.getAllocator(),
7081                                   Results.getCodeCompletionTUInfo());
7082 
7083     // If the result type was not already provided, add it to the
7084     // pattern as (type).
7085     if (ReturnType.isNull()) {
7086       QualType ResTy = Method->getSendResultType().stripObjCKindOfType(Context);
7087       AttributedType::stripOuterNullability(ResTy);
7088       AddObjCPassingTypeChunk(ResTy,
7089                               Method->getObjCDeclQualifier(), Context, Policy,
7090                               Builder);
7091     }
7092 
7093     Selector Sel = Method->getSelector();
7094 
7095     // Add the first part of the selector to the pattern.
7096     Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
7097                                                        Sel.getNameForSlot(0)));
7098 
7099     // Add parameters to the pattern.
7100     unsigned I = 0;
7101     for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
7102                                      PEnd = Method->param_end();
7103          P != PEnd; (void)++P, ++I) {
7104       // Add the part of the selector name.
7105       if (I == 0)
7106         Builder.AddTypedTextChunk(":");
7107       else if (I < Sel.getNumArgs()) {
7108         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7109         Builder.AddTypedTextChunk(
7110                 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
7111       } else
7112         break;
7113 
7114       // Add the parameter type.
7115       QualType ParamType;
7116       if ((*P)->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
7117         ParamType = (*P)->getType();
7118       else
7119         ParamType = (*P)->getOriginalType();
7120       ParamType = ParamType.substObjCTypeArgs(Context, {},
7121                                             ObjCSubstitutionContext::Parameter);
7122       AttributedType::stripOuterNullability(ParamType);
7123       AddObjCPassingTypeChunk(ParamType,
7124                               (*P)->getObjCDeclQualifier(),
7125                               Context, Policy,
7126                               Builder);
7127 
7128       if (IdentifierInfo *Id = (*P)->getIdentifier())
7129         Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
7130     }
7131 
7132     if (Method->isVariadic()) {
7133       if (Method->param_size() > 0)
7134         Builder.AddChunk(CodeCompletionString::CK_Comma);
7135       Builder.AddTextChunk("...");
7136     }
7137 
7138     if (IsInImplementation && Results.includeCodePatterns()) {
7139       // We will be defining the method here, so add a compound statement.
7140       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7141       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
7142       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
7143       if (!Method->getReturnType()->isVoidType()) {
7144         // If the result type is not void, add a return clause.
7145         Builder.AddTextChunk("return");
7146         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7147         Builder.AddPlaceholderChunk("expression");
7148         Builder.AddChunk(CodeCompletionString::CK_SemiColon);
7149       } else
7150         Builder.AddPlaceholderChunk("statements");
7151 
7152       Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
7153       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
7154     }
7155 
7156     unsigned Priority = CCP_CodePattern;
7157     if (!M->second.getInt())
7158       Priority += CCD_InBaseClass;
7159 
7160     Results.AddResult(Result(Builder.TakeString(), Method, Priority));
7161   }
7162 
7163   // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
7164   // the properties in this class and its categories.
7165   if (Context.getLangOpts().ObjC2) {
7166     SmallVector<ObjCContainerDecl *, 4> Containers;
7167     Containers.push_back(SearchDecl);
7168 
7169     VisitedSelectorSet KnownSelectors;
7170     for (KnownMethodsMap::iterator M = KnownMethods.begin(),
7171                                 MEnd = KnownMethods.end();
7172          M != MEnd; ++M)
7173       KnownSelectors.insert(M->first);
7174 
7175 
7176     ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
7177     if (!IFace)
7178       if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
7179         IFace = Category->getClassInterface();
7180 
7181     if (IFace)
7182       for (auto *Cat : IFace->visible_categories())
7183         Containers.push_back(Cat);
7184 
7185     for (unsigned I = 0, N = Containers.size(); I != N; ++I)
7186       for (auto *P : Containers[I]->instance_properties())
7187         AddObjCKeyValueCompletions(P, IsInstanceMethod, ReturnType, Context,
7188                                    KnownSelectors, Results);
7189   }
7190 
7191   Results.ExitScope();
7192 
7193   HandleCodeCompleteResults(this, CodeCompleter,
7194                             CodeCompletionContext::CCC_Other,
7195                             Results.data(),Results.size());
7196 }
7197 
7198 void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
7199                                               bool IsInstanceMethod,
7200                                               bool AtParameterName,
7201                                               ParsedType ReturnTy,
7202                                          ArrayRef<IdentifierInfo *> SelIdents) {
7203   // If we have an external source, load the entire class method
7204   // pool from the AST file.
7205   if (ExternalSource) {
7206     for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
7207          I != N; ++I) {
7208       Selector Sel = ExternalSource->GetExternalSelector(I);
7209       if (Sel.isNull() || MethodPool.count(Sel))
7210         continue;
7211 
7212       ReadMethodPool(Sel);
7213     }
7214   }
7215 
7216   // Build the set of methods we can see.
7217   typedef CodeCompletionResult Result;
7218   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7219                         CodeCompleter->getCodeCompletionTUInfo(),
7220                         CodeCompletionContext::CCC_Other);
7221 
7222   if (ReturnTy)
7223     Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
7224 
7225   Results.EnterNewScope();
7226   for (GlobalMethodPool::iterator M = MethodPool.begin(),
7227                                   MEnd = MethodPool.end();
7228        M != MEnd; ++M) {
7229     for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
7230                                                        &M->second.second;
7231          MethList && MethList->getMethod();
7232          MethList = MethList->getNext()) {
7233       if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
7234         continue;
7235 
7236       if (AtParameterName) {
7237         // Suggest parameter names we've seen before.
7238         unsigned NumSelIdents = SelIdents.size();
7239         if (NumSelIdents &&
7240             NumSelIdents <= MethList->getMethod()->param_size()) {
7241           ParmVarDecl *Param =
7242               MethList->getMethod()->parameters()[NumSelIdents - 1];
7243           if (Param->getIdentifier()) {
7244             CodeCompletionBuilder Builder(Results.getAllocator(),
7245                                           Results.getCodeCompletionTUInfo());
7246             Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
7247                                            Param->getIdentifier()->getName()));
7248             Results.AddResult(Builder.TakeString());
7249           }
7250         }
7251 
7252         continue;
7253       }
7254 
7255       Result R(MethList->getMethod(),
7256                Results.getBasePriority(MethList->getMethod()), nullptr);
7257       R.StartParameter = SelIdents.size();
7258       R.AllParametersAreInformative = false;
7259       R.DeclaringEntity = true;
7260       Results.MaybeAddResult(R, CurContext);
7261     }
7262   }
7263 
7264   Results.ExitScope();
7265   HandleCodeCompleteResults(this, CodeCompleter,
7266                             CodeCompletionContext::CCC_Other,
7267                             Results.data(),Results.size());
7268 }
7269 
7270 void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
7271   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7272                         CodeCompleter->getCodeCompletionTUInfo(),
7273                         CodeCompletionContext::CCC_PreprocessorDirective);
7274   Results.EnterNewScope();
7275 
7276   // #if <condition>
7277   CodeCompletionBuilder Builder(Results.getAllocator(),
7278                                 Results.getCodeCompletionTUInfo());
7279   Builder.AddTypedTextChunk("if");
7280   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7281   Builder.AddPlaceholderChunk("condition");
7282   Results.AddResult(Builder.TakeString());
7283 
7284   // #ifdef <macro>
7285   Builder.AddTypedTextChunk("ifdef");
7286   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7287   Builder.AddPlaceholderChunk("macro");
7288   Results.AddResult(Builder.TakeString());
7289 
7290   // #ifndef <macro>
7291   Builder.AddTypedTextChunk("ifndef");
7292   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7293   Builder.AddPlaceholderChunk("macro");
7294   Results.AddResult(Builder.TakeString());
7295 
7296   if (InConditional) {
7297     // #elif <condition>
7298     Builder.AddTypedTextChunk("elif");
7299     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7300     Builder.AddPlaceholderChunk("condition");
7301     Results.AddResult(Builder.TakeString());
7302 
7303     // #else
7304     Builder.AddTypedTextChunk("else");
7305     Results.AddResult(Builder.TakeString());
7306 
7307     // #endif
7308     Builder.AddTypedTextChunk("endif");
7309     Results.AddResult(Builder.TakeString());
7310   }
7311 
7312   // #include "header"
7313   Builder.AddTypedTextChunk("include");
7314   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7315   Builder.AddTextChunk("\"");
7316   Builder.AddPlaceholderChunk("header");
7317   Builder.AddTextChunk("\"");
7318   Results.AddResult(Builder.TakeString());
7319 
7320   // #include <header>
7321   Builder.AddTypedTextChunk("include");
7322   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7323   Builder.AddTextChunk("<");
7324   Builder.AddPlaceholderChunk("header");
7325   Builder.AddTextChunk(">");
7326   Results.AddResult(Builder.TakeString());
7327 
7328   // #define <macro>
7329   Builder.AddTypedTextChunk("define");
7330   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7331   Builder.AddPlaceholderChunk("macro");
7332   Results.AddResult(Builder.TakeString());
7333 
7334   // #define <macro>(<args>)
7335   Builder.AddTypedTextChunk("define");
7336   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7337   Builder.AddPlaceholderChunk("macro");
7338   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7339   Builder.AddPlaceholderChunk("args");
7340   Builder.AddChunk(CodeCompletionString::CK_RightParen);
7341   Results.AddResult(Builder.TakeString());
7342 
7343   // #undef <macro>
7344   Builder.AddTypedTextChunk("undef");
7345   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7346   Builder.AddPlaceholderChunk("macro");
7347   Results.AddResult(Builder.TakeString());
7348 
7349   // #line <number>
7350   Builder.AddTypedTextChunk("line");
7351   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7352   Builder.AddPlaceholderChunk("number");
7353   Results.AddResult(Builder.TakeString());
7354 
7355   // #line <number> "filename"
7356   Builder.AddTypedTextChunk("line");
7357   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7358   Builder.AddPlaceholderChunk("number");
7359   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7360   Builder.AddTextChunk("\"");
7361   Builder.AddPlaceholderChunk("filename");
7362   Builder.AddTextChunk("\"");
7363   Results.AddResult(Builder.TakeString());
7364 
7365   // #error <message>
7366   Builder.AddTypedTextChunk("error");
7367   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7368   Builder.AddPlaceholderChunk("message");
7369   Results.AddResult(Builder.TakeString());
7370 
7371   // #pragma <arguments>
7372   Builder.AddTypedTextChunk("pragma");
7373   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7374   Builder.AddPlaceholderChunk("arguments");
7375   Results.AddResult(Builder.TakeString());
7376 
7377   if (getLangOpts().ObjC1) {
7378     // #import "header"
7379     Builder.AddTypedTextChunk("import");
7380     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7381     Builder.AddTextChunk("\"");
7382     Builder.AddPlaceholderChunk("header");
7383     Builder.AddTextChunk("\"");
7384     Results.AddResult(Builder.TakeString());
7385 
7386     // #import <header>
7387     Builder.AddTypedTextChunk("import");
7388     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7389     Builder.AddTextChunk("<");
7390     Builder.AddPlaceholderChunk("header");
7391     Builder.AddTextChunk(">");
7392     Results.AddResult(Builder.TakeString());
7393   }
7394 
7395   // #include_next "header"
7396   Builder.AddTypedTextChunk("include_next");
7397   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7398   Builder.AddTextChunk("\"");
7399   Builder.AddPlaceholderChunk("header");
7400   Builder.AddTextChunk("\"");
7401   Results.AddResult(Builder.TakeString());
7402 
7403   // #include_next <header>
7404   Builder.AddTypedTextChunk("include_next");
7405   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7406   Builder.AddTextChunk("<");
7407   Builder.AddPlaceholderChunk("header");
7408   Builder.AddTextChunk(">");
7409   Results.AddResult(Builder.TakeString());
7410 
7411   // #warning <message>
7412   Builder.AddTypedTextChunk("warning");
7413   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7414   Builder.AddPlaceholderChunk("message");
7415   Results.AddResult(Builder.TakeString());
7416 
7417   // Note: #ident and #sccs are such crazy anachronisms that we don't provide
7418   // completions for them. And __include_macros is a Clang-internal extension
7419   // that we don't want to encourage anyone to use.
7420 
7421   // FIXME: we don't support #assert or #unassert, so don't suggest them.
7422   Results.ExitScope();
7423 
7424   HandleCodeCompleteResults(this, CodeCompleter,
7425                             CodeCompletionContext::CCC_PreprocessorDirective,
7426                             Results.data(), Results.size());
7427 }
7428 
7429 void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
7430   CodeCompleteOrdinaryName(S,
7431                            S->getFnParent()? Sema::PCC_RecoveryInFunction
7432                                            : Sema::PCC_Namespace);
7433 }
7434 
7435 void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
7436   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7437                         CodeCompleter->getCodeCompletionTUInfo(),
7438                         IsDefinition? CodeCompletionContext::CCC_MacroName
7439                                     : CodeCompletionContext::CCC_MacroNameUse);
7440   if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
7441     // Add just the names of macros, not their arguments.
7442     CodeCompletionBuilder Builder(Results.getAllocator(),
7443                                   Results.getCodeCompletionTUInfo());
7444     Results.EnterNewScope();
7445     for (Preprocessor::macro_iterator M = PP.macro_begin(),
7446                                    MEnd = PP.macro_end();
7447          M != MEnd; ++M) {
7448       Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
7449                                            M->first->getName()));
7450       Results.AddResult(CodeCompletionResult(Builder.TakeString(),
7451                                              CCP_CodePattern,
7452                                              CXCursor_MacroDefinition));
7453     }
7454     Results.ExitScope();
7455   } else if (IsDefinition) {
7456     // FIXME: Can we detect when the user just wrote an include guard above?
7457   }
7458 
7459   HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7460                             Results.data(), Results.size());
7461 }
7462 
7463 void Sema::CodeCompletePreprocessorExpression() {
7464   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7465                         CodeCompleter->getCodeCompletionTUInfo(),
7466                         CodeCompletionContext::CCC_PreprocessorExpression);
7467 
7468   if (!CodeCompleter || CodeCompleter->includeMacros())
7469     AddMacroResults(PP, Results, true);
7470 
7471     // defined (<macro>)
7472   Results.EnterNewScope();
7473   CodeCompletionBuilder Builder(Results.getAllocator(),
7474                                 Results.getCodeCompletionTUInfo());
7475   Builder.AddTypedTextChunk("defined");
7476   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7477   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7478   Builder.AddPlaceholderChunk("macro");
7479   Builder.AddChunk(CodeCompletionString::CK_RightParen);
7480   Results.AddResult(Builder.TakeString());
7481   Results.ExitScope();
7482 
7483   HandleCodeCompleteResults(this, CodeCompleter,
7484                             CodeCompletionContext::CCC_PreprocessorExpression,
7485                             Results.data(), Results.size());
7486 }
7487 
7488 void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
7489                                                  IdentifierInfo *Macro,
7490                                                  MacroInfo *MacroInfo,
7491                                                  unsigned Argument) {
7492   // FIXME: In the future, we could provide "overload" results, much like we
7493   // do for function calls.
7494 
7495   // Now just ignore this. There will be another code-completion callback
7496   // for the expanded tokens.
7497 }
7498 
7499 void Sema::CodeCompleteNaturalLanguage() {
7500   HandleCodeCompleteResults(this, CodeCompleter,
7501                             CodeCompletionContext::CCC_NaturalLanguage,
7502                             nullptr, 0);
7503 }
7504 
7505 void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
7506                                        CodeCompletionTUInfo &CCTUInfo,
7507                  SmallVectorImpl<CodeCompletionResult> &Results) {
7508   ResultBuilder Builder(*this, Allocator, CCTUInfo,
7509                         CodeCompletionContext::CCC_Recovery);
7510   if (!CodeCompleter || CodeCompleter->includeGlobals()) {
7511     CodeCompletionDeclConsumer Consumer(Builder,
7512                                         Context.getTranslationUnitDecl());
7513     LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
7514                        Consumer);
7515   }
7516 
7517   if (!CodeCompleter || CodeCompleter->includeMacros())
7518     AddMacroResults(PP, Builder, true);
7519 
7520   Results.clear();
7521   Results.insert(Results.end(),
7522                  Builder.data(), Builder.data() + Builder.size());
7523 }
7524