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