Skip to content

Commit 09854fa

Browse files
wanda-phiwhitequark
authored andcommitted
hdl.ast: make it impossible to construct *Castable instances.
Fixes #1072.
1 parent ace7aea commit 09854fa

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

amaranth/hdl/_ast.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,12 @@ class ShapeCastable:
191191
The source code of the :mod:`amaranth.lib.data` module can be used as a reference for
192192
implementing a fully featured shape-castable object.
193193
"""
194+
195+
def __init__(self, *args, **kwargs):
196+
if type(self) is ShapeCastable:
197+
raise TypeError("Can't instantiate abstract class ShapeCastable")
198+
super().__init__(*args, **kwargs)
199+
194200
def __init_subclass__(cls, **kwargs):
195201
if cls.as_shape is ShapeCastable.as_shape:
196202
raise TypeError(f"Class '{cls.__name__}' deriving from 'ShapeCastable' must override "
@@ -1616,6 +1622,12 @@ class ValueCastable:
16161622
from :class:`ValueCastable` is mutable, it is up to the user to ensure that it is not mutated
16171623
in a way that changes its representation after the first call to :meth:`as_value`.
16181624
"""
1625+
1626+
def __init__(self, *args, **kwargs):
1627+
if type(self) is ValueCastable:
1628+
raise TypeError("Can't instantiate abstract class ValueCastable")
1629+
super().__init__(*args, **kwargs)
1630+
16191631
def __init_subclass__(cls, **kwargs):
16201632
if not hasattr(cls, "as_value"):
16211633
raise TypeError(f"Class '{cls.__name__}' deriving from `ValueCastable` must override "

tests/test_hdl_ast.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,11 @@ def test_recurse(self):
191191
sc = MockShapeCastable(MockShapeCastable(unsigned(1)))
192192
self.assertEqual(Shape.cast(sc), unsigned(1))
193193

194+
def test_abstract(self):
195+
with self.assertRaisesRegex(TypeError,
196+
r"^Can't instantiate abstract class ShapeCastable$"):
197+
ShapeCastable()
198+
194199

195200
class ShapeLikeTestCase(FHDLTestCase):
196201
def test_construct(self):
@@ -1400,6 +1405,11 @@ def test_recurse(self):
14001405
vc = MockValueCastable(MockValueCastable(Signal()))
14011406
self.assertIsInstance(Value.cast(vc), Signal)
14021407

1408+
def test_abstract(self):
1409+
with self.assertRaisesRegex(TypeError,
1410+
r"^Can't instantiate abstract class ValueCastable$"):
1411+
ValueCastable()
1412+
14031413

14041414
class ValueLikeTestCase(FHDLTestCase):
14051415
def test_construct(self):

0 commit comments

Comments
 (0)