lib.enum: allow empty enums.

This commit is contained in:
Charlotte 2023-07-02 21:39:10 +10:00 committed by Catherine
parent e6d8d5a354
commit 7e438180e0
2 changed files with 10 additions and 12 deletions

View file

@ -112,16 +112,11 @@ class EnumMeta(ShapeCastable, py_enum.EnumMeta):
if hasattr(cls, "_amaranth_shape_"):
# Shape was provided explicitly; return it.
return cls._amaranth_shape_
elif cls.__members__:
# Shape was not provided explicitly, but enumeration has members; treat it
# the same way `Shape.cast` treats standard library enumerations, so that
# `amaranth.lib.enum.Enum` can be a drop-in replacement for `enum.Enum`.
return Shape._cast_plain_enum(cls)
else:
# Shape was not provided explicitly, and enumeration has no members.
# This is a base or mixin class that cannot be instantiated directly.
raise TypeError("Enumeration '{}.{}' does not have a defined shape"
.format(cls.__module__, cls.__qualname__))
# Shape was not provided explicitly; treat it the same way `Shape.cast` treats
# standard library enumerations, so that `amaranth.lib.enum.Enum` can be a drop-in
# replacement for `enum.Enum`.
return Shape._cast_plain_enum(cls)
def __call__(cls, value):
# :class:`py_enum.Enum` uses ``__call__()`` for type casting: ``E(x)`` returns

View file

@ -1,3 +1,5 @@
import enum as py_enum
from amaranth import *
from amaranth.lib.enum import Enum
@ -21,9 +23,10 @@ class EnumTestCase(FHDLTestCase):
def test_shape_no_members(self):
class EnumA(Enum):
pass
with self.assertRaisesRegex(TypeError,
r"^Enumeration '.+?\.EnumA' does not have a defined shape$"):
Shape.cast(EnumA)
class PyEnumA(py_enum.Enum):
pass
self.assertEqual(Shape.cast(EnumA), unsigned(0))
self.assertEqual(Shape.cast(PyEnumA), unsigned(0))
def test_shape_explicit(self):
class EnumA(Enum, shape=signed(2)):