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