Skip to content

Implement RFC 42: Const from shape-castable. #1063

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 6, 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
11 changes: 9 additions & 2 deletions amaranth/hdl/_ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -701,8 +701,15 @@ def _rhs_signals(self):
raise NotImplementedError # :nocov:


class _ConstMeta(ABCMeta):
def __call__(cls, value, shape=None, src_loc_at=0, **kwargs):
if isinstance(shape, ShapeCastable):
return shape.const(value)
return super().__call__(value, shape, **kwargs, src_loc_at=src_loc_at + 1)


@final
class Const(Value):
class Const(Value, metaclass=_ConstMeta):
"""A constant, literal integer value.

Parameters
Expand Down Expand Up @@ -760,7 +767,7 @@ def __init__(self, value, shape=None, *, src_loc_at=0):
"shape {!r}; this is likely an off-by-one error"
.format(self.value, shape),
category=SyntaxWarning,
stacklevel=2)
stacklevel=3)
shape = Shape.cast(shape, src_loc_at=1 + src_loc_at)
self.width = shape.width
self.signed = shape.signed
Expand Down
19 changes: 19 additions & 0 deletions tests/test_hdl_ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -467,6 +467,25 @@ def test_hash(self):
with self.assertRaises(TypeError):
hash(Const(0))

def test_shape_castable(self):
class MockConstValue:
def __init__(self, value):
self.value = value

class MockConstShape(ShapeCastable):
def as_shape(self):
return unsigned(8)

def __call__(self, value):
return value

def const(self, init):
return MockConstValue(init)

s = Const(10, MockConstShape())
self.assertIsInstance(s, MockConstValue)
self.assertEqual(s.value, 10)


class OperatorTestCase(FHDLTestCase):
def test_bool(self):
Expand Down