From d528a232bb84279ab998631d38447d0294856d66 Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 20 Oct 2026 03:26:17 +0900 Subject: [PATCH] feat(cli): run SystemVerilog and Veryl native testbenches Add `celox run SOURCE... --top TOP` to execute HDL testbenches directly without a cocotb harness. Accept ordered .sv/.v sources or one Veryl project entry file, discover Veryl project sources and dependencies, and use the existing simulator and native testbench APIs. Forward HDL output, return failure for assertions and runtime errors, and expose the existing O0/O1/O2 optimization settings plus a scheduler-step/Veryl-tick limit. Report SV $stop as an error because the command has no interactive debugger. Preserve the optional systemverilog feature and explain how to enable it in builds without SV support. Document both languages in the English and Japanese CLI guides and cover the command boundary with integration tests, including delayed SV execution, execution limits, project discovery, relative paths, feature selection and failure exit codes. Compiler lowering, state-machine construction and optimizer implementation are unchanged. Validation: - cargo test --locked -p celox-vpi --test run_cli --bin celox - cargo test --locked -p celox-vpi --features systemverilog - cargo clippy --locked -p celox-vpi --all-targets -- -D warnings - cargo clippy --locked -p celox-vpi --all-targets --features systemverilog -- -D warnings - cargo fmt --all -- --check - pnpm run lint The cocotb-dependent end-to-end test retains its existing ignored status; this change exercises direct HDL execution and the ordinary VPI regression tests. Change-Id: Ib0d36d52483be3404f2e7ac72cfd8c89dc9fc21f --- crates/celox-vpi/src/bin/celox.rs | 248 ++++++++++++++++++++++++++- crates/celox-vpi/tests/run_cli.rs | 267 ++++++++++++++++++++++++++++++ docs/guide/cocotb.md | 40 ++++- docs/ja/guide/cocotb.md | 34 +++- 4 files changed, 584 insertions(+), 5 deletions(-) create mode 100644 crates/celox-vpi/tests/run_cli.rs diff --git a/crates/celox-vpi/src/bin/celox.rs b/crates/celox-vpi/src/bin/celox.rs index bde14acad89..5a6f8200973 100644 --- a/crates/celox-vpi/src/bin/celox.rs +++ b/crates/celox-vpi/src/bin/celox.rs @@ -18,7 +18,7 @@ use clap::{Args, Parser, Subcommand}; #[command( name = "celox", version = env!("CELOX_VERSION"), - about = "Compile and run Veryl designs with Celox" + about = "Compile and run Veryl and SystemVerilog designs with Celox" )] struct Cli { #[command(subcommand)] @@ -27,12 +27,241 @@ struct Cli { #[derive(Subcommand)] enum CliCommand { + /// Run a SystemVerilog or Veryl native testbench. + Run(RunArgs), /// Build native executables for VPI testbenches. Vpi(VpiArgs), /// Inspect saved simulation state files. State(StateArgs), } +#[derive(Args)] +struct RunArgs { + /// SystemVerilog sources in compilation order, or one Veryl project entry file. + #[arg(required = true)] + sources: Vec, + + /// Top-level testbench module name. + #[arg(long)] + top: String, + + /// Compiler optimization level: O0, O1, O2. + #[arg(short = 'O', long, default_value = "O1", value_parser = parse_opt_level)] + opt_level: celox::OptLevel, + + /// Maximum SV scheduler steps or Veryl testbench ticks before failing. + /// Does not bound compilation or work within a single step/tick. + #[arg(long, default_value_t = 1_000_000, value_parser = clap::value_parser!(u64).range(1..))] + max_steps: u64, +} + +fn parse_opt_level(value: &str) -> Result { + celox::OptLevel::parse(value).ok_or_else(|| "expected O0, O1, or O2".to_string()) +} + +fn run_testbench(arguments: RunArgs) -> Result<(), String> { + let all_sv = arguments.sources.iter().all(|path| { + path.extension() + .is_some_and(|extension| extension == "sv" || extension == "v") + }); + if all_sv { + #[cfg(feature = "systemverilog")] + return run_sv(arguments); + #[cfg(not(feature = "systemverilog"))] + return Err( + "SystemVerilog support requires building celox-vpi with --features systemverilog" + .to_string(), + ); + } + if arguments.sources.len() != 1 + || !arguments.sources[0] + .extension() + .is_some_and(|extension| extension == "veryl") + { + return Err("pass .sv/.v sources, or one .veryl project entry file".to_string()); + } + let source = &arguments.sources[0]; + let mut metadata = veryl_metadata::Metadata::search_from(source) + .ok() + .map(|path| { + veryl_metadata::Metadata::load(&path) + .map_err(|error| format!("failed to load {}: {error}", path.display())) + }) + .transpose()?; + let mut paths: Vec = if let Some(metadata) = &mut metadata { + metadata + .paths::<&Path>(&[], false, true) + .map_err(|error| format!("failed to discover project sources: {error}"))? + .into_iter() + .map(|path| path.src) + .collect() + } else { + Vec::new() + }; + let entry = source + .canonicalize() + .map_err(|error| format!("failed to read {}: {error}", source.display()))?; + if !paths.iter().any(|path| path == &entry) { + paths.push(entry); + } + let sources = paths + .iter() + .map(|path| { + std::fs::read_to_string(path) + .map(|text| (text, path.as_path())) + .map_err(|error| format!("failed to read {}: {error}", path.display())) + }) + .collect::, _>>()?; + let mut builder = celox::Simulator::from_sources( + sources + .iter() + .map(|(text, path)| (text.as_str(), *path)) + .collect(), + &arguments.top, + ) + .four_state(true) + .opt_level(arguments.opt_level); + if let Some(metadata) = metadata { + builder = builder.with_metadata(metadata); + } + let mut simulator = builder + .build() + .map_err(|error| format!("compilation failed:\n{error}"))?; + let program = celox::testbench::compile_initial_testbench(&simulator).ok_or_else(|| { + "selected module has no native testbench; select a #[test] module with --top".to_string() + })?; + let result = celox::testbench::run_compiled_testbench_with_tick_limit( + &mut simulator, + &program, + arguments.max_steps, + ); + if result.tick_limit_reached { + return Err(format!( + "simulation reached --max-steps {} testbench ticks before completion", + arguments.max_steps + )); + } + match result.result { + celox::TestResult::Pass => Ok(()), + celox::TestResult::Fail(message) => Err(message), + } +} + +#[cfg(feature = "systemverilog")] +fn run_sv(arguments: RunArgs) -> Result<(), String> { + let contents = arguments + .sources + .iter() + .map(|path| { + std::fs::read_to_string(path) + .map_err(|error| format!("failed to read {}: {error}", path.display())) + }) + .collect::, _>>()?; + let sources = contents + .iter() + .zip(&arguments.sources) + .map(|(text, path)| (text.as_str(), path.as_path())) + .collect(); + let simulation = celox::Simulation::from_sv_sources(sources, &arguments.top) + .four_state(true) + .opt_level(arguments.opt_level) + .build() + .map_err(|error| format!("compilation failed:\n{error}"))?; + simulate_sv( + simulation, + arguments.max_steps, + &mut std::io::stdout().lock(), + ) +} + +#[cfg(feature = "systemverilog")] +fn simulate_sv( + mut simulation: celox::Simulation, + max_steps: u64, + output: &mut impl Write, +) -> Result<(), String> { + let mut failed = false; + let initial = simulation.eval_comb(); + drain_sv_output(&mut simulation, output, &mut failed)?; + initial.map_err(|error| error.to_string())?; + let mut steps = 0; + while !simulation.is_finished() && simulation.next_event_time().is_some() { + if steps == max_steps { + return Err(format!("simulation exceeded --max-steps {}", max_steps)); + } + let step = simulation.step(); + drain_sv_output(&mut simulation, output, &mut failed)?; + if step.map_err(|error| error.to_string())?.is_none() { + break; + } + steps += 1; + } + if failed { + return Err("SystemVerilog testbench reported an assertion failure or $error".to_string()); + } + Ok(()) +} + +#[cfg(feature = "systemverilog")] +fn drain_sv_output( + simulation: &mut celox::Simulation, + output: &mut impl Write, + failed: &mut bool, +) -> Result<(), String> { + let mut fatal = false; + let mut stopped = false; + let mut missed = 0; + for event in simulation.drain_runtime_events() { + let (message, newline) = match event { + celox::RuntimeEvent::Display { message } => (message, true), + celox::RuntimeEvent::Write { message } => (message, false), + celox::RuntimeEvent::AssertContinue { message } => { + *failed = true; + (message, true) + } + celox::RuntimeEvent::AssertFatal { message } => { + fatal = true; + (message, true) + } + celox::RuntimeEvent::Finish => continue, + celox::RuntimeEvent::Stop => { + stopped = true; + continue; + } + celox::RuntimeEvent::Missed { count } => { + missed += count; + continue; + } + }; + output + .write_all(&message) + .and_then(|()| { + if newline { + output.write_all(b"\n") + } else { + Ok(()) + } + }) + .map_err(|error| format!("failed to write simulation output: {error}"))?; + } + output + .flush() + .map_err(|error| format!("failed to flush simulation output: {error}"))?; + if missed != 0 { + return Err(format!("{missed} runtime events were lost")); + } + if fatal { + return Err("SystemVerilog testbench reported $fatal".to_string()); + } + if stopped || simulation.is_stopped() { + return Err( + "SystemVerilog testbench requested $stop; interactive simulation is unavailable" + .to_string(), + ); + } + Ok(()) +} + #[derive(Args)] struct StateArgs { #[command(subcommand)] @@ -497,6 +726,7 @@ fn run() -> Result { run_simulation(attached.image, SimulationArgs::parse()).map(|()| ExitCode::SUCCESS) } None => match Cli::parse().command { + CliCommand::Run(arguments) => run_testbench(arguments).map(|()| ExitCode::SUCCESS), CliCommand::Vpi(arguments) => match arguments.command { VpiCommand::Build(arguments) => build(arguments).map(|()| ExitCode::SUCCESS), }, @@ -519,6 +749,22 @@ fn main() -> ExitCode { mod tests { use super::*; + #[cfg(feature = "systemverilog")] + #[test] + fn sv_scheduler_limit_fails_and_preserves_scheduled_output() { + let source = + "module Top(input bit clk); always @(posedge clk) $display(\"tick\"); endmodule"; + let mut simulation = + celox::Simulation::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top") + .build() + .unwrap(); + simulation.add_clock("clk", 2, 1); + let mut output = Vec::new(); + let error = simulate_sv(simulation, 3, &mut output).unwrap_err(); + assert!(error.contains("exceeded --max-steps 3")); + assert!(String::from_utf8(output).unwrap().contains("tick")); + } + fn state_file(count: u8, stale: u8) -> StateFile { let object = |path: &str, role, value: u8, mask: u8| StateObject { path: path.into(), diff --git a/crates/celox-vpi/tests/run_cli.rs b/crates/celox-vpi/tests/run_cli.rs new file mode 100644 index 00000000000..dc3ab8c6d7c --- /dev/null +++ b/crates/celox-vpi/tests/run_cli.rs @@ -0,0 +1,267 @@ +//! End-to-end coverage of the direct HDL testbench command-line boundary. + +use std::process::Command; + +fn run(sources: &[(&str, &str)], extra: &[&str]) -> std::process::Output { + let temporary = tempfile::tempdir().unwrap(); + let mut command = Command::new(env!("CARGO_BIN_EXE_celox")); + command.arg("run"); + for (name, source) in sources { + let path = temporary.path().join(name); + std::fs::write(&path, source).unwrap(); + command.arg(path); + } + command.args(["--top", "Top"]).args(extra).output().unwrap() +} + +#[cfg(feature = "systemverilog")] +#[test] +fn runs_multiple_sources_and_preserves_display_and_write_output() { + let output = run( + &[ + ( + "types.sv", + "package types; parameter int VALUE = 42; endpackage", + ), + ( + "top.sv", + "module Top; initial begin $write(\"value=\"); $display(\"%0d\", types::VALUE); $finish; end endmodule", + ), + ], + &[], + ); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(output.stdout, b"value=42\n"); +} + +#[cfg(feature = "systemverilog")] +#[test] +fn no_remaining_events_is_success() { + let output = run( + &[( + "top.sv", + "module Top; initial $display(\"done\"); endmodule", + )], + &[], + ); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(output.stdout, b"done\n"); +} + +#[cfg(feature = "systemverilog")] +#[test] +fn fatal_and_nonfatal_failures_return_failure_with_output() { + for action in [ + "$fatal(1, \"failed\")", + "$error(\"failed\")", + "assert (0) else $error(\"failed\")", + ] { + let source = format!("module Top; initial begin {action}; $finish; end endmodule"); + let output = run(&[("top.sv", &source)], &[]); + assert_eq!(output.status.code(), Some(1), "{action}: {output:?}"); + assert!( + String::from_utf8_lossy(&output.stdout).contains("failed"), + "{action}: {output:?}" + ); + } +} + +#[test] +fn invalid_source_and_missing_source_return_failure() { + let output = run(&[("bad.veryl", "module Top { invalid syntax }")], &[]); + assert_eq!(output.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&output.stderr).contains("compilation failed")); + + let temporary = tempfile::tempdir().unwrap(); + let missing = temporary.path().join("missing.veryl"); + let output = Command::new(env!("CARGO_BIN_EXE_celox")) + .arg("run") + .arg(&missing) + .args(["--top", "Top"]) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&output.stderr).contains("failed to read")); +} + +#[test] +fn requires_sources_top_and_positive_step_limit() { + for args in [ + vec!["run", "--top", "Top"], + vec!["run", "top.sv"], + vec!["run", "top.sv", "--top", "Top", "--max-steps", "0"], + ] { + let output = Command::new(env!("CARGO_BIN_EXE_celox")) + .args(args) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(2)); + } +} + +#[test] +fn runs_veryl_native_testbenches_and_reports_assertions() { + for (assertion, success) in [("1'd1", true), ("1'd0", false)] { + let source = format!( + "#[test(Top)] module Top {{ initial {{ $display(\"native tb\"); $assert({assertion}); $finish(); }} }}" + ); + let output = run(&[("top.veryl", &source)], &[]); + assert_eq!(output.status.success(), success, "{output:?}"); + // The native testbench API forwards HDL output to stderr. + assert!( + String::from_utf8_lossy(&output.stderr).contains("native tb"), + "{output:?}" + ); + } +} + +#[test] +fn veryl_tick_limit_is_a_failure() { + let output = run( + &[( + "top.veryl", + "#[test(Top)] module Top { inst clk: $tb::clock_gen; initial { clk.next(10); $finish(); } }", + )], + &["--max-steps", "2"], + ); + assert_eq!(output.status.code(), Some(1)); + assert!( + String::from_utf8_lossy(&output.stderr).contains("testbench ticks before completion"), + "{output:?}" + ); +} + +#[test] +fn veryl_project_discovers_sibling_sources() { + let temporary = tempfile::tempdir().unwrap(); + std::fs::write( + temporary.path().join("Veryl.toml"), + "[project]\nname = \"cli_project\"\nversion = \"0.1.0\"\n", + ) + .unwrap(); + std::fs::write(temporary.path().join("dut.veryl"), "module Dut {} ").unwrap(); + let source = temporary.path().join("top.veryl"); + std::fs::write( + &source, + "#[test(Top)] module Top { inst dut: Dut; initial { $assert(1'd1); $finish(); } }", + ) + .unwrap(); + let output = Command::new(env!("CARGO_BIN_EXE_celox")) + .arg("run") + .arg(source) + .args(["--top", "Top"]) + .output() + .unwrap(); + assert!(output.status.success(), "{output:?}"); +} + +#[test] +fn rejects_mixed_sources_and_veryl_without_a_testbench() { + let output = run(&[("top.sv", ""), ("top.veryl", "")], &[]); + assert_eq!(output.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&output.stderr).contains("one .veryl")); + let output = run(&[("top.veryl", "module Top {}")], &[]); + assert_eq!(output.status.code(), Some(1)); + assert!( + String::from_utf8_lossy(&output.stderr).contains("no native testbench"), + "{output:?}" + ); +} + +#[cfg(feature = "systemverilog")] +#[test] +fn sv_delays_complete_and_execution_limit_fails() { + let output = run( + &[( + "top.sv", + "module Top; initial begin #1; $display(\"later\"); $finish; end endmodule", + )], + &[], + ); + assert!(output.status.success(), "{output:?}"); + assert_eq!(output.stdout, b"later\n"); + + let output = run( + &[( + "clock.sv", + "module Top; bit clk = 0; initial forever #1 clk = ~clk; endmodule", + )], + &["--max-steps", "3"], + ); + assert_eq!(output.status.code(), Some(1)); + assert!( + String::from_utf8_lossy(&output.stderr).contains("exceeded --max-steps 3"), + "{output:?}" + ); +} + +#[test] +fn accepts_supported_optimization_levels() { + for extension in ["sv", "veryl"] + .into_iter() + .filter(|extension| *extension != "sv" || cfg!(feature = "systemverilog")) + { + let name = format!("top.{extension}"); + let source = if extension == "sv" { + "module Top; initial $finish; endmodule" + } else { + "#[test(Top)] module Top { initial { $finish(); } }" + }; + for level in ["O0", "O1", "O2"] { + let output = run(&[(&name, source)], &["-O", level]); + assert!(output.status.success(), "{extension}, {level}: {output:?}"); + } + } + let output = run(&[("top.sv", "")], &["-O", "O3"]); + assert_eq!(output.status.code(), Some(2)); +} + +#[test] +fn accepts_relative_standalone_veryl_source() { + let temporary = tempfile::tempdir().unwrap(); + std::fs::write( + temporary.path().join("top.veryl"), + "#[test(Top)] module Top { initial { $finish(); } }", + ) + .unwrap(); + let output = Command::new(env!("CARGO_BIN_EXE_celox")) + .current_dir(temporary.path()) + .args(["run", "top.veryl", "--top", "Top"]) + .output() + .unwrap(); + assert!(output.status.success(), "{output:?}"); +} + +#[cfg(not(feature = "systemverilog"))] +#[test] +fn sv_without_feature_explains_how_to_enable_it() { + let output = run(&[("top.sv", "module Top; endmodule")], &[]); + assert_eq!(output.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&output.stderr).contains("--features systemverilog")); +} + +#[cfg(feature = "systemverilog")] +#[test] +fn sv_stop_is_not_reported_as_successful_completion() { + let output = run( + &[( + "top.sv", + "module Top; initial begin $display(\"before stop\"); $stop; $display(\"after stop\"); end endmodule", + )], + &[], + ); + assert_eq!(output.status.code(), Some(1)); + assert!( + String::from_utf8_lossy(&output.stderr).contains("requested $stop"), + "{output:?}" + ); + assert_eq!(output.stdout, b"before stop\n"); +} diff --git a/docs/guide/cocotb.md b/docs/guide/cocotb.md index 4dea3699243..b69d648878d 100644 --- a/docs/guide/cocotb.md +++ b/docs/guide/cocotb.md @@ -10,10 +10,11 @@ sources when it runs. The CLI is currently built from the Celox source tree: ```sh -cargo build --release -p celox-vpi --bin celox +cargo build --release -p celox-vpi --features systemverilog --bin celox ``` -Install cocotb into the Python environment you want to use: +The `run` command below needs no Python installation. For VPI tests, install +cocotb into the Python environment you want to use: ```sh python3 -m pip install cocotb @@ -21,6 +22,41 @@ python3 -m pip install cocotb The repository dev container already includes cocotb 2.0.1 and Verilator. +## Run an HDL testbench directly + +Use the same command for a SystemVerilog testbench and a Veryl native +`#[test]` module: + +```sh +target/release/celox run src/types.sv src/Dut.sv test/Top.sv --top Top +target/release/celox run test/Top.veryl --top Top +``` + +For SystemVerilog, pass `.sv` or `.v` sources in compilation order. The command +uses four-state simulation and runs until `$finish` or no scheduled events +remain. For Veryl, pass one project entry file: Celox discovers `Veryl.toml` +and collects the project's sources and dependencies. A standalone +Veryl file also works. Select the native testbench module with `--top`. +Veryl uses the existing native testbench executor; a test may also complete by +falling through its initial blocks. + +The command uses the existing frontends' supported language subsets; unsupported +constructs produce compilation diagnostics. `-O O0`, `-O O1` (default), and +`-O O2` select the existing compiler optimization levels. + +Successful completion returns status 0. Compilation errors, runtime errors, +assertion failures, `$error`, `$fatal`, lost runtime events, and exhausted +execution limits return status 1. SV `$stop` also returns status 1 because this +command has no interactive debugger. Invalid command arguments return status 2. +SV `$display`/`$write` output goes to stdout; the existing Veryl native +testbench executor sends its HDL output to stderr. + +`--max-steps N` sets a positive execution limit (default: 1000000). It counts +scheduler steps for SV and testbench ticks for Veryl. Reaching the Veryl tick +limit before completion fails the command. This limit does not bound compilation +or work within a single step/tick; use an external process timeout when a wall +clock limit is needed. Source languages cannot be mixed in one invocation. + ## Compile a design Pass one source in the Veryl project and name the top-level module: diff --git a/docs/ja/guide/cocotb.md b/docs/ja/guide/cocotb.md index dad1d689619..aaac854211b 100644 --- a/docs/ja/guide/cocotb.md +++ b/docs/ja/guide/cocotb.md @@ -10,10 +10,10 @@ CeloxはVerylの設計を、VPI経由で通常の 現在、CLIはCeloxのソースツリーからビルドします。 ```sh -cargo build --release -p celox-vpi --bin celox +cargo build --release -p celox-vpi --features systemverilog --bin celox ``` -利用するPython環境へcocotbをインストールします。 +後述の`run`コマンドにはPythonは不要です。VPIテストを使う場合は、利用するPython環境へcocotbをインストールします。 ```sh python3 -m pip install cocotb @@ -21,6 +21,36 @@ python3 -m pip install cocotb リポジトリのdevcontainerにはcocotb 2.0.1とVerilatorがあらかじめ入っています。 +## HDLテストベンチを直接実行する + +SystemVerilogのテストベンチとVerylのnative `#[test]`モジュールを、同じコマンドで実行できます。 + +```sh +target/release/celox run src/types.sv src/Dut.sv test/Top.sv --top Top +target/release/celox run test/Top.veryl --top Top +``` + +SVは`.sv`または`.v`をコンパイル順に指定します。4値シミュレーションを使い、 +`$finish`または実行待ちイベントがなくなるまで実行します。 +Verylはプロジェクト内の1ファイルを指定すると、`Veryl.toml`から +ソースと依存関係を収集します。単独のVerylファイルも使用できます。 +`--top`にはnative testbenchのモジュール名を指定します。 +既存のnative testbench実行器を使うため、initialブロックの末尾への到達でも完了します。 + +実行できる構文は既存フロントエンドの対応範囲に従い、未対応構文にはコンパイル診断を返します。 +`-O O0`、`-O O1`(既定値)、`-O O2`で既存コンパイラの最適化レベルを選択できます。 + +正常終了は終了コード0、コンパイル・実行エラー、アサーション失敗、`$error`、 +`$fatal`、実行時イベントの欠落、実行上限による打ち切りは1、引数エラーは2です。 +SVの`$stop`も、対話デバッガーを持たないため終了コード1になります。 +SVの`$display`/`$write`は標準出力、VerylのHDL出力は既存実行器に従って標準エラー出力に送ります。 + +`--max-steps N`で正の実行上限を指定できます(既定値1000000)。 +SVではスケジューラのステップ数、Verylではtestbenchのtick数です。 +Verylでは完了前にtick上限に達すると失敗します。 +コンパイルや1ステップ・tick内の処理時間は制限しないため、実時間の制限が必要な場合は +外部のタイムアウト機能を使ってください。1回の実行で言語を混在させることはできません。 + ## 設計をコンパイルする Verylプロジェクト内のソースを1つ指定し、トップレベルモジュール名を渡します。