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