Repository: phanrahan/magma (language: python)

Issue:
[Types] Add fill (with 0 or 1) function for all types



Discussion / hints:

Fix patch:
diff --git a/magma/__init__.py b/magma/__init__.py
index 22ea0b7d1..275bbb5a5 100644
--- a/magma/__init__.py
+++ b/magma/__init__.py
@@ -119,6 +119,7 @@ def set_mantle_target(t):
 from magma.compile import MagmaCompileException
 from magma.linking import link_module, link_default_module, clear_link_info
 import magma.math
+from magma.value_utils import fill
 
 ################################################################################
 # BEGIN ALIASES
diff --git a/magma/value_utils.py b/magma/value_utils.py
index 9c745c176..4941fa349 100644
--- a/magma/value_utils.py
+++ b/magma/value_utils.py
@@ -103,3 +103,20 @@ def _make_selector_impl(value, child):
 
 def make_selector(value):
     return _make_selector_impl(value, None)
+
+
+class _FillVisitor(ValueVisitor):
+    def __init__(self, fill_value: bool):
+        self._fill_value = fill_value
+
+    def visit_Digital(self, value):
+        value @= self._fill_value
+
+    def visit_Bits(self, value):
+        size = len(value)
+        fill_value = 0 if not self._fill_value else (1 << size) - 1
+        value @= fill_value
+
+
+def fill(value, fill_value: bool):
+    _FillVisitor(fill_value).visit(value)


Test patch:
diff --git a/tests/test_value_utils.py b/tests/test_value_utils.py
index bbaeae784..7cad99c2b 100644
--- a/tests/test_value_utils.py
+++ b/tests/test_value_utils.py
@@ -1,6 +1,13 @@
+import pytest
+
 import magma as m
-from magma.value_utils import (ValueVisitor, ArraySelector, TupleSelector,
-                               make_selector)
+from magma.value_utils import (
+    ValueVisitor,
+    ArraySelector,
+    TupleSelector,
+    make_selector,
+    fill,
+)
 
 
 class _Prod(m.Product):
@@ -67,3 +74,26 @@ class _Foo(m.Circuit):
 
     assert str(selector) == "[0].x[0]"
     assert selector.select(_Foo.I) is _Foo.I[0].x[0]
+
+
+@pytest.mark.parametrize("fill_value", (True, False))
+def test_fill(fill_value):
+    S = m.AnonProduct[{"x": m.Bits[8], "y": m.Bit}]
+    T = m.AnonProduct[{"s": S, "u": m.Array[4, m.Bits[6]]}]
+
+    t = T()
+    fill(t, fill_value)
+
+    value = t.value()
+    assert value is not None
+
+    assert value.s.const()
+    assert value.s.x.const()
+    assert value.s.y.const()
+    assert int(value.s.x) == (0 if not fill_value else 255)
+    assert int(value.s.y) == (0 if not fill_value else 1)
+
+    assert value.u.const()
+    for u_i in value.u:
+        assert u_i.const()
+        assert int(u_i) == (0 if not fill_value else 63)