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