|
| 1 | +from typing import (Callable as _Callable, |
| 2 | + cast as _cast, |
| 3 | + Generic as _Generic, |
| 4 | + Iterable as _Iterable, |
| 5 | + Type as _Type, |
| 6 | + TypeVar as _TypeVar) |
| 7 | + |
| 8 | +__all__ = ['Matcher', 'MatchError'] |
| 9 | + |
| 10 | +_S = _TypeVar('_S') |
| 11 | +_T = _TypeVar('_T') |
| 12 | +_U = _TypeVar('_U') |
| 13 | + |
| 14 | + |
| 15 | +class MatchError(LookupError): |
| 16 | + """ |
| 17 | + An error raised when a match call exhausts all matchers without |
| 18 | + finding a match. |
| 19 | + """ |
| 20 | + pass |
| 21 | + |
| 22 | + |
| 23 | +class _Case(_Generic[_S, _T]): |
| 24 | + def __init__(self, |
| 25 | + matcher: _Callable[[_S], bool], |
| 26 | + actions: _Iterable[_Callable[[_S], _T]]) -> None: |
| 27 | + self._matcher = matcher |
| 28 | + self._actions = actions |
| 29 | + |
| 30 | + def matches(self, value: _S) -> bool: |
| 31 | + return self._matcher(value) |
| 32 | + |
| 33 | + def result(self, value: _S) -> _T: |
| 34 | + returnValue = None # type: _T |
| 35 | + for action in self._actions: |
| 36 | + returnValue = action(value) |
| 37 | + return returnValue |
| 38 | + |
| 39 | + |
| 40 | +class Matcher(_Generic[_S, _T]): |
| 41 | + @staticmethod |
| 42 | + def match(value: _S, matchers: _Iterable[_Case[_S, _T]]) -> _T: |
| 43 | + for matcher in matchers: |
| 44 | + if matcher.matches(value): |
| 45 | + return matcher.result(value) |
| 46 | + raise MatchError("{} doesn't match any of the " |
| 47 | + "provided clauses".format(value)) |
| 48 | + |
| 49 | + @staticmethod |
| 50 | + def Value(key: _S, *actions: _Callable[[_S], _T]) -> _Case[_S, _T]: |
| 51 | + return _Case(lambda value: value == key, actions) |
| 52 | + |
| 53 | + @staticmethod |
| 54 | + def Values(keys: _Iterable[_S], *actions: _Callable[[_S], _T]) -> _Case[_S, _T]: |
| 55 | + return _Case(lambda value: any(value == key for key in keys), actions) |
| 56 | + |
| 57 | + @staticmethod |
| 58 | + def Type(typ: _Type[_U], *actions: _Callable[[_U], _T]) -> _Case[_S, _T]: |
| 59 | + def castWrapper(action: _Callable[[_U], _T]) -> _Callable[[_S], _T]: |
| 60 | + return lambda value: action(_cast(_U, value)) |
| 61 | + |
| 62 | + return _Case(lambda value: isinstance(value, typ), |
| 63 | + map(castWrapper, actions)) |
| 64 | + |
| 65 | + @staticmethod |
| 66 | + def Else(*actions: _Callable[[_S], _T]) -> _Case[_S, _T]: |
| 67 | + return _Case(lambda value: True, actions) |
0 commit comments