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