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