back.verilog: allow stripping the src attribute, for cleaner output.
[nmigen.git] / nmigen / back / verilog.py
1 import os
2 import subprocess
3
4 from . import rtlil
5
6
7 __all__ = ["convert"]
8
9
10 class YosysError(Exception):
11 pass
12
13
14 def convert(*args, strip_src=False, **kwargs):
15 try:
16 popen = subprocess.Popen([os.getenv("YOSYS", "yosys"), "-q", "-"],
17 stdin=subprocess.PIPE,
18 stdout=subprocess.PIPE,
19 stderr=subprocess.PIPE,
20 encoding="utf-8")
21 except FileNotFoundError as e:
22 if os.getenv("YOSYS"):
23 raise YosysError("Could not find Yosys in {} as specified via the YOSYS environment "
24 "variable".format(os.getenv("YOSYS"))) from e
25 else:
26 raise YosysError("Could not find Yosys in PATH. Place `yosys` in PATH or specify "
27 "path explicitly via the YOSYS environment variable") from e
28
29 attr_map = []
30 if strip_src:
31 attr_map.append("-remove src")
32
33 il_text = rtlil.convert(*args, **kwargs)
34 verilog_text, error = popen.communicate("""
35 # Convert nMigen's RTLIL to readable Verilog.
36 read_ilang <<rtlil
37 {}
38 rtlil
39 proc_init
40 proc_arst
41 proc_dff
42 proc_clean
43 memory_collect
44 attrmap {}
45 write_verilog -norename
46 """.format(il_text, " ".join(attr_map)))
47 if popen.returncode:
48 raise YosysError(error.strip())
49 else:
50 return verilog_text