Marshallers.h 27 KB

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