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