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