Skip to content

lib.enum: add .format() implementation. #1320

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
Apr 11, 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
9 changes: 7 additions & 2 deletions amaranth/lib/enum.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
import warnings
import operator

from ..hdl import Value, ValueCastable, Shape, ShapeCastable, Const, SyntaxWarning
from ..hdl._repr import *
from ..hdl import Value, ValueCastable, Shape, ShapeCastable, Const, SyntaxWarning, Format
from ..hdl._repr import Repr, FormatEnum


__all__ = py_enum.__all__ + ["EnumView", "FlagView"]
Expand Down Expand Up @@ -176,6 +176,11 @@ def const(cls, init):
def from_bits(cls, bits):
return cls(bits)

def format(cls, value, format_spec):
if format_spec != "":
raise ValueError(f"Format specifier {format_spec!r} is not supported for enums")
return Format.Enum(value, cls)

def _value_repr(cls, value):
yield Repr(FormatEnum(cls), value)

Expand Down
35 changes: 34 additions & 1 deletion tests/test_sim.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from amaranth.sim import *
from amaranth.lib.memory import Memory
from amaranth.lib.data import View, StructLayout
from amaranth.lib import enum

from .utils import *
from amaranth._utils import _ignore_deprecated
Expand Down Expand Up @@ -1165,7 +1166,7 @@ def process():
Counter: 009
"""))

def test_print(self):
def test_print_str(self):
def enc(s):
return Cat(
Const(b, 8)
Expand Down Expand Up @@ -1196,6 +1197,38 @@ def process():
Counter: non-zero
"""))

def test_print_enum(self):
class MyEnum(enum.Enum, shape=unsigned(2)):
A = 0
B = 1
CDE = 2

sig = Signal(MyEnum)
ctr = Signal(2)
m = Module()
m.d.comb += sig.eq(ctr)
m.d.sync += [
Print(sig),
ctr.eq(ctr + 1),
]
output = StringIO()
with redirect_stdout(output):
with self.assertSimulation(m) as sim:
sim.add_clock(1e-6, domain="sync")
def process():
yield Tick()
yield Tick()
yield Tick()
yield Tick()
sim.add_testbench(process)
self.assertEqual(output.getvalue(), dedent("""\
A
B
CDE
[unknown]
"""))


def test_assert(self):
m = Module()
ctr = Signal(16)
Expand Down