lib.enum: accept any const-castable expression as member value.

This behavior was introduced by amaranth-lang/rfcs#4. See #755.
This commit is contained in:
Catherine 2023-05-12 14:47:21 +00:00
parent bf8bbb0f63
commit 4398575322
4 changed files with 69 additions and 24 deletions

View file

@ -282,30 +282,25 @@ Constant-castable objects are accepted anywhere a constant integer is accepted.
.. doctest::
>>> Const.cast(Cat(Direction.TOP, Direction.LEFT))
(const 4'd4)
>>> Const.cast(Cat(C(10, 4), C(1, 2)))
(const 6'd26)
.. TODO: uncomment when this actually works
They may be used in enumeration members, provided the enumeration inherits from :class:`amaranth.lib.enum.Enum`:
.. comment::
.. testcode::
They may be used in enumeration members:
class Funct(amaranth.lib.enum.Enum, shape=4):
ADD = 0
...
.. testcode::
class Funct(enum.Enum):
ADD = 0
...
class Op(enum.Enum):
REG = 0
IMM = 1
class Instr(enum.Enum):
ADD = Cat(Funct.ADD, Op.REG)
ADDI = Cat(Funct.ADD, Op.IMM)
...
class Op(amaranth.lib.enum.Enum, shape=1):
REG = 0
IMM = 1
class Instr(amaranth.lib.enum.Enum, shape=5):
ADD = Cat(Funct.ADD, Op.REG)
ADDI = Cat(Funct.ADD, Op.IMM)
...
.. note::

View file

@ -15,16 +15,36 @@ A shape can be specified for an enumeration with the ``shape=`` keyword argument
from amaranth.lib import enum
class Funct4(enum.Enum, shape=4):
class Funct(enum.Enum, shape=4):
ADD = 0
SUB = 1
MUL = 2
.. doctest::
>>> Shape.cast(Funct4)
>>> Shape.cast(Funct)
unsigned(4)
Any :ref:`constant-castable <lang-constcasting>` expression can be used as the value of a member:
.. testcode::
class Op(enum.Enum, shape=1):
REG = 0
IMM = 1
class Instr(enum.Enum, shape=5):
ADD = Cat(Funct.ADD, Op.REG)
ADDI = Cat(Funct.ADD, Op.IMM)
SUB = Cat(Funct.SUB, Op.REG)
SUBI = Cat(Funct.SUB, Op.IMM)
...
.. doctest::
>>> Instr.SUBI
<Instr.SUBI: 17>
This module is a drop-in replacement for the standard :mod:`enum` module, and re-exports all of its members (not just the ones described below). In an Amaranth project, all ``import enum`` statements may be replaced with ``from amaranth.lib import enum``.