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