From df70aae887e6e3a06df0044b419eb40674543c18 Mon Sep 17 00:00:00 2001 From: whitequark Date: Thu, 22 Oct 2020 16:08:38 +0000 Subject: [PATCH] sim._pyrtl: sign extend RHS of assignment. Fixes #502. --- nmigen/sim/_pyrtl.py | 5 ++++- tests/test_sim.py | 5 +++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/nmigen/sim/_pyrtl.py b/nmigen/sim/_pyrtl.py index d7b4326..f7abc3b 100644 --- a/nmigen/sim/_pyrtl.py +++ b/nmigen/sim/_pyrtl.py @@ -337,7 +337,10 @@ class _StatementCompiler(StatementVisitor, _Compiler): self.emitter.append("pass") def on_Assign(self, stmt): - return self.lhs(stmt.lhs)(self.rhs(stmt.rhs)) + gen_rhs = f"({(1 << len(stmt.rhs)) - 1} & {self.rhs(stmt.rhs)})" + if stmt.rhs.shape().signed: + gen_rhs = f"sign({gen_rhs}, {-1 << (len(stmt.rhs) - 1)})" + return self.lhs(stmt.lhs)(gen_rhs) def on_Switch(self, stmt): gen_test = self.emitter.def_var("test", diff --git a/tests/test_sim.py b/tests/test_sim.py index bb806f2..d2d255f 100644 --- a/tests/test_sim.py +++ b/tests/test_sim.py @@ -67,6 +67,11 @@ class SimulatorUnitTestCase(FHDLTestCase): self.assertStatement(stmt, [C(0b01, unsigned(2)), C(0b0001, signed(4))], C(1)) self.assertStatement(stmt, [C(0b11, unsigned(2)), C(0b1111, signed(4))], C(1)) + def test_as_signed_issue_502(self): + stmt = lambda y, a: y.eq(a.as_signed()) + self.assertStatement(stmt, [C(0b01, unsigned(2))], C(0b0001, signed(4))) + self.assertStatement(stmt, [C(0b11, unsigned(2))], C(0b1111, signed(4))) + def test_any(self): stmt = lambda y, a: y.eq(a.any()) self.assertStatement(stmt, [C(0b00, 2)], C(0)) -- 2.30.2