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