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