hdl.ast: add Value.{as_signed,as_unsigned}.

Before this commit, there was no way to do so besides creating and
assigning an intermediate signal, which could not be extracted into
a helper function due to Module statefulness.

Fixes #292.
This commit is contained in:
whitequark 2020-02-06 18:27:55 +00:00
parent 9301e31b69
commit 27b47faf16
5 changed files with 51 additions and 0 deletions

View file

@ -239,6 +239,26 @@ class Value(metaclass=ABCMeta):
else:
raise TypeError("Cannot index value with {}".format(repr(key)))
def as_unsigned(self):
"""Conversion to unsigned.
Returns
-------
Value, out
This ``Value`` reinterpreted as a unsigned integer.
"""
return Operator("u", [self])
def as_signed(self):
"""Conversion to signed.
Returns
-------
Value, out
This ``Value`` reinterpreted as a signed integer.
"""
return Operator("s", [self])
def bool(self):
"""Conversion to boolean.
@ -552,6 +572,10 @@ class Operator(Value):
return Shape(a_width + 1, True)
if self.operator in ("b", "r|", "r&", "r^"):
return Shape(1, False)
if self.operator == "u":
return Shape(a_width, False)
if self.operator == "s":
return Shape(a_width, True)
elif len(op_shapes) == 2:
(a_width, a_signed), (b_width, b_signed) = op_shapes
if self.operator in ("+", "-"):