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