From 834663f4b1af8f419a762ddf642d2b74738d5536 Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 20 Oct 2026 18:23:45 +0900 Subject: [PATCH] feat(cli)!: support numeric top parameter overrides Taxi's cocotb parameter set enables ID_EN and DEST_EN, but the CLI previously required editing a copy of its top module to select those values. Both `celox run` and `celox vpi build` now accept repeatable `-G NAME=VALUE` / `--parameter NAME=VALUE` (`--param` alias), plus `[parameters]` and `[targets.NAME.parameters]` in celox.toml, for SystemVerilog and Veryl tops. Merge parameters by name in common -> target -> CLI order, with the last assignment winning. Values use the existing unsigned 64-bit builder interface, accepting decimal/0x/0o/0b forms and digit separators; TOML also accepts numeric strings for the full u64 range. HDL expressions, negative values, string values, and type parameters remain outside this interface. Declaration types determine conversion and truncation. Preserve the existing public driver helpers while adding a parameter-aware entry point. Reject invalid assignments and unknown parameter names. Veryl's previous unknown-top behavior silently ignored typos, including names that exist only on a child module; update that regression to require rejection without retargeting the child. Validation: - Full celox-vpi suite with SystemVerilog, including 10 project CLI tests for precedence, duplicates, aliases, dependent parameters, native image width/value, unchanged source, and invalid input. - 256 parameter/backend regressions (89 param_override, 4 param_override_width, 163 parameterized_ops). - NAPI build and 6 JS parameter integration tests; affected-crate Clippy with warnings denied and formatting. - Original fpganinja/taxi top at cc70b270b910d369ab1ad7b3855e76399fd461f1, with no RTL/Python edits: 9/9 cocotb tests at O1 and 9/9 at O2. The manifest supplies ID_EN=1 and CLI DEST_EN=1 overrides the manifest's DEST_EN=0. O2 lists observed interface signals in live_signals. After rebasing onto master, both runs pass without additional patches: master includes the #1441 event metadata and #1570 callback-order fixes. All 3 cocotb integration tests also pass. The updated CLI preserves the master O2 default for run and O1 for vpi build. BREAKING CHANGE: Unknown Veryl top parameter overrides now fail compilation instead of being silently ignored. This also affects SimulatorBuilder::param callers and parameter overrides passed through NAPI. Depends-On: https://github.com/celox-sim/celox/pull/1579 Change-Id: I7a792c472bd9810fdca4f5034b9f6bb004332eeb --- crates/celox-vpi/src/bin/celox.rs | 17 ++- crates/celox-vpi/src/bin/celox/project.rs | 92 ++++++++++++++ crates/celox-vpi/src/driver.rs | 36 +++++- crates/celox-vpi/tests/project_cli.rs | 144 ++++++++++++++++++++++ crates/celox/src/simulator/builder.rs | 14 +++ crates/celox/tests/param_override.rs | 27 +++- docs/guide/celox-toml.md | 35 ++++++ docs/ja/guide/celox-toml.md | 23 ++++ 8 files changed, 373 insertions(+), 15 deletions(-) diff --git a/crates/celox-vpi/src/bin/celox.rs b/crates/celox-vpi/src/bin/celox.rs index 82497626db9..89dde289003 100644 --- a/crates/celox-vpi/src/bin/celox.rs +++ b/crates/celox-vpi/src/bin/celox.rs @@ -164,6 +164,7 @@ fn run_testbench(arguments: RunArgs) -> Result<(), String> { .opt_level(arguments.opt_level) .diagnostic_policy(arguments.design.diagnostics.clone()) .signal_access(arguments.design.signal_access.clone()); + builder = arguments.design.apply_parameters(builder); if let Some(metadata) = metadata { builder = builder.with_metadata(metadata); } @@ -198,11 +199,14 @@ fn run_sv(arguments: RunConfig) -> Result<(), String> { .iter() .map(|(text, path)| (text.as_str(), path.as_path())) .collect(); - let simulation = celox::Simulation::from_sv_sources(source_refs, &arguments.design.top) + let builder = celox::Simulation::from_sv_sources(source_refs, &arguments.design.top) .four_state(true) .opt_level(arguments.opt_level) .diagnostic_policy(arguments.design.diagnostics.clone()) - .signal_access(arguments.design.signal_access.clone()) + .signal_access(arguments.design.signal_access.clone()); + let simulation = arguments + .design + .apply_parameters(builder) .build() .map_err(|error| format!("compilation failed:\n{error}"))?; report_warnings(simulation.warnings())?; @@ -430,11 +434,13 @@ fn compile_native_design(design: &Design) -> Result .iter() .map(|(text, path)| (text.as_str(), path.as_path())) .collect(); - let simulator = celox::Simulator::from_sv_sources(refs, &design.top) + let builder = celox::Simulator::from_sv_sources(refs, &design.top) .four_state(true) .diagnostic_policy(design.diagnostics.clone()) .signal_access(design.signal_access.clone()) - .opt_level(design.opt_level.unwrap_or(celox::OptLevel::O1)) + .opt_level(design.opt_level.unwrap_or(celox::OptLevel::O1)); + let simulator = design + .apply_parameters(builder) .build() .map_err(|error| format!("compilation failed:\n{error}"))?; report_warnings(simulator.warnings())?; @@ -453,12 +459,13 @@ fn compile_native_design(design: &Design) -> Result { return Err("pass .sv/.v sources, or one .veryl project entry file".to_string()); } - let (image, warnings) = celox_vpi::driver::compile_native_image_with_options( + let (image, warnings) = celox_vpi::driver::compile_native_image_with_parameters( &design.sources[0], &design.top, design.diagnostics.clone(), design.opt_level.unwrap_or(celox::OptLevel::O1), design.signal_access.clone(), + &design.parameters, )?; report_warnings(&warnings)?; Ok(image) diff --git a/crates/celox-vpi/src/bin/celox/project.rs b/crates/celox-vpi/src/bin/celox/project.rs index 7dee4979c58..49073eaddfd 100644 --- a/crates/celox-vpi/src/bin/celox/project.rs +++ b/crates/celox-vpi/src/bin/celox/project.rs @@ -53,6 +53,14 @@ pub(super) struct DesignArgs { /// SystemVerilog macro, NAME or NAME=VALUE (repeatable; last value wins). #[arg(short = 'D', long = "define", value_name = "NAME[=VALUE]")] defines: Vec, + /// Override a numeric top parameter (repeatable; last value wins). + #[arg( + short = 'G', + long = "parameter", + visible_alias = "param", + value_name = "NAME=VALUE" + )] + parameters: Vec, /// Top-level module; overrides the selected target. #[arg(long)] top: Option, @@ -73,6 +81,7 @@ struct Manifest { filelists: Vec, include_dirs: Vec, defines: BTreeMap, + parameters: BTreeMap, top: Option, opt_level: Option, live_signals: Option>, @@ -90,6 +99,7 @@ struct Target { filelists: Vec, include_dirs: Vec, defines: BTreeMap, + parameters: BTreeMap, top: Option, opt_level: Option, live_signals: Option>, @@ -103,6 +113,7 @@ pub(super) struct Design { pub sources: Vec, pub include_dirs: Vec, pub defines: BTreeMap, + pub parameters: BTreeMap, pub top: String, pub opt_level: Option, pub signal_access: celox::SignalAccessOptions, @@ -194,6 +205,7 @@ impl DesignArgs { &config.include_dirs, &config.defines, )?; + design.extend_parameters(&config.parameters)?; design.diagnostics = config.diagnostics.clone(); design.top = config.top.clone().unwrap_or_default(); let mut opt_level = config.opt_level.as_deref(); @@ -201,6 +213,7 @@ impl DesignArgs { design.signal_access.force_signals = config.force_signals.clone().unwrap_or_default(); design.max_steps = config.max_steps; if let Some(target) = selected { + design.extend_parameters(&target.parameters)?; design.diagnostics.0.extend(target.diagnostics.0.clone()); design.extend( base, @@ -266,6 +279,12 @@ impl DesignArgs { for define in &self.defines { design.define(define)?; } + for parameter in self.parameters { + let (name, value) = parameter + .split_once('=') + .ok_or_else(|| format!("invalid parameter `{parameter}`: expected NAME=VALUE"))?; + design.set_parameter(name, parse_parameter_value(value)?)?; + } if let Some(top) = self.top { design.top = top; } @@ -286,7 +305,80 @@ impl DesignArgs { } } +/// TOML integers cover ordinary values; strings also permit radix prefixes +/// and the full unsigned 64-bit range supported by SimulatorBuilder::param. +#[derive(Deserialize)] +#[serde(untagged)] +enum ParameterValue { + Integer(u64), + String(String), +} + +fn parse_parameter_value(value: &str) -> Result { + let (radix, digits) = if let Some(digits) = value.strip_prefix("0x") { + (16, digits) + } else if let Some(digits) = value.strip_prefix("0b") { + (2, digits) + } else if let Some(digits) = value.strip_prefix("0o") { + (8, digits) + } else { + (10, value) + }; + let invalid = || { + format!( + "invalid parameter value `{value}`: expected an unsigned 64-bit integer (decimal, 0x, 0o, or 0b)" + ) + }; + if digits.is_empty() + || digits.starts_with('_') + || digits.ends_with('_') + || digits.contains("__") + || digits.starts_with('+') + { + return Err(invalid()); + } + u64::from_str_radix(&digits.replace('_', ""), radix).map_err(|_| invalid()) +} + impl Design { + pub fn apply_parameters<'a, T>( + &self, + mut builder: celox::SimulatorBuilder<'a, T>, + ) -> celox::SimulatorBuilder<'a, T> { + for (name, value) in &self.parameters { + builder = builder.param(name, *value); + } + builder + } + + fn extend_parameters( + &mut self, + parameters: &BTreeMap, + ) -> Result<(), String> { + for (name, value) in parameters { + let value = match value { + ParameterValue::Integer(value) => *value, + ParameterValue::String(value) => parse_parameter_value(value)?, + }; + self.set_parameter(name, value)?; + } + Ok(()) + } + + fn set_parameter(&mut self, name: &str, value: u64) -> Result<(), String> { + if name.is_empty() + || !name.bytes().enumerate().all(|(index, byte)| { + byte == b'_' + || byte.is_ascii_alphabetic() + || (index != 0 && (byte.is_ascii_digit() || byte == b'$')) + }) + { + return Err(format!("invalid top parameter name `{name}`")); + } + self.parameters.insert(name.to_string(), value); + Ok(()) + } + pub fn is_sv(&self) -> bool { self.sources.iter().all(|path| { path.extension() diff --git a/crates/celox-vpi/src/driver.rs b/crates/celox-vpi/src/driver.rs index 442a5c2b154..9c7f09adb60 100644 --- a/crates/celox-vpi/src/driver.rs +++ b/crates/celox-vpi/src/driver.rs @@ -1,6 +1,6 @@ //! Shared compiler and cocotb runtime entry points used by the command-line tools. -use std::path::Path; +use std::{collections::BTreeMap, path::Path}; use celox::{ CompilationWarning, DiagnosticPolicy, NativeProgramImage, NativeProgramInstance, Simulator, @@ -61,6 +61,7 @@ pub fn compile_native_image_with_diagnostics( celox::OptLevel::O0, celox::SignalAccessOptions::default(), true, + &BTreeMap::new(), ) } @@ -72,7 +73,19 @@ pub fn compile_native_image_with_options( level: celox::OptLevel, access: celox::SignalAccessOptions, ) -> Result<(NativeProgramImage, Vec), String> { - compile_native_image_configured(source, top, policy, level, access, false) + compile_native_image_with_parameters(source, top, policy, level, access, &BTreeMap::new()) +} + +/// Compile with numeric top parameter overrides, leaving project source files intact. +pub fn compile_native_image_with_parameters( + source: &Path, + top: &str, + policy: DiagnosticPolicy, + level: celox::OptLevel, + access: celox::SignalAccessOptions, + parameters: &BTreeMap, +) -> Result<(NativeProgramImage, Vec), String> { + compile_native_image_configured(source, top, policy, level, access, false, parameters) } fn compile_native_image_configured( @@ -82,6 +95,7 @@ fn compile_native_image_configured( level: celox::OptLevel, access: celox::SignalAccessOptions, legacy_force: bool, + parameters: &BTreeMap, ) -> Result<(NativeProgramImage, Vec), String> { let simulator = if let Ok(metadata_path) = Metadata::search_from(source) { let mut metadata = Metadata::load(&metadata_path) @@ -101,23 +115,33 @@ fn compile_native_image_configured( .iter() .map(|(contents, path)| (contents.as_str(), path.as_path())) .collect::>(); - Simulator::from_sources(source_refs, top) + let builder = Simulator::from_sources(source_refs, top) .with_metadata(metadata) .diagnostic_policy(policy.clone()) .four_state(true) .native_force_support(legacy_force) .signal_access(access.clone()) - .opt_level(level) + .opt_level(level); + parameters + .iter() + .fold(builder, |builder, (name, value)| { + builder.param(name, *value) + }) .build() } else { let contents = std::fs::read_to_string(source) .map_err(|error| format!("failed to read {}: {error}", source.display()))?; - Simulator::from_sources(vec![(contents.as_str(), source)], top) + let builder = Simulator::from_sources(vec![(contents.as_str(), source)], top) .diagnostic_policy(policy.clone()) .four_state(true) .native_force_support(legacy_force) .signal_access(access.clone()) - .opt_level(level) + .opt_level(level); + parameters + .iter() + .fold(builder, |builder, (name, value)| { + builder.param(name, *value) + }) .build() } .map_err(|error| format!("compilation failed: {error}"))?; diff --git a/crates/celox-vpi/tests/project_cli.rs b/crates/celox-vpi/tests/project_cli.rs index cc19f775f52..3cde4fd21cc 100644 --- a/crates/celox-vpi/tests/project_cli.rs +++ b/crates/celox-vpi/tests/project_cli.rs @@ -425,3 +425,147 @@ fn native_build_applies_target_and_cli_signal_access_contracts() { assert!(!output.status.success()); assert!(String::from_utf8_lossy(&output.stderr).contains("Top.typo")); } + +#[cfg(feature = "systemverilog")] +#[test] +fn top_parameters_merge_common_target_and_cli_without_editing_sv() { + let root = tempfile::tempdir().unwrap(); + let source = "module Top #(parameter W=8, parameter V=1, parameter NEXT=V+1) (output logic [W-1:0] y); assign y=NEXT; initial begin #1; $display(\"v=%0d w=%0d\", y, $bits(y)); $finish; end endmodule"; + fs::write(root.path().join("top.sv"), source).unwrap(); + fs::write( + root.path().join("celox.toml"), + r#" + sources = ["top.sv"] + top = "Top" + [parameters] + W = 8 + V = 2 + [targets.wide.parameters] + W = 16 + V = "0x1233" + "#, + ) + .unwrap(); + let output = invoke(root.path(), &["run", "--target", "wide"]); + success(&output); + assert_eq!(output.stdout, b"v=4660 w=16\n"); + let output = invoke( + root.path(), + &[ + "run", + "--target", + "wide", + "-GV=0b11", + "--parameter", + "V=0o10", + ], + ); + success(&output); + assert_eq!(output.stdout, b"v=9 w=16\n"); + success(&invoke( + root.path(), + &[ + "vpi", + "build", + "--target", + "wide", + "--param", + "V=18446744073709551615", + "-o", + "sim", + ], + )); + let bytes = fs::read(root.path().join("sim")).unwrap(); + let image = celox::NativeProgramImage::discover_appended(&bytes) + .unwrap() + .unwrap() + .image; + // Safety: the CLI just compiled this test's source. + let sim = unsafe { celox::NativeProgramInstance::from_image(image) }.unwrap(); + let signal = sim.signal_ref("Top.y").unwrap(); + assert_eq!(signal.width, 16); + assert_eq!(celox::SimBackend::get_as::(sim.backend(), signal), 0); + assert_eq!( + fs::read_to_string(root.path().join("top.sv")).unwrap(), + source + ); + let output = invoke(root.path(), &["run", "--target", "wide", "-GMISSING=1"]); + assert!(!output.status.success()); + assert!( + String::from_utf8_lossy(&output.stderr).contains("unknown top-level parameter override") + ); +} + +#[test] +fn top_parameters_reach_veryl_run_and_native_build() { + let root = tempfile::tempdir().unwrap(); + fs::write( + root.path().join("tb.veryl"), + "#[test(Top)] module Top #(param V: u32 = 1) { initial { $assert(V == 7); $finish(); } }", + ) + .unwrap(); + success(&invoke( + root.path(), + &["run", "tb.veryl", "--top", "Top", "-G", "V=7"], + )); + fs::write( + root.path().join("dut.veryl"), + "module Top #(param W: u32 = 8, param V: u32 = 1) (y: output logic) { assign y=V; }", + ) + .unwrap(); + success(&invoke( + root.path(), + &[ + "vpi", + "build", + "dut.veryl", + "--top", + "Top", + "-GW=16", + "-GV=0x1234", + "-o", + "sim", + ], + )); + let bytes = fs::read(root.path().join("sim")).unwrap(); + let image = celox::NativeProgramImage::discover_appended(&bytes) + .unwrap() + .unwrap() + .image; + // Safety: the CLI just compiled this test's source. + let sim = unsafe { celox::NativeProgramInstance::from_image(image) }.unwrap(); + let signal = sim.signal_ref("Top.y").unwrap(); + assert_eq!(signal.width, 16); + assert_eq!( + celox::SimBackend::get_as::(sim.backend(), signal), + 0x1234 + ); + let output = invoke( + root.path(), + &["vpi", "build", "dut.veryl", "--top", "Top", "-GWIDHT=16"], + ); + assert!(!output.status.success()); + assert!( + String::from_utf8_lossy(&output.stderr).contains("unknown top-level parameter override") + ); +} + +#[test] +fn invalid_parameter_assignments_are_rejected() { + let root = tempfile::tempdir().unwrap(); + for value in [ + "V", + "=1", + "x.y=1", + "V=", + "V=-1", + "V=1+2", + "V=18446744073709551616", + "V=0x", + "V=0b2", + "V=_1", + ] { + let output = invoke(root.path(), &["run", "dut.sv", "--top", "Top", "-G", value]); + rejected(&output, "parameter"); + } +} diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 13193247e64..a76a0547bbf 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -176,6 +176,20 @@ pub(super) fn elaborate_parameterized_module( .map(|(name, value)| (resource_table::insert_str(name), value.clone())) .collect(); + for name in values.keys() { + if !property + .parameters + .iter() + .any(|parameter| parameter.name == *name) + { + return Err(ParserError::illegal_context( + "top-level parameter override", + format!("unknown top-level parameter override `{name}`"), + Some(&top_token), + )); + } + } + // push_override expects expressions that have already been evaluated in // the formal parameter type (as get_overridden_params does for HDL insts). // Resolve the header in declaration order so dependent widths/defaults see diff --git a/crates/celox/tests/param_override.rs b/crates/celox/tests/param_override.rs index 8111ca3a862..60f80a41e95 100644 --- a/crates/celox/tests/param_override.rs +++ b/crates/celox/tests/param_override.rs @@ -329,7 +329,7 @@ fn test_top_param_override_does_not_change_child_default() { } #[test] -fn test_unknown_top_param_does_not_override_child_param() { +fn test_unknown_top_param_cannot_target_child_param() { let code = r#" module Child #( param WIDTH: u32 = 3, @@ -348,10 +348,29 @@ fn test_unknown_top_param_does_not_override_child_param() { } "#; - let mut sim = Simulator::builder(code, "Top") + let error = Simulator::builder(code, "Top") .param("WIDTH", 16) .build() - .unwrap(); + .err() + .unwrap() + .to_string(); + assert!( + error.contains("unknown top-level parameter override `WIDTH`"), + "{error}" + ); +} - assert_eq!(sim.get(sim.signal("value")), 3u32.into()); +#[test] +fn unknown_top_parameter_override_is_rejected() { + let source = "module Top #(param WIDTH: u32 = 8) (y: output logic) { assign y=0; }"; + let error = Simulator::builder(source, "Top") + .param("WIDHT", 16) + .build() + .err() + .unwrap() + .to_string(); + assert!( + error.contains("unknown top-level parameter override `WIDHT`"), + "{error}" + ); } diff --git a/docs/guide/celox-toml.md b/docs/guide/celox-toml.md index ae045b83a79..7709d31d8b9 100644 --- a/docs/guide/celox-toml.md +++ b/docs/guide/celox-toml.md @@ -229,3 +229,38 @@ and `[]` clears it. Repeat `--live-signal` or `--force-signal` for multiple path `--no-live-signals` and `--no-force-signals` clear inherited lists and conflict with the corresponding path options. These settings apply to the two CLI compilation commands; JavaScript simulator options are configured separately. + +## CLI top parameter overrides + +Both `run` and `vpi build` accept repeatable `-G NAME=VALUE` or +`--parameter NAME=VALUE` (`--param` is an alias). These override numeric +parameters of the selected top module in SystemVerilog or Veryl, before +elaboration, without modifying source files. + +```sh +celox vpi build --project celox.toml -G ID_EN=1 -G DEST_EN=1 -o dut-sim +``` + +```toml +sources = ["top.sv"] +top = "Top" + +[parameters] +ID_EN = 1 +DEST_EN = 1 +DATA_W = 8 + +[targets.wide.parameters] +DATA_W = 64 +``` + +Common parameters are merged with the selected target's parameters, followed +by CLI assignments. The last assignment to each name wins; unrelated entries +are inherited. Values are unsigned 64-bit integers: decimal, `0x` hexadecimal, +`0o` octal, or `0b` binary. Digit separators such as `0x12_34` are accepted. +TOML values can be integers or strings (`DATA_W = "0x40"`); use strings for +values above TOML's signed 64-bit integer range. Negative numbers, HDL +expressions/literals, strings as HDL values, and type parameters are not +supported by this interface. Declared HDL parameter types still determine +conversion and truncation. Invalid assignments and unknown parameter names +produce errors. diff --git a/docs/ja/guide/celox-toml.md b/docs/ja/guide/celox-toml.md index 21735388d2b..df0b71e3556 100644 --- a/docs/ja/guide/celox-toml.md +++ b/docs/ja/guide/celox-toml.md @@ -181,3 +181,26 @@ celox run --project celox.toml --target observe --no-force-signals ``` 共通設定→選択したターゲット→CLIの順に優先されます。信号リストは全体を置き換えます。ターゲットで省略したリストは共通設定を継承し、`[]` で空にできます。CLIでは `--live-signal` / `--force-signal` を繰り返して列挙し、`--no-live-signals` / `--no-force-signals` で継承したリストを空にできます。リストを空にするオプションと、対応するパス指定は併用できません。これらの設定はCLIの2つのコンパイルコマンドに適用されます。JavaScriptのシミュレータオプションは別に指定します。 + +## CLIのtopパラメータ指定 + +`run` と `vpi build` では、`-G NAME=VALUE` または `--parameter NAME=VALUE` を繰り返し指定できます(`--param` も同じ意味です)。選択したtopモジュールの数値パラメータをエラボレーション前に上書きします。SystemVerilog・Verylの両方で使え、ソースの書き換えは不要です。 + +```sh +celox vpi build --project celox.toml -G ID_EN=1 -G DEST_EN=1 -o dut-sim +``` + +```toml +sources = ["top.sv"] +top = "Top" + +[parameters] +ID_EN = 1 +DEST_EN = 1 +DATA_W = 8 + +[targets.wide.parameters] +DATA_W = 64 +``` + +共通設定→選択したターゲット→CLIの順に、パラメータ名ごとに上書きします。同じ名前の最後の指定が有効になり、他の名前の指定は継承します。値は符号なし64bit整数で、10進数・`0x`(16進)・`0o`(8進)・`0b`(2進)を使えます。`0x12_34` のような桁区切りも使えます。TOMLでは整数または文字列(`DATA_W = "0x40"`)で指定し、TOMLの符号付き64bit整数の範囲を超える値は文字列にします。負数、HDLの式やリテラル、HDLの文字列値、型パラメータには対応していません。型変換と切り詰めには、HDL側で宣言したパラメータの型が使われます。不正な指定や存在しないパラメータ名はエラーになります。