From 7342662bee8017609d3fe14ff0966b7fb1c232ac Mon Sep 17 00:00:00 2001 From: whitequark Date: Tue, 10 Sep 2019 07:25:28 +0000 Subject: [PATCH] hdl.ast: warn if reset value is truncated. Fixes #183. --- nmigen/hdl/ast.py | 8 ++++++++ nmigen/test/test_hdl_ast.py | 11 +++++++++++ 2 files changed, 19 insertions(+) diff --git a/nmigen/hdl/ast.py b/nmigen/hdl/ast.py index 0afa5d9..56671ed 100644 --- a/nmigen/hdl/ast.py +++ b/nmigen/hdl/ast.py @@ -665,6 +665,14 @@ class Signal(Value, DUID): if not isinstance(self.nbits, int) or self.nbits < 0: raise TypeError("Width must be a non-negative integer, not '{!r}'".format(self.nbits)) + + reset_nbits = bits_for(reset, self.signed) + if reset != 0 and reset_nbits > self.nbits: + warnings.warn("Reset value {!r} requires {} bits to represent, but the signal " + "only has {} bits" + .format(reset, reset_nbits, self.nbits), + SyntaxWarning, stacklevel=2 + src_loc_at) + self.reset = int(reset) self.reset_less = bool(reset_less) diff --git a/nmigen/test/test_hdl_ast.py b/nmigen/test/test_hdl_ast.py index 1fd70aa..9ad4d32 100644 --- a/nmigen/test/test_hdl_ast.py +++ b/nmigen/test/test_hdl_ast.py @@ -510,6 +510,17 @@ class SignalTestCase(FHDLTestCase): self.assertEqual(s1.reset, 0b111) self.assertEqual(s1.reset_less, True) + def test_reset_narrow(self): + with self.assertWarns(SyntaxWarning, + msg="Reset value 8 requires 4 bits to represent, but the signal only has 3 bits"): + Signal(3, reset=8) + with self.assertWarns(SyntaxWarning, + msg="Reset value 4 requires 4 bits to represent, but the signal only has 3 bits"): + Signal((3, True), reset=4) + with self.assertWarns(SyntaxWarning, + msg="Reset value -5 requires 4 bits to represent, but the signal only has 3 bits"): + Signal((3, True), reset=-5) + def test_attrs(self): s1 = Signal() self.assertEqual(s1.attrs, {}) -- 2.30.2