feat(build): binding template and build pipeline

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
thomasandClaude Sonnet 5.5 committed 2026-09-30 08:44:17 +02:00
1 parent d5195a4a39
commit d1d30f6846
4 files changed
+430

No files matched your search

+142
View File
@@ -0,0 +1,142 @@
"""Build pipeline: Verilator -> nanobind binding -> shared library."""
import shutil
import sysconfig
from contextlib import contextmanager
from pathlib import Path
from rich.console import Console
from rich.markup import escape
from . import verilator
from .verilator import DlvError, VPort
TEMPLATES = Path(__file__).parent / "templates"
console = Console(highlight=False)
@contextmanager
def step(label: str):
"""Spinner while running, then ✓ / ✗."""
with console.status(label):
try:
yield
except BaseException:
console.print(f"[red]✗[/red] {escape(label)}")
raise
console.print(f"[green]✓[/green] {escape(label)}")
def sh(cmd: list[str], verbose: bool, cwd: Path | None = None) -> None:
"""Run a command with buffered output; print it only on failure or with -v."""
r = verilator.run([str(c) for c in cmd], cwd=cwd)
out = (r.stdout + r.stderr).strip()
if verbose and out:
console.print(escape(out))
if r.returncode != 0:
raise DlvError(f"{cmd[0]} failed (exit {r.returncode})" + ("" if verbose else f":\n{out}"))
def ctype(width: int) -> str:
return "uint8_t" if width <= 8 else "uint16_t" if width <= 16 else "uint32_t" if width <= 32 else "uint64_t"
def pick_module(file: Path, module: str | None) -> str:
from .parser import parse_file
mods = [m.name for m in parse_file(file)]
if module:
return module
if file.stem not in mods:
hint = f" (modules in file: {', '.join(mods)})" if mods else ""
raise DlvError(f"module name differs from file name '{file.name}'; pass --module{hint}")
return file.stem
def check_ports(ports: list[VPort], clock: str) -> VPort:
by_name = {p.name: p for p in ports}
clk = by_name.get(clock)
if clk is None or clk.direction != "input":
raise DlvError(f"--clock {clock}: not an input port (inputs: {', '.join(p.name for p in ports if p.direction == 'input')})")
if clk.width != 1:
raise DlvError(f"--clock {clock}: must be a 1-bit input, but is {clk.width} bits wide")
for p in ports:
if p.width > 64:
raise DlvError(f"port '{p.name}' is {p.width} bits wide; ports > 64 bits are not supported")
if p.direction == "inout":
raise DlvError(f"port '{p.name}': inout ports are not supported")
return clk
def render(top: str, ports: list[VPort], clock: str, trace: bool) -> str:
from jinja2 import Environment, FileSystemLoader
def view(p: VPort) -> dict:
return {"name": p.name, "width": p.width, "ctype": ctype(p.width), "mask": hex((1 << p.width) - 1)}
env = Environment(loader=FileSystemLoader(TEMPLATES), keep_trailing_newline=True)
return env.get_template("binding.cpp.j2").render(
top=top,
clock=clock,
trace=trace,
inputs=[view(p) for p in ports if p.direction == "input" and p.name != clock],
outputs=[view(p) for p in ports if p.direction == "output"],
)
def nanobind_object(work: Path, cxxflags: list[str], verbose: bool) -> Path:
"""nanobind runtime, compiled once per (nanobind version, python) and cached."""
import nanobind
tag = f"{nanobind.__version__}-{sysconfig.get_config_var('SOABI') or 'py'}"
obj = work.parent / f"_nanobind-{tag}" / "nb_combined.o"
if not obj.exists():
obj.parent.mkdir(parents=True, exist_ok=True)
src = Path(nanobind.source_dir()) / "nb_combined.cpp"
robin = Path(nanobind.include_dir()).parent / "ext" / "robin_map" / "include"
sh(["g++", *cxxflags, "-I", nanobind.include_dir(), "-I", robin, "-c", src, "-o", obj], verbose)
return obj
def build(file: Path, clock: str | None, out: Path, module: str | None = None, trace: bool = False, verbose: bool = False) -> Path:
import nanobind
if not clock:
raise DlvError("--clock is required (modules without a master clock are not supported)")
file = file.resolve()
if not file.exists():
raise DlvError(f"file not found: {file}")
with step("Checking verilator"):
version = verilator.check()
if not shutil.which("g++"):
raise DlvError("g++ not found in PATH")
top = pick_module(file, module)
with step("Reading ports"):
ports = verilator.ports(file, top)
check_ports(ports, clock)
work = Path(".dlv/build").resolve() / top
shutil.rmtree(work, ignore_errors=True)
work.mkdir(parents=True)
with step("Generating binding"):
(work / "binding.cpp").write_text(render(top, ports, clock, trace))
with step(f"Running verilator {version}"):
sh(
["verilator", "--cc", "--build", "-j", "0", "--Mdir", work, "--top-module", top,
"-Wno-fatal", "-CFLAGS", "-fPIC -O2", *(["--trace-fst"] if trace else []), file],
verbose,
)
with step("Compiling extension"):
cxxflags = ["-std=c++17", "-O2", "-fPIC", "-fvisibility=hidden", "-DNDEBUG",
"-I", sysconfig.get_paths()["include"]]
nb_obj = nanobind_object(work, cxxflags, verbose)
vroot = verilator.root() / "include"
target = out.resolve() / f"{top}{sysconfig.get_config_var('EXT_SUFFIX')}"
out.mkdir(parents=True, exist_ok=True)
sh(
["g++", *cxxflags, "-shared", "-I", nanobind.include_dir(), "-I", work, "-I", vroot,
"-I", vroot / "vltstd", work / "binding.cpp", nb_obj, work / f"V{top}__ALL.a",
work / "libverilated.a", "-pthread", "-lz", "-o", target],
verbose,
)
console.print(f"Built [bold]{escape(str(target))}[/bold]", soft_wrap=True)
return target
+72
View File
@@ -0,0 +1,72 @@
# PYTHON_ARGCOMPLETE_OK
"""dlv command line. Heavy imports happen only after argcomplete."""
import argparse
import sys
from pathlib import Path
def _modules(parsed_args) -> list:
from .parser import parse_file
try:
return parse_file(parsed_args.file)
except (OSError, AttributeError):
return []
def complete_module(prefix, parsed_args, **kw):
return [m.name for m in _modules(parsed_args)]
def complete_clock(prefix, parsed_args, **kw):
mods = _modules(parsed_args)
name = parsed_args.module or Path(parsed_args.file).stem
mod = next((m for m in mods if m.name == name), mods[0] if len(mods) == 1 else None)
return [p.name for p in mod.ports if p.direction == "input" and p.width == 1] if mod else []
def make_parser() -> argparse.ArgumentParser:
ap = argparse.ArgumentParser(prog="dlv", description="Verilog module -> importable Python module (Verilator + nanobind)")
sub = ap.add_subparsers(dest="cmd", required=True)
b = sub.add_parser("build", help="build a Python module from a Verilog file")
b.add_argument("file", metavar="FILE.v", help="Verilog source file")
b.add_argument("--clock", metavar="PORT", help="master clock input (1 bit, required)").completer = complete_clock
b.add_argument("-o", "--output", metavar="DIR", default=".", help="output directory (default: cwd)")
b.add_argument("--module", metavar="M", help="top module (default: file name)").completer = complete_module
b.add_argument("--trace", action="store_true", help="enable FST tracing (trace_open/trace_close)")
b.add_argument("-v", "--verbose", action="store_true", help="show tool output")
i = sub.add_parser("init", help="install shell completion")
i.add_argument("--shell", choices=["bash", "zsh", "fish"], help="default: from $SHELL")
return ap
def main(argv: list[str] | None = None) -> int:
import argcomplete
ap = make_parser()
argcomplete.autocomplete(ap)
args = ap.parse_args(argv)
from .verilator import DlvError
try:
if args.cmd == "build":
from .build import build
build(Path(args.file), args.clock, Path(args.output), args.module, args.trace, args.verbose)
else:
from .completion import init
init(args.shell)
except DlvError as e:
from rich.console import Console
from rich.markup import escape
Console(stderr=True, highlight=False).print(f"[red]error:[/red] {escape(str(e))}")
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
+33
View File
@@ -0,0 +1,33 @@
"""`dlv init`: install argcomplete-based shell completion for bash, zsh and fish."""
import os
from pathlib import Path
from argcomplete import shellcode
from .verilator import DlvError
_TARGETS = {
"bash": Path("~/.local/share/bash-completion/completions/dlv"),
"zsh": Path("~/.local/share/zsh/site-functions/_dlv"),
"fish": Path("~/.config/fish/completions/dlv.fish"),
}
_HINTS = {
"bash": "Restart your shell (bash-completion loads it on demand).",
"zsh": "Make sure ~/.local/share/zsh/site-functions is in your fpath before compinit, then restart zsh.",
"fish": "Restart fish.",
}
def init(shell: str | None = None) -> Path:
from .build import console
shell = shell or Path(os.environ.get("SHELL", "")).name
if shell not in _TARGETS:
raise DlvError("cannot detect shell from $SHELL; use --shell bash|zsh|fish")
path = _TARGETS[shell].expanduser()
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(shellcode(["dlv"], shell=shell))
console.print(f"[green]✓[/green] Installed {shell} completion: {path}", soft_wrap=True)
console.print(_HINTS[shell])
return path
+183
View File
@@ -0,0 +1,183 @@
// Generated by dlv. Do not edit.
#include <nanobind/nanobind.h>
#include <nanobind/ndarray.h>
#include <nanobind/stl/string.h>
#include <memory>
#include <string>
#include "V{{ top }}.h"
#include "verilated.h"
{% if trace %}#include "verilated_fst_c.h"
{% endif %}
namespace nb = nanobind;
using namespace nb::literals;
namespace {
template <typename T>
using In = nb::ndarray<T, nb::ndim<1>, nb::c_contig, nb::device::cpu>;
// Coerce anything array-like to a contiguous 1-D uint64 numpy array.
nb::object as_u64(nb::handle v) {
auto np = nb::module_::import_("numpy");
return np.attr("ascontiguousarray")(v, "dtype"_a = np.attr("uint64"));
}
struct Model {
std::unique_ptr<VerilatedContext> ctx;
std::unique_ptr<V{{ top }}> top;
{% if trace %} std::unique_ptr<VerilatedFstC> tfp;
{% endif %}
Model() {
ctx = std::make_unique<VerilatedContext>();
{% if trace %} ctx->traceEverOn(true);
{% endif %} top = std::make_unique<V{{ top }}>(ctx.get());
top->{{ clock }} = 0;
eval();
}
~Model() {
{% if trace %} trace_close();
{% endif %} top->final();
}
void eval() {
top->eval();
{% if trace %} if (tfp) tfp->dump(ctx->time());
{% endif %} ctx->timeInc(1);
}
// One clock period starting with a rising edge (idle level 0).
void tick_ris() {
if (top->{{ clock }}) {
top->{{ clock }} = 0;
eval();
}
top->{{ clock }} = 1;
eval();
top->{{ clock }} = 0;
eval();
}
// One clock period starting with a falling edge (idle level 1).
void tick_fal() {
if (!top->{{ clock }}) {
top->{{ clock }} = 1;
eval();
}
top->{{ clock }} = 0;
eval();
top->{{ clock }} = 1;
eval();
}
void set_inputs(nb::dict d) {
for (auto [k, v] : d) {
std::string key = nb::cast<std::string>(k);
{% for p in inputs %} if (key == "{{ p.name }}") { top->{{ p.name }} = nb::cast<uint64_t>(v) & {{ p.mask }}ULL; continue; }
{% endfor %} if (key == "{{ clock }}") throw nb::value_error("'{{ clock }}' is the clock and driven by the model");
throw nb::key_error(("no such input: " + key).c_str());
}
}
nb::dict get() {
nb::dict r;
{% for p in outputs %} r["{{ p.name }}"] = (uint64_t)top->{{ p.name }};
{% endfor %} return r;
}
void proc_ris(nb::dict d) { set_inputs(d); tick_ris(); }
void proc_fal(nb::dict d) { set_inputs(d); tick_fal(); }
void cycle_ris(size_t n) { for (size_t i = 0; i < n; i++) tick_ris(); }
void cycle_fal(size_t n) { for (size_t i = 0; i < n; i++) tick_fal(); }
nb::dict step(size_t n, nb::dict d) {
nb::dict r;
// Inputs: one value per cycle (length n) or a single value for all cycles (length 1).
{% for p in inputs %} nb::object o_{{ p.name }}; const uint64_t* a_{{ p.name }} = nullptr; size_t l_{{ p.name }} = 0;
{% endfor %} for (auto [k, v] : d) {
std::string key = nb::cast<std::string>(k);
bool known = false;
{% for p in inputs %} if (key == "{{ p.name }}") {
o_{{ p.name }} = as_u64(v);
auto a = nb::cast<In<uint64_t>>(o_{{ p.name }});
a_{{ p.name }} = a.data();
l_{{ p.name }} = a.shape(0);
if (l_{{ p.name }} != n && l_{{ p.name }} != 1)
throw nb::value_error("input '{{ p.name }}' must have length n or 1");
known = true;
}
{% endfor %} if (!known) throw nb::key_error(("no such input: " + key).c_str());
}
{% for p in outputs %} auto* b_{{ p.name }} = new {{ p.ctype }}[n ? n : 1];
nb::capsule c_{{ p.name }}(b_{{ p.name }}, [](void* p) noexcept { delete[] ({{ p.ctype }}*)p; });
{% endfor %} {
nb::gil_scoped_release release;
for (size_t i = 0; i < n; i++) {
{% for p in inputs %} if (a_{{ p.name }}) top->{{ p.name }} = a_{{ p.name }}[l_{{ p.name }} == 1 ? 0 : i] & {{ p.mask }}ULL;
{% endfor %} tick_ris();
{% for p in outputs %} b_{{ p.name }}[i] = top->{{ p.name }};
{% endfor %} }
}
{% for p in outputs %} r["{{ p.name }}"] = nb::cast(nb::ndarray<nb::numpy, {{ p.ctype }}, nb::ndim<1>>(b_{{ p.name }}, {n}, c_{{ p.name }}));
{% endfor %} return r;
}
{% if trace %}
void trace_open(const std::string& path) {
trace_close();
tfp = std::make_unique<VerilatedFstC>();
top->trace(tfp.get(), 99);
tfp->open(path.c_str());
}
void trace_close() {
if (tfp) {
tfp->close();
tfp.reset();
}
}
{% endif %}
nb::dict info() {
nb::dict i, o, r;
{% for p in inputs %} i["{{ p.name }}"] = {{ p.width }};
{% endfor %}{% for p in outputs %} o["{{ p.name }}"] = {{ p.width }};
{% endfor %} r["name"] = "{{ top }}";
r["inputs"] = i;
r["outputs"] = o;
r["clock"] = "{{ clock }}";
return r;
}
};
// Default instance behind the module-level functions, created on first use.
Model& dflt() {
static Model* m = new Model();
return *m;
}
} // namespace
NB_MODULE({{ top }}, m) {
nb::class_<Model>(m, "Model")
.def(nb::init<>())
.def("info", &Model::info)
.def("proc_ris", &Model::proc_ris, "inputs"_a = nb::dict())
.def("proc_fal", &Model::proc_fal, "inputs"_a = nb::dict())
.def("cycle_ris", &Model::cycle_ris, "n"_a = 1)
.def("cycle_fal", &Model::cycle_fal, "n"_a = 1)
.def("get", &Model::get)
.def("step", &Model::step, "n"_a, "inputs"_a = nb::dict()){% if trace %}
.def("trace_open", &Model::trace_open, "path"_a)
.def("trace_close", &Model::trace_close){% endif %};
m.def("info", [] { return dflt().info(); });
m.def("proc_ris", [](nb::dict d) { dflt().proc_ris(d); }, "inputs"_a = nb::dict());
m.def("proc_fal", [](nb::dict d) { dflt().proc_fal(d); }, "inputs"_a = nb::dict());
m.def("cycle_ris", [](size_t n) { dflt().cycle_ris(n); }, "n"_a = 1);
m.def("cycle_fal", [](size_t n) { dflt().cycle_fal(n); }, "n"_a = 1);
m.def("get", [] { return dflt().get(); });
m.def("step", [](size_t n, nb::dict d) { return dflt().step(n, d); }, "n"_a, "inputs"_a = nb::dict());{% if trace %}
m.def("trace_open", [](const std::string& p) { dflt().trace_open(p); }, "path"_a);
m.def("trace_close", [] { dflt().trace_close(); });{% endif %}
}