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