hdl._ast: fix using 0-width Switch with integer keys.

This comes up in `AssignmentLegalizer`-produced `Switch`es for
`ArrayProxy`.
This commit is contained in:
Wanda 2024-02-13 23:48:59 +01:00 committed by Catherine
parent 0ecd06a7e5
commit 5ffb48b5fb
2 changed files with 16 additions and 0 deletions

View file

@ -2294,8 +2294,14 @@ class Switch(Statement):
key = "".join(key.split()) # remove whitespace
elif isinstance(key, int):
key = format(key & key_mask, "b").rjust(len(self.test), "0")
# fixup for 0-width test
if key_mask == 0:
key = ""
elif isinstance(key, Enum):
key = format(key.value & key_mask, "b").rjust(len(self.test), "0")
# fixup for 0-width test
if key_mask == 0:
key = ""
else:
raise TypeError("Object {!r} cannot be used as a switch key"
.format(key))

View file

@ -1473,6 +1473,16 @@ class SwitchTestCase(FHDLTestCase):
s = Switch(Const(0, 8), {-10: []})
self.assertEqual(s.cases, {("11110110",): []})
def test_int_zero_width(self):
s = Switch(Const(0, 0), {0: []})
self.assertEqual(s.cases, {("",): []})
def test_int_zero_width_enum(self):
class ZeroEnum(Enum):
A = 0
s = Switch(Const(0, 0), {ZeroEnum.A: []})
self.assertEqual(s.cases, {("",): []})
def test_enum_case(self):
s = Switch(Const(0, UnsignedEnum), {UnsignedEnum.FOO: []})
self.assertEqual(s.cases, {("01",): []})