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