Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions amaranth/hdl/_ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -2294,8 +2294,14 @@ def __init__(self, test, cases, *, src_loc=None, src_loc_at=0, case_src_locs={})
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))
Expand Down
10 changes: 10 additions & 0 deletions tests/test_hdl_ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -1473,6 +1473,16 @@ def test_int_neg_case(self):
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",): []})
Expand Down