hdl.ast: add Value.xor, mapping to $reduce_xor.

Fixes #147.
This commit is contained in:
whitequark 2019-09-13 14:28:43 +00:00
parent b23a9794a4
commit 32310aecad
4 changed files with 23 additions and 0 deletions

View file

@ -135,6 +135,9 @@ class _RHSValueCompiler(_ValueCompiler):
val, = value.operands
mask = (1 << len(val)) - 1
return lambda state: normalize(arg(state) == mask, shape)
if value.op == "r^":
# Believe it or not, this is the fastest way to compute a sideways XOR in Python.
return lambda state: normalize(str(arg(state)).count("1") % 2, shape)
elif len(value.operands) == 2:
lhs, rhs = map(self, value.operands)
if value.op == "+":

View file

@ -157,6 +157,16 @@ class Value(metaclass=ABCMeta):
"""
return Operator("r&", [self])
def xor(self):
"""Compute pairwise exclusive-or of every bit.
Returns
-------
Value, out
``1`` if an odd number of bits are set, ``0`` if an even number of bits are set.
"""
return Operator("r^", [self])
def implies(premise, conclusion):
"""Implication.

View file

@ -259,6 +259,10 @@ class OperatorTestCase(FHDLTestCase):
v = Const(0b101).all()
self.assertEqual(repr(v), "(r& (const 3'd5))")
def test_xor(self):
v = Const(0b101).xor()
self.assertEqual(repr(v), "(r^ (const 3'd5))")
def test_hash(self):
with self.assertRaises(TypeError):
hash(Const(0) + Const(0))

View file

@ -69,6 +69,12 @@ class SimulatorUnitTestCase(FHDLTestCase):
self.assertStatement(stmt, [C(0b01, 2)], C(0))
self.assertStatement(stmt, [C(0b11, 2)], C(1))
def test_xor(self):
stmt = lambda y, a: y.eq(a.xor())
self.assertStatement(stmt, [C(0b00, 2)], C(0))
self.assertStatement(stmt, [C(0b01, 2)], C(1))
self.assertStatement(stmt, [C(0b11, 2)], C(0))
def test_add(self):
stmt = lambda y, a, b: y.eq(a + b)
self.assertStatement(stmt, [C(0, 4), C(1, 4)], C(1, 4))