Skip to content

Commit c59447c

Browse files
wanda-phiwhitequark
authored andcommitted
hdl._ast: make Signal.like work properly with ShapeCastables.
Fixes #1285.
1 parent 0be2dda commit c59447c

File tree

2 files changed

+20
-6
lines changed

2 files changed

+20
-6
lines changed

amaranth/hdl/_ast.py

+11-6
Original file line numberDiff line numberDiff line change
@@ -2177,13 +2177,14 @@ def like(cls, other, *, name=None, name_suffix=None, init=None, reset=None, src_
21772177
21782178
Parameters
21792179
----------
2180-
other : Value
2180+
other : ValueLike
21812181
Object to base this Signal on.
21822182
"""
2183+
cast_other = Value.cast(other)
21832184
if name is not None:
21842185
new_name = str(name)
21852186
elif name_suffix is not None:
2186-
new_name = other.name + str(name_suffix)
2187+
new_name = cast_other.name + str(name_suffix)
21872188
else:
21882189
new_name = tracer.get_var_name(depth=2 + src_loc_at, default="$like")
21892190
# TODO(amaranth-0.7): remove
@@ -2196,11 +2197,15 @@ def like(cls, other, *, name=None, name_suffix=None, init=None, reset=None, src_
21962197
if isinstance(other, ValueCastable):
21972198
shape = other.shape()
21982199
else:
2199-
shape = Value.cast(other).shape()
2200+
shape = cast_other.shape()
22002201
kw = dict(shape=shape, name=new_name)
2201-
if isinstance(other, Signal):
2202-
kw.update(init=other.init, reset_less=other.reset_less,
2203-
attrs=other.attrs, decoder=other.decoder)
2202+
if isinstance(cast_other, Signal):
2203+
if isinstance(shape, ShapeCastable):
2204+
other_init = shape.from_bits(cast_other.init)
2205+
else:
2206+
other_init = cast_other.init
2207+
kw.update(init=other_init, reset_less=cast_other.reset_less,
2208+
attrs=cast_other.attrs, decoder=cast_other.decoder)
22042209
kw.update(kwargs)
22052210
if init is not None:
22062211
kw["init"] = init

tests/test_lib_data.py

+9
Original file line numberDiff line numberDiff line change
@@ -641,6 +641,15 @@ def test_signal_like(self):
641641
s1 = Signal(data.StructLayout({"a": unsigned(1)}))
642642
s2 = Signal.like(s1)
643643
self.assertEqual(s2.shape(), data.StructLayout({"a": unsigned(1)}))
644+
s3 = Signal.like(s1, name_suffix="a")
645+
self.assertEqual(s3.as_value().name, "s1a")
646+
647+
s4 = Signal(data.StructLayout({"a": unsigned(2), "b": unsigned(3)}), init={"a": 1}, reset_less=True, attrs={"x": "y"})
648+
s5 = Signal.like(s4)
649+
self.assertEqual(s5.as_value().init, 0b00001)
650+
self.assertEqual(s5.as_value().reset_less, True)
651+
self.assertEqual(s5.as_value().attrs, {"x": "y"})
652+
644653

645654
def test_bug_837_array_layout_getitem_str(self):
646655
with self.assertRaisesRegex(TypeError,

0 commit comments

Comments
 (0)