speed up ==, hash, <, >, <=, and >= for plain_data
[nmutil.git] / src / nmutil / sim_util.py
1 # SPDX-License-Identifier: LGPL-3-or-later
2 # Copyright 2021 Jacob Lifshay
3
4 # Funded by NLnet Assure Programme 2021-02-052, https://nlnet.nl/assure part
5 # of Horizon 2020 EU Programme 957073.
6
7 from contextlib import contextmanager
8 from hashlib import sha256
9
10 from nmigen.hdl.ir import Fragment, ClockDomain
11 from nmutil.get_test_path import get_test_path
12 from nmigen.sim import Simulator
13 from nmigen.back.rtlil import convert
14
15
16 def hash_256(v):
17 return int.from_bytes(
18 sha256(bytes(v, encoding='utf-8')).digest(),
19 byteorder='little'
20 )
21
22
23 def write_il(test_case, dut, ports=()):
24 # only elaborate once, cuz users' stupid code breaks if elaborating twice
25 dut = Fragment.get(dut, platform=None)
26 if "sync" not in dut.domains:
27 dut.add_domains(ClockDomain("sync"))
28 path = get_test_path(test_case, "sim_test_out")
29 path.parent.mkdir(parents=True, exist_ok=True)
30 il_path = path.with_suffix(".il")
31 il_path.write_text(convert(dut, ports=ports), encoding="utf-8")
32 return dut, path
33
34
35 @contextmanager
36 def do_sim(test_case, dut, traces=(), ports=None):
37 if ports is None:
38 ports = traces
39 dut, path = write_il(test_case, dut, ports)
40 sim = Simulator(dut)
41 vcd_path = path.with_suffix(".vcd")
42 gtkw_path = path.with_suffix(".gtkw")
43 with sim.write_vcd(vcd_path.open("wt", encoding="utf-8"),
44 gtkw_path.open("wt", encoding="utf-8"),
45 traces=traces):
46 yield sim