From f27f368637324c566606642da8e970b8b47e613d Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 21 Oct 2026 10:17:55 +0900 Subject: [PATCH] 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]` 診断に表示されるコードを使って、コンパイル時の診断レベルを個別に変更できます。