clang  9.0.0svn
Marshallers.h
Go to the documentation of this file.
1 //===- Marshallers.h - Generic matcher function marshallers -----*- 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 /// \file
10 /// Functions templates and classes to wrap matcher construct functions.
11 ///
12 /// A collection of template function and classes that provide a generic
13 /// marshalling layer on top of matcher construct functions.
14 /// These are used by the registry to export all marshaller constructors with
15 /// the same generic interface.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #ifndef LLVM_CLANG_LIB_ASTMATCHERS_DYNAMIC_MARSHALLERS_H
20 #define LLVM_CLANG_LIB_ASTMATCHERS_DYNAMIC_MARSHALLERS_H
21 
27 #include "clang/Basic/AttrKinds.h"
28 #include "clang/Basic/LLVM.h"
29 #include "llvm/ADT/ArrayRef.h"
30 #include "llvm/ADT/None.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/StringRef.h"
33 #include "llvm/ADT/StringSwitch.h"
34 #include "llvm/ADT/Twine.h"
35 #include <cassert>
36 #include <cstddef>
37 #include <iterator>
38 #include <limits>
39 #include <memory>
40 #include <string>
41 #include <utility>
42 #include <vector>
43 
44 namespace clang {
45 namespace ast_matchers {
46 namespace dynamic {
47 namespace internal {
48 
49 /// Helper template class to just from argument type to the right is/get
50 /// functions in VariantValue.
51 /// Used to verify and extract the matcher arguments below.
52 template <class T> struct ArgTypeTraits;
53 template <class T> struct ArgTypeTraits<const T &> : public ArgTypeTraits<T> {
54 };
55 
56 template <> struct ArgTypeTraits<std::string> {
57  static bool is(const VariantValue &Value) { return Value.isString(); }
58 
59  static const std::string &get(const VariantValue &Value) {
60  return Value.getString();
61  }
62 
63  static ArgKind getKind() {
65  }
66 };
67 
68 template <>
69 struct ArgTypeTraits<StringRef> : public ArgTypeTraits<std::string> {
70 };
71 
72 template <class T> struct ArgTypeTraits<ast_matchers::internal::Matcher<T>> {
73  static bool is(const VariantValue &Value) {
74  return Value.isMatcher() && Value.getMatcher().hasTypedMatcher<T>();
75  }
76 
77  static ast_matchers::internal::Matcher<T> get(const VariantValue &Value) {
78  return Value.getMatcher().getTypedMatcher<T>();
79  }
80 
81  static ArgKind getKind() {
82  return ArgKind(ast_type_traits::ASTNodeKind::getFromNodeKind<T>());
83  }
84 };
85 
86 template <> struct ArgTypeTraits<bool> {
87  static bool is(const VariantValue &Value) { return Value.isBoolean(); }
88 
89  static bool get(const VariantValue &Value) {
90  return Value.getBoolean();
91  }
92 
93  static ArgKind getKind() {
95  }
96 };
97 
98 template <> struct ArgTypeTraits<double> {
99  static bool is(const VariantValue &Value) { return Value.isDouble(); }
100 
101  static double get(const VariantValue &Value) {
102  return Value.getDouble();
103  }
104 
105  static ArgKind getKind() {
106  return ArgKind(ArgKind::AK_Double);
107  }
108 };
109 
110 template <> struct ArgTypeTraits<unsigned> {
111  static bool is(const VariantValue &Value) { return Value.isUnsigned(); }
112 
113  static unsigned get(const VariantValue &Value) {
114  return Value.getUnsigned();
115  }
116 
117  static ArgKind getKind() {
119  }
120 };
121 
122 template <> struct ArgTypeTraits<attr::Kind> {
123 private:
124  static Optional<attr::Kind> getAttrKind(llvm::StringRef AttrKind) {
125  return llvm::StringSwitch<Optional<attr::Kind>>(AttrKind)
126 #define ATTR(X) .Case("attr::" #X, attr:: X)
127 #include "clang/Basic/AttrList.inc"
128  .Default(llvm::None);
129  }
130 
131 public:
132  static bool is(const VariantValue &Value) {
133  return Value.isString() && getAttrKind(Value.getString());
134  }
135 
136  static attr::Kind get(const VariantValue &Value) {
137  return *getAttrKind(Value.getString());
138  }
139 
140  static ArgKind getKind() {
141  return ArgKind(ArgKind::AK_String);
142  }
143 };
144 
145 template <> struct ArgTypeTraits<CastKind> {
146 private:
147  static Optional<CastKind> getCastKind(llvm::StringRef AttrKind) {
148  return llvm::StringSwitch<Optional<CastKind>>(AttrKind)
149 #define CAST_OPERATION(Name) .Case( #Name, CK_##Name)
150 #include "clang/AST/OperationKinds.def"
151  .Default(llvm::None);
152  }
153 
154 public:
155  static bool is(const VariantValue &Value) {
156  return Value.isString() && getCastKind(Value.getString());
157  }
158 
159  static CastKind get(const VariantValue &Value) {
160  return *getCastKind(Value.getString());
161  }
162 
163  static ArgKind getKind() {
164  return ArgKind(ArgKind::AK_String);
165  }
166 };
167 
168 /// Matcher descriptor interface.
169 ///
170 /// Provides a \c create() method that constructs the matcher from the provided
171 /// arguments, and various other methods for type introspection.
173 public:
174  virtual ~MatcherDescriptor() = default;
175 
176  virtual VariantMatcher create(SourceRange NameRange,
178  Diagnostics *Error) const = 0;
179 
180  /// Returns whether the matcher is variadic. Variadic matchers can take any
181  /// number of arguments, but they must be of the same type.
182  virtual bool isVariadic() const = 0;
183 
184  /// Returns the number of arguments accepted by the matcher if not variadic.
185  virtual unsigned getNumArgs() const = 0;
186 
187  /// Given that the matcher is being converted to type \p ThisKind, append the
188  /// set of argument types accepted for argument \p ArgNo to \p ArgKinds.
189  // FIXME: We should provide the ability to constrain the output of this
190  // function based on the types of other matcher arguments.
191  virtual void getArgKinds(ast_type_traits::ASTNodeKind ThisKind, unsigned ArgNo,
192  std::vector<ArgKind> &ArgKinds) const = 0;
193 
194  /// Returns whether this matcher is convertible to the given type. If it is
195  /// so convertible, store in *Specificity a value corresponding to the
196  /// "specificity" of the converted matcher to the given context, and in
197  /// *LeastDerivedKind the least derived matcher kind which would result in the
198  /// same matcher overload. Zero specificity indicates that this conversion
199  /// would produce a trivial matcher that will either always or never match.
200  /// Such matchers are excluded from code completion results.
201  virtual bool isConvertibleTo(
202  ast_type_traits::ASTNodeKind Kind, unsigned *Specificity = nullptr,
203  ast_type_traits::ASTNodeKind *LeastDerivedKind = nullptr) const = 0;
204 
205  /// Returns whether the matcher will, given a matcher of any type T, yield a
206  /// matcher of type T.
207  virtual bool isPolymorphic() const { return false; }
208 };
209 
212  ast_type_traits::ASTNodeKind Kind, unsigned *Specificity,
213  ast_type_traits::ASTNodeKind *LeastDerivedKind) {
214  for (const ast_type_traits::ASTNodeKind &NodeKind : RetKinds) {
215  if (ArgKind(NodeKind).isConvertibleTo(Kind, Specificity)) {
216  if (LeastDerivedKind)
217  *LeastDerivedKind = NodeKind;
218  return true;
219  }
220  }
221  return false;
222 }
223 
224 /// Simple callback implementation. Marshaller and function are provided.
225 ///
226 /// This class wraps a function of arbitrary signature and a marshaller
227 /// function into a MatcherDescriptor.
228 /// The marshaller is in charge of taking the VariantValue arguments, checking
229 /// their types, unpacking them and calling the underlying function.
231 public:
232  using MarshallerType = VariantMatcher (*)(void (*Func)(),
233  StringRef MatcherName,
234  SourceRange NameRange,
236  Diagnostics *Error);
237 
238  /// \param Marshaller Function to unpack the arguments and call \c Func
239  /// \param Func Matcher construct function. This is the function that
240  /// compile-time matcher expressions would use to create the matcher.
241  /// \param RetKinds The list of matcher types to which the matcher is
242  /// convertible.
243  /// \param ArgKinds The types of the arguments this matcher takes.
245  MarshallerType Marshaller, void (*Func)(), StringRef MatcherName,
247  ArrayRef<ArgKind> ArgKinds)
248  : Marshaller(Marshaller), Func(Func), MatcherName(MatcherName),
249  RetKinds(RetKinds.begin(), RetKinds.end()),
250  ArgKinds(ArgKinds.begin(), ArgKinds.end()) {}
251 
254  Diagnostics *Error) const override {
255  return Marshaller(Func, MatcherName, NameRange, Args, Error);
256  }
257 
258  bool isVariadic() const override { return false; }
259  unsigned getNumArgs() const override { return ArgKinds.size(); }
260 
261  void getArgKinds(ast_type_traits::ASTNodeKind ThisKind, unsigned ArgNo,
262  std::vector<ArgKind> &Kinds) const override {
263  Kinds.push_back(ArgKinds[ArgNo]);
264  }
265 
267  ast_type_traits::ASTNodeKind Kind, unsigned *Specificity,
268  ast_type_traits::ASTNodeKind *LeastDerivedKind) const override {
269  return isRetKindConvertibleTo(RetKinds, Kind, Specificity,
270  LeastDerivedKind);
271  }
272 
273 private:
274  const MarshallerType Marshaller;
275  void (* const Func)();
276  const std::string MatcherName;
277  const std::vector<ast_type_traits::ASTNodeKind> RetKinds;
278  const std::vector<ArgKind> ArgKinds;
279 };
280 
281 /// Helper methods to extract and merge all possible typed matchers
282 /// out of the polymorphic object.
283 template <class PolyMatcher>
284 static void mergePolyMatchers(const PolyMatcher &Poly,
285  std::vector<DynTypedMatcher> &Out,
286  ast_matchers::internal::EmptyTypeList) {}
287 
288 template <class PolyMatcher, class TypeList>
289 static void mergePolyMatchers(const PolyMatcher &Poly,
290  std::vector<DynTypedMatcher> &Out, TypeList) {
291  Out.push_back(ast_matchers::internal::Matcher<typename TypeList::head>(Poly));
292  mergePolyMatchers(Poly, Out, typename TypeList::tail());
293 }
294 
295 /// Convert the return values of the functions into a VariantMatcher.
296 ///
297 /// There are 2 cases right now: The return value is a Matcher<T> or is a
298 /// polymorphic matcher. For the former, we just construct the VariantMatcher.
299 /// For the latter, we instantiate all the possible Matcher<T> of the poly
300 /// matcher.
301 static VariantMatcher outvalueToVariantMatcher(const DynTypedMatcher &Matcher) {
302  return VariantMatcher::SingleMatcher(Matcher);
303 }
304 
305 template <typename T>
306 static VariantMatcher outvalueToVariantMatcher(const T &PolyMatcher,
307  typename T::ReturnTypes * =
308  nullptr) {
309  std::vector<DynTypedMatcher> Matchers;
310  mergePolyMatchers(PolyMatcher, Matchers, typename T::ReturnTypes());
311  VariantMatcher Out = VariantMatcher::PolymorphicMatcher(std::move(Matchers));
312  return Out;
313 }
314 
315 template <typename T>
317  std::vector<ast_type_traits::ASTNodeKind> &RetTypes) {
318  RetTypes.push_back(
319  ast_type_traits::ASTNodeKind::getFromNodeKind<typename T::head>());
320  buildReturnTypeVectorFromTypeList<typename T::tail>(RetTypes);
321 }
322 
323 template <>
324 inline void
325 buildReturnTypeVectorFromTypeList<ast_matchers::internal::EmptyTypeList>(
326  std::vector<ast_type_traits::ASTNodeKind> &RetTypes) {}
327 
328 template <typename T>
330  static void build(std::vector<ast_type_traits::ASTNodeKind> &RetTypes) {
331  buildReturnTypeVectorFromTypeList<typename T::ReturnTypes>(RetTypes);
332  }
333 };
334 
335 template <typename T>
336 struct BuildReturnTypeVector<ast_matchers::internal::Matcher<T>> {
337  static void build(std::vector<ast_type_traits::ASTNodeKind> &RetTypes) {
338  RetTypes.push_back(ast_type_traits::ASTNodeKind::getFromNodeKind<T>());
339  }
340 };
341 
342 template <typename T>
343 struct BuildReturnTypeVector<ast_matchers::internal::BindableMatcher<T>> {
344  static void build(std::vector<ast_type_traits::ASTNodeKind> &RetTypes) {
345  RetTypes.push_back(ast_type_traits::ASTNodeKind::getFromNodeKind<T>());
346  }
347 };
348 
349 /// Variadic marshaller function.
350 template <typename ResultT, typename ArgT,
351  ResultT (*Func)(ArrayRef<const ArgT *>)>
353 variadicMatcherDescriptor(StringRef MatcherName, SourceRange NameRange,
354  ArrayRef<ParserValue> Args, Diagnostics *Error) {
355  ArgT **InnerArgs = new ArgT *[Args.size()]();
356 
357  bool HasError = false;
358  for (size_t i = 0, e = Args.size(); i != e; ++i) {
359  using ArgTraits = ArgTypeTraits<ArgT>;
360 
361  const ParserValue &Arg = Args[i];
362  const VariantValue &Value = Arg.Value;
363  if (!ArgTraits::is(Value)) {
364  Error->addError(Arg.Range, Error->ET_RegistryWrongArgType)
365  << (i + 1) << ArgTraits::getKind().asString() << Value.getTypeAsString();
366  HasError = true;
367  break;
368  }
369  InnerArgs[i] = new ArgT(ArgTraits::get(Value));
370  }
371 
372  VariantMatcher Out;
373  if (!HasError) {
374  Out = outvalueToVariantMatcher(Func(llvm::makeArrayRef(InnerArgs,
375  Args.size())));
376  }
377 
378  for (size_t i = 0, e = Args.size(); i != e; ++i) {
379  delete InnerArgs[i];
380  }
381  delete[] InnerArgs;
382  return Out;
383 }
384 
385 /// Matcher descriptor for variadic functions.
386 ///
387 /// This class simply wraps a VariadicFunction with the right signature to export
388 /// it as a MatcherDescriptor.
389 /// This allows us to have one implementation of the interface for as many free
390 /// functions as we want, reducing the number of symbols and size of the
391 /// object file.
393 public:
394  using RunFunc = VariantMatcher (*)(StringRef MatcherName,
395  SourceRange NameRange,
397  Diagnostics *Error);
398 
399  template <typename ResultT, typename ArgT,
400  ResultT (*F)(ArrayRef<const ArgT *>)>
402  ast_matchers::internal::VariadicFunction<ResultT, ArgT, F> Func,
403  StringRef MatcherName)
404  : Func(&variadicMatcherDescriptor<ResultT, ArgT, F>),
405  MatcherName(MatcherName.str()),
406  ArgsKind(ArgTypeTraits<ArgT>::getKind()) {
408  }
409 
412  Diagnostics *Error) const override {
413  return Func(MatcherName, NameRange, Args, Error);
414  }
415 
416  bool isVariadic() const override { return true; }
417  unsigned getNumArgs() const override { return 0; }
418 
419  void getArgKinds(ast_type_traits::ASTNodeKind ThisKind, unsigned ArgNo,
420  std::vector<ArgKind> &Kinds) const override {
421  Kinds.push_back(ArgsKind);
422  }
423 
425  ast_type_traits::ASTNodeKind Kind, unsigned *Specificity,
426  ast_type_traits::ASTNodeKind *LeastDerivedKind) const override {
427  return isRetKindConvertibleTo(RetKinds, Kind, Specificity,
428  LeastDerivedKind);
429  }
430 
431 private:
432  const RunFunc Func;
433  const std::string MatcherName;
434  std::vector<ast_type_traits::ASTNodeKind> RetKinds;
435  const ArgKind ArgsKind;
436 };
437 
438 /// Return CK_Trivial when appropriate for VariadicDynCastAllOfMatchers.
440 public:
441  template <typename BaseT, typename DerivedT>
443  ast_matchers::internal::VariadicDynCastAllOfMatcher<BaseT, DerivedT> Func,
444  StringRef MatcherName)
445  : VariadicFuncMatcherDescriptor(Func, MatcherName),
446  DerivedKind(ast_type_traits::ASTNodeKind::getFromNodeKind<DerivedT>()) {
447  }
448 
449  bool
451  ast_type_traits::ASTNodeKind *LeastDerivedKind) const override {
452  // If Kind is not a base of DerivedKind, either DerivedKind is a base of
453  // Kind (in which case the match will always succeed) or Kind and
454  // DerivedKind are unrelated (in which case it will always fail), so set
455  // Specificity to 0.
457  LeastDerivedKind)) {
458  if (Kind.isSame(DerivedKind) || !Kind.isBaseOf(DerivedKind)) {
459  if (Specificity)
460  *Specificity = 0;
461  }
462  return true;
463  } else {
464  return false;
465  }
466  }
467 
468 private:
469  const ast_type_traits::ASTNodeKind DerivedKind;
470 };
471 
472 /// Helper macros to check the arguments on all marshaller functions.
473 #define CHECK_ARG_COUNT(count) \
474  if (Args.size() != count) { \
475  Error->addError(NameRange, Error->ET_RegistryWrongArgCount) \
476  << count << Args.size(); \
477  return VariantMatcher(); \
478  }
479 
480 #define CHECK_ARG_TYPE(index, type) \
481  if (!ArgTypeTraits<type>::is(Args[index].Value)) { \
482  Error->addError(Args[index].Range, Error->ET_RegistryWrongArgType) \
483  << (index + 1) << ArgTypeTraits<type>::getKind().asString() \
484  << Args[index].Value.getTypeAsString(); \
485  return VariantMatcher(); \
486  }
487 
488 /// 0-arg marshaller function.
489 template <typename ReturnType>
490 static VariantMatcher matcherMarshall0(void (*Func)(), StringRef MatcherName,
491  SourceRange NameRange,
493  Diagnostics *Error) {
494  using FuncType = ReturnType (*)();
495  CHECK_ARG_COUNT(0);
496  return outvalueToVariantMatcher(reinterpret_cast<FuncType>(Func)());
497 }
498 
499 /// 1-arg marshaller function.
500 template <typename ReturnType, typename ArgType1>
501 static VariantMatcher matcherMarshall1(void (*Func)(), StringRef MatcherName,
502  SourceRange NameRange,
504  Diagnostics *Error) {
505  using FuncType = ReturnType (*)(ArgType1);
506  CHECK_ARG_COUNT(1);
507  CHECK_ARG_TYPE(0, ArgType1);
508  return outvalueToVariantMatcher(reinterpret_cast<FuncType>(Func)(
510 }
511 
512 /// 2-arg marshaller function.
513 template <typename ReturnType, typename ArgType1, typename ArgType2>
514 static VariantMatcher matcherMarshall2(void (*Func)(), StringRef MatcherName,
515  SourceRange NameRange,
517  Diagnostics *Error) {
518  using FuncType = ReturnType (*)(ArgType1, ArgType2);
519  CHECK_ARG_COUNT(2);
520  CHECK_ARG_TYPE(0, ArgType1);
521  CHECK_ARG_TYPE(1, ArgType2);
522  return outvalueToVariantMatcher(reinterpret_cast<FuncType>(Func)(
524  ArgTypeTraits<ArgType2>::get(Args[1].Value)));
525 }
526 
527 #undef CHECK_ARG_COUNT
528 #undef CHECK_ARG_TYPE
529 
530 /// Helper class used to collect all the possible overloads of an
531 /// argument adaptative matcher function.
532 template <template <typename ToArg, typename FromArg> class ArgumentAdapterT,
533  typename FromTypes, typename ToTypes>
535 public:
537  StringRef Name, std::vector<std::unique_ptr<MatcherDescriptor>> &Out)
538  : Name(Name), Out(Out) {
539  collect(FromTypes());
540  }
541 
542 private:
543  using AdaptativeFunc = ast_matchers::internal::ArgumentAdaptingMatcherFunc<
544  ArgumentAdapterT, FromTypes, ToTypes>;
545 
546  /// End case for the recursion
547  static void collect(ast_matchers::internal::EmptyTypeList) {}
548 
549  /// Recursive case. Get the overload for the head of the list, and
550  /// recurse to the tail.
551  template <typename FromTypeList>
552  inline void collect(FromTypeList);
553 
554  StringRef Name;
555  std::vector<std::unique_ptr<MatcherDescriptor>> &Out;
556 };
557 
558 /// MatcherDescriptor that wraps multiple "overloads" of the same
559 /// matcher.
560 ///
561 /// It will try every overload and generate appropriate errors for when none or
562 /// more than one overloads match the arguments.
564 public:
566  MutableArrayRef<std::unique_ptr<MatcherDescriptor>> Callbacks)
567  : Overloads(std::make_move_iterator(Callbacks.begin()),
568  std::make_move_iterator(Callbacks.end())) {}
569 
570  ~OverloadedMatcherDescriptor() override = default;
571 
574  Diagnostics *Error) const override {
575  std::vector<VariantMatcher> Constructed;
576  Diagnostics::OverloadContext Ctx(Error);
577  for (const auto &O : Overloads) {
578  VariantMatcher SubMatcher = O->create(NameRange, Args, Error);
579  if (!SubMatcher.isNull()) {
580  Constructed.push_back(SubMatcher);
581  }
582  }
583 
584  if (Constructed.empty()) return VariantMatcher(); // No overload matched.
585  // We ignore the errors if any matcher succeeded.
586  Ctx.revertErrors();
587  if (Constructed.size() > 1) {
588  // More than one constructed. It is ambiguous.
589  Error->addError(NameRange, Error->ET_RegistryAmbiguousOverload);
590  return VariantMatcher();
591  }
592  return Constructed[0];
593  }
594 
595  bool isVariadic() const override {
596  bool Overload0Variadic = Overloads[0]->isVariadic();
597 #ifndef NDEBUG
598  for (const auto &O : Overloads) {
599  assert(Overload0Variadic == O->isVariadic());
600  }
601 #endif
602  return Overload0Variadic;
603  }
604 
605  unsigned getNumArgs() const override {
606  unsigned Overload0NumArgs = Overloads[0]->getNumArgs();
607 #ifndef NDEBUG
608  for (const auto &O : Overloads) {
609  assert(Overload0NumArgs == O->getNumArgs());
610  }
611 #endif
612  return Overload0NumArgs;
613  }
614 
615  void getArgKinds(ast_type_traits::ASTNodeKind ThisKind, unsigned ArgNo,
616  std::vector<ArgKind> &Kinds) const override {
617  for (const auto &O : Overloads) {
618  if (O->isConvertibleTo(ThisKind))
619  O->getArgKinds(ThisKind, ArgNo, Kinds);
620  }
621  }
622 
624  ast_type_traits::ASTNodeKind Kind, unsigned *Specificity,
625  ast_type_traits::ASTNodeKind *LeastDerivedKind) const override {
626  for (const auto &O : Overloads) {
627  if (O->isConvertibleTo(Kind, Specificity, LeastDerivedKind))
628  return true;
629  }
630  return false;
631  }
632 
633 private:
634  std::vector<std::unique_ptr<MatcherDescriptor>> Overloads;
635 };
636 
637 /// Variadic operator marshaller function.
639 public:
640  using VarOp = DynTypedMatcher::VariadicOperator;
641 
642  VariadicOperatorMatcherDescriptor(unsigned MinCount, unsigned MaxCount,
643  VarOp Op, StringRef MatcherName)
644  : MinCount(MinCount), MaxCount(MaxCount), Op(Op),
645  MatcherName(MatcherName) {}
646 
649  Diagnostics *Error) const override {
650  if (Args.size() < MinCount || MaxCount < Args.size()) {
651  const std::string MaxStr =
652  (MaxCount == std::numeric_limits<unsigned>::max() ? ""
653  : Twine(MaxCount))
654  .str();
655  Error->addError(NameRange, Error->ET_RegistryWrongArgCount)
656  << ("(" + Twine(MinCount) + ", " + MaxStr + ")") << Args.size();
657  return VariantMatcher();
658  }
659 
660  std::vector<VariantMatcher> InnerArgs;
661  for (size_t i = 0, e = Args.size(); i != e; ++i) {
662  const ParserValue &Arg = Args[i];
663  const VariantValue &Value = Arg.Value;
664  if (!Value.isMatcher()) {
665  Error->addError(Arg.Range, Error->ET_RegistryWrongArgType)
666  << (i + 1) << "Matcher<>" << Value.getTypeAsString();
667  return VariantMatcher();
668  }
669  InnerArgs.push_back(Value.getMatcher());
670  }
671  return VariantMatcher::VariadicOperatorMatcher(Op, std::move(InnerArgs));
672  }
673 
674  bool isVariadic() const override { return true; }
675  unsigned getNumArgs() const override { return 0; }
676 
677  void getArgKinds(ast_type_traits::ASTNodeKind ThisKind, unsigned ArgNo,
678  std::vector<ArgKind> &Kinds) const override {
679  Kinds.push_back(ThisKind);
680  }
681 
682  bool isConvertibleTo(ast_type_traits::ASTNodeKind Kind, unsigned *Specificity,
683  ast_type_traits::ASTNodeKind *LeastDerivedKind) const override {
684  if (Specificity)
685  *Specificity = 1;
686  if (LeastDerivedKind)
687  *LeastDerivedKind = Kind;
688  return true;
689  }
690 
691  bool isPolymorphic() const override { return true; }
692 
693 private:
694  const unsigned MinCount;
695  const unsigned MaxCount;
696  const VarOp Op;
697  const StringRef MatcherName;
698 };
699 
700 /// Helper functions to select the appropriate marshaller functions.
701 /// They detect the number of arguments, arguments types and return type.
702 
703 /// 0-arg overload
704 template <typename ReturnType>
705 std::unique_ptr<MatcherDescriptor>
706 makeMatcherAutoMarshall(ReturnType (*Func)(), StringRef MatcherName) {
707  std::vector<ast_type_traits::ASTNodeKind> RetTypes;
709  return llvm::make_unique<FixedArgCountMatcherDescriptor>(
710  matcherMarshall0<ReturnType>, reinterpret_cast<void (*)()>(Func),
711  MatcherName, RetTypes, None);
712 }
713 
714 /// 1-arg overload
715 template <typename ReturnType, typename ArgType1>
716 std::unique_ptr<MatcherDescriptor>
717 makeMatcherAutoMarshall(ReturnType (*Func)(ArgType1), StringRef MatcherName) {
718  std::vector<ast_type_traits::ASTNodeKind> RetTypes;
721  return llvm::make_unique<FixedArgCountMatcherDescriptor>(
722  matcherMarshall1<ReturnType, ArgType1>,
723  reinterpret_cast<void (*)()>(Func), MatcherName, RetTypes, AK);
724 }
725 
726 /// 2-arg overload
727 template <typename ReturnType, typename ArgType1, typename ArgType2>
728 std::unique_ptr<MatcherDescriptor>
729 makeMatcherAutoMarshall(ReturnType (*Func)(ArgType1, ArgType2),
730  StringRef MatcherName) {
731  std::vector<ast_type_traits::ASTNodeKind> RetTypes;
735  return llvm::make_unique<FixedArgCountMatcherDescriptor>(
736  matcherMarshall2<ReturnType, ArgType1, ArgType2>,
737  reinterpret_cast<void (*)()>(Func), MatcherName, RetTypes, AKs);
738 }
739 
740 /// Variadic overload.
741 template <typename ResultT, typename ArgT,
742  ResultT (*Func)(ArrayRef<const ArgT *>)>
743 std::unique_ptr<MatcherDescriptor> makeMatcherAutoMarshall(
744  ast_matchers::internal::VariadicFunction<ResultT, ArgT, Func> VarFunc,
745  StringRef MatcherName) {
746  return llvm::make_unique<VariadicFuncMatcherDescriptor>(VarFunc, MatcherName);
747 }
748 
749 /// Overload for VariadicDynCastAllOfMatchers.
750 ///
751 /// Not strictly necessary, but DynCastAllOfMatcherDescriptor gives us better
752 /// completion results for that type of matcher.
753 template <typename BaseT, typename DerivedT>
754 std::unique_ptr<MatcherDescriptor> makeMatcherAutoMarshall(
755  ast_matchers::internal::VariadicDynCastAllOfMatcher<BaseT, DerivedT>
756  VarFunc,
757  StringRef MatcherName) {
758  return llvm::make_unique<DynCastAllOfMatcherDescriptor>(VarFunc, MatcherName);
759 }
760 
761 /// Argument adaptative overload.
762 template <template <typename ToArg, typename FromArg> class ArgumentAdapterT,
763  typename FromTypes, typename ToTypes>
764 std::unique_ptr<MatcherDescriptor> makeMatcherAutoMarshall(
765  ast_matchers::internal::ArgumentAdaptingMatcherFunc<ArgumentAdapterT,
766  FromTypes, ToTypes>,
767  StringRef MatcherName) {
768  std::vector<std::unique_ptr<MatcherDescriptor>> Overloads;
770  Overloads);
771  return llvm::make_unique<OverloadedMatcherDescriptor>(Overloads);
772 }
773 
774 template <template <typename ToArg, typename FromArg> class ArgumentAdapterT,
775  typename FromTypes, typename ToTypes>
776 template <typename FromTypeList>
777 inline void AdaptativeOverloadCollector<ArgumentAdapterT, FromTypes,
778  ToTypes>::collect(FromTypeList) {
779  Out.push_back(makeMatcherAutoMarshall(
780  &AdaptativeFunc::template create<typename FromTypeList::head>, Name));
781  collect(typename FromTypeList::tail());
782 }
783 
784 /// Variadic operator overload.
785 template <unsigned MinCount, unsigned MaxCount>
786 std::unique_ptr<MatcherDescriptor> makeMatcherAutoMarshall(
787  ast_matchers::internal::VariadicOperatorMatcherFunc<MinCount, MaxCount>
788  Func,
789  StringRef MatcherName) {
790  return llvm::make_unique<VariadicOperatorMatcherDescriptor>(
791  MinCount, MaxCount, Func.Op, MatcherName);
792 }
793 
794 } // namespace internal
795 } // namespace dynamic
796 } // namespace ast_matchers
797 } // namespace clang
798 
799 #endif // LLVM_CLANG_AST_MATCHERS_DYNAMIC_MARSHALLERS_H
void getArgKinds(ast_type_traits::ASTNodeKind ThisKind, unsigned ArgNo, std::vector< ArgKind > &Kinds) const override
Given that the matcher is being converted to type ThisKind, append the set of argument types accepted...
Definition: Marshallers.h:677
VariantMatcher create(SourceRange NameRange, ArrayRef< ParserValue > Args, Diagnostics *Error) const override
Definition: Marshallers.h:647
bool hasTypedMatcher() const
Determines if the contained matcher can be converted to Matcher<T>.
Definition: VariantValue.h:176
VariantMatcher variadicMatcherDescriptor(StringRef MatcherName, SourceRange NameRange, ArrayRef< ParserValue > Args, Diagnostics *Error)
Variadic marshaller function.
Definition: Marshallers.h:353
bool isSame(ASTNodeKind Other) const
Returns true if this and Other represent the same kind.
Definition: ASTTypeTraits.h:64
bool isPolymorphic() const override
Returns whether the matcher will, given a matcher of any type T, yield a matcher of type T...
Definition: Marshallers.h:691
VariantMatcher(*)(StringRef MatcherName, SourceRange NameRange, ArrayRef< ParserValue > Args, Diagnostics *Error) RunFunc
Definition: Marshallers.h:397
static VariantMatcher SingleMatcher(const DynTypedMatcher &Matcher)
Clones the provided matcher.
bool isBoolean() const
Boolean value functions.
bool isUnsigned() const
Unsigned value functions.
bool isConvertibleTo(ast_type_traits::ASTNodeKind Kind, unsigned *Specificity, ast_type_traits::ASTNodeKind *LeastDerivedKind) const override
Returns whether this matcher is convertible to the given type.
Definition: Marshallers.h:450
static VariantMatcher VariadicOperatorMatcher(DynTypedMatcher::VariadicOperator Op, std::vector< VariantMatcher > Args)
Creates a &#39;variadic&#39; operator matcher.
unsigned getNumArgs() const override
Returns the number of arguments accepted by the matcher if not variadic.
Definition: Marshallers.h:259
VariantMatcher create(SourceRange NameRange, ArrayRef< ParserValue > Args, Diagnostics *Error) const override
Definition: Marshallers.h:252
FixedArgCountMatcherDescriptor(MarshallerType Marshaller, void(*Func)(), StringRef MatcherName, ArrayRef< ast_type_traits::ASTNodeKind > RetKinds, ArrayRef< ArgKind > ArgKinds)
Definition: Marshallers.h:244
Definition: Format.h:2071
Defines the clang::attr::Kind enum.
virtual bool isPolymorphic() const
Returns whether the matcher will, given a matcher of any type T, yield a matcher of type T...
Definition: Marshallers.h:207
VariantMatcher create(SourceRange NameRange, ArrayRef< ParserValue > Args, Diagnostics *Error) const override
Definition: Marshallers.h:572
OverloadedMatcherDescriptor(MutableArrayRef< std::unique_ptr< MatcherDescriptor >> Callbacks)
Definition: Marshallers.h:565
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified...
VariadicOperatorMatcherDescriptor(unsigned MinCount, unsigned MaxCount, VarOp Op, StringRef MatcherName)
Definition: Marshallers.h:642
unsigned getNumArgs() const override
Returns the number of arguments accepted by the matcher if not variadic.
Definition: Marshallers.h:417
void revertErrors()
Revert all errors that happened within this context.
Definition: Diagnostics.cpp:55
bool isVariadic() const override
Returns whether the matcher is variadic.
Definition: Marshallers.h:595
bool isConvertibleTo(ast_type_traits::ASTNodeKind Kind, unsigned *Specificity, ast_type_traits::ASTNodeKind *LeastDerivedKind) const override
Returns whether this matcher is convertible to the given type.
Definition: Marshallers.h:424
A VariantValue instance annotated with its parser context.
Definition: Diagnostics.h:42
return Out str()
CastKind
CastKind - The kind of operation required for a conversion.
std::string getTypeAsString() const
String representation of the type of the value.
bool isRetKindConvertibleTo(ArrayRef< ast_type_traits::ASTNodeKind > RetKinds, ast_type_traits::ASTNodeKind Kind, unsigned *Specificity, ast_type_traits::ASTNodeKind *LeastDerivedKind)
Definition: Marshallers.h:210
unsigned getNumArgs() const override
Returns the number of arguments accepted by the matcher if not variadic.
Definition: Marshallers.h:675
#define bool
Definition: stdbool.h:31
static void build(std::vector< ast_type_traits::ASTNodeKind > &RetTypes)
Definition: Marshallers.h:337
static VariantMatcher matcherMarshall2(void(*Func)(), StringRef MatcherName, SourceRange NameRange, ArrayRef< ParserValue > Args, Diagnostics *Error)
2-arg marshaller function.
Definition: Marshallers.h:514
Diagnostics class to manage error messages.
bool isDouble() const
Double value functions.
VariadicFuncMatcherDescriptor(ast_matchers::internal::VariadicFunction< ResultT, ArgT, F > Func, StringRef MatcherName)
Definition: Marshallers.h:401
AdaptativeOverloadCollector(StringRef Name, std::vector< std::unique_ptr< MatcherDescriptor >> &Out)
Definition: Marshallers.h:536
Helper class to manage error messages.
Definition: Diagnostics.h:50
#define ATTR(X)
ArgStream addError(SourceRange Range, ErrorType Error)
Add an error to the diagnostics.
Definition: Diagnostics.cpp:65
bool isConvertibleTo(ast_type_traits::ASTNodeKind Kind, unsigned *Specificity, ast_type_traits::ASTNodeKind *LeastDerivedKind) const override
Returns whether this matcher is convertible to the given type.
Definition: Marshallers.h:266
Kind
bool isVariadic() const override
Returns whether the matcher is variadic.
Definition: Marshallers.h:674
void getArgKinds(ast_type_traits::ASTNodeKind ThisKind, unsigned ArgNo, std::vector< ArgKind > &Kinds) const override
Given that the matcher is being converted to type ThisKind, append the set of argument types accepted...
Definition: Marshallers.h:261
void getArgKinds(ast_type_traits::ASTNodeKind ThisKind, unsigned ArgNo, std::vector< ArgKind > &Kinds) const override
Given that the matcher is being converted to type ThisKind, append the set of argument types accepted...
Definition: Marshallers.h:615
VariantMatcher create(SourceRange NameRange, ArrayRef< ParserValue > Args, Diagnostics *Error) const override
Definition: Marshallers.h:410
const VariantMatcher & getMatcher() const
Return CK_Trivial when appropriate for VariadicDynCastAllOfMatchers.
Definition: Marshallers.h:439
#define CHECK_ARG_COUNT(count)
Helper macros to check the arguments on all marshaller functions.
Definition: Marshallers.h:473
const std::string & getString() const
bool isVariadic() const override
Returns whether the matcher is variadic.
Definition: Marshallers.h:258
bool isBaseOf(ASTNodeKind Other, unsigned *Distance=nullptr) const
Returns true if this is a base kind of (or same as) Other.
MatcherDescriptor that wraps multiple "overloads" of the same matcher.
Definition: Marshallers.h:563
std::unique_ptr< MatcherDescriptor > makeMatcherAutoMarshall(ReturnType(*Func)(), StringRef MatcherName)
Helper functions to select the appropriate marshaller functions.
Definition: Marshallers.h:706
Dataflow Directional Tag Classes.
bool isConvertibleTo(ast_type_traits::ASTNodeKind Kind, unsigned *Specificity, ast_type_traits::ASTNodeKind *LeastDerivedKind) const override
Returns whether this matcher is convertible to the given type.
Definition: Marshallers.h:682
bool isMatcher() const
Matcher value functions.
std::unique_ptr< DiagnosticConsumer > create(StringRef OutputFile, DiagnosticOptions *Diags, bool MergeChildRecords=false)
Returns a DiagnosticConsumer that serializes diagnostics to a bitcode file.
static VariantMatcher matcherMarshall0(void(*Func)(), StringRef MatcherName, SourceRange NameRange, ArrayRef< ParserValue > Args, Diagnostics *Error)
0-arg marshaller function.
Definition: Marshallers.h:490
bool isNull() const
Whether the matcher is null.
Definition: VariantValue.h:158
static VariantMatcher PolymorphicMatcher(std::vector< DynTypedMatcher > Matchers)
Clones the provided matchers.
VariantMatcher(*)(void(*Func)(), StringRef MatcherName, SourceRange NameRange, ArrayRef< ParserValue > Args, Diagnostics *Error) MarshallerType
Definition: Marshallers.h:236
static void mergePolyMatchers(const PolyMatcher &Poly, std::vector< DynTypedMatcher > &Out, ast_matchers::internal::EmptyTypeList)
Helper methods to extract and merge all possible typed matchers out of the polymorphic object...
Definition: Marshallers.h:284
Helper template class to just from argument type to the right is/get functions in VariantValue...
Definition: Marshallers.h:52
Context for overloaded matcher construction.
Definition: Diagnostics.h:121
#define CHECK_ARG_TYPE(index, type)
Definition: Marshallers.h:480
X
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
Definition: SemaDecl.cpp:13978
void getArgKinds(ast_type_traits::ASTNodeKind ThisKind, unsigned ArgNo, std::vector< ArgKind > &Kinds) const override
Given that the matcher is being converted to type ThisKind, append the set of argument types accepted...
Definition: Marshallers.h:419
DynCastAllOfMatcherDescriptor(ast_matchers::internal::VariadicDynCastAllOfMatcher< BaseT, DerivedT > Func, StringRef MatcherName)
Definition: Marshallers.h:442
static void build(std::vector< ast_type_traits::ASTNodeKind > &RetTypes)
Definition: Marshallers.h:330
#define CAST_OPERATION(Name)
__DEVICE__ int max(int __a, int __b)
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:956
Polymorphic value type.
bool isConvertibleTo(ast_type_traits::ASTNodeKind Kind, unsigned *Specificity, ast_type_traits::ASTNodeKind *LeastDerivedKind) const override
Returns whether this matcher is convertible to the given type.
Definition: Marshallers.h:623
static VariantMatcher outvalueToVariantMatcher(const DynTypedMatcher &Matcher)
Convert the return values of the functions into a VariantMatcher.
Definition: Marshallers.h:301
Helper class used to collect all the possible overloads of an argument adaptative matcher function...
Definition: Marshallers.h:534
unsigned getNumArgs() const override
Returns the number of arguments accepted by the matcher if not variadic.
Definition: Marshallers.h:605
bool isString() const
String value functions.
static VariantMatcher matcherMarshall1(void(*Func)(), StringRef MatcherName, SourceRange NameRange, ArrayRef< ParserValue > Args, Diagnostics *Error)
1-arg marshaller function.
Definition: Marshallers.h:501
void buildReturnTypeVectorFromTypeList(std::vector< ast_type_traits::ASTNodeKind > &RetTypes)
Definition: Marshallers.h:316
bool isVariadic() const override
Returns whether the matcher is variadic.
Definition: Marshallers.h:416