From 732ccd4c4cf54c5d490de42c272520c79d9958f8 Mon Sep 17 00:00:00 2001 From: Stuart Olsen Date: Sat, 14 Mar 2020 22:22:03 -0700 Subject: [PATCH] back.pysim: implement modulus operator. --- nmigen/back/pysim.py | 3 +++ nmigen/test/test_sim.py | 7 +++++++ 2 files changed, 10 insertions(+) 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)) -- 2.30.2