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