utils: add litex_read_verilog utility
authorFlorent Kermarrec <florent@enjoy-digital.fr>
Fri, 16 Nov 2018 15:03:23 +0000 (16:03 +0100)
committerFlorent Kermarrec <florent@enjoy-digital.fr>
Fri, 16 Nov 2018 15:09:44 +0000 (16:09 +0100)
generate Migen's modules from verilog files

litex/utils/litex_read_verilog.py [new file with mode: 0755]
setup.py

diff --git a/litex/utils/litex_read_verilog.py b/litex/utils/litex_read_verilog.py
new file mode 100755 (executable)
index 0000000..b939d2f
--- /dev/null
@@ -0,0 +1,60 @@
+#!/usr/bin/env python3
+import os
+import sys
+import json
+
+from litex.build import tools
+
+def main():
+    if len(sys.argv) < 2:
+        print("usage: litex_read_verilog verilog_file [module]")
+        exit(1)
+
+    verilog_file = sys.argv[1]
+    json_file = verilog_file + ".json"
+    module = None if len(sys.argv) < 3 else sys.argv[2]
+
+    # use yosys to convert verilog to json
+    yosys_v2j = "\n".join([
+        "read_verilog -sv {}".format(verilog_file),
+        "write_json {}.json".format(verilog_file)
+    ])
+    tools.write_to_file("yosys_v2j.ys", yosys_v2j)
+    os.system("yosys -q yosys_v2j.ys")
+
+    # load json and convert to migen module
+    f = open(json_file, "r")
+    j = json.load(f)
+
+    # create list of modules
+    modules = [module] if module is not None else j["modules"].keys()
+
+    # create migen definitions
+    for module in modules:
+        migen_def = []
+        migen_def.append("class {}(Module):".format(module))
+        migen_def.append(" "*4 + "def __init__(self):")
+        for name, info in j["modules"][module]["ports"].items():
+            length = "" if len(info["bits"]) == 1 else len(info["bits"])
+            migen_def.append(" " * 8 + "self.{} = Signal({})".format(name, length))
+        migen_def.append("")
+        migen_def.append(" "*4 + "# # #")
+        migen_def.append("")
+        migen_def.append(" "*4 + "self.specials += Instance(\"{}\",".format(module))
+        for name, info in j["modules"][module]["ports"].items():
+            io_prefix = {
+                "input": "i",
+                "output": "o",
+                "inout": "io"
+            }[info["direction"]]
+            migen_def.append(" "*8 + "{}_{}=self.{},".format(io_prefix, name, name))
+        migen_def.append(" "*4 + ")")
+        migen_def.append("")
+        print("\n".join(migen_def))
+
+    # keep things clean after us
+    os.system("rm " + json_file)
+
+
+if __name__ == "__main__":
+    main()
index bf3c743be1b9778bdb78b99270b01681c7ae20c0..ed0dd4d392f4f5c834c99003f7ede7d2e2158a59 100755 (executable)
--- a/setup.py
+++ b/setup.py
@@ -40,6 +40,7 @@ setup(
             "litex_term=litex.utils.litex_term:main",
             "litex_server=litex.utils.litex_server:main",
             "litex_sim=litex.utils.litex_sim:main",
+            "litex_read_verilog=litex.utils.litex_read_verilog:main",
             "litex_simple=litex.boards.targets.simple:main",
         ],
     },