Repository: amaranth-lang/amaranth (python)

Issue:
Wrong normalization for `Const(-16, 4)`
```
>>> Const(-16, 4)
(const 4'sd-16)
```

This const does not fit in 4 bits and should be normalized to 0.

Pull request description:
hdl.ast: fix signed `Const` normalization.
Fixes #805.

Patch:
diff --git a/amaranth/hdl/ast.py b/amaranth/hdl/ast.py
index 33feba7..427293e 100644
--- a/amaranth/hdl/ast.py
+++ b/amaranth/hdl/ast.py
@@ -647,7 +647,7 @@ class Const(Value):
             shape = Shape.cast(shape, src_loc_at=1 + src_loc_at)
         self.width  = shape.width
         self.signed = shape.signed
-        if self.signed and self.value >> (self.width - 1):
+        if self.signed and self.value >> (self.width - 1) & 1:
             self.value |= -(1 << self.width)
         else:
             self.value &= (1 << self.width) - 1


Test patch:
diff --git a/tests/test_hdl_ast.py b/tests/test_hdl_ast.py
index bfec166..b4e93e8 100644
--- a/tests/test_hdl_ast.py
+++ b/tests/test_hdl_ast.py
@@ -369,6 +369,8 @@ class ConstTestCase(FHDLTestCase):
 
     def test_normalization(self):
         self.assertEqual(Const(0b10110, signed(5)).value, -10)
+        self.assertEqual(Const(0b10000, signed(4)).value, 0)
+        self.assertEqual(Const(-16, 4).value, 0)
 
     def test_value(self):
         self.assertEqual(Const(10).value, 10)