| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113 |
- //
- // match.hpp
- // case-matcher
- //
- // Created by Sam Jaffe on 9/10/16.
- //
- #pragma once
- #include <array>
- #include <tuple>
- namespace matcher {
- struct {} any;
- using any_t = decltype(any);
-
- template <typename T>
- bool operator==(T const &, any_t) { return true; }
- }
- namespace matcher {
- template <typename T, size_t I>
- struct any_of_t {
- std::array<T, I> options;
- };
-
- template <typename T, size_t I>
- bool operator==(T const & t, any_of_t<T, I> const & of) {
- return std::find(of.options.begin(), of.options.end(), t) != of.options.end();
- }
-
- template <typename... Args>
- any_of_t<typename std::common_type<Args...>::type, sizeof...(Args)> any_of(Args &&... args) {
- return {{args...}};
- }
- }
- namespace matcher {
- template <typename Container>
- struct any_in_t {
- Container options;
- };
-
- template <typename T, typename Container>
- bool operator==(T const & t, any_in_t<Container> const & of) {
- return std::find(of.options.begin(), of.options.end(), t) != of.options.end();
- }
-
- template <typename Container>
- any_in_t<Container> any_in(Container && args) {
- return {args};
- }
- }
- namespace matcher {
- template <typename Pred>
- struct predicate_t {
- Pred predicate;
- };
-
- template <typename T, typename Pred>
- bool operator==(T const & t, predicate_t<Pred> const & of) {
- return of.predicate(t);
- }
-
- template <typename Pred>
- predicate_t<Pred> matches(Pred && args) {
- return {args};
- }
- }
- namespace matcher {
- template <typename... Args>
- struct matcher {
- public:
- matcher(Args &&... args) : value(std::forward<Args>(args)...) {}
-
- operator bool( ) const { return true; }
- bool unmatched( ) const { return ! satisfied; }
-
- template <typename... NArgs>
- bool matches(NArgs &&... args) const {
- bool const matched = value == std::make_tuple(std::forward<NArgs>(args)...);
- satisfied |= matched;
- return matched;
- }
- private:
- std::tuple<Args...> value;
- mutable bool satisfied = false;
- };
-
- template <typename... Args>
- matcher<Args...> make_matcher(Args &&... args) {
- return matcher<Args...>(std::forward<Args>(args)...);
- }
- }
- #define match( ... ) \
- if ( auto const & _matcher_local = \
- ::matcher::make_matcher( __VA_ARGS__ ) )
- #define with( ... ) \
- if ( _matcher_local.unmatched( ) && \
- _matcher_local.matches( __VA_ARGS__ ) )
- #define else_with( ... ) \
- else if ( _matcher_local.matches( __VA_ARGS__ ) )
- #define and_with( ... ) \
- if ( _matcher_local.matches( __VA_ARGS__ ) )
- #define nomatch( ) \
- if ( _matcher_local.unmatched( ) )
|