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