sim.pysim: only import pyvcd when needed.

In some environments (e.g. Pyodide) it may be advantageous to not load
this library, and with the import at file level, it makes the entire
simulator unusable, not just `PySimEngine.write_vcd`.

This might also help people whose Python environments are unusually
broken, whom we've historically accommodated.
This commit is contained in:
Catherine 2024-02-11 17:14:51 +00:00
parent 5797643c9c
commit 9aebf49565

View file

@ -1,8 +1,6 @@
from contextlib import contextmanager
import itertools
import re
from vcd import VCDWriter
from vcd.gtkw import GTKWSave
from ..hdl import *
from ..hdl._repr import *
@ -39,6 +37,10 @@ class _VCDWriter:
raise NotImplementedError
def __init__(self, fragment, *, vcd_file, gtkw_file=None, traces=()):
# Although pyvcd is a mandatory dependency, be resilient and import it as needed, so that
# the simulator is still usable if it's not installed for some reason.
import vcd, vcd.gtkw
if isinstance(vcd_file, str):
vcd_file = open(vcd_file, "w")
if isinstance(gtkw_file, str):
@ -47,13 +49,13 @@ class _VCDWriter:
self.vcd_signal_vars = SignalDict()
self.vcd_memory_vars = {}
self.vcd_file = vcd_file
self.vcd_writer = vcd_file and VCDWriter(self.vcd_file,
self.vcd_writer = vcd_file and vcd.VCDWriter(self.vcd_file,
timescale="1 ps", comment="Generated by Amaranth")
self.gtkw_signal_names = SignalDict()
self.gtkw_memory_names = {}
self.gtkw_file = gtkw_file
self.gtkw_save = gtkw_file and GTKWSave(self.gtkw_file)
self.gtkw_save = gtkw_file and vcd.gtkw.GTKWSave(self.gtkw_file)
self.traces = []