From f27f368637324c566606642da8e970b8b47e613d Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 21 Oct 2026 10:17:55 +0900 Subject: [PATCH 1/3] feat(cli): configure SV simulation timescales Taxi's BASE-R gearbox tests request 1ns/1fs, but the CLI had no way to pass that setting to compilation. Their 6.206206ns cocotb clocks failed with the source modules' 1ps simulation resolution. Add --timescale UNIT/PRECISION to run and vpi build, with matching root and target settings in celox.toml and a validated Rust builder option. The selected precision contributes to global scheduler resolution. Preserve explicit source units and delay rounding, finer source precision, and the separate mixed_timescale diagnostic policy. Keep 1ns/1ps when no option is supplied. Validation: - 17 project CLI tests, including precedence, invalid values, run, and attached-image precision. - 6 timing API tests across interpreter, Cranelift, native and WASM, plus mixed-language interface probes; 11 diagnostic-policy tests. - SV analyzer: 762 passed, 3 existing ignores; shared SV suite: 3242 passed, 90 existing ignores. - cocotb 2.1: all 5 integration tests passed; the new femtosecond-clock test also passed with 2.0.1. - Taxi cc70b270b910d369ab1ad7b3855e76399fd461f1: 20 BASE-R cases passed at O1 with gearbox configurations 1/2 and USXGMII disabled; 220 other cases were filtered out. Original sources, parameters, and clock periods were retained. - Formatting, affected-crate all-target Clippy, and celox without default features passed. Change-Id: I6e723be119270564f5b71b08a7b83744d7eadba9 --- crates/celox-sv-analyzer/src/ast.rs | 2 +- .../celox-sv-analyzer/src/ast/interfaces.rs | 7 +- crates/celox-sv-analyzer/src/ast/packages.rs | 11 ++- .../celox-sv-analyzer/src/ast/timescales.rs | 35 +++++--- crates/celox-sv-analyzer/src/lib.rs | 6 +- crates/celox-sv-analyzer/src/parsed.rs | 3 +- crates/celox-vpi/src/bin/celox.rs | 2 + crates/celox-vpi/src/bin/celox/project.rs | 15 ++++ crates/celox-vpi/tests/cocotb_e2e.rs | 21 +++++ .../tests/fixtures/cocotb/test_fs_clock.py | 18 +++++ crates/celox-vpi/tests/project_cli.rs | 63 +++++++++++++++ crates/celox/src/diagnostic_policy.rs | 6 +- crates/celox/src/lib.rs | 3 + crates/celox/src/parser.rs | 6 +- crates/celox/src/simulator/builder.rs | 36 ++++++++- crates/celox/src/timescale.rs | 77 ++++++++++++++++++ crates/celox/tests/sv_timescale_options.rs | 80 +++++++++++++++++++ docs/guide/celox-toml.md | 15 ++++ docs/ja/guide/celox-toml.md | 15 ++++ 19 files changed, 389 insertions(+), 32 deletions(-) create mode 100644 crates/celox-vpi/tests/fixtures/cocotb/test_fs_clock.py create mode 100644 crates/celox/src/timescale.rs create mode 100644 crates/celox/tests/sv_timescale_options.rs diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 23794d3418f..6b4448933f1 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -1428,7 +1428,7 @@ pub(crate) fn generated_time_declarations( sources: &[(&str, &std::path::Path)], roots: Option<&[&str]>, ) -> Result { - timescales::generated_source_declarations(sources, roots, false) + timescales::generated_source_declarations(sources, roots, crate::AnalysisOptions::default()) } const MAX_GENERATE_LOOP_EXPANSION: usize = 10_000; diff --git a/crates/celox-sv-analyzer/src/ast/interfaces.rs b/crates/celox-sv-analyzer/src/ast/interfaces.rs index fabbf9e9a25..c7a6e0db247 100644 --- a/crates/celox-sv-analyzer/src/ast/interfaces.rs +++ b/crates/celox-sv-analyzer/src/ast/interfaces.rs @@ -89,7 +89,7 @@ pub fn interface_prototypes_with_options( .zip(sources) .map(|(file, (_, path))| (&file.syntax_tree, *path)) .collect::>(), - options.allow_mixed_timescales, + options, )?) }; let trees = files @@ -97,9 +97,8 @@ pub fn interface_prototypes_with_options( .zip(sources) .map(|(file, (_, path))| (&file.syntax_tree, *path)) .collect::>(); - let packages = - packages::Packages::analyze_with_options(&trees, None, options.allow_mixed_timescales) - .map_err(|error| error.with_warnings(source_warnings))?; + let packages = packages::Packages::analyze_with_options(&trees, None, options) + .map_err(|error| error.with_warnings(source_warnings))?; let package_warnings = packages.warnings().to_vec(); let mut used_names = design .modules diff --git a/crates/celox-sv-analyzer/src/ast/packages.rs b/crates/celox-sv-analyzer/src/ast/packages.rs index c32ab382d95..734d9669bc0 100644 --- a/crates/celox-sv-analyzer/src/ast/packages.rs +++ b/crates/celox-sv-analyzer/src/ast/packages.rs @@ -197,19 +197,19 @@ impl Packages { trees: &[(&SyntaxTree, &Path)], roots: Option<&[&str]>, ) -> Result { - Self::analyze_with_options(trees, roots, false) + Self::analyze_with_options(trees, roots, crate::AnalysisOptions::default()) } pub(crate) fn analyze_with_options( trees: &[(&SyntaxTree, &Path)], roots: Option<&[&str]>, - allow_mixed_timescales: bool, + options: crate::AnalysisOptions, ) -> Result { let mut warnings = Vec::new(); for (tree, _) in trees { super::warnings::append(&mut warnings, super::warnings::packages(tree)); } - match Self::analyze_with_roots_impl(trees, roots, allow_mixed_timescales) { + match Self::analyze_with_roots_impl(trees, roots, options) { Ok(packages) => Ok(packages.with_warnings(warnings)), Err(error) => Err(error.with_warnings(warnings)), } @@ -218,10 +218,9 @@ impl Packages { fn analyze_with_roots_impl( trees: &[(&SyntaxTree, &Path)], roots: Option<&[&str]>, - allow_mixed_timescales: bool, + options: crate::AnalysisOptions, ) -> Result { - let mut timescales = - timescales::Timescales::collect_with_options(trees, allow_mixed_timescales)?; + let mut timescales = timescales::Timescales::collect_with_options(trees, options)?; if let Some(roots) = roots { timescales.select_roots(roots); } diff --git a/crates/celox-sv-analyzer/src/ast/timescales.rs b/crates/celox-sv-analyzer/src/ast/timescales.rs index 4b04f9a5316..6a2096d3e65 100644 --- a/crates/celox-sv-analyzer/src/ast/timescales.rs +++ b/crates/celox-sv-analyzer/src/ast/timescales.rs @@ -107,7 +107,7 @@ pub(super) struct Timescales { instantiated: HashSet, roots: Option>, specified: [u8; 2], - allow_mixed_timescales: bool, + options: crate::AnalysisOptions, } /// Time-query state owned by one analysis, shared explicitly by nested scopes. @@ -361,7 +361,7 @@ fn time_declarations(unit: Option, precision: Option) -> String { pub(crate) fn generated_source_declarations( sources: &[(&str, &Path)], roots: Option<&[&str]>, - allow_mixed_timescales: bool, + options: crate::AnalysisOptions, ) -> Converted { let trees = sources .iter() @@ -372,7 +372,7 @@ pub(crate) fn generated_source_declarations( .iter() .map(|(tree, path)| (tree, *path)) .collect::>(), - allow_mixed_timescales, + options, )?; if let Some(roots) = roots { scales.select_roots(roots); @@ -516,13 +516,12 @@ impl Timescales { self.precision.unwrap_or(DEFAULT.precision) } fn including_tree(&self, tree: &SyntaxTree) -> Converted { - let local = - Self::collect_with_options(&[(tree, Path::new(""))], self.allow_mixed_timescales)?; + let local = Self::collect_with_options(&[(tree, Path::new(""))], self.options)?; let specified = [ self.specified[0] | local.specified[0], self.specified[1] | local.specified[1], ]; - if specified.contains(&3) && !self.allow_mixed_timescales { + if specified.contains(&3) && !self.options.allow_mixed_timescales { return Err(unsupported( "mixed explicit and default time units or precisions across design elements", )); @@ -577,17 +576,29 @@ impl Timescales { #[cfg(test)] pub(super) fn collect(trees: &[(&SyntaxTree, &Path)]) -> Converted { - Self::collect_with_options(trees, false) + Self::collect_with_options(trees, crate::AnalysisOptions::default()) } pub(super) fn collect_with_options( trees: &[(&SyntaxTree, &Path)], - allow_mixed_timescales: bool, + options: crate::AnalysisOptions, ) -> Converted { #[cfg(test)] COLLECTIONS.with(|count| count.set(count.get() + 1)); + let default = match options.default_timescale { + Some((unit, precision)) + if (-15..=2).contains(&unit) + && (-15..=2).contains(&precision) + && precision <= unit => + { + Scale { unit, precision } + } + Some(_) => return Err(unsupported("invalid default time unit or precision")), + None => DEFAULT, + }; let mut design = Self { - allow_mixed_timescales, + precision: options.default_timescale.map(|(_, precision)| precision), + options, ..Self::default() }; // Each bit records whether a design element uses a default (1) or an @@ -686,8 +697,8 @@ impl Timescales { } directives.sort_by_key(|(at, _)| *at); let unit = Scale { - unit: unit_decl.0.unwrap_or(DEFAULT.unit), - precision: unit_decl.1.unwrap_or(DEFAULT.precision), + unit: unit_decl.0.unwrap_or(default.unit), + precision: unit_decl.1.unwrap_or(default.precision), }; if unit.precision > unit.unit { return Err(unsupported("timeprecision coarser than timeunit")); @@ -740,7 +751,7 @@ impl Timescales { }), ); } - if specified.contains(&3) && !allow_mixed_timescales { + if specified.contains(&3) && !options.allow_mixed_timescales { return Err(unsupported( "mixed explicit and default time units or precisions across design elements", )); diff --git a/crates/celox-sv-analyzer/src/lib.rs b/crates/celox-sv-analyzer/src/lib.rs index a9deafc2c07..b1a6961fb1a 100644 --- a/crates/celox-sv-analyzer/src/lib.rs +++ b/crates/celox-sv-analyzer/src/lib.rs @@ -44,10 +44,12 @@ pub use parsed::ParsedSource; /// simulator's two-state/four-state mode is known. pub const DIV_ZERO_UNKNOWN_LITERAL: &str = "$celox_div_zero_unknown"; -/// Options for recoverable language compatibility checks. +/// Language compatibility checks and implementation-defined timing defaults. #[derive(Debug, Clone, Copy, Default)] pub struct AnalysisOptions { pub allow_mixed_timescales: bool, + /// Default unit/precision exponents; precision also bounds global resolution. + pub default_timescale: Option<(i32, i32)>, } /// Errors reported by the SystemVerilog analyzer. @@ -246,7 +248,7 @@ pub fn generated_time_declarations_with_options( roots: Option<&[&str]>, options: AnalysisOptions, ) -> Result { - ast::timescales::generated_source_declarations(sources, roots, options.allow_mixed_timescales) + ast::timescales::generated_source_declarations(sources, roots, options) } /// Parse and analyze a SystemVerilog source string. diff --git a/crates/celox-sv-analyzer/src/parsed.rs b/crates/celox-sv-analyzer/src/parsed.rs index fb1b1d798df..300a5369603 100644 --- a/crates/celox-sv-analyzer/src/parsed.rs +++ b/crates/celox-sv-analyzer/src/parsed.rs @@ -130,8 +130,7 @@ impl ParsedSource { } } } - let mut packages = - Packages::analyze_with_options(&trees, roots, options.allow_mixed_timescales)?; + let mut packages = Packages::analyze_with_options(&trees, roots, options)?; packages.interface_names = design_units .into_iter() .filter_map(|(name, kind)| { diff --git a/crates/celox-vpi/src/bin/celox.rs b/crates/celox-vpi/src/bin/celox.rs index 46d2a3882eb..399a7fd538a 100644 --- a/crates/celox-vpi/src/bin/celox.rs +++ b/crates/celox-vpi/src/bin/celox.rs @@ -160,6 +160,7 @@ fn run_sv(arguments: RunConfig) -> Result<(), String> { .threads(arguments.execution.threads as usize) .opt_level(arguments.opt_level) .diagnostic_policy(arguments.design.diagnostics.clone()) + .sv_timescale(arguments.design.timescale) .signal_access(arguments.design.signal_access.clone()); let builder = arguments.design.apply_parameters(builder); let max_steps = if arguments.execution.unlimited { @@ -405,6 +406,7 @@ fn compile_native_design(design: &Design) -> Result let builder = celox::Simulator::from_sv_sources(refs, &design.top) .four_state(design.four_state.unwrap_or(false)) .diagnostic_policy(design.diagnostics.clone()) + .sv_timescale(design.timescale) .signal_access(design.signal_access.clone()) .opt_level(design.opt_level.unwrap_or(celox::OptLevel::O1)); let simulator = design diff --git a/crates/celox-vpi/src/bin/celox/project.rs b/crates/celox-vpi/src/bin/celox/project.rs index f3082b12cb5..99fa3b8341b 100644 --- a/crates/celox-vpi/src/bin/celox/project.rs +++ b/crates/celox-vpi/src/bin/celox/project.rs @@ -18,6 +18,9 @@ pub(super) struct DesignArgs { /// Override a compilation diagnostic: CODE=allow|warn|error (repeatable). #[arg(long = "diagnostic", value_name = "CODE=LEVEL")] diagnostics: Vec, + /// Default SV UNIT/PRECISION and global scheduler resolution, e.g. 1ns/1fs. + #[arg(long, value_name = "UNIT/PRECISION")] + timescale: Option, /// Use two-state simulation, resolving X/Z to zero. #[arg(long, conflicts_with = "four_state")] two_state: bool, @@ -102,6 +105,7 @@ struct Manifest { top: Option, opt_level: Option, four_state: Option, + timescale: Option, live_signals: Option>, force_signals: Option>, max_steps: Option, @@ -135,6 +139,7 @@ struct Target { top: Option, opt_level: Option, four_state: Option, + timescale: Option, live_signals: Option>, force_signals: Option>, max_steps: Option, @@ -152,6 +157,7 @@ pub(super) struct Design { pub top: String, pub opt_level: Option, pub four_state: Option, + pub timescale: Option, pub signal_access: celox::SignalAccessOptions, pub max_steps: Option, } @@ -281,6 +287,7 @@ impl DesignArgs { design.diagnostics = config.diagnostics.clone(); design.top = config.top.clone().unwrap_or_default(); let mut opt_level = config.opt_level.as_deref(); + let mut timescale = config.timescale.as_deref(); design.signal_access.live_signals = config.live_signals.clone().unwrap_or_default(); design.signal_access.force_signals = config.force_signals.clone().unwrap_or_default(); @@ -300,6 +307,7 @@ impl DesignArgs { design.top.clone_from(top); } opt_level = target.opt_level.as_deref().or(opt_level); + timescale = target.timescale.as_deref().or(timescale); if let Some(paths) = &target.live_signals { design.signal_access.live_signals.clone_from(paths); } @@ -309,6 +317,7 @@ impl DesignArgs { design.max_steps = target.max_steps.or(design.max_steps); design.four_state = target.four_state.or(design.four_state); } + design.timescale = timescale.map(str::parse).transpose()?; design.opt_level = opt_level .map(|value| { celox::OptLevel::parse(value).ok_or_else(|| { @@ -334,6 +343,9 @@ impl DesignArgs { } })); design.opt_level = self.opt_level.or(design.opt_level); + if let Some(timescale) = self.timescale { + design.timescale = Some(timescale.parse()?); + } if self.two_state { design.four_state = Some(false); } @@ -390,6 +402,9 @@ impl DesignArgs { if design.top.trim().is_empty() { return Err("provide --top MODULE or set top in celox.toml".to_string()); } + if !design.is_sv() && design.timescale.is_some() { + return Err("timescale requires SystemVerilog sources".into()); + } if !design.is_sv() && !design.sv_parameters.is_empty() { return Err("SV parameter literals require .sv/.v sources".to_string()); } diff --git a/crates/celox-vpi/tests/cocotb_e2e.rs b/crates/celox-vpi/tests/cocotb_e2e.rs index d2049d78e88..2e41b9b75ca 100644 --- a/crates/celox-vpi/tests/cocotb_e2e.rs +++ b/crates/celox-vpi/tests/cocotb_e2e.rs @@ -102,7 +102,27 @@ fn cocotb_observes_edges_before_nonblocking_updates() { check_cocotb_native_design(&["edge_phase.sv"], "test_edge_phase", "edge_precedes_nba"); } +#[test] +#[ignore = "requires a cocotb installation; CI runs this test explicitly"] +fn cocotb_accepts_femtosecond_clock_periods() { + check_cocotb_native_design_with_options( + &["edge_phase.sv"], + "test_fs_clock", + "femtosecond_clock", + &["--timescale", "1ns/1fs"], + ); +} + fn check_cocotb_native_design(source: &[&str], module: &str, filter: &str) { + check_cocotb_native_design_with_options(source, module, filter, &[]); +} + +fn check_cocotb_native_design_with_options( + source: &[&str], + module: &str, + filter: &str, + options: &[&str], +) { let python = env::var_os("CELOX_COCOTB_PYTHON") .expect("CELOX_COCOTB_PYTHON must name the cocotb Python interpreter"); let python = python.to_string_lossy().into_owned(); @@ -115,6 +135,7 @@ fn check_cocotb_native_design(source: &[&str], module: &str, filter: &str) { .arg("vpi") .arg("build") .args(source.iter().map(|path| fixture.join(path))) + .args(options) .args(["--top", "Top", "--output"]) .arg(&executable) .output() diff --git a/crates/celox-vpi/tests/fixtures/cocotb/test_fs_clock.py b/crates/celox-vpi/tests/fixtures/cocotb/test_fs_clock.py new file mode 100644 index 00000000000..4d96c8c5a0d --- /dev/null +++ b/crates/celox-vpi/tests/fixtures/cocotb/test_fs_clock.py @@ -0,0 +1,18 @@ +"""The original 1ps SV scope can be driven by a 1fs-resolution testbench.""" +import cocotb +from cocotb.clock import Clock +from cocotb.triggers import RisingEdge, Timer +from cocotb.utils import get_sim_time + + +@cocotb.test() +async def femtosecond_clock(dut): + dut.d.value = 1 + clock = Clock(dut.clk, 6.206206, unit="ns") + cocotb.start_soon(clock.start()) + await RisingEdge(dut.clk) + first = get_sim_time(unit="fs") + await RisingEdge(dut.clk) + assert get_sim_time(unit="fs") - first == 6206206 + await Timer(1, unit="fs") + assert int(dut.q.value) == 1 diff --git a/crates/celox-vpi/tests/project_cli.rs b/crates/celox-vpi/tests/project_cli.rs index 06be274810f..d1b03347042 100644 --- a/crates/celox-vpi/tests/project_cli.rs +++ b/crates/celox-vpi/tests/project_cli.rs @@ -811,3 +811,66 @@ fn sv_cli_defaults_to_two_state_for_run_and_native_images() { let instance = unsafe { celox::NativeProgramInstance::from_image(image) }.unwrap(); assert!(!instance.four_state()); } + +#[cfg(feature = "systemverilog")] +#[test] +fn timescale_reaches_run_and_native_images_with_target_and_cli_precedence() { + let root = tempfile::tempdir().unwrap(); + fs::write( + root.path().join("top.sv"), + r#" +`timescale 1ns/1ps +module Top(input bit clk, output bit q); + always_ff @(posedge clk) q <= !q; + initial begin + $display("SCALE %0d %0d", $timeprecision(), $timeprecision($root)); + #1ns $finish; + end +endmodule +"#, + ) + .unwrap(); + fs::write( + root.path().join("celox.toml"), + r#" +sources = ["top.sv"] +top = "Top" +timescale = "1ns/10fs" +[targets.fine] +timescale = "1ns/1fs" +"#, + ) + .unwrap(); + for (options, precision) in [ + (vec![], -14), + (vec!["--target", "fine"], -15), + (vec!["--target", "fine", "--timescale", "10ns/100fs"], -13), + (vec!["--timescale", "1ns/10ps"], -12), + ] { + let output = invoke(root.path(), &[vec!["run"], options.clone()].concat()); + success(&output); + assert!( + String::from_utf8_lossy(&output.stdout).contains(&format!("SCALE -12 {precision}")), + "{output:?}" + ); + success(&invoke( + root.path(), + &[vec!["vpi", "build", "-o", "sim"], options].concat(), + )); + let bytes = fs::read(root.path().join("sim")).unwrap(); + // Safety: the test compiled this trusted runtime itself. + let instance = + unsafe { celox::NativeProgramInstance::from_attached_bytes(&bytes) }.unwrap(); + assert_eq!(instance.time_precision().exponent(), precision); + } + rejected( + &invoke(root.path(), &["run", "--timescale", "1ps/1ns"]), + "invalid timescale", + ); + fs::write( + root.path().join("celox.toml"), + "sources=['top.sv']\ntop='Top'\ntimescale='1ns/2fs'", + ) + .unwrap(); + rejected(&invoke(root.path(), &["run"]), "invalid timescale"); +} diff --git a/crates/celox/src/diagnostic_policy.rs b/crates/celox/src/diagnostic_policy.rs index 181e0a112e6..c09f126e789 100644 --- a/crates/celox/src/diagnostic_policy.rs +++ b/crates/celox/src/diagnostic_policy.rs @@ -83,9 +83,13 @@ impl DiagnosticPolicy { } #[cfg(feature = "systemverilog")] - pub(crate) fn sv_options(&self) -> celox_frontend_sv::AnalysisOptions { + pub(crate) fn sv_options( + &self, + timescale: Option, + ) -> celox_frontend_sv::AnalysisOptions { celox_frontend_sv::AnalysisOptions { allow_mixed_timescales: self.level("mixed_timescale") != DiagnosticLevel::Error, + default_timescale: timescale.map(|scale| (scale.unit, scale.precision)), } } diff --git a/crates/celox/src/lib.rs b/crates/celox/src/lib.rs index 364e49bfa1c..bebe2cb78c9 100644 --- a/crates/celox/src/lib.rs +++ b/crates/celox/src/lib.rs @@ -232,3 +232,6 @@ pub use diagnostic_policy::{DiagnosticLevel, DiagnosticPolicy}; mod signal_access; pub use signal_access::SignalAccessOptions; + +mod timescale; +pub use timescale::SvTimescale; diff --git a/crates/celox/src/parser.rs b/crates/celox/src/parser.rs index 36c5b0bc558..77cac6a231b 100644 --- a/crates/celox/src/parser.rs +++ b/crates/celox/src/parser.rs @@ -590,6 +590,7 @@ pub fn parse_sv( optimize_options: &crate::optimizer::OptimizeOptions, diagnostics: &crate::RuntimeDiagnostics, diagnostic_policy: &crate::DiagnosticPolicy, + sv_timescale: Option, preserve_element_storage_layout: bool, testbench_random_seed: Option, component_libraries: Vec, @@ -610,7 +611,7 @@ pub fn parse_sv( &frontend_trace_options, trace.is_some().then_some(&mut frontend_trace), warnings, - diagnostic_policy.sv_options(), + diagnostic_policy.sv_options(sv_timescale), force_signals, ) .map_err(|error| match error { @@ -685,6 +686,7 @@ pub fn parse_mixed( optimize_options: &crate::optimizer::OptimizeOptions, diagnostics: &crate::RuntimeDiagnostics, diagnostic_policy: &crate::DiagnosticPolicy, + sv_timescale: Option, preserve_element_storage_layout: bool, testbench_random_seed: Option, component_libraries: Vec, @@ -834,7 +836,7 @@ pub fn parse_mixed( sv_top_parameters, &requests, &mut warnings, - diagnostic_policy.sv_options(), + diagnostic_policy.sv_options(sv_timescale), ); let external = match external { Ok(external) => external, diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 89059ee1f19..0bd27b87f59 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -305,6 +305,7 @@ fn analyze( optimize_options: &crate::optimizer::OptimizeOptions, diagnostics: &crate::RuntimeDiagnostics, diagnostic_policy: &crate::DiagnosticPolicy, + sv_timescale: Option, injected_manifests: &[(String, veryl_metadata::ComponentManifest)], preserve_element_storage_layout: bool, recover_comb_loops: bool, @@ -317,7 +318,7 @@ fn analyze( Vec, ) { #[cfg(not(feature = "systemverilog"))] - let _ = diagnostic_policy; + let _ = (diagnostic_policy, sv_timescale); symbol_table::clear(); attribute_table::clear(); @@ -399,7 +400,7 @@ fn analyze( sv_sources, Some(&references), &mut sv_probe_warnings, - diagnostic_policy.sv_options(), + diagnostic_policy.sv_options(sv_timescale), ) .map_err(|error| match error { celox_frontend_sv::FrontendError::Analyzer(error) => parser::sv_analysis_error(error), @@ -605,6 +606,7 @@ fn analyze( optimize_options, diagnostics, diagnostic_policy, + sv_timescale, preserve_element_storage_layout, testbench_random_seed, component_libraries, @@ -771,6 +773,7 @@ pub fn compile_to_sir_with_file_dependencies( optimize_options, &crate::RuntimeDiagnostics::default(), &crate::DiagnosticPolicy::default(), + None, &[], crate::backend::memory_layout::MemoryLayoutMode::Packed, true, @@ -887,6 +890,7 @@ fn compile_frontend_testbench_to_sir_with_layout_mode( optimize_options: &crate::optimizer::OptimizeOptions, diagnostics: &crate::RuntimeDiagnostics, diagnostic_policy: &crate::DiagnosticPolicy, + sv_timescale: Option, injected_manifests: &[(String, veryl_metadata::ComponentManifest)], layout_mode: crate::backend::memory_layout::MemoryLayoutMode, recover_comb_loops: bool, @@ -920,6 +924,7 @@ fn compile_frontend_testbench_to_sir_with_layout_mode( optimize_options, diagnostics, diagnostic_policy, + sv_timescale, injected_manifests, layout_mode == crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, recover_comb_loops, @@ -980,6 +985,7 @@ fn compile_to_sir_with_layout_mode( optimize_options: &crate::optimizer::OptimizeOptions, diagnostics: &crate::RuntimeDiagnostics, diagnostic_policy: &crate::DiagnosticPolicy, + sv_timescale: Option, injected_manifests: &[(String, veryl_metadata::ComponentManifest)], layout_mode: crate::backend::memory_layout::MemoryLayoutMode, recover_comb_loops: bool, @@ -1003,6 +1009,7 @@ fn compile_to_sir_with_layout_mode( optimize_options, diagnostics, diagnostic_policy, + sv_timescale, injected_manifests, layout_mode == crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, recover_comb_loops, @@ -1079,6 +1086,7 @@ pub fn compile_sv_to_sir( optimize_options, &crate::RuntimeDiagnostics::default(), &crate::DiagnosticPolicy::default(), + None, crate::backend::memory_layout::MemoryLayoutMode::Packed, &[], &[], @@ -1109,6 +1117,7 @@ fn compile_sv_to_sir_with_layout_mode( optimize_options: &crate::optimizer::OptimizeOptions, diagnostics: &crate::RuntimeDiagnostics, diagnostic_policy: &crate::DiagnosticPolicy, + sv_timescale: Option, layout_mode: crate::backend::memory_layout::MemoryLayoutMode, force_signals: &[String], sv_param_literals: &[(String, String)], @@ -1152,6 +1161,7 @@ fn compile_sv_to_sir_with_layout_mode( optimize_options, diagnostics, diagnostic_policy, + sv_timescale, layout_mode == crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, metadata.test.seed, component_libraries, @@ -1259,6 +1269,7 @@ pub fn compile_mixed_to_sir_with_file_dependencies( optimize_options, &crate::RuntimeDiagnostics::default(), &crate::DiagnosticPolicy::default(), + None, &[], crate::backend::memory_layout::MemoryLayoutMode::Packed, true, @@ -1292,6 +1303,7 @@ fn compile_mixed_to_sir_with_layout_mode( optimize_options: &crate::optimizer::OptimizeOptions, diagnostics: &crate::RuntimeDiagnostics, diagnostic_policy: &crate::DiagnosticPolicy, + sv_timescale: Option, injected_manifests: &[(String, veryl_metadata::ComponentManifest)], layout_mode: crate::backend::memory_layout::MemoryLayoutMode, recover_comb_loops: bool, @@ -1315,6 +1327,7 @@ fn compile_mixed_to_sir_with_layout_mode( optimize_options, diagnostics, diagnostic_policy, + sv_timescale, injected_manifests, layout_mode == crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, recover_comb_loops, @@ -1378,6 +1391,7 @@ fn compile_hdl_to_sir_with_layout_mode( optimize_options: &crate::optimizer::OptimizeOptions, diagnostics: &crate::RuntimeDiagnostics, diagnostic_policy: &crate::DiagnosticPolicy, + sv_timescale: Option, injected_manifests: &[(String, veryl_metadata::ComponentManifest)], layout_mode: crate::backend::memory_layout::MemoryLayoutMode, recover_comb_loops: bool, @@ -1416,6 +1430,7 @@ fn compile_hdl_to_sir_with_layout_mode( optimize_options, diagnostics, diagnostic_policy, + sv_timescale, injected_manifests, layout_mode, recover_comb_loops, @@ -1440,6 +1455,7 @@ fn compile_hdl_to_sir_with_layout_mode( optimize_options, diagnostics, diagnostic_policy, + sv_timescale, injected_manifests, layout_mode, recover_comb_loops, @@ -1461,6 +1477,7 @@ fn compile_hdl_to_sir_with_layout_mode( optimize_options, diagnostics, diagnostic_policy, + sv_timescale, layout_mode, force_signals, sv_param_literals, @@ -1481,6 +1498,7 @@ fn compile_hdl_to_sir_with_layout_mode( optimize_options, diagnostics, diagnostic_policy, + sv_timescale, injected_manifests, layout_mode, recover_comb_loops, @@ -1534,6 +1552,8 @@ mod host { pub trace: crate::debug::TraceOptions, pub diagnostics: crate::RuntimeDiagnostics, pub diagnostic_policy: crate::DiagnosticPolicy, + /// Default SystemVerilog time unit and global scheduler precision. + pub sv_timescale: Option, /// When true, JIT-compiled functions emit trigger detection code for /// edge-based event discovery. Only needed by [`crate::Simulation`]. pub emit_triggers: bool, @@ -1793,6 +1813,7 @@ mod host { trace: Default::default(), diagnostics: Default::default(), diagnostic_policy: Default::default(), + sv_timescale: None, emit_triggers: false, native_force_support: false, signal_access: crate::SignalAccessOptions::default(), @@ -2220,6 +2241,13 @@ mod host { } /// Override recoverable compilation diagnostic severities. + /// Set default SV timing and contribute its precision to the scheduler. + /// Explicit source time declarations retain their units and rounding. + pub fn sv_timescale(mut self, timescale: Option) -> Self { + self.options.sv_timescale = timescale; + self + } + pub fn diagnostic_policy(mut self, policy: crate::DiagnosticPolicy) -> Self { self.options.diagnostic_policy = policy; self @@ -2589,6 +2617,7 @@ mod host { &self.options.optimize_options, &self.options.diagnostics, &self.options.diagnostic_policy, + self.options.sv_timescale, &injected_manifests, layout_mode, !self.options.native_force_support, @@ -2613,6 +2642,7 @@ mod host { &self.options.optimize_options, &self.options.diagnostics, &self.options.diagnostic_policy, + self.options.sv_timescale, &injected_manifests, layout_mode, !self.options.native_force_support, @@ -3249,6 +3279,7 @@ mod host { &self.options.optimize_options, &self.options.diagnostics, &self.options.diagnostic_policy, + self.options.sv_timescale, &injected_manifests, layout_mode, !self.options.native_force_support, @@ -3273,6 +3304,7 @@ mod host { &self.options.optimize_options, &self.options.diagnostics, &self.options.diagnostic_policy, + self.options.sv_timescale, &injected_manifests, layout_mode, !self.options.native_force_support, diff --git a/crates/celox/src/timescale.rs b/crates/celox/src/timescale.rs new file mode 100644 index 00000000000..fdd1f47e68e --- /dev/null +++ b/crates/celox/src/timescale.rs @@ -0,0 +1,77 @@ +//! Simulation default time unit and scheduler precision. + +/// Default SV time unit/precision. Explicit source declarations take precedence; +/// the precision also contributes to the global scheduler resolution. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SvTimescale { + pub(crate) unit: i32, + pub(crate) precision: i32, +} + +impl std::str::FromStr for SvTimescale { + type Err = String; + + fn from_str(value: &str) -> Result { + fn exponent(value: &str) -> Option { + let value = value.trim(); + let split = value.find(|c: char| !c.is_ascii_digit())?; + let magnitude = match &value[..split] { + "1" => 0, + "10" => 1, + "100" => 2, + _ => return None, + }; + let unit = match &value[split..] { + "s" => 0, + "ms" => -3, + "us" => -6, + "ns" => -9, + "ps" => -12, + "fs" => -15, + _ => return None, + }; + Some(unit + magnitude) + } + let invalid = || { + format!( + "invalid timescale `{value}`: expected UNIT/PRECISION (1, 10, or 100 s/ms/us/ns/ps/fs), with precision no coarser than unit" + ) + }; + let (unit, precision) = value.split_once('/').ok_or_else(invalid)?; + let unit = exponent(unit).ok_or_else(invalid)?; + let precision = exponent(precision).ok_or_else(invalid)?; + if precision > unit { + return Err(invalid()); + } + Ok(Self { unit, precision }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn validates_time_magnitudes_units_and_precision_order() { + for (text, unit, precision) in [ + ("1ns/1fs", -9, -15), + ("100s / 10fs", 2, -14), + ("10ps/1ps", -11, -12), + ] { + assert_eq!( + text.parse::().unwrap(), + SvTimescale { unit, precision } + ); + } + for text in [ + "1ns", + "1ns/1ps/1fs", + "2ns/1fs", + "1ps/1ns", + "1ns/0fs", + "1ns/1as", + "1.0ns/1fs", + ] { + assert!(text.parse::().is_err(), "{text}"); + } + } +} diff --git a/crates/celox/tests/sv_timescale_options.rs b/crates/celox/tests/sv_timescale_options.rs new file mode 100644 index 00000000000..41c62323b46 --- /dev/null +++ b/crates/celox/tests/sv_timescale_options.rs @@ -0,0 +1,80 @@ +#![cfg(feature = "systemverilog")] +//! Celox's default timing configuration must preserve authored scope rounding. +use std::path::Path; + +macro_rules! timing { + ($name:ident, $backend:ident) => { + #[test] + fn $name() { + let source = r#" +module Child(output bit value); + timeunit 1ns / 1ps; + initial begin value = 0; #1.5ps value = 1; end +endmodule +module Top(output bit default_value, explicit_value, queries); + Child child(explicit_value); + assign queries = ($timeunit() == -9) && ($timeprecision() == -15) + && ($timeprecision(child) == -12) && ($timeprecision($root) == -15); + initial begin default_value = 0; #1.5ps default_value = 1; end +endmodule +"#; + let mut policy = celox::DiagnosticPolicy::default(); + policy.set_override("mixed_timescale=allow").unwrap(); + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("configured_timing.sv"))], + "Top", + ) + .sv_timescale(Some("1ns/1fs".parse().unwrap())) + .diagnostic_policy(policy) + .$backend() + .unwrap(); + sim.run_until(1499).unwrap(); + assert_eq!(sim.get(sim.signal("queries")), 1u8.into()); + assert_eq!(sim.get(sim.signal("default_value")), 0u8.into()); + sim.run_until(1500).unwrap(); + assert_eq!(sim.get(sim.signal("default_value")), 1u8.into()); + sim.run_until(1999).unwrap(); + assert_eq!(sim.get(sim.signal("explicit_value")), 0u8.into()); + sim.run_until(2000).unwrap(); + assert_eq!(sim.get(sim.signal("explicit_value")), 1u8.into()); + } + }; +} +timing!(interpreter, build_interpreter); +timing!(cranelift, build); +timing!(wasm, build_wasm); +#[cfg(target_arch = "x86_64")] +timing!(native, build_native); + +#[test] +fn configuring_defaults_does_not_relax_mixed_timescale_diagnostics() { + let source = "module Child; timeunit 1ns/1ps; endmodule module Top; Child child(); endmodule"; + let error = celox::Simulator::from_sv_sources(vec![(source, Path::new("mixed.sv"))], "Top") + .sv_timescale(Some("1ns/1fs".parse().unwrap())) + .build_interpreter() + .err() + .unwrap(); + assert!( + error + .to_string() + .contains("mixed explicit and default time"), + "{error}" + ); +} + +#[test] +fn mixed_language_interface_probes_receive_configured_timing() { + let veryl = "module Top(a: input logic<8>, y: output logic<8>) { inst bus: $sv::Bus; assign bus.req = a; assign y = bus.rsp; }"; + let bus = "interface Bus; logic [7:0] req, rsp; assign rsp = req + ($timeprecision($root) == -15); endinterface"; + let mut sim = celox::Simulator::from_mixed_sources( + vec![(veryl, Path::new("top.veryl"))], + vec![(bus, Path::new("bus.sv"))], + "Top", + ) + .sv_timescale(Some("1ns/1fs".parse().unwrap())) + .build_interpreter() + .unwrap(); + let a = sim.signal("a"); + sim.modify(|io| io.set(a, 41u8)).unwrap(); + assert_eq!(sim.get(sim.signal("y")), 42u8.into()); +} diff --git a/docs/guide/celox-toml.md b/docs/guide/celox-toml.md index 97239f5edcc..7f26b211bcf 100644 --- a/docs/guide/celox-toml.md +++ b/docs/guide/celox-toml.md @@ -129,6 +129,21 @@ The Vite plugin picks up `test_veryl/` automatically and generates type definiti - The Vite plugin regenerates types for test sources on hot reload, just like for production sources. - `[simulation]` settings apply to every `Simulation.fromProject` / `Simulation.create` call within the project. A per-call `{ maxSteps }` option always takes precedence over the `celox.toml` value. + +### CLI SystemVerilog timing + +For `celox run` and `celox vpi build`, set `timescale = "1ns/1fs"` at the +manifest root or in `[targets.NAME]`. `--timescale 1ns/1fs` overrides the selected +target, which overrides the root setting. The default remains `1ns/1ps`. + +This sets the default time unit and precision for scopes without source timing +declarations. The configured precision also contributes to the global scheduler +resolution, so cocotb can schedule femtosecond clock periods even when an SV +module declares `1ns/1ps`. Explicit `timeunit`, `timeprecision`, and `` `timescale `` +settings retain their scope units and delay rounding. The global resolution is +the finest configured or declared precision. Values use magnitudes 1, 10, or 100 +and units `s`, `ms`, `us`, `ns`, `ps`, or `fs`; precision cannot be coarser than unit. + ### `[diagnostics]` Override individual compilation diagnostics by their displayed code: diff --git a/docs/ja/guide/celox-toml.md b/docs/ja/guide/celox-toml.md index e50629a9358..afbe5a31c7b 100644 --- a/docs/ja/guide/celox-toml.md +++ b/docs/ja/guide/celox-toml.md @@ -117,6 +117,21 @@ Vite プラグインは `test_veryl/` を自動的に検出し、そこで宣言 - Vite プラグインは本番ソースと同様に、ホットリロード時にテストソースの型も再生成します。 - `[simulation]` の設定は、プロジェクト内の `Simulation.fromProject` / `Simulation.create` 呼び出しすべてに適用されます。呼び出し時に `{ maxSteps }` を指定すると、常に `celox.toml` の値より優先されます。 + +### CLI の SystemVerilog 時間設定 + +`celox run` と `celox vpi build` では、ルートまたは `[targets.NAME]` に +`timescale = "1ns/1fs"` を指定できます。優先順位は `--timescale 1ns/1fs`、 +選択ターゲット、ルート設定の順です。未指定時は従来どおり `1ns/1ps` です。 + +時間宣言のないスコープの既定単位・精度を設定し、指定した精度を全体の +スケジューラ精度にも反映します。SV モジュールが `1ns/1ps` を宣言していても、 +cocotb から fs 単位のクロックを駆動できます。明示された `timeunit`、 +`timeprecision`、`` `timescale `` によるスコープ内の単位と遅延の丸めは維持します。 +全体の精度は、設定とソース宣言のうち最も細かい値になります。値は倍率 +1・10・100 と単位 `s`・`ms`・`us`・`ns`・`ps`・`fs` を使い、精度を単位より +粗くする指定はエラーです。 + ### `[diagnostics]` 診断に表示されるコードを使って、コンパイル時の診断レベルを個別に変更できます。 From 388c2141216f902aa6afb8ebe8a2e459a86ffdfb Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 21 Oct 2026 12:07:59 +0900 Subject: [PATCH 2/3] fix(sv): fill unbased parameter overrides to their declared width Overriding a 58-bit parameter with '1 through -G or the Rust builder retained only 32 one bits, corrupting Taxi LFSR initialization. Apply the declaration width and signedness after selecting the override, including the final override pass, before binding dependent parameters. Extend API and CLI coverage above 32 bits and check signed fills, dependent parameters, and wide X/Z overrides. Validation: - SV analyzer: 770 passed, 3 existing ignores. - Literal-parameter API regression passes on all four backend variants; project CLI suite: 17 passed. - Taxi cc70b270b910d369ab1ad7b3855e76399fd461f1: original 58-bit scramble and descramble configurations pass at O1 with the original '1 argument and cocotb 2.0.1. - Formatting and all-target Clippy for the affected crates pass. Change-Id: If5f1b4a1bc351fcdacd025ea7d9d0829360d4b2c --- .../celox-sv-analyzer/src/ast/parameters.rs | 8 +++-- .../src/ast/parameters/tests.rs | 31 +++++++++++++++++++ crates/celox-vpi/tests/project_cli.rs | 4 +-- .../frontends/systemverilog/hierarchy.rs | 13 +++++--- 4 files changed, 48 insertions(+), 8 deletions(-) diff --git a/crates/celox-sv-analyzer/src/ast/parameters.rs b/crates/celox-sv-analyzer/src/ast/parameters.rs index 8bd0afb46cf..77f6b969d1d 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters.rs @@ -119,7 +119,11 @@ pub(super) fn apply_parameter_overrides( } for parameter in parameters { if let Some(value) = overrides.get(parameter.name()) { - parameter.value = Some(value.clone()); + parameter.value = normalize_unbased_unsized_parameter_value( + Some(value.clone()), + parameter.declared_width(), + parameter.declared_signed(), + ); } } Ok(()) @@ -431,7 +435,6 @@ pub(super) fn parameters_from_native_with_environment( } else { None }; - value = normalize_unbased_unsized_parameter_value(value, parameter_width, parameter_signed); // Apply overrides as each declaration is collected so later // parameter initializers (including casts) are evaluated from the // specialized values rather than defaults that will be replaced @@ -439,6 +442,7 @@ pub(super) fn parameters_from_native_with_environment( if !is_local && let Some(override_value) = parameter_overrides.get(&name) { value = Some(override_value.clone()); } + value = normalize_unbased_unsized_parameter_value(value, parameter_width, parameter_signed); if value .as_ref() .is_some_and(|expression| is_unbounded(expression, const_env)) diff --git a/crates/celox-sv-analyzer/src/ast/parameters/tests.rs b/crates/celox-sv-analyzer/src/ast/parameters/tests.rs index a1ea6d0ef37..3ea1ba6bf94 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters/tests.rs @@ -1385,3 +1385,34 @@ fn logical_type_inference_requires_operand_types_outside_bounded_proofs() { }), ); } + +#[test] +fn unbased_parameter_overrides_fill_declared_width_before_dependent_parameters() { + let tree = crate::source_tree::parse_scope_fixture( + "module Top #(parameter logic [57:0] FILL=0, \ + parameter logic signed [57:0] SIGNED_FILL=0, \ + parameter logic [57:0] COPY=FILL, parameter NEGATIVE=SIGNED_FILL < 0); endmodule", + Path::new("unbased_parameter_overrides.sv"), + ) + .unwrap(); + let tree = AnalysisContext::unspecialized(&tree); + for (literal, unsigned, signed) in [("'1", (1i128 << 58) - 1, -1), ("'0", 0, 0)] { + let overrides = ["FILL", "SIGNED_FILL"] + .into_iter() + .map(|name| (name.into(), ConstExpr::Literal(literal.into()))) + .collect(); + let mut parameters = + parameters_from_scope(&tree, &HashMap::default(), &HashMap::default(), &overrides) + .unwrap(); + for reapplied in [false, true] { + if reapplied { + apply_parameter_overrides(&mut parameters, &overrides).unwrap(); + } + let values = const_env_from_parameters(&tree.state, ¶meters); + assert_eq!(values["FILL"], unsigned, "{literal}, reapplied={reapplied}"); + assert_eq!(values["SIGNED_FILL"], signed); + assert_eq!(values["COPY"], unsigned); + assert_eq!(values["NEGATIVE"], i128::from(signed < 0)); + } + } +} diff --git a/crates/celox-vpi/tests/project_cli.rs b/crates/celox-vpi/tests/project_cli.rs index d1b03347042..43426385fbc 100644 --- a/crates/celox-vpi/tests/project_cli.rs +++ b/crates/celox-vpi/tests/project_cli.rs @@ -596,11 +596,11 @@ fn sv_parameter_literals_preserve_types_across_project_target_and_cli() { let root = tempfile::tempdir().unwrap(); let source = r#" module Top #(parameter VENDOR="GENERIC", parameter NEG=3, - parameter logic [64:0] WIDE=0, parameter logic [11:0] FILL=0, + parameter logic [64:0] WIDE=0, parameter logic [57:0] FILL=0, parameter logic [3:0] UNKNOWN=0)(output logic matched); assign matched=(VENDOR == "XILINX") && (NEG == -8) && (NEG < 0) && ($bits(NEG) == 32) && ($bits(VENDOR) == 48) - && (WIDE == 65'h10000000000000001) && (FILL == 12'hfff) + && (WIDE == 65'h10000000000000001) && (FILL == 58'h3ffffffffffffff) && (UNKNOWN === 4'b10xz); initial begin #1; assert(matched) else $fatal(1,"literal parameter types"); $display("ok"); $finish; end diff --git a/crates/celox/tests/frontends/systemverilog/hierarchy.rs b/crates/celox/tests/frontends/systemverilog/hierarchy.rs index f1baf76a403..c1dc0f96413 100644 --- a/crates/celox/tests/frontends/systemverilog/hierarchy.rs +++ b/crates/celox/tests/frontends/systemverilog/hierarchy.rs @@ -368,12 +368,16 @@ sv_backends! { @setup { let source = r#" module Top #(parameter TEXT="default", parameter NEG=0, - parameter logic [11:0] FILL=0, parameter logic [3:0] UNKNOWN=0, - parameter logic [64:0] WIDE=0, parameter FINAL=0)(output logic matched); + parameter logic [57:0] FILL=0, parameter logic [3:0] UNKNOWN=0, + parameter logic [64:0] WIDE=0, parameter FINAL=0, + parameter logic [57:0] X=0, parameter logic [57:0] Z=0, + parameter logic [57:0] COPY=FILL)(output logic matched); assign matched=(TEXT=="XILINX") && ($bits(TEXT)==48) && (NEG==-8) && (NEG<0) && ($bits(NEG)==32) - && (FILL==12'hfff) && (UNKNOWN===4'b10xz) - && (WIDE==65'h10000000000000001) && (FINAL==7); + && (FILL==58'h3ffffffffffffff) && (UNKNOWN===4'b10xz) + && (WIDE==65'h10000000000000001) && (FINAL==7) + && (COPY==58'h3ffffffffffffff) + && (X===58'bx) && (Z===58'bz); endmodule "#; } @@ -383,6 +387,7 @@ sv_backends! { .param_literal("FILL", "'1").param_literal("UNKNOWN", "4'b10xz") .param_literal("WIDE", "65'h10000000000000001") .param_literal("FINAL", "-1").param("FINAL", 7) + .param_literal("X", "'x").param_literal("Z", "'z") .four_state(true).opt_level(celox::OptLevel::O2); assert_eq!(sim.get(sim.signal("matched")), BigUint::from(1u8)); } From 40433f0d9b563f23e13d2b7edbb00eb5c4c2078d Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 21 Oct 2026 12:08:13 +0900 Subject: [PATCH 3/3] fix(sv): defer indexed part-select base binding until types are available Runtime casts in an indexed part-select base were bound during preliminary validation as constant expressions, rejecting valid Taxi DMA selects with a constant-cast-operand error. Validate the positive constant width there and let normal expression lowering bind the variable base with complete type information, as required by IEEE 1800-2023 11.5.1. Add a shared regression for numeric and typedef casts in runtime read and write bases, including truncating indices. Validation: - Shared SV suite: 3287 passed, 90 existing ignores across the backend variants; indexed-select group: 298 passed. - New shared case passes Verilator and Icarus execution. - SV analyzer: 770 passed, 3 existing ignores; project CLI: 17 passed. - Original Taxi AXI CDMA [8-0] and AXI DMA [0-8] builds pass the former cast error and stop at separate combinational expression lowering failures for read_addr_next and addr_next. Neither is counted as an upstream runtime pass. - Formatting and affected-crate all-target Clippy pass. Change-Id: I57adbbd3abcd3c0e4761b3deb63d5232558a7f27 --- .../celox-sv-analyzer/src/ast/validation.rs | 9 +++---- .../src/sv/cases/indexed_select.vtest | 27 +++++++++++++++++++ .../frontends/systemverilog/indexed_select.rs | 4 +++ 3 files changed, 35 insertions(+), 5 deletions(-) diff --git a/crates/celox-sv-analyzer/src/ast/validation.rs b/crates/celox-sv-analyzer/src/ast/validation.rs index c68a5d34ca4..efbe9323bcc 100644 --- a/crates/celox-sv-analyzer/src/ast/validation.rs +++ b/crates/celox-sv-analyzer/src/ast/validation.rs @@ -466,12 +466,11 @@ fn validate_scope( return Err(unsupported("mintypmax expression")); } ExprKind::Select { dimension, .. } => { - if let DimensionKind::Indexed { base, width, .. } = dimension.kind { + if let DimensionKind::Indexed { width, .. } = dimension.kind { if parameter_ranges.iter().any(|range| contains(*range, dimension.tokens)) { continue; } - let mut dimensions = indexed_dimensions.clone(); - dimensions.constant_indexed_base = true; - let value = expression_binding::value(base, native, syntax_tree, &dimensions)?; - selects::indexed_expression_value(&syntax_tree.state, value, &dimensions).ok_or_else(|| unsupported("index expression"))?; + // IEEE 1800-2023 11.5.1 permits a variable base. Its + // expression is bound after variable types are available; + // only the width requires constant validation here. check_indexed_width(width, syntax_tree, indexed_dimensions)?; } } diff --git a/crates/celox-test-suite/src/sv/cases/indexed_select.vtest b/crates/celox-test-suite/src/sv/cases/indexed_select.vtest index 34f641f537e..da1e5612b22 100644 --- a/crates/celox-test-suite/src/sv/cases/indexed_select.vtest +++ b/crates/celox-test-suite/src/sv/cases/indexed_select.vtest @@ -1736,3 +1736,30 @@ (top Top) (assert_eq enumeration 10) (assert_eq width 10)) + +(case runtime_indexed_bases_preserve_numeric_and_type_casts + (source "runtime_indexed_cast.sv" #" + module Top(input logic [63:0] data, input logic [1:0] offset, + input logic [3:0] index, + output logic [31:0] y, output logic [3:0] narrowed, + output logic [3:0] typed, output logic [63:0] written); + typedef logic [2:0] index_t; + assign y = data[3'(4-offset)*8 +: 32]; + assign narrowed = data[2'(index) +: 4]; + assign typed = data[index_t'(index) +: 4]; + always_comb begin + written = data; + written[3'(4-offset)*8 +: 8] = 8'hff; + end + endmodule + "#) + (top Top) + (modify (set data 0x0123456789abcdef)) + (for offset_value (range 0 4) + (modify (set offset offset_value)) + (assert_eq y (& (>> 0x0123456789abcdef (* (- 4 offset_value) 8)) 0xffffffff)) + (assert_eq written (| 0x0123456789abcdef (<< 0xff (* (- 4 offset_value) 8))))) + (for index_value (range 0 16) + (modify (set index index_value)) + (assert_eq narrowed (& (>> 0x0123456789abcdef (& index_value 3)) 15)) + (assert_eq typed (& (>> 0x0123456789abcdef (& index_value 7)) 15)))) diff --git a/crates/celox/tests/frontends/systemverilog/indexed_select.rs b/crates/celox/tests/frontends/systemverilog/indexed_select.rs index 9acf8d49142..94701d08590 100644 --- a/crates/celox/tests/frontends/systemverilog/indexed_select.rs +++ b/crates/celox/tests/frontends/systemverilog/indexed_select.rs @@ -128,6 +128,10 @@ sv_backends! { assert_eq!(sim.get(sim.signal("narrow")), 0x1bu8.into()); } + fn runtime_indexed_bases_preserve_numeric_and_type_casts(sim) { + @case "indexed_select::runtime_indexed_bases_preserve_numeric_and_type_casts"; + } + fn indexed_select_preserves_selected_and_cast_bases(sim) { @case "indexed_select::indexed_select_preserves_selected_and_cast_bases"; }