Skip to content

Commit

Permalink
chore: split up and/or and add cython casts
Browse files Browse the repository at this point in the history
  • Loading branch information
cpcloud committed Aug 6, 2024
1 parent 1f32dfa commit d017ee3
Showing 1 changed file with 38 additions and 12 deletions.
50 changes: 38 additions & 12 deletions koerce/patterns.py
Original file line number Diff line number Diff line change
Expand Up @@ -279,12 +279,8 @@ def __or__(self, other: Pattern) -> AnyOf:
-------
New pattern that matches if either of the patterns match.
"""
if isinstance(self, AnyOf) and isinstance(other, AnyOf):
return AnyOf(*self.inners, *other.inners)
elif isinstance(self, AnyOf):
return AnyOf(*self.inners, other)
elif isinstance(other, AnyOf):
return AnyOf(self, *other.inners)
if isinstance(other, AnyOf):
return AnyOf(self, *cython.cast(AnyOf, other).inners)
else:
return AnyOf(self, other)

Expand All @@ -300,12 +296,8 @@ def __and__(self, other: Pattern) -> AllOf:
-------
New pattern that matches if both of the patterns match.
"""
if isinstance(self, AllOf) and isinstance(other, AllOf):
return AllOf(*self.inners, *other.inners)
elif isinstance(self, AllOf):
return AllOf(*self.inners, other)
elif isinstance(other, AllOf):
return AllOf(self, *other.inners)
if isinstance(other, AllOf):
return AllOf(self, *cython.cast(AllOf, other).inners)
else:
return AllOf(self, other)

Expand Down Expand Up @@ -881,6 +873,23 @@ def match(self, value, ctx: Context):
pass
raise NoMatchError()

def __or__(self, other: Pattern) -> AnyOf:
"""Syntax sugar for matching either of the patterns.
Parameters
----------
other
The other pattern to match against.
Returns
-------
New pattern that matches if either of the patterns match.
"""
if isinstance(other, AnyOf):
return AnyOf(*self.inners, *cython.cast(AnyOf, other).inners)
else:
return AnyOf(*self.inners, other)


@cython.final
@cython.cclass
Expand All @@ -903,6 +912,23 @@ def match(self, value, ctx: Context):
value = inner.match(value, ctx)
return value

def __and__(self, other: Pattern) -> AllOf:
"""Syntax sugar for matching both of the patterns.
Parameters
----------
other
The other pattern to match against.
Returns
-------
New pattern that matches if both of the patterns match.
"""
if isinstance(other, AllOf):
return AllOf(*self.inners, *cython.cast(AllOf, other).inners)
else:
return AllOf(*self.inners, other)


def NoneOf(*args) -> Pattern:
"""Match none of the passed patterns."""
Expand Down

0 comments on commit d017ee3

Please sign in to comment.