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