match.hpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. //
  2. // match.hpp
  3. // case-matcher
  4. //
  5. // Created by Sam Jaffe on 9/10/16.
  6. //
  7. #pragma once
  8. #include <array>
  9. #include <tuple>
  10. namespace matcher {
  11. struct {} any;
  12. using any_t = decltype(any);
  13. template <typename T>
  14. bool operator==(T const &, any_t) { return true; }
  15. }
  16. namespace matcher {
  17. template <typename T, size_t I>
  18. struct any_of_t {
  19. std::array<T, I> options;
  20. };
  21. template <typename T, size_t I>
  22. bool operator==(T const & t, any_of_t<T, I> const & of) {
  23. return std::find(of.options.begin(), of.options.end(), t) != of.options.end();
  24. }
  25. template <typename... Args>
  26. any_of_t<typename std::common_type<Args...>::type, sizeof...(Args)> any_of(Args &&... args) {
  27. return {{args...}};
  28. }
  29. }
  30. namespace matcher {
  31. template <typename Container>
  32. struct any_in_t {
  33. Container options;
  34. };
  35. template <typename T, typename Container>
  36. bool operator==(T const & t, any_in_t<Container> const & of) {
  37. return std::find(of.options.begin(), of.options.end(), t) != of.options.end();
  38. }
  39. template <typename Container>
  40. any_in_t<Container> any_in(Container && args) {
  41. return {args};
  42. }
  43. }
  44. namespace matcher {
  45. template <typename... Args>
  46. struct matcher {
  47. public:
  48. matcher(Args &&... args) : value(std::forward<Args>(args)...) {}
  49. operator bool( ) const { return true; }
  50. bool unmatched( ) const { return ! satisfied; }
  51. template <typename... NArgs>
  52. bool matches(NArgs &&... args) const {
  53. bool const matched = value == std::make_tuple(std::forward<NArgs>(args)...);
  54. satisfied |= matched;
  55. return matched;
  56. }
  57. private:
  58. std::tuple<Args...> value;
  59. mutable bool satisfied = false;
  60. };
  61. template <typename... Args>
  62. matcher<Args...> make_matcher(Args &&... args) {
  63. return matcher<Args...>(std::forward<Args>(args)...);
  64. }
  65. }
  66. #define match( ... ) \
  67. if ( auto const & _matcher_local = \
  68. ::matcher::make_matcher( __VA_ARGS__ ) )
  69. #define with( ... ) \
  70. if ( _matcher_local.unmatched( ) && \
  71. _matcher_local.matches( __VA_ARGS__ ) )
  72. #define else_with( ... ) \
  73. else if ( _matcher_local.matches( __VA_ARGS__ ) )
  74. #define and_with( ... ) \
  75. if ( _matcher_local.matches( __VA_ARGS__ ) )
  76. #define nomatch( ) \
  77. if ( _matcher_local.unmatched( ) )