From: Stuart Olsen Date: Sun, 15 Mar 2020 05:22:03 +0000 (-0700) Subject: back.pysim: implement modulus operator. X-Git-Url: https://git.libre-soc.org/?a=commitdiff_plain;h=732ccd4c4cf54c5d490de42c272520c79d9958f8;p=nmigen.git back.pysim: implement modulus operator. --- diff --git a/nmigen/back/pysim.py b/nmigen/back/pysim.py index 5d599a3..96e98e7 100644 --- a/nmigen/back/pysim.py +++ b/nmigen/back/pysim.py @@ -363,6 +363,7 @@ class _ValueCompiler(ValueVisitor, _Compiler): helpers = { "sign": lambda value, sign: value | sign if value & sign else value, "zdiv": lambda lhs, rhs: 0 if rhs == 0 else lhs // rhs, + "zmod": lambda lhs, rhs: 0 if rhs == 0 else lhs % rhs, } def on_ClockSignal(self, value): @@ -448,6 +449,8 @@ class _RHSValueCompiler(_ValueCompiler): return f"({sign(lhs)} * {sign(rhs)})" if value.operator == "//": return f"zdiv({sign(lhs)}, {sign(rhs)})" + if value.operator == "%": + return f"zmod({sign(lhs)}, {sign(rhs)})" if value.operator == "&": return f"({self(lhs)} & {self(rhs)})" if value.operator == "|": diff --git a/nmigen/test/test_sim.py b/nmigen/test/test_sim.py index d3585a4..677f257 100644 --- a/nmigen/test/test_sim.py +++ b/nmigen/test/test_sim.py @@ -110,6 +110,13 @@ class SimulatorUnitTestCase(FHDLTestCase): self.assertStatement(stmt, [C(2, 4), C(2, 4)], C(1, 8)) self.assertStatement(stmt, [C(7, 4), C(2, 4)], C(3, 8)) + def test_mod(self): + stmt = lambda y, a, b: y.eq(a % b) + self.assertStatement(stmt, [C(2, 4), C(0, 4)], C(0, 8)) + self.assertStatement(stmt, [C(2, 4), C(1, 4)], C(0, 8)) + self.assertStatement(stmt, [C(2, 4), C(2, 4)], C(0, 8)) + self.assertStatement(stmt, [C(7, 4), C(2, 4)], C(1, 8)) + def test_and(self): stmt = lambda y, a, b: y.eq(a & b) self.assertStatement(stmt, [C(0b1100, 4), C(0b1010, 4)], C(0b1000, 4))