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