clang  6.0.0svn
SemaCodeComplete.cpp
Go to the documentation of this file.
1 //===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the code-completion semantic actions.
11 //
12 //===----------------------------------------------------------------------===//
13 #include "clang/AST/DeclCXX.h"
14 #include "clang/AST/DeclObjC.h"
15 #include "clang/AST/ExprCXX.h"
16 #include "clang/AST/ExprObjC.h"
18 #include "clang/Basic/CharInfo.h"
19 #include "clang/Lex/HeaderSearch.h"
20 #include "clang/Lex/MacroInfo.h"
21 #include "clang/Lex/Preprocessor.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"
28 #include "llvm/ADT/DenseSet.h"
29 #include "llvm/ADT/SmallBitVector.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/ADT/StringSwitch.h"
34 #include "llvm/ADT/Twine.h"
35 #include <list>
36 #include <map>
37 #include <vector>
38 
39 using namespace clang;
40 using namespace sema;
41 
42 namespace {
43  /// \brief A container of code-completion results.
44  class ResultBuilder {
45  public:
46  /// \brief The type of a name-lookup filter, which can be provided to the
47  /// name-lookup routines to specify which declarations should be included in
48  /// the result set (when it returns true) and which declarations should be
49  /// filtered out (returns false).
50  typedef bool (ResultBuilder::*LookupFilter)(const NamedDecl *) const;
51 
52  typedef CodeCompletionResult Result;
53 
54  private:
55  /// \brief The actual results we have found.
56  std::vector<Result> Results;
57 
58  /// \brief A record of all of the declarations we have found and placed
59  /// into the result set, used to ensure that no declaration ever gets into
60  /// the result set twice.
61  llvm::SmallPtrSet<const Decl*, 16> AllDeclsFound;
62 
63  typedef std::pair<const NamedDecl *, unsigned> DeclIndexPair;
64 
65  /// \brief An entry in the shadow map, which is optimized to store
66  /// a single (declaration, index) mapping (the common case) but
67  /// can also store a list of (declaration, index) mappings.
68  class ShadowMapEntry {
69  typedef SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
70 
71  /// \brief Contains either the solitary NamedDecl * or a vector
72  /// of (declaration, index) pairs.
73  llvm::PointerUnion<const NamedDecl *, DeclIndexPairVector*> DeclOrVector;
74 
75  /// \brief When the entry contains a single declaration, this is
76  /// the index associated with that entry.
77  unsigned SingleDeclIndex;
78 
79  public:
80  ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) { }
81 
82  void Add(const NamedDecl *ND, unsigned Index) {
83  if (DeclOrVector.isNull()) {
84  // 0 - > 1 elements: just set the single element information.
85  DeclOrVector = ND;
86  SingleDeclIndex = Index;
87  return;
88  }
89 
90  if (const NamedDecl *PrevND =
91  DeclOrVector.dyn_cast<const NamedDecl *>()) {
92  // 1 -> 2 elements: create the vector of results and push in the
93  // existing declaration.
94  DeclIndexPairVector *Vec = new DeclIndexPairVector;
95  Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
96  DeclOrVector = Vec;
97  }
98 
99  // Add the new element to the end of the vector.
100  DeclOrVector.get<DeclIndexPairVector*>()->push_back(
101  DeclIndexPair(ND, Index));
102  }
103 
104  void Destroy() {
105  if (DeclIndexPairVector *Vec
106  = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
107  delete Vec;
108  DeclOrVector = ((NamedDecl *)nullptr);
109  }
110  }
111 
112  // Iteration.
113  class iterator;
114  iterator begin() const;
115  iterator end() const;
116  };
117 
118  /// \brief A mapping from declaration names to the declarations that have
119  /// this name within a particular scope and their index within the list of
120  /// results.
121  typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
122 
123  /// \brief The semantic analysis object for which results are being
124  /// produced.
125  Sema &SemaRef;
126 
127  /// \brief The allocator used to allocate new code-completion strings.
128  CodeCompletionAllocator &Allocator;
129 
130  CodeCompletionTUInfo &CCTUInfo;
131 
132  /// \brief If non-NULL, a filter function used to remove any code-completion
133  /// results that are not desirable.
134  LookupFilter Filter;
135 
136  /// \brief Whether we should allow declarations as
137  /// nested-name-specifiers that would otherwise be filtered out.
138  bool AllowNestedNameSpecifiers;
139 
140  /// \brief If set, the type that we would prefer our resulting value
141  /// declarations to have.
142  ///
143  /// Closely matching the preferred type gives a boost to a result's
144  /// priority.
145  CanQualType PreferredType;
146 
147  /// \brief A list of shadow maps, which is used to model name hiding at
148  /// different levels of, e.g., the inheritance hierarchy.
149  std::list<ShadowMap> ShadowMaps;
150 
151  /// \brief If we're potentially referring to a C++ member function, the set
152  /// of qualifiers applied to the object type.
153  Qualifiers ObjectTypeQualifiers;
154 
155  /// \brief Whether the \p ObjectTypeQualifiers field is active.
156  bool HasObjectTypeQualifiers;
157 
158  /// \brief The selector that we prefer.
159  Selector PreferredSelector;
160 
161  /// \brief The completion context in which we are gathering results.
162  CodeCompletionContext CompletionContext;
163 
164  /// \brief If we are in an instance method definition, the \@implementation
165  /// object.
166  ObjCImplementationDecl *ObjCImplementation;
167 
168  void AdjustResultPriorityForDecl(Result &R);
169 
170  void MaybeAddConstructorResults(Result R);
171 
172  public:
173  explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator,
174  CodeCompletionTUInfo &CCTUInfo,
175  const CodeCompletionContext &CompletionContext,
176  LookupFilter Filter = nullptr)
177  : SemaRef(SemaRef), Allocator(Allocator), CCTUInfo(CCTUInfo),
178  Filter(Filter),
179  AllowNestedNameSpecifiers(false), HasObjectTypeQualifiers(false),
180  CompletionContext(CompletionContext),
181  ObjCImplementation(nullptr)
182  {
183  // If this is an Objective-C instance method definition, dig out the
184  // corresponding implementation.
185  switch (CompletionContext.getKind()) {
191  if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
192  if (Method->isInstanceMethod())
193  if (ObjCInterfaceDecl *Interface = Method->getClassInterface())
194  ObjCImplementation = Interface->getImplementation();
195  break;
196 
197  default:
198  break;
199  }
200  }
201 
202  /// \brief Determine the priority for a reference to the given declaration.
203  unsigned getBasePriority(const NamedDecl *D);
204 
205  /// \brief Whether we should include code patterns in the completion
206  /// results.
207  bool includeCodePatterns() const {
208  return SemaRef.CodeCompleter &&
210  }
211 
212  /// \brief Set the filter used for code-completion results.
213  void setFilter(LookupFilter Filter) {
214  this->Filter = Filter;
215  }
216 
217  Result *data() { return Results.empty()? nullptr : &Results.front(); }
218  unsigned size() const { return Results.size(); }
219  bool empty() const { return Results.empty(); }
220 
221  /// \brief Specify the preferred type.
222  void setPreferredType(QualType T) {
223  PreferredType = SemaRef.Context.getCanonicalType(T);
224  }
225 
226  /// \brief Set the cv-qualifiers on the object type, for us in filtering
227  /// calls to member functions.
228  ///
229  /// When there are qualifiers in this set, they will be used to filter
230  /// out member functions that aren't available (because there will be a
231  /// cv-qualifier mismatch) or prefer functions with an exact qualifier
232  /// match.
233  void setObjectTypeQualifiers(Qualifiers Quals) {
234  ObjectTypeQualifiers = Quals;
235  HasObjectTypeQualifiers = true;
236  }
237 
238  /// \brief Set the preferred selector.
239  ///
240  /// When an Objective-C method declaration result is added, and that
241  /// method's selector matches this preferred selector, we give that method
242  /// a slight priority boost.
243  void setPreferredSelector(Selector Sel) {
244  PreferredSelector = Sel;
245  }
246 
247  /// \brief Retrieve the code-completion context for which results are
248  /// being collected.
249  const CodeCompletionContext &getCompletionContext() const {
250  return CompletionContext;
251  }
252 
253  /// \brief Specify whether nested-name-specifiers are allowed.
254  void allowNestedNameSpecifiers(bool Allow = true) {
255  AllowNestedNameSpecifiers = Allow;
256  }
257 
258  /// \brief Return the semantic analysis object for which we are collecting
259  /// code completion results.
260  Sema &getSema() const { return SemaRef; }
261 
262  /// \brief Retrieve the allocator used to allocate code completion strings.
263  CodeCompletionAllocator &getAllocator() const { return Allocator; }
264 
265  CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
266 
267  /// \brief Determine whether the given declaration is at all interesting
268  /// as a code-completion result.
269  ///
270  /// \param ND the declaration that we are inspecting.
271  ///
272  /// \param AsNestedNameSpecifier will be set true if this declaration is
273  /// only interesting when it is a nested-name-specifier.
274  bool isInterestingDecl(const NamedDecl *ND,
275  bool &AsNestedNameSpecifier) const;
276 
277  /// \brief Check whether the result is hidden by the Hiding declaration.
278  ///
279  /// \returns true if the result is hidden and cannot be found, false if
280  /// the hidden result could still be found. When false, \p R may be
281  /// modified to describe how the result can be found (e.g., via extra
282  /// qualification).
283  bool CheckHiddenResult(Result &R, DeclContext *CurContext,
284  const NamedDecl *Hiding);
285 
286  /// \brief Add a new result to this result set (if it isn't already in one
287  /// of the shadow maps), or replace an existing result (for, e.g., a
288  /// redeclaration).
289  ///
290  /// \param R the result to add (if it is unique).
291  ///
292  /// \param CurContext the context in which this result will be named.
293  void MaybeAddResult(Result R, DeclContext *CurContext = nullptr);
294 
295  /// \brief Add a new result to this result set, where we already know
296  /// the hiding declaration (if any).
297  ///
298  /// \param R the result to add (if it is unique).
299  ///
300  /// \param CurContext the context in which this result will be named.
301  ///
302  /// \param Hiding the declaration that hides the result.
303  ///
304  /// \param InBaseClass whether the result was found in a base
305  /// class of the searched context.
306  void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
307  bool InBaseClass);
308 
309  /// \brief Add a new non-declaration result to this result set.
310  void AddResult(Result R);
311 
312  /// \brief Enter into a new scope.
313  void EnterNewScope();
314 
315  /// \brief Exit from the current scope.
316  void ExitScope();
317 
318  /// \brief Ignore this declaration, if it is seen again.
319  void Ignore(const Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
320 
321  /// \name Name lookup predicates
322  ///
323  /// These predicates can be passed to the name lookup functions to filter the
324  /// results of name lookup. All of the predicates have the same type, so that
325  ///
326  //@{
327  bool IsOrdinaryName(const NamedDecl *ND) const;
328  bool IsOrdinaryNonTypeName(const NamedDecl *ND) const;
329  bool IsIntegralConstantValue(const NamedDecl *ND) const;
330  bool IsOrdinaryNonValueName(const NamedDecl *ND) const;
331  bool IsNestedNameSpecifier(const NamedDecl *ND) const;
332  bool IsEnum(const NamedDecl *ND) const;
333  bool IsClassOrStruct(const NamedDecl *ND) const;
334  bool IsUnion(const NamedDecl *ND) const;
335  bool IsNamespace(const NamedDecl *ND) const;
336  bool IsNamespaceOrAlias(const NamedDecl *ND) const;
337  bool IsType(const NamedDecl *ND) const;
338  bool IsMember(const NamedDecl *ND) const;
339  bool IsObjCIvar(const NamedDecl *ND) const;
340  bool IsObjCMessageReceiver(const NamedDecl *ND) const;
341  bool IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const;
342  bool IsObjCCollection(const NamedDecl *ND) const;
343  bool IsImpossibleToSatisfy(const NamedDecl *ND) const;
344  //@}
345  };
346 }
347 
349  llvm::PointerUnion<const NamedDecl *, const DeclIndexPair *> DeclOrIterator;
350  unsigned SingleDeclIndex;
351 
352 public:
353  typedef DeclIndexPair value_type;
354  typedef value_type reference;
356  typedef std::input_iterator_tag iterator_category;
357 
358  class pointer {
359  DeclIndexPair Value;
360 
361  public:
362  pointer(const DeclIndexPair &Value) : Value(Value) { }
363 
364  const DeclIndexPair *operator->() const {
365  return &Value;
366  }
367  };
368 
369  iterator() : DeclOrIterator((NamedDecl *)nullptr), SingleDeclIndex(0) {}
370 
371  iterator(const NamedDecl *SingleDecl, unsigned Index)
372  : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
373 
374  iterator(const DeclIndexPair *Iterator)
375  : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
376 
378  if (DeclOrIterator.is<const NamedDecl *>()) {
379  DeclOrIterator = (NamedDecl *)nullptr;
380  SingleDeclIndex = 0;
381  return *this;
382  }
383 
384  const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
385  ++I;
386  DeclOrIterator = I;
387  return *this;
388  }
389 
390  /*iterator operator++(int) {
391  iterator tmp(*this);
392  ++(*this);
393  return tmp;
394  }*/
395 
396  reference operator*() const {
397  if (const NamedDecl *ND = DeclOrIterator.dyn_cast<const NamedDecl *>())
398  return reference(ND, SingleDeclIndex);
399 
400  return *DeclOrIterator.get<const DeclIndexPair*>();
401  }
402 
403  pointer operator->() const {
404  return pointer(**this);
405  }
406 
407  friend bool operator==(const iterator &X, const iterator &Y) {
408  return X.DeclOrIterator.getOpaqueValue()
409  == Y.DeclOrIterator.getOpaqueValue() &&
410  X.SingleDeclIndex == Y.SingleDeclIndex;
411  }
412 
413  friend bool operator!=(const iterator &X, const iterator &Y) {
414  return !(X == Y);
415  }
416 };
417 
419 ResultBuilder::ShadowMapEntry::begin() const {
420  if (DeclOrVector.isNull())
421  return iterator();
422 
423  if (const NamedDecl *ND = DeclOrVector.dyn_cast<const NamedDecl *>())
424  return iterator(ND, SingleDeclIndex);
425 
426  return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
427 }
428 
430 ResultBuilder::ShadowMapEntry::end() const {
431  if (DeclOrVector.is<const NamedDecl *>() || DeclOrVector.isNull())
432  return iterator();
433 
434  return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
435 }
436 
437 /// \brief Compute the qualification required to get from the current context
438 /// (\p CurContext) to the target context (\p TargetContext).
439 ///
440 /// \param Context the AST context in which the qualification will be used.
441 ///
442 /// \param CurContext the context where an entity is being named, which is
443 /// typically based on the current scope.
444 ///
445 /// \param TargetContext the context in which the named entity actually
446 /// resides.
447 ///
448 /// \returns a nested name specifier that refers into the target context, or
449 /// NULL if no qualification is needed.
450 static NestedNameSpecifier *
452  const DeclContext *CurContext,
453  const DeclContext *TargetContext) {
455 
456  for (const DeclContext *CommonAncestor = TargetContext;
457  CommonAncestor && !CommonAncestor->Encloses(CurContext);
458  CommonAncestor = CommonAncestor->getLookupParent()) {
459  if (CommonAncestor->isTransparentContext() ||
460  CommonAncestor->isFunctionOrMethod())
461  continue;
462 
463  TargetParents.push_back(CommonAncestor);
464  }
465 
466  NestedNameSpecifier *Result = nullptr;
467  while (!TargetParents.empty()) {
468  const DeclContext *Parent = TargetParents.pop_back_val();
469 
470  if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
471  if (!Namespace->getIdentifier())
472  continue;
473 
474  Result = NestedNameSpecifier::Create(Context, Result, Namespace);
475  }
476  else if (const TagDecl *TD = dyn_cast<TagDecl>(Parent))
477  Result = NestedNameSpecifier::Create(Context, Result,
478  false,
479  Context.getTypeDeclType(TD).getTypePtr());
480  }
481  return Result;
482 }
483 
484 /// Determine whether \p Id is a name reserved for the implementation (C99
485 /// 7.1.3, C++ [lib.global.names]).
486 static bool isReservedName(const IdentifierInfo *Id,
487  bool doubleUnderscoreOnly = false) {
488  if (Id->getLength() < 2)
489  return false;
490  const char *Name = Id->getNameStart();
491  return Name[0] == '_' &&
492  (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z' &&
493  !doubleUnderscoreOnly));
494 }
495 
496 // Some declarations have reserved names that we don't want to ever show.
497 // Filter out names reserved for the implementation if they come from a
498 // system header.
499 static bool shouldIgnoreDueToReservedName(const NamedDecl *ND, Sema &SemaRef) {
500  const IdentifierInfo *Id = ND->getIdentifier();
501  if (!Id)
502  return false;
503 
504  // Ignore reserved names for compiler provided decls.
505  if (isReservedName(Id) && ND->getLocation().isInvalid())
506  return true;
507 
508  // For system headers ignore only double-underscore names.
509  // This allows for system headers providing private symbols with a single
510  // underscore.
511  if (isReservedName(Id, /*doubleUnderscoreOnly=*/true) &&
512  SemaRef.SourceMgr.isInSystemHeader(
513  SemaRef.SourceMgr.getSpellingLoc(ND->getLocation())))
514  return true;
515 
516  return false;
517 }
518 
519 bool ResultBuilder::isInterestingDecl(const NamedDecl *ND,
520  bool &AsNestedNameSpecifier) const {
521  AsNestedNameSpecifier = false;
522 
523  auto *Named = ND;
524  ND = ND->getUnderlyingDecl();
525 
526  // Skip unnamed entities.
527  if (!ND->getDeclName())
528  return false;
529 
530  // Friend declarations and declarations introduced due to friends are never
531  // added as results.
533  return false;
534 
535  // Class template (partial) specializations are never added as results.
536  if (isa<ClassTemplateSpecializationDecl>(ND) ||
537  isa<ClassTemplatePartialSpecializationDecl>(ND))
538  return false;
539 
540  // Using declarations themselves are never added as results.
541  if (isa<UsingDecl>(ND))
542  return false;
543 
544  if (shouldIgnoreDueToReservedName(ND, SemaRef))
545  return false;
546 
547  if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
548  (isa<NamespaceDecl>(ND) &&
549  Filter != &ResultBuilder::IsNamespace &&
550  Filter != &ResultBuilder::IsNamespaceOrAlias &&
551  Filter != nullptr))
552  AsNestedNameSpecifier = true;
553 
554  // Filter out any unwanted results.
555  if (Filter && !(this->*Filter)(Named)) {
556  // Check whether it is interesting as a nested-name-specifier.
557  if (AllowNestedNameSpecifiers && SemaRef.getLangOpts().CPlusPlus &&
558  IsNestedNameSpecifier(ND) &&
559  (Filter != &ResultBuilder::IsMember ||
560  (isa<CXXRecordDecl>(ND) &&
561  cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
562  AsNestedNameSpecifier = true;
563  return true;
564  }
565 
566  return false;
567  }
568  // ... then it must be interesting!
569  return true;
570 }
571 
572 bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
573  const NamedDecl *Hiding) {
574  // In C, there is no way to refer to a hidden name.
575  // FIXME: This isn't true; we can find a tag name hidden by an ordinary
576  // name if we introduce the tag type.
577  if (!SemaRef.getLangOpts().CPlusPlus)
578  return true;
579 
580  const DeclContext *HiddenCtx =
581  R.Declaration->getDeclContext()->getRedeclContext();
582 
583  // There is no way to qualify a name declared in a function or method.
584  if (HiddenCtx->isFunctionOrMethod())
585  return true;
586 
587  if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
588  return true;
589 
590  // We can refer to the result with the appropriate qualification. Do it.
591  R.Hidden = true;
592  R.QualifierIsInformative = false;
593 
594  if (!R.Qualifier)
595  R.Qualifier = getRequiredQualification(SemaRef.Context,
596  CurContext,
597  R.Declaration->getDeclContext());
598  return false;
599 }
600 
601 /// \brief A simplified classification of types used to determine whether two
602 /// types are "similar enough" when adjusting priorities.
604  switch (T->getTypeClass()) {
605  case Type::Builtin:
606  switch (cast<BuiltinType>(T)->getKind()) {
607  case BuiltinType::Void:
608  return STC_Void;
609 
610  case BuiltinType::NullPtr:
611  return STC_Pointer;
612 
613  case BuiltinType::Overload:
614  case BuiltinType::Dependent:
615  return STC_Other;
616 
617  case BuiltinType::ObjCId:
618  case BuiltinType::ObjCClass:
619  case BuiltinType::ObjCSel:
620  return STC_ObjectiveC;
621 
622  default:
623  return STC_Arithmetic;
624  }
625 
626  case Type::Complex:
627  return STC_Arithmetic;
628 
629  case Type::Pointer:
630  return STC_Pointer;
631 
632  case Type::BlockPointer:
633  return STC_Block;
634 
635  case Type::LValueReference:
636  case Type::RValueReference:
638 
639  case Type::ConstantArray:
640  case Type::IncompleteArray:
641  case Type::VariableArray:
642  case Type::DependentSizedArray:
643  return STC_Array;
644 
645  case Type::DependentSizedExtVector:
646  case Type::Vector:
647  case Type::ExtVector:
648  return STC_Arithmetic;
649 
650  case Type::FunctionProto:
651  case Type::FunctionNoProto:
652  return STC_Function;
653 
654  case Type::Record:
655  return STC_Record;
656 
657  case Type::Enum:
658  return STC_Arithmetic;
659 
660  case Type::ObjCObject:
661  case Type::ObjCInterface:
662  case Type::ObjCObjectPointer:
663  return STC_ObjectiveC;
664 
665  default:
666  return STC_Other;
667  }
668 }
669 
670 /// \brief Get the type that a given expression will have if this declaration
671 /// is used as an expression in its "typical" code-completion form.
673  ND = cast<NamedDecl>(ND->getUnderlyingDecl());
674 
675  if (const TypeDecl *Type = dyn_cast<TypeDecl>(ND))
676  return C.getTypeDeclType(Type);
677  if (const ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
678  return C.getObjCInterfaceType(Iface);
679 
680  QualType T;
681  if (const FunctionDecl *Function = ND->getAsFunction())
682  T = Function->getCallResultType();
683  else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
684  T = Method->getSendResultType();
685  else if (const EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
686  T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
687  else if (const ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
688  T = Property->getType();
689  else if (const ValueDecl *Value = dyn_cast<ValueDecl>(ND))
690  T = Value->getType();
691  else
692  return QualType();
693 
694  // Dig through references, function pointers, and block pointers to
695  // get down to the likely type of an expression when the entity is
696  // used.
697  do {
698  if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
699  T = Ref->getPointeeType();
700  continue;
701  }
702 
703  if (const PointerType *Pointer = T->getAs<PointerType>()) {
704  if (Pointer->getPointeeType()->isFunctionType()) {
705  T = Pointer->getPointeeType();
706  continue;
707  }
708 
709  break;
710  }
711 
712  if (const BlockPointerType *Block = T->getAs<BlockPointerType>()) {
713  T = Block->getPointeeType();
714  continue;
715  }
716 
717  if (const FunctionType *Function = T->getAs<FunctionType>()) {
718  T = Function->getReturnType();
719  continue;
720  }
721 
722  break;
723  } while (true);
724 
725  return T;
726 }
727 
728 unsigned ResultBuilder::getBasePriority(const NamedDecl *ND) {
729  if (!ND)
730  return CCP_Unlikely;
731 
732  // Context-based decisions.
733  const DeclContext *LexicalDC = ND->getLexicalDeclContext();
734  if (LexicalDC->isFunctionOrMethod()) {
735  // _cmd is relatively rare
736  if (const ImplicitParamDecl *ImplicitParam =
737  dyn_cast<ImplicitParamDecl>(ND))
738  if (ImplicitParam->getIdentifier() &&
739  ImplicitParam->getIdentifier()->isStr("_cmd"))
740  return CCP_ObjC_cmd;
741 
742  return CCP_LocalDeclaration;
743  }
744 
745  const DeclContext *DC = ND->getDeclContext()->getRedeclContext();
746  if (DC->isRecord() || isa<ObjCContainerDecl>(DC)) {
747  // Explicit destructor calls are very rare.
748  if (isa<CXXDestructorDecl>(ND))
749  return CCP_Unlikely;
750  // Explicit operator and conversion function calls are also very rare.
751  auto DeclNameKind = ND->getDeclName().getNameKind();
752  if (DeclNameKind == DeclarationName::CXXOperatorName ||
753  DeclNameKind == DeclarationName::CXXLiteralOperatorName ||
755  return CCP_Unlikely;
756  return CCP_MemberDeclaration;
757  }
758 
759  // Content-based decisions.
760  if (isa<EnumConstantDecl>(ND))
761  return CCP_Constant;
762 
763  // Use CCP_Type for type declarations unless we're in a statement, Objective-C
764  // message receiver, or parenthesized expression context. There, it's as
765  // likely that the user will want to write a type as other declarations.
766  if ((isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
767  !(CompletionContext.getKind() == CodeCompletionContext::CCC_Statement ||
768  CompletionContext.getKind()
770  CompletionContext.getKind()
772  return CCP_Type;
773 
774  return CCP_Declaration;
775 }
776 
777 void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
778  // If this is an Objective-C method declaration whose selector matches our
779  // preferred selector, give it a priority boost.
780  if (!PreferredSelector.isNull())
781  if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
782  if (PreferredSelector == Method->getSelector())
783  R.Priority += CCD_SelectorMatch;
784 
785  // If we have a preferred type, adjust the priority for results with exactly-
786  // matching or nearly-matching types.
787  if (!PreferredType.isNull()) {
788  QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
789  if (!T.isNull()) {
790  CanQualType TC = SemaRef.Context.getCanonicalType(T);
791  // Check for exactly-matching types (modulo qualifiers).
792  if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
793  R.Priority /= CCF_ExactTypeMatch;
794  // Check for nearly-matching types, based on classification of each.
795  else if ((getSimplifiedTypeClass(PreferredType)
796  == getSimplifiedTypeClass(TC)) &&
797  !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
798  R.Priority /= CCF_SimilarTypeMatch;
799  }
800  }
801 }
802 
803 void ResultBuilder::MaybeAddConstructorResults(Result R) {
804  if (!SemaRef.getLangOpts().CPlusPlus || !R.Declaration ||
805  !CompletionContext.wantConstructorResults())
806  return;
807 
808  ASTContext &Context = SemaRef.Context;
809  const NamedDecl *D = R.Declaration;
810  const CXXRecordDecl *Record = nullptr;
811  if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
812  Record = ClassTemplate->getTemplatedDecl();
813  else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
814  // Skip specializations and partial specializations.
815  if (isa<ClassTemplateSpecializationDecl>(Record))
816  return;
817  } else {
818  // There are no constructors here.
819  return;
820  }
821 
822  Record = Record->getDefinition();
823  if (!Record)
824  return;
825 
826 
827  QualType RecordTy = Context.getTypeDeclType(Record);
828  DeclarationName ConstructorName
830  Context.getCanonicalType(RecordTy));
831  DeclContext::lookup_result Ctors = Record->lookup(ConstructorName);
832  for (DeclContext::lookup_iterator I = Ctors.begin(),
833  E = Ctors.end();
834  I != E; ++I) {
835  R.Declaration = *I;
836  R.CursorKind = getCursorKindForDecl(R.Declaration);
837  Results.push_back(R);
838  }
839 }
840 
841 void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
842  assert(!ShadowMaps.empty() && "Must enter into a results scope");
843 
844  if (R.Kind != Result::RK_Declaration) {
845  // For non-declaration results, just add the result.
846  Results.push_back(R);
847  return;
848  }
849 
850  // Look through using declarations.
851  if (const UsingShadowDecl *Using =
852  dyn_cast<UsingShadowDecl>(R.Declaration)) {
853  MaybeAddResult(Result(Using->getTargetDecl(),
854  getBasePriority(Using->getTargetDecl()),
855  R.Qualifier),
856  CurContext);
857  return;
858  }
859 
860  const Decl *CanonDecl = R.Declaration->getCanonicalDecl();
861  unsigned IDNS = CanonDecl->getIdentifierNamespace();
862 
863  bool AsNestedNameSpecifier = false;
864  if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
865  return;
866 
867  // C++ constructors are never found by name lookup.
868  if (isa<CXXConstructorDecl>(R.Declaration))
869  return;
870 
871  ShadowMap &SMap = ShadowMaps.back();
872  ShadowMapEntry::iterator I, IEnd;
873  ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
874  if (NamePos != SMap.end()) {
875  I = NamePos->second.begin();
876  IEnd = NamePos->second.end();
877  }
878 
879  for (; I != IEnd; ++I) {
880  const NamedDecl *ND = I->first;
881  unsigned Index = I->second;
882  if (ND->getCanonicalDecl() == CanonDecl) {
883  // This is a redeclaration. Always pick the newer declaration.
884  Results[Index].Declaration = R.Declaration;
885 
886  // We're done.
887  return;
888  }
889  }
890 
891  // This is a new declaration in this scope. However, check whether this
892  // declaration name is hidden by a similarly-named declaration in an outer
893  // scope.
894  std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
895  --SMEnd;
896  for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
897  ShadowMapEntry::iterator I, IEnd;
898  ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
899  if (NamePos != SM->end()) {
900  I = NamePos->second.begin();
901  IEnd = NamePos->second.end();
902  }
903  for (; I != IEnd; ++I) {
904  // A tag declaration does not hide a non-tag declaration.
905  if (I->first->hasTagIdentifierNamespace() &&
908  continue;
909 
910  // Protocols are in distinct namespaces from everything else.
911  if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
912  || (IDNS & Decl::IDNS_ObjCProtocol)) &&
913  I->first->getIdentifierNamespace() != IDNS)
914  continue;
915 
916  // The newly-added result is hidden by an entry in the shadow map.
917  if (CheckHiddenResult(R, CurContext, I->first))
918  return;
919 
920  break;
921  }
922  }
923 
924  // Make sure that any given declaration only shows up in the result set once.
925  if (!AllDeclsFound.insert(CanonDecl).second)
926  return;
927 
928  // If the filter is for nested-name-specifiers, then this result starts a
929  // nested-name-specifier.
930  if (AsNestedNameSpecifier) {
931  R.StartsNestedNameSpecifier = true;
932  R.Priority = CCP_NestedNameSpecifier;
933  } else
934  AdjustResultPriorityForDecl(R);
935 
936  // If this result is supposed to have an informative qualifier, add one.
937  if (R.QualifierIsInformative && !R.Qualifier &&
938  !R.StartsNestedNameSpecifier) {
939  const DeclContext *Ctx = R.Declaration->getDeclContext();
940  if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
941  R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr,
942  Namespace);
943  else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
944  R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr,
945  false, SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
946  else
947  R.QualifierIsInformative = false;
948  }
949 
950  // Insert this result into the set of results and into the current shadow
951  // map.
952  SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
953  Results.push_back(R);
954 
955  if (!AsNestedNameSpecifier)
956  MaybeAddConstructorResults(R);
957 }
958 
959 void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
960  NamedDecl *Hiding, bool InBaseClass = false) {
961  if (R.Kind != Result::RK_Declaration) {
962  // For non-declaration results, just add the result.
963  Results.push_back(R);
964  return;
965  }
966 
967  // Look through using declarations.
968  if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
969  AddResult(Result(Using->getTargetDecl(),
970  getBasePriority(Using->getTargetDecl()),
971  R.Qualifier),
972  CurContext, Hiding);
973  return;
974  }
975 
976  bool AsNestedNameSpecifier = false;
977  if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
978  return;
979 
980  // C++ constructors are never found by name lookup.
981  if (isa<CXXConstructorDecl>(R.Declaration))
982  return;
983 
984  if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
985  return;
986 
987  // Make sure that any given declaration only shows up in the result set once.
988  if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()).second)
989  return;
990 
991  // If the filter is for nested-name-specifiers, then this result starts a
992  // nested-name-specifier.
993  if (AsNestedNameSpecifier) {
994  R.StartsNestedNameSpecifier = true;
995  R.Priority = CCP_NestedNameSpecifier;
996  }
997  else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
998  isa<CXXRecordDecl>(R.Declaration->getDeclContext()
999  ->getRedeclContext()))
1000  R.QualifierIsInformative = true;
1001 
1002  // If this result is supposed to have an informative qualifier, add one.
1003  if (R.QualifierIsInformative && !R.Qualifier &&
1004  !R.StartsNestedNameSpecifier) {
1005  const DeclContext *Ctx = R.Declaration->getDeclContext();
1006  if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
1007  R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr,
1008  Namespace);
1009  else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
1010  R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr, false,
1011  SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
1012  else
1013  R.QualifierIsInformative = false;
1014  }
1015 
1016  // Adjust the priority if this result comes from a base class.
1017  if (InBaseClass)
1018  R.Priority += CCD_InBaseClass;
1019 
1020  AdjustResultPriorityForDecl(R);
1021 
1022  if (HasObjectTypeQualifiers)
1023  if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
1024  if (Method->isInstance()) {
1025  Qualifiers MethodQuals
1026  = Qualifiers::fromCVRMask(Method->getTypeQualifiers());
1027  if (ObjectTypeQualifiers == MethodQuals)
1028  R.Priority += CCD_ObjectQualifierMatch;
1029  else if (ObjectTypeQualifiers - MethodQuals) {
1030  // The method cannot be invoked, because doing so would drop
1031  // qualifiers.
1032  return;
1033  }
1034  }
1035 
1036  // Insert this result into the set of results.
1037  Results.push_back(R);
1038 
1039  if (!AsNestedNameSpecifier)
1040  MaybeAddConstructorResults(R);
1041 }
1042 
1043 void ResultBuilder::AddResult(Result R) {
1044  assert(R.Kind != Result::RK_Declaration &&
1045  "Declaration results need more context");
1046  Results.push_back(R);
1047 }
1048 
1049 /// \brief Enter into a new scope.
1050 void ResultBuilder::EnterNewScope() { ShadowMaps.emplace_back(); }
1051 
1052 /// \brief Exit from the current scope.
1053 void ResultBuilder::ExitScope() {
1054  for (ShadowMap::iterator E = ShadowMaps.back().begin(),
1055  EEnd = ShadowMaps.back().end();
1056  E != EEnd;
1057  ++E)
1058  E->second.Destroy();
1059 
1060  ShadowMaps.pop_back();
1061 }
1062 
1063 /// \brief Determines whether this given declaration will be found by
1064 /// ordinary name lookup.
1065 bool ResultBuilder::IsOrdinaryName(const NamedDecl *ND) const {
1066  ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1067 
1068  // If name lookup finds a local extern declaration, then we are in a
1069  // context where it behaves like an ordinary name.
1070  unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1071  if (SemaRef.getLangOpts().CPlusPlus)
1073  else if (SemaRef.getLangOpts().ObjC1) {
1074  if (isa<ObjCIvarDecl>(ND))
1075  return true;
1076  }
1077 
1078  return ND->getIdentifierNamespace() & IDNS;
1079 }
1080 
1081 /// \brief Determines whether this given declaration will be found by
1082 /// ordinary name lookup but is not a type name.
1083 bool ResultBuilder::IsOrdinaryNonTypeName(const NamedDecl *ND) const {
1084  ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1085  if (isa<TypeDecl>(ND))
1086  return false;
1087  // Objective-C interfaces names are not filtered by this method because they
1088  // can be used in a class property expression. We can still filter out
1089  // @class declarations though.
1090  if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND)) {
1091  if (!ID->getDefinition())
1092  return false;
1093  }
1094 
1095  unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1096  if (SemaRef.getLangOpts().CPlusPlus)
1098  else if (SemaRef.getLangOpts().ObjC1) {
1099  if (isa<ObjCIvarDecl>(ND))
1100  return true;
1101  }
1102 
1103  return ND->getIdentifierNamespace() & IDNS;
1104 }
1105 
1106 bool ResultBuilder::IsIntegralConstantValue(const NamedDecl *ND) const {
1107  if (!IsOrdinaryNonTypeName(ND))
1108  return 0;
1109 
1110  if (const ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
1111  if (VD->getType()->isIntegralOrEnumerationType())
1112  return true;
1113 
1114  return false;
1115 }
1116 
1117 /// \brief Determines whether this given declaration will be found by
1118 /// ordinary name lookup.
1119 bool ResultBuilder::IsOrdinaryNonValueName(const NamedDecl *ND) const {
1120  ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1121 
1122  unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1123  if (SemaRef.getLangOpts().CPlusPlus)
1125 
1126  return (ND->getIdentifierNamespace() & IDNS) &&
1127  !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
1128  !isa<ObjCPropertyDecl>(ND);
1129 }
1130 
1131 /// \brief Determines whether the given declaration is suitable as the
1132 /// start of a C++ nested-name-specifier, e.g., a class or namespace.
1133 bool ResultBuilder::IsNestedNameSpecifier(const NamedDecl *ND) const {
1134  // Allow us to find class templates, too.
1135  if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1136  ND = ClassTemplate->getTemplatedDecl();
1137 
1138  return SemaRef.isAcceptableNestedNameSpecifier(ND);
1139 }
1140 
1141 /// \brief Determines whether the given declaration is an enumeration.
1142 bool ResultBuilder::IsEnum(const NamedDecl *ND) const {
1143  return isa<EnumDecl>(ND);
1144 }
1145 
1146 /// \brief Determines whether the given declaration is a class or struct.
1147 bool ResultBuilder::IsClassOrStruct(const NamedDecl *ND) const {
1148  // Allow us to find class templates, too.
1149  if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1150  ND = ClassTemplate->getTemplatedDecl();
1151 
1152  // For purposes of this check, interfaces match too.
1153  if (const RecordDecl *RD = dyn_cast<RecordDecl>(ND))
1154  return RD->getTagKind() == TTK_Class ||
1155  RD->getTagKind() == TTK_Struct ||
1156  RD->getTagKind() == TTK_Interface;
1157 
1158  return false;
1159 }
1160 
1161 /// \brief Determines whether the given declaration is a union.
1162 bool ResultBuilder::IsUnion(const NamedDecl *ND) const {
1163  // Allow us to find class templates, too.
1164  if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1165  ND = ClassTemplate->getTemplatedDecl();
1166 
1167  if (const RecordDecl *RD = dyn_cast<RecordDecl>(ND))
1168  return RD->getTagKind() == TTK_Union;
1169 
1170  return false;
1171 }
1172 
1173 /// \brief Determines whether the given declaration is a namespace.
1174 bool ResultBuilder::IsNamespace(const NamedDecl *ND) const {
1175  return isa<NamespaceDecl>(ND);
1176 }
1177 
1178 /// \brief Determines whether the given declaration is a namespace or
1179 /// namespace alias.
1180 bool ResultBuilder::IsNamespaceOrAlias(const NamedDecl *ND) const {
1181  return isa<NamespaceDecl>(ND->getUnderlyingDecl());
1182 }
1183 
1184 /// \brief Determines whether the given declaration is a type.
1185 bool ResultBuilder::IsType(const NamedDecl *ND) const {
1186  ND = ND->getUnderlyingDecl();
1187  return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1188 }
1189 
1190 /// \brief Determines which members of a class should be visible via
1191 /// "." or "->". Only value declarations, nested name specifiers, and
1192 /// using declarations thereof should show up.
1193 bool ResultBuilder::IsMember(const NamedDecl *ND) const {
1194  ND = ND->getUnderlyingDecl();
1195  return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
1196  isa<ObjCPropertyDecl>(ND);
1197 }
1198 
1200  T = C.getCanonicalType(T);
1201  switch (T->getTypeClass()) {
1202  case Type::ObjCObject:
1203  case Type::ObjCInterface:
1204  case Type::ObjCObjectPointer:
1205  return true;
1206 
1207  case Type::Builtin:
1208  switch (cast<BuiltinType>(T)->getKind()) {
1209  case BuiltinType::ObjCId:
1210  case BuiltinType::ObjCClass:
1211  case BuiltinType::ObjCSel:
1212  return true;
1213 
1214  default:
1215  break;
1216  }
1217  return false;
1218 
1219  default:
1220  break;
1221  }
1222 
1223  if (!C.getLangOpts().CPlusPlus)
1224  return false;
1225 
1226  // FIXME: We could perform more analysis here to determine whether a
1227  // particular class type has any conversions to Objective-C types. For now,
1228  // just accept all class types.
1229  return T->isDependentType() || T->isRecordType();
1230 }
1231 
1232 bool ResultBuilder::IsObjCMessageReceiver(const NamedDecl *ND) const {
1233  QualType T = getDeclUsageType(SemaRef.Context, ND);
1234  if (T.isNull())
1235  return false;
1236 
1237  T = SemaRef.Context.getBaseElementType(T);
1238  return isObjCReceiverType(SemaRef.Context, T);
1239 }
1240 
1241 bool ResultBuilder::IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const {
1242  if (IsObjCMessageReceiver(ND))
1243  return true;
1244 
1245  const VarDecl *Var = dyn_cast<VarDecl>(ND);
1246  if (!Var)
1247  return false;
1248 
1249  return Var->hasLocalStorage() && !Var->hasAttr<BlocksAttr>();
1250 }
1251 
1252 bool ResultBuilder::IsObjCCollection(const NamedDecl *ND) const {
1253  if ((SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryName(ND)) ||
1254  (!SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1255  return false;
1256 
1257  QualType T = getDeclUsageType(SemaRef.Context, ND);
1258  if (T.isNull())
1259  return false;
1260 
1261  T = SemaRef.Context.getBaseElementType(T);
1262  return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1263  T->isObjCIdType() ||
1264  (SemaRef.getLangOpts().CPlusPlus && T->isRecordType());
1265 }
1266 
1267 bool ResultBuilder::IsImpossibleToSatisfy(const NamedDecl *ND) const {
1268  return false;
1269 }
1270 
1271 /// \brief Determines whether the given declaration is an Objective-C
1272 /// instance variable.
1273 bool ResultBuilder::IsObjCIvar(const NamedDecl *ND) const {
1274  return isa<ObjCIvarDecl>(ND);
1275 }
1276 
1277 namespace {
1278  /// \brief Visible declaration consumer that adds a code-completion result
1279  /// for each visible declaration.
1280  class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1281  ResultBuilder &Results;
1282  DeclContext *CurContext;
1283 
1284  public:
1285  CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
1286  : Results(Results), CurContext(CurContext) { }
1287 
1288  void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
1289  bool InBaseClass) override {
1290  bool Accessible = true;
1291  if (Ctx)
1292  Accessible = Results.getSema().IsSimplyAccessible(ND, Ctx);
1293 
1294  ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr,
1295  false, Accessible);
1296  Results.AddResult(Result, CurContext, Hiding, InBaseClass);
1297  }
1298  };
1299 }
1300 
1301 /// \brief Add type specifiers for the current language as keyword results.
1302 static void AddTypeSpecifierResults(const LangOptions &LangOpts,
1303  ResultBuilder &Results) {
1304  typedef CodeCompletionResult Result;
1305  Results.AddResult(Result("short", CCP_Type));
1306  Results.AddResult(Result("long", CCP_Type));
1307  Results.AddResult(Result("signed", CCP_Type));
1308  Results.AddResult(Result("unsigned", CCP_Type));
1309  Results.AddResult(Result("void", CCP_Type));
1310  Results.AddResult(Result("char", CCP_Type));
1311  Results.AddResult(Result("int", CCP_Type));
1312  Results.AddResult(Result("float", CCP_Type));
1313  Results.AddResult(Result("double", CCP_Type));
1314  Results.AddResult(Result("enum", CCP_Type));
1315  Results.AddResult(Result("struct", CCP_Type));
1316  Results.AddResult(Result("union", CCP_Type));
1317  Results.AddResult(Result("const", CCP_Type));
1318  Results.AddResult(Result("volatile", CCP_Type));
1319 
1320  if (LangOpts.C99) {
1321  // C99-specific
1322  Results.AddResult(Result("_Complex", CCP_Type));
1323  Results.AddResult(Result("_Imaginary", CCP_Type));
1324  Results.AddResult(Result("_Bool", CCP_Type));
1325  Results.AddResult(Result("restrict", CCP_Type));
1326  }
1327 
1328  CodeCompletionBuilder Builder(Results.getAllocator(),
1329  Results.getCodeCompletionTUInfo());
1330  if (LangOpts.CPlusPlus) {
1331  // C++-specific
1332  Results.AddResult(Result("bool", CCP_Type +
1333  (LangOpts.ObjC1? CCD_bool_in_ObjC : 0)));
1334  Results.AddResult(Result("class", CCP_Type));
1335  Results.AddResult(Result("wchar_t", CCP_Type));
1336 
1337  // typename qualified-id
1338  Builder.AddTypedTextChunk("typename");
1339  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1340  Builder.AddPlaceholderChunk("qualifier");
1341  Builder.AddTextChunk("::");
1342  Builder.AddPlaceholderChunk("name");
1343  Results.AddResult(Result(Builder.TakeString()));
1344 
1345  if (LangOpts.CPlusPlus11) {
1346  Results.AddResult(Result("auto", CCP_Type));
1347  Results.AddResult(Result("char16_t", CCP_Type));
1348  Results.AddResult(Result("char32_t", CCP_Type));
1349 
1350  Builder.AddTypedTextChunk("decltype");
1351  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1352  Builder.AddPlaceholderChunk("expression");
1353  Builder.AddChunk(CodeCompletionString::CK_RightParen);
1354  Results.AddResult(Result(Builder.TakeString()));
1355  }
1356  } else
1357  Results.AddResult(Result("__auto_type", CCP_Type));
1358 
1359  // GNU extensions
1360  if (LangOpts.GNUMode) {
1361  // FIXME: Enable when we actually support decimal floating point.
1362  // Results.AddResult(Result("_Decimal32"));
1363  // Results.AddResult(Result("_Decimal64"));
1364  // Results.AddResult(Result("_Decimal128"));
1365 
1366  Builder.AddTypedTextChunk("typeof");
1367  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1368  Builder.AddPlaceholderChunk("expression");
1369  Results.AddResult(Result(Builder.TakeString()));
1370 
1371  Builder.AddTypedTextChunk("typeof");
1372  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1373  Builder.AddPlaceholderChunk("type");
1374  Builder.AddChunk(CodeCompletionString::CK_RightParen);
1375  Results.AddResult(Result(Builder.TakeString()));
1376  }
1377 
1378  // Nullability
1379  Results.AddResult(Result("_Nonnull", CCP_Type));
1380  Results.AddResult(Result("_Null_unspecified", CCP_Type));
1381  Results.AddResult(Result("_Nullable", CCP_Type));
1382 }
1383 
1385  const LangOptions &LangOpts,
1386  ResultBuilder &Results) {
1387  typedef CodeCompletionResult Result;
1388  // Note: we don't suggest either "auto" or "register", because both
1389  // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1390  // in C++0x as a type specifier.
1391  Results.AddResult(Result("extern"));
1392  Results.AddResult(Result("static"));
1393 
1394  if (LangOpts.CPlusPlus11) {
1395  CodeCompletionAllocator &Allocator = Results.getAllocator();
1396  CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
1397 
1398  // alignas
1399  Builder.AddTypedTextChunk("alignas");
1400  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1401  Builder.AddPlaceholderChunk("expression");
1402  Builder.AddChunk(CodeCompletionString::CK_RightParen);
1403  Results.AddResult(Result(Builder.TakeString()));
1404 
1405  Results.AddResult(Result("constexpr"));
1406  Results.AddResult(Result("thread_local"));
1407  }
1408 }
1409 
1411  const LangOptions &LangOpts,
1412  ResultBuilder &Results) {
1413  typedef CodeCompletionResult Result;
1414  switch (CCC) {
1415  case Sema::PCC_Class:
1417  if (LangOpts.CPlusPlus) {
1418  Results.AddResult(Result("explicit"));
1419  Results.AddResult(Result("friend"));
1420  Results.AddResult(Result("mutable"));
1421  Results.AddResult(Result("virtual"));
1422  }
1423  // Fall through
1424 
1427  case Sema::PCC_Namespace:
1428  case Sema::PCC_Template:
1429  if (LangOpts.CPlusPlus || LangOpts.C99)
1430  Results.AddResult(Result("inline"));
1431  break;
1432 
1434  case Sema::PCC_Expression:
1435  case Sema::PCC_Statement:
1436  case Sema::PCC_ForInit:
1437  case Sema::PCC_Condition:
1439  case Sema::PCC_Type:
1442  break;
1443  }
1444 }
1445 
1446 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1447 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1448 static void AddObjCVisibilityResults(const LangOptions &LangOpts,
1449  ResultBuilder &Results,
1450  bool NeedAt);
1451 static void AddObjCImplementationResults(const LangOptions &LangOpts,
1452  ResultBuilder &Results,
1453  bool NeedAt);
1454 static void AddObjCInterfaceResults(const LangOptions &LangOpts,
1455  ResultBuilder &Results,
1456  bool NeedAt);
1457 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
1458 
1459 static void AddTypedefResult(ResultBuilder &Results) {
1460  CodeCompletionBuilder Builder(Results.getAllocator(),
1461  Results.getCodeCompletionTUInfo());
1462  Builder.AddTypedTextChunk("typedef");
1463  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1464  Builder.AddPlaceholderChunk("type");
1465  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1466  Builder.AddPlaceholderChunk("name");
1467  Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1468 }
1469 
1471  const LangOptions &LangOpts) {
1472  switch (CCC) {
1473  case Sema::PCC_Namespace:
1474  case Sema::PCC_Class:
1476  case Sema::PCC_Template:
1478  case Sema::PCC_Statement:
1480  case Sema::PCC_Type:
1483  return true;
1484 
1485  case Sema::PCC_Expression:
1486  case Sema::PCC_Condition:
1487  return LangOpts.CPlusPlus;
1488 
1491  return false;
1492 
1493  case Sema::PCC_ForInit:
1494  return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
1495  }
1496 
1497  llvm_unreachable("Invalid ParserCompletionContext!");
1498 }
1499 
1501  const Preprocessor &PP) {
1502  PrintingPolicy Policy = Sema::getPrintingPolicy(Context, PP);
1503  Policy.AnonymousTagLocations = false;
1504  Policy.SuppressStrongLifetime = true;
1505  Policy.SuppressUnwrittenScope = true;
1506  Policy.SuppressScope = true;
1507  return Policy;
1508 }
1509 
1510 /// \brief Retrieve a printing policy suitable for code completion.
1512  return getCompletionPrintingPolicy(S.Context, S.PP);
1513 }
1514 
1515 /// \brief Retrieve the string representation of the given type as a string
1516 /// that has the appropriate lifetime for code completion.
1517 ///
1518 /// This routine provides a fast path where we provide constant strings for
1519 /// common type names.
1521  ASTContext &Context,
1522  const PrintingPolicy &Policy,
1523  CodeCompletionAllocator &Allocator) {
1524  if (!T.getLocalQualifiers()) {
1525  // Built-in type names are constant strings.
1526  if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
1527  return BT->getNameAsCString(Policy);
1528 
1529  // Anonymous tag types are constant strings.
1530  if (const TagType *TagT = dyn_cast<TagType>(T))
1531  if (TagDecl *Tag = TagT->getDecl())
1532  if (!Tag->hasNameForLinkage()) {
1533  switch (Tag->getTagKind()) {
1534  case TTK_Struct: return "struct <anonymous>";
1535  case TTK_Interface: return "__interface <anonymous>";
1536  case TTK_Class: return "class <anonymous>";
1537  case TTK_Union: return "union <anonymous>";
1538  case TTK_Enum: return "enum <anonymous>";
1539  }
1540  }
1541  }
1542 
1543  // Slow path: format the type as a string.
1544  std::string Result;
1545  T.getAsStringInternal(Result, Policy);
1546  return Allocator.CopyString(Result);
1547 }
1548 
1549 /// \brief Add a completion for "this", if we're in a member function.
1550 static void addThisCompletion(Sema &S, ResultBuilder &Results) {
1551  QualType ThisTy = S.getCurrentThisType();
1552  if (ThisTy.isNull())
1553  return;
1554 
1555  CodeCompletionAllocator &Allocator = Results.getAllocator();
1556  CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
1558  Builder.AddResultTypeChunk(GetCompletionTypeString(ThisTy,
1559  S.Context,
1560  Policy,
1561  Allocator));
1562  Builder.AddTypedTextChunk("this");
1563  Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1564 }
1565 
1567  ResultBuilder &Results,
1568  const LangOptions &LangOpts) {
1569  if (!LangOpts.CPlusPlus11)
1570  return;
1571 
1572  Builder.AddTypedTextChunk("static_assert");
1574  Builder.AddPlaceholderChunk("expression");
1576  Builder.AddPlaceholderChunk("message");
1578  Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1579 }
1580 
1581 /// \brief Add language constructs that show up for "ordinary" names.
1583  Scope *S,
1584  Sema &SemaRef,
1585  ResultBuilder &Results) {
1586  CodeCompletionAllocator &Allocator = Results.getAllocator();
1587  CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
1588 
1589  typedef CodeCompletionResult Result;
1590  switch (CCC) {
1591  case Sema::PCC_Namespace:
1592  if (SemaRef.getLangOpts().CPlusPlus) {
1593  if (Results.includeCodePatterns()) {
1594  // namespace <identifier> { declarations }
1595  Builder.AddTypedTextChunk("namespace");
1596  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1597  Builder.AddPlaceholderChunk("identifier");
1598  Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1599  Builder.AddPlaceholderChunk("declarations");
1600  Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1601  Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1602  Results.AddResult(Result(Builder.TakeString()));
1603  }
1604 
1605  // namespace identifier = identifier ;
1606  Builder.AddTypedTextChunk("namespace");
1607  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1608  Builder.AddPlaceholderChunk("name");
1609  Builder.AddChunk(CodeCompletionString::CK_Equal);
1610  Builder.AddPlaceholderChunk("namespace");
1611  Results.AddResult(Result(Builder.TakeString()));
1612 
1613  // Using directives
1614  Builder.AddTypedTextChunk("using");
1615  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1616  Builder.AddTextChunk("namespace");
1617  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1618  Builder.AddPlaceholderChunk("identifier");
1619  Results.AddResult(Result(Builder.TakeString()));
1620 
1621  // asm(string-literal)
1622  Builder.AddTypedTextChunk("asm");
1623  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1624  Builder.AddPlaceholderChunk("string-literal");
1625  Builder.AddChunk(CodeCompletionString::CK_RightParen);
1626  Results.AddResult(Result(Builder.TakeString()));
1627 
1628  if (Results.includeCodePatterns()) {
1629  // Explicit template instantiation
1630  Builder.AddTypedTextChunk("template");
1631  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1632  Builder.AddPlaceholderChunk("declaration");
1633  Results.AddResult(Result(Builder.TakeString()));
1634  }
1635  }
1636 
1637  if (SemaRef.getLangOpts().ObjC1)
1638  AddObjCTopLevelResults(Results, true);
1639 
1640  AddTypedefResult(Results);
1641  // Fall through
1642 
1643  case Sema::PCC_Class:
1644  if (SemaRef.getLangOpts().CPlusPlus) {
1645  // Using declaration
1646  Builder.AddTypedTextChunk("using");
1647  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1648  Builder.AddPlaceholderChunk("qualifier");
1649  Builder.AddTextChunk("::");
1650  Builder.AddPlaceholderChunk("name");
1651  Results.AddResult(Result(Builder.TakeString()));
1652 
1653  // using typename qualifier::name (only in a dependent context)
1654  if (SemaRef.CurContext->isDependentContext()) {
1655  Builder.AddTypedTextChunk("using");
1656  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1657  Builder.AddTextChunk("typename");
1658  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1659  Builder.AddPlaceholderChunk("qualifier");
1660  Builder.AddTextChunk("::");
1661  Builder.AddPlaceholderChunk("name");
1662  Results.AddResult(Result(Builder.TakeString()));
1663  }
1664 
1665  AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts());
1666 
1667  if (CCC == Sema::PCC_Class) {
1668  AddTypedefResult(Results);
1669 
1670  bool IsNotInheritanceScope =
1672  // public:
1673  Builder.AddTypedTextChunk("public");
1674  if (IsNotInheritanceScope && Results.includeCodePatterns())
1675  Builder.AddChunk(CodeCompletionString::CK_Colon);
1676  Results.AddResult(Result(Builder.TakeString()));
1677 
1678  // protected:
1679  Builder.AddTypedTextChunk("protected");
1680  if (IsNotInheritanceScope && Results.includeCodePatterns())
1681  Builder.AddChunk(CodeCompletionString::CK_Colon);
1682  Results.AddResult(Result(Builder.TakeString()));
1683 
1684  // private:
1685  Builder.AddTypedTextChunk("private");
1686  if (IsNotInheritanceScope && Results.includeCodePatterns())
1687  Builder.AddChunk(CodeCompletionString::CK_Colon);
1688  Results.AddResult(Result(Builder.TakeString()));
1689  }
1690  }
1691  // Fall through
1692 
1693  case Sema::PCC_Template:
1695  if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns()) {
1696  // template < parameters >
1697  Builder.AddTypedTextChunk("template");
1698  Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1699  Builder.AddPlaceholderChunk("parameters");
1700  Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1701  Results.AddResult(Result(Builder.TakeString()));
1702  }
1703 
1704  AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1705  AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1706  break;
1707 
1709  AddObjCInterfaceResults(SemaRef.getLangOpts(), Results, true);
1710  AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1711  AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1712  break;
1713 
1715  AddObjCImplementationResults(SemaRef.getLangOpts(), Results, true);
1716  AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1717  AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1718  break;
1719 
1721  AddObjCVisibilityResults(SemaRef.getLangOpts(), Results, true);
1722  break;
1723 
1725  case Sema::PCC_Statement: {
1726  AddTypedefResult(Results);
1727 
1728  if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns() &&
1729  SemaRef.getLangOpts().CXXExceptions) {
1730  Builder.AddTypedTextChunk("try");
1731  Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1732  Builder.AddPlaceholderChunk("statements");
1733  Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1734  Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1735  Builder.AddTextChunk("catch");
1736  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1737  Builder.AddPlaceholderChunk("declaration");
1738  Builder.AddChunk(CodeCompletionString::CK_RightParen);
1739  Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1740  Builder.AddPlaceholderChunk("statements");
1741  Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1742  Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1743  Results.AddResult(Result(Builder.TakeString()));
1744  }
1745  if (SemaRef.getLangOpts().ObjC1)
1746  AddObjCStatementResults(Results, true);
1747 
1748  if (Results.includeCodePatterns()) {
1749  // if (condition) { statements }
1750  Builder.AddTypedTextChunk("if");
1751  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1752  if (SemaRef.getLangOpts().CPlusPlus)
1753  Builder.AddPlaceholderChunk("condition");
1754  else
1755  Builder.AddPlaceholderChunk("expression");
1756  Builder.AddChunk(CodeCompletionString::CK_RightParen);
1757  Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1758  Builder.AddPlaceholderChunk("statements");
1759  Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1760  Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1761  Results.AddResult(Result(Builder.TakeString()));
1762 
1763  // switch (condition) { }
1764  Builder.AddTypedTextChunk("switch");
1765  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1766  if (SemaRef.getLangOpts().CPlusPlus)
1767  Builder.AddPlaceholderChunk("condition");
1768  else
1769  Builder.AddPlaceholderChunk("expression");
1770  Builder.AddChunk(CodeCompletionString::CK_RightParen);
1771  Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1772  Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1773  Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1774  Results.AddResult(Result(Builder.TakeString()));
1775  }
1776 
1777  // Switch-specific statements.
1778  if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
1779  // case expression:
1780  Builder.AddTypedTextChunk("case");
1781  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1782  Builder.AddPlaceholderChunk("expression");
1783  Builder.AddChunk(CodeCompletionString::CK_Colon);
1784  Results.AddResult(Result(Builder.TakeString()));
1785 
1786  // default:
1787  Builder.AddTypedTextChunk("default");
1788  Builder.AddChunk(CodeCompletionString::CK_Colon);
1789  Results.AddResult(Result(Builder.TakeString()));
1790  }
1791 
1792  if (Results.includeCodePatterns()) {
1793  /// while (condition) { statements }
1794  Builder.AddTypedTextChunk("while");
1795  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1796  if (SemaRef.getLangOpts().CPlusPlus)
1797  Builder.AddPlaceholderChunk("condition");
1798  else
1799  Builder.AddPlaceholderChunk("expression");
1800  Builder.AddChunk(CodeCompletionString::CK_RightParen);
1801  Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1802  Builder.AddPlaceholderChunk("statements");
1803  Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1804  Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1805  Results.AddResult(Result(Builder.TakeString()));
1806 
1807  // do { statements } while ( expression );
1808  Builder.AddTypedTextChunk("do");
1809  Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1810  Builder.AddPlaceholderChunk("statements");
1811  Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1812  Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1813  Builder.AddTextChunk("while");
1814  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1815  Builder.AddPlaceholderChunk("expression");
1816  Builder.AddChunk(CodeCompletionString::CK_RightParen);
1817  Results.AddResult(Result(Builder.TakeString()));
1818 
1819  // for ( for-init-statement ; condition ; expression ) { statements }
1820  Builder.AddTypedTextChunk("for");
1821  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1822  if (SemaRef.getLangOpts().CPlusPlus || SemaRef.getLangOpts().C99)
1823  Builder.AddPlaceholderChunk("init-statement");
1824  else
1825  Builder.AddPlaceholderChunk("init-expression");
1826  Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1827  Builder.AddPlaceholderChunk("condition");
1828  Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1829  Builder.AddPlaceholderChunk("inc-expression");
1830  Builder.AddChunk(CodeCompletionString::CK_RightParen);
1831  Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1832  Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1833  Builder.AddPlaceholderChunk("statements");
1834  Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1835  Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1836  Results.AddResult(Result(Builder.TakeString()));
1837  }
1838 
1839  if (S->getContinueParent()) {
1840  // continue ;
1841  Builder.AddTypedTextChunk("continue");
1842  Results.AddResult(Result(Builder.TakeString()));
1843  }
1844 
1845  if (S->getBreakParent()) {
1846  // break ;
1847  Builder.AddTypedTextChunk("break");
1848  Results.AddResult(Result(Builder.TakeString()));
1849  }
1850 
1851  // "return expression ;" or "return ;", depending on whether we
1852  // know the function is void or not.
1853  bool isVoid = false;
1854  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1855  isVoid = Function->getReturnType()->isVoidType();
1856  else if (ObjCMethodDecl *Method
1857  = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1858  isVoid = Method->getReturnType()->isVoidType();
1859  else if (SemaRef.getCurBlock() &&
1860  !SemaRef.getCurBlock()->ReturnType.isNull())
1861  isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
1862  Builder.AddTypedTextChunk("return");
1863  if (!isVoid) {
1864  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1865  Builder.AddPlaceholderChunk("expression");
1866  }
1867  Results.AddResult(Result(Builder.TakeString()));
1868 
1869  // goto identifier ;
1870  Builder.AddTypedTextChunk("goto");
1871  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1872  Builder.AddPlaceholderChunk("label");
1873  Results.AddResult(Result(Builder.TakeString()));
1874 
1875  // Using directives
1876  Builder.AddTypedTextChunk("using");
1877  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1878  Builder.AddTextChunk("namespace");
1879  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1880  Builder.AddPlaceholderChunk("identifier");
1881  Results.AddResult(Result(Builder.TakeString()));
1882 
1883  AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts());
1884  }
1885  LLVM_FALLTHROUGH;
1886 
1887  // Fall through (for statement expressions).
1888  case Sema::PCC_ForInit:
1889  case Sema::PCC_Condition:
1890  AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1891  // Fall through: conditions and statements can have expressions.
1892  LLVM_FALLTHROUGH;
1893 
1895  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1897  // (__bridge <type>)<expression>
1898  Builder.AddTypedTextChunk("__bridge");
1899  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1900  Builder.AddPlaceholderChunk("type");
1901  Builder.AddChunk(CodeCompletionString::CK_RightParen);
1902  Builder.AddPlaceholderChunk("expression");
1903  Results.AddResult(Result(Builder.TakeString()));
1904 
1905  // (__bridge_transfer <Objective-C type>)<expression>
1906  Builder.AddTypedTextChunk("__bridge_transfer");
1907  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1908  Builder.AddPlaceholderChunk("Objective-C type");
1909  Builder.AddChunk(CodeCompletionString::CK_RightParen);
1910  Builder.AddPlaceholderChunk("expression");
1911  Results.AddResult(Result(Builder.TakeString()));
1912 
1913  // (__bridge_retained <CF type>)<expression>
1914  Builder.AddTypedTextChunk("__bridge_retained");
1915  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1916  Builder.AddPlaceholderChunk("CF type");
1917  Builder.AddChunk(CodeCompletionString::CK_RightParen);
1918  Builder.AddPlaceholderChunk("expression");
1919  Results.AddResult(Result(Builder.TakeString()));
1920  }
1921  // Fall through
1922  LLVM_FALLTHROUGH;
1923 
1924  case Sema::PCC_Expression: {
1925  if (SemaRef.getLangOpts().CPlusPlus) {
1926  // 'this', if we're in a non-static member function.
1927  addThisCompletion(SemaRef, Results);
1928 
1929  // true
1930  Builder.AddResultTypeChunk("bool");
1931  Builder.AddTypedTextChunk("true");
1932  Results.AddResult(Result(Builder.TakeString()));
1933 
1934  // false
1935  Builder.AddResultTypeChunk("bool");
1936  Builder.AddTypedTextChunk("false");
1937  Results.AddResult(Result(Builder.TakeString()));
1938 
1939  if (SemaRef.getLangOpts().RTTI) {
1940  // dynamic_cast < type-id > ( expression )
1941  Builder.AddTypedTextChunk("dynamic_cast");
1942  Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1943  Builder.AddPlaceholderChunk("type");
1944  Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1945  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1946  Builder.AddPlaceholderChunk("expression");
1947  Builder.AddChunk(CodeCompletionString::CK_RightParen);
1948  Results.AddResult(Result(Builder.TakeString()));
1949  }
1950 
1951  // static_cast < type-id > ( expression )
1952  Builder.AddTypedTextChunk("static_cast");
1953  Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1954  Builder.AddPlaceholderChunk("type");
1955  Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1956  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1957  Builder.AddPlaceholderChunk("expression");
1958  Builder.AddChunk(CodeCompletionString::CK_RightParen);
1959  Results.AddResult(Result(Builder.TakeString()));
1960 
1961  // reinterpret_cast < type-id > ( expression )
1962  Builder.AddTypedTextChunk("reinterpret_cast");
1963  Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1964  Builder.AddPlaceholderChunk("type");
1965  Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1966  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1967  Builder.AddPlaceholderChunk("expression");
1968  Builder.AddChunk(CodeCompletionString::CK_RightParen);
1969  Results.AddResult(Result(Builder.TakeString()));
1970 
1971  // const_cast < type-id > ( expression )
1972  Builder.AddTypedTextChunk("const_cast");
1973  Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1974  Builder.AddPlaceholderChunk("type");
1975  Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1976  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1977  Builder.AddPlaceholderChunk("expression");
1978  Builder.AddChunk(CodeCompletionString::CK_RightParen);
1979  Results.AddResult(Result(Builder.TakeString()));
1980 
1981  if (SemaRef.getLangOpts().RTTI) {
1982  // typeid ( expression-or-type )
1983  Builder.AddResultTypeChunk("std::type_info");
1984  Builder.AddTypedTextChunk("typeid");
1985  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1986  Builder.AddPlaceholderChunk("expression-or-type");
1987  Builder.AddChunk(CodeCompletionString::CK_RightParen);
1988  Results.AddResult(Result(Builder.TakeString()));
1989  }
1990 
1991  // new T ( ... )
1992  Builder.AddTypedTextChunk("new");
1993  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1994  Builder.AddPlaceholderChunk("type");
1995  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1996  Builder.AddPlaceholderChunk("expressions");
1997  Builder.AddChunk(CodeCompletionString::CK_RightParen);
1998  Results.AddResult(Result(Builder.TakeString()));
1999 
2000  // new T [ ] ( ... )
2001  Builder.AddTypedTextChunk("new");
2002  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2003  Builder.AddPlaceholderChunk("type");
2004  Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
2005  Builder.AddPlaceholderChunk("size");
2006  Builder.AddChunk(CodeCompletionString::CK_RightBracket);
2007  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2008  Builder.AddPlaceholderChunk("expressions");
2009  Builder.AddChunk(CodeCompletionString::CK_RightParen);
2010  Results.AddResult(Result(Builder.TakeString()));
2011 
2012  // delete expression
2013  Builder.AddResultTypeChunk("void");
2014  Builder.AddTypedTextChunk("delete");
2015  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2016  Builder.AddPlaceholderChunk("expression");
2017  Results.AddResult(Result(Builder.TakeString()));
2018 
2019  // delete [] expression
2020  Builder.AddResultTypeChunk("void");
2021  Builder.AddTypedTextChunk("delete");
2022  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2023  Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
2024  Builder.AddChunk(CodeCompletionString::CK_RightBracket);
2025  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2026  Builder.AddPlaceholderChunk("expression");
2027  Results.AddResult(Result(Builder.TakeString()));
2028 
2029  if (SemaRef.getLangOpts().CXXExceptions) {
2030  // throw expression
2031  Builder.AddResultTypeChunk("void");
2032  Builder.AddTypedTextChunk("throw");
2033  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2034  Builder.AddPlaceholderChunk("expression");
2035  Results.AddResult(Result(Builder.TakeString()));
2036  }
2037 
2038  // FIXME: Rethrow?
2039 
2040  if (SemaRef.getLangOpts().CPlusPlus11) {
2041  // nullptr
2042  Builder.AddResultTypeChunk("std::nullptr_t");
2043  Builder.AddTypedTextChunk("nullptr");
2044  Results.AddResult(Result(Builder.TakeString()));
2045 
2046  // alignof
2047  Builder.AddResultTypeChunk("size_t");
2048  Builder.AddTypedTextChunk("alignof");
2049  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2050  Builder.AddPlaceholderChunk("type");
2051  Builder.AddChunk(CodeCompletionString::CK_RightParen);
2052  Results.AddResult(Result(Builder.TakeString()));
2053 
2054  // noexcept
2055  Builder.AddResultTypeChunk("bool");
2056  Builder.AddTypedTextChunk("noexcept");
2057  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2058  Builder.AddPlaceholderChunk("expression");
2059  Builder.AddChunk(CodeCompletionString::CK_RightParen);
2060  Results.AddResult(Result(Builder.TakeString()));
2061 
2062  // sizeof... expression
2063  Builder.AddResultTypeChunk("size_t");
2064  Builder.AddTypedTextChunk("sizeof...");
2065  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2066  Builder.AddPlaceholderChunk("parameter-pack");
2067  Builder.AddChunk(CodeCompletionString::CK_RightParen);
2068  Results.AddResult(Result(Builder.TakeString()));
2069  }
2070  }
2071 
2072  if (SemaRef.getLangOpts().ObjC1) {
2073  // Add "super", if we're in an Objective-C class with a superclass.
2074  if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
2075  // The interface can be NULL.
2076  if (ObjCInterfaceDecl *ID = Method->getClassInterface())
2077  if (ID->getSuperClass()) {
2078  std::string SuperType;
2079  SuperType = ID->getSuperClass()->getNameAsString();
2080  if (Method->isInstanceMethod())
2081  SuperType += " *";
2082 
2083  Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
2084  Builder.AddTypedTextChunk("super");
2085  Results.AddResult(Result(Builder.TakeString()));
2086  }
2087  }
2088 
2089  AddObjCExpressionResults(Results, true);
2090  }
2091 
2092  if (SemaRef.getLangOpts().C11) {
2093  // _Alignof
2094  Builder.AddResultTypeChunk("size_t");
2095  if (SemaRef.PP.isMacroDefined("alignof"))
2096  Builder.AddTypedTextChunk("alignof");
2097  else
2098  Builder.AddTypedTextChunk("_Alignof");
2099  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2100  Builder.AddPlaceholderChunk("type");
2101  Builder.AddChunk(CodeCompletionString::CK_RightParen);
2102  Results.AddResult(Result(Builder.TakeString()));
2103  }
2104 
2105  // sizeof expression
2106  Builder.AddResultTypeChunk("size_t");
2107  Builder.AddTypedTextChunk("sizeof");
2108  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2109  Builder.AddPlaceholderChunk("expression-or-type");
2110  Builder.AddChunk(CodeCompletionString::CK_RightParen);
2111  Results.AddResult(Result(Builder.TakeString()));
2112  break;
2113  }
2114 
2115  case Sema::PCC_Type:
2117  break;
2118  }
2119 
2120  if (WantTypesInContext(CCC, SemaRef.getLangOpts()))
2121  AddTypeSpecifierResults(SemaRef.getLangOpts(), Results);
2122 
2123  if (SemaRef.getLangOpts().CPlusPlus && CCC != Sema::PCC_Type)
2124  Results.AddResult(Result("operator"));
2125 }
2126 
2127 /// \brief If the given declaration has an associated type, add it as a result
2128 /// type chunk.
2129 static void AddResultTypeChunk(ASTContext &Context,
2130  const PrintingPolicy &Policy,
2131  const NamedDecl *ND,
2132  QualType BaseType,
2133  CodeCompletionBuilder &Result) {
2134  if (!ND)
2135  return;
2136 
2137  // Skip constructors and conversion functions, which have their return types
2138  // built into their names.
2139  if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
2140  return;
2141 
2142  // Determine the type of the declaration (if it has a type).
2143  QualType T;
2144  if (const FunctionDecl *Function = ND->getAsFunction())
2145  T = Function->getReturnType();
2146  else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
2147  if (!BaseType.isNull())
2148  T = Method->getSendResultType(BaseType);
2149  else
2150  T = Method->getReturnType();
2151  } else if (const EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND)) {
2152  T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
2154  } else if (isa<UnresolvedUsingValueDecl>(ND)) {
2155  /* Do nothing: ignore unresolved using declarations*/
2156  } else if (const ObjCIvarDecl *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
2157  if (!BaseType.isNull())
2158  T = Ivar->getUsageType(BaseType);
2159  else
2160  T = Ivar->getType();
2161  } else if (const ValueDecl *Value = dyn_cast<ValueDecl>(ND)) {
2162  T = Value->getType();
2163  } else if (const ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND)) {
2164  if (!BaseType.isNull())
2165  T = Property->getUsageType(BaseType);
2166  else
2167  T = Property->getType();
2168  }
2169 
2170  if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
2171  return;
2172 
2173  Result.AddResultTypeChunk(GetCompletionTypeString(T, Context, Policy,
2174  Result.getAllocator()));
2175 }
2176 
2178  const NamedDecl *FunctionOrMethod,
2179  CodeCompletionBuilder &Result) {
2180  if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
2181  if (Sentinel->getSentinel() == 0) {
2182  if (PP.getLangOpts().ObjC1 && PP.isMacroDefined("nil"))
2183  Result.AddTextChunk(", nil");
2184  else if (PP.isMacroDefined("NULL"))
2185  Result.AddTextChunk(", NULL");
2186  else
2187  Result.AddTextChunk(", (void*)0");
2188  }
2189 }
2190 
2191 static std::string formatObjCParamQualifiers(unsigned ObjCQuals,
2192  QualType &Type) {
2193  std::string Result;
2194  if (ObjCQuals & Decl::OBJC_TQ_In)
2195  Result += "in ";
2196  else if (ObjCQuals & Decl::OBJC_TQ_Inout)
2197  Result += "inout ";
2198  else if (ObjCQuals & Decl::OBJC_TQ_Out)
2199  Result += "out ";
2200  if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
2201  Result += "bycopy ";
2202  else if (ObjCQuals & Decl::OBJC_TQ_Byref)
2203  Result += "byref ";
2204  if (ObjCQuals & Decl::OBJC_TQ_Oneway)
2205  Result += "oneway ";
2206  if (ObjCQuals & Decl::OBJC_TQ_CSNullability) {
2207  if (auto nullability = AttributedType::stripOuterNullability(Type)) {
2208  switch (*nullability) {
2210  Result += "nonnull ";
2211  break;
2212 
2214  Result += "nullable ";
2215  break;
2216 
2218  Result += "null_unspecified ";
2219  break;
2220  }
2221  }
2222  }
2223  return Result;
2224 }
2225 
2226 /// \brief Tries to find the most appropriate type location for an Objective-C
2227 /// block placeholder.
2228 ///
2229 /// This function ignores things like typedefs and qualifiers in order to
2230 /// present the most relevant and accurate block placeholders in code completion
2231 /// results.
2233  FunctionTypeLoc &Block,
2234  FunctionProtoTypeLoc &BlockProto,
2235  bool SuppressBlock = false) {
2236  if (!TSInfo)
2237  return;
2238  TypeLoc TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
2239  while (true) {
2240  // Look through typedefs.
2241  if (!SuppressBlock) {
2242  if (TypedefTypeLoc TypedefTL = TL.getAs<TypedefTypeLoc>()) {
2243  if (TypeSourceInfo *InnerTSInfo =
2244  TypedefTL.getTypedefNameDecl()->getTypeSourceInfo()) {
2245  TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2246  continue;
2247  }
2248  }
2249 
2250  // Look through qualified types
2251  if (QualifiedTypeLoc QualifiedTL = TL.getAs<QualifiedTypeLoc>()) {
2252  TL = QualifiedTL.getUnqualifiedLoc();
2253  continue;
2254  }
2255 
2256  if (AttributedTypeLoc AttrTL = TL.getAs<AttributedTypeLoc>()) {
2257  TL = AttrTL.getModifiedLoc();
2258  continue;
2259  }
2260  }
2261 
2262  // Try to get the function prototype behind the block pointer type,
2263  // then we're done.
2264  if (BlockPointerTypeLoc BlockPtr = TL.getAs<BlockPointerTypeLoc>()) {
2265  TL = BlockPtr.getPointeeLoc().IgnoreParens();
2266  Block = TL.getAs<FunctionTypeLoc>();
2267  BlockProto = TL.getAs<FunctionProtoTypeLoc>();
2268  }
2269  break;
2270  }
2271 }
2272 
2273 static std::string
2275  FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto,
2276  bool SuppressBlockName = false,
2277  bool SuppressBlock = false,
2278  Optional<ArrayRef<QualType>> ObjCSubsts = None);
2279 
2280 static std::string FormatFunctionParameter(const PrintingPolicy &Policy,
2281  const ParmVarDecl *Param,
2282  bool SuppressName = false,
2283  bool SuppressBlock = false,
2284  Optional<ArrayRef<QualType>> ObjCSubsts = None) {
2285  bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
2286  if (Param->getType()->isDependentType() ||
2287  !Param->getType()->isBlockPointerType()) {
2288  // The argument for a dependent or non-block parameter is a placeholder
2289  // containing that parameter's type.
2290  std::string Result;
2291 
2292  if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
2293  Result = Param->getIdentifier()->getName();
2294 
2295  QualType Type = Param->getType();
2296  if (ObjCSubsts)
2297  Type = Type.substObjCTypeArgs(Param->getASTContext(), *ObjCSubsts,
2299  if (ObjCMethodParam) {
2300  Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier(),
2301  Type);
2302  Result += Type.getAsString(Policy) + ")";
2303  if (Param->getIdentifier() && !SuppressName)
2304  Result += Param->getIdentifier()->getName();
2305  } else {
2306  Type.getAsStringInternal(Result, Policy);
2307  }
2308  return Result;
2309  }
2310 
2311  // The argument for a block pointer parameter is a block literal with
2312  // the appropriate type.
2313  FunctionTypeLoc Block;
2314  FunctionProtoTypeLoc BlockProto;
2315  findTypeLocationForBlockDecl(Param->getTypeSourceInfo(), Block, BlockProto,
2316  SuppressBlock);
2317  // Try to retrieve the block type information from the property if this is a
2318  // parameter in a setter.
2319  if (!Block && ObjCMethodParam &&
2320  cast<ObjCMethodDecl>(Param->getDeclContext())->isPropertyAccessor()) {
2321  if (const auto *PD = cast<ObjCMethodDecl>(Param->getDeclContext())
2322  ->findPropertyDecl(/*CheckOverrides=*/false))
2323  findTypeLocationForBlockDecl(PD->getTypeSourceInfo(), Block, BlockProto,
2324  SuppressBlock);
2325  }
2326 
2327  if (!Block) {
2328  // We were unable to find a FunctionProtoTypeLoc with parameter names
2329  // for the block; just use the parameter type as a placeholder.
2330  std::string Result;
2331  if (!ObjCMethodParam && Param->getIdentifier())
2332  Result = Param->getIdentifier()->getName();
2333 
2334  QualType Type = Param->getType().getUnqualifiedType();
2335 
2336  if (ObjCMethodParam) {
2337  Result = Type.getAsString(Policy);
2338  std::string Quals =
2340  if (!Quals.empty())
2341  Result = "(" + Quals + " " + Result + ")";
2342  if (Result.back() != ')')
2343  Result += " ";
2344  if (Param->getIdentifier())
2345  Result += Param->getIdentifier()->getName();
2346  } else {
2347  Type.getAsStringInternal(Result, Policy);
2348  }
2349 
2350  return Result;
2351  }
2352 
2353  // We have the function prototype behind the block pointer type, as it was
2354  // written in the source.
2355  return formatBlockPlaceholder(Policy, Param, Block, BlockProto,
2356  /*SuppressBlockName=*/false, SuppressBlock,
2357  ObjCSubsts);
2358 }
2359 
2360 /// \brief Returns a placeholder string that corresponds to an Objective-C block
2361 /// declaration.
2362 ///
2363 /// \param BlockDecl A declaration with an Objective-C block type.
2364 ///
2365 /// \param Block The most relevant type location for that block type.
2366 ///
2367 /// \param SuppressBlockName Determines wether or not the name of the block
2368 /// declaration is included in the resulting string.
2369 static std::string
2370 formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl,
2371  FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto,
2372  bool SuppressBlockName, bool SuppressBlock,
2373  Optional<ArrayRef<QualType>> ObjCSubsts) {
2374  std::string Result;
2375  QualType ResultType = Block.getTypePtr()->getReturnType();
2376  if (ObjCSubsts)
2377  ResultType =
2378  ResultType.substObjCTypeArgs(BlockDecl->getASTContext(), *ObjCSubsts,
2380  if (!ResultType->isVoidType() || SuppressBlock)
2381  ResultType.getAsStringInternal(Result, Policy);
2382 
2383  // Format the parameter list.
2384  std::string Params;
2385  if (!BlockProto || Block.getNumParams() == 0) {
2386  if (BlockProto && BlockProto.getTypePtr()->isVariadic())
2387  Params = "(...)";
2388  else
2389  Params = "(void)";
2390  } else {
2391  Params += "(";
2392  for (unsigned I = 0, N = Block.getNumParams(); I != N; ++I) {
2393  if (I)
2394  Params += ", ";
2395  Params += FormatFunctionParameter(Policy, Block.getParam(I),
2396  /*SuppressName=*/false,
2397  /*SuppressBlock=*/true, ObjCSubsts);
2398 
2399  if (I == N - 1 && BlockProto.getTypePtr()->isVariadic())
2400  Params += ", ...";
2401  }
2402  Params += ")";
2403  }
2404 
2405  if (SuppressBlock) {
2406  // Format as a parameter.
2407  Result = Result + " (^";
2408  if (!SuppressBlockName && BlockDecl->getIdentifier())
2409  Result += BlockDecl->getIdentifier()->getName();
2410  Result += ")";
2411  Result += Params;
2412  } else {
2413  // Format as a block literal argument.
2414  Result = '^' + Result;
2415  Result += Params;
2416 
2417  if (!SuppressBlockName && BlockDecl->getIdentifier())
2418  Result += BlockDecl->getIdentifier()->getName();
2419  }
2420 
2421  return Result;
2422 }
2423 
2424 static std::string GetDefaultValueString(const ParmVarDecl *Param,
2425  const SourceManager &SM,
2426  const LangOptions &LangOpts) {
2427  const SourceRange SrcRange = Param->getDefaultArgRange();
2428  CharSourceRange CharSrcRange = CharSourceRange::getTokenRange(SrcRange);
2429  bool Invalid = CharSrcRange.isInvalid();
2430  if (Invalid)
2431  return "";
2432  StringRef srcText = Lexer::getSourceText(CharSrcRange, SM, LangOpts, &Invalid);
2433  if (Invalid)
2434  return "";
2435 
2436  if (srcText.empty() || srcText == "=") {
2437  // Lexer can't determine the value.
2438  // This happens if the code is incorrect (for example class is forward declared).
2439  return "";
2440  }
2441  std::string DefValue(srcText.str());
2442  // FIXME: remove this check if the Lexer::getSourceText value is fixed and
2443  // this value always has (or always does not have) '=' in front of it
2444  if (DefValue.at(0) != '=') {
2445  // If we don't have '=' in front of value.
2446  // Lexer returns built-in types values without '=' and user-defined types values with it.
2447  return " = " + DefValue;
2448  }
2449  return " " + DefValue;
2450 }
2451 
2452 /// \brief Add function parameter chunks to the given code completion string.
2454  const PrintingPolicy &Policy,
2455  const FunctionDecl *Function,
2456  CodeCompletionBuilder &Result,
2457  unsigned Start = 0,
2458  bool InOptional = false) {
2459  bool FirstParameter = true;
2460 
2461  for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
2462  const ParmVarDecl *Param = Function->getParamDecl(P);
2463 
2464  if (Param->hasDefaultArg() && !InOptional) {
2465  // When we see an optional default argument, put that argument and
2466  // the remaining default arguments into a new, optional string.
2467  CodeCompletionBuilder Opt(Result.getAllocator(),
2468  Result.getCodeCompletionTUInfo());
2469  if (!FirstParameter)
2471  AddFunctionParameterChunks(PP, Policy, Function, Opt, P, true);
2472  Result.AddOptionalChunk(Opt.TakeString());
2473  break;
2474  }
2475 
2476  if (FirstParameter)
2477  FirstParameter = false;
2478  else
2480 
2481  InOptional = false;
2482 
2483  // Format the placeholder string.
2484  std::string PlaceholderStr = FormatFunctionParameter(Policy, Param);
2485  if (Param->hasDefaultArg())
2486  PlaceholderStr += GetDefaultValueString(Param, PP.getSourceManager(), PP.getLangOpts());
2487 
2488  if (Function->isVariadic() && P == N - 1)
2489  PlaceholderStr += ", ...";
2490 
2491  // Add the placeholder string.
2492  Result.AddPlaceholderChunk(
2493  Result.getAllocator().CopyString(PlaceholderStr));
2494  }
2495 
2496  if (const FunctionProtoType *Proto
2497  = Function->getType()->getAs<FunctionProtoType>())
2498  if (Proto->isVariadic()) {
2499  if (Proto->getNumParams() == 0)
2500  Result.AddPlaceholderChunk("...");
2501 
2502  MaybeAddSentinel(PP, Function, Result);
2503  }
2504 }
2505 
2506 /// \brief Add template parameter chunks to the given code completion string.
2508  const PrintingPolicy &Policy,
2509  const TemplateDecl *Template,
2510  CodeCompletionBuilder &Result,
2511  unsigned MaxParameters = 0,
2512  unsigned Start = 0,
2513  bool InDefaultArg = false) {
2514  bool FirstParameter = true;
2515 
2516  // Prefer to take the template parameter names from the first declaration of
2517  // the template.
2518  Template = cast<TemplateDecl>(Template->getCanonicalDecl());
2519 
2520  TemplateParameterList *Params = Template->getTemplateParameters();
2521  TemplateParameterList::iterator PEnd = Params->end();
2522  if (MaxParameters)
2523  PEnd = Params->begin() + MaxParameters;
2524  for (TemplateParameterList::iterator P = Params->begin() + Start;
2525  P != PEnd; ++P) {
2526  bool HasDefaultArg = false;
2527  std::string PlaceholderStr;
2528  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2529  if (TTP->wasDeclaredWithTypename())
2530  PlaceholderStr = "typename";
2531  else
2532  PlaceholderStr = "class";
2533 
2534  if (TTP->getIdentifier()) {
2535  PlaceholderStr += ' ';
2536  PlaceholderStr += TTP->getIdentifier()->getName();
2537  }
2538 
2539  HasDefaultArg = TTP->hasDefaultArgument();
2540  } else if (NonTypeTemplateParmDecl *NTTP
2541  = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
2542  if (NTTP->getIdentifier())
2543  PlaceholderStr = NTTP->getIdentifier()->getName();
2544  NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
2545  HasDefaultArg = NTTP->hasDefaultArgument();
2546  } else {
2547  assert(isa<TemplateTemplateParmDecl>(*P));
2548  TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2549 
2550  // Since putting the template argument list into the placeholder would
2551  // be very, very long, we just use an abbreviation.
2552  PlaceholderStr = "template<...> class";
2553  if (TTP->getIdentifier()) {
2554  PlaceholderStr += ' ';
2555  PlaceholderStr += TTP->getIdentifier()->getName();
2556  }
2557 
2558  HasDefaultArg = TTP->hasDefaultArgument();
2559  }
2560 
2561  if (HasDefaultArg && !InDefaultArg) {
2562  // When we see an optional default argument, put that argument and
2563  // the remaining default arguments into a new, optional string.
2564  CodeCompletionBuilder Opt(Result.getAllocator(),
2565  Result.getCodeCompletionTUInfo());
2566  if (!FirstParameter)
2568  AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
2569  P - Params->begin(), true);
2570  Result.AddOptionalChunk(Opt.TakeString());
2571  break;
2572  }
2573 
2574  InDefaultArg = false;
2575 
2576  if (FirstParameter)
2577  FirstParameter = false;
2578  else
2580 
2581  // Add the placeholder string.
2582  Result.AddPlaceholderChunk(
2583  Result.getAllocator().CopyString(PlaceholderStr));
2584  }
2585 }
2586 
2587 /// \brief Add a qualifier to the given code-completion string, if the
2588 /// provided nested-name-specifier is non-NULL.
2589 static void
2591  NestedNameSpecifier *Qualifier,
2592  bool QualifierIsInformative,
2593  ASTContext &Context,
2594  const PrintingPolicy &Policy) {
2595  if (!Qualifier)
2596  return;
2597 
2598  std::string PrintedNNS;
2599  {
2600  llvm::raw_string_ostream OS(PrintedNNS);
2601  Qualifier->print(OS, Policy);
2602  }
2603  if (QualifierIsInformative)
2604  Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
2605  else
2606  Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
2607 }
2608 
2609 static void
2611  const FunctionDecl *Function) {
2612  const FunctionProtoType *Proto
2613  = Function->getType()->getAs<FunctionProtoType>();
2614  if (!Proto || !Proto->getTypeQuals())
2615  return;
2616 
2617  // FIXME: Add ref-qualifier!
2618 
2619  // Handle single qualifiers without copying
2620  if (Proto->getTypeQuals() == Qualifiers::Const) {
2621  Result.AddInformativeChunk(" const");
2622  return;
2623  }
2624 
2625  if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2626  Result.AddInformativeChunk(" volatile");
2627  return;
2628  }
2629 
2630  if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2631  Result.AddInformativeChunk(" restrict");
2632  return;
2633  }
2634 
2635  // Handle multiple qualifiers.
2636  std::string QualsStr;
2637  if (Proto->isConst())
2638  QualsStr += " const";
2639  if (Proto->isVolatile())
2640  QualsStr += " volatile";
2641  if (Proto->isRestrict())
2642  QualsStr += " restrict";
2643  Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
2644 }
2645 
2646 /// \brief Add the name of the given declaration
2647 static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
2648  const NamedDecl *ND,
2649  CodeCompletionBuilder &Result) {
2650  DeclarationName Name = ND->getDeclName();
2651  if (!Name)
2652  return;
2653 
2654  switch (Name.getNameKind()) {
2656  const char *OperatorName = nullptr;
2657  switch (Name.getCXXOverloadedOperator()) {
2658  case OO_None:
2659  case OO_Conditional:
2661  OperatorName = "operator";
2662  break;
2663 
2664 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2665  case OO_##Name: OperatorName = "operator" Spelling; break;
2666 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2667 #include "clang/Basic/OperatorKinds.def"
2668 
2669  case OO_New: OperatorName = "operator new"; break;
2670  case OO_Delete: OperatorName = "operator delete"; break;
2671  case OO_Array_New: OperatorName = "operator new[]"; break;
2672  case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2673  case OO_Call: OperatorName = "operator()"; break;
2674  case OO_Subscript: OperatorName = "operator[]"; break;
2675  }
2676  Result.AddTypedTextChunk(OperatorName);
2677  break;
2678  }
2679 
2684  Result.AddTypedTextChunk(
2685  Result.getAllocator().CopyString(ND->getNameAsString()));
2686  break;
2687 
2693  break;
2694 
2696  CXXRecordDecl *Record = nullptr;
2697  QualType Ty = Name.getCXXNameType();
2698  if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2699  Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2700  else if (const InjectedClassNameType *InjectedTy
2701  = Ty->getAs<InjectedClassNameType>())
2702  Record = InjectedTy->getDecl();
2703  else {
2704  Result.AddTypedTextChunk(
2705  Result.getAllocator().CopyString(ND->getNameAsString()));
2706  break;
2707  }
2708 
2709  Result.AddTypedTextChunk(
2710  Result.getAllocator().CopyString(Record->getNameAsString()));
2711  if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
2713  AddTemplateParameterChunks(Context, Policy, Template, Result);
2715  }
2716  break;
2717  }
2718  }
2719 }
2720 
2722  const CodeCompletionContext &CCContext,
2723  CodeCompletionAllocator &Allocator,
2724  CodeCompletionTUInfo &CCTUInfo,
2725  bool IncludeBriefComments) {
2726  return CreateCodeCompletionString(S.Context, S.PP, CCContext, Allocator,
2727  CCTUInfo, IncludeBriefComments);
2728 }
2729 
2730 /// \brief If possible, create a new code completion string for the given
2731 /// result.
2732 ///
2733 /// \returns Either a new, heap-allocated code completion string describing
2734 /// how to use this result, or NULL to indicate that the string or name of the
2735 /// result is all that is needed.
2738  Preprocessor &PP,
2739  const CodeCompletionContext &CCContext,
2740  CodeCompletionAllocator &Allocator,
2741  CodeCompletionTUInfo &CCTUInfo,
2742  bool IncludeBriefComments) {
2743  CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
2744 
2745  PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP);
2746  if (Kind == RK_Pattern) {
2747  Pattern->Priority = Priority;
2748  Pattern->Availability = Availability;
2749 
2750  if (Declaration) {
2751  Result.addParentContext(Declaration->getDeclContext());
2752  Pattern->ParentName = Result.getParentName();
2753  // Provide code completion comment for self.GetterName where
2754  // GetterName is the getter method for a property with name
2755  // different from the property name (declared via a property
2756  // getter attribute.
2757  const NamedDecl *ND = Declaration;
2758  if (const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(ND))
2759  if (M->isPropertyAccessor())
2760  if (const ObjCPropertyDecl *PDecl = M->findPropertyDecl())
2761  if (PDecl->getGetterName() == M->getSelector() &&
2762  PDecl->getIdentifier() != M->getIdentifier()) {
2763  if (const RawComment *RC =
2764  Ctx.getRawCommentForAnyRedecl(M)) {
2765  Result.addBriefComment(RC->getBriefText(Ctx));
2766  Pattern->BriefComment = Result.getBriefComment();
2767  }
2768  else if (const RawComment *RC =
2769  Ctx.getRawCommentForAnyRedecl(PDecl)) {
2770  Result.addBriefComment(RC->getBriefText(Ctx));
2771  Pattern->BriefComment = Result.getBriefComment();
2772  }
2773  }
2774  }
2775 
2776  return Pattern;
2777  }
2778 
2779  if (Kind == RK_Keyword) {
2780  Result.AddTypedTextChunk(Keyword);
2781  return Result.TakeString();
2782  }
2783 
2784  if (Kind == RK_Macro) {
2785  const MacroInfo *MI = PP.getMacroInfo(Macro);
2786  Result.AddTypedTextChunk(
2787  Result.getAllocator().CopyString(Macro->getName()));
2788 
2789  if (!MI || !MI->isFunctionLike())
2790  return Result.TakeString();
2791 
2792  // Format a function-like macro with placeholders for the arguments.
2794  MacroInfo::param_iterator A = MI->param_begin(), AEnd = MI->param_end();
2795 
2796  // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
2797  if (MI->isC99Varargs()) {
2798  --AEnd;
2799 
2800  if (A == AEnd) {
2801  Result.AddPlaceholderChunk("...");
2802  }
2803  }
2804 
2805  for (MacroInfo::param_iterator A = MI->param_begin(); A != AEnd; ++A) {
2806  if (A != MI->param_begin())
2808 
2809  if (MI->isVariadic() && (A+1) == AEnd) {
2810  SmallString<32> Arg = (*A)->getName();
2811  if (MI->isC99Varargs())
2812  Arg += ", ...";
2813  else
2814  Arg += "...";
2815  Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
2816  break;
2817  }
2818 
2819  // Non-variadic macros are simple.
2820  Result.AddPlaceholderChunk(
2821  Result.getAllocator().CopyString((*A)->getName()));
2822  }
2824  return Result.TakeString();
2825  }
2826 
2827  assert(Kind == RK_Declaration && "Missed a result kind?");
2828  const NamedDecl *ND = Declaration;
2829  Result.addParentContext(ND->getDeclContext());
2830 
2831  if (IncludeBriefComments) {
2832  // Add documentation comment, if it exists.
2833  if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(ND)) {
2834  Result.addBriefComment(RC->getBriefText(Ctx));
2835  }
2836  else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
2837  if (OMD->isPropertyAccessor())
2838  if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
2839  if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(PDecl))
2840  Result.addBriefComment(RC->getBriefText(Ctx));
2841  }
2842 
2843  if (StartsNestedNameSpecifier) {
2844  Result.AddTypedTextChunk(
2845  Result.getAllocator().CopyString(ND->getNameAsString()));
2846  Result.AddTextChunk("::");
2847  return Result.TakeString();
2848  }
2849 
2850  for (const auto *I : ND->specific_attrs<AnnotateAttr>())
2851  Result.AddAnnotation(Result.getAllocator().CopyString(I->getAnnotation()));
2852 
2853  AddResultTypeChunk(Ctx, Policy, ND, CCContext.getBaseType(), Result);
2854 
2855  if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
2856  AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2857  Ctx, Policy);
2858  AddTypedNameChunk(Ctx, Policy, ND, Result);
2860  AddFunctionParameterChunks(PP, Policy, Function, Result);
2862  AddFunctionTypeQualsToCompletionString(Result, Function);
2863  return Result.TakeString();
2864  }
2865 
2866  if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
2867  AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2868  Ctx, Policy);
2869  FunctionDecl *Function = FunTmpl->getTemplatedDecl();
2870  AddTypedNameChunk(Ctx, Policy, Function, Result);
2871 
2872  // Figure out which template parameters are deduced (or have default
2873  // arguments).
2874  llvm::SmallBitVector Deduced;
2875  Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced);
2876  unsigned LastDeducibleArgument;
2877  for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2878  --LastDeducibleArgument) {
2879  if (!Deduced[LastDeducibleArgument - 1]) {
2880  // C++0x: Figure out if the template argument has a default. If so,
2881  // the user doesn't need to type this argument.
2882  // FIXME: We need to abstract template parameters better!
2883  bool HasDefaultArg = false;
2884  NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
2885  LastDeducibleArgument - 1);
2886  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2887  HasDefaultArg = TTP->hasDefaultArgument();
2888  else if (NonTypeTemplateParmDecl *NTTP
2889  = dyn_cast<NonTypeTemplateParmDecl>(Param))
2890  HasDefaultArg = NTTP->hasDefaultArgument();
2891  else {
2892  assert(isa<TemplateTemplateParmDecl>(Param));
2893  HasDefaultArg
2894  = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
2895  }
2896 
2897  if (!HasDefaultArg)
2898  break;
2899  }
2900  }
2901 
2902  if (LastDeducibleArgument) {
2903  // Some of the function template arguments cannot be deduced from a
2904  // function call, so we introduce an explicit template argument list
2905  // containing all of the arguments up to the first deducible argument.
2907  AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result,
2908  LastDeducibleArgument);
2910  }
2911 
2912  // Add the function parameters
2914  AddFunctionParameterChunks(PP, Policy, Function, Result);
2916  AddFunctionTypeQualsToCompletionString(Result, Function);
2917  return Result.TakeString();
2918  }
2919 
2920  if (const TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
2921  AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2922  Ctx, Policy);
2923  Result.AddTypedTextChunk(
2924  Result.getAllocator().CopyString(Template->getNameAsString()));
2926  AddTemplateParameterChunks(Ctx, Policy, Template, Result);
2928  return Result.TakeString();
2929  }
2930 
2931  if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
2932  Selector Sel = Method->getSelector();
2933  if (Sel.isUnarySelector()) {
2934  Result.AddTypedTextChunk(Result.getAllocator().CopyString(
2935  Sel.getNameForSlot(0)));
2936  return Result.TakeString();
2937  }
2938 
2939  std::string SelName = Sel.getNameForSlot(0).str();
2940  SelName += ':';
2941  if (StartParameter == 0)
2942  Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
2943  else {
2944  Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
2945 
2946  // If there is only one parameter, and we're past it, add an empty
2947  // typed-text chunk since there is nothing to type.
2948  if (Method->param_size() == 1)
2949  Result.AddTypedTextChunk("");
2950  }
2951  unsigned Idx = 0;
2952  for (ObjCMethodDecl::param_const_iterator P = Method->param_begin(),
2953  PEnd = Method->param_end();
2954  P != PEnd; (void)++P, ++Idx) {
2955  if (Idx > 0) {
2956  std::string Keyword;
2957  if (Idx > StartParameter)
2959  if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
2960  Keyword += II->getName();
2961  Keyword += ":";
2962  if (Idx < StartParameter || AllParametersAreInformative)
2963  Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
2964  else
2965  Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
2966  }
2967 
2968  // If we're before the starting parameter, skip the placeholder.
2969  if (Idx < StartParameter)
2970  continue;
2971 
2972  std::string Arg;
2973  QualType ParamType = (*P)->getType();
2974  Optional<ArrayRef<QualType>> ObjCSubsts;
2975  if (!CCContext.getBaseType().isNull())
2976  ObjCSubsts = CCContext.getBaseType()->getObjCSubstitutions(Method);
2977 
2978  if (ParamType->isBlockPointerType() && !DeclaringEntity)
2979  Arg = FormatFunctionParameter(Policy, *P, true,
2980  /*SuppressBlock=*/false,
2981  ObjCSubsts);
2982  else {
2983  if (ObjCSubsts)
2984  ParamType = ParamType.substObjCTypeArgs(Ctx, *ObjCSubsts,
2986  Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier(),
2987  ParamType);
2988  Arg += ParamType.getAsString(Policy) + ")";
2989  if (IdentifierInfo *II = (*P)->getIdentifier())
2990  if (DeclaringEntity || AllParametersAreInformative)
2991  Arg += II->getName();
2992  }
2993 
2994  if (Method->isVariadic() && (P + 1) == PEnd)
2995  Arg += ", ...";
2996 
2997  if (DeclaringEntity)
2998  Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
2999  else if (AllParametersAreInformative)
3000  Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
3001  else
3002  Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
3003  }
3004 
3005  if (Method->isVariadic()) {
3006  if (Method->param_size() == 0) {
3007  if (DeclaringEntity)
3008  Result.AddTextChunk(", ...");
3009  else if (AllParametersAreInformative)
3010  Result.AddInformativeChunk(", ...");
3011  else
3012  Result.AddPlaceholderChunk(", ...");
3013  }
3014 
3015  MaybeAddSentinel(PP, Method, Result);
3016  }
3017 
3018  return Result.TakeString();
3019  }
3020 
3021  if (Qualifier)
3022  AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
3023  Ctx, Policy);
3024 
3025  Result.AddTypedTextChunk(
3026  Result.getAllocator().CopyString(ND->getNameAsString()));
3027  return Result.TakeString();
3028 }
3029 
3030 /// \brief Add function overload parameter chunks to the given code completion
3031 /// string.
3033  const PrintingPolicy &Policy,
3034  const FunctionDecl *Function,
3035  const FunctionProtoType *Prototype,
3036  CodeCompletionBuilder &Result,
3037  unsigned CurrentArg,
3038  unsigned Start = 0,
3039  bool InOptional = false) {
3040  bool FirstParameter = true;
3041  unsigned NumParams = Function ? Function->getNumParams()
3042  : Prototype->getNumParams();
3043 
3044  for (unsigned P = Start; P != NumParams; ++P) {
3045  if (Function && Function->getParamDecl(P)->hasDefaultArg() && !InOptional) {
3046  // When we see an optional default argument, put that argument and
3047  // the remaining default arguments into a new, optional string.
3048  CodeCompletionBuilder Opt(Result.getAllocator(),
3049  Result.getCodeCompletionTUInfo());
3050  if (!FirstParameter)
3052  // Optional sections are nested.
3053  AddOverloadParameterChunks(Context, Policy, Function, Prototype, Opt,
3054  CurrentArg, P, /*InOptional=*/true);
3055  Result.AddOptionalChunk(Opt.TakeString());
3056  return;
3057  }
3058 
3059  if (FirstParameter)
3060  FirstParameter = false;
3061  else
3063 
3064  InOptional = false;
3065 
3066  // Format the placeholder string.
3067  std::string Placeholder;
3068  if (Function) {
3069  const ParmVarDecl *Param = Function->getParamDecl(P);
3070  Placeholder = FormatFunctionParameter(Policy, Param);
3071  if (Param->hasDefaultArg())
3072  Placeholder += GetDefaultValueString(Param, Context.getSourceManager(), Context.getLangOpts());
3073  } else {
3074  Placeholder = Prototype->getParamType(P).getAsString(Policy);
3075  }
3076 
3077  if (P == CurrentArg)
3078  Result.AddCurrentParameterChunk(
3079  Result.getAllocator().CopyString(Placeholder));
3080  else
3081  Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Placeholder));
3082  }
3083 
3084  if (Prototype && Prototype->isVariadic()) {
3085  CodeCompletionBuilder Opt(Result.getAllocator(),
3086  Result.getCodeCompletionTUInfo());
3087  if (!FirstParameter)
3089 
3090  if (CurrentArg < NumParams)
3091  Opt.AddPlaceholderChunk("...");
3092  else
3093  Opt.AddCurrentParameterChunk("...");
3094 
3095  Result.AddOptionalChunk(Opt.TakeString());
3096  }
3097 }
3098 
3101  unsigned CurrentArg, Sema &S,
3102  CodeCompletionAllocator &Allocator,
3103  CodeCompletionTUInfo &CCTUInfo,
3104  bool IncludeBriefComments) const {
3106 
3107  // FIXME: Set priority, availability appropriately.
3108  CodeCompletionBuilder Result(Allocator,CCTUInfo, 1, CXAvailability_Available);
3109  FunctionDecl *FDecl = getFunction();
3110  const FunctionProtoType *Proto
3111  = dyn_cast<FunctionProtoType>(getFunctionType());
3112  if (!FDecl && !Proto) {
3113  // Function without a prototype. Just give the return type and a
3114  // highlighted ellipsis.
3115  const FunctionType *FT = getFunctionType();
3116  Result.AddResultTypeChunk(Result.getAllocator().CopyString(
3117  FT->getReturnType().getAsString(Policy)));
3121  return Result.TakeString();
3122  }
3123 
3124  if (FDecl) {
3125  if (IncludeBriefComments && CurrentArg < FDecl->getNumParams())
3126  if (auto RC = S.getASTContext().getRawCommentForAnyRedecl(
3127  FDecl->getParamDecl(CurrentArg)))
3128  Result.addBriefComment(RC->getBriefText(S.getASTContext()));
3129  AddResultTypeChunk(S.Context, Policy, FDecl, QualType(), Result);
3130  Result.AddTextChunk(
3131  Result.getAllocator().CopyString(FDecl->getNameAsString()));
3132  } else {
3133  Result.AddResultTypeChunk(
3134  Result.getAllocator().CopyString(
3135  Proto->getReturnType().getAsString(Policy)));
3136  }
3137 
3139  AddOverloadParameterChunks(S.getASTContext(), Policy, FDecl, Proto, Result,
3140  CurrentArg);
3141  Result.AddChunk(CodeCompletionString::CK_RightParen);
3142 
3143  return Result.TakeString();
3144 }
3145 
3146 unsigned clang::getMacroUsagePriority(StringRef MacroName,
3147  const LangOptions &LangOpts,
3148  bool PreferredTypeIsPointer) {
3149  unsigned Priority = CCP_Macro;
3150 
3151  // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
3152  if (MacroName.equals("nil") || MacroName.equals("NULL") ||
3153  MacroName.equals("Nil")) {
3154  Priority = CCP_Constant;
3155  if (PreferredTypeIsPointer)
3156  Priority = Priority / CCF_SimilarTypeMatch;
3157  }
3158  // Treat "YES", "NO", "true", and "false" as constants.
3159  else if (MacroName.equals("YES") || MacroName.equals("NO") ||
3160  MacroName.equals("true") || MacroName.equals("false"))
3161  Priority = CCP_Constant;
3162  // Treat "bool" as a type.
3163  else if (MacroName.equals("bool"))
3164  Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
3165 
3166 
3167  return Priority;
3168 }
3169 
3171  if (!D)
3172  return CXCursor_UnexposedDecl;
3173 
3174  switch (D->getKind()) {
3175  case Decl::Enum: return CXCursor_EnumDecl;
3176  case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
3177  case Decl::Field: return CXCursor_FieldDecl;
3178  case Decl::Function:
3179  return CXCursor_FunctionDecl;
3180  case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
3181  case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
3182  case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
3183 
3184  case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
3185  case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
3186  case Decl::ObjCMethod:
3187  return cast<ObjCMethodDecl>(D)->isInstanceMethod()
3189  case Decl::CXXMethod: return CXCursor_CXXMethod;
3190  case Decl::CXXConstructor: return CXCursor_Constructor;
3191  case Decl::CXXDestructor: return CXCursor_Destructor;
3192  case Decl::CXXConversion: return CXCursor_ConversionFunction;
3193  case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
3194  case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
3195  case Decl::ParmVar: return CXCursor_ParmDecl;
3196  case Decl::Typedef: return CXCursor_TypedefDecl;
3197  case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
3198  case Decl::TypeAliasTemplate: return CXCursor_TypeAliasTemplateDecl;
3199  case Decl::Var: return CXCursor_VarDecl;
3200  case Decl::Namespace: return CXCursor_Namespace;
3201  case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
3202  case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
3203  case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
3204  case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
3205  case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
3206  case Decl::ClassTemplate: return CXCursor_ClassTemplate;
3207  case Decl::AccessSpec: return CXCursor_CXXAccessSpecifier;
3208  case Decl::ClassTemplatePartialSpecialization:
3210  case Decl::UsingDirective: return CXCursor_UsingDirective;
3211  case Decl::StaticAssert: return CXCursor_StaticAssert;
3212  case Decl::Friend: return CXCursor_FriendDecl;
3213  case Decl::TranslationUnit: return CXCursor_TranslationUnit;
3214 
3215  case Decl::Using:
3216  case Decl::UnresolvedUsingValue:
3217  case Decl::UnresolvedUsingTypename:
3219 
3220  case Decl::ObjCPropertyImpl:
3221  switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
3223  return CXCursor_ObjCDynamicDecl;
3224 
3227  }
3228 
3229  case Decl::Import:
3231 
3232  case Decl::ObjCTypeParam: return CXCursor_TemplateTypeParameter;
3233 
3234  default:
3235  if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
3236  switch (TD->getTagKind()) {
3237  case TTK_Interface: // fall through
3238  case TTK_Struct: return CXCursor_StructDecl;
3239  case TTK_Class: return CXCursor_ClassDecl;
3240  case TTK_Union: return CXCursor_UnionDecl;
3241  case TTK_Enum: return CXCursor_EnumDecl;
3242  }
3243  }
3244  }
3245 
3246  return CXCursor_UnexposedDecl;
3247 }
3248 
3249 static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
3250  bool IncludeUndefined,
3251  bool TargetTypeIsPointer = false) {
3252  typedef CodeCompletionResult Result;
3253 
3254  Results.EnterNewScope();
3255 
3257  MEnd = PP.macro_end();
3258  M != MEnd; ++M) {
3259  auto MD = PP.getMacroDefinition(M->first);
3260  if (IncludeUndefined || MD) {
3261  if (MacroInfo *MI = MD.getMacroInfo())
3262  if (MI->isUsedForHeaderGuard())
3263  continue;
3264 
3265  Results.AddResult(Result(M->first,
3266  getMacroUsagePriority(M->first->getName(),
3267  PP.getLangOpts(),
3268  TargetTypeIsPointer)));
3269  }
3270  }
3271 
3272  Results.ExitScope();
3273 
3274 }
3275 
3276 static void AddPrettyFunctionResults(const LangOptions &LangOpts,
3277  ResultBuilder &Results) {
3278  typedef CodeCompletionResult Result;
3279 
3280  Results.EnterNewScope();
3281 
3282  Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
3283  Results.AddResult(Result("__FUNCTION__", CCP_Constant));
3284  if (LangOpts.C99 || LangOpts.CPlusPlus11)
3285  Results.AddResult(Result("__func__", CCP_Constant));
3286  Results.ExitScope();
3287 }
3288 
3290  CodeCompleteConsumer *CodeCompleter,
3291  CodeCompletionContext Context,
3292  CodeCompletionResult *Results,
3293  unsigned NumResults) {
3294  if (CodeCompleter)
3295  CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
3296 }
3297 
3300  switch (PCC) {
3301  case Sema::PCC_Namespace:
3303 
3304  case Sema::PCC_Class:
3306 
3309 
3312 
3315 
3316  case Sema::PCC_Template:
3318  if (S.CurContext->isFileContext())
3320  if (S.CurContext->isRecord())
3323 
3326 
3327  case Sema::PCC_ForInit:
3328  if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 ||
3329  S.getLangOpts().ObjC1)
3331  else
3333 
3334  case Sema::PCC_Expression:
3335  case Sema::PCC_Condition:
3337 
3338  case Sema::PCC_Statement:
3340 
3341  case Sema::PCC_Type:
3343 
3346 
3349  }
3350 
3351  llvm_unreachable("Invalid ParserCompletionContext!");
3352 }
3353 
3354 /// \brief If we're in a C++ virtual member function, add completion results
3355 /// that invoke the functions we override, since it's common to invoke the
3356 /// overridden function as well as adding new functionality.
3357 ///
3358 /// \param S The semantic analysis object for which we are generating results.
3359 ///
3360 /// \param InContext This context in which the nested-name-specifier preceding
3361 /// the code-completion point
3362 static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
3363  ResultBuilder &Results) {
3364  // Look through blocks.
3365  DeclContext *CurContext = S.CurContext;
3366  while (isa<BlockDecl>(CurContext))
3367  CurContext = CurContext->getParent();
3368 
3369 
3370  CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
3371  if (!Method || !Method->isVirtual())
3372  return;
3373 
3374  // We need to have names for all of the parameters, if we're going to
3375  // generate a forwarding call.
3376  for (auto P : Method->parameters())
3377  if (!P->getDeclName())
3378  return;
3379 
3382  MEnd = Method->end_overridden_methods();
3383  M != MEnd; ++M) {
3384  CodeCompletionBuilder Builder(Results.getAllocator(),
3385  Results.getCodeCompletionTUInfo());
3386  const CXXMethodDecl *Overridden = *M;
3387  if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
3388  continue;
3389 
3390  // If we need a nested-name-specifier, add one now.
3391  if (!InContext) {
3392  NestedNameSpecifier *NNS
3393  = getRequiredQualification(S.Context, CurContext,
3394  Overridden->getDeclContext());
3395  if (NNS) {
3396  std::string Str;
3397  llvm::raw_string_ostream OS(Str);
3398  NNS->print(OS, Policy);
3399  Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
3400  }
3401  } else if (!InContext->Equals(Overridden->getDeclContext()))
3402  continue;
3403 
3404  Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
3405  Overridden->getNameAsString()));
3406  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3407  bool FirstParam = true;
3408  for (auto P : Method->parameters()) {
3409  if (FirstParam)
3410  FirstParam = false;
3411  else
3412  Builder.AddChunk(CodeCompletionString::CK_Comma);
3413 
3414  Builder.AddPlaceholderChunk(
3415  Results.getAllocator().CopyString(P->getIdentifier()->getName()));
3416  }
3417  Builder.AddChunk(CodeCompletionString::CK_RightParen);
3418  Results.AddResult(CodeCompletionResult(Builder.TakeString(),
3422  Overridden));
3423  Results.Ignore(Overridden);
3424  }
3425 }
3426 
3428  ModuleIdPath Path) {
3429  typedef CodeCompletionResult Result;
3430  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3431  CodeCompleter->getCodeCompletionTUInfo(),
3433  Results.EnterNewScope();
3434 
3435  CodeCompletionAllocator &Allocator = Results.getAllocator();
3436  CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
3437  typedef CodeCompletionResult Result;
3438  if (Path.empty()) {
3439  // Enumerate all top-level modules.
3440  SmallVector<Module *, 8> Modules;
3441  PP.getHeaderSearchInfo().collectAllModules(Modules);
3442  for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
3443  Builder.AddTypedTextChunk(
3444  Builder.getAllocator().CopyString(Modules[I]->Name));
3445  Results.AddResult(Result(Builder.TakeString(),
3446  CCP_Declaration,
3448  Modules[I]->isAvailable()
3451  }
3452  } else if (getLangOpts().Modules) {
3453  // Load the named module.
3454  Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
3456  /*IsInclusionDirective=*/false);
3457  // Enumerate submodules.
3458  if (Mod) {
3459  for (Module::submodule_iterator Sub = Mod->submodule_begin(),
3460  SubEnd = Mod->submodule_end();
3461  Sub != SubEnd; ++Sub) {
3462 
3463  Builder.AddTypedTextChunk(
3464  Builder.getAllocator().CopyString((*Sub)->Name));
3465  Results.AddResult(Result(Builder.TakeString(),
3466  CCP_Declaration,
3468  (*Sub)->isAvailable()
3471  }
3472  }
3473  }
3474  Results.ExitScope();
3475  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3476  Results.data(),Results.size());
3477 }
3478 
3480  ParserCompletionContext CompletionContext) {
3481  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3482  CodeCompleter->getCodeCompletionTUInfo(),
3483  mapCodeCompletionContext(*this, CompletionContext));
3484  Results.EnterNewScope();
3485 
3486  // Determine how to filter results, e.g., so that the names of
3487  // values (functions, enumerators, function templates, etc.) are
3488  // only allowed where we can have an expression.
3489  switch (CompletionContext) {
3490  case PCC_Namespace:
3491  case PCC_Class:
3492  case PCC_ObjCInterface:
3493  case PCC_ObjCImplementation:
3494  case PCC_ObjCInstanceVariableList:
3495  case PCC_Template:
3496  case PCC_MemberTemplate:
3497  case PCC_Type:
3498  case PCC_LocalDeclarationSpecifiers:
3499  Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
3500  break;
3501 
3502  case PCC_Statement:
3503  case PCC_ParenthesizedExpression:
3504  case PCC_Expression:
3505  case PCC_ForInit:
3506  case PCC_Condition:
3507  if (WantTypesInContext(CompletionContext, getLangOpts()))
3508  Results.setFilter(&ResultBuilder::IsOrdinaryName);
3509  else
3510  Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
3511 
3512  if (getLangOpts().CPlusPlus)
3513  MaybeAddOverrideCalls(*this, /*InContext=*/nullptr, Results);
3514  break;
3515 
3516  case PCC_RecoveryInFunction:
3517  // Unfiltered
3518  break;
3519  }
3520 
3521  // If we are in a C++ non-static member function, check the qualifiers on
3522  // the member function to filter/prioritize the results list.
3523  if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
3524  if (CurMethod->isInstance())
3525  Results.setObjectTypeQualifiers(
3526  Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
3527 
3528  CodeCompletionDeclConsumer Consumer(Results, CurContext);
3529  LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3530  CodeCompleter->includeGlobals());
3531 
3532  AddOrdinaryNameResults(CompletionContext, S, *this, Results);
3533  Results.ExitScope();
3534 
3535  switch (CompletionContext) {
3536  case PCC_ParenthesizedExpression:
3537  case PCC_Expression:
3538  case PCC_Statement:
3539  case PCC_RecoveryInFunction:
3540  if (S->getFnParent())
3541  AddPrettyFunctionResults(getLangOpts(), Results);
3542  break;
3543 
3544  case PCC_Namespace:
3545  case PCC_Class:
3546  case PCC_ObjCInterface:
3547  case PCC_ObjCImplementation:
3548  case PCC_ObjCInstanceVariableList:
3549  case PCC_Template:
3550  case PCC_MemberTemplate:
3551  case PCC_ForInit:
3552  case PCC_Condition:
3553  case PCC_Type:
3554  case PCC_LocalDeclarationSpecifiers:
3555  break;
3556  }
3557 
3558  if (CodeCompleter->includeMacros())
3559  AddMacroResults(PP, Results, false);
3560 
3561  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3562  Results.data(),Results.size());
3563 }
3564 
3565 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3566  ParsedType Receiver,
3567  ArrayRef<IdentifierInfo *> SelIdents,
3568  bool AtArgumentExpression,
3569  bool IsSuper,
3570  ResultBuilder &Results);
3571 
3573  bool AllowNonIdentifiers,
3574  bool AllowNestedNameSpecifiers) {
3575  typedef CodeCompletionResult Result;
3576  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3577  CodeCompleter->getCodeCompletionTUInfo(),
3578  AllowNestedNameSpecifiers
3581  Results.EnterNewScope();
3582 
3583  // Type qualifiers can come after names.
3584  Results.AddResult(Result("const"));
3585  Results.AddResult(Result("volatile"));
3586  if (getLangOpts().C99)
3587  Results.AddResult(Result("restrict"));
3588 
3589  if (getLangOpts().CPlusPlus) {
3590  if (getLangOpts().CPlusPlus11 &&
3593  Results.AddResult("final");
3594 
3595  if (AllowNonIdentifiers) {
3596  Results.AddResult(Result("operator"));
3597  }
3598 
3599  // Add nested-name-specifiers.
3600  if (AllowNestedNameSpecifiers) {
3601  Results.allowNestedNameSpecifiers();
3602  Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
3603  CodeCompletionDeclConsumer Consumer(Results, CurContext);
3604  LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3605  CodeCompleter->includeGlobals());
3606  Results.setFilter(nullptr);
3607  }
3608  }
3609  Results.ExitScope();
3610 
3611  // If we're in a context where we might have an expression (rather than a
3612  // declaration), and what we've seen so far is an Objective-C type that could
3613  // be a receiver of a class message, this may be a class message send with
3614  // the initial opening bracket '[' missing. Add appropriate completions.
3615  if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
3620  !DS.isTypeAltiVecVector() &&
3621  S &&
3622  (S->getFlags() & Scope::DeclScope) != 0 &&
3625  Scope::AtCatchScope)) == 0) {
3626  ParsedType T = DS.getRepAsType();
3627  if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
3628  AddClassMessageCompletions(*this, S, T, None, false, false, Results);
3629  }
3630 
3631  // Note that we intentionally suppress macro results here, since we do not
3632  // encourage using macros to produce the names of entities.
3633 
3634  HandleCodeCompleteResults(this, CodeCompleter,
3635  Results.getCompletionContext(),
3636  Results.data(), Results.size());
3637 }
3638 
3641  : PreferredType(PreferredType), IntegralConstantExpression(false),
3642  ObjCCollection(false) { }
3643 
3648 };
3649 
3650 /// \brief Perform code-completion in an expression context when we know what
3651 /// type we're looking for.
3653  const CodeCompleteExpressionData &Data) {
3654  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3655  CodeCompleter->getCodeCompletionTUInfo(),
3657  if (Data.ObjCCollection)
3658  Results.setFilter(&ResultBuilder::IsObjCCollection);
3659  else if (Data.IntegralConstantExpression)
3660  Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
3661  else if (WantTypesInContext(PCC_Expression, getLangOpts()))
3662  Results.setFilter(&ResultBuilder::IsOrdinaryName);
3663  else
3664  Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
3665 
3666  if (!Data.PreferredType.isNull())
3667  Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3668 
3669  // Ignore any declarations that we were told that we don't care about.
3670  for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3671  Results.Ignore(Data.IgnoreDecls[I]);
3672 
3673  CodeCompletionDeclConsumer Consumer(Results, CurContext);
3674  LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3675  CodeCompleter->includeGlobals());
3676 
3677  Results.EnterNewScope();
3678  AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
3679  Results.ExitScope();
3680 
3681  bool PreferredTypeIsPointer = false;
3682  if (!Data.PreferredType.isNull())
3683  PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3685  || Data.PreferredType->isBlockPointerType();
3686 
3687  if (S->getFnParent() &&
3688  !Data.ObjCCollection &&
3690  AddPrettyFunctionResults(getLangOpts(), Results);
3691 
3692  if (CodeCompleter->includeMacros())
3693  AddMacroResults(PP, Results, false, PreferredTypeIsPointer);
3694  HandleCodeCompleteResults(this, CodeCompleter,
3696  Data.PreferredType),
3697  Results.data(),Results.size());
3698 }
3699 
3701  if (E.isInvalid())
3702  CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
3703  else if (getLangOpts().ObjC1)
3704  CodeCompleteObjCInstanceMessage(S, E.get(), None, false);
3705 }
3706 
3707 /// \brief The set of properties that have already been added, referenced by
3708 /// property name.
3709 typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3710 
3711 /// \brief Retrieve the container definition, if any?
3713  if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
3714  if (Interface->hasDefinition())
3715  return Interface->getDefinition();
3716 
3717  return Interface;
3718  }
3719 
3720  if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3721  if (Protocol->hasDefinition())
3722  return Protocol->getDefinition();
3723 
3724  return Protocol;
3725  }
3726  return Container;
3727 }
3728 
3729 /// \brief Adds a block invocation code completion result for the given block
3730 /// declaration \p BD.
3731 static void AddObjCBlockCall(ASTContext &Context, const PrintingPolicy &Policy,
3732  CodeCompletionBuilder &Builder,
3733  const NamedDecl *BD,
3734  const FunctionTypeLoc &BlockLoc,
3735  const FunctionProtoTypeLoc &BlockProtoLoc) {
3736  Builder.AddResultTypeChunk(
3737  GetCompletionTypeString(BlockLoc.getReturnLoc().getType(), Context,
3738  Policy, Builder.getAllocator()));
3739 
3740  AddTypedNameChunk(Context, Policy, BD, Builder);
3742 
3743  if (BlockProtoLoc && BlockProtoLoc.getTypePtr()->isVariadic()) {
3744  Builder.AddPlaceholderChunk("...");
3745  } else {
3746  for (unsigned I = 0, N = BlockLoc.getNumParams(); I != N; ++I) {
3747  if (I)
3749 
3750  // Format the placeholder string.
3751  std::string PlaceholderStr =
3752  FormatFunctionParameter(Policy, BlockLoc.getParam(I));
3753 
3754  if (I == N - 1 && BlockProtoLoc &&
3755  BlockProtoLoc.getTypePtr()->isVariadic())
3756  PlaceholderStr += ", ...";
3757 
3758  // Add the placeholder string.
3759  Builder.AddPlaceholderChunk(
3760  Builder.getAllocator().CopyString(PlaceholderStr));
3761  }
3762  }
3763 
3765 }
3766 
3767 static void AddObjCProperties(
3768  const CodeCompletionContext &CCContext, ObjCContainerDecl *Container,
3769  bool AllowCategories, bool AllowNullaryMethods, DeclContext *CurContext,
3770  AddedPropertiesSet &AddedProperties, ResultBuilder &Results,
3771  bool IsBaseExprStatement = false, bool IsClassProperty = false) {
3772  typedef CodeCompletionResult Result;
3773 
3774  // Retrieve the definition.
3775  Container = getContainerDef(Container);
3776 
3777  // Add properties in this container.
3778  const auto AddProperty = [&](const ObjCPropertyDecl *P) {
3779  if (!AddedProperties.insert(P->getIdentifier()).second)
3780  return;
3781 
3782  // FIXME: Provide block invocation completion for non-statement
3783  // expressions.
3784  if (!P->getType().getTypePtr()->isBlockPointerType() ||
3785  !IsBaseExprStatement) {
3786  Results.MaybeAddResult(Result(P, Results.getBasePriority(P), nullptr),
3787  CurContext);
3788  return;
3789  }
3790 
3791  // Block setter and invocation completion is provided only when we are able
3792  // to find the FunctionProtoTypeLoc with parameter names for the block.
3793  FunctionTypeLoc BlockLoc;
3794  FunctionProtoTypeLoc BlockProtoLoc;
3795  findTypeLocationForBlockDecl(P->getTypeSourceInfo(), BlockLoc,
3796  BlockProtoLoc);
3797  if (!BlockLoc) {
3798  Results.MaybeAddResult(Result(P, Results.getBasePriority(P), nullptr),
3799  CurContext);
3800  return;
3801  }
3802 
3803  // The default completion result for block properties should be the block
3804  // invocation completion when the base expression is a statement.
3805  CodeCompletionBuilder Builder(Results.getAllocator(),
3806  Results.getCodeCompletionTUInfo());
3807  AddObjCBlockCall(Container->getASTContext(),
3808  getCompletionPrintingPolicy(Results.getSema()), Builder, P,
3809  BlockLoc, BlockProtoLoc);
3810  Results.MaybeAddResult(
3811  Result(Builder.TakeString(), P, Results.getBasePriority(P)),
3812  CurContext);
3813 
3814  // Provide additional block setter completion iff the base expression is a
3815  // statement and the block property is mutable.
3816  if (!P->isReadOnly()) {
3817  CodeCompletionBuilder Builder(Results.getAllocator(),
3818  Results.getCodeCompletionTUInfo());
3819  AddResultTypeChunk(Container->getASTContext(),
3820  getCompletionPrintingPolicy(Results.getSema()), P,
3821  CCContext.getBaseType(), Builder);
3822  Builder.AddTypedTextChunk(
3823  Results.getAllocator().CopyString(P->getName()));
3824  Builder.AddChunk(CodeCompletionString::CK_Equal);
3825 
3826  std::string PlaceholderStr = formatBlockPlaceholder(
3827  getCompletionPrintingPolicy(Results.getSema()), P, BlockLoc,
3828  BlockProtoLoc, /*SuppressBlockName=*/true);
3829  // Add the placeholder string.
3830  Builder.AddPlaceholderChunk(
3831  Builder.getAllocator().CopyString(PlaceholderStr));
3832 
3833  // When completing blocks properties that return void the default
3834  // property completion result should show up before the setter,
3835  // otherwise the setter completion should show up before the default
3836  // property completion, as we normally want to use the result of the
3837  // call.
3838  Results.MaybeAddResult(
3839  Result(Builder.TakeString(), P,
3840  Results.getBasePriority(P) +
3841  (BlockLoc.getTypePtr()->getReturnType()->isVoidType()
3844  CurContext);
3845  }
3846  };
3847 
3848  if (IsClassProperty) {
3849  for (const auto *P : Container->class_properties())
3850  AddProperty(P);
3851  } else {
3852  for (const auto *P : Container->instance_properties())
3853  AddProperty(P);
3854  }
3855 
3856  // Add nullary methods or implicit class properties
3857  if (AllowNullaryMethods) {
3858  ASTContext &Context = Container->getASTContext();
3859  PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
3860  // Adds a method result
3861  const auto AddMethod = [&](const ObjCMethodDecl *M) {
3862  IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0);
3863  if (!Name)
3864  return;
3865  if (!AddedProperties.insert(Name).second)
3866  return;
3867  CodeCompletionBuilder Builder(Results.getAllocator(),
3868  Results.getCodeCompletionTUInfo());
3869  AddResultTypeChunk(Context, Policy, M, CCContext.getBaseType(), Builder);
3870  Builder.AddTypedTextChunk(
3871  Results.getAllocator().CopyString(Name->getName()));
3872  Results.MaybeAddResult(
3873  Result(Builder.TakeString(), M,
3875  CurContext);
3876  };
3877 
3878  if (IsClassProperty) {
3879  for (const auto *M : Container->methods()) {
3880  // Gather the class method that can be used as implicit property
3881  // getters. Methods with arguments or methods that return void aren't
3882  // added to the results as they can't be used as a getter.
3883  if (!M->getSelector().isUnarySelector() ||
3884  M->getReturnType()->isVoidType() || M->isInstanceMethod())
3885  continue;
3886  AddMethod(M);
3887  }
3888  } else {
3889  for (auto *M : Container->methods()) {
3890  if (M->getSelector().isUnarySelector())
3891  AddMethod(M);
3892  }
3893  }
3894  }
3895 
3896  // Add properties in referenced protocols.
3897  if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3898  for (auto *P : Protocol->protocols())
3899  AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
3900  CurContext, AddedProperties, Results,
3901  IsBaseExprStatement, IsClassProperty);
3902  } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
3903  if (AllowCategories) {
3904  // Look through categories.
3905  for (auto *Cat : IFace->known_categories())
3906  AddObjCProperties(CCContext, Cat, AllowCategories, AllowNullaryMethods,
3907  CurContext, AddedProperties, Results,
3908  IsBaseExprStatement, IsClassProperty);
3909  }
3910 
3911  // Look through protocols.
3912  for (auto *I : IFace->all_referenced_protocols())
3913  AddObjCProperties(CCContext, I, AllowCategories, AllowNullaryMethods,
3914  CurContext, AddedProperties, Results,
3915  IsBaseExprStatement, IsClassProperty);
3916 
3917  // Look in the superclass.
3918  if (IFace->getSuperClass())
3919  AddObjCProperties(CCContext, IFace->getSuperClass(), AllowCategories,
3920  AllowNullaryMethods, CurContext, AddedProperties,
3921  Results, IsBaseExprStatement, IsClassProperty);
3922  } else if (const ObjCCategoryDecl *Category
3923  = dyn_cast<ObjCCategoryDecl>(Container)) {
3924  // Look through protocols.
3925  for (auto *P : Category->protocols())
3926  AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
3927  CurContext, AddedProperties, Results,
3928  IsBaseExprStatement, IsClassProperty);
3929  }
3930 }
3931 
3933  ResultBuilder &Results, Scope *S,
3934  QualType BaseType,
3935  RecordDecl *RD) {
3936  // Indicate that we are performing a member access, and the cv-qualifiers
3937  // for the base object type.
3938  Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3939 
3940  // Access to a C/C++ class, struct, or union.
3941  Results.allowNestedNameSpecifiers();
3942  CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext);
3943  SemaRef.LookupVisibleDecls(RD, Sema::LookupMemberName, Consumer,
3944  SemaRef.CodeCompleter->includeGlobals(),
3945  /*IncludeDependentBases=*/true);
3946 
3947  if (SemaRef.getLangOpts().CPlusPlus) {
3948  if (!Results.empty()) {
3949  // The "template" keyword can follow "->" or "." in the grammar.
3950  // However, we only want to suggest the template keyword if something
3951  // is dependent.
3952  bool IsDependent = BaseType->isDependentType();
3953  if (!IsDependent) {
3954  for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3955  if (DeclContext *Ctx = DepScope->getEntity()) {
3956  IsDependent = Ctx->isDependentContext();
3957  break;
3958  }
3959  }
3960 
3961  if (IsDependent)
3962  Results.AddResult(CodeCompletionResult("template"));
3963  }
3964  }
3965 }
3966 
3968  SourceLocation OpLoc, bool IsArrow,
3969  bool IsBaseExprStatement) {
3970  if (!Base || !CodeCompleter)
3971  return;
3972 
3973  ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
3974  if (ConvertedBase.isInvalid())
3975  return;
3976  Base = ConvertedBase.get();
3977 
3978  QualType BaseType = Base->getType();
3979 
3980  if (IsArrow) {
3981  if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3982  BaseType = Ptr->getPointeeType();
3983  else if (BaseType->isObjCObjectPointerType())
3984  /*Do nothing*/ ;
3985  else
3986  return;
3987  }
3988 
3989  enum CodeCompletionContext::Kind contextKind;
3990 
3991  if (IsArrow) {
3993  }
3994  else {
3995  if (BaseType->isObjCObjectPointerType() ||
3996  BaseType->isObjCObjectOrInterfaceType()) {
3998  }
3999  else {
4001  }
4002  }
4003 
4004  CodeCompletionContext CCContext(contextKind, BaseType);
4005  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4006  CodeCompleter->getCodeCompletionTUInfo(),
4007  CCContext,
4008  &ResultBuilder::IsMember);
4009  Results.EnterNewScope();
4010  if (const RecordType *Record = BaseType->getAs<RecordType>()) {
4011  AddRecordMembersCompletionResults(*this, Results, S, BaseType,
4012  Record->getDecl());
4013  } else if (const auto *TST = BaseType->getAs<TemplateSpecializationType>()) {
4014  TemplateName TN = TST->getTemplateName();
4015  if (const auto *TD =
4016  dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl())) {
4017  CXXRecordDecl *RD = TD->getTemplatedDecl();
4018  AddRecordMembersCompletionResults(*this, Results, S, BaseType, RD);
4019  }
4020  } else if (const auto *ICNT = BaseType->getAs<InjectedClassNameType>()) {
4021  if (auto *RD = ICNT->getDecl())
4022  AddRecordMembersCompletionResults(*this, Results, S, BaseType, RD);
4023  } else if (!IsArrow && BaseType->isObjCObjectPointerType()) {
4024  // Objective-C property reference.
4025  AddedPropertiesSet AddedProperties;
4026 
4027  if (const ObjCObjectPointerType *ObjCPtr =
4028  BaseType->getAsObjCInterfacePointerType()) {
4029  // Add property results based on our interface.
4030  assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
4031  AddObjCProperties(CCContext, ObjCPtr->getInterfaceDecl(), true,
4032  /*AllowNullaryMethods=*/true, CurContext,
4033  AddedProperties, Results, IsBaseExprStatement);
4034  }
4035 
4036  // Add properties from the protocols in a qualified interface.
4037  for (auto *I : BaseType->getAs<ObjCObjectPointerType>()->quals())
4038  AddObjCProperties(CCContext, I, true, /*AllowNullaryMethods=*/true,
4039  CurContext, AddedProperties, Results,
4040  IsBaseExprStatement);
4041  } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
4042  (!IsArrow && BaseType->isObjCObjectType())) {
4043  // Objective-C instance variable access.
4044  ObjCInterfaceDecl *Class = nullptr;
4045  if (const ObjCObjectPointerType *ObjCPtr
4046  = BaseType->getAs<ObjCObjectPointerType>())
4047  Class = ObjCPtr->getInterfaceDecl();
4048  else
4049  Class = BaseType->getAs<ObjCObjectType>()->getInterface();
4050 
4051  // Add all ivars from this class and its superclasses.
4052  if (Class) {
4053  CodeCompletionDeclConsumer Consumer(Results, CurContext);
4054  Results.setFilter(&ResultBuilder::IsObjCIvar);
4055  LookupVisibleDecls(Class, LookupMemberName, Consumer,
4056  CodeCompleter->includeGlobals());
4057  }
4058  }
4059 
4060  // FIXME: How do we cope with isa?
4061 
4062  Results.ExitScope();
4063 
4064  // Hand off the results found for code completion.
4065  HandleCodeCompleteResults(this, CodeCompleter,
4066  Results.getCompletionContext(),
4067  Results.data(),Results.size());
4068 }
4069 
4071  IdentifierInfo &ClassName,
4072  SourceLocation ClassNameLoc,
4073  bool IsBaseExprStatement) {
4074  IdentifierInfo *ClassNamePtr = &ClassName;
4075  ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(ClassNamePtr, ClassNameLoc);
4076  if (!IFace)
4077  return;
4078  CodeCompletionContext CCContext(
4080  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4081  CodeCompleter->getCodeCompletionTUInfo(), CCContext,
4082  &ResultBuilder::IsMember);
4083  Results.EnterNewScope();
4084  AddedPropertiesSet AddedProperties;
4085  AddObjCProperties(CCContext, IFace, true,
4086  /*AllowNullaryMethods=*/true, CurContext, AddedProperties,
4087  Results, IsBaseExprStatement,
4088  /*IsClassProperty=*/true);
4089  Results.ExitScope();
4090  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4091  Results.data(), Results.size());
4092 }
4093 
4094 void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
4095  if (!CodeCompleter)
4096  return;
4097 
4098  ResultBuilder::LookupFilter Filter = nullptr;
4101  switch ((DeclSpec::TST)TagSpec) {
4102  case DeclSpec::TST_enum:
4103  Filter = &ResultBuilder::IsEnum;
4104  ContextKind = CodeCompletionContext::CCC_EnumTag;
4105  break;
4106 
4107  case DeclSpec::TST_union:
4108  Filter = &ResultBuilder::IsUnion;
4110  break;
4111 
4112  case DeclSpec::TST_struct:
4113  case DeclSpec::TST_class:
4115  Filter = &ResultBuilder::IsClassOrStruct;
4117  break;
4118 
4119  default:
4120  llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
4121  }
4122 
4123  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4124  CodeCompleter->getCodeCompletionTUInfo(), ContextKind);
4125  CodeCompletionDeclConsumer Consumer(Results, CurContext);
4126 
4127  // First pass: look for tags.
4128  Results.setFilter(Filter);
4129  LookupVisibleDecls(S, LookupTagName, Consumer,
4130  CodeCompleter->includeGlobals());
4131 
4132  if (CodeCompleter->includeGlobals()) {
4133  // Second pass: look for nested name specifiers.
4134  Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
4135  LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
4136  }
4137 
4138  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4139  Results.data(),Results.size());
4140 }
4141 
4142 static void AddTypeQualifierResults(DeclSpec &DS, ResultBuilder &Results,
4143  const LangOptions &LangOpts) {
4144  if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
4145  Results.AddResult("const");
4147  Results.AddResult("volatile");
4148  if (LangOpts.C99 && !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
4149  Results.AddResult("restrict");
4150  if (LangOpts.C11 && !(DS.getTypeQualifiers() & DeclSpec::TQ_atomic))
4151  Results.AddResult("_Atomic");
4152  if (LangOpts.MSVCCompat && !(DS.getTypeQualifiers() & DeclSpec::TQ_unaligned))
4153  Results.AddResult("__unaligned");
4154 }
4155 
4157  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4158  CodeCompleter->getCodeCompletionTUInfo(),
4160  Results.EnterNewScope();
4161  AddTypeQualifierResults(DS, Results, LangOpts);
4162  Results.ExitScope();
4163  HandleCodeCompleteResults(this, CodeCompleter,
4164  Results.getCompletionContext(),
4165  Results.data(), Results.size());
4166 }
4167 
4169  const VirtSpecifiers *VS) {
4170  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4171  CodeCompleter->getCodeCompletionTUInfo(),
4173  Results.EnterNewScope();
4174  AddTypeQualifierResults(DS, Results, LangOpts);
4175  if (LangOpts.CPlusPlus11) {
4176  Results.AddResult("noexcept");
4177  if (D.getContext() == Declarator::MemberContext && !D.isCtorOrDtor() &&
4178  !D.isStaticMember()) {
4179  if (!VS || !VS->isFinalSpecified())
4180  Results.AddResult("final");
4181  if (!VS || !VS->isOverrideSpecified())
4182  Results.AddResult("override");
4183  }
4184  }
4185  Results.ExitScope();
4186  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4187  Results.data(), Results.size());
4188 }
4189 
4191  CodeCompleteExpression(S, QualType(getASTContext().getSizeType()));
4192 }
4193 
4195  if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
4196  return;
4197 
4198  SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
4199  QualType type = Switch->getCond()->IgnoreImplicit()->getType();
4200  if (!type->isEnumeralType()) {
4201  CodeCompleteExpressionData Data(type);
4202  Data.IntegralConstantExpression = true;
4203  CodeCompleteExpression(S, Data);
4204  return;
4205  }
4206 
4207  // Code-complete the cases of a switch statement over an enumeration type
4208  // by providing the list of
4209  EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
4210  if (EnumDecl *Def = Enum->getDefinition())
4211  Enum = Def;
4212 
4213  // Determine which enumerators we have already seen in the switch statement.
4214  // FIXME: Ideally, we would also be able to look *past* the code-completion
4215  // token, in case we are code-completing in the middle of the switch and not
4216  // at the end. However, we aren't able to do so at the moment.
4217  llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
4218  NestedNameSpecifier *Qualifier = nullptr;
4219  for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
4220  SC = SC->getNextSwitchCase()) {
4221  CaseStmt *Case = dyn_cast<CaseStmt>(SC);
4222  if (!Case)
4223  continue;
4224 
4225  Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
4226  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
4227  if (EnumConstantDecl *Enumerator
4228  = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
4229  // We look into the AST of the case statement to determine which
4230  // enumerator was named. Alternatively, we could compute the value of
4231  // the integral constant expression, then compare it against the
4232  // values of each enumerator. However, value-based approach would not
4233  // work as well with C++ templates where enumerators declared within a
4234  // template are type- and value-dependent.
4235  EnumeratorsSeen.insert(Enumerator);
4236 
4237  // If this is a qualified-id, keep track of the nested-name-specifier
4238  // so that we can reproduce it as part of code completion, e.g.,
4239  //
4240  // switch (TagD.getKind()) {
4241  // case TagDecl::TK_enum:
4242  // break;
4243  // case XXX
4244  //
4245  // At the XXX, our completions are TagDecl::TK_union,
4246  // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
4247  // TK_struct, and TK_class.
4248  Qualifier = DRE->getQualifier();
4249  }
4250  }
4251 
4252  if (getLangOpts().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
4253  // If there are no prior enumerators in C++, check whether we have to
4254  // qualify the names of the enumerators that we suggest, because they
4255  // may not be visible in this scope.
4256  Qualifier = getRequiredQualification(Context, CurContext, Enum);
4257  }
4258 
4259  // Add any enumerators that have not yet been mentioned.
4260  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4261  CodeCompleter->getCodeCompletionTUInfo(),
4263  Results.EnterNewScope();
4264  for (auto *E : Enum->enumerators()) {
4265  if (EnumeratorsSeen.count(E))
4266  continue;
4267 
4268  CodeCompletionResult R(E, CCP_EnumInCase, Qualifier);
4269  Results.AddResult(R, CurContext, nullptr, false);
4270  }
4271  Results.ExitScope();
4272 
4273  //We need to make sure we're setting the right context,
4274  //so only say we include macros if the code completer says we do
4276  if (CodeCompleter->includeMacros()) {
4277  AddMacroResults(PP, Results, false);
4279  }
4280 
4281  HandleCodeCompleteResults(this, CodeCompleter,
4282  kind,
4283  Results.data(),Results.size());
4284 }
4285 
4286 static bool anyNullArguments(ArrayRef<Expr *> Args) {
4287  if (Args.size() && !Args.data())
4288  return true;
4289 
4290  for (unsigned I = 0; I != Args.size(); ++I)
4291  if (!Args[I])
4292  return true;
4293 
4294  return false;
4295 }
4296 
4298 
4299 static void mergeCandidatesWithResults(Sema &SemaRef,
4301  OverloadCandidateSet &CandidateSet,
4302  SourceLocation Loc) {
4303  if (!CandidateSet.empty()) {
4304  // Sort the overload candidate set by placing the best overloads first.
4305  std::stable_sort(
4306  CandidateSet.begin(), CandidateSet.end(),
4307  [&](const OverloadCandidate &X, const OverloadCandidate &Y) {
4308  return isBetterOverloadCandidate(SemaRef, X, Y, Loc,
4309  CandidateSet.getKind());
4310  });
4311 
4312  // Add the remaining viable overload candidates as code-completion results.
4313  for (auto &Candidate : CandidateSet) {
4314  if (Candidate.Function && Candidate.Function->isDeleted())
4315  continue;
4316  if (Candidate.Viable)
4317  Results.push_back(ResultCandidate(Candidate.Function));
4318  }
4319  }
4320 }
4321 
4322 /// \brief Get the type of the Nth parameter from a given set of overload
4323 /// candidates.
4324 static QualType getParamType(Sema &SemaRef,
4325  ArrayRef<ResultCandidate> Candidates,
4326  unsigned N) {
4327 
4328  // Given the overloads 'Candidates' for a function call matching all arguments
4329  // up to N, return the type of the Nth parameter if it is the same for all
4330  // overload candidates.
4331  QualType ParamType;
4332  for (auto &Candidate : Candidates) {
4333  if (auto FType = Candidate.getFunctionType())
4334  if (auto Proto = dyn_cast<FunctionProtoType>(FType))
4335  if (N < Proto->getNumParams()) {
4336  if (ParamType.isNull())
4337  ParamType = Proto->getParamType(N);
4338  else if (!SemaRef.Context.hasSameUnqualifiedType(
4339  ParamType.getNonReferenceType(),
4340  Proto->getParamType(N).getNonReferenceType()))
4341  // Otherwise return a default-constructed QualType.
4342  return QualType();
4343  }
4344  }
4345 
4346  return ParamType;
4347 }
4348 
4349 static void CodeCompleteOverloadResults(Sema &SemaRef, Scope *S,
4351  unsigned CurrentArg,
4352  bool CompleteExpressionWithCurrentArg = true) {
4353  QualType ParamType;
4354  if (CompleteExpressionWithCurrentArg)
4355  ParamType = getParamType(SemaRef, Candidates, CurrentArg);
4356 
4357  if (ParamType.isNull())
4359  else
4360  SemaRef.CodeCompleteExpression(S, ParamType);
4361 
4362  if (!Candidates.empty())
4363  SemaRef.CodeCompleter->ProcessOverloadCandidates(SemaRef, CurrentArg,
4364  Candidates.data(),
4365  Candidates.size());
4366 }
4367 
4369  if (!CodeCompleter)
4370  return;
4371 
4372  // When we're code-completing for a call, we fall back to ordinary
4373  // name code-completion whenever we can't produce specific
4374  // results. We may want to revisit this strategy in the future,
4375  // e.g., by merging the two kinds of results.
4376 
4377  // FIXME: Provide support for variadic template functions.
4378 
4379  // Ignore type-dependent call expressions entirely.
4380  if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args) ||
4382  CodeCompleteOrdinaryName(S, PCC_Expression);
4383  return;
4384  }
4385 
4386  // Build an overload candidate set based on the functions we find.
4387  SourceLocation Loc = Fn->getExprLoc();
4389 
4391 
4392  Expr *NakedFn = Fn->IgnoreParenCasts();
4393  if (auto ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
4394  AddOverloadedCallCandidates(ULE, Args, CandidateSet,
4395  /*PartialOverloading=*/true);
4396  else if (auto UME = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4397  TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
4398  if (UME->hasExplicitTemplateArgs()) {
4399  UME->copyTemplateArgumentsInto(TemplateArgsBuffer);
4400  TemplateArgs = &TemplateArgsBuffer;
4401  }
4402 
4403  // Add the base as first argument (use a nullptr if the base is implicit).
4404  SmallVector<Expr *, 12> ArgExprs(
4405  1, UME->isImplicitAccess() ? nullptr : UME->getBase());
4406  ArgExprs.append(Args.begin(), Args.end());
4407  UnresolvedSet<8> Decls;
4408  Decls.append(UME->decls_begin(), UME->decls_end());
4409  const bool FirstArgumentIsBase = !UME->isImplicitAccess() && UME->getBase();
4410  AddFunctionCandidates(Decls, ArgExprs, CandidateSet, TemplateArgs,
4411  /*SuppressUsedConversions=*/false,
4412  /*PartialOverloading=*/true,
4413  FirstArgumentIsBase);
4414  } else {
4415  FunctionDecl *FD = nullptr;
4416  if (auto MCE = dyn_cast<MemberExpr>(NakedFn))
4417  FD = dyn_cast<FunctionDecl>(MCE->getMemberDecl());
4418  else if (auto DRE = dyn_cast<DeclRefExpr>(NakedFn))
4419  FD = dyn_cast<FunctionDecl>(DRE->getDecl());
4420  if (FD) { // We check whether it's a resolved function declaration.
4421  if (!getLangOpts().CPlusPlus ||
4422  !FD->getType()->getAs<FunctionProtoType>())
4423  Results.push_back(ResultCandidate(FD));
4424  else
4425  AddOverloadCandidate(FD, DeclAccessPair::make(FD, FD->getAccess()),
4426  Args, CandidateSet,
4427  /*SuppressUsedConversions=*/false,
4428  /*PartialOverloading=*/true);
4429 
4430  } else if (auto DC = NakedFn->getType()->getAsCXXRecordDecl()) {
4431  // If expression's type is CXXRecordDecl, it may overload the function
4432  // call operator, so we check if it does and add them as candidates.
4433  // A complete type is needed to lookup for member function call operators.
4434  if (isCompleteType(Loc, NakedFn->getType())) {
4435  DeclarationName OpName = Context.DeclarationNames
4436  .getCXXOperatorName(OO_Call);
4437  LookupResult R(*this, OpName, Loc, LookupOrdinaryName);
4438  LookupQualifiedName(R, DC);
4439  R.suppressDiagnostics();
4440  SmallVector<Expr *, 12> ArgExprs(1, NakedFn);
4441  ArgExprs.append(Args.begin(), Args.end());
4442  AddFunctionCandidates(R.asUnresolvedSet(), ArgExprs, CandidateSet,
4443  /*ExplicitArgs=*/nullptr,
4444  /*SuppressUsedConversions=*/false,
4445  /*PartialOverloading=*/true);
4446  }
4447  } else {
4448  // Lastly we check whether expression's type is function pointer or
4449  // function.
4450  QualType T = NakedFn->getType();
4451  if (!T->getPointeeType().isNull())
4452  T = T->getPointeeType();
4453 
4454  if (auto FP = T->getAs<FunctionProtoType>()) {
4455  if (!TooManyArguments(FP->getNumParams(), Args.size(),
4456  /*PartialOverloading=*/true) ||
4457  FP->isVariadic())
4458  Results.push_back(ResultCandidate(FP));
4459  } else if (auto FT = T->getAs<FunctionType>())
4460  // No prototype and declaration, it may be a K & R style function.
4461  Results.push_back(ResultCandidate(FT));
4462  }
4463  }
4464 
4465  mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
4466  CodeCompleteOverloadResults(*this, S, Results, Args.size(),
4467  !CandidateSet.empty());
4468 }
4469 
4471  ArrayRef<Expr *> Args) {
4472  if (!CodeCompleter)
4473  return;
4474 
4475  // A complete type is needed to lookup for constructors.
4476  if (!isCompleteType(Loc, Type))
4477  return;
4478 
4479  CXXRecordDecl *RD = Type->getAsCXXRecordDecl();
4480  if (!RD) {
4481  CodeCompleteExpression(S, Type);
4482  return;
4483  }
4484 
4485  // FIXME: Provide support for member initializers.
4486  // FIXME: Provide support for variadic template constructors.
4487 
4489 
4490  for (auto C : LookupConstructors(RD)) {
4491  if (auto FD = dyn_cast<FunctionDecl>(C)) {
4492  AddOverloadCandidate(FD, DeclAccessPair::make(FD, C->getAccess()),
4493  Args, CandidateSet,
4494  /*SuppressUsedConversions=*/false,
4495  /*PartialOverloading=*/true);
4496  } else if (auto FTD = dyn_cast<FunctionTemplateDecl>(C)) {
4497  AddTemplateOverloadCandidate(FTD,
4498  DeclAccessPair::make(FTD, C->getAccess()),
4499  /*ExplicitTemplateArgs=*/nullptr,
4500  Args, CandidateSet,
4501  /*SuppressUsedConversions=*/false,
4502  /*PartialOverloading=*/true);
4503  }
4504  }
4505 
4507  mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
4508  CodeCompleteOverloadResults(*this, S, Results, Args.size());
4509 }
4510 
4512  ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
4513  if (!VD) {
4514  CodeCompleteOrdinaryName(S, PCC_Expression);
4515  return;
4516  }
4517 
4518  CodeCompleteExpression(S, VD->getType());
4519 }
4520 
4522  QualType ResultType;
4523  if (isa<BlockDecl>(CurContext)) {
4524  if (BlockScopeInfo *BSI = getCurBlock())
4525  ResultType = BSI->ReturnType;
4526  } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
4527  ResultType = Function->getReturnType();
4528  else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
4529  ResultType = Method->getReturnType();
4530 
4531  if (ResultType.isNull())
4532  CodeCompleteOrdinaryName(S, PCC_Expression);
4533  else
4534  CodeCompleteExpression(S, ResultType);
4535 }
4536 
4538  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4539  CodeCompleter->getCodeCompletionTUInfo(),
4540  mapCodeCompletionContext(*this, PCC_Statement));
4541  Results.setFilter(&ResultBuilder::IsOrdinaryName);
4542  Results.EnterNewScope();
4543 
4544  CodeCompletionDeclConsumer Consumer(Results, CurContext);
4545  LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4546  CodeCompleter->includeGlobals());
4547 
4548  AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
4549 
4550  // "else" block
4551  CodeCompletionBuilder Builder(Results.getAllocator(),
4552  Results.getCodeCompletionTUInfo());
4553  Builder.AddTypedTextChunk("else");
4554  if (Results.includeCodePatterns()) {
4555  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4556  Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4557  Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4558  Builder.AddPlaceholderChunk("statements");
4559  Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4560  Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4561  }
4562  Results.AddResult(Builder.TakeString());
4563 
4564  // "else if" block
4565  Builder.AddTypedTextChunk("else");
4566  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4567  Builder.AddTextChunk("if");
4568  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4569  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4570  if (getLangOpts().CPlusPlus)
4571  Builder.AddPlaceholderChunk("condition");
4572  else
4573  Builder.AddPlaceholderChunk("expression");
4574  Builder.AddChunk(CodeCompletionString::CK_RightParen);
4575  if (Results.includeCodePatterns()) {
4576  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4577  Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4578  Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4579  Builder.AddPlaceholderChunk("statements");
4580  Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4581  Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4582  }
4583  Results.AddResult(Builder.TakeString());
4584 
4585  Results.ExitScope();
4586 
4587  if (S->getFnParent())
4588  AddPrettyFunctionResults(getLangOpts(), Results);
4589 
4590  if (CodeCompleter->includeMacros())
4591  AddMacroResults(PP, Results, false);
4592 
4593  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4594  Results.data(),Results.size());
4595 }
4596 
4598  if (LHS)
4599  CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
4600  else
4601  CodeCompleteOrdinaryName(S, PCC_Expression);
4602 }
4603 
4605  bool EnteringContext) {
4606  if (SS.isEmpty() || !CodeCompleter)
4607  return;
4608 
4609  // We want to keep the scope specifier even if it's invalid (e.g. the scope
4610  // "a::b::" is not corresponding to any context/namespace in the AST), since
4611  // it can be useful for global code completion which have information about
4612  // contexts/symbols that are not in the AST.
4613  if (SS.isInvalid()) {
4615  CC.setCXXScopeSpecifier(SS);
4616  HandleCodeCompleteResults(this, CodeCompleter, CC, nullptr, 0);
4617  return;
4618  }
4619  // Always pretend to enter a context to ensure that a dependent type
4620  // resolves to a dependent record.
4621  DeclContext *Ctx = computeDeclContext(SS, /*EnteringContext=*/true);
4622  if (!Ctx)
4623  return;
4624 
4625  // Try to instantiate any non-dependent declaration contexts before
4626  // we look in them.
4627  if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
4628  return;
4629 
4630  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4631  CodeCompleter->getCodeCompletionTUInfo(),
4633  Results.EnterNewScope();
4634 
4635  // The "template" keyword can follow "::" in the grammar, but only
4636  // put it into the grammar if the nested-name-specifier is dependent.
4637  NestedNameSpecifier *NNS = SS.getScopeRep();
4638  if (!Results.empty() && NNS->isDependent())
4639  Results.AddResult("template");
4640 
4641  // Add calls to overridden virtual functions, if there are any.
4642  //
4643  // FIXME: This isn't wonderful, because we don't know whether we're actually
4644  // in a context that permits expressions. This is a general issue with
4645  // qualified-id completions.
4646  if (!EnteringContext)
4647  MaybeAddOverrideCalls(*this, Ctx, Results);
4648  Results.ExitScope();
4649 
4650  if (CodeCompleter->includeNamespaceLevelDecls() ||
4651  (!Ctx->isNamespace() && !Ctx->isTranslationUnit())) {
4652  CodeCompletionDeclConsumer Consumer(Results, CurContext);
4653  LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer,
4654  /*IncludeGlobalScope=*/true,
4655  /*IncludeDependentBases=*/true);
4656  }
4657 
4658  auto CC = Results.getCompletionContext();
4659  CC.setCXXScopeSpecifier(SS);
4660 
4661  HandleCodeCompleteResults(this, CodeCompleter, CC, Results.data(),
4662  Results.size());
4663 }
4664 
4666  if (!CodeCompleter)
4667  return;
4668 
4669  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4670  CodeCompleter->getCodeCompletionTUInfo(),
4672  &ResultBuilder::IsNestedNameSpecifier);
4673  Results.EnterNewScope();
4674 
4675  // If we aren't in class scope, we could see the "namespace" keyword.
4676  if (!S->isClassScope())
4677  Results.AddResult(CodeCompletionResult("namespace"));
4678 
4679  // After "using", we can see anything that would start a
4680  // nested-name-specifier.
4681  CodeCompletionDeclConsumer Consumer(Results, CurContext);
4682  LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4683  CodeCompleter->includeGlobals());
4684  Results.ExitScope();
4685 
4686  HandleCodeCompleteResults(this, CodeCompleter,
4688  Results.data(),Results.size());
4689 }
4690 
4692  if (!CodeCompleter)
4693  return;
4694 
4695  // After "using namespace", we expect to see a namespace name or namespace
4696  // alias.
4697  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4698  CodeCompleter->getCodeCompletionTUInfo(),
4700  &ResultBuilder::IsNamespaceOrAlias);
4701  Results.EnterNewScope();
4702  CodeCompletionDeclConsumer Consumer(Results, CurContext);
4703  LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4704  CodeCompleter->includeGlobals());
4705  Results.ExitScope();
4706  HandleCodeCompleteResults(this, CodeCompleter,
4708  Results.data(),Results.size());
4709 }
4710 
4712  if (!CodeCompleter)
4713  return;
4714 
4715  DeclContext *Ctx = S->getEntity();
4716  if (!S->getParent())
4717  Ctx = Context.getTranslationUnitDecl();
4718 
4719  bool SuppressedGlobalResults
4720  = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
4721 
4722  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4723  CodeCompleter->getCodeCompletionTUInfo(),
4724  SuppressedGlobalResults
4727  &ResultBuilder::IsNamespace);
4728 
4729  if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
4730  // We only want to see those namespaces that have already been defined
4731  // within this scope, because its likely that the user is creating an
4732  // extended namespace declaration. Keep track of the most recent
4733  // definition of each namespace.
4734  std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
4736  NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
4737  NS != NSEnd; ++NS)
4738  OrigToLatest[NS->getOriginalNamespace()] = *NS;
4739 
4740  // Add the most recent definition (or extended definition) of each
4741  // namespace to the list of results.
4742  Results.EnterNewScope();
4743  for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
4744  NS = OrigToLatest.begin(),
4745  NSEnd = OrigToLatest.end();
4746  NS != NSEnd; ++NS)
4747  Results.AddResult(CodeCompletionResult(
4748  NS->second, Results.getBasePriority(NS->second),
4749  nullptr),
4750  CurContext, nullptr, false);
4751  Results.ExitScope();
4752  }
4753 
4754  HandleCodeCompleteResults(this, CodeCompleter,
4755  Results.getCompletionContext(),
4756  Results.data(),Results.size());
4757 }
4758 
4760  if (!CodeCompleter)
4761  return;
4762 
4763  // After "namespace", we expect to see a namespace or alias.
4764  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4765  CodeCompleter->getCodeCompletionTUInfo(),
4767  &ResultBuilder::IsNamespaceOrAlias);
4768  CodeCompletionDeclConsumer Consumer(Results, CurContext);
4769  LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4770  CodeCompleter->includeGlobals());
4771  HandleCodeCompleteResults(this, CodeCompleter,
4772  Results.getCompletionContext(),
4773  Results.data(),Results.size());
4774 }
4775 
4777  if (!CodeCompleter)
4778  return;
4779 
4780  typedef CodeCompletionResult Result;
4781  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4782  CodeCompleter->getCodeCompletionTUInfo(),
4784  &ResultBuilder::IsType);
4785  Results.EnterNewScope();
4786 
4787  // Add the names of overloadable operators.
4788 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4789  if (std::strcmp(Spelling, "?")) \
4790  Results.AddResult(Result(Spelling));
4791 #include "clang/Basic/OperatorKinds.def"
4792 
4793  // Add any type names visible from the current scope
4794  Results.allowNestedNameSpecifiers();
4795  CodeCompletionDeclConsumer Consumer(Results, CurContext);
4796  LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4797  CodeCompleter->includeGlobals());
4798 
4799  // Add any type specifiers
4800  AddTypeSpecifierResults(getLangOpts(), Results);
4801  Results.ExitScope();
4802 
4803  HandleCodeCompleteResults(this, CodeCompleter,
4805  Results.data(),Results.size());
4806 }
4807 
4809  Decl *ConstructorD,
4810  ArrayRef <CXXCtorInitializer *> Initializers) {
4811  if (!ConstructorD)
4812  return;
4813 
4814  AdjustDeclIfTemplate(ConstructorD);
4815 
4816  CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ConstructorD);
4817  if (!Constructor)
4818  return;
4819 
4820  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4821  CodeCompleter->getCodeCompletionTUInfo(),
4823  Results.EnterNewScope();
4824 
4825  // Fill in any already-initialized fields or base classes.
4826  llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
4827  llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
4828  for (unsigned I = 0, E = Initializers.size(); I != E; ++I) {
4829  if (Initializers[I]->isBaseInitializer())
4830  InitializedBases.insert(
4831  Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
4832  else
4833  InitializedFields.insert(cast<FieldDecl>(
4834  Initializers[I]->getAnyMember()));
4835  }
4836 
4837  // Add completions for base classes.
4838  CodeCompletionBuilder Builder(Results.getAllocator(),
4839  Results.getCodeCompletionTUInfo());
4841  bool SawLastInitializer = Initializers.empty();
4842  CXXRecordDecl *ClassDecl = Constructor->getParent();
4843  for (const auto &Base : ClassDecl->bases()) {
4844  if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
4845  .second) {
4846  SawLastInitializer
4847  = !Initializers.empty() &&
4848  Initializers.back()->isBaseInitializer() &&
4849  Context.hasSameUnqualifiedType(Base.getType(),
4850  QualType(Initializers.back()->getBaseClass(), 0));
4851  continue;
4852  }
4853 
4854  Builder.AddTypedTextChunk(
4855  Results.getAllocator().CopyString(
4856  Base.getType().getAsString(Policy)));
4857  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4858  Builder.AddPlaceholderChunk("args");
4859  Builder.AddChunk(CodeCompletionString::CK_RightParen);
4860  Results.AddResult(CodeCompletionResult(Builder.TakeString(),
4861  SawLastInitializer? CCP_NextInitializer
4863  SawLastInitializer = false;
4864  }
4865 
4866  // Add completions for virtual base classes.
4867  for (const auto &Base : ClassDecl->vbases()) {
4868  if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
4869  .second) {
4870  SawLastInitializer
4871  = !Initializers.empty() &&
4872  Initializers.back()->isBaseInitializer() &&
4873  Context.hasSameUnqualifiedType(Base.getType(),
4874  QualType(Initializers.back()->getBaseClass(), 0));
4875  continue;
4876  }
4877 
4878  Builder.AddTypedTextChunk(
4879  Builder.getAllocator().CopyString(
4880  Base.getType().getAsString(Policy)));
4881  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4882  Builder.AddPlaceholderChunk("args");
4883  Builder.AddChunk(CodeCompletionString::CK_RightParen);
4884  Results.AddResult(CodeCompletionResult(Builder.TakeString(),
4885  SawLastInitializer? CCP_NextInitializer
4887  SawLastInitializer = false;
4888  }
4889 
4890  // Add completions for members.
4891  for (auto *Field : ClassDecl->fields()) {
4892  if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))
4893  .second) {
4894  SawLastInitializer
4895  = !Initializers.empty() &&
4896  Initializers.back()->isAnyMemberInitializer() &&
4897  Initializers.back()->getAnyMember() == Field;
4898  continue;
4899  }
4900 
4901  if (!Field->getDeclName())
4902  continue;
4903 
4904  Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
4905  Field->getIdentifier()->getName()));
4906  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4907  Builder.AddPlaceholderChunk("args");
4908  Builder.AddChunk(CodeCompletionString::CK_RightParen);
4909  Results.AddResult(CodeCompletionResult(Builder.TakeString(),
4910  SawLastInitializer? CCP_NextInitializer
4914  Field));
4915  SawLastInitializer = false;
4916  }
4917  Results.ExitScope();
4918 
4919  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4920  Results.data(), Results.size());
4921 }
4922 
4923 /// \brief Determine whether this scope denotes a namespace.
4924 static bool isNamespaceScope(Scope *S) {
4925  DeclContext *DC = S->getEntity();
4926  if (!DC)
4927  return false;
4928 
4929  return DC->isFileContext();
4930 }
4931 
4933  bool AfterAmpersand) {
4934  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4935  CodeCompleter->getCodeCompletionTUInfo(),
4937  Results.EnterNewScope();
4938 
4939  // Note what has already been captured.
4940  llvm::SmallPtrSet<IdentifierInfo *, 4> Known;
4941  bool IncludedThis = false;
4942  for (const auto &C : Intro.Captures) {
4943  if (C.Kind == LCK_This) {
4944  IncludedThis = true;
4945  continue;
4946  }
4947 
4948  Known.insert(C.Id);
4949  }
4950 
4951  // Look for other capturable variables.
4952  for (; S && !isNamespaceScope(S); S = S->getParent()) {
4953  for (const auto *D : S->decls()) {
4954  const auto *Var = dyn_cast<VarDecl>(D);
4955  if (!Var ||
4956  !Var->hasLocalStorage() ||
4957  Var->hasAttr<BlocksAttr>())
4958  continue;
4959 
4960  if (Known.insert(Var->getIdentifier()).second)
4961  Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration),
4962  CurContext, nullptr, false);
4963  }
4964  }
4965 
4966  // Add 'this', if it would be valid.
4967  if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy)
4968  addThisCompletion(*this, Results);
4969 
4970  Results.ExitScope();
4971 
4972  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4973  Results.data(), Results.size());
4974 }
4975 
4976 /// Macro that optionally prepends an "@" to the string literal passed in via
4977 /// Keyword, depending on whether NeedAt is true or false.
4978 #define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) ((NeedAt)? "@" Keyword : Keyword)
4979 
4980 static void AddObjCImplementationResults(const LangOptions &LangOpts,
4981  ResultBuilder &Results,
4982  bool NeedAt) {
4983  typedef CodeCompletionResult Result;
4984  // Since we have an implementation, we can end it.
4985  Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
4986 
4987  CodeCompletionBuilder Builder(Results.getAllocator(),
4988  Results.getCodeCompletionTUInfo());
4989  if (LangOpts.ObjC2) {
4990  // @dynamic
4991  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"dynamic"));
4992  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4993  Builder.AddPlaceholderChunk("property");
4994  Results.AddResult(Result(Builder.TakeString()));
4995 
4996  // @synthesize
4997  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synthesize"));
4998  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4999  Builder.AddPlaceholderChunk("property");
5000  Results.AddResult(Result(Builder.TakeString()));
5001  }
5002 }
5003 
5004 static void AddObjCInterfaceResults(const LangOptions &LangOpts,
5005  ResultBuilder &Results,
5006  bool NeedAt) {
5007  typedef CodeCompletionResult Result;
5008 
5009  // Since we have an interface or protocol, we can end it.
5010  Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
5011 
5012  if (LangOpts.ObjC2) {
5013  // @property
5014  Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"property")));
5015 
5016  // @required
5017  Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"required")));
5018 
5019  // @optional
5020  Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"optional")));
5021  }
5022 }
5023 
5024 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
5025  typedef CodeCompletionResult Result;
5026  CodeCompletionBuilder Builder(Results.getAllocator(),
5027  Results.getCodeCompletionTUInfo());
5028 
5029  // @class name ;
5030  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"class"));
5031  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5032  Builder.AddPlaceholderChunk("name");
5033  Results.AddResult(Result(Builder.TakeString()));
5034 
5035  if (Results.includeCodePatterns()) {
5036  // @interface name
5037  // FIXME: Could introduce the whole pattern, including superclasses and
5038  // such.
5039  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"interface"));
5040  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5041  Builder.AddPlaceholderChunk("class");
5042  Results.AddResult(Result(Builder.TakeString()));
5043 
5044  // @protocol name
5045  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
5046  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5047  Builder.AddPlaceholderChunk("protocol");
5048  Results.AddResult(Result(Builder.TakeString()));
5049 
5050  // @implementation name
5051  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"implementation"));
5052  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5053  Builder.AddPlaceholderChunk("class");
5054  Results.AddResult(Result(Builder.TakeString()));
5055  }
5056 
5057  // @compatibility_alias name
5058  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"compatibility_alias"));
5059  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5060  Builder.AddPlaceholderChunk("alias");
5061  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5062  Builder.AddPlaceholderChunk("class");
5063  Results.AddResult(Result(Builder.TakeString()));
5064 
5065  if (Results.getSema().getLangOpts().Modules) {
5066  // @import name
5067  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import"));
5068  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5069  Builder.AddPlaceholderChunk("module");
5070  Results.AddResult(Result(Builder.TakeString()));
5071  }
5072 }
5073 
5075  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5076  CodeCompleter->getCodeCompletionTUInfo(),
5078  Results.EnterNewScope();
5079  if (isa<ObjCImplDecl>(CurContext))
5080  AddObjCImplementationResults(getLangOpts(), Results, false);
5081  else if (CurContext->isObjCContainer())
5082  AddObjCInterfaceResults(getLangOpts(), Results, false);
5083  else
5084  AddObjCTopLevelResults(Results, false);
5085  Results.ExitScope();
5086  HandleCodeCompleteResults(this, CodeCompleter,
5088  Results.data(),Results.size());
5089 }
5090 
5091 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
5092  typedef CodeCompletionResult Result;
5093  CodeCompletionBuilder Builder(Results.getAllocator(),
5094  Results.getCodeCompletionTUInfo());
5095 
5096  // @encode ( type-name )
5097  const char *EncodeType = "char[]";
5098  if (Results.getSema().getLangOpts().CPlusPlus ||
5099  Results.getSema().getLangOpts().ConstStrings)
5100  EncodeType = "const char[]";
5101  Builder.AddResultTypeChunk(EncodeType);
5102  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"encode"));
5103  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5104  Builder.AddPlaceholderChunk("type-name");
5105  Builder.AddChunk(CodeCompletionString::CK_RightParen);
5106  Results.AddResult(Result(Builder.TakeString()));
5107 
5108  // @protocol ( protocol-name )
5109  Builder.AddResultTypeChunk("Protocol *");
5110  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
5111  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5112  Builder.AddPlaceholderChunk("protocol-name");
5113  Builder.AddChunk(CodeCompletionString::CK_RightParen);
5114  Results.AddResult(Result(Builder.TakeString()));
5115 
5116  // @selector ( selector )
5117  Builder.AddResultTypeChunk("SEL");
5118  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"selector"));
5119  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5120  Builder.AddPlaceholderChunk("selector");
5121  Builder.AddChunk(CodeCompletionString::CK_RightParen);
5122  Results.AddResult(Result(Builder.TakeString()));
5123 
5124  // @"string"
5125  Builder.AddResultTypeChunk("NSString *");
5126  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"\""));
5127  Builder.AddPlaceholderChunk("string");
5128  Builder.AddTextChunk("\"");
5129  Results.AddResult(Result(Builder.TakeString()));
5130 
5131  // @[objects, ...]
5132  Builder.AddResultTypeChunk("NSArray *");
5133  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"["));
5134  Builder.AddPlaceholderChunk("objects, ...");
5135  Builder.AddChunk(CodeCompletionString::CK_RightBracket);
5136  Results.AddResult(Result(Builder.TakeString()));
5137 
5138  // @{key : object, ...}
5139  Builder.AddResultTypeChunk("NSDictionary *");
5140  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"{"));
5141  Builder.AddPlaceholderChunk("key");
5142  Builder.AddChunk(CodeCompletionString::CK_Colon);
5143  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5144  Builder.AddPlaceholderChunk("object, ...");
5145  Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5146  Results.AddResult(Result(Builder.TakeString()));
5147 
5148  // @(expression)
5149  Builder.AddResultTypeChunk("id");
5150  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "("));
5151  Builder.AddPlaceholderChunk("expression");
5152  Builder.AddChunk(CodeCompletionString::CK_RightParen);
5153  Results.AddResult(Result(Builder.TakeString()));
5154 }
5155 
5156 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
5157  typedef CodeCompletionResult Result;
5158  CodeCompletionBuilder Builder(Results.getAllocator(),
5159  Results.getCodeCompletionTUInfo());
5160 
5161  if (Results.includeCodePatterns()) {
5162  // @try { statements } @catch ( declaration ) { statements } @finally
5163  // { statements }
5164  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"try"));
5165  Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5166  Builder.AddPlaceholderChunk("statements");
5167  Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5168  Builder.AddTextChunk("@catch");
5169  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5170  Builder.AddPlaceholderChunk("parameter");
5171  Builder.AddChunk(CodeCompletionString::CK_RightParen);
5172  Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5173  Builder.AddPlaceholderChunk("statements");
5174  Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5175  Builder.AddTextChunk("@finally");
5176  Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5177  Builder.AddPlaceholderChunk("statements");
5178  Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5179  Results.AddResult(Result(Builder.TakeString()));
5180  }
5181 
5182  // @throw
5183  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"throw"));
5184  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5185  Builder.AddPlaceholderChunk("expression");
5186  Results.AddResult(Result(Builder.TakeString()));
5187 
5188  if (Results.includeCodePatterns()) {
5189  // @synchronized ( expression ) { statements }
5190  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synchronized"));
5191  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5192  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5193  Builder.AddPlaceholderChunk("expression");
5194  Builder.AddChunk(CodeCompletionString::CK_RightParen);
5195  Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5196  Builder.AddPlaceholderChunk("statements");
5197  Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5198  Results.AddResult(Result(Builder.TakeString()));
5199  }
5200 }
5201 
5202 static void AddObjCVisibilityResults(const LangOptions &LangOpts,
5203  ResultBuilder &Results,
5204  bool NeedAt) {
5205  typedef CodeCompletionResult Result;
5206  Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"private")));
5207  Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"protected")));
5208  Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"public")));
5209  if (LangOpts.ObjC2)
5210  Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"package")));
5211 }
5212 
5214  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5215  CodeCompleter->getCodeCompletionTUInfo(),
5217  Results.EnterNewScope();
5218  AddObjCVisibilityResults(getLangOpts(), Results, false);
5219  Results.ExitScope();
5220  HandleCodeCompleteResults(this, CodeCompleter,
5222  Results.data(),Results.size());
5223 }
5224 
5226  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5227  CodeCompleter->getCodeCompletionTUInfo(),
5229  Results.EnterNewScope();
5230  AddObjCStatementResults(Results, false);
5231  AddObjCExpressionResults(Results, false);
5232  Results.ExitScope();
5233  HandleCodeCompleteResults(this, CodeCompleter,
5235  Results.data(),Results.size());
5236 }
5237 
5239  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5240  CodeCompleter->getCodeCompletionTUInfo(),
5242  Results.EnterNewScope();
5243  AddObjCExpressionResults(Results, false);
5244  Results.ExitScope();
5245  HandleCodeCompleteResults(this, CodeCompleter,
5247  Results.data(),Results.size());
5248 }
5249 
5250 /// \brief Determine whether the addition of the given flag to an Objective-C
5251 /// property's attributes will cause a conflict.
5252 static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
5253  // Check if we've already added this flag.
5254  if (Attributes & NewFlag)
5255  return true;
5256 
5257  Attributes |= NewFlag;
5258 
5259  // Check for collisions with "readonly".
5260  if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
5261  (Attributes & ObjCDeclSpec::DQ_PR_readwrite))
5262  return true;
5263 
5264  // Check for more than one of { assign, copy, retain, strong, weak }.
5265  unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
5271  if (AssignCopyRetMask &&
5272  AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
5273  AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
5274  AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
5275  AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
5276  AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong &&
5277  AssignCopyRetMask != ObjCDeclSpec::DQ_PR_weak)
5278  return true;
5279 
5280  return false;
5281 }
5282 
5284  if (!CodeCompleter)
5285  return;
5286 
5287  unsigned Attributes = ODS.getPropertyAttributes();
5288 
5289  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5290  CodeCompleter->getCodeCompletionTUInfo(),
5292  Results.EnterNewScope();
5294  Results.AddResult(CodeCompletionResult("readonly"));
5296  Results.AddResult(CodeCompletionResult("assign"));
5297  if (!ObjCPropertyFlagConflicts(Attributes,
5299  Results.AddResult(CodeCompletionResult("unsafe_unretained"));
5301  Results.AddResult(CodeCompletionResult("readwrite"));
5303  Results.AddResult(CodeCompletionResult("retain"));
5305  Results.AddResult(CodeCompletionResult("strong"));
5307  Results.AddResult(CodeCompletionResult("copy"));
5309  Results.AddResult(CodeCompletionResult("nonatomic"));
5311  Results.AddResult(CodeCompletionResult("atomic"));
5312 
5313  // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC.
5314  if (getLangOpts().ObjCWeak || getLangOpts().getGC() != LangOptions::NonGC)
5316  Results.AddResult(CodeCompletionResult("weak"));
5317 
5319  CodeCompletionBuilder Setter(Results.getAllocator(),
5320  Results.getCodeCompletionTUInfo());
5321  Setter.AddTypedTextChunk("setter");
5322  Setter.AddTextChunk("=");
5323  Setter.AddPlaceholderChunk("method");
5324  Results.AddResult(CodeCompletionResult(Setter.TakeString()));
5325  }
5327  CodeCompletionBuilder Getter(Results.getAllocator(),
5328  Results.getCodeCompletionTUInfo());
5329  Getter.AddTypedTextChunk("getter");
5330  Getter.AddTextChunk("=");
5331  Getter.AddPlaceholderChunk("method");
5332  Results.AddResult(CodeCompletionResult(Getter.TakeString()));
5333  }
5335  Results.AddResult(CodeCompletionResult("nonnull"));
5336  Results.AddResult(CodeCompletionResult("nullable"));
5337  Results.AddResult(CodeCompletionResult("null_unspecified"));
5338  Results.AddResult(CodeCompletionResult("null_resettable"));
5339  }
5340  Results.ExitScope();
5341  HandleCodeCompleteResults(this, CodeCompleter,
5343  Results.data(),Results.size());
5344 }
5345 
5346 /// \brief Describes the kind of Objective-C method that we want to find
5347 /// via code completion.
5349  MK_Any, ///< Any kind of method, provided it means other specified criteria.
5350  MK_ZeroArgSelector, ///< Zero-argument (unary) selector.
5351  MK_OneArgSelector ///< One-argument selector.
5352 };
5353 
5355  ObjCMethodKind WantKind,
5356  ArrayRef<IdentifierInfo *> SelIdents,
5357  bool AllowSameLength = true) {
5358  unsigned NumSelIdents = SelIdents.size();
5359  if (NumSelIdents > Sel.getNumArgs())
5360  return false;
5361 
5362  switch (WantKind) {
5363  case MK_Any: break;
5364  case MK_ZeroArgSelector: return Sel.isUnarySelector();
5365  case MK_OneArgSelector: return Sel.getNumArgs() == 1;
5366  }
5367 
5368  if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
5369  return false;
5370 
5371  for (unsigned I = 0; I != NumSelIdents; ++I)
5372  if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
5373  return false;
5374 
5375  return true;
5376 }
5377 
5379  ObjCMethodKind WantKind,
5380  ArrayRef<IdentifierInfo *> SelIdents,
5381  bool AllowSameLength = true) {
5382  return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
5383  AllowSameLength);
5384 }
5385 
5386 namespace {
5387  /// \brief A set of selectors, which is used to avoid introducing multiple
5388  /// completions with the same selector into the result set.
5389  typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
5390 }
5391 
5392 /// \brief Add all of the Objective-C methods in the given Objective-C
5393 /// container to the set of results.
5394 ///
5395 /// The container will be a class, protocol, category, or implementation of
5396 /// any of the above. This mether will recurse to include methods from
5397 /// the superclasses of classes along with their categories, protocols, and
5398 /// implementations.
5399 ///
5400 /// \param Container the container in which we'll look to find methods.
5401 ///
5402 /// \param WantInstanceMethods Whether to add instance methods (only); if
5403 /// false, this routine will add factory methods (only).
5404 ///
5405 /// \param CurContext the context in which we're performing the lookup that
5406 /// finds methods.
5407 ///
5408 /// \param AllowSameLength Whether we allow a method to be added to the list
5409 /// when it has the same number of parameters as we have selector identifiers.
5410 ///
5411 /// \param Results the structure into which we'll add results.
5412 static void AddObjCMethods(ObjCContainerDecl *Container,
5413  bool WantInstanceMethods, ObjCMethodKind WantKind,
5414  ArrayRef<IdentifierInfo *> SelIdents,
5415  DeclContext *CurContext,
5416  VisitedSelectorSet &Selectors, bool AllowSameLength,
5417  ResultBuilder &Results, bool InOriginalClass = true,
5418  bool IsRootClass = false) {
5419  typedef CodeCompletionResult Result;
5420  Container = getContainerDef(Container);
5421  ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
5422  IsRootClass = IsRootClass || (IFace && !IFace->getSuperClass());
5423  for (auto *M : Container->methods()) {
5424  // The instance methods on the root class can be messaged via the
5425  // metaclass.
5426  if (M->isInstanceMethod() == WantInstanceMethods ||
5427  (IsRootClass && !WantInstanceMethods)) {
5428  // Check whether the selector identifiers we've been given are a
5429  // subset of the identifiers for this particular method.
5430  if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength))
5431  continue;
5432 
5433  if (!Selectors.insert(M->getSelector()).second)
5434  continue;
5435 
5436  Result R = Result(M, Results.getBasePriority(M), nullptr);
5437  R.StartParameter = SelIdents.size();
5438  R.AllParametersAreInformative = (WantKind != MK_Any);
5439  if (!InOriginalClass)
5440  R.Priority += CCD_InBaseClass;
5441  Results.MaybeAddResult(R, CurContext);
5442  }
5443  }
5444 
5445  // Visit the protocols of protocols.
5446  if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5447  if (Protocol->hasDefinition()) {
5448  const ObjCList<ObjCProtocolDecl> &Protocols
5449  = Protocol->getReferencedProtocols();
5450  for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5451  E = Protocols.end();
5452  I != E; ++I)
5453  AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext,
5454  Selectors, AllowSameLength, Results, false, IsRootClass);
5455  }
5456  }
5457 
5458  if (!IFace || !IFace->hasDefinition())
5459  return;
5460 
5461  // Add methods in protocols.
5462  for (auto *I : IFace->protocols())
5463  AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents, CurContext,
5464  Selectors, AllowSameLength, Results, false, IsRootClass);
5465 
5466  // Add methods in categories.
5467  for (auto *CatDecl : IFace->known_categories()) {
5468  AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
5469  CurContext, Selectors, AllowSameLength, Results,
5470  InOriginalClass, IsRootClass);
5471 
5472  // Add a categories protocol methods.
5473  const ObjCList<ObjCProtocolDecl> &Protocols
5474  = CatDecl->getReferencedProtocols();
5475  for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5476  E = Protocols.end();
5477  I != E; ++I)
5478  AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext,
5479  Selectors, AllowSameLength, Results, false, IsRootClass);
5480 
5481  // Add methods in category implementations.
5482  if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
5483  AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext,
5484  Selectors, AllowSameLength, Results, InOriginalClass,
5485  IsRootClass);
5486  }
5487 
5488  // Add methods in superclass.
5489  // Avoid passing in IsRootClass since root classes won't have super classes.
5490  if (IFace->getSuperClass())
5491  AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
5492  SelIdents, CurContext, Selectors, AllowSameLength, Results,
5493  /*IsRootClass=*/false);
5494 
5495  // Add methods in our implementation, if any.
5496  if (ObjCImplementationDecl *Impl = IFace->getImplementation())
5497  AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext,
5498  Selectors, AllowSameLength, Results, InOriginalClass,
5499  IsRootClass);
5500 }
5501 
5502 
5504  // Try to find the interface where getters might live.
5505  ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
5506  if (!Class) {
5508  = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
5509  Class = Category->getClassInterface();
5510 
5511  if (!Class)
5512  return;
5513  }
5514 
5515  // Find all of the potential getters.
5516  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5517  CodeCompleter->getCodeCompletionTUInfo(),
5519  Results.EnterNewScope();
5520 
5521  VisitedSelectorSet Selectors;
5522  AddObjCMethods(Class, true, MK_ZeroArgSelector, None, CurContext, Selectors,
5523  /*AllowSameLength=*/true, Results);
5524  Results.ExitScope();
5525  HandleCodeCompleteResults(this, CodeCompleter,
5527  Results.data(),Results.size());
5528 }
5529 
5531  // Try to find the interface where setters might live.
5532  ObjCInterfaceDecl *Class
5533  = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
5534  if (!Class) {
5536  = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
5537  Class = Category->getClassInterface();
5538