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