8 from contextlib
import contextmanager
10 from nmigen
.hdl
.ast
import *
11 from nmigen
.hdl
.ir
import *
12 from nmigen
.back
import rtlil
13 from nmigen
._toolchain
import require_tool
16 __all__
= ["FHDLTestCase"]
19 class FHDLTestCase(unittest
.TestCase
):
20 def assertRepr(self
, obj
, repr_str
):
21 if isinstance(obj
, list):
22 obj
= Statement
.cast(obj
)
23 def prepare_repr(repr_str
):
24 repr_str
= re
.sub(r
"\s+", " ", repr_str
)
25 repr_str
= re
.sub(r
"\( (?=\()", "(", repr_str
)
26 repr_str
= re
.sub(r
"\) (?=\))", ")", repr_str
)
27 return repr_str
.strip()
28 self
.assertEqual(prepare_repr(repr(obj
)), prepare_repr(repr_str
))
30 def assertFormal(self
, spec
, mode
="bmc", depth
=1):
31 caller
, *_
= traceback
.extract_stack(limit
=2)
32 spec_root
, _
= os
.path
.splitext(caller
.filename
)
33 spec_dir
= os
.path
.dirname(spec_root
)
34 spec_name
= "{}_{}".format(
35 os
.path
.basename(spec_root
).replace("test_", "spec_"),
36 caller
.name
.replace("test_", "")
39 # The sby -f switch seems not fully functional when sby is reading from stdin.
40 if os
.path
.exists(os
.path
.join(spec_dir
, spec_name
)):
41 shutil
.rmtree(os
.path
.join(spec_dir
, spec_name
))
44 # A mix of BMC and k-induction, as per personal communication with Claire Wolf.
45 script
= "setattr -unset init w:* a:nmigen.sample_reg %d"
50 config
= textwrap
.dedent("""\
70 rtlil
=rtlil
.convert(Fragment
.get(spec
, platform
="formal"))
72 with subprocess
.Popen([require_tool("sby"), "-f", "-d", spec_name
], cwd
=spec_dir
,
73 universal_newlines
=True,
74 stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
) as proc
:
75 stdout
, stderr
= proc
.communicate(config
)
76 if proc
.returncode
!= 0:
77 self
.fail("Formal verification failed:\n" + stdout
)