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