Skip to content

Commit

Permalink
Use pattern matching
Browse files Browse the repository at this point in the history
  • Loading branch information
tekknolagi committed Jul 24, 2024
1 parent 90e1a48 commit 1dd285a
Showing 1 changed file with 12 additions and 6 deletions.
18 changes: 12 additions & 6 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@ def _set_forwarded(self, value):


class Operation(Value):
__match_args__ = ("name", "args")

def __init__(self, name: str, args: list[Value]):
self.name = name
self.args = args
self._args = args
self.forwarded = None

def __repr__(self):
Expand All @@ -31,10 +33,14 @@ def find(self) -> Value:
op = next
return op

@property
def args(self):
return tuple(arg.find() for arg in self._args)

def arg(self, index):
# change to above: return the
# representative of argument 'index'
return self.args[index].find()
return self._args[index].find()

def make_equal_to(self, value: Value):
# this is "union" in the union-find sense,
Expand All @@ -51,6 +57,8 @@ def _set_forwarded(self, value: Value):


class Constant(Value):
__match_args__ = ("value",)

def __init__(self, value: Any):
self.value = value

Expand Down Expand Up @@ -187,10 +195,8 @@ def parity_of(value):
result = Block()
for op in block:
# Try to simplify
if isinstance(op, Operation) and op.name == "bitand":
arg = op.arg(0)
mask = op.arg(1)
if isinstance(mask, Constant) and mask.value == 1:
match op:
case Operation("bitand", [arg, Constant(1)]) | Operation("bitand", [Constant(1), arg]):
if parity_of(arg) is EVEN:
op.make_equal_to(Constant(0))
continue
Expand Down

0 comments on commit 1dd285a

Please sign in to comment.