From df1e561960c5272b5f242b8d13ad37e0fc36e893 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 10 Oct 2026 04:39:24 +0900 Subject: [PATCH 01/75] test(suite): drive timed designs from shared cases Shared cases could only drive a design through host writes and ticks, so the SystemVerilog timing controls had no portable cases that run on the external simulators too. - Add `(run_until TIME)` and `(run_to_finish)` to the script language and `run_until` / `run_to_finish` to the `Backend` contract. A case using them is timed (`Design::timed`): the design's own processes, delays and clocks run, and only checks may follow `run_to_finish`. - Generate timed testbenches for Verilator and Icarus: every compiled source gets a `1ns/1ps` time scale, the testbench counts picoseconds so its settles stay inside one time unit, `run_until` delays to the exact time, and the checks after `run_to_finish` run in a `final` block while a `forever` delay keeps the simulation alive until the design finishes. A simulator's own `$finish` notice is not design output. - Let a `Simulation` be built on each backend (`SimulatorBuilder::build_{native,cranelift,wasm,interpreter}`) and read or write four-state values, so Celox runs timed cases on every backend through a `Simulation`-backed adapter. - Add the `timing` SystemVerilog group: 13 cases for `#delay`, `@(event)`, `wait`, `always` processes, tasks with timing and four-state edges, and refresh the retained verification reports. The Veryl suite's results are unchanged under the new time scale. --- crates/celox-test-suite/README.md | 15 + crates/celox-test-suite/src/backend.rs | 25 ++ crates/celox-test-suite/src/frontend.rs | 9 +- crates/celox-test-suite/src/lib.rs | 1 + crates/celox-test-suite/src/script/ast.rs | 97 +++++ crates/celox-test-suite/src/script/interp.rs | 14 + crates/celox-test-suite/src/script/mod.rs | 7 + crates/celox-test-suite/src/script/sv.rs | 156 +++++++- crates/celox-test-suite/src/sv/cases/mod.rs | 4 + .../src/sv/cases/timing.vtest | 341 ++++++++++++++++++ crates/celox-test-suite/src/verification.rs | 10 + .../celox-test-suite/verification/icarus.json | 1 + .../verification/sv/icarus.json | 143 ++++++++ .../verification/sv/verilator.json | 143 ++++++++ .../verification/verilator.json | 1 + crates/celox/src/simulation.rs | 24 ++ crates/celox/src/simulator/builder.rs | 68 ++++ .../tests/frontends/systemverilog/suite.rs | 130 ++++++- .../tests/frontends/systemverilog/timing.rs | 56 +++ crates/celox/tests/systemverilog.rs | 2 + 20 files changed, 1220 insertions(+), 27 deletions(-) create mode 100644 crates/celox-test-suite/src/sv/cases/timing.vtest create mode 100644 crates/celox/tests/frontends/systemverilog/timing.rs diff --git a/crates/celox-test-suite/README.md b/crates/celox-test-suite/README.md index c774912a5a0..9139385e4b8 100644 --- a/crates/celox-test-suite/README.md +++ b/crates/celox-test-suite/README.md @@ -90,6 +90,13 @@ behavioral model and verifies that incorrect results are rejected. changes. `read` observes settled values, including after a direct write. `tick` executes the named event once and settles its consequences. Event names can refer to clocks or asynchronous resets; use the declaration's polarity. +- A design with `Design::timed` is driven by `run_until` and `run_to_finish` + instead of `tick`: the simulator runs the design's own processes, delays + and clocks. `run_until` advances to the given time in the design's time + units and fails when the design has finished by then; `run_to_finish` runs + until a process calls `$finish` and fails when the events run out first. A + `write` in a timed case takes effect at the current time. The optional + methods' defaults return an unsupported-operation error. - Start each design with fresh storage: zero for two-state signals and X for four-state signals. Initial combinational outputs must be readable before an input is written. Generic clock/reset types use Veryl's defaults (positive @@ -237,6 +244,14 @@ static). Script values are integers of unbounded width, so an expectation never depends on the simulator's width or X rules; arithmetic on unknown bits is an error. +A case whose design has processes with delays or event controls, or a clock +it generates itself, advances time with `run_until` and `run_to_finish` and +checks the design's output with `expect_output`. Design delays count time +units; the generated testbench for an external simulator sets a time scale of +1 ns with 1 ps precision and settles in 1 ps steps, so its checks after +`run_until` observe everything the design did at that time. Only checks may +follow `run_to_finish`; they run in a `final` block. + For an invalid design, write `(expect reject)` and no statements. `TestCase::expectation` lets consumers select these separately. For additional SV expectations, add `(tags evaluation_order)` (or other `TestTag` names). diff --git a/crates/celox-test-suite/src/backend.rs b/crates/celox-test-suite/src/backend.rs index 6b4a030319c..0a6595fbd1d 100644 --- a/crates/celox-test-suite/src/backend.rs +++ b/crates/celox-test-suite/src/backend.rs @@ -18,6 +18,10 @@ pub struct Design { pub four_state: bool, /// Values of the top module's parameters, overriding their defaults. pub parameters: Vec<(String, u64)>, + /// Whether the case advances simulation time (`run_until`, + /// `run_to_finish`), so the design's own processes, delays and clocks + /// must run. An adapter builds a timed simulation for such a design. + pub timed: bool, } impl Design { @@ -30,6 +34,7 @@ impl Design { top: top.into(), four_state: false, parameters: Vec::new(), + timed: false, } } @@ -89,6 +94,18 @@ pub trait Backend { fn take_output(&mut self) -> Result { Err("this adapter does not capture design output".into()) } + /// Advance simulation time to `time` (inclusive), running the design's + /// processes, delays and clocks. Fails when `time` is in the past or + /// when a process ended the simulation at or before `time`. Only a + /// timed design (`Design::timed`) receives this call. + fn run_until(&mut self, _time: u64) -> Result<()> { + Err("this adapter does not run timed simulations".into()) + } + /// Run until a process ends the simulation with `$finish`. Fails when + /// the simulation runs out of events first. + fn run_to_finish(&mut self) -> Result<()> { + Err("this adapter does not run timed simulations".into()) + } } /// Compiler callback used by every test. Capturing closures allow the caller to @@ -200,6 +217,14 @@ impl Simulator { self.backend.take_output() } + pub fn run_until(&mut self, time: u64) -> Result<()> { + self.backend.run_until(time) + } + + pub fn run_to_finish(&mut self) -> Result<()> { + self.backend.run_to_finish() + } + pub fn tick(&mut self, event: Event) -> Result<()> { self.backend.tick(&self.events.borrow()[event.0]) } diff --git a/crates/celox-test-suite/src/frontend.rs b/crates/celox-test-suite/src/frontend.rs index fb4719efe1b..a3ae73063eb 100644 --- a/crates/celox-test-suite/src/frontend.rs +++ b/crates/celox-test-suite/src/frontend.rs @@ -12,6 +12,11 @@ use std::path::{Path, PathBuf}; /// The module that instantiates the top with a rejection case's parameters. const PARAMETERS_TOP: &str = "celox_suite_parameters"; +/// The time scale every compiled source gets: a script time unit is 1 ns, +/// and the generated testbench settles in 1 ps steps between them. The +/// directive persists across the files that follow it in one compilation. +const TIMESCALE: &str = "`timescale 1ns/1ps\n"; + /// A design translated to SystemVerilog for an external simulator. pub struct PreparedDesign { /// SystemVerilog sources to compile, in order. @@ -63,7 +68,9 @@ pub(crate) fn stage( let prepared = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| frontend.prepare(design))) .map_err(|error| EmissionError(panic_message(error.as_ref())))??; - let mut paths = Vec::new(); + let timescale = directory.join("timescale.sv"); + write_if_changed(×cale, TIMESCALE.as_bytes())?; + let mut paths = vec![timescale]; for (index, source) in prepared.sources.iter().enumerate() { let path = directory.join(format!("source_{index}.sv")); write_if_changed(&path, source.as_bytes())?; diff --git a/crates/celox-test-suite/src/lib.rs b/crates/celox-test-suite/src/lib.rs index 34323149915..5a7bbbb9674 100644 --- a/crates/celox-test-suite/src/lib.rs +++ b/crates/celox-test-suite/src/lib.rs @@ -202,6 +202,7 @@ impl script::ScriptCase { top: self.top.clone(), four_state: self.four_state, parameters: self.parameters.clone(), + timed: self.is_timed(), } } } diff --git a/crates/celox-test-suite/src/script/ast.rs b/crates/celox-test-suite/src/script/ast.rs index 5ee2a89951f..2a003b32ce3 100644 --- a/crates/celox-test-suite/src/script/ast.rs +++ b/crates/celox-test-suite/src/script/ast.rs @@ -208,6 +208,40 @@ pub enum StmtKind { /// `(expect_output TEXT)`: the design printed exactly TEXT with /// `$display`/`$write` since the start or the previous `expect_output`. ExpectOutput(String), + /// `(run_until TIME)`: advance simulation time to TIME, running the + /// design's processes, delays and clocks. + RunUntil(Expr), + /// `(run_to_finish)`: run until a process of the design ends the + /// simulation with `$finish`. Only checks may follow it. + RunToFinish, +} + +impl Stmt { + /// Visit this statement and the statements nested in it. + pub fn walk<'a>(&'a self, visit: &mut impl FnMut(&'a Stmt)) { + visit(self); + match &self.kind { + StmtKind::Modify(body) | StmtKind::Block(body) | StmtKind::For(_, _, body) => { + body.iter().for_each(|stmt| stmt.walk(visit)); + } + StmtKind::If(_, then, otherwise) => { + then.walk(visit); + if let Some(otherwise) = otherwise { + otherwise.walk(visit); + } + } + _ => {} + } + } + + /// Whether this is a check that reads but never drives the design: + /// what may follow `(run_to_finish)`. + pub fn is_check(&self) -> bool { + matches!( + self.kind, + StmtKind::AssertEq(..) | StmtKind::Assert(..) | StmtKind::ExpectOutput(_) + ) + } } /// Part of a source file: text, or a file of the Veryl standard library @@ -236,6 +270,60 @@ pub struct ScriptCase { pub pos: Pos, } +impl ScriptCase { + /// Whether the case advances simulation time, so the design's own + /// processes, delays and clocks run. + pub fn is_timed(&self) -> bool { + let mut timed = false; + for stmt in &self.body { + stmt.walk(&mut |stmt| { + timed |= matches!(stmt.kind, StmtKind::RunUntil(_) | StmtKind::RunToFinish); + }); + } + timed + } + + /// The statements before and after a top-level `(run_to_finish)`. + pub fn split_at_finish(&self) -> (&[Stmt], Option<&[Stmt]>) { + match self + .body + .iter() + .position(|stmt| stmt.kind == StmtKind::RunToFinish) + { + Some(at) => (&self.body[..at], Some(&self.body[at + 1..])), + None => (&self.body, None), + } + } +} + +/// `(run_to_finish)` is a top-level statement, at most once, and only +/// checks follow it: after the design has finished, nothing can drive it. +fn validate_finish(body: &[Stmt]) -> Result<(), ScriptError> { + let mut finished = false; + for stmt in body { + if finished && !stmt.is_check() { + return error( + stmt.pos, + "only assert_eq, assert and expect_output may follow run_to_finish", + ); + } + if stmt.kind == StmtKind::RunToFinish { + finished = true; + continue; + } + let mut nested = None; + stmt.walk(&mut |inner| { + if inner.kind == StmtKind::RunToFinish && nested.is_none() { + nested = Some(inner.pos); + } + }); + if let Some(pos) = nested { + return error(pos, "run_to_finish must be a top-level statement"); + } + } + Ok(()) +} + #[derive(Debug)] pub struct ScriptError { pub pos: Pos, @@ -583,6 +671,14 @@ pub fn stmt(form: &Sexpr) -> Result { arity(items, pos, 1, Some(1))?; StmtKind::ExpectOutput(string(&items[1], "output")?) } + "run_until" => { + arity(items, pos, 1, Some(1))?; + StmtKind::RunUntil(expr(&items[1])?) + } + "run_to_finish" => { + arity(items, pos, 0, Some(0))?; + StmtKind::RunToFinish + } _ => return error(pos, format!("unknown statement `{head}`")), }; Ok(Stmt { kind, pos }) @@ -767,6 +863,7 @@ pub fn group(text: &str) -> Result<(String, Vec), ScriptError> { if case.expectation == Expectation::CompilationError && !case.body.is_empty() { return error(pos, "a rejected case has no statements"); } + validate_finish(&case.body)?; parsed.push(case); } Ok((group_name, parsed)) diff --git a/crates/celox-test-suite/src/script/interp.rs b/crates/celox-test-suite/src/script/interp.rs index 06367874114..f0234c4c762 100644 --- a/crates/celox-test-suite/src/script/interp.rs +++ b/crates/celox-test-suite/src/script/interp.rs @@ -499,6 +499,20 @@ impl Interpreter<'_> { panic!("run_testbench: {error}"); } } + StmtKind::RunUntil(time) => { + let time = self.known(time, pos, "time")?; + let Some(time) = time.to_u64() else { + return fail(pos, format!("time {time} is out of range")); + }; + if let Err(error) = self.sim.run_until(time) { + panic!("run_until {time}: {error}"); + } + } + StmtKind::RunToFinish => { + if let Err(error) = self.sim.run_to_finish() { + panic!("run_to_finish: {error}"); + } + } StmtKind::ExpectOutput(expected) => { let output = self .sim diff --git a/crates/celox-test-suite/src/script/mod.rs b/crates/celox-test-suite/src/script/mod.rs index 1fe86cfbbd9..f6a2143cc49 100644 --- a/crates/celox-test-suite/src/script/mod.rs +++ b/crates/celox-test-suite/src/script/mod.rs @@ -24,6 +24,13 @@ //! | `(expand NAME (ITEM...) STMT...)` | Repeat the statements with `{NAME}` replaced by each item's text (in names and messages); `(expand (A B) ((a1 b1) ...) ...)` binds several. | //! | `(run_testbench)` | Run the design's native testbench to `$finish`. | //! | `(expect_output TEXT)` | The design printed exactly TEXT with `$display`/`$write` since the start or the previous `expect_output`. | +//! | `(run_until TIME)` | Advance simulation time to TIME, running the design's processes, delays and clocks. TIME counts the design's time units and must not be in the past; a design that finishes first fails the case. | +//! | `(run_to_finish)` | Run until a process of the design calls `$finish`; a simulation that runs out of events first fails the case. Only `assert_eq`, `assert` and `expect_output` may follow, and read the final state. | +//! +//! A case with `run_until` or `run_to_finish` is timed: the design's own +//! `initial` and `always` processes run, and a write takes effect at the +//! current time, so a process waiting for the signal resumes when time next +//! advances. `tick` is not available in a timed case. //! //! A signal is `name` at the top or `inst.name`, `inst[2].name` below it. //! diff --git a/crates/celox-test-suite/src/script/sv.rs b/crates/celox-test-suite/src/script/sv.rs index bca4aad141c..721bb39bbcd 100644 --- a/crates/celox-test-suite/src/script/sv.rs +++ b/crates/celox-test-suite/src/script/sv.rs @@ -11,7 +11,13 @@ //! The timing follows the process adapters: a write takes effect at the next //! settle, which advances time by one step; a tick drives the event port to //! its inactive and then its active level, settling after each, and restores -//! a level that was neither. +//! a level that was neither. The testbench counts time in picoseconds while +//! the design's time unit is a nanosecond (see the staged time scale), so +//! the steps stay inside one script time unit: `run_until` reaches the +//! script's time exactly, and the settle before the next read runs after +//! everything the design does at that time. After `run_to_finish` the +//! testbench only keeps the simulation alive; the checks that follow run in +//! a `final` block, when the design has called `$finish`. use super::ast::{Actual, Expr, Op, ScriptCase, Sequence, Stmt, StmtKind, Value}; use super::sexpr::Pos; @@ -94,10 +100,50 @@ fn hex_encode(text: &str) -> String { text.bytes().map(|byte| format!("{byte:02x}")).collect() } +/// Whether a line is a simulator's own notice of a `$finish` call, which is +/// not output of the design: Verilator prints `- FILE:LINE: Verilog $finish` +/// and Icarus Verilog `FILE:LINE: $finish called at TIME (UNIT)`. +fn is_finish_notice(line: &str) -> bool { + // `FILE:LINE` + let located = |text: &str| { + text.rsplit_once(':') + .is_some_and(|(file, line)| !file.is_empty() && line.parse::().is_ok()) + }; + if let Some(location) = line + .strip_prefix("- ") + .and_then(|rest| rest.strip_suffix(": Verilog $finish")) + { + return located(location); + } + if let Some((location, rest)) = line.split_once(": $finish called at ") { + return located(location) && rest.ends_with(')'); + } + false +} + +/// `text` without the simulators' `$finish` notices. +fn design_output(text: &str) -> String { + let mut output = String::new(); + let mut rest = text; + while let Some(at) = rest.find('\n') { + let line = &rest[..at]; + if !is_finish_notice(line) { + output.push_str(line); + output.push('\n'); + } + rest = &rest[at + 1..]; + } + if !is_finish_notice(rest) { + output.push_str(rest); + } + output +} + /// Check a generated testbench's stdout. The script must have run to its /// end: a design's `$finish` can end some simulators' runs early without a /// failure. Before that, the text before each `expect_output` marker, since -/// the previous one, must equal the text the marker encodes. +/// the previous one, must equal the text the marker encodes. A simulator's +/// notice of a `$finish` call is not design output. pub fn check_output(log: &str) -> Result<(), String> { let Some(end) = log.find(&format!("\n{END_MARKER}\n")) else { return Err("the simulation ended before the script did".into()); @@ -120,6 +166,7 @@ pub fn check_output(log: &str) -> Result<(), String> { .collect::>>() .ok_or("malformed output marker")?; let expected = String::from_utf8_lossy(&bytes); + let output = design_output(output); if output != expected { return Err(format!( "{location}: expect_output: expected {expected:?}, got {output:?}" @@ -155,6 +202,9 @@ struct Generator<'a> { out: String, indent: usize, temps: usize, + /// Generating the checks after `run_to_finish`, which run in a `final` + /// block: time cannot advance there, and the state is final. + in_final: bool, } fn path_text(path: &SignalPath) -> String { @@ -235,7 +285,11 @@ fn walk_stmt(stmt: &Stmt, visit: &mut impl FnMut(&Expr)) { walk_stmt(otherwise, visit); } } - StmtKind::Eval | StmtKind::RunTestbench | StmtKind::ExpectOutput(_) => {} + StmtKind::RunUntil(e) => walk_expr(e, visit), + StmtKind::Eval + | StmtKind::RunTestbench + | StmtKind::RunToFinish + | StmtKind::ExpectOutput(_) => {} } } @@ -486,7 +540,7 @@ impl Generator<'_> { } fn settle_for(&mut self, exprs: &[&Expr]) { - if reads(exprs) { + if reads(exprs) && !self.in_final { self.line("settle();"); } } @@ -784,10 +838,50 @@ impl Generator<'_> { self.where_(pos) ))); } + StmtKind::RunUntil(time) => { + if self.in_final { + return Err(Unsupported(format!( + "{}: run_until after run_to_finish", + self.where_(pos) + ))); + } + self.settle_for(&[time]); + let time = self.expr(time); + self.require_known(&time, pos, "time"); + let temp = self.temp(); + self.line("begin"); + self.indent += 1; + self.line(format!("longint {temp};")); + self.line(format!("{temp} = longint'({time}) * 1000;")); + // The settle steps stay inside the current time unit. + self.line(format!("if ({temp} / 1000 < $time / 1000) begin")); + self.indent += 1; + self.fail( + pos, + "run_until %0d: the simulation is already at %0d", + &[format!("{temp} / 1000"), "$time / 1000".into()], + ); + self.indent -= 1; + self.line("end"); + self.line(format!("if ({temp} > $time) #({temp} - $time);")); + self.line("settled = 0;"); + self.indent -= 1; + self.line("end"); + } + StmtKind::RunToFinish => { + return Err(Unsupported(format!( + "{}: run_to_finish inside a block", + self.where_(pos) + ))); + } StmtKind::ExpectOutput(text) => { // HDL cannot read back its own output, so the harness checks // it: the marker closes the output so far, which must equal - // the hex-encoded text (see `check_output`). + // the hex-encoded text (see `check_output`). The marker + // follows everything the design printed at this time. + if !self.in_final { + self.line("settle();"); + } self.line(format!( "$write(\"\\n{OUTPUT_MARKER}{} {}\\n\");", hex_encode(text), @@ -816,15 +910,32 @@ pub fn testbench(case: &ScriptCase, design: &DesignInfo) -> Result { + generator.in_final = true; + generator.block(after)?; + Some(std::mem::take(&mut generator.out)) + } + None => None, }; - generator.block(&case.body)?; - let body = generator.out; let w = width - 1; let mut out = String::new(); let _ = writeln!(out, "// Generated from {} by celox-test-suite.", case.name); // Script values are deliberately wider than the signals they meet. let _ = writeln!(out, "/* verilator lint_off WIDTH */"); let _ = writeln!(out, "module {TESTBENCH_TOP};"); + let _ = writeln!(out, " timeunit 1ps;"); + let _ = writeln!(out, " timeprecision 1ps;"); for port in &design.inputs { let range = port .array @@ -901,8 +1012,22 @@ pub fn testbench(case: &ScriptCase, design: &DesignInfo) -> Result { + // The design ends the simulation; the checks run in its wake. + out.push_str(" end\n\n final begin\n"); + out.push_str(&checks); + out.push_str(&end); + out.push_str(" end\nendmodule\n"); + } + None => { + out.push_str(&end); + out.push_str(" $finish;\n end\nendmodule\n"); + } + } Ok(out) } @@ -910,6 +1035,19 @@ pub fn testbench(case: &ScriptCase, design: &DesignInfo) -> Result ScriptCase { let source = format!( "(group g (category operators)) (case t (source \"test.veryl\" \"\") (top Top) {text})" diff --git a/crates/celox-test-suite/src/sv/cases/mod.rs b/crates/celox-test-suite/src/sv/cases/mod.rs index 772cb0f92bc..8f88d2cba33 100644 --- a/crates/celox-test-suite/src/sv/cases/mod.rs +++ b/crates/celox-test-suite/src/sv/cases/mod.rs @@ -55,6 +55,10 @@ pub(super) const GROUPS: &[Group] = &[ file: "src/sv/cases/system_functions.vtest", text: include_str!("system_functions.vtest"), }, + Group { + file: "src/sv/cases/timing.vtest", + text: include_str!("timing.vtest"), + }, Group { file: "src/sv/cases/types.vtest", text: include_str!("types.vtest"), diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest new file mode 100644 index 00000000000..19e4a0c7536 --- /dev/null +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -0,0 +1,341 @@ +(group timing (category sequential)) + +; Procedural timing controls: `#delay`, `@(event)` and `wait (condition)` in +; `initial` blocks and `always` processes. The script advances time with +; `run_until` and `run_to_finish`; the design generates its own clocks. + +(case delays_resume_initial_blocks_at_later_times + (source "delays.sv" #" + module Top(output logic [7:0] a); + parameter int GAP = 4; + logic [7:0] pause = 8'd3; + initial begin + a = 8'd1; + #10 a = 8'd2; + #GAP a = 8'd3; + #(pause) a = 8'd4; + #0 a = 8'd5; + #pause; + $finish; + end + endmodule + "#) + (top Top) + (run_until 0) + (assert_eq a 1) + (run_until 10) + (assert_eq a 2) + (run_until 14) + (assert_eq a 3) + (run_until 17) + (assert_eq a 5 "the zero delay resumes at the same time") + (run_to_finish) + (assert_eq a 5)) + +(case always_with_a_delay_generates_a_clock + (source "clock.sv" #" + module Top(output logic [7:0] count, output logic clk); + initial clk = 1'b0; + initial count = 8'd0; + always #5 clk = ~clk; + always_ff @(posedge clk) count <= count + 8'd1; + endmodule + "#) + (top Top) + (run_until 4) + (assert_eq clk 0) + (assert_eq count 0) + ; Rising edges at 5, 15, ..., 95. + (run_until 100) + (assert_eq count 10) + (assert_eq clk 0)) + +(case edge_waits_resume_before_the_registers_of_that_edge_update + (source "edges.sv" #" + module Top(output logic [7:0] q); + logic clk = 1'b0; + logic [7:0] d = 8'd0; + initial q = 8'd0; + always #5 clk = ~clk; + always_ff @(posedge clk) q <= d; + initial begin + d = 8'd1; + @(posedge clk); + $display("first q=%0d", q); + #1 d = 8'd2; + @(posedge clk); + $display("second q=%0d", q); + @(negedge clk); + $display("negedge q=%0d", q); + repeat (2) @(posedge clk); + $display("repeat q=%0d", q); + $finish; + end + endmodule + "#) + (top Top) + ; A process woken by an edge runs in the active region, before the + ; nonblocking updates of that edge (IEEE 1800-2023 4.4). + (run_to_finish) + (expect_output "first q=0\nsecond q=1\nnegedge q=2\nrepeat q=2\n") + (assert_eq q 2)) + +(case any_change_waits_wake_on_every_value_change + (source "changes.sv" #" + module Top(output logic [7:0] data, output logic flag); + logic [7:0] other = 8'd0; + initial begin + data = 8'd0; + flag = 1'b0; + #3 data = 8'd7; + #4 data = 8'd7; + #1 data = 8'd9; + #2 other = 8'd1; + #2 flag = 1'b1; + #1 $finish; + end + initial forever begin + @(data); + $display("data=%0d", data); + end + initial forever begin + @(other or flag); + $display("other=%0d flag=%0d", other, flag); + end + initial forever begin + @(flag, data); + $display("either"); + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "data=7\neither\ndata=9\neither\nother=1 flag=0\nother=1 flag=1\neither\n")) + +(case wait_statements_block_until_their_condition_holds + (source "wait.sv" #" + module Top(output logic [7:0] y); + logic go = 1'b0; + logic [7:0] level = 8'd0; + initial begin + y = 8'd0; + #7 go = 1'b1; + #5 level = 8'd3; + #5 level = 8'd5; + end + initial begin + wait (go) $display("go"); + wait (go); + $display("still go"); + wait (level > 8'd4) y = level; + $display("level=%0d", level); + #1 $finish; + end + endmodule + "#) + (top Top) + (run_until 6) + (expect_output "") + (run_until 7) + (expect_output "go\nstill go\n") + (run_to_finish) + (expect_output "level=5\n") + (assert_eq y 5)) + +(case level_sensitive_always_runs_as_a_process + (source "level.sv" #" + module Top(output logic [7:0] y); + logic [7:0] a = 8'd0; + logic [7:0] b = 8'd0; + initial y = 8'd0; + always @(a or b) y = a + b; + initial begin + #2 a = 8'd3; + #2 b = 8'd4; + #2 a = 8'd5; + #2 $finish; + end + endmodule + "#) + (top Top) + (run_until 1) + (assert_eq y 0) + (run_until 3) + (assert_eq y 3) + (run_until 5) + (assert_eq y 7) + (run_to_finish) + (assert_eq y 9)) + +(case processes_wake_each_other_at_the_same_time + (source "handshake.sv" #" + module Top(output logic [7:0] y); + logic start = 1'b0; + logic done = 1'b0; + initial begin + y = 8'd0; + #3 start = 1'b1; + @(posedge done); + $display("done at y=%0d", y); + $finish; + end + initial begin + @(posedge start); + y = 8'd1; + #0 y = 8'd2; + done = 1'b1; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "done at y=2\n")) + +(case tasks_with_timing_controls_run_in_processes + (source "tasks.sv" #" + module Top(output logic [7:0] y); + logic clk = 1'b0; + always #5 clk = ~clk; + task automatic pulse(input logic [7:0] value, input int cycles); + y = value; + repeat (cycles) @(posedge clk); + #1 y = 8'd0; + endtask + initial begin + y = 8'd0; + pulse(8'd7, 2); + $display("y=%0d", y); + pulse(8'd9, 1); + $display("y=%0d", y); + $finish; + end + endmodule + "#) + (top Top) + (run_until 10) + (assert_eq y 7) + ; The first pulse ends at 16, when the second one starts. + (run_until 16) + (assert_eq y 9) + (expect_output "y=0\n") + (run_until 25) + (assert_eq y 9) + (run_to_finish) + (expect_output "y=0\n") + (assert_eq y 0)) + +(case edge_waits_see_the_signals_the_script_drives + (source "driven.sv" #" + module Top(input logic a, output logic [7:0] seen); + initial begin + seen = 8'd0; + forever begin + @(posedge a); + seen = seen + 8'd1; + end + end + endmodule + "#) + (top Top) + (modify (set a 0)) + (run_until 1) + (for value (list 1 0 1 1 0) + (modify (set a value)) + (run_until 2)) + (assert_eq seen 2) + (modify (set a 1)) + (run_until 3) + (assert_eq seen 3)) + +(case finish_in_an_always_process_ends_the_simulation + (source "finish.sv" #" + module Top(output logic [7:0] ticks); + initial ticks = 8'd0; + always begin + #3 ticks = ticks + 8'd1; + if (ticks == 8'd4) $finish; + end + endmodule + "#) + (top Top) + (run_until 7) + (assert_eq ticks 2) + (run_to_finish) + (assert_eq ticks 4)) + +(case waiting_processes_do_not_keep_an_idle_simulation_running + (source "idle.sv" #" + module Top(output logic [7:0] y); + logic never = 1'b0; + initial begin + y = 8'd1; + @(posedge never); + y = 8'd2; + end + initial #5 y = 8'd3; + endmodule + "#) + (top Top) + (run_until 5) + (assert_eq y 3) + (run_until 100) + (assert_eq y 3)) + +(case four_state_edges_count_transitions_through_unknown + (source "four_state_edges.sv" #" + module Top(output logic [7:0] pos, output logic [7:0] neg, output logic [7:0] any); + logic s = 1'b0; + initial begin + pos = 8'd0; + neg = 8'd0; + any = 8'd0; + #1 s = 1'bx; // 0 -> x: posedge + #1 s = 1'b1; // x -> 1: posedge + #1 s = 1'bz; // 1 -> z: negedge + #1 s = 1'bx; // z -> x: no edge, a change + #1 s = 1'b0; // x -> 0: negedge + #1 s = 1'b1; // 0 -> 1: posedge + #1 s = 1'b0; // 1 -> 0: negedge + #1 $finish; + end + initial forever begin + @(posedge s); + pos = pos + 8'd1; + end + initial forever begin + @(negedge s); + neg = neg + 8'd1; + end + initial forever begin + @(s); + any = any + 8'd1; + end + endmodule + "#) + (top Top) + (four_state) + (run_to_finish) + (assert_eq pos 3) + (assert_eq neg 3) + (assert_eq any 7)) + +(case unknown_delays_and_conditions_count_as_zero_and_false + (source "unknown.sv" #" + module Top(output logic [7:0] y); + logic [7:0] amount = 8'bx; + logic flag = 1'bx; + initial begin + y = 8'd1; + #amount y = 8'd2; + wait (flag) y = 8'd3; + $finish; + end + initial #4 flag = 1'b1; + endmodule + "#) + (top Top) + (four_state) + (run_until 0) + (assert_eq y 2) + (run_to_finish) + (assert_eq y 3)) diff --git a/crates/celox-test-suite/src/verification.rs b/crates/celox-test-suite/src/verification.rs index cee32fb6acb..428a36591ea 100644 --- a/crates/celox-test-suite/src/verification.rs +++ b/crates/celox-test-suite/src/verification.rs @@ -498,6 +498,16 @@ impl Backend for ObservedBackend { .take_output() .inspect_err(|_| self.failed.store(true, Ordering::Relaxed)) } + fn run_until(&mut self, time: u64) -> Result<()> { + self.backend + .run_until(time) + .inspect_err(|_| self.failed.store(true, Ordering::Relaxed)) + } + fn run_to_finish(&mut self) -> Result<()> { + self.backend + .run_to_finish() + .inspect_err(|_| self.failed.store(true, Ordering::Relaxed)) + } } /// How a runner builds a case for a tool: a design for the process diff --git a/crates/celox-test-suite/verification/icarus.json b/crates/celox-test-suite/verification/icarus.json index 75107787915..99a56cae385 100644 --- a/crates/celox-test-suite/verification/icarus.json +++ b/crates/celox-test-suite/verification/icarus.json @@ -10959,6 +10959,7 @@ "exclude_stronger_than_sv": false, "include_ignored": false, "schema_version": 3, + "suite": "veryl", "suite_version": "0.10.1", "tool": "icarus", "version": "Icarus Verilog version 13.0 (stable) (v13_0)" diff --git a/crates/celox-test-suite/verification/sv/icarus.json b/crates/celox-test-suite/verification/sv/icarus.json index 6ca307b0857..fc5673d30d5 100644 --- a/crates/celox-test-suite/verification/sv/icarus.json +++ b/crates/celox-test-suite/verification/sv/icarus.json @@ -3014,6 +3014,149 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::always_with_a_delay_generates_a_clock", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::any_change_waits_wake_on_every_value_change", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::delays_resume_initial_blocks_at_later_times", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::edge_waits_resume_before_the_registers_of_that_edge_update", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::edge_waits_see_the_signals_the_script_drives", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::finish_in_an_always_process_ends_the_simulation", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::four_state_edges_count_transitions_through_unknown", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::level_sensitive_always_runs_as_a_process", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::processes_wake_each_other_at_the_same_time", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::tasks_with_timing_controls_run_in_processes", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::unknown_delays_and_conditions_count_as_zero_and_false", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::wait_statements_block_until_their_condition_holds", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::waiting_processes_do_not_keep_an_idle_simulation_running", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", diff --git a/crates/celox-test-suite/verification/sv/verilator.json b/crates/celox-test-suite/verification/sv/verilator.json index 7a6fc8db517..5692d8be4e2 100644 --- a/crates/celox-test-suite/verification/sv/verilator.json +++ b/crates/celox-test-suite/verification/sv/verilator.json @@ -2438,6 +2438,149 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::always_with_a_delay_generates_a_clock", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::any_change_waits_wake_on_every_value_change", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::delays_resume_initial_blocks_at_later_times", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::edge_waits_resume_before_the_registers_of_that_edge_update", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::edge_waits_see_the_signals_the_script_drives", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::finish_in_an_always_process_ends_the_simulation", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "four-state expectations", + "expectation": "Simulation", + "name": "timing::four_state_edges_count_transitions_through_unknown", + "phase": "compile", + "status": "unsupported", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::level_sensitive_always_runs_as_a_process", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::processes_wake_each_other_at_the_same_time", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::tasks_with_timing_controls_run_in_processes", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "four-state expectations", + "expectation": "Simulation", + "name": "timing::unknown_delays_and_conditions_count_as_zero_and_false", + "phase": "compile", + "status": "unsupported", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::wait_statements_block_until_their_condition_holds", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::waiting_processes_do_not_keep_an_idle_simulation_running", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", diff --git a/crates/celox-test-suite/verification/verilator.json b/crates/celox-test-suite/verification/verilator.json index feefaa64d0e..f6a004019c4 100644 --- a/crates/celox-test-suite/verification/verilator.json +++ b/crates/celox-test-suite/verification/verilator.json @@ -9376,6 +9376,7 @@ "exclude_stronger_than_sv": false, "include_ignored": false, "schema_version": 3, + "suite": "veryl", "suite_version": "0.10.1", "tool": "verilator", "version": "Verilator 5.052 2026-09-05 rev v5.052" diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 4a8c70b2ca3..918ccfb00dd 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -356,6 +356,30 @@ impl Simulation { self.simulator.get(signal) } + /// Returns the value and unknown-bit mask of a signal. + pub fn get_four_state( + &mut self, + signal: SignalRef, + ) -> (num_bigint::BigUint, num_bigint::BigUint) { + self.simulator.get_four_state(signal) + } + + /// Sets a signal to a known value. The write takes effect at the current + /// time: processes waiting for it resume when the simulation next runs. + pub fn set_wide(&mut self, signal: SignalRef, value: num_bigint::BigUint) { + self.simulator.set_wide(signal, value); + } + + /// Sets a signal's value and unknown-bit mask, like [`Self::set_wide`]. + pub fn set_four_state( + &mut self, + signal: SignalRef, + value: num_bigint::BigUint, + mask: num_bigint::BigUint, + ) { + self.simulator.set_four_state(signal, value, mask); + } + /// Modifies internal state via a callback and re-stabilizes combinational logic. pub fn modify(&mut self, f: F) -> Result<(), RuntimeErrorCode> where diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index d3ad161008a..e048819221c 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -2847,6 +2847,74 @@ mod host { } } + /// The same configuration as a builder of an event-driven + /// [`Simulator`] that emits the triggers the timed scheduler needs. + fn into_simulator_builder(self) -> SimulatorBuilder<'a, Simulator> { + let mut builder = SimulatorBuilder { + sources: self.sources, + sv_sources: self.sv_sources, + top: self.top, + ignored_loops: self.ignored_loops, + true_loops: self.true_loops, + options: self.options, + vcd_path: self.vcd_path, + metadata: self.metadata, + clock_type: self.clock_type, + reset_type: self.reset_type, + param_overrides: self.param_overrides, + live_signals: self.live_signals, + injected_components: self.injected_components, + frontend_artifact: self.frontend_artifact, + _marker: std::marker::PhantomData, + }; + builder.options.emit_triggers = true; + builder + } + + /// Compiles with the Cranelift JIT backend and constructs the timed + /// simulation wrapper. + pub fn build_cranelift(self) -> Result, SimulatorError> { + Ok(crate::Simulation::new( + self.into_simulator_builder().build_cranelift()?, + )) + } + + /// Compiles with the interpreter backend and constructs the timed + /// simulation wrapper. + pub fn build_interpreter( + self, + ) -> Result, SimulatorError> { + Ok(crate::Simulation::new( + self.into_simulator_builder().build_interpreter()?, + )) + } + + /// Compiles with the WebAssembly backend and constructs the timed + /// simulation wrapper. + pub fn build_wasm( + self, + ) -> Result, SimulatorError> + { + Ok(crate::Simulation::new( + self.into_simulator_builder().build_wasm()?, + )) + } + + /// Compiles with the native backend of the host architecture and + /// constructs the timed simulation wrapper. + #[cfg(any( + all(target_arch = "x86_64", not(feature = "arm64-codegen")), + all(target_arch = "aarch64", not(feature = "x86_64-codegen")) + ))] + pub fn build_native( + self, + ) -> Result, SimulatorError> + { + Ok(crate::Simulation::new( + self.into_simulator_builder().build_native()?, + )) + } + /// Compiles the Veryl source and constructs the timed simulation wrapper. pub fn build(mut self) -> Result { self.options.emit_triggers = true; diff --git a/crates/celox/tests/frontends/systemverilog/suite.rs b/crates/celox/tests/frontends/systemverilog/suite.rs index e2e82704238..f9b9df73bf8 100644 --- a/crates/celox/tests/frontends/systemverilog/suite.rs +++ b/crates/celox/tests/frontends/systemverilog/suite.rs @@ -1,10 +1,97 @@ //! Runs SystemVerilog suite cases on the Celox backends. -use celox::{BigUint, SimBackend, Simulator}; +use celox::{BigUint, RuntimeEvent, SimBackend, Simulation, Simulator}; use celox_test_suite::{Backend, CompilationRejected, Design, Result, SignalPath}; struct CeloxBackend(Simulator); +/// A timed case: the design's own processes and clocks run. +struct TimedBackend(Simulation); + +fn signal_of(sim: &Simulation, path: &SignalPath) -> celox::SignalRef { + let instances: Vec<_> = path + .instances + .iter() + .map(|i| (i.name.as_str(), i.index.unwrap_or(0))) + .collect(); + sim.child_signal(&instances, &path.name) +} + +fn collect_output(events: Vec) -> Result { + let mut output = String::new(); + for event in events { + match event { + RuntimeEvent::Display { message } => { + output.push_str(&message); + output.push('\n'); + } + RuntimeEvent::Write { message } => output.push_str(&message), + RuntimeEvent::Missed { count } => { + return Err(format!("{count} runtime events were missed").into()); + } + // Simulators print severity messages in their own words. + _ => {} + } + } + Ok(output) +} + +impl Backend for TimedBackend { + fn write(&mut self, path: &SignalPath, payload: BigUint, mask: BigUint) -> Result<()> { + let signal = signal_of(&self.0, path); + if mask == BigUint::default() { + self.0.set_wide(signal, payload); + } else { + self.0.set_four_state(signal, payload, mask); + } + Ok(()) + } + + fn read(&mut self, path: &SignalPath) -> Result<(BigUint, BigUint)> { + let signal = signal_of(&self.0, path); + Ok(self.0.get_four_state(signal)) + } + + fn eval_comb(&mut self) -> Result<()> { + self.0.eval_comb().map_err(Into::into) + } + + fn tick(&mut self, _event: &str) -> Result<()> { + Err("tick is not available in a timed case; the design drives its clocks".into()) + } + + fn take_output(&mut self) -> Result { + collect_output(self.0.drain_runtime_events()) + } + + fn run_until(&mut self, time: u64) -> Result<()> { + let now = self.0.time(); + if time < now { + return Err(format!("run_until {time}: the simulation is already at {now}").into()); + } + self.0.run_until(time)?; + if self.0.is_finished() { + return Err(format!( + "run_until {time}: the design finished the simulation at {}", + self.0.time() + ) + .into()); + } + Ok(()) + } + + fn run_to_finish(&mut self) -> Result<()> { + self.0.run_until(u64::MAX - 1)?; + if !self.0.is_finished() { + return Err( + "run_to_finish: the simulation ran out of events before a process finished it" + .into(), + ); + } + Ok(()) + } +} + impl CeloxBackend { fn signal(&self, path: &SignalPath) -> celox::SignalRef { let instances: Vec<_> = path @@ -40,22 +127,7 @@ impl Backend for CeloxBackend { } fn take_output(&mut self) -> Result { - let mut output = String::new(); - for event in self.0.drain_runtime_events() { - match event { - celox::RuntimeEvent::Display { message } => { - output.push_str(&message); - output.push('\n'); - } - celox::RuntimeEvent::Write { message } => output.push_str(&message), - celox::RuntimeEvent::Missed { count } => { - return Err(format!("{count} runtime events were missed").into()); - } - // Simulators print severity messages in their own words. - _ => {} - } - } - Ok(output) + collect_output(self.0.drain_runtime_events()) } } @@ -65,6 +137,30 @@ fn build(design: &Design, backend: &str) -> Result> { .iter() .map(|source| (source.text.as_str(), source.path.as_path())) .collect::>(); + if design.timed { + let builder = design.parameters.iter().fold( + Simulation::from_sv_sources(sources, &design.top).four_state(design.four_state), + |builder, (name, value)| builder.param(name, *value), + ); + return Ok(match backend { + "native" => Box::new(TimedBackend(builder.build_native()?)), + "cranelift" => Box::new(TimedBackend(builder.build_cranelift()?)), + "native-parallel" => Box::new(TimedBackend( + builder + .threads(4) + .parallel_partition(celox::ParallelPartition::Always) + .build_native()?, + )), + "cranelift-parallel" => Box::new(TimedBackend( + builder + .threads(4) + .parallel_partition(celox::ParallelPartition::Always) + .build_cranelift()?, + )), + "wasm" => Box::new(TimedBackend(builder.build_wasm()?)), + _ => return Err(format!("unknown backend: {backend}").into()), + }); + } let builder = design.parameters.iter().fold( Simulator::from_sv_sources(sources, &design.top).four_state(design.four_state), |builder, (name, value)| builder.param(name, *value), diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs new file mode 100644 index 00000000000..6ba7c955e05 --- /dev/null +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -0,0 +1,56 @@ +//! Shared timing-control cases: `#delay`, `@(event)` and `wait` in +//! processes, driven through the timed `Simulation` on every backend. + +sv_backends! { + fn delays_resume_initial_blocks_at_later_times(sim) { + @case "timing::delays_resume_initial_blocks_at_later_times"; + } + + fn always_with_a_delay_generates_a_clock(sim) { + @case "timing::always_with_a_delay_generates_a_clock"; + } + + fn edge_waits_resume_before_the_registers_of_that_edge_update(sim) { + @case "timing::edge_waits_resume_before_the_registers_of_that_edge_update"; + } + + fn any_change_waits_wake_on_every_value_change(sim) { + @case "timing::any_change_waits_wake_on_every_value_change"; + } + + fn wait_statements_block_until_their_condition_holds(sim) { + @case "timing::wait_statements_block_until_their_condition_holds"; + } + + fn level_sensitive_always_runs_as_a_process(sim) { + @case "timing::level_sensitive_always_runs_as_a_process"; + } + + fn processes_wake_each_other_at_the_same_time(sim) { + @case "timing::processes_wake_each_other_at_the_same_time"; + } + + fn tasks_with_timing_controls_run_in_processes(sim) { + @case "timing::tasks_with_timing_controls_run_in_processes"; + } + + fn edge_waits_see_the_signals_the_script_drives(sim) { + @case "timing::edge_waits_see_the_signals_the_script_drives"; + } + + fn finish_in_an_always_process_ends_the_simulation(sim) { + @case "timing::finish_in_an_always_process_ends_the_simulation"; + } + + fn waiting_processes_do_not_keep_an_idle_simulation_running(sim) { + @case "timing::waiting_processes_do_not_keep_an_idle_simulation_running"; + } + + fn four_state_edges_count_transitions_through_unknown(sim) { + @case "timing::four_state_edges_count_transitions_through_unknown"; + } + + fn unknown_delays_and_conditions_count_as_zero_and_false(sim) { + @case "timing::unknown_delays_and_conditions_count_as_zero_and_false"; + } +} diff --git a/crates/celox/tests/systemverilog.rs b/crates/celox/tests/systemverilog.rs index 882b45bcbce..17d89d522d0 100644 --- a/crates/celox/tests/systemverilog.rs +++ b/crates/celox/tests/systemverilog.rs @@ -123,6 +123,8 @@ mod suite; mod synthesizable; #[path = "frontends/systemverilog/system_functions.rs"] mod system_functions; +#[path = "frontends/systemverilog/timing.rs"] +mod timing; #[path = "frontends/systemverilog/types.rs"] mod types; From 5c9b14ced842368d50bfd92b402cdbe9c3d234b5 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 10 Oct 2026 14:59:38 +0900 Subject: [PATCH 02/75] fix(suite): align the generated timed testbench with the Celox adapter - Settling in the Celox timed adapter also resumes the processes a write woke (`Simulation::settle`), as the generated bench's settle step does. - `run_to_finish` keeps one late event pending instead of a perpetual one; when it comes, the run fails as unfinished and skips the final checks. - Simulator `$finish` notices are filtered only for the staged source files, not for every line of their shape. - The script's top-level bindings are module-scope variables, so the checks after `run_to_finish` see them in their `final` block. - `run_until` rejects a time above `RUN_UNTIL_LIMIT` in every adapter. --- crates/celox-test-suite/README.md | 11 +- crates/celox-test-suite/src/script/ast.rs | 5 + crates/celox-test-suite/src/script/interp.rs | 4 +- crates/celox-test-suite/src/script/sv.rs | 158 +++++++++++++++--- crates/celox-test-suite/src/verification.rs | 12 +- crates/celox/src/simulation.rs | 9 + .../frontends/systemverilog/processes.rs | 24 +++ .../tests/frontends/systemverilog/suite.rs | 4 +- 8 files changed, 195 insertions(+), 32 deletions(-) diff --git a/crates/celox-test-suite/README.md b/crates/celox-test-suite/README.md index d6f3c137c22..5e40d8eb00d 100644 --- a/crates/celox-test-suite/README.md +++ b/crates/celox-test-suite/README.md @@ -95,8 +95,11 @@ behavioral model and verifies that incorrect results are rejected. and clocks. `run_until` advances to the given time in the design's time units and fails when the design has finished by then; `run_to_finish` runs until a process calls `$finish` and fails when the events run out first. A - `write` in a timed case takes effect at the current time. The optional - methods' defaults return an unsupported-operation error. + `write` in a timed case takes effect at the current time, and `eval_comb` + also resumes the processes it woke, as a simulator's settle step does. A + time later than `RUN_UNTIL_LIMIT` (`i64::MAX / 1000`) is out of range in + every adapter. The optional methods' defaults return an + unsupported-operation error. - Start each design with fresh storage: zero for two-state signals and X for four-state signals. Initial combinational outputs must be readable before an input is written. Generic clock/reset types use Veryl's defaults (positive @@ -250,7 +253,9 @@ checks the design's output with `expect_output`. Design delays count time units; the generated testbench for an external simulator sets a time scale of 1 ns with 1 ps precision and settles in 1 ps steps, so its checks after `run_until` observe everything the design did at that time. Only checks may -follow `run_to_finish`; they run in a `final` block. +follow `run_to_finish`; they run in a `final` block, which sees the script's +top-level bindings. A design that does not finish within the generated +testbench's guard fails `run_to_finish` instead of passing the checks. For an invalid design, write `(expect reject)` and no statements. `TestCase::expectation` lets consumers select these separately. For additional diff --git a/crates/celox-test-suite/src/script/ast.rs b/crates/celox-test-suite/src/script/ast.rs index 2a003b32ce3..7991b9cb84c 100644 --- a/crates/celox-test-suite/src/script/ast.rs +++ b/crates/celox-test-suite/src/script/ast.rs @@ -178,6 +178,11 @@ pub struct Stmt { pub pos: Pos, } +/// The latest time `run_until` may name, in the design's time unit: the +/// generated external testbenches scale it to picoseconds in a 64-bit +/// signed time, and every adapter rejects a later time alike. +pub const RUN_UNTIL_LIMIT: u64 = i64::MAX as u64 / 1000; + #[derive(Clone, Debug, PartialEq, Eq)] pub enum StmtKind { /// `(set SIGNAL EXPR)`: stage a write; `eval`, a read or a tick settles it. diff --git a/crates/celox-test-suite/src/script/interp.rs b/crates/celox-test-suite/src/script/interp.rs index f0234c4c762..7cf1c956654 100644 --- a/crates/celox-test-suite/src/script/interp.rs +++ b/crates/celox-test-suite/src/script/interp.rs @@ -1,6 +1,6 @@ //! Script interpreter over the backend-independent [`Simulator`]. -use super::ast::{Actual, Expr, Op, ScriptCase, Sequence, Stmt, StmtKind, Value}; +use super::ast::{Actual, Expr, Op, RUN_UNTIL_LIMIT, ScriptCase, Sequence, Stmt, StmtKind, Value}; use super::sexpr::Pos; use crate::{Signal, SignalPath, Simulator}; use num_bigint::{BigInt, BigUint, Sign}; @@ -501,7 +501,7 @@ impl Interpreter<'_> { } StmtKind::RunUntil(time) => { let time = self.known(time, pos, "time")?; - let Some(time) = time.to_u64() else { + let Some(time) = time.to_u64().filter(|time| *time <= RUN_UNTIL_LIMIT) else { return fail(pos, format!("time {time} is out of range")); }; if let Err(error) = self.sim.run_until(time) { diff --git a/crates/celox-test-suite/src/script/sv.rs b/crates/celox-test-suite/src/script/sv.rs index 721bb39bbcd..34ccac46427 100644 --- a/crates/celox-test-suite/src/script/sv.rs +++ b/crates/celox-test-suite/src/script/sv.rs @@ -19,7 +19,7 @@ //! testbench only keeps the simulation alive; the checks that follow run in //! a `final` block, when the design has called `$finish`. -use super::ast::{Actual, Expr, Op, ScriptCase, Sequence, Stmt, StmtKind, Value}; +use super::ast::{Actual, Expr, Op, RUN_UNTIL_LIMIT, ScriptCase, Sequence, Stmt, StmtKind, Value}; use super::sexpr::Pos; use crate::SignalPath; use num_traits::{Signed, ToPrimitive}; @@ -96,6 +96,10 @@ const OUTPUT_MARKER: &str = "@suite output "; /// the whole script has run. const END_MARKER: &str = "@suite end"; +/// Picoseconds after the script's last statement at which a design that +/// `run_to_finish` waits for is judged never to finish. +const RUN_TO_FINISH_GUARD: u64 = 1_000_000_000; + fn hex_encode(text: &str) -> String { text.bytes().map(|byte| format!("{byte:02x}")).collect() } @@ -121,19 +125,42 @@ fn is_finish_notice(line: &str) -> bool { false } -/// `text` without the simulators' `$finish` notices. -fn design_output(text: &str) -> String { +/// Whether `line` is a simulator's notice of a `$finish` in one of the +/// simulation's source files `sources` (file names): a design may print a +/// line of the same shape, which is its output. +fn is_source_finish_notice(line: &str, sources: &[String]) -> bool { + is_finish_notice(line) + && notice_file(line).is_some_and(|file| { + let name = std::path::Path::new(file) + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_default(); + sources.iter().any(|source| *source == name) + }) +} + +/// The file a `$finish` notice names. +fn notice_file(line: &str) -> Option<&str> { + let location = match line.strip_prefix("- ") { + Some(rest) => rest.strip_suffix(": Verilog $finish")?, + None => line.split_once(": $finish called at ")?.0, + }; + Some(location.rsplit_once(':')?.0) +} + +/// `text` without the simulators' `$finish` notices for `sources`. +fn design_output(text: &str, sources: &[String]) -> String { let mut output = String::new(); let mut rest = text; while let Some(at) = rest.find('\n') { let line = &rest[..at]; - if !is_finish_notice(line) { + if !is_source_finish_notice(line, sources) { output.push_str(line); output.push('\n'); } rest = &rest[at + 1..]; } - if !is_finish_notice(rest) { + if !is_source_finish_notice(rest, sources) { output.push_str(rest); } output @@ -143,8 +170,9 @@ fn design_output(text: &str) -> String { /// end: a design's `$finish` can end some simulators' runs early without a /// failure. Before that, the text before each `expect_output` marker, since /// the previous one, must equal the text the marker encodes. A simulator's -/// notice of a `$finish` call is not design output. -pub fn check_output(log: &str) -> Result<(), String> { +/// notice of a `$finish` call in one of the simulation's source files +/// (`sources`, file names) is not design output. +pub fn check_output(log: &str, sources: &[String]) -> Result<(), String> { let Some(end) = log.find(&format!("\n{END_MARKER}\n")) else { return Err("the simulation ended before the script did".into()); }; @@ -166,7 +194,7 @@ pub fn check_output(log: &str) -> Result<(), String> { .collect::>>() .ok_or("malformed output marker")?; let expected = String::from_utf8_lossy(&bytes); - let output = design_output(output); + let output = design_output(output, sources); if output != expected { return Err(format!( "{location}: expect_output: expected {expected:?}, got {output:?}" @@ -205,6 +233,9 @@ struct Generator<'a> { /// Generating the checks after `run_to_finish`, which run in a `final` /// block: time cannot advance there, and the state is final. in_final: bool, + /// The script's top-level bindings, declared at module scope so the + /// checks after `run_to_finish`, in their own block, still see them. + declarations: Vec, } fn path_text(path: &SignalPath) -> String { @@ -546,6 +577,13 @@ impl Generator<'_> { } fn block(&mut self, stmts: &[Stmt]) -> Result<(), Unsupported> { + self.block_at(stmts, false) + } + + /// `stmts` as a block. The bindings of the script's top level + /// (`top_level`) are module-scope variables; a nested block's are local + /// to it. + fn block_at(&mut self, stmts: &[Stmt], top_level: bool) -> Result<(), Unsupported> { self.line("begin"); self.indent += 1; let mut opened = 0; @@ -561,11 +599,21 @@ impl Generator<'_> { self.indent += 1; self.line(format!("logic signed [{w}:0] {temp};")); self.line(format!("{temp} = {value};")); - self.line("begin"); - self.indent += 1; - opened += 2; - self.line(format!("logic signed [{w}:0] v_{name};")); - self.line(format!("v_{name} = {temp};")); + if top_level { + let declaration = format!("logic signed [{w}:0] v_{name};"); + if !self.declarations.contains(&declaration) { + self.declarations.push(declaration); + } + self.line(format!("v_{name} = {temp};")); + self.indent -= 1; + self.line("end"); + } else { + self.line("begin"); + self.indent += 1; + opened += 2; + self.line(format!("logic signed [{w}:0] v_{name};")); + self.line(format!("v_{name} = {temp};")); + } } else { self.stmt(stmt)?; } @@ -848,6 +896,15 @@ impl Generator<'_> { self.settle_for(&[time]); let time = self.expr(time); self.require_known(&time, pos, "time"); + // The time is scaled to picoseconds in a 64-bit time. + self.line(format!( + "if ({time} < 0 || {time} > {}'sd{RUN_UNTIL_LIMIT}) begin", + self.width + )); + self.indent += 1; + self.fail(pos, "time %0d is out of range", &[time.clone()]); + self.indent -= 1; + self.line("end"); let temp = self.temp(); self.line("begin"); self.indent += 1; @@ -911,23 +968,38 @@ pub fn testbench(case: &ScriptCase, design: &DesignInfo) -> Result { generator.in_final = true; - generator.block(after)?; + generator.block_at(after, true)?; Some(std::mem::take(&mut generator.out)) } None => None, }; + let declarations = std::mem::take(&mut generator.declarations); let w = width - 1; let mut out = String::new(); let _ = writeln!(out, "// Generated from {} by celox-test-suite.", case.name); @@ -970,6 +1042,12 @@ pub fn testbench(case: &ScriptCase, design: &DesignInfo) -> Result Result { // The design ends the simulation; the checks run in its wake. out.push_str(" end\n\n final begin\n"); + out.push_str(" if (!suite_unfinished)\n"); out.push_str(&checks); out.push_str(&end); out.push_str(" end\nendmodule\n"); @@ -1037,15 +1116,44 @@ mod tests { #[test] fn finish_notices_are_not_design_output() { + let sources = ["source_0.sv".to_string()]; let icarus = "done\n/tmp/case/source_0.sv:17: $finish called at 18000 (1ps)\n"; - assert_eq!(design_output(icarus), "done\n"); + assert_eq!(design_output(icarus, &sources), "done\n"); let verilator = "done\n- /tmp/case/source_0.sv:19: Verilog $finish\n"; - assert_eq!(design_output(verilator), "done\n"); + assert_eq!(design_output(verilator, &sources), "done\n"); assert_eq!( - design_output("a: $finish called at x\n"), + design_output("a: $finish called at x\n", &sources), "a: $finish called at x\n" ); - assert_eq!(design_output("no newline"), "no newline"); + assert_eq!(design_output("no newline", &sources), "no newline"); + // A design's line of the same shape names no source file. + let printed = "foo.sv:1: $finish called at 0 (1ps)\n"; + assert_eq!(design_output(printed, &sources), printed); + } + + #[test] + fn top_level_bindings_are_module_variables_for_the_final_checks() { + let text = testbench( + &case("(let expected 5) (run_to_finish) (assert_eq o expected)"), + &design(), + ) + .unwrap(); + assert!(text.contains(" logic signed [127:0] v_expected;\n")); + assert!(text.contains("v_expected = t1;")); + assert!(text.contains("final begin\n if (!suite_unfinished)\n")); + // The design must finish: a late event fails the run instead of + // letting an exhausted event queue pass the final checks. + assert!(text.contains("#1000000000;\n")); + assert!(text.contains("suite_unfinished = 1;")); + assert!(text.contains("run_to_finish: the design did not finish the simulation")); + assert!(!text.contains("forever #")); + } + + #[test] + fn run_until_rejects_times_outside_the_shared_range() { + let text = testbench(&case("(run_until 5)"), &design()).unwrap(); + assert!(text.contains(&format!("> 128'sd{RUN_UNTIL_LIMIT}) begin"))); + assert!(text.contains("time %0d is out of range")); } fn case(text: &str) -> ScriptCase { @@ -1107,14 +1215,14 @@ mod tests { assert!(text.contains(r#"$write("\n@suite output 610a62 g::t at"#)); assert!(text.contains(r#"$write("\n@suite end\n");"#)); let log = "a\nb\n@suite output 610a62 here\n\n@suite output there\n\n@suite end\nfinish\n"; - assert_eq!(check_output(log), Ok(())); + assert_eq!(check_output(log, &[]), Ok(())); assert_eq!( - check_output("a\n@suite output 610a62 here\n\n@suite end\n"), + check_output("a\n@suite output 610a62 here\n\n@suite end\n", &[]), Err(r#"here: expect_output: expected "a\nb", got "a""#.into()) ); // A design's $finish ended the run before the script did. assert_eq!( - check_output("a\nb\n@suite output 610a62 here\n"), + check_output("a\nb\n@suite output 610a62 here\n", &[]), Err("the simulation ended before the script did".into()) ); } diff --git a/crates/celox-test-suite/src/verification.rs b/crates/celox-test-suite/src/verification.rs index 2f9d26af2dd..97f158f9694 100644 --- a/crates/celox-test-suite/src/verification.rs +++ b/crates/celox-test-suite/src/verification.rs @@ -619,7 +619,17 @@ fn run_script( match backend.run_testbench() { Ok(()) => { let log = std::fs::read(directory.join("protocol.log")).unwrap_or_default(); - match crate::script::sv::check_output(&String::from_utf8_lossy(&log)) { + // The simulators' `$finish` notices name the staged source files. + let sources: Vec = std::fs::read_dir(directory) + .map(|entries| { + entries + .filter_map(|entry| entry.ok()) + .map(|entry| entry.file_name().to_string_lossy().into_owned()) + .filter(|name| name.ends_with(".sv") || name.ends_with(".v")) + .collect() + }) + .unwrap_or_default(); + match crate::script::sv::check_output(&String::from_utf8_lossy(&log), &sources) { Ok(()) => ("passed", "execute", String::new()), Err(detail) => ("mismatch", "execute", detail), } diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 813e5770e86..af33f535077 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -423,6 +423,15 @@ impl Simulation { self.state.step(&mut self.simulator) } + /// Settle the combinational logic after host writes and resume the + /// processes they woke at the current time, with the rounds that + /// follow, as [`Self::step`] does before advancing. Time does not + /// advance. + pub fn settle(&mut self) -> Result<(), RuntimeErrorCode> { + self.simulator.eval_comb()?; + self.state.poll_waiting(&mut self.simulator) + } + /// Advance time and run until `end_time` (inclusive). As for /// [`Self::step`], processes that a host write woke resume first. pub fn run_until(&mut self, end_time: u64) -> Result<(), RuntimeErrorCode> { diff --git a/crates/celox/tests/frontends/systemverilog/processes.rs b/crates/celox/tests/frontends/systemverilog/processes.rs index bf6e36187e5..753366fb425 100644 --- a/crates/celox/tests/frontends/systemverilog/processes.rs +++ b/crates/celox/tests/frontends/systemverilog/processes.rs @@ -837,3 +837,27 @@ fn rejects_nonblocking_assignments_in_tasks_a_process_calls() { build_error(source) ); } + +/// `Simulation::settle` resumes the processes a host write woke at the +/// current time, as a simulator's settle step does, without advancing time. +#[test] +fn settle_resumes_the_processes_a_host_write_wakes() { + let source = r#" + module Top(input logic go, output logic [7:0] seen); + initial begin + seen = 8'd0; + wait (go); + seen = 8'd1; + #0 seen = 8'd2; + end + endmodule + "#; + let mut sim = simulation(source); + let (go, seen) = (sim.signal("go"), sim.signal("seen")); + assert_eq!(sim.step().unwrap(), Some(0)); + assert_eq!(sim.get(seen), 0u8.into()); + sim.set_wide(go, 1u8.into()); + sim.settle().unwrap(); + assert_eq!(sim.get(seen), 2u8.into()); + assert_eq!(sim.time(), 0); +} diff --git a/crates/celox/tests/frontends/systemverilog/suite.rs b/crates/celox/tests/frontends/systemverilog/suite.rs index f9b9df73bf8..233a3ad44be 100644 --- a/crates/celox/tests/frontends/systemverilog/suite.rs +++ b/crates/celox/tests/frontends/systemverilog/suite.rs @@ -52,8 +52,10 @@ impl Backend for TimedBackend { Ok(self.0.get_four_state(signal)) } + /// Settling also resumes the processes the writes woke, as the external + /// simulators' settle step does. fn eval_comb(&mut self) -> Result<()> { - self.0.eval_comb().map_err(Into::into) + self.0.settle().map_err(Into::into) } fn tick(&mut self, _event: &str) -> Result<()> { From d56c1ba536f787dbc4d1039bfd552c8270f7f8aa Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 10 Oct 2026 15:37:00 +0900 Subject: [PATCH 03/75] style(suite): satisfy clippy in the testbench generator --- crates/celox-test-suite/src/script/sv.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/celox-test-suite/src/script/sv.rs b/crates/celox-test-suite/src/script/sv.rs index 34ccac46427..3f0a4fb5151 100644 --- a/crates/celox-test-suite/src/script/sv.rs +++ b/crates/celox-test-suite/src/script/sv.rs @@ -135,7 +135,7 @@ fn is_source_finish_notice(line: &str, sources: &[String]) -> bool { .file_name() .map(|name| name.to_string_lossy().into_owned()) .unwrap_or_default(); - sources.iter().any(|source| *source == name) + sources.contains(&name) }) } @@ -902,7 +902,7 @@ impl Generator<'_> { self.width )); self.indent += 1; - self.fail(pos, "time %0d is out of range", &[time.clone()]); + self.fail(pos, "time %0d is out of range", std::slice::from_ref(&time)); self.indent -= 1; self.line("end"); let temp = self.temp(); From c98c668625d2fb16cedab7eeda65bb041615eb99 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 10 Oct 2026 19:35:07 +0900 Subject: [PATCH 04/75] fix(suite): keep settle's result shape after poll_waiting reports progress --- crates/celox/src/simulation.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 9a96c395d85..10bab2a482c 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -433,7 +433,8 @@ impl Simulation { /// advance. pub fn settle(&mut self) -> Result<(), RuntimeErrorCode> { self.simulator.eval_comb()?; - self.state.poll_waiting(&mut self.simulator) + self.state.poll_waiting(&mut self.simulator)?; + Ok(()) } /// Advance time and run until `end_time` (inclusive). As for From ed99110802ff376bebd068aa24f3ca96dcf1668b Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 07:17:53 +0900 Subject: [PATCH 05/75] fix(suite): settle timed cases without advancing time --- crates/celox-test-suite/README.md | 19 ++- crates/celox-test-suite/src/frontend.rs | 52 ++++++- crates/celox-test-suite/src/icarus.cpp | 19 +++ crates/celox-test-suite/src/lib.rs | 1 + crates/celox-test-suite/src/script/ast.rs | 30 ++++ crates/celox-test-suite/src/script/mod.rs | 8 +- crates/celox-test-suite/src/script/sv.rs | 130 +++++++++++------- crates/celox-test-suite/src/script/timed.rs | 110 +++++++++++++++ .../src/sv/cases/timing.vtest | 59 ++++++++ .../celox-test-suite/tests/timed_protocol.rs | 49 +++++++ crates/celox/src/simulation.rs | 3 +- .../tests/frontends/systemverilog/suite.rs | 18 ++- .../tests/frontends/systemverilog/timing.rs | 28 ++++ 13 files changed, 469 insertions(+), 57 deletions(-) create mode 100644 crates/celox-test-suite/src/script/timed.rs create mode 100644 crates/celox-test-suite/tests/timed_protocol.rs diff --git a/crates/celox-test-suite/README.md b/crates/celox-test-suite/README.md index c6c616e67a3..693b154d04c 100644 --- a/crates/celox-test-suite/README.md +++ b/crates/celox-test-suite/README.md @@ -250,12 +250,19 @@ error. A case whose design has processes with delays or event controls, or a clock it generates itself, advances time with `run_until` and `run_to_finish` and checks the design's output with `expect_output`. Design delays count time -units; the generated testbench for an external simulator sets a time scale of -1 ns with 1 ps precision and settles in 1 ps steps, so its checks after -`run_until` observe everything the design did at that time. Only checks may -follow `run_to_finish`; they run in a `final` block, which sees the script's -top-level bindings. A design that does not finish within the generated -testbench's guard fails `run_to_finish` instead of passing the checks. +units with the injected 1 ns / 1 ps scale. Explicit `timescale`, `timeunit` +and `timeprecision` declarations are rejected consistently by the Celox and +external adapters. `tick` cannot be mixed with timed operations. + +Reads, output collection and `eval` settle processes due at the current +timestamp without advancing time. External scripted adapters use an Icarus +read/write synchronization callback or a Verilator clocking event sampled in +the observed region. Initial blocks start after pre-run input writes settle. +`run_until` drains its target timestamp before subsequent writes. Only checks +may follow `run_to_finish`; they run in a `final` block that sees the script's +top-level bindings. There is no simulated-time deadline: final checks require +that the script reached the operation and that the design called `$finish`. +Event exhaustion before explicit completion fails the case. For an invalid design, write `(expect reject)` and no statements. `TestCase::expectation` lets consumers select these separately. For additional diff --git a/crates/celox-test-suite/src/frontend.rs b/crates/celox-test-suite/src/frontend.rs index a3ae73063eb..f375ebacad3 100644 --- a/crates/celox-test-suite/src/frontend.rs +++ b/crates/celox-test-suite/src/frontend.rs @@ -3,6 +3,8 @@ use crate::process::write_if_changed; use crate::script::ScriptCase; use crate::script::sv::{DesignInfo, TESTBENCH_TOP, testbench as generate_testbench}; +use crate::script::timed::{after_trivia, sv_words}; +use crate::validate_timed_design; use crate::verification::{EmissionError, panic_message}; use crate::{Design, Expectation, Result}; use std::collections::BTreeMap; @@ -13,7 +15,7 @@ use std::path::{Path, PathBuf}; const PARAMETERS_TOP: &str = "celox_suite_parameters"; /// The time scale every compiled source gets: a script time unit is 1 ns, -/// and the generated testbench settles in 1 ps steps between them. The +/// and the generated timed testbench settles without advancing time. The /// directive persists across the files that follow it in one compilation. const TIMESCALE: &str = "`timescale 1ns/1ps\n"; @@ -57,6 +59,7 @@ pub(crate) fn stage( directory: &Path, script: Option<&ScriptCase>, ) -> Result { + validate_timed_design(design)?; fs::create_dir_all(directory)?; let directory = fs::canonicalize(directory)?; for (index, source) in design.sources.iter().enumerate() { @@ -71,8 +74,18 @@ pub(crate) fn stage( let timescale = directory.join("timescale.sv"); write_if_changed(×cale, TIMESCALE.as_bytes())?; let mut paths = vec![timescale]; + if design.timed { + let control = directory.join("timed_control.sv"); + write_if_changed(&control, TIMED_CONTROL.as_bytes())?; + paths.push(control); + } for (index, source) in prepared.sources.iter().enumerate() { let path = directory.join(format!("source_{index}.sv")); + let source = if design.timed { + timed_source(source) + } else { + source.clone() + }; write_if_changed(&path, source.as_bytes())?; paths.push(path); } @@ -119,3 +132,40 @@ pub(crate) fn stage( edges: prepared.edges, }) } + +const TIMED_CONTROL: &str = r#"package celox_suite_timed_control; + bit started = 0; + bit finished = 0; + function automatic void celox_suite_start_design(); + started = 1; + endfunction + function automatic void celox_suite_finish_design(input int code = 1); + finished = 1; + case (code) + 0: $finish(0); + 2: $finish(2); + default: $finish(1); + endcase + endfunction +endpackage +"#; + +fn timed_source(source: &str) -> String { + let mut output = String::from("import celox_suite_timed_control::*;\n"); + let mut previous = 0; + for (start, end, word) in sv_words(source) { + let replacement = match word { + "initial" => "initial wait (celox_suite_timed_control::started)", + "$finish" if after_trivia(&source[end..]).starts_with('(') => { + "celox_suite_finish_design" + } + "$finish" => "celox_suite_finish_design()", + _ => continue, + }; + output.push_str(&source[previous..start]); + output.push_str(replacement); + previous = end; + } + output.push_str(&source[previous..]); + output +} diff --git a/crates/celox-test-suite/src/icarus.cpp b/crates/celox-test-suite/src/icarus.cpp index bf31a6b98e7..1da6b2521a7 100644 --- a/crates/celox-test-suite/src/icarus.cpp +++ b/crates/celox-test-suite/src/icarus.cpp @@ -129,7 +129,26 @@ static PLI_INT32 start(p_cb_data) { return commands(nullptr); } +static PLI_INT32 resume_settle(p_cb_data cb) { + s_vpi_value value{}; value.format = vpiIntVal; value.value.integer = 1; + vpi_put_value(reinterpret_cast(cb->user_data), &value, nullptr, vpiNoDelay); + return 0; +} +static PLI_INT32 request_settle(PLI_BYTE8*) { + vpiHandle call = vpi_handle(vpiSysTfCall, nullptr); + vpiHandle args = vpi_iterate(vpiArgument, call); + vpiHandle ready = vpi_scan(args); + s_vpi_time time{}; time.type = vpiSimTime; + s_cb_data cb{}; cb.reason = cbReadWriteSynch; cb.cb_rtn = resume_settle; + cb.time = &time; cb.user_data = reinterpret_cast(ready); + vpi_register_cb(&cb); + return 0; +} static void register_suite() { + s_vpi_systf_data settle{}; settle.type = vpiSysTask; + settle.tfname = const_cast("$celox_suite_settle"); settle.calltf = request_settle; + vpi_register_systf(&settle); + s_vpi_systf_data finish{}; finish.type = vpiSysTask; finish.tfname = const_cast("$celox_suite_finish"); diff --git a/crates/celox-test-suite/src/lib.rs b/crates/celox-test-suite/src/lib.rs index 0b34e6a34e8..4421718af97 100644 --- a/crates/celox-test-suite/src/lib.rs +++ b/crates/celox-test-suite/src/lib.rs @@ -25,6 +25,7 @@ pub use backend::{ pub use frontend::{Frontend, PreparedDesign}; pub use num_bigint::BigUint; pub use scalar::Scalar; +pub use script::validate_timed_design; /// Errors from a compiler or simulator adapter. Assertions fail by panicking, /// just like ordinary Rust tests; adapter errors are included in that failure. diff --git a/crates/celox-test-suite/src/script/ast.rs b/crates/celox-test-suite/src/script/ast.rs index 7991b9cb84c..d715bfcfb63 100644 --- a/crates/celox-test-suite/src/script/ast.rs +++ b/crates/celox-test-suite/src/script/ast.rs @@ -868,6 +868,18 @@ pub fn group(text: &str) -> Result<(String, Vec), ScriptError> { if case.expectation == Expectation::CompilationError && !case.body.is_empty() { return error(pos, "a rejected case has no statements"); } + if case.is_timed() { + let mut tick = false; + for stmt in &case.body { + stmt.walk(&mut |stmt| tick |= matches!(stmt.kind, StmtKind::Tick(..))); + } + if tick { + return error( + pos, + "tick cannot be combined with run_until or run_to_finish", + ); + } + } validate_finish(&case.body)?; parsed.push(case); } @@ -962,3 +974,21 @@ mod tests { assert_eq!(cases[1].expectation, Expectation::CompilationError); } } + +#[cfg(test)] +mod timing_mode_tests { + use super::*; + #[test] + fn mixed_tick_and_time_controls_are_rejected_even_in_nested_blocks() { + for body in [ + "(tick clk) (run_until 1)", + "(if 0 (tick clk)) (run_to_finish)", + ] { + let text = format!( + "(group mode (category sequential)) (case test (source \"test.sv\" \"module Top; endmodule\") (top Top) {body})" + ); + let error = group(&text).unwrap_err(); + assert!(error.message.contains("tick cannot be combined"), "{error}"); + } + } +} diff --git a/crates/celox-test-suite/src/script/mod.rs b/crates/celox-test-suite/src/script/mod.rs index f6a2143cc49..0d6cdf59012 100644 --- a/crates/celox-test-suite/src/script/mod.rs +++ b/crates/celox-test-suite/src/script/mod.rs @@ -29,8 +29,9 @@ //! //! A case with `run_until` or `run_to_finish` is timed: the design's own //! `initial` and `always` processes run, and a write takes effect at the -//! current time, so a process waiting for the signal resumes when time next -//! advances. `tick` is not available in a timed case. +//! current time. Reads, output collection and `eval` settle waiting and due +//! processes at that timestamp. `tick` cannot be mixed with timed operations; +//! timed shared sources use the injected scale and omit explicit time scales. //! //! A signal is `name` at the top or `inst.name`, `inst[2].name` below it. //! @@ -60,3 +61,6 @@ pub mod sexpr; pub mod sv; pub use ast::{ScriptCase, ScriptError}; + +pub(crate) mod timed; +pub use timed::validate_timed_design; diff --git a/crates/celox-test-suite/src/script/sv.rs b/crates/celox-test-suite/src/script/sv.rs index 3f0a4fb5151..b9a17602031 100644 --- a/crates/celox-test-suite/src/script/sv.rs +++ b/crates/celox-test-suite/src/script/sv.rs @@ -8,16 +8,13 @@ //! starts with `@suite assert` and ends the run with `$fatal`; success reaches //! `$finish` (after `$celox_suite_finish` under Icarus). //! -//! The timing follows the process adapters: a write takes effect at the next -//! settle, which advances time by one step; a tick drives the event port to -//! its inactive and then its active level, settling after each, and restores -//! a level that was neither. The testbench counts time in picoseconds while -//! the design's time unit is a nanosecond (see the staged time scale), so -//! the steps stay inside one script time unit: `run_until` reaches the -//! script's time exactly, and the settle before the next read runs after -//! everything the design does at that time. After `run_to_finish` the -//! testbench only keeps the simulation alive; the checks that follow run in -//! a `final` block, when the design has called `$finish`. +//! Untimed cases use one-step settling between driver operations. Timed +//! cases synchronize with the scheduler without advancing time: Icarus uses +//! a read/write callback and Verilator a clocking event in the observed +//! region. Their initial blocks start after pre-run inputs settle. +//! `run_until` drains its target timestamp before the next script operation. +//! After `run_to_finish`, read-only final checks require both reaching that +//! operation and explicit design completion; event exhaustion is a failure. use super::ast::{Actual, Expr, Op, RUN_UNTIL_LIMIT, ScriptCase, Sequence, Stmt, StmtKind, Value}; use super::sexpr::Pos; @@ -96,10 +93,6 @@ const OUTPUT_MARKER: &str = "@suite output "; /// the whole script has run. const END_MARKER: &str = "@suite end"; -/// Picoseconds after the script's last statement at which a design that -/// `run_to_finish` waits for is judged never to finish. -const RUN_TO_FINISH_GUARD: u64 = 1_000_000_000; - fn hex_encode(text: &str) -> String { text.bytes().map(|byte| format!("{byte:02x}")).collect() } @@ -119,12 +112,26 @@ fn is_finish_notice(line: &str) -> bool { { return located(location); } - if let Some((location, rest)) = line.split_once(": $finish called at ") { + if let Some((location, rest)) = icarus_finish_notice(line) { return located(location) && rest.ends_with(')'); } false } +fn icarus_finish_notice(line: &str) -> Option<(&str, &str)> { + let (location, rest) = line.split_once(": $finish")?; + let rest = if let Some(rest) = rest.strip_prefix('(') { + let (argument, rest) = rest.split_once(')')?; + if argument.parse::().ok()? > 2 { + return None; + } + rest + } else { + rest + }; + Some((location, rest.strip_prefix(" called at ")?)) +} + /// Whether `line` is a simulator's notice of a `$finish` in one of the /// simulation's source files `sources` (file names): a design may print a /// line of the same shape, which is its output. @@ -143,7 +150,7 @@ fn is_source_finish_notice(line: &str, sources: &[String]) -> bool { fn notice_file(line: &str) -> Option<&str> { let location = match line.strip_prefix("- ") { Some(rest) => rest.strip_suffix(": Verilog $finish")?, - None => line.split_once(": $finish called at ")?.0, + None => icarus_finish_notice(line)?.0, }; Some(location.rsplit_once(':')?.0) } @@ -896,6 +903,7 @@ impl Generator<'_> { self.settle_for(&[time]); let time = self.expr(time); self.require_known(&time, pos, "time"); + self.line("settle_now();"); // The time is scaled to picoseconds in a 64-bit time. self.line(format!( "if ({time} < 0 || {time} > {}'sd{RUN_UNTIL_LIMIT}) begin", @@ -908,8 +916,8 @@ impl Generator<'_> { let temp = self.temp(); self.line("begin"); self.indent += 1; - self.line(format!("longint {temp};")); - self.line(format!("{temp} = longint'({time}) * 1000;")); + self.line(format!("time {temp};")); + self.line(format!("{temp} = time'({time}) * 1000;")); // The settle steps stay inside the current time unit. self.line(format!("if ({temp} / 1000 < $time / 1000) begin")); self.indent += 1; @@ -921,7 +929,7 @@ impl Generator<'_> { self.indent -= 1; self.line("end"); self.line(format!("if ({temp} > $time) #({temp} - $time);")); - self.line("settled = 0;"); + self.line("settle_now();"); self.indent -= 1; self.line("end"); } @@ -973,22 +981,9 @@ pub fn testbench(case: &ScriptCase, design: &DesignInfo) -> Result Result Result { // The design ends the simulation; the checks run in its wake. out.push_str(" end\n\n final begin\n"); - out.push_str(" if (!suite_unfinished)\n"); + out.push_str( + " if (!suite_reached_finish || !celox_suite_timed_control::finished) begin\n", + ); + out.push_str(" $display(\"@suite assert run_to_finish was not reached or the design did not finish\");\n end else begin\n"); out.push_str(&checks); out.push_str(&end); - out.push_str(" end\nendmodule\n"); + out.push_str(" end\n end\nendmodule\n"); } None => { out.push_str(&end); out.push_str(" $finish;\n end\nendmodule\n"); } } + if case.is_timed() { + out = out.replace( + " timeprecision 1ps;", + " timeprecision 1ps;\n import celox_suite_timed_control::*;", + ); + out = out.replace( + " task automatic settle_now;\n #1;\n settled = 1;\n endtask", + r#" bit suite_progress = 0; +`ifndef CELOX_SUITE_ICARUS + clocking suite_settled @(suite_progress); + input #0 progress = suite_progress; + endclocking +`endif + task automatic settle_queues; +`ifdef CELOX_SUITE_ICARUS + suite_progress = 0; + $celox_suite_settle(suite_progress); + wait (suite_progress); +`else + suite_progress <= ~suite_progress; + @(suite_settled); +`endif + endtask + task automatic settle_now; + if (!celox_suite_timed_control::started) begin + settle_queues(); + celox_suite_start_design(); + end + settle_queues(); + settled = 1; + endtask"#, + ); + out = out.replace( + " initial begin\n", + " initial begin\n settle_queues();\n", + ); + } Ok(out) } @@ -1121,6 +1155,13 @@ mod tests { assert_eq!(design_output(icarus, &sources), "done\n"); let verilator = "done\n- /tmp/case/source_0.sv:19: Verilog $finish\n"; assert_eq!(design_output(verilator, &sources), "done\n"); + assert_eq!( + design_output( + "done\n/tmp/case/source_0.sv:17: $finish(1) called at 18000 (1ps)\n", + &sources + ), + "done\n" + ); assert_eq!( design_output("a: $finish called at x\n", &sources), "a: $finish called at x\n" @@ -1140,12 +1181,9 @@ mod tests { .unwrap(); assert!(text.contains(" logic signed [127:0] v_expected;\n")); assert!(text.contains("v_expected = t1;")); - assert!(text.contains("final begin\n if (!suite_unfinished)\n")); - // The design must finish: a late event fails the run instead of - // letting an exhausted event queue pass the final checks. - assert!(text.contains("#1000000000;\n")); - assert!(text.contains("suite_unfinished = 1;")); - assert!(text.contains("run_to_finish: the design did not finish the simulation")); + assert!(text.contains("final begin\n if (!suite_reached_finish || !celox_suite_timed_control::finished) begin\n")); + assert!(text.contains("suite_reached_finish = 1;")); + assert!(text.contains("run_to_finish was not reached or the design did not finish")); assert!(!text.contains("forever #")); } diff --git a/crates/celox-test-suite/src/script/timed.rs b/crates/celox-test-suite/src/script/timed.rs new file mode 100644 index 00000000000..412638fdabd --- /dev/null +++ b/crates/celox-test-suite/src/script/timed.rs @@ -0,0 +1,110 @@ +use crate::{Design, Result}; + +/// Raw scheduler units are portable only with the suite's injected scale. +/// Comments, strings and escaped identifiers are not declarations. +pub fn validate_timed_design(design: &Design) -> Result<()> { + if design.timed + && design.sources.iter().any(|source| { + sv_words(&source.text).iter().any(|(start, _, word)| { + matches!(*word, "timeunit" | "timeprecision") + || (*word == "timescale" && source.text[..*start].ends_with('`')) + }) + }) + { + return Err("explicit time scales are not supported in timed shared cases".into()); + } + Ok(()) +} + +pub(crate) fn sv_words(source: &str) -> Vec<(usize, usize, &str)> { + let bytes = source.as_bytes(); + let mut words = Vec::new(); + let mut at = 0; + while at < bytes.len() { + match bytes[at] { + b'/' if bytes.get(at + 1) == Some(&b'/') => { + at += 2; + while at < bytes.len() && bytes[at] != b'\n' { + at += 1; + } + } + b'/' if bytes.get(at + 1) == Some(&b'*') => { + at += 2; + while at + 1 < bytes.len() && &bytes[at..at + 2] != b"*/" { + at += 1; + } + at = (at + 2).min(bytes.len()); + } + b'"' => { + at += 1; + while at < bytes.len() { + match bytes[at] { + b'\\' => at = (at + 2).min(bytes.len()), + b'"' => { + at += 1; + break; + } + _ => at += 1, + } + } + } + b'\\' => { + at += 1; + while at < bytes.len() && !bytes[at].is_ascii_whitespace() { + at += 1; + } + } + b'a'..=b'z' | b'A'..=b'Z' | b'_' | b'$' => { + let start = at; + at += 1; + while at < bytes.len() + && (bytes[at].is_ascii_alphanumeric() || matches!(bytes[at], b'_' | b'$')) + { + at += 1; + } + words.push((start, at, &source[start..at])); + } + _ => at += 1, + } + } + words +} + +#[cfg(feature = "external")] +pub(crate) fn after_trivia(mut source: &str) -> &str { + loop { + source = source.trim_start(); + if source.starts_with("//") { + source = source.find('\n').map_or("", |at| &source[at + 1..]); + } else if source.starts_with("/*") { + source = source.find("*/").map_or("", |at| &source[at + 2..]); + } else { + return source; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn design(source: &str) -> Design { + let text = format!( + "(group timing (category sequential)) (case scale (source \"test.sv\" #\"{source}\"#) (top Top) (run_until 0))" + ); + crate::load_group("timing.vtest", &text, crate::no_std_library)[0].design() + } + + #[test] + fn explicit_scales_are_rejected_without_rejecting_literal_text() { + for source in [ + "`timescale 10ns/1ps\nmodule Top; endmodule", + "module Top; timeunit 10ns; endmodule", + "module Top; timeprecision 1fs; endmodule", + ] { + assert!(validate_timed_design(&design(source)).is_err()); + } + let source = "// `timescale 10ns/1ps\nmodule Top; bit timescale; initial $display(\"timeunit 10ns\"); endmodule"; + assert!(validate_timed_design(&design(source)).is_ok()); + } +} diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 19e4a0c7536..42b7b1fb651 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -339,3 +339,62 @@ (assert_eq y 2) (run_to_finish) (assert_eq y 3)) + +(case host_inputs_are_staged_before_time_zero_initial_blocks + (source "setup.sv" #"module Top(input bit a, output bit y); initial y = a; endmodule"#) + (top Top) + (set a 1) + (run_until 0) + (assert_eq y 1)) + +(case eval_starts_due_time_zero_processes + (source "eval.sv" #"module Top(output bit [7:0] y); initial y = 7; endmodule"#) + (top Top) + (eval) + (assert_eq y 7) + (run_until 0)) + +(case direct_reads_settle_waiting_processes + (source "read.sv" #"module Top(input bit go, output bit [7:0] seen); + initial begin wait (go); seen = 1; #0; seen = 2; end + endmodule"#) + (top Top) + (run_until 0) + (set go 1) + (assert_eq seen 2)) + +(case output_reads_settle_waiting_processes + (source "output.sv" #"module Top(input bit go); + initial begin wait (go); $display("woke"); end + endmodule"#) + (top Top) + (run_until 0) + (set go 1) + (expect_output "woke\n")) + +(case run_until_drains_target_time_before_later_writes + (source "boundary.sv" #"module Top(input bit [7:0] a, output bit [7:0] y); + initial #10 y = a; + endmodule"#) + (top Top) + (set a 1) + (run_until 10) + (set a 2) + (assert_eq y 1)) + +(case repeated_settles_do_not_advance_design_time + (source "settles.sv" #"module Top(output bit seen); initial #1 seen = 1; endmodule"#) + (top Top) + (run_until 0) + (for i (range 0 1001) (eval)) + (assert_eq seen 0) + (run_until 1) + (assert_eq seen 1)) + +(case run_to_finish_has_no_simulated_time_deadline + (source "late.sv" #"module Top(output bit done); + initial begin #1000001; done = 1; $finish; end + endmodule"#) + (top Top) + (run_to_finish) + (assert_eq done 1)) diff --git a/crates/celox-test-suite/tests/timed_protocol.rs b/crates/celox-test-suite/tests/timed_protocol.rs new file mode 100644 index 00000000000..f2326edfa8f --- /dev/null +++ b/crates/celox-test-suite/tests/timed_protocol.rs @@ -0,0 +1,49 @@ +#![cfg(all(feature = "icarus", feature = "verilator"))] + +use celox_test_suite::{Backend, load_group, no_std_library}; + +#[test] +#[ignore = "requires Icarus, Verilator and a C++ compiler"] +fn early_finish_and_event_exhaustion_do_not_skip_script_checks() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../target/timed-protocol") + .join(std::process::id().to_string()); + for (name, source, script) in [ + ( + "early", + "module Top(output bit done); initial #5 $finish; endmodule", + "(run_until 10) (assert_eq done 1) (run_to_finish)", + ), + ( + "idle", + "module Top(output bit done); initial done = 1; endmodule", + "(run_to_finish) (assert_eq done 1)", + ), + ] { + let text = format!( + "(group protocol (category sequential)) (case {name} (source \"test.sv\" #\"{source}\"#) (top Top) {script})" + ); + let case = load_group("protocol.vtest", &text, no_std_library)[0]; + let frontend = celox_test_suite::sv::verification::SvFrontend; + let mut icarus = celox_test_suite::icarus::Icarus::build_script( + &frontend, + case, + &root.join(name).join("icarus"), + ) + .unwrap(); + assert!(icarus.run_testbench().is_err(), "Icarus accepted {name}"); + let mut verilator = celox_test_suite::verilator::Verilator::build_script( + &frontend, + case, + &root.join(name).join("verilator"), + ) + .unwrap(); + let result = verilator.run_testbench(); + let log = std::fs::read_to_string(root.join(name).join("verilator/protocol.log")).unwrap(); + assert!( + result.is_err() || celox_test_suite::script::sv::check_output(&log, &[]).is_err(), + "Verilator accepted {name}" + ); + } + std::fs::remove_dir_all(root).unwrap(); +} diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index ecd6a3087c5..1d8d1cd9136 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -449,7 +449,8 @@ impl Simulation { /// advance. pub fn settle(&mut self) -> Result<(), RuntimeErrorCode> { self.simulator.eval_comb()?; - self.state.poll_waiting(&mut self.simulator)?; + let time = self.state.time(); + self.state.settle_at(&mut self.simulator, time)?; Ok(()) } diff --git a/crates/celox/tests/frontends/systemverilog/suite.rs b/crates/celox/tests/frontends/systemverilog/suite.rs index 233a3ad44be..99b1d4fb557 100644 --- a/crates/celox/tests/frontends/systemverilog/suite.rs +++ b/crates/celox/tests/frontends/systemverilog/suite.rs @@ -48,6 +48,7 @@ impl Backend for TimedBackend { } fn read(&mut self, path: &SignalPath) -> Result<(BigUint, BigUint)> { + self.0.settle()?; let signal = signal_of(&self.0, path); Ok(self.0.get_four_state(signal)) } @@ -63,6 +64,7 @@ impl Backend for TimedBackend { } fn take_output(&mut self) -> Result { + self.0.settle()?; collect_output(self.0.drain_runtime_events()) } @@ -83,7 +85,7 @@ impl Backend for TimedBackend { } fn run_to_finish(&mut self) -> Result<()> { - self.0.run_until(u64::MAX - 1)?; + while !self.0.is_finished() && self.0.step()?.is_some() {} if !self.0.is_finished() { return Err( "run_to_finish: the simulation ran out of events before a process finished it" @@ -134,6 +136,7 @@ impl Backend for CeloxBackend { } fn build(design: &Design, backend: &str) -> Result> { + celox_test_suite::validate_timed_design(design)?; let sources = design .sources .iter() @@ -220,3 +223,16 @@ pub fn run_case(name: &'static str, backend: &'static str) { .unwrap_or_else(|panic| std::panic::resume_unwind(panic)); }); } + +#[test] +fn run_to_finish_reaches_the_last_scheduler_timestamp() { + let source = "module Top(output bit done); initial begin #(64'hffffffffffffffff); done = 1; $finish; end endmodule"; + let simulation = + celox::Simulation::from_sv_sources(vec![(source, std::path::Path::new("last.sv"))], "Top") + .build() + .unwrap(); + let mut backend = TimedBackend(simulation); + backend.run_to_finish().unwrap(); + assert_eq!(backend.0.time(), u64::MAX); + assert_eq!(backend.0.get(backend.0.signal("done")), 1u8.into()); +} diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 6ba7c955e05..fe3b192aee8 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -53,4 +53,32 @@ sv_backends! { fn unknown_delays_and_conditions_count_as_zero_and_false(sim) { @case "timing::unknown_delays_and_conditions_count_as_zero_and_false"; } + + fn host_inputs_are_staged_before_time_zero_initial_blocks(sim) { + @case "timing::host_inputs_are_staged_before_time_zero_initial_blocks"; + } + + fn eval_starts_due_time_zero_processes(sim) { + @case "timing::eval_starts_due_time_zero_processes"; + } + + fn direct_reads_settle_waiting_processes(sim) { + @case "timing::direct_reads_settle_waiting_processes"; + } + + fn output_reads_settle_waiting_processes(sim) { + @case "timing::output_reads_settle_waiting_processes"; + } + + fn run_until_drains_target_time_before_later_writes(sim) { + @case "timing::run_until_drains_target_time_before_later_writes"; + } + + fn repeated_settles_do_not_advance_design_time(sim) { + @case "timing::repeated_settles_do_not_advance_design_time"; + } + + fn run_to_finish_has_no_simulated_time_deadline(sim) { + @case "timing::run_to_finish_has_no_simulated_time_deadline"; + } } From 10b39919c3e407106c3256471c308c7e874e65d2 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 08:12:37 +0900 Subject: [PATCH 06/75] fix(suite): stage always processes and avoid control-name collisions --- crates/celox-test-suite/README.md | 5 +- crates/celox-test-suite/src/frontend.rs | 86 ++++++++++++++++--- crates/celox-test-suite/src/script/timed.rs | 8 +- .../src/sv/cases/timing.vtest | 17 ++++ .../tests/frontends/systemverilog/timing.rs | 9 ++ 5 files changed, 111 insertions(+), 14 deletions(-) diff --git a/crates/celox-test-suite/README.md b/crates/celox-test-suite/README.md index 693b154d04c..3c0da4d0309 100644 --- a/crates/celox-test-suite/README.md +++ b/crates/celox-test-suite/README.md @@ -251,13 +251,14 @@ A case whose design has processes with delays or event controls, or a clock it generates itself, advances time with `run_until` and `run_to_finish` and checks the design's output with `expect_output`. Design delays count time units with the injected 1 ns / 1 ps scale. Explicit `timescale`, `timeunit` -and `timeprecision` declarations are rejected consistently by the Celox and +and `timeprecision` declarations, and `resetall`, are rejected consistently by the Celox and external adapters. `tick` cannot be mixed with timed operations. Reads, output collection and `eval` settle processes due at the current timestamp without advancing time. External scripted adapters use an Icarus read/write synchronization callback or a Verilator clocking event sampled in -the observed region. Initial blocks start after pre-run input writes settle. +the observed region. Initial blocks and plain time-zero `always` processes start after pre-run input +writes settle. Internal control names are chosen to avoid source identifiers. `run_until` drains its target timestamp before subsequent writes. Only checks may follow `run_to_finish`; they run in a `final` block that sees the script's top-level bindings. There is no simulated-time deadline: final checks require diff --git a/crates/celox-test-suite/src/frontend.rs b/crates/celox-test-suite/src/frontend.rs index f375ebacad3..d2a014c9358 100644 --- a/crates/celox-test-suite/src/frontend.rs +++ b/crates/celox-test-suite/src/frontend.rs @@ -71,18 +71,19 @@ pub(crate) fn stage( let prepared = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| frontend.prepare(design))) .map_err(|error| EmissionError(panic_message(error.as_ref())))??; + let control_names = timed_names(&prepared.sources); let timescale = directory.join("timescale.sv"); write_if_changed(×cale, TIMESCALE.as_bytes())?; let mut paths = vec![timescale]; if design.timed { let control = directory.join("timed_control.sv"); - write_if_changed(&control, TIMED_CONTROL.as_bytes())?; + write_if_changed(&control, control_names.generated(TIMED_CONTROL).as_bytes())?; paths.push(control); } for (index, source) in prepared.sources.iter().enumerate() { let path = directory.join(format!("source_{index}.sv")); let source = if design.timed { - timed_source(source) + timed_source(source, &control_names) } else { source.clone() }; @@ -119,7 +120,13 @@ pub(crate) fn stage( .as_ref() .ok_or("the frontend gives no port information for a generated testbench")?; let path = directory.join("testbench.sv"); - write_if_changed(&path, generate_testbench(case, info)?.as_bytes())?; + let bench = generate_testbench(case, info)?; + let bench = if design.timed { + control_names.generated(&bench) + } else { + bench + }; + write_if_changed(&path, bench.as_bytes())?; paths.push(path); top = TESTBENCH_TOP.to_string(); testbench = true; @@ -150,20 +157,79 @@ const TIMED_CONTROL: &str = r#"package celox_suite_timed_control; endpackage "#; -fn timed_source(source: &str) -> String { - let mut output = String::from("import celox_suite_timed_control::*;\n"); +struct TimedNames { + package: String, + start: String, + finish: String, +} + +fn timed_names(sources: &[String]) -> TimedNames { + let words = sources + .iter() + .flat_map(|source| sv_words(source).into_iter().map(|(_, _, word)| word)) + .collect::>(); + for suffix in 0u64.. { + let name = |base: &str| { + if suffix == 0 { + base.to_string() + } else { + format!("{base}_{suffix}") + } + }; + let names = TimedNames { + package: name("celox_suite_timed_control"), + start: name("celox_suite_start_design"), + finish: name("celox_suite_finish_design"), + }; + if [&names.package, &names.start, &names.finish] + .into_iter() + .all(|name| !words.contains(name.as_str())) + { + return names; + } + } + unreachable!() +} +impl TimedNames { + fn generated(&self, source: &str) -> String { + let mut output = String::new(); + let mut previous = 0; + for (start, end, word) in sv_words(source) { + // Generated package references and unqualified helper calls; leave + // source signal paths (dut.name) and quoted script text intact. + if source[..start].trim_end().ends_with('.') { + continue; + } + let replacement = match word { + "celox_suite_timed_control" => &self.package, + "celox_suite_start_design" => &self.start, + "celox_suite_finish_design" => &self.finish, + _ => continue, + }; + output.push_str(&source[previous..start]); + output.push_str(replacement); + previous = end; + } + output.push_str(&source[previous..]); + output + } +} + +fn timed_source(source: &str, names: &TimedNames) -> String { + let mut output = format!("import {}::*;\n", names.package); let mut previous = 0; for (start, end, word) in sv_words(source) { let replacement = match word { - "initial" => "initial wait (celox_suite_timed_control::started)", - "$finish" if after_trivia(&source[end..]).starts_with('(') => { - "celox_suite_finish_design" + "initial" => format!("initial wait ({}::started)", names.package), + "always" if !after_trivia(&source[end..]).starts_with('@') => { + format!("always wait ({}::started)", names.package) } - "$finish" => "celox_suite_finish_design()", + "$finish" if after_trivia(&source[end..]).starts_with('(') => names.finish.clone(), + "$finish" => format!("{}()", names.finish), _ => continue, }; output.push_str(&source[previous..start]); - output.push_str(replacement); + output.push_str(&replacement); previous = end; } output.push_str(&source[previous..]); diff --git a/crates/celox-test-suite/src/script/timed.rs b/crates/celox-test-suite/src/script/timed.rs index 412638fdabd..502ac839223 100644 --- a/crates/celox-test-suite/src/script/timed.rs +++ b/crates/celox-test-suite/src/script/timed.rs @@ -7,11 +7,14 @@ pub fn validate_timed_design(design: &Design) -> Result<()> { && design.sources.iter().any(|source| { sv_words(&source.text).iter().any(|(start, _, word)| { matches!(*word, "timeunit" | "timeprecision") - || (*word == "timescale" && source.text[..*start].ends_with('`')) + || (matches!(*word, "timescale" | "resetall") + && source.text[..*start].ends_with('`')) }) }) { - return Err("explicit time scales are not supported in timed shared cases".into()); + return Err( + "explicit time scales and resetall are not supported in timed shared cases".into(), + ); } Ok(()) } @@ -99,6 +102,7 @@ mod tests { fn explicit_scales_are_rejected_without_rejecting_literal_text() { for source in [ "`timescale 10ns/1ps\nmodule Top; endmodule", + "`resetall\nmodule Top; endmodule", "module Top; timeunit 10ns; endmodule", "module Top; timeprecision 1fs; endmodule", ] { diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 42b7b1fb651..c3fb00fabe6 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -398,3 +398,20 @@ (top Top) (run_to_finish) (assert_eq done 1)) + +(case plain_always_processes_start_after_host_inputs + (source "always.sv" #"module Top(input bit a, output bit y); always begin y=a; #1; end endmodule"#) + (top Top) + (set a 1) + (run_until 0) + (assert_eq y 1)) + +(case timed_control_names_do_not_collide_with_design_names + (source "names.sv" #"package celox_suite_timed_control; localparam int N=1; endpackage + module Top(output bit done); + function void celox_suite_finish_design(); done=0; endfunction + initial begin #1; done=1; $finish; end + endmodule"#) + (top Top) + (run_to_finish) + (assert_eq done 1)) diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index fe3b192aee8..c61c9298861 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -82,3 +82,12 @@ sv_backends! { @case "timing::run_to_finish_has_no_simulated_time_deadline"; } } + +sv_backends! { + fn plain_always_processes_start_after_host_inputs(sim) { + @case "timing::plain_always_processes_start_after_host_inputs"; + } + fn timed_control_names_do_not_collide_with_design_names(sim) { + @case "timing::timed_control_names_do_not_collide_with_design_names"; + } +} From 9f699568690a06763b92522647ec7470fc54e7f1 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 09:04:18 +0900 Subject: [PATCH 07/75] fix(suite): gate event processes and reject finishes before completion runs --- crates/celox-test-suite/README.md | 10 +++-- crates/celox-test-suite/src/frontend.rs | 2 +- crates/celox-test-suite/src/script/sv.rs | 4 ++ .../src/sv/cases/timing.vtest | 11 +++++ .../celox-test-suite/tests/timed_protocol.rs | 5 +++ .../tests/frontends/systemverilog/suite.rs | 41 +++++++++++++++++++ .../tests/frontends/systemverilog/timing.rs | 6 +++ 7 files changed, 74 insertions(+), 5 deletions(-) diff --git a/crates/celox-test-suite/README.md b/crates/celox-test-suite/README.md index 3c0da4d0309..0a64042c60f 100644 --- a/crates/celox-test-suite/README.md +++ b/crates/celox-test-suite/README.md @@ -93,8 +93,9 @@ behavioral model and verifies that incorrect results are rejected. - A design with `Design::timed` is driven by `run_until` and `run_to_finish` instead of `tick`: the simulator runs the design's own processes, delays and clocks. `run_until` advances to the given time in the design's time - units and fails when the design has finished by then; `run_to_finish` runs - until a process calls `$finish` and fails when the events run out first. A + units and fails when the design has finished by then; `run_to_finish` rejects + an already-finished design, runs until a process calls `$finish`, and fails + when the events run out first. A `write` in a timed case takes effect at the current time, and `eval_comb` also resumes the processes it woke, as a simulator's settle step does. A time later than `RUN_UNTIL_LIMIT` (`i64::MAX / 1000`) is out of range in @@ -257,8 +258,9 @@ external adapters. `tick` cannot be mixed with timed operations. Reads, output collection and `eval` settle processes due at the current timestamp without advancing time. External scripted adapters use an Icarus read/write synchronization callback or a Verilator clocking event sampled in -the observed region. Initial blocks and plain time-zero `always` processes start after pre-run input -writes settle. Internal control names are chosen to avoid source identifiers. +the observed region. Initial blocks and all `always` processes start after +pre-run input writes settle. Internal control names are chosen to avoid source +identifiers. `run_until` drains its target timestamp before subsequent writes. Only checks may follow `run_to_finish`; they run in a `final` block that sees the script's top-level bindings. There is no simulated-time deadline: final checks require diff --git a/crates/celox-test-suite/src/frontend.rs b/crates/celox-test-suite/src/frontend.rs index d2a014c9358..5c85a10312e 100644 --- a/crates/celox-test-suite/src/frontend.rs +++ b/crates/celox-test-suite/src/frontend.rs @@ -221,7 +221,7 @@ fn timed_source(source: &str, names: &TimedNames) -> String { for (start, end, word) in sv_words(source) { let replacement = match word { "initial" => format!("initial wait ({}::started)", names.package), - "always" if !after_trivia(&source[end..]).starts_with('@') => { + "always" => { format!("always wait ({}::started)", names.package) } "$finish" if after_trivia(&source[end..]).starts_with('(') => names.finish.clone(), diff --git a/crates/celox-test-suite/src/script/sv.rs b/crates/celox-test-suite/src/script/sv.rs index b9a17602031..e08e35a816b 100644 --- a/crates/celox-test-suite/src/script/sv.rs +++ b/crates/celox-test-suite/src/script/sv.rs @@ -981,6 +981,10 @@ pub fn testbench(case: &ScriptCase, design: &DesignInfo) -> Result Backend for TimedBackend { } fn run_to_finish(&mut self) -> Result<()> { + if self.0.is_finished() { + return Err( + "run_to_finish: the design already finished before the operation began".into(), + ); + } while !self.0.is_finished() && self.0.step()?.is_some() {} if !self.0.is_finished() { return Err( @@ -236,3 +241,39 @@ fn run_to_finish_reaches_the_last_scheduler_timestamp() { assert_eq!(backend.0.time(), u64::MAX); assert_eq!(backend.0.get(backend.0.signal("done")), 1u8.into()); } + +#[test] +fn run_to_finish_rejects_a_finish_during_an_earlier_settle() { + for operation in 0..3 { + let source = "module Top(input bit go, output bit done); initial begin wait(go); done=1; $finish; end endmodule"; + let simulation = + Simulation::from_sv_sources(vec![(source, std::path::Path::new("early.sv"))], "Top") + .build() + .unwrap(); + let mut backend = TimedBackend(simulation); + backend.run_until(0).unwrap(); + let go = backend.0.signal("go"); + backend.0.set_wide(go, 1u8.into()); + match operation { + 0 => backend.eval_comb().unwrap(), + 1 => { + backend + .read(&SignalPath { + instances: Vec::new(), + name: "done".into(), + }) + .unwrap(); + } + _ => { + backend.take_output().unwrap(); + } + } + assert!( + backend + .run_to_finish() + .unwrap_err() + .to_string() + .contains("already finished") + ); + } +} diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index c61c9298861..1a7b146d184 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -91,3 +91,9 @@ sv_backends! { @case "timing::timed_control_names_do_not_collide_with_design_names"; } } + +sv_backends! { + fn event_always_processes_start_after_host_inputs(sim) { + @case "timing::event_always_processes_start_after_host_inputs"; + } +} From c2ba17fed0cf7168e8776f7614f7b68db9d325ca Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 10:43:57 +0900 Subject: [PATCH 08/75] fix(suite): defer startup FF actions while retaining setup edges --- crates/celox-test-suite/README.md | 3 +- crates/celox-test-suite/src/frontend.rs | 28 ++- .../celox-test-suite/src/frontend/timed_ff.rs | 166 ++++++++++++++++++ .../src/sv/cases/timing.vtest | 46 +++++ .../tests/frontends/systemverilog/timing.rs | 15 ++ 5 files changed, 253 insertions(+), 5 deletions(-) create mode 100644 crates/celox-test-suite/src/frontend/timed_ff.rs diff --git a/crates/celox-test-suite/README.md b/crates/celox-test-suite/README.md index 0a64042c60f..bf63e5a6607 100644 --- a/crates/celox-test-suite/README.md +++ b/crates/celox-test-suite/README.md @@ -259,7 +259,8 @@ Reads, output collection and `eval` settle processes due at the current timestamp without advancing time. External scripted adapters use an Icarus read/write synchronization callback or a Verilator clocking event sampled in the observed region. Initial blocks and all `always` processes start after -pre-run input writes settle. Internal control names are chosen to avoid source +pre-run input writes settle. `always_ff` listeners retain setup edges and defer +their actions until startup, preserving initial reads before queued NBAs. Internal control names are chosen to avoid source identifiers. `run_until` drains its target timestamp before subsequent writes. Only checks may follow `run_to_finish`; they run in a `final` block that sees the script's diff --git a/crates/celox-test-suite/src/frontend.rs b/crates/celox-test-suite/src/frontend.rs index 5c85a10312e..cc507fb729a 100644 --- a/crates/celox-test-suite/src/frontend.rs +++ b/crates/celox-test-suite/src/frontend.rs @@ -1,5 +1,7 @@ //! What a suite supplies to build its designs with an external simulator. +mod timed_ff; + use crate::process::write_if_changed; use crate::script::ScriptCase; use crate::script::sv::{DesignInfo, TESTBENCH_TOP, testbench as generate_testbench}; @@ -83,7 +85,7 @@ pub(crate) fn stage( for (index, source) in prepared.sources.iter().enumerate() { let path = directory.join(format!("source_{index}.sv")); let source = if design.timed { - timed_source(source, &control_names) + timed_source(source, &control_names)? } else { source.clone() }; @@ -215,10 +217,28 @@ impl TimedNames { } } -fn timed_source(source: &str, names: &TimedNames) -> String { - let mut output = format!("import {}::*;\n", names.package); +fn timed_source(source: &str, names: &TimedNames) -> Result { + Ok(format!( + "import {}::*;\n{}", + names.package, + timed_content(source, names)? + )) +} + +fn timed_content(source: &str, names: &TimedNames) -> Result { + let mut output = String::new(); let mut previous = 0; for (start, end, word) in sv_words(source) { + if start < previous { + continue; + } + if word == "always_ff" { + let (body_end, replacement) = timed_ff::gated(source, start, end, names)?; + output.push_str(&source[previous..start]); + output.push_str(&replacement); + previous = body_end; + continue; + } let replacement = match word { "initial" => format!("initial wait ({}::started)", names.package), "always" => { @@ -233,5 +253,5 @@ fn timed_source(source: &str, names: &TimedNames) -> String { previous = end; } output.push_str(&source[previous..]); - output + Ok(output) } diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs new file mode 100644 index 00000000000..5e604759a21 --- /dev/null +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -0,0 +1,166 @@ +//! Keep FF listeners armed during setup, deferring their actions until startup. +use super::*; + +fn trivia(source: &str, at: usize) -> usize { + source.len() - after_trivia(&source[at..]).len() +} +fn skip_token(source: &str, at: &mut usize) -> bool { + let bytes = source.as_bytes(); + if bytes.get(*at..*at + 2) == Some(b"//") { + *at = source[*at..] + .find('\n') + .map_or(bytes.len(), |end| *at + end); + } else if bytes.get(*at..*at + 2) == Some(b"/*") { + *at = source[*at + 2..] + .find("*/") + .map_or(bytes.len(), |end| *at + end + 4); + } else if bytes.get(*at) == Some(&b'"') { + *at += 1; + while *at < bytes.len() { + match bytes[*at] { + b'\\' => *at = (*at + 2).min(bytes.len()), + b'"' => { + *at += 1; + break; + } + _ => *at += 1, + } + } + } else if bytes.get(*at) == Some(&b'\\') { + while *at < bytes.len() && !bytes[*at].is_ascii_whitespace() { + *at += 1; + } + } else { + return false; + } + true +} +fn parens(source: &str, begin: usize) -> Option { + if source.as_bytes().get(begin) != Some(&b'(') { + return None; + } + let mut at = begin; + let mut depth = 0; + while at < source.len() { + if skip_token(source, &mut at) { + continue; + } + match source.as_bytes()[at] { + b'(' => depth += 1, + b')' => { + depth -= 1; + if depth == 0 { + return Some(at + 1); + } + } + _ => {} + } + at += 1; + } + None +} +fn statement_end(source: &str, at: usize) -> Option { + let at = trivia(source, at); + if source[at..].starts_with("(*") { + return statement_end(source, parens(source, at)?); + } + let words = sv_words(&source[at..]); + let keyword = words.first().filter(|word| word.0 == 0).map(|word| word.2); + match keyword { + Some("begin" | "case" | "casez" | "casex") => { + let is_block = keyword == Some("begin"); + let mut depth = 0; + for (_, end, word) in &words { + if (is_block && *word == "begin") + || (!is_block && matches!(*word, "case" | "casez" | "casex")) + { + depth += 1; + } + if (is_block && *word == "end") || (!is_block && *word == "endcase") { + depth -= 1; + if depth == 0 { + let end = at + end; + let label = trivia(source, end); + if source.as_bytes().get(label) == Some(&b':') { + let start = trivia(source, label + 1); + let name = sv_words(&source[start..]).first().copied()?; + return Some(start + name.1); + } + return Some(end); + } + } + } + None + } + Some("if" | "for" | "foreach" | "while" | "repeat") => { + let word = words.first()?; + let end = parens(source, trivia(source, at + word.1))?; + let body = statement_end(source, end)?; + let next = trivia(source, body); + if keyword == Some("if") && source[next..].starts_with("else") { + statement_end(source, next + 4) + } else { + Some(body) + } + } + Some("forever") => statement_end(source, at + words.first()?.1), + _ => { + let mut cursor = at; + let mut depth = 0; + while cursor < source.len() { + if skip_token(source, &mut cursor) { + continue; + } + match source.as_bytes()[cursor] { + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' => depth -= 1, + b';' if depth == 0 => return Some(cursor + 1), + _ => {} + } + cursor += 1; + } + None + } + } +} + +pub(super) fn gated( + source: &str, + start: usize, + end: usize, + names: &TimedNames, +) -> Result<(usize, String)> { + let at = trivia(source, end); + if source.as_bytes().get(at) != Some(&b'@') { + return Err("timed always_ff requires an explicit event control".into()); + } + let begin = trivia(source, at + 1); + let event_end = parens(source, begin).ok_or("unsupported timed always_ff event control")?; + let body_start = trivia(source, event_end); + let body_end = + statement_end(source, body_start).ok_or("unsupported timed always_ff statement")?; + let body = timed_content(&source[body_start..body_end], names)?; + let identifiers = sv_words(source) + .into_iter() + .map(|word| word.2) + .collect::>(); + let fresh = |kind: &str| { + for suffix in 0.. { + let name = format!("celox_suite_ff_{kind}_{start}_{suffix}"); + if !identifiers.contains(name.as_str()) { + return name; + } + } + unreachable!() + }; + let armed = fresh("armed"); + let pending = fresh("pending"); + let package = &names.package; + let event = &source[begin + 1..event_end - 1]; + Ok(( + body_end, + format!( + "always @({event} or posedge {package}::started) begin\n bit {armed}=0;\n bit {pending}=0;\n if (!{package}::started) {pending}=1;\n else if ({armed} || {pending}) begin\n {pending}=0;\n {body}\n end\n {armed}={package}::started;\nend" + ), + )) +} diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index e6b240d3157..cb9a8639d28 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -426,3 +426,49 @@ (set a 1) (run_until 0) (assert_eq y 0)) + +(case ff_actions_wait_for_staged_startup + (source "ff_start.sv" #"module Top(input bit clk, output bit y, output bit seen); + always_ff @(posedge clk) seen<=1; + initial y=seen; + endmodule"#) + (top Top) + (set clk 1) + (run_until 0) + (assert_eq y 0) + (assert_eq seen 1)) + +(case ff_startup_does_not_invent_an_unstaged_edge + (source "ff_idle.sv" #"module Top(input bit clk, output bit seen); + always_ff @(posedge clk) begin if (clk) seen<=1; end + endmodule"#) + (top Top) + (set clk 0) + (run_until 0) + (assert_eq seen 0) + (set clk 1) + (run_until 0) + (assert_eq seen 1)) + +(case ff_startup_preserves_nested_if_case_actions + (source "ff_nested.sv" #"module Top(input bit clk, en, output bit [7:0] seen, output bit flag, y); + always_ff @(posedge clk) if (en) begin : update + seen<=seen+1; + case(en) 1: flag<=1; default: flag<=0; endcase + end else begin seen<=0; flag<=0; end + initial y=flag; + endmodule"#) + (top Top) + (set en 1) + (set clk 1) + (run_until 0) + (assert_eq y 0) + (assert_eq seen 1) + (assert_eq flag 1) + (set en 0) + (set clk 0) + (eval) + (set clk 1) + (run_until 0) + (assert_eq seen 0) + (assert_eq flag 0)) diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 1a7b146d184..7f4b370acad 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -97,3 +97,18 @@ sv_backends! { @case "timing::event_always_processes_start_after_host_inputs"; } } + +sv_backends! { + fn ff_actions_wait_for_staged_startup(sim) { + @case "timing::ff_actions_wait_for_staged_startup"; + } + fn ff_startup_does_not_invent_an_unstaged_edge(sim) { + @case "timing::ff_startup_does_not_invent_an_unstaged_edge"; + } +} + +sv_backends! { + fn ff_startup_preserves_nested_if_case_actions(sim) { + @case "timing::ff_startup_preserves_nested_if_case_actions"; + } +} From 6517cb2c2d7ced496842fd92b56524525103ab14 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 11:04:15 +0900 Subject: [PATCH 09/75] fix(suite): stage edge-only always and preserve qualified macro bodies --- crates/celox-test-suite/src/frontend.rs | 4 +- .../celox-test-suite/src/frontend/timed_ff.rs | 71 +++++++++++++++++++ .../src/sv/cases/timing.vtest | 25 +++++++ .../celox-test-suite/tests/timed_protocol.rs | 21 ++++++ .../tests/frontends/systemverilog/timing.rs | 6 ++ 5 files changed, 125 insertions(+), 2 deletions(-) diff --git a/crates/celox-test-suite/src/frontend.rs b/crates/celox-test-suite/src/frontend.rs index cc507fb729a..2ef1f23f26e 100644 --- a/crates/celox-test-suite/src/frontend.rs +++ b/crates/celox-test-suite/src/frontend.rs @@ -232,10 +232,10 @@ fn timed_content(source: &str, names: &TimedNames) -> Result { if start < previous { continue; } - if word == "always_ff" { + if word == "always_ff" || (word == "always" && timed_ff::edge_control(source, end)) { let (body_end, replacement) = timed_ff::gated(source, start, end, names)?; output.push_str(&source[previous..start]); - output.push_str(&replacement); + output.push_str(&timed_ff::in_macro(source, start, replacement)); previous = body_end; continue; } diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index 5e604759a21..d0d9db85ff9 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -67,6 +67,7 @@ fn statement_end(source: &str, at: usize) -> Option { let words = sv_words(&source[at..]); let keyword = words.first().filter(|word| word.0 == 0).map(|word| word.2); match keyword { + Some("unique" | "unique0" | "priority") => statement_end(source, at + words.first()?.1), Some("begin" | "case" | "casez" | "casex") => { let is_block = keyword == Some("begin"); let mut depth = 0; @@ -164,3 +165,73 @@ pub(super) fn gated( ), )) } + +/// The frontend classifies an ordinary always as FF only when every leaf +/// of its event list is explicitly edge-qualified. +pub(super) fn edge_control(source: &str, end: usize) -> bool { + let at = trivia(source, end); + if source.as_bytes().get(at) != Some(&b'@') { + return false; + } + let begin = trivia(source, at + 1); + let Some(end) = parens(source, begin) else { + return false; + }; + let event = &source[begin + 1..end - 1]; + let ors = sv_words(event) + .into_iter() + .filter_map(|(start, _, word)| (word == "or").then_some(start)) + .collect::>(); + let mut at = 0; + let mut start = 0; + let mut depth = 0; + let mut leaves = Vec::new(); + while at < event.len() { + if skip_token(event, &mut at) { + continue; + } + if depth == 0 && (event.as_bytes()[at] == b',' || ors.contains(&at)) { + leaves.push(&event[start..at]); + at += if ors.contains(&at) { 2 } else { 1 }; + start = at; + continue; + } + match event.as_bytes()[at] { + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' => depth -= 1, + _ => {} + } + at += 1; + } + leaves.push(&event[start..]); + leaves.into_iter().all(|leaf| { + let leaf = after_trivia(leaf); + matches!(sv_words(leaf).first(), Some((0, _, "posedge" | "negedge"))) + }) +} + +/// Multiline macro replacements must keep every generated line in the +/// original definition. Existing continuation lines already have a slash. +pub(super) fn in_macro(source: &str, start: usize, replacement: String) -> String { + let lines = source[..start].split('\n').collect::>(); + let mut first = lines.len() - 1; + while first > 0 && lines[first - 1].trim_end().ends_with('\\') { + first -= 1; + } + if !lines[first].trim_start().starts_with("`define") { + return replacement; + } + let mut output = String::new(); + for line in replacement.split_inclusive('\n') { + if let Some(content) = line.strip_suffix('\n') { + output.push_str(content); + if !content.trim_end().ends_with('\\') { + output.push_str(" \\"); + } + output.push('\n'); + } else { + output.push_str(line); + } + } + output +} diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index cb9a8639d28..49a1babb50f 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -472,3 +472,28 @@ (run_until 0) (assert_eq seen 0) (assert_eq flag 0)) + +(case qualified_ff_startup_actions + (source "qualified.sv" #"module Top(input bit clk, en, output bit q, y); + always_ff @(posedge clk) priority case(en) 1: q<=1; default: q<=0; endcase + initial y=q; + endmodule"#) + (top Top) (set en 1) (set clk 1) (run_until 0) + (assert_eq y 0) (assert_eq q 1)) + +(case ordinary_edge_always_retains_staged_startup_edges + (source "ordinary.sv" #"module Top(input bit clk, output bit q, y); + always @(posedge clk) q<=1; + initial y=q; + endmodule"#) + (top Top) (set clk 1) (run_until 0) + (assert_eq y 0) (assert_eq q 1)) + +(case macro_ff_startup_actions + (source "macro.sv" #"`define FF always_ff @(posedge clk) q<=1; + module Top(input bit clk, output bit q, y); + `FF + initial y=q; + endmodule"#) + (top Top) (set clk 1) (run_until 0) + (assert_eq y 0) (assert_eq q 1)) diff --git a/crates/celox-test-suite/tests/timed_protocol.rs b/crates/celox-test-suite/tests/timed_protocol.rs index 48a9ba4185d..d225b4f4174 100644 --- a/crates/celox-test-suite/tests/timed_protocol.rs +++ b/crates/celox-test-suite/tests/timed_protocol.rs @@ -52,3 +52,24 @@ fn early_finish_and_event_exhaustion_do_not_skip_script_checks() { } std::fs::remove_dir_all(root).unwrap(); } + +#[test] +#[ignore = "requires Verilator and a C++ compiler; Icarus rejects unique-if syntax"] +fn qualified_ff_if_actions_are_not_truncated_during_staging() { + let text = r##"(group qualified (category sequential)) + (case startup (source "qualified.sv" #"module Top(input bit clk, en, output bit q, y); + always_ff @(posedge clk) unique if(en) q<=1; else q<=0; + initial y=q; + endmodule"#) (top Top) (set en 1) (set clk 1) (run_until 0) (assert_eq y 0) (assert_eq q 1))"##; + let case = load_group("qualified.vtest", text, no_std_library)[0]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../target/qualified-ff-protocol") + .join(std::process::id().to_string()); + let frontend = celox_test_suite::sv::verification::SvFrontend; + let mut backend = + celox_test_suite::verilator::Verilator::build_script(&frontend, case, &root).unwrap(); + backend.run_testbench().unwrap(); + let log = std::fs::read_to_string(root.join("protocol.log")).unwrap(); + celox_test_suite::script::sv::check_output(&log, &[]).unwrap(); + std::fs::remove_dir_all(root).unwrap(); +} diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 7f4b370acad..78361930df9 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -112,3 +112,9 @@ sv_backends! { @case "timing::ff_startup_preserves_nested_if_case_actions"; } } + +sv_backends! { + fn qualified_ff_startup_actions(sim) { @case "timing::qualified_ff_startup_actions"; } + fn ordinary_edge_always_retains_staged_startup_edges(sim) { @case "timing::ordinary_edge_always_retains_staged_startup_edges"; } + fn macro_ff_startup_actions(sim) { @case "timing::macro_ff_startup_actions"; } +} From edc168aafdee0b5ec8ec6c9dd2eadf7cbbca1f8d Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 11:39:00 +0900 Subject: [PATCH 10/75] fix(suite): stage expanded and timed always bodies correctly --- crates/celox-test-suite/src/frontend.rs | 15 +++- .../celox-test-suite/src/frontend/timed_ff.rs | 90 ++++++++++++++++++- .../src/sv/cases/timing.vtest | 46 ++++++++++ .../tests/frontends/systemverilog/timing.rs | 5 ++ 4 files changed, 153 insertions(+), 3 deletions(-) diff --git a/crates/celox-test-suite/src/frontend.rs b/crates/celox-test-suite/src/frontend.rs index 2ef1f23f26e..d270c191cfc 100644 --- a/crates/celox-test-suite/src/frontend.rs +++ b/crates/celox-test-suite/src/frontend.rs @@ -218,21 +218,31 @@ impl TimedNames { } fn timed_source(source: &str, names: &TimedNames) -> Result { + // Stage actual declarations after macro expansion, including process + // keywords supplied as macro arguments. + let syntax = celox_sv_analyzer::syntax::parse_source(source, Path::new("timed.sv"))?; + let root = (&syntax).into_iter().next().ok_or("empty timed source")?; + let expanded = syntax + .get_str(vec![root]) + .ok_or("missing timed source text")?; Ok(format!( "import {}::*;\n{}", names.package, - timed_content(source, names)? + timed_content(expanded, names)? )) } fn timed_content(source: &str, names: &TimedNames) -> Result { let mut output = String::new(); let mut previous = 0; + let timed_tasks = timed_ff::timed_tasks(source); for (start, end, word) in sv_words(source) { if start < previous { continue; } - if word == "always_ff" || (word == "always" && timed_ff::edge_control(source, end)) { + if word == "always_ff" + || (word == "always" && timed_ff::edge_control(source, end, &timed_tasks)) + { let (body_end, replacement) = timed_ff::gated(source, start, end, names)?; output.push_str(&source[previous..start]); output.push_str(&timed_ff::in_macro(source, start, replacement)); @@ -241,6 +251,7 @@ fn timed_content(source: &str, names: &TimedNames) -> Result { } let replacement = match word { "initial" => format!("initial wait ({}::started)", names.package), + "always" if timed_ff::wildcard_control(source, end) => continue, "always" => { format!("always wait ({}::started)", names.package) } diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index d0d9db85ff9..2ea6b62ca48 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -104,6 +104,17 @@ fn statement_end(source: &str, at: usize) -> Option { Some(body) } } + Some("do") => { + let body = statement_end(source, at + words.first()?.1)?; + let next = trivia(source, body); + let word = sv_words(&source[next..]).first().copied()?; + if word.0 != 0 || word.2 != "while" { + return None; + } + let end = parens(source, trivia(source, next + word.1))?; + let semicolon = trivia(source, end); + (source.as_bytes().get(semicolon) == Some(&b';')).then_some(semicolon + 1) + } Some("forever") => statement_end(source, at + words.first()?.1), _ => { let mut cursor = at; @@ -168,7 +179,11 @@ pub(super) fn gated( /// The frontend classifies an ordinary always as FF only when every leaf /// of its event list is explicitly edge-qualified. -pub(super) fn edge_control(source: &str, end: usize) -> bool { +pub(super) fn edge_control( + source: &str, + end: usize, + timed_tasks: &std::collections::BTreeSet, +) -> bool { let at = trivia(source, end); if source.as_bytes().get(at) != Some(&b'@') { return false; @@ -177,6 +192,17 @@ pub(super) fn edge_control(source: &str, end: usize) -> bool { let Some(end) = parens(source, begin) else { return false; }; + let Some(body_end) = statement_end(source, end) else { + return false; + }; + let body = &source[end..body_end]; + if has_timing(body) + || sv_words(body) + .iter() + .any(|word| timed_tasks.contains(word.2)) + { + return false; + } let event = &source[begin + 1..end - 1]; let ors = sv_words(event) .into_iter() @@ -235,3 +261,65 @@ pub(super) fn in_macro(source: &str, start: usize, replacement: String) -> Strin } output } + +pub(super) fn wildcard_control(source: &str, end: usize) -> bool { + let at = trivia(source, end); + if source.as_bytes().get(at) != Some(&b'@') { + return false; + } + let begin = trivia(source, at + 1); + if source.as_bytes().get(begin) == Some(&b'*') { + return true; + } + parens(source, begin).is_some_and(|end| after_trivia(&source[begin + 1..end - 1]).trim() == "*") +} + +fn has_timing(source: &str) -> bool { + if sv_words(source).iter().any(|word| word.2 == "wait") { + return true; + } + let mut at = 0; + while at < source.len() { + if skip_token(source, &mut at) { + continue; + } + if matches!(source.as_bytes()[at], b'#' | b'@') { + return true; + } + at += 1; + } + false +} + +pub(super) fn timed_tasks(source: &str) -> std::collections::BTreeSet { + let words = sv_words(source); + let mut tasks = Vec::new(); + for (index, (_, end, word)) in words.iter().enumerate() { + if *word != "task" { + continue; + } + let Some((_, body_end, _)) = words[index + 1..].iter().find(|word| word.2 == "endtask") + else { + continue; + }; + let Some((_, _, name)) = words[index + 1..] + .iter() + .find(|word| !matches!(word.2, "automatic" | "static")) + else { + continue; + }; + tasks.push((name.to_string(), &source[*end..*body_end])); + } + let mut timed = std::collections::BTreeSet::new(); + loop { + let before = timed.len(); + for (name, body) in &tasks { + if has_timing(body) || sv_words(body).iter().any(|word| timed.contains(word.2)) { + timed.insert(name.clone()); + } + } + if timed.len() == before { + return timed; + } + } +} diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 49a1babb50f..3099b1644b9 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -497,3 +497,49 @@ endmodule"#) (top Top) (set clk 1) (run_until 0) (assert_eq y 0) (assert_eq q 1)) + +(case macro_argument_process_keywords_are_expanded_before_staging + (source "macro_arg.sv" #"`define FF(kind) kind @(posedge clk) q <= d; + module Top(input bit clk, d, output bit q, seen); + `FF(always_ff) + initial seen=q; + endmodule"#) + (top Top) + (set d 1) (set clk 1) (run_until 0) + (assert_eq seen 0) (assert_eq q 1)) + +(case do_while_ff_bodies_are_staged_in_full + (source "do_while.sv" #"module Top(input bit clk, d, output bit q, seen); + always_ff @(posedge clk) do q <= d; while (0); + initial seen=q; + endmodule"#) + (top Top) + (set d 1) (set clk 1) (run_until 0) + (assert_eq seen 0) (assert_eq q 1)) + +(case wildcard_always_blocks_settle_staged_inputs + (source "wildcard.sv" #"module Top(input bit a, output bit y, z); + always @(*) y=a; + always @* z=a; + initial #1; + endmodule"#) + (top Top) + (set a 1) (run_until 0) (assert_eq y 1) (assert_eq z 1)) + +(case timed_edge_always_bodies_do_not_replay_setup_edges + (source "delayed.sv" #"module Top(input bit clk, output bit q); + always @(posedge clk) #1 q=1; + endmodule"#) + (top Top) + (set clk 1) (run_until 1) (assert_eq q 0) + (set clk 0) (eval) (set clk 1) (run_until 2) (assert_eq q 1)) + +(case timed_edge_always_task_calls_do_not_replay_setup_edges + (source "task.sv" #"module Top(input bit clk, output bit q); + task tick; #1 q=1; endtask + task relay; tick(); endtask + always @(posedge clk) relay(); + endmodule"#) + (top Top) + (set clk 1) (run_until 1) (assert_eq q 0) + (set clk 0) (eval) (set clk 1) (run_until 2) (assert_eq q 1)) diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 78361930df9..61b82826277 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -117,4 +117,9 @@ sv_backends! { fn qualified_ff_startup_actions(sim) { @case "timing::qualified_ff_startup_actions"; } fn ordinary_edge_always_retains_staged_startup_edges(sim) { @case "timing::ordinary_edge_always_retains_staged_startup_edges"; } fn macro_ff_startup_actions(sim) { @case "timing::macro_ff_startup_actions"; } + fn macro_argument_process_keywords_are_expanded_before_staging(sim) { @case "timing::macro_argument_process_keywords_are_expanded_before_staging"; } + fn do_while_ff_bodies_are_staged_in_full(sim) { @case "timing::do_while_ff_bodies_are_staged_in_full"; } + fn wildcard_always_blocks_settle_staged_inputs(sim) { @case "timing::wildcard_always_blocks_settle_staged_inputs"; } + fn timed_edge_always_bodies_do_not_replay_setup_edges(sim) { @case "timing::timed_edge_always_bodies_do_not_replay_setup_edges"; } + fn timed_edge_always_task_calls_do_not_replay_setup_edges(sim) { @case "timing::timed_edge_always_task_calls_do_not_replay_setup_edges"; } } From 1515e0af2ce318cd44763a27f3b28950faef7436 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 12:13:04 +0900 Subject: [PATCH 11/75] fix(suite): resolve timed task scopes and retain automatic FF staging --- crates/celox-test-suite/src/frontend.rs | 33 ++-- .../celox-test-suite/src/frontend/timed_ff.rs | 157 +++++++++++++----- .../src/sv/cases/timing.vtest | 33 ++++ .../tests/frontends/systemverilog/timing.rs | 3 + 4 files changed, 175 insertions(+), 51 deletions(-) diff --git a/crates/celox-test-suite/src/frontend.rs b/crates/celox-test-suite/src/frontend.rs index d270c191cfc..d4b3c6f39db 100644 --- a/crates/celox-test-suite/src/frontend.rs +++ b/crates/celox-test-suite/src/frontend.rs @@ -70,9 +70,15 @@ pub(crate) fn stage( source.text.as_bytes(), )?; } - let prepared = + let mut prepared = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| frontend.prepare(design))) .map_err(|error| EmissionError(panic_message(error.as_ref())))??; + if design.timed { + for source in &mut prepared.sources { + *source = expanded_timed_source(source)?; + } + } + let task_timing = timed_ff::TaskTiming::new(&prepared.sources); let control_names = timed_names(&prepared.sources); let timescale = directory.join("timescale.sv"); write_if_changed(×cale, TIMESCALE.as_bytes())?; @@ -85,7 +91,7 @@ pub(crate) fn stage( for (index, source) in prepared.sources.iter().enumerate() { let path = directory.join(format!("source_{index}.sv")); let source = if design.timed { - timed_source(source, &control_names)? + timed_source(source, &control_names, &task_timing)? } else { source.clone() }; @@ -217,33 +223,32 @@ impl TimedNames { } } -fn timed_source(source: &str, names: &TimedNames) -> Result { - // Stage actual declarations after macro expansion, including process - // keywords supplied as macro arguments. +fn expanded_timed_source(source: &str) -> Result { let syntax = celox_sv_analyzer::syntax::parse_source(source, Path::new("timed.sv"))?; let root = (&syntax).into_iter().next().ok_or("empty timed source")?; - let expanded = syntax + Ok(syntax .get_str(vec![root]) - .ok_or("missing timed source text")?; + .ok_or("missing timed source text")? + .to_owned()) +} + +fn timed_source(source: &str, names: &TimedNames, tasks: &timed_ff::TaskTiming) -> Result { Ok(format!( "import {}::*;\n{}", names.package, - timed_content(expanded, names)? + timed_content(source, names, tasks)? )) } -fn timed_content(source: &str, names: &TimedNames) -> Result { +fn timed_content(source: &str, names: &TimedNames, tasks: &timed_ff::TaskTiming) -> Result { let mut output = String::new(); let mut previous = 0; - let timed_tasks = timed_ff::timed_tasks(source); for (start, end, word) in sv_words(source) { if start < previous { continue; } - if word == "always_ff" - || (word == "always" && timed_ff::edge_control(source, end, &timed_tasks)) - { - let (body_end, replacement) = timed_ff::gated(source, start, end, names)?; + if word == "always_ff" || (word == "always" && timed_ff::edge_control(source, end, tasks)) { + let (body_end, replacement) = timed_ff::gated(source, start, end, names, tasks)?; output.push_str(&source[previous..start]); output.push_str(&timed_ff::in_macro(source, start, replacement)); previous = body_end; diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index 2ea6b62ca48..3b29a77557b 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -141,6 +141,7 @@ pub(super) fn gated( start: usize, end: usize, names: &TimedNames, + tasks: &TaskTiming, ) -> Result<(usize, String)> { let at = trivia(source, end); if source.as_bytes().get(at) != Some(&b'@') { @@ -151,7 +152,7 @@ pub(super) fn gated( let body_start = trivia(source, event_end); let body_end = statement_end(source, body_start).ok_or("unsupported timed always_ff statement")?; - let body = timed_content(&source[body_start..body_end], names)?; + let body = timed_content(&source[body_start..body_end], names, tasks)?; let identifiers = sv_words(source) .into_iter() .map(|word| word.2) @@ -172,18 +173,14 @@ pub(super) fn gated( Ok(( body_end, format!( - "always @({event} or posedge {package}::started) begin\n bit {armed}=0;\n bit {pending}=0;\n if (!{package}::started) {pending}=1;\n else if ({armed} || {pending}) begin\n {pending}=0;\n {body}\n end\n {armed}={package}::started;\nend" + "bit {armed}=0;\nbit {pending}=0;\nalways @({event} or posedge {package}::started) begin\n if (!{package}::started) {pending}=1;\n else if ({armed} || {pending}) begin\n {pending}=0;\n {body}\n end\n {armed}={package}::started;\nend" ), )) } /// The frontend classifies an ordinary always as FF only when every leaf /// of its event list is explicitly edge-qualified. -pub(super) fn edge_control( - source: &str, - end: usize, - timed_tasks: &std::collections::BTreeSet, -) -> bool { +pub(super) fn edge_control(source: &str, end: usize, tasks: &TaskTiming) -> bool { let at = trivia(source, end); if source.as_bytes().get(at) != Some(&b'@') { return false; @@ -196,11 +193,7 @@ pub(super) fn edge_control( return false; }; let body = &source[end..body_end]; - if has_timing(body) - || sv_words(body) - .iter() - .any(|word| timed_tasks.contains(word.2)) - { + if has_timing(body) || tasks.has_timed_call(source, end, body_end) { return false; } let event = &source[begin + 1..end - 1]; @@ -291,35 +284,125 @@ fn has_timing(source: &str) -> bool { false } -pub(super) fn timed_tasks(source: &str) -> std::collections::BTreeSet { - let words = sv_words(source); - let mut tasks = Vec::new(); - for (index, (_, end, word)) in words.iter().enumerate() { - if *word != "task" { - continue; +#[derive(Default)] +pub(super) struct TaskTiming { + tasks: BTreeMap, +} + +fn container_at(source: &str, at: usize) -> String { + let words = sv_words(&source[..at]); + let mut scope = String::new(); + for (index, (_, _, word)) in words.iter().enumerate() { + match *word { + "module" | "interface" | "package" => { + if let Some((_, _, name)) = words[index + 1..] + .iter() + .find(|word| !matches!(word.2, "static" | "automatic")) + { + scope = name.to_string(); + } + } + "endmodule" | "endinterface" | "endpackage" => scope.clear(), + _ => {} } - let Some((_, body_end, _)) = words[index + 1..].iter().find(|word| word.2 == "endtask") - else { - continue; - }; - let Some((_, _, name)) = words[index + 1..] - .iter() - .find(|word| !matches!(word.2, "automatic" | "static")) - else { - continue; - }; - tasks.push((name.to_string(), &source[*end..*body_end])); } - let mut timed = std::collections::BTreeSet::new(); - loop { - let before = timed.len(); - for (name, body) in &tasks { - if has_timing(body) || sv_words(body).iter().any(|word| timed.contains(word.2)) { - timed.insert(name.clone()); + scope +} + +impl TaskTiming { + pub(super) fn new(sources: &[String]) -> Self { + let mut result = Self::default(); + let mut records = Vec::new(); + for source in sources { + let words = sv_words(source); + for (index, (start, end, word)) in words.iter().enumerate() { + if *word != "task" { + continue; + } + let Some((_, body_end, _)) = + words[index + 1..].iter().find(|word| word.2 == "endtask") + else { + continue; + }; + let Some((_, _, name)) = words[index + 1..] + .iter() + .find(|word| !matches!(word.2, "automatic" | "static")) + else { + continue; + }; + let scope = container_at(source, *start); + let key = format!("{scope}::{name}"); + let header_end = source[*end..*body_end] + .find(';') + .map_or(*end, |offset| end + offset + 1); + result + .tasks + .insert(key.clone(), has_timing(&source[header_end..*body_end])); + records.push((key, source.as_str(), header_end, *body_end)); + } + } + loop { + let mut changed = false; + for (key, source, start, end) in &records { + if !result.tasks[key] && result.has_timed_call(source, *start, *end) { + result.tasks.insert(key.clone(), true); + changed = true; + } + } + if !changed { + return result; } } - if timed.len() == before { - return timed; + } + + fn resolve(&self, source: &str, at: usize, name: &str) -> Option { + let prefix = source[..at].trim_end(); + if let Some(prefix) = prefix.strip_suffix("::") { + let package = sv_words(prefix).last()?.2; + return self.tasks.get(&format!("{package}::{name}")).copied(); + } + let scope = container_at(source, at); + if let Some(value) = self.tasks.get(&format!("{scope}::{name}")) { + return Some(*value); + } + for (start, end, word) in sv_words(&source[..at]) { + if word != "import" { + continue; + } + let import_scope = container_at(source, start); + if !import_scope.is_empty() && import_scope != scope { + continue; + } + let tail = &source[end..]; + let clause = &tail[..tail.find(';')?]; + let words = sv_words(clause); + let Some((_, _, package)) = words.first() else { + continue; + }; + let selected = words.get(1).map(|word| word.2); + if selected == Some(name) || (selected.is_none() && clause.contains('*')) { + if let Some(value) = self.tasks.get(&format!("{package}::{name}")) { + return Some(*value); + } + } } + None + } + + fn has_timed_call(&self, source: &str, start: usize, end: usize) -> bool { + sv_words(&source[start..end]) + .iter() + .any(|(at, word_end, name)| { + if !self + .tasks + .keys() + .any(|key| key.ends_with(&format!("::{name}"))) + { + return false; + } + let tail = after_trivia(&source[start + word_end..end]); + (tail.starts_with('(') || tail.starts_with(';')) + && self.resolve(source, start + at, name).unwrap_or(true) + }) } } diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 3099b1644b9..a58764bfa81 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -543,3 +543,36 @@ (top Top) (set clk 1) (run_until 1) (assert_eq q 0) (set clk 0) (eval) (set clk 1) (run_until 2) (assert_eq q 1)) + +(case imported_timed_tasks_do_not_replay_setup_edges + (source "delays.sv" #"package delays; + task automatic tick(output bit value); #1 value=1; endtask + endpackage"#) + (source "imported.sv" #"module Top(input bit clk, output bit q); + import delays::*; + always @(posedge clk) tick(q); + endmodule"#) + (top Top) + (set clk 1) (run_until 1) (assert_eq q 0) + (set clk 0) (eval) (set clk 1) (run_until 2) (assert_eq q 1)) + +(case untimed_local_tasks_shadow_timed_tasks_in_other_scopes + (source "slow.sv" #"package slow; + task automatic tick(output bit value); #1 value=1; endtask + endpackage"#) + (source "local.sv" #"module Top(input bit clk, output bit q, seen); + task tick; q<=1; endtask + always @(posedge clk) tick(); + initial seen=q; + endmodule"#) + (top Top) + (set clk 1) (run_until 0) (assert_eq seen 0) (assert_eq q 1)) + +(case automatic_module_ff_staging_keeps_its_state + (source "automatic.sv" #"module automatic Top(input bit clk, output bit q, seen); + always_ff @(posedge clk) q<=1; + initial seen=q; + endmodule"#) + (top Top) + (set clk 1) (run_until 0) (assert_eq seen 0) (assert_eq q 1) + (set clk 0) (eval) (set clk 1) (run_until 1) (assert_eq q 1)) diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 61b82826277..3af3199475f 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -122,4 +122,7 @@ sv_backends! { fn wildcard_always_blocks_settle_staged_inputs(sim) { @case "timing::wildcard_always_blocks_settle_staged_inputs"; } fn timed_edge_always_bodies_do_not_replay_setup_edges(sim) { @case "timing::timed_edge_always_bodies_do_not_replay_setup_edges"; } fn timed_edge_always_task_calls_do_not_replay_setup_edges(sim) { @case "timing::timed_edge_always_task_calls_do_not_replay_setup_edges"; } + fn imported_timed_tasks_do_not_replay_setup_edges(sim) { @case "timing::imported_timed_tasks_do_not_replay_setup_edges"; } + fn untimed_local_tasks_shadow_timed_tasks_in_other_scopes(sim) { @case "timing::untimed_local_tasks_shadow_timed_tasks_in_other_scopes"; } + fn automatic_module_ff_staging_keeps_its_state(sim) { @case "timing::automatic_module_ff_staging_keeps_its_state"; } } From e74b945cf52c110fd9327199ae5572cfe633421a Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 13:02:45 +0900 Subject: [PATCH 12/75] fix(suite): import only the generated timed finish helper --- crates/celox-test-suite/src/frontend.rs | 3 ++- crates/celox-test-suite/src/sv/cases/timing.vtest | 8 ++++++++ crates/celox/tests/frontends/systemverilog/timing.rs | 1 + 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/celox-test-suite/src/frontend.rs b/crates/celox-test-suite/src/frontend.rs index d4b3c6f39db..eb05a7e777d 100644 --- a/crates/celox-test-suite/src/frontend.rs +++ b/crates/celox-test-suite/src/frontend.rs @@ -234,8 +234,9 @@ fn expanded_timed_source(source: &str) -> Result { fn timed_source(source: &str, names: &TimedNames, tasks: &timed_ff::TaskTiming) -> Result { Ok(format!( - "import {}::*;\n{}", + "import {}::{};\n{}", names.package, + names.finish, timed_content(source, names, tasks)? )) } diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index a58764bfa81..cecacd9c4a9 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -576,3 +576,11 @@ (top Top) (set clk 1) (run_until 0) (assert_eq seen 0) (assert_eq q 1) (set clk 0) (eval) (set clk 1) (run_until 1) (assert_eq q 1)) + +(case control_members_do_not_pollute_user_package_imports + (source "user.sv" #"package user_values; localparam bit started=1; localparam bit finished=1; endpackage"#) + (source "top.sv" #"module Top(output bit q); import user_values::*; + initial begin q=started & finished; #1; $finish; end + endmodule"#) + (top Top) + (run_until 0) (assert_eq q 1) (run_to_finish)) diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 3af3199475f..90e318abc83 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -125,4 +125,5 @@ sv_backends! { fn imported_timed_tasks_do_not_replay_setup_edges(sim) { @case "timing::imported_timed_tasks_do_not_replay_setup_edges"; } fn untimed_local_tasks_shadow_timed_tasks_in_other_scopes(sim) { @case "timing::untimed_local_tasks_shadow_timed_tasks_in_other_scopes"; } fn automatic_module_ff_staging_keeps_its_state(sim) { @case "timing::automatic_module_ff_staging_keeps_its_state"; } + fn control_members_do_not_pollute_user_package_imports(sim) { @case "timing::control_members_do_not_pollute_user_package_imports"; } } From 202cc9f23ecadd194a79c62d4f1c2acfc1895357 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 13:16:08 +0900 Subject: [PATCH 13/75] test(suite): cover blocking and nonblocking FF publication --- .../src/sv/cases/timing.vtest | 27 +++++++++++++++++++ .../tests/frontends/systemverilog/timing.rs | 3 +++ 2 files changed, 30 insertions(+) diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index cecacd9c4a9..5db5ab499c1 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -584,3 +584,30 @@ endmodule"#) (top Top) (run_until 0) (assert_eq q 1) (run_to_finish)) + +(case blocking_ff_stores_are_visible_before_inactive_work + (source "blocking.sv" #"module Top(output bit [7:0] q, observed, derived_seen); + bit clk; wire [7:0] derived=q+1; + always @(posedge clk) q=1; + initial #1 clk=1; + initial begin @(posedge clk); #0; observed=q; derived_seen=derived; q=9; end + endmodule"#) + (top Top) (run_until 1) (assert_eq observed 1) (assert_eq derived_seen 2) (assert_eq q 9)) + +(case nonblocking_ff_stores_remain_pending_during_inactive_work + (source "nonblocking.sv" #"module Top(output bit [7:0] q, observed, derived_seen); + bit clk; wire [7:0] derived=q+1; + always @(posedge clk) q<=1; + initial #1 clk=1; + initial begin @(posedge clk); #0; observed=q; derived_seen=derived; q=9; end + endmodule"#) + (top Top) (run_until 1) (assert_eq observed 0) (assert_eq derived_seen 1) (assert_eq q 1)) + +(case mixed_ff_stores_keep_their_active_and_nba_values + (source "mixed.sv" #"module Top(output bit [7:0] q, observed, derived_seen); + bit clk; wire [7:0] derived=q+1; + always @(posedge clk) begin q<=7; q=2; end + initial #1 clk=1; + initial begin @(posedge clk); #0; observed=q; derived_seen=derived; q=9; end + endmodule"#) + (top Top) (run_until 1) (assert_eq observed 2) (assert_eq derived_seen 3) (assert_eq q 7)) diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 90e318abc83..f414178052d 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -126,4 +126,7 @@ sv_backends! { fn untimed_local_tasks_shadow_timed_tasks_in_other_scopes(sim) { @case "timing::untimed_local_tasks_shadow_timed_tasks_in_other_scopes"; } fn automatic_module_ff_staging_keeps_its_state(sim) { @case "timing::automatic_module_ff_staging_keeps_its_state"; } fn control_members_do_not_pollute_user_package_imports(sim) { @case "timing::control_members_do_not_pollute_user_package_imports"; } + fn blocking_ff_stores_are_visible_before_inactive_work(sim) { @case "timing::blocking_ff_stores_are_visible_before_inactive_work"; } + fn nonblocking_ff_stores_remain_pending_during_inactive_work(sim) { @case "timing::nonblocking_ff_stores_remain_pending_during_inactive_work"; } + fn mixed_ff_stores_keep_their_active_and_nba_values(sim) { @case "timing::mixed_ff_stores_keep_their_active_and_nba_values"; } } From 582ca999b5c13ceba85e075c7cf9b8460e195c4f Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 13:45:57 +0900 Subject: [PATCH 14/75] fix(suite): preserve qualified tasks and complete staged actions --- crates/celox-test-suite/src/frontend.rs | 62 +++++++++++++++++++ .../celox-test-suite/src/frontend/timed_ff.rs | 23 ++++++- crates/celox-test-suite/src/script/sv.rs | 12 ++-- .../src/sv/cases/timing.vtest | 28 +++++++++ .../tests/frontends/systemverilog/suite.rs | 55 +++++++++++----- .../tests/frontends/systemverilog/timing.rs | 7 +++ 6 files changed, 164 insertions(+), 23 deletions(-) diff --git a/crates/celox-test-suite/src/frontend.rs b/crates/celox-test-suite/src/frontend.rs index eb05a7e777d..2921af27c99 100644 --- a/crates/celox-test-suite/src/frontend.rs +++ b/crates/celox-test-suite/src/frontend.rs @@ -272,3 +272,65 @@ fn timed_content(source: &str, names: &TimedNames, tasks: &timed_ff::TaskTiming) output.push_str(&source[previous..]); Ok(output) } + +#[cfg(all(test, feature = "icarus", feature = "verilator"))] +mod timed_staging_tests { + use crate as celox_test_suite; + use crate::{Backend, load_group, no_std_library}; + + #[test] + #[ignore = "requires Icarus, Verilator and a C++ compiler; Celox does not yet support hierarchical task calls"] + fn qualified_timed_tasks_do_not_use_same_named_local_tasks() { + let text = r##"(group qualified (category sequential)) + (case task (source "task.sv" #"module Worker(output bit q); + task tick; #1 q=1; endtask + endmodule + module Top(input bit clk, output bit q); + Worker worker(.q(q)); bit dummy; + task tick; dummy=1; endtask + always @(posedge clk) worker.tick(); + endmodule"#) + (top Top) (set clk 1) (run_until 1) (assert_eq q 0) + (set clk 0) (eval) (set clk 1) (run_until 2) (assert_eq q 1))"##; + let case = load_group("qualified-task.vtest", text, no_std_library)[0]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../target/qualified-task-protocol") + .join(std::process::id().to_string()); + struct TaskFrontend; + impl celox_test_suite::frontend::Frontend for TaskFrontend { + fn source_extension(&self) -> &'static str { + "sv" + } + fn prepare( + &self, + design: &celox_test_suite::Design, + ) -> celox_test_suite::Result { + let frontend = celox_test_suite::sv::verification::SvFrontend; + let mut actual = frontend.prepare(design)?; + // Port shapes are known independently of unsupported method-call + // analysis; this test exercises the external staging adapter. + let stub = celox_test_suite::Design::new( + "module Top(input bit clk, output bit q); endmodule", + "Top", + ); + actual.info = frontend.prepare(&stub)?.info; + Ok(actual) + } + } + let frontend = TaskFrontend; + let mut icarus = + celox_test_suite::icarus::Icarus::build_script(&frontend, case, &root.join("icarus")) + .unwrap(); + icarus.run_testbench().unwrap(); + let mut verilator = celox_test_suite::verilator::Verilator::build_script( + &frontend, + case, + &root.join("verilator"), + ) + .unwrap(); + verilator.run_testbench().unwrap(); + let log = std::fs::read_to_string(root.join("verilator/protocol.log")).unwrap(); + celox_test_suite::script::sv::check_output(&log, &[]).unwrap(); + std::fs::remove_dir_all(root).unwrap(); + } +} diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index 3b29a77557b..1a80b503635 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -93,12 +93,14 @@ fn statement_end(source: &str, at: usize) -> Option { } None } - Some("if" | "for" | "foreach" | "while" | "repeat") => { + Some("if" | "for" | "foreach" | "while" | "repeat" | "assert" | "assume" | "cover") => { let word = words.first()?; let end = parens(source, trivia(source, at + word.1))?; let body = statement_end(source, end)?; let next = trivia(source, body); - if keyword == Some("if") && source[next..].starts_with("else") { + if matches!(keyword, Some("if" | "assert" | "assume")) + && source[next..].starts_with("else") + { statement_end(source, next + 4) } else { Some(body) @@ -168,12 +170,13 @@ pub(super) fn gated( }; let armed = fresh("armed"); let pending = fresh("pending"); + let scope = fresh("scope"); let package = &names.package; let event = &source[begin + 1..event_end - 1]; Ok(( body_end, format!( - "bit {armed}=0;\nbit {pending}=0;\nalways @({event} or posedge {package}::started) begin\n if (!{package}::started) {pending}=1;\n else if ({armed} || {pending}) begin\n {pending}=0;\n {body}\n end\n {armed}={package}::started;\nend" + "if (1) begin : {scope}\nbit {armed}=0;\nbit {pending}=0;\nalways @({event} or posedge {package}::started) begin\n if (!{package}::started) {pending}=1;\n else if ({armed} || {pending}) begin\n {pending}=0;\n {body}\n end\n {armed}={package}::started;\nend\nend else begin end" ), )) } @@ -361,6 +364,20 @@ impl TaskTiming { let package = sv_words(prefix).last()?.2; return self.tasks.get(&format!("{package}::{name}")).copied(); } + if let Some(prefix) = prefix.strip_suffix('.') { + let instance = sv_words(prefix).last()?.2; + let scope = container_at(source, at); + let words = sv_words(&source[..at]); + for pair in words.windows(2) { + if pair[1].2 == instance && container_at(source, pair[0].0) == scope { + if let Some(value) = self.tasks.get(&format!("{}::{name}", pair[0].2)) { + return Some(*value); + } + } + } + // An unresolved qualified call cannot use a same-named local task. + return None; + } let scope = container_at(source, at); if let Some(value) = self.tasks.get(&format!("{scope}::{name}")) { return Some(*value); diff --git a/crates/celox-test-suite/src/script/sv.rs b/crates/celox-test-suite/src/script/sv.rs index e08e35a816b..4c4a2d18ab6 100644 --- a/crates/celox-test-suite/src/script/sv.rs +++ b/crates/celox-test-suite/src/script/sv.rs @@ -142,7 +142,7 @@ fn is_source_finish_notice(line: &str, sources: &[String]) -> bool { .file_name() .map(|name| name.to_string_lossy().into_owned()) .unwrap_or_default(); - sources.contains(&name) + name == "timed_control.sv" && sources.contains(&name) }) } @@ -1154,14 +1154,14 @@ mod tests { #[test] fn finish_notices_are_not_design_output() { - let sources = ["source_0.sv".to_string()]; - let icarus = "done\n/tmp/case/source_0.sv:17: $finish called at 18000 (1ps)\n"; + let sources = ["timed_control.sv".to_string(), "source_0.sv".to_string()]; + let icarus = "done\n/tmp/case/timed_control.sv:17: $finish called at 18000 (1ps)\n"; assert_eq!(design_output(icarus, &sources), "done\n"); - let verilator = "done\n- /tmp/case/source_0.sv:19: Verilog $finish\n"; + let verilator = "done\n- /tmp/case/timed_control.sv:19: Verilog $finish\n"; assert_eq!(design_output(verilator, &sources), "done\n"); assert_eq!( design_output( - "done\n/tmp/case/source_0.sv:17: $finish(1) called at 18000 (1ps)\n", + "done\n/tmp/case/timed_control.sv:17: $finish(1) called at 18000 (1ps)\n", &sources ), "done\n" @@ -1172,7 +1172,7 @@ mod tests { ); assert_eq!(design_output("no newline", &sources), "no newline"); // A design's line of the same shape names no source file. - let printed = "foo.sv:1: $finish called at 0 (1ps)\n"; + let printed = "source_0.sv:17: $finish called at 0 (1ps)\n"; assert_eq!(design_output(printed, &sources), printed); } diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 5db5ab499c1..5cda2f3aafc 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -611,3 +611,31 @@ initial begin @(posedge clk); #0; observed=q; derived_seen=derived; q=9; end endmodule"#) (top Top) (run_until 1) (assert_eq observed 2) (assert_eq derived_seen 3) (assert_eq q 7)) + +(case single_item_generate_ff_rewrites_keep_their_else + (source "generate_ff.sv" #"module Top(input bit clk, output bit [1:0] q, seen); + if (0) always_ff @(posedge clk) q<=1; + else always_ff @(posedge clk) q<=2; + initial seen=q; + endmodule"#) + (top Top) (set clk 1) (run_until 0) (assert_eq seen 0) (assert_eq q 2)) + +(case immediate_assertion_ff_keeps_both_actions + (source "assert_ff.sv" #"module Top(input bit clk, en, output bit q); + always_ff @(posedge clk) assert (en) q<=1; else q<=0; + endmodule"#) + (top Top) (set en 0) (set clk 1) (run_until 0) (assert_eq q 0) + (set clk 0) (eval) (set en 1) (set clk 1) (run_until 1) (assert_eq q 1)) + +(case printed_finish_notice_is_design_output + (source "printed.sv" #"module Top; + initial begin $display("source_0.sv:17: $finish called at 0 (1ps)"); #1; $finish; end + endmodule"#) + (top Top) (run_until 0) (expect_output "source_0.sv:17: $finish called at 0 (1ps)\n") (run_to_finish)) + +(case combinational_finish_ends_timed_execution + (source "comb_finish.sv" #"module Top(output bit done); + initial begin #1; done=1; end + always_comb if(done) $finish; + endmodule"#) + (top Top) (run_to_finish) (assert_eq done 1)) diff --git a/crates/celox/tests/frontends/systemverilog/suite.rs b/crates/celox/tests/frontends/systemverilog/suite.rs index 6310a53ff72..60adf337d51 100644 --- a/crates/celox/tests/frontends/systemverilog/suite.rs +++ b/crates/celox/tests/frontends/systemverilog/suite.rs @@ -6,7 +6,22 @@ use celox_test_suite::{Backend, CompilationRejected, Design, Result, SignalPath} struct CeloxBackend(Simulator); /// A timed case: the design's own processes and clocks run. -struct TimedBackend(Simulation); +struct TimedBackend(Simulation, Vec, bool); +impl TimedBackend { + fn new(sim: Simulation) -> Self { + Self(sim, Vec::new(), false) + } + fn capture_events(&mut self) { + let events = self.0.drain_runtime_events(); + self.2 |= events + .iter() + .any(|event| matches!(event, RuntimeEvent::Finish)); + self.1.extend(events); + } + fn finished(&self) -> bool { + self.0.is_finished() || self.2 + } +} fn signal_of(sim: &Simulation, path: &SignalPath) -> celox::SignalRef { let instances: Vec<_> = path @@ -49,6 +64,7 @@ impl Backend for TimedBackend { fn read(&mut self, path: &SignalPath) -> Result<(BigUint, BigUint)> { self.0.settle()?; + self.capture_events(); let signal = signal_of(&self.0, path); Ok(self.0.get_four_state(signal)) } @@ -56,7 +72,9 @@ impl Backend for TimedBackend { /// Settling also resumes the processes the writes woke, as the external /// simulators' settle step does. fn eval_comb(&mut self) -> Result<()> { - self.0.settle().map_err(Into::into) + self.0.settle()?; + self.capture_events(); + Ok(()) } fn tick(&mut self, _event: &str) -> Result<()> { @@ -65,7 +83,8 @@ impl Backend for TimedBackend { fn take_output(&mut self) -> Result { self.0.settle()?; - collect_output(self.0.drain_runtime_events()) + self.capture_events(); + collect_output(std::mem::take(&mut self.1)) } fn run_until(&mut self, time: u64) -> Result<()> { @@ -74,7 +93,8 @@ impl Backend for TimedBackend { return Err(format!("run_until {time}: the simulation is already at {now}").into()); } self.0.run_until(time)?; - if self.0.is_finished() { + self.capture_events(); + if self.finished() { return Err(format!( "run_until {time}: the design finished the simulation at {}", self.0.time() @@ -85,13 +105,20 @@ impl Backend for TimedBackend { } fn run_to_finish(&mut self) -> Result<()> { - if self.0.is_finished() { + self.capture_events(); + if self.finished() { return Err( "run_to_finish: the design already finished before the operation began".into(), ); } - while !self.0.is_finished() && self.0.step()?.is_some() {} - if !self.0.is_finished() { + while !self.finished() { + let step = self.0.step()?; + self.capture_events(); + if step.is_none() { + break; + } + } + if !self.finished() { return Err( "run_to_finish: the simulation ran out of events before a process finished it" .into(), @@ -153,21 +180,21 @@ fn build(design: &Design, backend: &str) -> Result> { |builder, (name, value)| builder.param(name, *value), ); return Ok(match backend { - "native" => Box::new(TimedBackend(builder.build_native()?)), - "cranelift" => Box::new(TimedBackend(builder.build_cranelift()?)), - "native-parallel" => Box::new(TimedBackend( + "native" => Box::new(TimedBackend::new(builder.build_native()?)), + "cranelift" => Box::new(TimedBackend::new(builder.build_cranelift()?)), + "native-parallel" => Box::new(TimedBackend::new( builder .threads(4) .parallel_partition(celox::ParallelPartition::Always) .build_native()?, )), - "cranelift-parallel" => Box::new(TimedBackend( + "cranelift-parallel" => Box::new(TimedBackend::new( builder .threads(4) .parallel_partition(celox::ParallelPartition::Always) .build_cranelift()?, )), - "wasm" => Box::new(TimedBackend(builder.build_wasm()?)), + "wasm" => Box::new(TimedBackend::new(builder.build_wasm()?)), _ => return Err(format!("unknown backend: {backend}").into()), }); } @@ -236,7 +263,7 @@ fn run_to_finish_reaches_the_last_scheduler_timestamp() { celox::Simulation::from_sv_sources(vec![(source, std::path::Path::new("last.sv"))], "Top") .build() .unwrap(); - let mut backend = TimedBackend(simulation); + let mut backend = TimedBackend::new(simulation); backend.run_to_finish().unwrap(); assert_eq!(backend.0.time(), u64::MAX); assert_eq!(backend.0.get(backend.0.signal("done")), 1u8.into()); @@ -250,7 +277,7 @@ fn run_to_finish_rejects_a_finish_during_an_earlier_settle() { Simulation::from_sv_sources(vec![(source, std::path::Path::new("early.sv"))], "Top") .build() .unwrap(); - let mut backend = TimedBackend(simulation); + let mut backend = TimedBackend::new(simulation); backend.run_until(0).unwrap(); let go = backend.0.signal("go"); backend.0.set_wide(go, 1u8.into()); diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index f414178052d..d315dfd3416 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -129,4 +129,11 @@ sv_backends! { fn blocking_ff_stores_are_visible_before_inactive_work(sim) { @case "timing::blocking_ff_stores_are_visible_before_inactive_work"; } fn nonblocking_ff_stores_remain_pending_during_inactive_work(sim) { @case "timing::nonblocking_ff_stores_remain_pending_during_inactive_work"; } fn mixed_ff_stores_keep_their_active_and_nba_values(sim) { @case "timing::mixed_ff_stores_keep_their_active_and_nba_values"; } + fn single_item_generate_ff_rewrites_keep_their_else(sim) { @case "timing::single_item_generate_ff_rewrites_keep_their_else"; } +} + +sv_backends! { + fn immediate_assertion_ff_keeps_both_actions(sim) { @case "timing::immediate_assertion_ff_keeps_both_actions"; } + fn printed_finish_notice_is_design_output(sim) { @case "timing::printed_finish_notice_is_design_output"; } + fn combinational_finish_ends_timed_execution(sim) { @case "timing::combinational_finish_ends_timed_execution"; } } From 6805e47595b21a875fd867e0b613e40a1ed5d1ee Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 14:45:19 +0900 Subject: [PATCH 15/75] fix(suite): resolve callable scopes and reject unexpected finishes --- crates/celox-test-suite/src/frontend.rs | 23 +++++++++ .../celox-test-suite/src/frontend/timed_ff.rs | 47 +++++++++++++++++-- .../src/sv/cases/timing.vtest | 17 +++++++ .../tests/frontends/systemverilog/suite.rs | 36 ++++++++++---- .../tests/frontends/systemverilog/timing.rs | 5 ++ 5 files changed, 116 insertions(+), 12 deletions(-) diff --git a/crates/celox-test-suite/src/frontend.rs b/crates/celox-test-suite/src/frontend.rs index 2921af27c99..94124a49ed5 100644 --- a/crates/celox-test-suite/src/frontend.rs +++ b/crates/celox-test-suite/src/frontend.rs @@ -333,4 +333,27 @@ mod timed_staging_tests { celox_test_suite::script::sv::check_output(&log, &[]).unwrap(); std::fs::remove_dir_all(root).unwrap(); } + #[test] + #[ignore = "requires Verilator and a C++ compiler; Icarus rejects deferred assertions"] + fn deferred_assertions_retain_staged_edges() { + let text = r##"(group deferred (category sequential)) + (case assertion (source "assert.sv" #"module Top(input bit clk,output bit q,seen); + task accept; q<=1; endtask + task reject; q<=0; endtask + always @(posedge clk) assert #0 (1) accept(); else reject(); + initial seen=q; + endmodule"#) (top Top) (set clk 1) (run_until 0) (assert_eq seen 0) (assert_eq q 1))"##; + let case = load_group("deferred.vtest", text, no_std_library)[0]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../target/deferred-assertion-protocol") + .join(std::process::id().to_string()); + let mut backend = celox_test_suite::verilator::Verilator::build_script( + &celox_test_suite::sv::verification::SvFrontend, + case, + &root, + ) + .unwrap(); + backend.run_testbench().unwrap(); + std::fs::remove_dir_all(root).unwrap(); + } } diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index 1a80b503635..803ff942fbc 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -95,7 +95,18 @@ fn statement_end(source: &str, at: usize) -> Option { } Some("if" | "for" | "foreach" | "while" | "repeat" | "assert" | "assume" | "cover") => { let word = words.first()?; - let end = parens(source, trivia(source, at + word.1))?; + let mut control = trivia(source, at + word.1); + if matches!(keyword, Some("assert" | "assume" | "cover")) { + if source[control..].starts_with("#0") { + control = trivia(source, control + 2); + } else if sv_words(&source[control..]) + .first() + .is_some_and(|word| word.0 == 0 && word.2 == "final") + { + control = trivia(source, control + 5); + } + } + let end = parens(source, control)?; let body = statement_end(source, end)?; let next = trivia(source, body); if matches!(keyword, Some("if" | "assert" | "assume")) @@ -279,6 +290,16 @@ fn has_timing(source: &str) -> bool { if skip_token(source, &mut at) { continue; } + if source.as_bytes()[at] == b'#' + && sv_words(&source[..at]) + .last() + .is_some_and(|word| matches!(word.2, "assert" | "assume" | "cover")) + && source[at..].starts_with("#0") + && source.as_bytes().get(trivia(source, at + 2)) == Some(&b'(') + { + at += 2; + continue; + } if matches!(source.as_bytes()[at], b'#' | b'@') { return true; } @@ -319,6 +340,20 @@ impl TaskTiming { for source in sources { let words = sv_words(source); for (index, (start, end, word)) in words.iter().enumerate() { + if *word == "function" { + let header_end = source[*end..] + .find(';') + .map(|offset| end + offset) + .unwrap_or(source.len()); + let header = &source[*end..header_end]; + let name_end = header.find('(').unwrap_or(header.len()); + if let Some((_, _, name)) = sv_words(&header[..name_end]).last() { + result + .tasks + .insert(format!("{}::{name}", container_at(source, *start)), false); + } + continue; + } if *word != "task" { continue; } @@ -382,6 +417,8 @@ impl TaskTiming { if let Some(value) = self.tasks.get(&format!("{scope}::{name}")) { return Some(*value); } + let mut explicit = None; + let mut wildcard = None; for (start, end, word) in sv_words(&source[..at]) { if word != "import" { continue; @@ -399,11 +436,15 @@ impl TaskTiming { let selected = words.get(1).map(|word| word.2); if selected == Some(name) || (selected.is_none() && clause.contains('*')) { if let Some(value) = self.tasks.get(&format!("{package}::{name}")) { - return Some(*value); + if selected == Some(name) { + explicit = Some(*value); + } else { + wildcard = Some(wildcard.unwrap_or(false) || *value); + } } } } - None + explicit.or(wildcard) } fn has_timed_call(&self, source: &str, start: usize, end: usize) -> bool { diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 5cda2f3aafc..021d23f4627 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -639,3 +639,20 @@ always_comb if(done) $finish; endmodule"#) (top Top) (run_to_finish) (assert_eq done 1)) + +(case local_function_shadows_unrelated_timed_task + (source "function.sv" #"package UnrelatedTasks; task tick; #1; endtask endpackage + module Top(input bit clk,output bit q,seen); + function bit tick(); return 1; endfunction + always @(posedge clk) q<=tick(); initial seen=q; + endmodule"#) + (top Top) (set clk 1) (run_until 0) (assert_eq seen 0) (assert_eq q 1)) + +(case explicit_timed_import_overrides_earlier_wildcard + (source "imports.sv" #"package A; task tick; endtask endpackage + package B; task tick; #1; endtask endpackage + module Top(input bit clk,output bit q); import A::*; import B::tick; + always @(posedge clk) begin tick(); q=1; end + endmodule"#) + (top Top) (set clk 1) (run_until 0) (assert_eq q 0) + (set clk 0) (eval) (set clk 1) (run_until 2) (assert_eq q 1)) diff --git a/crates/celox/tests/frontends/systemverilog/suite.rs b/crates/celox/tests/frontends/systemverilog/suite.rs index 60adf337d51..f53aa48eb4f 100644 --- a/crates/celox/tests/frontends/systemverilog/suite.rs +++ b/crates/celox/tests/frontends/systemverilog/suite.rs @@ -18,6 +18,15 @@ impl TimedBackend { .any(|event| matches!(event, RuntimeEvent::Finish)); self.1.extend(events); } + fn settle_checked(&mut self) -> Result<()> { + let already_finished = self.finished(); + self.0.settle()?; + self.capture_events(); + if !already_finished && self.finished() { + return Err("the design finished outside run_to_finish during settling".into()); + } + Ok(()) + } fn finished(&self) -> bool { self.0.is_finished() || self.2 } @@ -63,8 +72,7 @@ impl Backend for TimedBackend { } fn read(&mut self, path: &SignalPath) -> Result<(BigUint, BigUint)> { - self.0.settle()?; - self.capture_events(); + self.settle_checked()?; let signal = signal_of(&self.0, path); Ok(self.0.get_four_state(signal)) } @@ -72,8 +80,7 @@ impl Backend for TimedBackend { /// Settling also resumes the processes the writes woke, as the external /// simulators' settle step does. fn eval_comb(&mut self) -> Result<()> { - self.0.settle()?; - self.capture_events(); + self.settle_checked()?; Ok(()) } @@ -82,8 +89,7 @@ impl Backend for TimedBackend { } fn take_output(&mut self) -> Result { - self.0.settle()?; - self.capture_events(); + self.settle_checked()?; collect_output(std::mem::take(&mut self.1)) } @@ -282,17 +288,29 @@ fn run_to_finish_rejects_a_finish_during_an_earlier_settle() { let go = backend.0.signal("go"); backend.0.set_wide(go, 1u8.into()); match operation { - 0 => backend.eval_comb().unwrap(), + 0 => assert!( + backend + .eval_comb() + .unwrap_err() + .to_string() + .contains("finished outside") + ), 1 => { backend .read(&SignalPath { instances: Vec::new(), name: "done".into(), }) - .unwrap(); + .unwrap_err(); } _ => { - backend.take_output().unwrap(); + assert!( + backend + .take_output() + .unwrap_err() + .to_string() + .contains("finished outside") + ); } } assert!( diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index d315dfd3416..ff52a010c7a 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -137,3 +137,8 @@ sv_backends! { fn printed_finish_notice_is_design_output(sim) { @case "timing::printed_finish_notice_is_design_output"; } fn combinational_finish_ends_timed_execution(sim) { @case "timing::combinational_finish_ends_timed_execution"; } } + +sv_backends! { + fn local_function_shadows_unrelated_timed_task(sim) { @case "timing::local_function_shadows_unrelated_timed_task"; } + fn explicit_timed_import_overrides_earlier_wildcard(sim) { @case "timing::explicit_timed_import_overrides_earlier_wildcard"; } +} From 1f11ed59900d599a4bfe9304115bf3b8adaa1cf2 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 16:20:35 +0900 Subject: [PATCH 16/75] fix(suite): preserve generate names and lexical task imports --- crates/celox-test-suite/src/frontend.rs | 50 ++++++++++ .../celox-test-suite/src/frontend/timed_ff.rs | 96 ++++++++++++++++--- .../src/sv/cases/timing.vtest | 22 +++++ .../tests/frontends/systemverilog/timing.rs | 5 + 4 files changed, 160 insertions(+), 13 deletions(-) diff --git a/crates/celox-test-suite/src/frontend.rs b/crates/celox-test-suite/src/frontend.rs index 94124a49ed5..0d911147f8c 100644 --- a/crates/celox-test-suite/src/frontend.rs +++ b/crates/celox-test-suite/src/frontend.rs @@ -334,6 +334,56 @@ mod timed_staging_tests { std::fs::remove_dir_all(root).unwrap(); } #[test] + #[ignore = "requires Icarus, Verilator and a C++ compiler; frontend lacks implicit generate hierarchy analysis"] + fn ff_staging_preserves_implicit_generate_names() { + let text = r##"(group names (category sequential)) +(case names (source "names.sv" #"module Top(input bit clk,output bit q,y); + always_ff @(posedge clk) q<=1; + if(1) begin bit x;assign x=1;end + assign y=genblk1.x; + endmodule"#)(top Top)(set clk 1)(run_until 0)(assert_eq q 1)(assert_eq y 1))"##; + let case = load_group("names.vtest", text, no_std_library)[0]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../target/generate-name-protocol") + .join(std::process::id().to_string()); + struct NamesFrontend; + impl celox_test_suite::frontend::Frontend for NamesFrontend { + fn source_extension(&self) -> &'static str { + "sv" + } + fn prepare( + &self, + design: &celox_test_suite::Design, + ) -> celox_test_suite::Result { + let frontend = celox_test_suite::sv::verification::SvFrontend; + let mut actual = frontend.prepare(design)?; + // The adapter preserves names even when the frontend cannot + // analyze the original implicit generate hierarchy. + let stub = celox_test_suite::Design::new( + "module Top(input bit clk, output bit q,y); endmodule", + "Top", + ); + actual.info = frontend.prepare(&stub)?.info; + Ok(actual) + } + } + let frontend = NamesFrontend; + let mut icarus = + celox_test_suite::icarus::Icarus::build_script(&frontend, case, &root.join("icarus")) + .unwrap(); + icarus.run_testbench().unwrap(); + let mut verilator = celox_test_suite::verilator::Verilator::build_script( + &frontend, + case, + &root.join("verilator"), + ) + .unwrap(); + verilator.run_testbench().unwrap(); + let log = std::fs::read_to_string(root.join("verilator/protocol.log")).unwrap(); + celox_test_suite::script::sv::check_output(&log, &[]).unwrap(); + std::fs::remove_dir_all(root).unwrap(); + } + #[test] #[ignore = "requires Verilator and a C++ compiler; Icarus rejects deferred assertions"] fn deferred_assertions_retain_staged_edges() { let text = r##"(group deferred (category sequential)) diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index 803ff942fbc..2f69a00561e 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -110,7 +110,9 @@ fn statement_end(source: &str, at: usize) -> Option { let body = statement_end(source, end)?; let next = trivia(source, body); if matches!(keyword, Some("if" | "assert" | "assume")) - && source[next..].starts_with("else") + && sv_words(&source[next..]) + .first() + .is_some_and(|word| word.0 == 0 && word.2 == "else") { statement_end(source, next + 4) } else { @@ -149,6 +151,42 @@ fn statement_end(source: &str, at: usize) -> Option { } } +fn single_generate_body(source: &str, start: usize) -> bool { + let mut at = 0; + let mut last_word = ""; + let mut control_end = None; + while at < start { + if skip_token(source, &mut at) { + continue; + } + if source.as_bytes()[at] == b'(' { + if let Some(end) = parens(source, at) { + control_end = matches!(last_word, "if" | "for").then_some(end); + at = end; + continue; + } + } + if source.as_bytes()[at].is_ascii_alphabetic() || source.as_bytes()[at] == b'_' { + let begin = at; + at += 1; + while at < start + && (source.as_bytes()[at].is_ascii_alphanumeric() || source.as_bytes()[at] == b'_') + { + at += 1; + } + last_word = &source[begin..at]; + control_end = (last_word == "else").then_some(at); + } else { + if !source.as_bytes()[at].is_ascii_whitespace() { + control_end = None; + last_word = ""; + } + at += 1; + } + } + control_end.is_some_and(|end| trivia(source, end) == start) +} + pub(super) fn gated( source: &str, start: usize, @@ -181,15 +219,20 @@ pub(super) fn gated( }; let armed = fresh("armed"); let pending = fresh("pending"); - let scope = fresh("scope"); let package = &names.package; let event = &source[begin + 1..event_end - 1]; - Ok(( - body_end, - format!( - "if (1) begin : {scope}\nbit {armed}=0;\nbit {pending}=0;\nalways @({event} or posedge {package}::started) begin\n if (!{package}::started) {pending}=1;\n else if ({armed} || {pending}) begin\n {pending}=0;\n {body}\n end\n {armed}={package}::started;\nend\nend else begin end" - ), - )) + let staged = format!( + "bit {armed}=0;\nbit {pending}=0;\nalways @({event} or posedge {package}::started) begin\n if (!{package}::started) {pending}=1;\n else if ({armed} || {pending}) begin\n {pending}=0;\n {body}\n end\n {armed}={package}::started;\nend" + ); + // A single generate item needs a block for the additional declarations. + // Reuse that construct's unnamed body rather than inserting another if, + // which would change the user's implicit genblkN numbering. + let staged = if single_generate_body(source, start) { + format!("begin\n{staged}\nend") + } else { + staged + }; + Ok((body_end, staged)) } /// The frontend classifies an ordinary always as FF only when every leaf @@ -333,6 +376,25 @@ fn container_at(source: &str, at: usize) -> String { scope } +// Scope identities include their source offsets so closed sibling blocks +// cannot make their imports visible at a later module item. +fn lexical_scope_at(source: &str, at: usize) -> Vec { + let mut scopes = Vec::new(); + for (start, _, word) in sv_words(&source[..at]) { + match word { + "module" | "interface" | "package" | "begin" | "fork" | "task" | "function" => { + scopes.push(start) + } + "endmodule" | "endinterface" | "endpackage" | "end" | "join" | "join_any" + | "join_none" | "endtask" | "endfunction" => { + scopes.pop(); + } + _ => {} + } + } + scopes +} + impl TaskTiming { pub(super) fn new(sources: &[String]) -> Self { let mut result = Self::default(); @@ -417,8 +479,8 @@ impl TaskTiming { if let Some(value) = self.tasks.get(&format!("{scope}::{name}")) { return Some(*value); } - let mut explicit = None; - let mut wildcard = None; + let call_scope = lexical_scope_at(source, at); + let mut imports: BTreeMap, Option)> = BTreeMap::new(); for (start, end, word) in sv_words(&source[..at]) { if word != "import" { continue; @@ -427,6 +489,11 @@ impl TaskTiming { if !import_scope.is_empty() && import_scope != scope { continue; } + let lexical = lexical_scope_at(source, start); + if !call_scope.starts_with(&lexical) { + continue; + } + let (explicit, wildcard) = imports.entry(lexical.len()).or_default(); let tail = &source[end..]; let clause = &tail[..tail.find(';')?]; let words = sv_words(clause); @@ -437,14 +504,17 @@ impl TaskTiming { if selected == Some(name) || (selected.is_none() && clause.contains('*')) { if let Some(value) = self.tasks.get(&format!("{package}::{name}")) { if selected == Some(name) { - explicit = Some(*value); + *explicit = Some(*value); } else { - wildcard = Some(wildcard.unwrap_or(false) || *value); + *wildcard = Some(wildcard.unwrap_or(false) || *value); } } } } - explicit.or(wildcard) + imports + .into_values() + .rev() + .find_map(|(explicit, wildcard)| explicit.or(wildcard)) } fn has_timed_call(&self, source: &str, start: usize, end: usize) -> bool { diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 021d23f4627..7499491c611 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -656,3 +656,25 @@ endmodule"#) (top Top) (set clk 1) (run_until 0) (assert_eq q 0) (set clk 0) (eval) (set clk 1) (run_until 2) (assert_eq q 1)) + +(case else_prefixed_instance_is_not_an_else_action + (source "elsewhere.sv" #"module elsewhere; endmodule + module Top(input bit clk,en,output bit q); + always_ff @(posedge clk) if(en) q<=1; + elsewhere u(); + endmodule"#) + (top Top) (set en 1) (set clk 1) (run_until 0) (assert_eq q 1)) + +(case nested_imports_do_not_leak_into_module_edge_processes + (source "imports.sv" #"package A; + task automatic tick(output bit value); value=1; endtask + endpackage + package B; + task automatic tick(output bit value); #1 value=1; endtask + endpackage + module Top(input bit clk,output bit q); + import A::tick; + if(1) begin : nested import B::tick; end + always @(posedge clk) tick(q); + endmodule"#) + (top Top) (set clk 1) (run_until 0) (assert_eq q 1)) diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index ff52a010c7a..eb36680e2e6 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -142,3 +142,8 @@ sv_backends! { fn local_function_shadows_unrelated_timed_task(sim) { @case "timing::local_function_shadows_unrelated_timed_task"; } fn explicit_timed_import_overrides_earlier_wildcard(sim) { @case "timing::explicit_timed_import_overrides_earlier_wildcard"; } } + +sv_backends! { + fn else_prefixed_instance_is_not_an_else_action(sim) { @case "timing::else_prefixed_instance_is_not_an_else_action"; } + fn nested_imports_do_not_leak_into_module_edge_processes(sim) { @case "timing::nested_imports_do_not_leak_into_module_edge_processes"; } +} From 488ad2abe32ebdbf4d5cc1afcecea5007ed452dd Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 17:06:35 +0900 Subject: [PATCH 17/75] fix(suite): preserve case arms and adapter macro scopes --- crates/celox-test-suite/src/frontend.rs | 56 ++++++++++++++++++- .../celox-test-suite/src/frontend/timed_ff.rs | 7 ++- crates/celox-test-suite/src/icarus.rs | 2 +- .../src/sv/cases/timing.vtest | 18 ++++++ crates/celox-test-suite/src/verilator.rs | 2 +- .../tests/frontends/systemverilog/timing.rs | 5 ++ 6 files changed, 83 insertions(+), 7 deletions(-) diff --git a/crates/celox-test-suite/src/frontend.rs b/crates/celox-test-suite/src/frontend.rs index 0d911147f8c..0382327d0a5 100644 --- a/crates/celox-test-suite/src/frontend.rs +++ b/crates/celox-test-suite/src/frontend.rs @@ -60,6 +60,7 @@ pub(crate) fn stage( design: &Design, directory: &Path, script: Option<&ScriptCase>, + defines: &[&str], ) -> Result { validate_timed_design(design)?; fs::create_dir_all(directory)?; @@ -75,7 +76,7 @@ pub(crate) fn stage( .map_err(|error| EmissionError(panic_message(error.as_ref())))??; if design.timed { for source in &mut prepared.sources { - *source = expanded_timed_source(source)?; + *source = expanded_timed_source(source, defines)?; } } let task_timing = timed_ff::TaskTiming::new(&prepared.sources); @@ -223,8 +224,15 @@ impl TimedNames { } } -fn expanded_timed_source(source: &str) -> Result { - let syntax = celox_sv_analyzer::syntax::parse_source(source, Path::new("timed.sv"))?; +fn expanded_timed_source(source: &str, defines: &[&str]) -> Result { + let prefix = defines + .iter() + .map(|name| format!("`define {name}\n")) + .collect::(); + let syntax = celox_sv_analyzer::syntax::parse_source( + &format!("{prefix}{source}"), + Path::new("timed.sv"), + )?; let root = (&syntax).into_iter().next().ok_or("empty timed source")?; Ok(syntax .get_str(vec![root]) @@ -384,6 +392,33 @@ mod timed_staging_tests { std::fs::remove_dir_all(root).unwrap(); } #[test] + #[ignore = "requires Icarus, Verilator and a C++ compiler; tests external compilation-unit startup staging"] + fn compilation_unit_callables_retain_staged_edges() { + let text = r##"(group unit (category sequential)) + (case callable (source "unit.sv" #"function bit tick();return 1;endfunction + module Top(input bit clk,output bit q,seen);always @(posedge clk)q<=tick();initial seen=q;endmodule"#) + (top Top)(set clk 1)(run_until 0)(assert_eq seen 0)(assert_eq q 1))"##; + let case = load_group("unit.vtest", text, no_std_library)[0]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../target/unit-callable-protocol") + .join(std::process::id().to_string()); + let frontend = celox_test_suite::sv::verification::SvFrontend; + let mut icarus = + celox_test_suite::icarus::Icarus::build_script(&frontend, case, &root.join("icarus")) + .unwrap(); + icarus.run_testbench().unwrap(); + let mut verilator = celox_test_suite::verilator::Verilator::build_script( + &frontend, + case, + &root.join("verilator"), + ) + .unwrap(); + verilator.run_testbench().unwrap(); + let log = std::fs::read_to_string(root.join("verilator/protocol.log")).unwrap(); + celox_test_suite::script::sv::check_output(&log, &[]).unwrap(); + std::fs::remove_dir_all(root).unwrap(); + } + #[test] #[ignore = "requires Verilator and a C++ compiler; Icarus rejects deferred assertions"] fn deferred_assertions_retain_staged_edges() { let text = r##"(group deferred (category sequential)) @@ -407,3 +442,18 @@ mod timed_staging_tests { std::fs::remove_dir_all(root).unwrap(); } } + +#[cfg(test)] +mod adapter_define_tests { + use super::*; + #[test] + fn timed_macro_expansion_uses_the_adapter_define_set() { + let source = "module Top;\n`ifdef CELOX_SUITE_ICARUS\ninitial q=1;\n`else\ninitial q=0;\n`endif\nendmodule"; + let icarus = expanded_timed_source(source, &["CELOX_SUITE_ICARUS"]).unwrap(); + let other = expanded_timed_source(source, &[]).unwrap(); + assert!(icarus.contains("q=1")); + assert!(!icarus.contains("q=0")); + assert!(other.contains("q=0")); + assert!(!other.contains("q=1")); + } +} diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index 2f69a00561e..fbe9fc83061 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -177,7 +177,9 @@ fn single_generate_body(source: &str, start: usize) -> bool { last_word = &source[begin..at]; control_end = (last_word == "else").then_some(at); } else { - if !source.as_bytes()[at].is_ascii_whitespace() { + if source.as_bytes()[at] == b':' { + control_end = Some(at + 1); + } else if !source.as_bytes()[at].is_ascii_whitespace() { control_end = None; last_word = ""; } @@ -232,7 +234,7 @@ pub(super) fn gated( } else { staged }; - Ok((body_end, staged)) + Ok((body_end, format!("{staged}\n"))) } /// The frontend classifies an ordinary always as FF only when every leaf @@ -515,6 +517,7 @@ impl TaskTiming { .into_values() .rev() .find_map(|(explicit, wildcard)| explicit.or(wildcard)) + .or_else(|| self.tasks.get(&format!("::{name}")).copied()) } fn has_timed_call(&self, source: &str, start: usize, end: usize) -> bool { diff --git a/crates/celox-test-suite/src/icarus.rs b/crates/celox-test-suite/src/icarus.rs index 318685ba76b..8a45208050d 100644 --- a/crates/celox-test-suite/src/icarus.rs +++ b/crates/celox-test-suite/src/icarus.rs @@ -41,7 +41,7 @@ impl Icarus { top, testbench, edges, - } = stage(frontend, design, directory, script)?; + } = stage(frontend, design, directory, script, &["CELOX_SUITE_ICARUS"])?; write_if_changed( &directory.join("vpi_bits.hpp"), include_bytes!("vpi_bits.hpp"), diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 7499491c611..697079fcbb7 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -678,3 +678,21 @@ always @(posedge clk) tick(q); endmodule"#) (top Top) (set clk 1) (run_until 0) (assert_eq q 1)) + +(case single_item_case_generate_ff_is_staged_together + (source "case.sv" #"module Top(input bit clk,output bit q,seen); + localparam MODE=0; + case(MODE) 0:always_ff @(posedge clk)q<=1;default:always_ff @(posedge clk)q<=0;endcase + initial seen=q; + endmodule"#) + (top Top)(set clk 1)(run_until 0)(assert_eq seen 0)(assert_eq q 1)) + +(case timed_expansion_preserves_adapter_macros + (source "macros.sv" #"module Top(output bit q); + `ifdef CELOX_SUITE_ICARUS + initial begin q=1;#1;$finish;end + `else + initial begin q=1;#1;$finish;end + `endif + endmodule"#) + (top Top)(run_to_finish)(assert_eq q 1)) diff --git a/crates/celox-test-suite/src/verilator.rs b/crates/celox-test-suite/src/verilator.rs index 63023805f19..cf8daf421a5 100644 --- a/crates/celox-test-suite/src/verilator.rs +++ b/crates/celox-test-suite/src/verilator.rs @@ -41,7 +41,7 @@ impl Verilator { top, testbench, edges, - } = stage(frontend, design, directory, script)?; + } = stage(frontend, design, directory, script, &[])?; write_if_changed( &directory.join("vpi_bits.hpp"), include_bytes!("vpi_bits.hpp"), diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index eb36680e2e6..861f7e3f61c 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -147,3 +147,8 @@ sv_backends! { fn else_prefixed_instance_is_not_an_else_action(sim) { @case "timing::else_prefixed_instance_is_not_an_else_action"; } fn nested_imports_do_not_leak_into_module_edge_processes(sim) { @case "timing::nested_imports_do_not_leak_into_module_edge_processes"; } } + +sv_backends! { + fn single_item_case_generate_ff_is_staged_together(sim){@case "timing::single_item_case_generate_ff_is_staged_together";} + fn timed_expansion_preserves_adapter_macros(sim){@case "timing::timed_expansion_preserves_adapter_macros";} +} From 7ddff6d55e476e34ab73edaf07de0e4e69004ac2 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 19:00:02 +0900 Subject: [PATCH 18/75] fix(suite): preserve timed callable and harness identities --- crates/celox-runtime/src/simulation.rs | 13 ++++ crates/celox-test-suite/src/frontend.rs | 42 ++++++++++- .../celox-test-suite/src/frontend/timed_ff.rs | 69 +++++++++++++++---- crates/celox-test-suite/src/script/timed.rs | 2 + .../src/sv/cases/timing.vtest | 16 +++++ crates/celox/src/simulation.rs | 45 +++++++++++- crates/celox/tests/systemverilog.rs | 6 ++ 7 files changed, 176 insertions(+), 17 deletions(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 1826f3816aa..4cf98d2eb96 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -343,6 +343,19 @@ impl SimulationState { Ok(()) } + /// Whether a clock/reset differs from the last settled scheduler state. + /// Host reads may have already cleared backend trigger bits. + pub fn has_unsettled_edges(&self, backend: &B) -> bool { + self.topo_signals.iter().any(|(signal, id, _)| { + *id != usize::MAX + && self.edge_triggers( + *id, + self.last_clock_values.contains(*id), + backend.get_as::(*signal) != 0, + ) + }) + } + /// Whether any process is suspended on an event or a condition. pub fn has_waiting_processes(&self) -> bool { !self.waiting.is_empty() diff --git a/crates/celox-test-suite/src/frontend.rs b/crates/celox-test-suite/src/frontend.rs index 0382327d0a5..95c6b4958fe 100644 --- a/crates/celox-test-suite/src/frontend.rs +++ b/crates/celox-test-suite/src/frontend.rs @@ -209,10 +209,18 @@ impl TimedNames { if source[..start].trim_end().ends_with('.') { continue; } + let prefix = source[..start].trim_end(); + let tail = after_trivia(&source[end..]); + let previous_word = sv_words(prefix).last().map(|word| word.2); let replacement = match word { - "celox_suite_timed_control" => &self.package, - "celox_suite_start_design" => &self.start, - "celox_suite_finish_design" => &self.finish, + "celox_suite_timed_control" + if tail.starts_with("::") + || matches!(previous_word, Some("package" | "import")) => + { + &self.package + } + "celox_suite_start_design" if tail.starts_with('(') => &self.start, + "celox_suite_finish_design" if tail.starts_with('(') => &self.finish, _ => continue, }; output.push_str(&source[previous..start]); @@ -419,6 +427,34 @@ mod timed_staging_tests { std::fs::remove_dir_all(root).unwrap(); } #[test] + #[ignore = "requires Icarus, Verilator and a C++ compiler; exercises external declaration staging"] + fn local_declarations_retain_staged_edges() { + let text = r##"(group declarations (category sequential)) + (case local (source "decl.sv" #"module Top(input bit clk,output bit q); + task tick; #1; endtask + always @(posedge clk)begin int tick; q<=1; end endmodule"#) + (top Top)(set clk 1)(run_until 0)(assert_eq q 1))"##; + let case = load_group("decl.vtest", text, no_std_library)[0]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../target/declaration-staging") + .join(std::process::id().to_string()); + let frontend = celox_test_suite::sv::verification::SvFrontend; + let mut icarus = + celox_test_suite::icarus::Icarus::build_script(&frontend, case, &root.join("icarus")) + .unwrap(); + icarus.run_testbench().unwrap(); + let mut verilator = celox_test_suite::verilator::Verilator::build_script( + &frontend, + case, + &root.join("verilator"), + ) + .unwrap(); + verilator.run_testbench().unwrap(); + let log = std::fs::read_to_string(root.join("verilator/protocol.log")).unwrap(); + celox_test_suite::script::sv::check_output(&log, &[]).unwrap(); + std::fs::remove_dir_all(root).unwrap(); + } + #[test] #[ignore = "requires Verilator and a C++ compiler; Icarus rejects deferred assertions"] fn deferred_assertions_retain_staged_edges() { let text = r##"(group deferred (category sequential)) diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index fbe9fc83061..ec27765a852 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -498,17 +498,19 @@ impl TaskTiming { let (explicit, wildcard) = imports.entry(lexical.len()).or_default(); let tail = &source[end..]; let clause = &tail[..tail.find(';')?]; - let words = sv_words(clause); - let Some((_, _, package)) = words.first() else { - continue; - }; - let selected = words.get(1).map(|word| word.2); - if selected == Some(name) || (selected.is_none() && clause.contains('*')) { - if let Some(value) = self.tasks.get(&format!("{package}::{name}")) { - if selected == Some(name) { - *explicit = Some(*value); - } else { - *wildcard = Some(wildcard.unwrap_or(false) || *value); + for item in clause.split(',') { + let words = sv_words(item); + let Some((_, _, package)) = words.first() else { + continue; + }; + let selected = words.get(1).map(|word| word.2); + if selected == Some(name) || (selected.is_none() && item.contains('*')) { + if let Some(value) = self.tasks.get(&format!("{package}::{name}")) { + if selected == Some(name) { + *explicit = Some(*value); + } else { + *wildcard = Some(wildcard.unwrap_or(false) || *value); + } } } } @@ -532,8 +534,51 @@ impl TaskTiming { return false; } let tail = after_trivia(&source[start + word_end..end]); - (tail.starts_with('(') || tail.starts_with(';')) + let prefix = source[start..start + at].trim_end(); + let statement_start = prefix.is_empty() + || prefix.ends_with([';', ')', ':', '.']) + || sv_words(prefix) + .last() + .is_some_and(|word| matches!(word.2, "begin" | "end" | "else")); + (tail.starts_with('(') || (tail.starts_with(';') && statement_start)) && self.resolve(source, start + at, name).unwrap_or(true) }) } } + +#[cfg(test)] +mod callable_analysis_tests { + use super::*; + #[test] + fn local_declarations_are_not_no_argument_task_calls() { + for body in ["int tick; q<=1;", "int value, tick; q<=1;"] { + let source = format!( + "module Top;task tick;#1;endtask always @(posedge clk)begin {body} end endmodule" + ); + let tasks = TaskTiming::new(std::slice::from_ref(&source)); + let at = source.find("always").unwrap() + 6; + assert!(edge_control(&source, at, &tasks), "{body}"); + } + let source = + "module Top;task tick;#1;endtask always @(posedge clk)begin tick; end endmodule" + .to_string(); + let tasks = TaskTiming::new(std::slice::from_ref(&source)); + assert!(!edge_control( + &source, + source.find("always").unwrap() + 6, + &tasks + )); + } + #[test] + fn escaped_callable_names_remain_whole_tokens() { + let source = r"task \pause.task ; #1; endtask"; + assert_eq!( + sv_words(source) + .iter() + .filter(|x| x.2.starts_with('\\')) + .map(|x| x.2) + .collect::>(), + vec![r"\pause.task"] + ); + } +} diff --git a/crates/celox-test-suite/src/script/timed.rs b/crates/celox-test-suite/src/script/timed.rs index 502ac839223..ddab0c4f9a7 100644 --- a/crates/celox-test-suite/src/script/timed.rs +++ b/crates/celox-test-suite/src/script/timed.rs @@ -52,10 +52,12 @@ pub(crate) fn sv_words(source: &str) -> Vec<(usize, usize, &str)> { } } b'\\' => { + let start = at; at += 1; while at < bytes.len() && !bytes[at].is_ascii_whitespace() { at += 1; } + words.push((start, at, &source[start..at])); } b'a'..=b'z' | b'A'..=b'Z' | b'_' | b'$' => { let start = at; diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 697079fcbb7..4df2eb2e509 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -696,3 +696,19 @@ `endif endmodule"#) (top Top)(run_to_finish)(assert_eq q 1)) + +(case multiple_import_items_preserve_untimed_edges + (source "imports.sv" #"package A; task other; #1; endtask endpackage + package B; int result; task tick; result=1; endtask endpackage + module Top(input bit clk,output int q); import A::other, B::tick; + always @(posedge clk) tick(); assign q=B::result; endmodule"#) + (top Top)(set clk 1)(run_until 0)(assert_eq q 1)) +(case escaped_timed_tasks_do_not_replay_setup_edges + (source "escaped.sv" #"module Top(input bit clk,output bit q); + task \pause.task ; #1 q=1; endtask + always @(posedge clk) \pause.task ; endmodule"#) + (top Top)(set clk 1)(run_until 1)(assert_eq q 0) + (set clk 0)(eval)(set clk 1)(run_until 2)(assert_eq q 1)) +(case control_names_do_not_rewrite_the_dut_type + (source "collision.sv" #"module celox_suite_timed_control(output bit q);initial q=1;endmodule"#) + (top celox_suite_timed_control)(run_until 0)(assert_eq q 1)) diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 40820ae6ac7..fc929d6c43a 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -461,9 +461,20 @@ impl Simulation { /// follow, as [`Self::step`] does before advancing. Time does not /// advance. pub fn settle(&mut self) -> Result<(), RuntimeErrorCode> { - self.simulator.eval_comb()?; let time = self.state.time(); - self.state.settle_at(&mut self.simulator, time)?; + if self.simulator.dirty + || !self.simulator.backend.get_triggered_bits().is_empty() + || self.state.has_unsettled_edges(&self.simulator.backend) + || self + .state + .next_event_time() + .is_some_and(|next| next <= time) + { + self.settle_host_writes()?; + self.state.settle_at(&mut self.simulator, time)?; + } else { + self.state.poll_waiting(&mut self.simulator)?; + } Ok(()) } @@ -1274,3 +1285,33 @@ mod finish_and_cotrigger_tests { check(Simulation::new(builder().build_native().unwrap())); } } + +#[cfg(all(test, feature = "systemverilog"))] +mod idle_settle_tests { + use super::*; + #[test] + fn settled_reads_do_not_repeat_comb_side_effects() { + fn check(mut sim: Simulation) { + let a = sim.signal("a"); + sim.set_wide(a, 1u8.into()); + sim.run_until(0).unwrap(); + assert!( + sim.drain_runtime_events() + .iter() + .any(|e| matches!(e,crate::RuntimeEvent::Display { message } if message=="x")) + ); + sim.settle().unwrap(); + sim.settle().unwrap(); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + assert!(sim.drain_runtime_events().is_empty()); + } + let source = "module Top(input bit a,output bit q);always @* begin q=a;if(a)$display(\"x\");end endmodule"; + let builder = + || Simulator::from_sv_sources(vec![(source, std::path::Path::new("settle.sv"))], "Top"); + check(Simulation::new(builder().build_interpreter().unwrap())); + check(Simulation::new(builder().build_cranelift().unwrap())); + check(Simulation::new(builder().build_wasm().unwrap())); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(builder().build_native().unwrap())); + } +} diff --git a/crates/celox/tests/systemverilog.rs b/crates/celox/tests/systemverilog.rs index b33511146ab..c2d242f256b 100644 --- a/crates/celox/tests/systemverilog.rs +++ b/crates/celox/tests/systemverilog.rs @@ -215,3 +215,9 @@ fn simulates_systemverilog_always_ff() { sim.tick(clk).unwrap(); assert_eq!(sim.get(q), 1u8.into()); } + +sv_backends! { + fn multiple_import_items_preserve_untimed_edges(sim) { @case "timing::multiple_import_items_preserve_untimed_edges"; } + fn escaped_timed_tasks_do_not_replay_setup_edges(sim) { @case "timing::escaped_timed_tasks_do_not_replay_setup_edges"; } + fn control_names_do_not_rewrite_the_dut_type(sim) { @case "timing::control_names_do_not_rewrite_the_dut_type"; } +} From bcda630b3433eb509e43e5338a6fa3fa09d6ecfc Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 02:51:42 +0900 Subject: [PATCH 19/75] fix(suite): preserve generate scopes, attributes and source line numbers --- crates/celox-test-suite/src/frontend.rs | 2 +- .../celox-test-suite/src/frontend/timed_ff.rs | 43 +++++++++++++------ .../src/sv/cases/timing.vtest | 22 ++++++++++ crates/celox/src/simulation.rs | 28 ++++++++++++ crates/celox/tests/systemverilog.rs | 6 +++ 5 files changed, 88 insertions(+), 13 deletions(-) diff --git a/crates/celox-test-suite/src/frontend.rs b/crates/celox-test-suite/src/frontend.rs index 95c6b4958fe..04503ca7fec 100644 --- a/crates/celox-test-suite/src/frontend.rs +++ b/crates/celox-test-suite/src/frontend.rs @@ -238,7 +238,7 @@ fn expanded_timed_source(source: &str, defines: &[&str]) -> Result { .map(|name| format!("`define {name}\n")) .collect::(); let syntax = celox_sv_analyzer::syntax::parse_source( - &format!("{prefix}{source}"), + &format!("{prefix}`line 1 \"timed.sv\" 0\n{source}"), Path::new("timed.sv"), )?; let root = (&syntax).into_iter().next().ok_or("empty timed source")?; diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index ec27765a852..82392045325 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -161,6 +161,10 @@ fn single_generate_body(source: &str, start: usize) -> bool { } if source.as_bytes()[at] == b'(' { if let Some(end) = parens(source, at) { + if source[at..].starts_with("(*") { + at = end; + continue; + } control_end = matches!(last_word, "if" | "for").then_some(end); at = end; continue; @@ -186,7 +190,14 @@ fn single_generate_body(source: &str, start: usize) -> bool { at += 1; } } - control_end.is_some_and(|end| trivia(source, end) == start) + control_end.is_some_and(|end| { + let mut at = trivia(source, end); + while source[at..].starts_with("(*") { + let Some(end) = parens(source, at) else { return false; }; + at = trivia(source, end); + } + at == start + }) } pub(super) fn gated( @@ -355,7 +366,7 @@ fn has_timing(source: &str) -> bool { #[derive(Default)] pub(super) struct TaskTiming { - tasks: BTreeMap, + tasks: BTreeMap<(String, Vec, String), bool>, } fn container_at(source: &str, at: usize) -> String { @@ -397,6 +408,13 @@ fn lexical_scope_at(source: &str, at: usize) -> Vec { scopes } +fn callable_key(source: &str, at: usize, name: &str) -> (String, Vec, String) { + let container = container_at(source, at); + let mut scope = lexical_scope_at(source, at); + if !container.is_empty() && !scope.is_empty() { scope.remove(0); } + (container, scope, name.to_owned()) +} + impl TaskTiming { pub(super) fn new(sources: &[String]) -> Self { let mut result = Self::default(); @@ -414,7 +432,7 @@ impl TaskTiming { if let Some((_, _, name)) = sv_words(&header[..name_end]).last() { result .tasks - .insert(format!("{}::{name}", container_at(source, *start)), false); + .insert(callable_key(source, *start, name), false); } continue; } @@ -432,8 +450,7 @@ impl TaskTiming { else { continue; }; - let scope = container_at(source, *start); - let key = format!("{scope}::{name}"); + let key = callable_key(source, *start, name); let header_end = source[*end..*body_end] .find(';') .map_or(*end, |offset| end + offset + 1); @@ -461,7 +478,7 @@ impl TaskTiming { let prefix = source[..at].trim_end(); if let Some(prefix) = prefix.strip_suffix("::") { let package = sv_words(prefix).last()?.2; - return self.tasks.get(&format!("{package}::{name}")).copied(); + return self.tasks.get(&(package.to_owned(), Vec::new(), name.to_owned())).copied(); } if let Some(prefix) = prefix.strip_suffix('.') { let instance = sv_words(prefix).last()?.2; @@ -469,7 +486,7 @@ impl TaskTiming { let words = sv_words(&source[..at]); for pair in words.windows(2) { if pair[1].2 == instance && container_at(source, pair[0].0) == scope { - if let Some(value) = self.tasks.get(&format!("{}::{name}", pair[0].2)) { + if let Some(value) = self.tasks.get(&(pair[0].2.to_owned(), Vec::new(), name.to_owned())) { return Some(*value); } } @@ -478,8 +495,10 @@ impl TaskTiming { return None; } let scope = container_at(source, at); - if let Some(value) = self.tasks.get(&format!("{scope}::{name}")) { - return Some(*value); + let mut key = callable_key(source, at, name); + loop { + if let Some(value) = self.tasks.get(&key) { return Some(*value); } + if key.1.pop().is_none() { break; } } let call_scope = lexical_scope_at(source, at); let mut imports: BTreeMap, Option)> = BTreeMap::new(); @@ -505,7 +524,7 @@ impl TaskTiming { }; let selected = words.get(1).map(|word| word.2); if selected == Some(name) || (selected.is_none() && item.contains('*')) { - if let Some(value) = self.tasks.get(&format!("{package}::{name}")) { + if let Some(value) = self.tasks.get(&(package.to_owned(), Vec::new(), name.to_owned())) { if selected == Some(name) { *explicit = Some(*value); } else { @@ -519,7 +538,7 @@ impl TaskTiming { .into_values() .rev() .find_map(|(explicit, wildcard)| explicit.or(wildcard)) - .or_else(|| self.tasks.get(&format!("::{name}")).copied()) + .or_else(|| self.tasks.get(&(String::new(), Vec::new(), name.to_owned())).copied()) } fn has_timed_call(&self, source: &str, start: usize, end: usize) -> bool { @@ -529,7 +548,7 @@ impl TaskTiming { if !self .tasks .keys() - .any(|key| key.ends_with(&format!("::{name}"))) + .any(|key| key.2 == *name) { return false; } diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 4df2eb2e509..430d63405d0 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -712,3 +712,25 @@ (case control_names_do_not_rewrite_the_dut_type (source "collision.sv" #"module celox_suite_timed_control(output bit q);initial q=1;endmodule"#) (top celox_suite_timed_control)(run_until 0)(assert_eq q 1)) + +(case attributes_preserve_single_generate_arms + (source "attributes.sv" #"module Top(input bit clk,output bit q,r); + if(0) always_ff @(posedge clk)q<=0; + else (* keep *) always_ff @(posedge clk)q<=1; + case(0) + 0: (* keep *) always_ff @(posedge clk)r<=1; + default: (* keep *) always_ff @(posedge clk)r<=0; + endcase endmodule"#) + (top Top)(set clk 1)(run_until 0)(assert_eq q 1)(assert_eq r 1)) +(case adapter_defines_preserve_line_macros + (source "line.sv" #"module Top(output int q); +initial q=`__LINE__; +endmodule"#) + (top Top)(run_until 0)(assert_eq q 2)) +(case callable_timing_keeps_generate_scope + (source "scopes.sv" #"module Top(input bit clk,output bit q,r); + if(1) begin:untimed task tick;q=1;endtask always @(posedge clk)tick();end + if(1) begin:timed task tick;#1 r=1;endtask always @(posedge clk)tick();end + endmodule"#) + (top Top)(set clk 1)(run_until 1)(assert_eq q 1)(assert_eq r 0) + (set clk 0)(eval)(set clk 1)(run_until 2)(assert_eq r 1)) diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 380bcc70185..15dbf53d7d0 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -471,6 +471,9 @@ impl Simulation { .is_some_and(|next| next <= time) { self.settle_host_writes()?; + while self.state.next_event_time().is_some_and(|next| next <= time) { + self.state.step(&mut self.simulator)?; + } self.state.settle_at(&mut self.simulator, time)?; } else { self.state.poll_waiting(&mut self.simulator)?; @@ -1421,3 +1424,28 @@ mod direct_finish_tests { check(Simulation::new(builder().build_native().unwrap())); } } + +#[cfg(all(test, feature="systemverilog"))] +mod current_time_settle_tests { + use super::*; + #[test] + fn settle_consumes_current_time_clock_events() { + fn check(mut sim:Simulation) { + sim.run_until(0).unwrap(); + sim.schedule("clk",0,1).unwrap(); + sim.settle().unwrap(); + assert_eq!(sim.get(sim.signal("q")),1u8.into()); + assert_eq!(sim.time(),0); + assert_eq!(sim.next_event_time(),None); + sim.settle().unwrap(); + assert_eq!(sim.get(sim.signal("q")),1u8.into()); + } + let source="module Top(input bit clk,output bit[7:0]q);always @(posedge clk)q<=q+1;endmodule"; + let builder=||Simulator::from_sv_sources(vec![(source,std::path::Path::new("settle.sv"))],"Top"); + check(Simulation::new(builder().build_interpreter().unwrap())); + check(Simulation::new(builder().build_cranelift().unwrap())); + check(Simulation::new(builder().build_wasm().unwrap())); + #[cfg(any(target_arch="x86_64",target_arch="aarch64"))] + check(Simulation::new(builder().build_native().unwrap())); + } +} diff --git a/crates/celox/tests/systemverilog.rs b/crates/celox/tests/systemverilog.rs index c2d242f256b..9e826c9263e 100644 --- a/crates/celox/tests/systemverilog.rs +++ b/crates/celox/tests/systemverilog.rs @@ -221,3 +221,9 @@ sv_backends! { fn escaped_timed_tasks_do_not_replay_setup_edges(sim) { @case "timing::escaped_timed_tasks_do_not_replay_setup_edges"; } fn control_names_do_not_rewrite_the_dut_type(sim) { @case "timing::control_names_do_not_rewrite_the_dut_type"; } } + +sv_backends! { + fn attributes_preserve_single_generate_arms(sim) { @case "timing::attributes_preserve_single_generate_arms"; } + fn adapter_defines_preserve_line_macros(sim) { @case "timing::adapter_defines_preserve_line_macros"; } + fn callable_timing_keeps_generate_scope(sim) { @case "timing::callable_timing_keeps_generate_scope"; } +} From b02f9a0a20d34a26086198e943a00d21a4f24d17 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 02:54:47 +0900 Subject: [PATCH 20/75] fix(suite): avoid an idle evaluation after draining current events --- crates/celox/src/simulation.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 6b50e47ff38..6324054c8bc 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -472,10 +472,14 @@ impl Simulation { .is_some_and(|next| next <= time) { self.settle_host_writes()?; + let mut drained = false; while self.state.next_event_time().is_some_and(|next| next <= time) { self.state.step(&mut self.simulator)?; + drained = true; + } + if !drained { + self.state.settle_at(&mut self.simulator, time)?; } - self.state.settle_at(&mut self.simulator, time)?; } else { self.state.poll_waiting(&mut self.simulator)?; } From 25ebe05bd35a6bbfcf79f93f8d274a6c779dd966 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 03:00:27 +0900 Subject: [PATCH 21/75] fix(suite): adapt scoped callable keys and byte output assertions --- .../celox-test-suite/src/frontend/timed_ff.rs | 43 +++++++++---- crates/celox/src/simulation.rs | 60 ++++++++++--------- 2 files changed, 62 insertions(+), 41 deletions(-) diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index 82392045325..2d8109c9253 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -193,7 +193,9 @@ fn single_generate_body(source: &str, start: usize) -> bool { control_end.is_some_and(|end| { let mut at = trivia(source, end); while source[at..].starts_with("(*") { - let Some(end) = parens(source, at) else { return false; }; + let Some(end) = parens(source, at) else { + return false; + }; at = trivia(source, end); } at == start @@ -411,7 +413,9 @@ fn lexical_scope_at(source: &str, at: usize) -> Vec { fn callable_key(source: &str, at: usize, name: &str) -> (String, Vec, String) { let container = container_at(source, at); let mut scope = lexical_scope_at(source, at); - if !container.is_empty() && !scope.is_empty() { scope.remove(0); } + if !container.is_empty() && !scope.is_empty() { + scope.remove(0); + } (container, scope, name.to_owned()) } @@ -478,7 +482,10 @@ impl TaskTiming { let prefix = source[..at].trim_end(); if let Some(prefix) = prefix.strip_suffix("::") { let package = sv_words(prefix).last()?.2; - return self.tasks.get(&(package.to_owned(), Vec::new(), name.to_owned())).copied(); + return self + .tasks + .get(&(package.to_string(), Vec::new(), name.to_owned())) + .copied(); } if let Some(prefix) = prefix.strip_suffix('.') { let instance = sv_words(prefix).last()?.2; @@ -486,7 +493,10 @@ impl TaskTiming { let words = sv_words(&source[..at]); for pair in words.windows(2) { if pair[1].2 == instance && container_at(source, pair[0].0) == scope { - if let Some(value) = self.tasks.get(&(pair[0].2.to_owned(), Vec::new(), name.to_owned())) { + if let Some(value) = + self.tasks + .get(&(pair[0].2.to_owned(), Vec::new(), name.to_owned())) + { return Some(*value); } } @@ -497,8 +507,12 @@ impl TaskTiming { let scope = container_at(source, at); let mut key = callable_key(source, at, name); loop { - if let Some(value) = self.tasks.get(&key) { return Some(*value); } - if key.1.pop().is_none() { break; } + if let Some(value) = self.tasks.get(&key) { + return Some(*value); + } + if key.1.pop().is_none() { + break; + } } let call_scope = lexical_scope_at(source, at); let mut imports: BTreeMap, Option)> = BTreeMap::new(); @@ -524,7 +538,10 @@ impl TaskTiming { }; let selected = words.get(1).map(|word| word.2); if selected == Some(name) || (selected.is_none() && item.contains('*')) { - if let Some(value) = self.tasks.get(&(package.to_owned(), Vec::new(), name.to_owned())) { + if let Some(value) = + self.tasks + .get(&(package.to_string(), Vec::new(), name.to_owned())) + { if selected == Some(name) { *explicit = Some(*value); } else { @@ -538,18 +555,18 @@ impl TaskTiming { .into_values() .rev() .find_map(|(explicit, wildcard)| explicit.or(wildcard)) - .or_else(|| self.tasks.get(&(String::new(), Vec::new(), name.to_owned())).copied()) + .or_else(|| { + self.tasks + .get(&(String::new(), Vec::new(), name.to_owned())) + .copied() + }) } fn has_timed_call(&self, source: &str, start: usize, end: usize) -> bool { sv_words(&source[start..end]) .iter() .any(|(at, word_end, name)| { - if !self - .tasks - .keys() - .any(|key| key.2 == *name) - { + if !self.tasks.keys().any(|key| key.2 == *name) { return false; } let tail = after_trivia(&source[start + word_end..end]); diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 6324054c8bc..7e502b67ec6 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -473,7 +473,11 @@ impl Simulation { { self.settle_host_writes()?; let mut drained = false; - while self.state.next_event_time().is_some_and(|next| next <= time) { + while self + .state + .next_event_time() + .is_some_and(|next| next <= time) + { self.state.step(&mut self.simulator)?; drained = true; } @@ -1497,11 +1501,9 @@ mod idle_settle_tests { let a = sim.signal("a"); sim.set_wide(a, 1u8.into()); sim.run_until(0).unwrap(); - assert!( - sim.drain_runtime_events() - .iter() - .any(|e| matches!(e,crate::RuntimeEvent::Display { message } if message=="x")) - ); + assert!(sim.drain_runtime_events().iter().any( + |e| matches!(e,crate::RuntimeEvent::Display { message } if message.as_slice()==b"x") + )); sim.settle().unwrap(); sim.settle().unwrap(); assert_eq!(sim.get(sim.signal("q")), 1u8.into()); @@ -1620,27 +1622,29 @@ mod direct_finish_tests { } } -#[cfg(all(test, feature="systemverilog"))] +#[cfg(all(test, feature = "systemverilog"))] mod current_time_settle_tests { - use super::*; - #[test] - fn settle_consumes_current_time_clock_events() { - fn check(mut sim:Simulation) { - sim.run_until(0).unwrap(); - sim.schedule("clk",0,1).unwrap(); - sim.settle().unwrap(); - assert_eq!(sim.get(sim.signal("q")),1u8.into()); - assert_eq!(sim.time(),0); - assert_eq!(sim.next_event_time(),None); - sim.settle().unwrap(); - assert_eq!(sim.get(sim.signal("q")),1u8.into()); - } - let source="module Top(input bit clk,output bit[7:0]q);always @(posedge clk)q<=q+1;endmodule"; - let builder=||Simulator::from_sv_sources(vec![(source,std::path::Path::new("settle.sv"))],"Top"); - check(Simulation::new(builder().build_interpreter().unwrap())); - check(Simulation::new(builder().build_cranelift().unwrap())); - check(Simulation::new(builder().build_wasm().unwrap())); - #[cfg(any(target_arch="x86_64",target_arch="aarch64"))] - check(Simulation::new(builder().build_native().unwrap())); - } + use super::*; + #[test] + fn settle_consumes_current_time_clock_events() { + fn check(mut sim: Simulation) { + sim.run_until(0).unwrap(); + sim.schedule("clk", 0, 1).unwrap(); + sim.settle().unwrap(); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + assert_eq!(sim.time(), 0); + assert_eq!(sim.next_event_time(), None); + sim.settle().unwrap(); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + } + let source = + "module Top(input bit clk,output bit[7:0]q);always @(posedge clk)q<=q+1;endmodule"; + let builder = + || Simulator::from_sv_sources(vec![(source, std::path::Path::new("settle.sv"))], "Top"); + check(Simulation::new(builder().build_interpreter().unwrap())); + check(Simulation::new(builder().build_cranelift().unwrap())); + check(Simulation::new(builder().build_wasm().unwrap())); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(builder().build_native().unwrap())); + } } From 504ba1903fcd26323f79ce85f570c5e8c59704b2 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 03:01:36 +0900 Subject: [PATCH 22/75] style: format byte-output merge resolutions --- crates/celox-test-suite/src/script/sv.rs | 23 +++++++++++++++---- .../frontends/systemverilog/processes.rs | 12 +++++++--- .../systemverilog/system_functions.rs | 4 +++- 3 files changed, 30 insertions(+), 9 deletions(-) diff --git a/crates/celox-test-suite/src/script/sv.rs b/crates/celox-test-suite/src/script/sv.rs index bd6301616e0..2a4e4b4b054 100644 --- a/crates/celox-test-suite/src/script/sv.rs +++ b/crates/celox-test-suite/src/script/sv.rs @@ -160,9 +160,12 @@ fn design_output(text: &[u8], sources: &[String]) -> Vec { let mut output = Vec::new(); for chunk in text.split_inclusive(|byte| *byte == b'\n') { let line = chunk.strip_suffix(b"\n").unwrap_or(chunk); - let notice = std::str::from_utf8(line).ok() + let notice = std::str::from_utf8(line) + .ok() .is_some_and(|line| is_source_finish_notice(line, sources)); - if !notice { output.extend_from_slice(chunk); } + if !notice { + output.extend_from_slice(chunk); + } } output } @@ -1156,7 +1159,10 @@ mod tests { #[test] fn finish_notices_are_not_design_output() { let sources = vec!["timed_control.sv".to_string()]; - for log in [b"done\ntimed_control.sv:3: $finish called at 5 (1ns)\n".as_slice(), b"done\n- timed_control.sv:3: Verilog $finish\n"] { + for log in [ + b"done\ntimed_control.sv:3: $finish called at 5 (1ns)\n".as_slice(), + b"done\n- timed_control.sv:3: Verilog $finish\n", + ] { assert_eq!(design_output(log, &sources), b"done\n"); } let printed = b"\x80\xffsource_0.sv:3: $finish called at 5 (1ns)\n"; @@ -1259,11 +1265,18 @@ mod tests { #[test] fn checks_non_utf8_output_without_replacement() { assert_eq!( - check_output(b"\x80\xff\0\n@suite output 80ff00 here\n\n@suite end\n", &[]), + check_output( + b"\x80\xff\0\n@suite output 80ff00 here\n\n@suite end\n", + &[] + ), Ok(()) ); assert!( - check_output(b"\xef\xbf\xbd\xff\0\n@suite output 80ff00 here\n\n@suite end\n", &[]).is_err() + check_output( + b"\xef\xbf\xbd\xff\0\n@suite output 80ff00 here\n\n@suite end\n", + &[] + ) + .is_err() ); let text = testbench( &case("(tick clk) (expect_output (bytes 128 255 0))"), diff --git a/crates/celox/tests/frontends/systemverilog/processes.rs b/crates/celox/tests/frontends/systemverilog/processes.rs index 96d9dbc0622..ecb45f72828 100644 --- a/crates/celox/tests/frontends/systemverilog/processes.rs +++ b/crates/celox/tests/frontends/systemverilog/processes.rs @@ -39,8 +39,12 @@ fn displays(sim: &mut Simulation) -> Vec<(u64, String)> { while let Some(time) = sim.step().unwrap() { for event in sim.drain_runtime_events() { match event { - RuntimeEvent::Display { message } => lines.push((time, String::from_utf8(message).expect("UTF-8 test output"))), - RuntimeEvent::Write { message } => lines.push((time, String::from_utf8(message).expect("UTF-8 test output"))), + RuntimeEvent::Display { message } => { + lines.push((time, String::from_utf8(message).expect("UTF-8 test output"))) + } + RuntimeEvent::Write { message } => { + lines.push((time, String::from_utf8(message).expect("UTF-8 test output"))) + } RuntimeEvent::Finish => {} other => panic!("unexpected runtime event {other:?}"), } @@ -794,7 +798,9 @@ fn events_between_cascaded_register_updates_wake_waiters() { .drain_runtime_events() .into_iter() .filter_map(|event| match event { - RuntimeEvent::Display { message } => Some(String::from_utf8(message).expect("UTF-8 test output")), + RuntimeEvent::Display { message } => { + Some(String::from_utf8(message).expect("UTF-8 test output")) + } _ => None, }) .collect(); diff --git a/crates/celox/tests/frontends/systemverilog/system_functions.rs b/crates/celox/tests/frontends/systemverilog/system_functions.rs index 7d32ff73206..1b62c423507 100644 --- a/crates/celox/tests/frontends/systemverilog/system_functions.rs +++ b/crates/celox/tests/frontends/systemverilog/system_functions.rs @@ -1147,7 +1147,9 @@ fn finish_in_an_initial_block_ends_the_simulation() { assert_eq!( sim.drain_runtime_events(), vec![ - celox::RuntimeEvent::Display { message: b"before".to_vec() }, + celox::RuntimeEvent::Display { + message: b"before".to_vec() + }, celox::RuntimeEvent::Finish, ], ); From 803f117db3c872d31ca533a1906cb56509ad997d Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 03:41:11 +0900 Subject: [PATCH 23/75] fix(suite): retain FF attributes and predefine adapter macros without source shifts --- crates/celox-sv-analyzer/src/syntax.rs | 17 +++++++++- crates/celox-test-suite/src/frontend.rs | 16 +++++----- .../celox-test-suite/src/frontend/timed_ff.rs | 31 +++++++++++++++++-- 3 files changed, 51 insertions(+), 13 deletions(-) diff --git a/crates/celox-sv-analyzer/src/syntax.rs b/crates/celox-sv-analyzer/src/syntax.rs index 0f11640e107..8dca2a6d482 100644 --- a/crates/celox-sv-analyzer/src/syntax.rs +++ b/crates/celox-sv-analyzer/src/syntax.rs @@ -9,7 +9,22 @@ use crate::AnalyzerError; /// Parse a SystemVerilog source string into an `sv-parser` syntax tree. pub fn parse_source(code: &str, path: &Path) -> Result { - let defines: Defines = HashMap::>::default(); + parse_source_with_defines(code, path, &[]) +} + +/// Parse with predefined empty macros without adding lines to the source. +pub fn parse_source_with_defines( + code: &str, + path: &Path, + names: &[&str], +) -> Result { + let mut defines: Defines = HashMap::default(); + for name in names { + defines.insert( + (*name).to_owned(), + Some(Define::new((*name).to_owned(), Vec::new(), None)), + ); + } let includes: Vec<&Path> = Vec::new(); let (syntax_tree, _) = parse_sv_str(code, path, &defines, &includes, true, false) .map_err(|error| AnalyzerError::Parse(error.to_string()))?; diff --git a/crates/celox-test-suite/src/frontend.rs b/crates/celox-test-suite/src/frontend.rs index ddc38d1e835..b369f0655d2 100644 --- a/crates/celox-test-suite/src/frontend.rs +++ b/crates/celox-test-suite/src/frontend.rs @@ -233,13 +233,10 @@ impl TimedNames { } fn expanded_timed_source(source: &str, defines: &[&str]) -> Result { - let prefix = defines - .iter() - .map(|name| format!("`define {name}\n")) - .collect::(); - let syntax = celox_sv_analyzer::syntax::parse_source( - &format!("{prefix}`line 1 \"timed.sv\" 0\n{source}"), + let syntax = celox_sv_analyzer::syntax::parse_source_with_defines( + source, Path::new("timed.sv"), + defines, )?; let root = (&syntax).into_iter().next().ok_or("empty timed source")?; Ok(syntax @@ -265,9 +262,10 @@ fn timed_content(source: &str, names: &TimedNames, tasks: &timed_ff::TaskTiming) continue; } if word == "always_ff" || (word == "always" && timed_ff::edge_control(source, end, tasks)) { - let (body_end, replacement) = timed_ff::gated(source, start, end, names, tasks)?; - output.push_str(&source[previous..start]); - output.push_str(&timed_ff::in_macro(source, start, replacement)); + let (replacement_start, body_end, replacement) = + timed_ff::gated(source, start, end, names, tasks)?; + output.push_str(&source[previous..replacement_start]); + output.push_str(&timed_ff::in_macro(source, replacement_start, replacement)); previous = body_end; continue; } diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index 2d8109c9253..b0244013151 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -202,13 +202,36 @@ fn single_generate_body(source: &str, start: usize) -> bool { }) } +// Keep attributes on the generated always item, inside a generated block +// when the original listener was a single generate arm. +fn attributes_start(source: &str, start: usize) -> usize { + let mut at = 0; + let mut attributes = start; + while at < start { + at = trivia(source, at); + if at >= start { + break; + } + if source[at..].starts_with("(*") { + attributes = attributes.min(at); + at = parens(source, at).expect("parsed attribute"); + } else { + attributes = start; + if !skip_token(source, &mut at) { + at += 1; + } + } + } + attributes +} + pub(super) fn gated( source: &str, start: usize, end: usize, names: &TimedNames, tasks: &TaskTiming, -) -> Result<(usize, String)> { +) -> Result<(usize, usize, String)> { let at = trivia(source, end); if source.as_bytes().get(at) != Some(&b'@') { return Err("timed always_ff requires an explicit event control".into()); @@ -236,8 +259,10 @@ pub(super) fn gated( let pending = fresh("pending"); let package = &names.package; let event = &source[begin + 1..event_end - 1]; + let replacement_start = attributes_start(source, start); + let attributes = &source[replacement_start..start]; let staged = format!( - "bit {armed}=0;\nbit {pending}=0;\nalways @({event} or posedge {package}::started) begin\n if (!{package}::started) {pending}=1;\n else if ({armed} || {pending}) begin\n {pending}=0;\n {body}\n end\n {armed}={package}::started;\nend" + "bit {armed}=0;\nbit {pending}=0;\n{attributes}always @({event} or posedge {package}::started) begin\n if (!{package}::started) {pending}=1;\n else if ({armed} || {pending}) begin\n {pending}=0;\n {body}\n end\n {armed}={package}::started;\nend" ); // A single generate item needs a block for the additional declarations. // Reuse that construct's unnamed body rather than inserting another if, @@ -247,7 +272,7 @@ pub(super) fn gated( } else { staged }; - Ok((body_end, format!("{staged}\n"))) + Ok((replacement_start, body_end, format!("{staged}\n"))) } /// The frontend classifies an ordinary always as FF only when every leaf From 5226c512aa60f782e3a376665513dfff5d74b9d0 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 05:00:31 +0900 Subject: [PATCH 24/75] fix(suite): retain source identities and reject early finish and buffered fatal events --- crates/celox-test-suite/src/frontend.rs | 27 +++-- .../celox-test-suite/src/frontend/timed_ff.rs | 2 +- .../src/sv/cases/timing.vtest | 9 ++ .../tests/frontends/systemverilog/suite.rs | 100 +++++++++++++++++- crates/celox/tests/systemverilog.rs | 5 + 5 files changed, 126 insertions(+), 17 deletions(-) diff --git a/crates/celox-test-suite/src/frontend.rs b/crates/celox-test-suite/src/frontend.rs index b369f0655d2..281e4d2af40 100644 --- a/crates/celox-test-suite/src/frontend.rs +++ b/crates/celox-test-suite/src/frontend.rs @@ -75,8 +75,12 @@ pub(crate) fn stage( std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| frontend.prepare(design))) .map_err(|error| EmissionError(panic_message(error.as_ref())))??; if design.timed { - for source in &mut prepared.sources { - *source = expanded_timed_source(source, defines)?; + for (index, source) in prepared.sources.iter_mut().enumerate() { + let path = design + .sources + .get(index) + .map_or(Path::new("timed.sv"), |source| source.path.as_path()); + *source = expanded_timed_source(source, defines, path)?; } } let task_timing = timed_ff::TaskTiming::new(&prepared.sources); @@ -175,7 +179,11 @@ struct TimedNames { fn timed_names(sources: &[String]) -> TimedNames { let words = sources .iter() - .flat_map(|source| sv_words(source).into_iter().map(|(_, _, word)| word)) + .flat_map(|source| { + sv_words(source) + .into_iter() + .map(|(_, _, word)| word.strip_prefix('\\').unwrap_or(word)) + }) .collect::>(); for suffix in 0u64.. { let name = |base: &str| { @@ -232,12 +240,8 @@ impl TimedNames { } } -fn expanded_timed_source(source: &str, defines: &[&str]) -> Result { - let syntax = celox_sv_analyzer::syntax::parse_source_with_defines( - source, - Path::new("timed.sv"), - defines, - )?; +fn expanded_timed_source(source: &str, defines: &[&str], path: &Path) -> Result { + let syntax = celox_sv_analyzer::syntax::parse_source_with_defines(source, path, defines)?; let root = (&syntax).into_iter().next().ok_or("empty timed source")?; Ok(syntax .get_str(vec![root]) @@ -483,8 +487,9 @@ mod adapter_define_tests { #[test] fn timed_macro_expansion_uses_the_adapter_define_set() { let source = "module Top;\n`ifdef CELOX_SUITE_ICARUS\ninitial q=1;\n`else\ninitial q=0;\n`endif\nendmodule"; - let icarus = expanded_timed_source(source, &["CELOX_SUITE_ICARUS"]).unwrap(); - let other = expanded_timed_source(source, &[]).unwrap(); + let icarus = + expanded_timed_source(source, &["CELOX_SUITE_ICARUS"], Path::new("timed.sv")).unwrap(); + let other = expanded_timed_source(source, &[], Path::new("timed.sv")).unwrap(); assert!(icarus.contains("q=1")); assert!(!icarus.contains("q=0")); assert!(other.contains("q=0")); diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index b0244013151..0c3054c6403 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -244,7 +244,7 @@ pub(super) fn gated( let body = timed_content(&source[body_start..body_end], names, tasks)?; let identifiers = sv_words(source) .into_iter() - .map(|word| word.2) + .map(|word| word.2.strip_prefix('\\').unwrap_or(word.2)) .collect::>(); let fresh = |kind: &str| { for suffix in 0.. { diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 430d63405d0..1c135f6b88d 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -734,3 +734,12 @@ endmodule"#) endmodule"#) (top Top)(set clk 1)(run_until 1)(assert_eq q 1)(assert_eq r 0) (set clk 0)(eval)(set clk 1)(run_until 2)(assert_eq r 1)) + +(case timed_file_macros_keep_each_source_path + (source "first.sv" #"module Leaf;initial $display("%s",`__FILE__);endmodule"#) + (source "second.sv" #"module Top;Leaf u();initial #1 $display("%s",`__FILE__);endmodule"#) + (top Top)(run_until 1)(expect_output "first.sv\nsecond.sv\n")) +(case escaped_identifiers_do_not_collide_with_control_names + (source "escaped-control.sv" #"package \celox_suite_timed_control ;parameter bit Q=1;endpackage + module Top(output bit q);initial q=\celox_suite_timed_control ::Q;endmodule"#) + (top Top)(run_until 0)(assert_eq q 1)) diff --git a/crates/celox/tests/frontends/systemverilog/suite.rs b/crates/celox/tests/frontends/systemverilog/suite.rs index 82ea26ef373..0c02a9b7e15 100644 --- a/crates/celox/tests/frontends/systemverilog/suite.rs +++ b/crates/celox/tests/frontends/systemverilog/suite.rs @@ -11,17 +11,30 @@ impl TimedBackend { fn new(sim: Simulation) -> Self { Self(sim, Vec::new(), false) } - fn capture_events(&mut self) { + fn capture_events(&mut self) -> Result<()> { let events = self.0.drain_runtime_events(); self.2 |= events .iter() .any(|event| matches!(event, RuntimeEvent::Finish)); + let error = events.iter().find_map(|event| match event { + RuntimeEvent::AssertFatal { message } => Some(format!( + "fatal assertion: {}", + String::from_utf8(message.clone()).unwrap_or_else(|_| format!("{message:?}")) + )), + RuntimeEvent::Missed { count } => Some(format!("{count} runtime events were missed")), + _ => None, + }); self.1.extend(events); + if let Some(error) = error { + Err(error.into()) + } else { + Ok(()) + } } fn settle_checked(&mut self) -> Result<()> { let already_finished = self.finished(); self.0.settle()?; - self.capture_events(); + self.capture_events()?; if !already_finished && self.finished() { return Err("the design finished outside run_to_finish during settling".into()); } @@ -98,8 +111,9 @@ impl Backend for TimedBackend { if time < now { return Err(format!("run_until {time}: the simulation is already at {now}").into()); } + self.0.settle()?; self.0.run_until(time)?; - self.capture_events(); + self.capture_events()?; if self.finished() { return Err(format!( "run_until {time}: the design finished the simulation at {}", @@ -111,7 +125,7 @@ impl Backend for TimedBackend { } fn run_to_finish(&mut self) -> Result<()> { - self.capture_events(); + self.capture_events()?; if self.finished() { return Err( "run_to_finish: the design already finished before the operation began".into(), @@ -119,7 +133,7 @@ impl Backend for TimedBackend { } while !self.finished() { let step = self.0.step()?; - self.capture_events(); + self.capture_events()?; if step.is_none() { break; } @@ -322,3 +336,79 @@ fn run_to_finish_rejects_a_finish_during_an_earlier_settle() { ); } } + +#[test] +fn run_until_settles_a_host_edge_without_a_runtime_process() { + let source = "module Top(input bit clk);always_ff @(posedge clk)$finish;endmodule"; + for name in [ + "native", + "cranelift", + "native-parallel", + "cranelift-parallel", + "wasm", + ] { + let design = celox_test_suite::load_group( + "finish-edge.vtest", + &format!( + "(group protocol (category sequential))(case finish (source \"finish-edge.sv\" #\"{source}\"#)(top Top)(set clk 1)(run_until 0))" + ), + celox_test_suite::no_std_library, + )[0]; + let mut backend = build(&design.design(), name).unwrap(); + backend + .write( + &SignalPath { + instances: Vec::new(), + name: "clk".into(), + }, + 1u8.into(), + 0u8.into(), + ) + .unwrap(); + assert!( + backend + .run_until(0) + .unwrap_err() + .to_string() + .contains("finished"), + "{name}" + ); + } +} + +#[test] +fn buffered_host_fatal_cannot_be_hidden_by_a_later_finish() { + let source = "module Top(input bit go);always_comb if(go)$fatal(1,\"host fatal\");initial #1 $finish;endmodule"; + let text = format!( + "(group protocol (category sequential))(case fatal (source \"fatal.sv\" #\"{source}\"#)(top Top)(set go 1)(run_to_finish))" + ); + let case = + celox_test_suite::load_group("fatal.vtest", &text, celox_test_suite::no_std_library)[0]; + for name in [ + "native", + "cranelift", + "native-parallel", + "cranelift-parallel", + "wasm", + ] { + let mut backend = build(&case.design(), name).unwrap(); + backend + .write( + &SignalPath { + instances: Vec::new(), + name: "go".into(), + }, + 1u8.into(), + 0u8.into(), + ) + .unwrap(); + assert!( + backend + .run_to_finish() + .unwrap_err() + .to_string() + .contains("fatal"), + "{name}" + ); + } +} diff --git a/crates/celox/tests/systemverilog.rs b/crates/celox/tests/systemverilog.rs index 9e826c9263e..bc967087e30 100644 --- a/crates/celox/tests/systemverilog.rs +++ b/crates/celox/tests/systemverilog.rs @@ -227,3 +227,8 @@ sv_backends! { fn adapter_defines_preserve_line_macros(sim) { @case "timing::adapter_defines_preserve_line_macros"; } fn callable_timing_keeps_generate_scope(sim) { @case "timing::callable_timing_keeps_generate_scope"; } } + +sv_backends! { + fn timed_file_macros_keep_each_source_path(sim) { @case "timing::timed_file_macros_keep_each_source_path"; } + fn escaped_identifiers_do_not_collide_with_control_names(sim) { @case "timing::escaped_identifiers_do_not_collide_with_control_names"; } +} From 8a1ca30e6fb84d42a68fb92e8a7fecc247ec159b Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 05:07:25 +0900 Subject: [PATCH 25/75] fix(runtime): retain four-state host edge baselines across snapshots --- crates/celox-runtime/src/simulation.rs | 164 ++++++++++++------ crates/celox-runtime/src/state_file.rs | 20 ++- .../src/sv/cases/timing.vtest | 11 +- crates/celox/src/simulator/state_file.rs | 7 + 4 files changed, 148 insertions(+), 54 deletions(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index fd15aec25ca..cab3978b36d 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -133,6 +133,7 @@ pub struct SimulationState { scheduler: Scheduler, periodic_events: FxHashMap, last_clock_values: BitSet, + unknown_clock_values: BitSet, topo_signals: Vec<(SignalRef, usize, usize)>, domain_kinds: Vec>, event_info: Vec>, @@ -151,18 +152,44 @@ pub struct SimulationState { finish_round: bool, } +fn transition_edges(was: (bool, bool), is: (bool, bool)) -> (bool, bool) { + let (was_nonzero, was_unknown) = was; + let (is_nonzero, is_unknown) = is; + match (was_unknown, is_unknown) { + (true, true) => (false, false), + (true, false) => (is_nonzero, !is_nonzero), + (false, true) => (!was_nonzero, was_nonzero), + (false, false) => (!was_nonzero && is_nonzero, was_nonzero && !is_nonzero), + } +} + +/// The event signal's least significant bit and its X/Z mask. +fn sample_event_signal(backend: &B, signal: SignalRef) -> (bool, bool) { + if backend.layout().four_state && signal.is_4state { + let (value, mask) = backend.get_four_state(signal); + (value.bit(0), mask.bit(0)) + } else { + let value: u8 = backend.get_as(signal); + (value & 1 != 0, false) + } +} + impl SimulationState { /// Rebase edge detection after state was advanced outside this scheduler. pub fn synchronize_event_values(&mut self, backend: &B) { self.last_clock_values.make_empty(); + self.unknown_clock_values.make_empty(); for (signal, id, _) in &self.topo_signals { if *id == usize::MAX { continue; } - let value: u8 = backend.get_as(*signal); - if value != 0 { + let (is_nonzero, is_unknown) = sample_event_signal(backend, *signal); + if is_nonzero { self.last_clock_values.insert(*id); } + if is_unknown { + self.unknown_clock_values.insert(*id); + } } } @@ -170,16 +197,19 @@ impl SimulationState { let Some((signal, _, _)) = self.topo_signals.get(self.signal_index_by_id[id]) else { return true; }; - let was_nonzero = self.last_clock_values.contains(id); - let is_nonzero = backend.get_as::(*signal) != 0; + let was = ( + self.last_clock_values.contains(id), + self.unknown_clock_values.contains(id), + ); + let is = sample_event_signal(backend, *signal); match self.domain_kinds[id] { - Some(DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh) => { - !was_nonzero && is_nonzero - } - Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => { - was_nonzero && !is_nonzero - } - _ => was_nonzero != is_nonzero, + Some( + DomainKind::ClockPosedge + | DomainKind::ResetAsyncHigh + | DomainKind::ClockNegedge + | DomainKind::ResetAsyncLow, + ) => self.edge_triggers(id, was, is), + _ => was != is, } } @@ -189,17 +219,16 @@ impl SimulationState { if *id == usize::MAX { continue; } - let was_nonzero = self.last_clock_values.contains(*id); - let value: u8 = backend.get_as(*signal); - let is_nonzero = value != 0; + let was = ( + self.last_clock_values.contains(*id), + self.unknown_clock_values.contains(*id), + ); + let is = sample_event_signal(backend, *signal); + let (posedge, negedge) = transition_edges(was, is); let triggered = match self.domain_kinds[*id] { - Some(DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh) => { - !was_nonzero && is_nonzero - } - Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => { - was_nonzero && !is_nonzero - } - _ => was_nonzero != is_nonzero, + Some(DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh) => posedge, + Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => negedge, + _ => was != is, }; if triggered { backend.mark_triggered_bit(*id); @@ -216,6 +245,7 @@ impl SimulationState { processes: Vec, ) -> Self { let mut last_clock_values = BitSet::with_capacity(backend.num_events()); + let mut unknown_clock_values = BitSet::with_capacity(backend.num_events()); let mut signal_to_id = FxHashMap::default(); let mut signal_index_by_id = vec![usize::MAX; backend.num_events()]; for (index, (signal, id, _)) in topo_signals.iter().copied().enumerate() { @@ -224,16 +254,20 @@ impl SimulationState { } signal_to_id.insert(signal, id); signal_index_by_id[id] = index; - let value: u8 = backend.get_as(signal); - if value != 0 { + let (value, unknown) = sample_event_signal(backend, signal); + if value { last_clock_values.insert(id); } + if unknown { + unknown_clock_values.insert(id); + } } Self { scheduler: Scheduler::new(), periodic_events: FxHashMap::default(), last_clock_values, + unknown_clock_values, topo_signals, domain_kinds, event_info, @@ -389,8 +423,11 @@ impl SimulationState { *id != usize::MAX && self.edge_triggers( *id, - self.last_clock_values.contains(*id), - backend.get_as::(*signal) != 0, + ( + self.last_clock_values.contains(*id), + self.unknown_clock_values.contains(*id), + ), + sample_event_signal(backend, *signal), ) }) } @@ -634,9 +671,9 @@ impl SimulationState { let num_events = executor.backend().num_events(); let mut scheduled_edges = BitSet::with_capacity(num_events); for event in &events_to_process { - let before = executor.backend().get_as::(event.signal) != 0; + let before = sample_event_signal(executor.backend(), event.signal); executor.backend_mut().set(event.signal, event.next_val); - let after = executor.backend().get_as::(event.signal) != 0; + let after = sample_event_signal(executor.backend(), event.signal); if let Some(&id) = self.signal_to_id.get(&event.signal) && self.edge_triggers(id, before, after) { @@ -652,10 +689,10 @@ impl SimulationState { let counter_values = self.event_counter_values(executor.backend()); let mut process_driven = Vec::new(); if !ready_processes.is_empty() || !self.waiting.is_empty() { - let before: Vec = self + let before: Vec<(bool, bool)> = self .topo_signals .iter() - .map(|(signal, _, _)| executor.backend().get_as(*signal)) + .map(|(signal, _, _)| sample_event_signal(executor.backend(), *signal)) .collect(); let progressed = self.run_processes(executor, current_time, ready_processes)?; if self.finished && self.finish_round { @@ -668,9 +705,9 @@ impl SimulationState { if *id == usize::MAX { continue; } - let value: u8 = executor.backend().get_as(*signal); + let value = sample_event_signal(executor.backend(), *signal); if value != before { - process_driven.push((*id, value != 0)); + process_driven.push((*id, value)); } } } @@ -691,12 +728,15 @@ impl SimulationState { .filter_map(|event| { self.signal_to_id .get(&event.signal) - .map(|&id| (id, event.next_val != 0)) + .map(|&id| (id, (event.next_val & 1 != 0, false))) }) .chain(process_driven); for (id, is_nonzero) in scheduled { track_stable_edges = true; - let was_nonzero = self.last_clock_values.contains(id); + let was_nonzero = ( + self.last_clock_values.contains(id), + self.unknown_clock_values.contains(id), + ); if self.edge_triggers(id, was_nonzero, is_nonzero) { scheduled_trigger_ids.insert(id); executor.backend_mut().mark_triggered_bit(id); @@ -878,11 +918,16 @@ impl SimulationState { let before = self .topo_signals .iter() - .map(|(signal, _, _)| executor.backend().get_as::(*signal)) + .map(|(signal, _, _)| sample_event_signal(executor.backend(), *signal)) .collect::>(); for ((_, id, _), value) in self.topo_signals.iter().zip(&before) { if *id != usize::MAX && processed.contains(*id) { - if *value != 0 { + if value.1 { + self.unknown_clock_values.insert(*id); + } else { + self.unknown_clock_values.remove(*id); + } + if value.0 { self.last_clock_values.insert(*id); } else { self.last_clock_values.remove(*id); @@ -908,8 +953,8 @@ impl SimulationState { if *id != usize::MAX && self.edge_triggers( *id, - before != 0, - executor.backend().get_as::(*signal) != 0, + before, + sample_event_signal(executor.backend(), *signal), ) { executor.backend_mut().mark_triggered_bit(*id); @@ -934,10 +979,10 @@ impl SimulationState { // Poll between outer cascade stages (IEEE 1800-2023 4.5), never // between the domains evaluated in the same active region. let polled = !self.waiting.is_empty() && !self.finished; - let before: Vec = if polled { + let before: Vec<(bool, bool)> = if polled { self.topo_signals .iter() - .map(|(signal, _, _)| executor.backend().get_as(*signal)) + .map(|(signal, _, _)| sample_event_signal(executor.backend(), *signal)) .collect() } else { Vec::new() @@ -977,8 +1022,8 @@ impl SimulationState { if *id == usize::MAX { continue; } - let value: u8 = executor.backend().get_as(*signal); - if value != before && self.edge_triggers(*id, before != 0, value != 0) { + let value = sample_event_signal(executor.backend(), *signal); + if value != before && self.edge_triggers(*id, before, value) { driven.insert(*id); executor.backend_mut().mark_triggered_bit(*id); } @@ -1006,8 +1051,13 @@ impl SimulationState { if *id == usize::MAX { continue; } - let value: u8 = executor.backend().get_as(*signal); - if value != 0 { + let (value, unknown) = sample_event_signal(executor.backend(), *signal); + if unknown { + self.unknown_clock_values.insert(*id); + } else { + self.unknown_clock_values.remove(*id); + } + if value { self.last_clock_values.insert(*id); } else { self.last_clock_values.remove(*id); @@ -1068,15 +1118,12 @@ impl SimulationState { /// Whether a change of event signal `id` from `was_nonzero` to /// `is_nonzero` is the edge its domain triggers on. - fn edge_triggers(&self, id: usize, was_nonzero: bool, is_nonzero: bool) -> bool { + fn edge_triggers(&self, id: usize, was: (bool, bool), is: (bool, bool)) -> bool { + let (posedge, negedge) = transition_edges(was, is); match self.domain_kinds[id] { - Some(DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh) => { - !was_nonzero && is_nonzero - } - Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => { - was_nonzero && !is_nonzero - } - _ => !was_nonzero && is_nonzero, + Some(DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh) => posedge, + Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => negedge, + _ => posedge, } } @@ -1124,6 +1171,7 @@ impl SimulationState { event_queue: self.scheduler.event_queue.clone(), periodic_events: self.periodic_events.clone(), last_clock_values: self.last_clock_values.clone(), + unknown_clock_values: self.unknown_clock_values.clone(), process_wakeups: self.process_wakeups.clone(), waiting: self.waiting.clone(), inactive: self.inactive.clone(), @@ -1159,6 +1207,8 @@ impl SimulationState { self.periodic_events.clone_from(&snapshot.periodic_events); self.last_clock_values .clone_from(&snapshot.last_clock_values); + self.unknown_clock_values + .clone_from(&snapshot.unknown_clock_values); self.process_wakeups.clone_from(&snapshot.process_wakeups); self.waiting.clone_from(&snapshot.waiting); self.inactive.clone_from(&snapshot.inactive); @@ -1180,6 +1230,7 @@ pub struct ScheduleParts { pub periodic: Vec<(SimEvent, u64)>, /// Events whose signal was high when edge detection last sampled it. pub high_events: Vec, + pub unknown_events: Vec, /// Suspended processes and the time each resumes at. pub process_wakeups: Vec<(usize, u64)>, /// Processes waiting for an event or a condition, in ascending order. @@ -1219,6 +1270,11 @@ impl SimulationState { }) .collect(), high_events: self.last_clock_values.iter().map(|id| events[id]).collect(), + unknown_events: self + .unknown_clock_values + .iter() + .map(|id| events[id]) + .collect(), process_wakeups: { let mut wakeups = self .process_wakeups @@ -1256,6 +1312,10 @@ impl SimulationState { for event in parts.high_events { self.last_clock_values.insert(event.id()); } + self.unknown_clock_values.make_empty(); + for event in parts.unknown_events { + self.unknown_clock_values.insert(event.id()); + } self.process_wakeups = parts .process_wakeups .into_iter() @@ -1274,6 +1334,7 @@ pub struct SimulationSnapshot { event_queue: std::collections::BinaryHeap>, periodic_events: FxHashMap, last_clock_values: BitSet, + unknown_clock_values: BitSet, process_wakeups: BinaryHeap, waiting: BTreeSet, inactive: BTreeSet, @@ -1288,6 +1349,7 @@ impl Clone for SimulationSnapshot { event_queue: self.event_queue.clone(), periodic_events: self.periodic_events.clone(), last_clock_values: self.last_clock_values.clone(), + unknown_clock_values: self.unknown_clock_values.clone(), process_wakeups: self.process_wakeups.clone(), waiting: self.waiting.clone(), inactive: self.inactive.clone(), diff --git a/crates/celox-runtime/src/state_file.rs b/crates/celox-runtime/src/state_file.rs index af5e4737441..4c31ba9a53f 100644 --- a/crates/celox-runtime/src/state_file.rs +++ b/crates/celox-runtime/src/state_file.rs @@ -19,6 +19,7 @@ //! event count u32, then per event: scheduled event //! periodic count u32, then per marker: scheduled event | count u64 //! high count u32, then per event: event str +//! unknown count u32, then per event: event str (version 2 and later) //! scheduled event: time u64 | event str | signal str | value u8 //! str: byte length u32 | UTF-8 //! ``` @@ -26,7 +27,7 @@ use std::io::{self, Read, Write}; const MAGIC: &[u8; 8] = b"CXSTATE\0"; -const VERSION: u16 = 1; +const VERSION: u16 = 2; const FLAG_FOUR_STATE: u16 = 1 << 0; const FLAG_SCHEDULE: u16 = 1 << 1; @@ -77,6 +78,8 @@ pub struct ScheduleRecord { pub periodic: Vec<(ScheduledEvent, u64)>, /// Event paths whose signal was high when edge detection last sampled it. pub high_events: Vec, + /// Events whose baseline contains X/Z bits. + pub unknown_events: Vec, } /// Contents of a state file. @@ -168,6 +171,10 @@ impl StateFile { for event in &schedule.high_events { put_str(w, event)?; } + put_len(w, schedule.unknown_events.len())?; + for event in &schedule.unknown_events { + put_str(w, event)?; + } } Ok(()) } @@ -180,7 +187,7 @@ impl StateFile { return Err(StateFileError::BadMagic); } let version = get_u16(r)?; - if version != VERSION { + if !(1..=VERSION).contains(&version) { return Err(StateFileError::UnsupportedVersion(version)); } let flags = get_u16(r)?; @@ -233,7 +240,15 @@ impl StateFile { let high_events = (0..get_u32(r)?) .map(|_| get_str(r)) .collect::>()?; + let unknown_events = if version >= 2 { + (0..get_u32(r)?) + .map(|_| get_str(r)) + .collect::>()? + } else { + Vec::new() + }; Some(ScheduleRecord { + unknown_events, time, clocks, events, @@ -440,6 +455,7 @@ mod tests { events: vec![event.clone()], periodic: vec![(event, 1)], high_events: vec!["clk".into()], + unknown_events: vec!["clk".into()], }), } } diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 1c135f6b88d..5eb35c33ecf 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -283,9 +283,11 @@ (case four_state_edges_count_transitions_through_unknown (source "four_state_edges.sv" #" - module Top(output logic [7:0] pos, output logic [7:0] neg, output logic [7:0] any); + module Top(input logic host_clk, output logic [7:0] host_count, output logic [7:0] pos, output logic [7:0] neg, output logic [7:0] any); + always_ff @(posedge host_clk) host_count <= host_count + 1; logic s = 1'b0; initial begin + host_count = 8'd0; pos = 8'd0; neg = 8'd0; any = 8'd0; @@ -314,6 +316,13 @@ "#) (top Top) (four_state) + (set host_clk 0) + (run_until 0) + (set host_clk 1'bz)(eval)(assert_eq host_count 1) + (set host_clk 1'bx)(eval)(assert_eq host_count 1) + (set host_clk 1)(eval)(assert_eq host_count 2) + (set host_clk 0)(eval) + (set host_clk 1'bz)(eval)(assert_eq host_count 3) (run_to_finish) (assert_eq pos 3) (assert_eq neg 3) diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index 9da2ed70997..cb08ec47680 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -374,6 +374,7 @@ impl Simulator { .map(|(event, count)| (named(event), *count)) .collect(), high_events: parts.high_events.into_iter().map(event_path).collect(), + unknown_events: parts.unknown_events.into_iter().map(event_path).collect(), } } @@ -404,6 +405,7 @@ impl Simulator { .iter() .map(|(name, _)| name) .chain(&record.high_events) + .chain(&record.unknown_events) .chain(scheduled.clone().map(|event| &event.event)) .filter(|name| !events.contains_key(*name)) .chain( @@ -441,6 +443,11 @@ impl Simulator { .map(|(event, count)| (resolve(event), *count)) .collect(), high_events: record.high_events.iter().map(|name| events[name]).collect(), + unknown_events: record + .unknown_events + .iter() + .map(|name| events[name]) + .collect(), // State files are rejected for designs with processes. process_wakeups: Vec::new(), waiting_processes: Vec::new(), From d3ddd228f1452bf5039bcd6857172244d6f990c7 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 06:26:13 +0900 Subject: [PATCH 26/75] fix(suite): resolve generate-scoped imports and exported or unit task calls --- crates/celox-sv-analyzer/src/ast.rs | 8 + crates/celox-sv-analyzer/src/ast/imports.rs | 2 +- crates/celox-test-suite/LIMITATIONS.md | 1 + .../celox-test-suite/src/frontend/timed_ff.rs | 179 +++++++++++++++--- .../src/sv/cases/timing.vtest | 27 +++ .../repros/sv_timed_unit_icarus.json | 33 ++++ .../verification/sv/limitations.json | 17 ++ crates/celox/tests/systemverilog.rs | 3 + 8 files changed, 247 insertions(+), 23 deletions(-) create mode 100644 crates/celox-test-suite/verification/repros/sv_timed_unit_icarus.json diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 9a37aa47052..8c70e6a3a90 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -2434,3 +2434,11 @@ fn generate_scope_head(name: &str) -> Option<&str> { }; Some(&name[..end]) } + +/// Source ranges of generate scopes, including single-item bodies. +/// Offsets refer to the parsed, preprocessed source text. +pub fn generate_scope_ranges(tree: &SyntaxTree) -> Vec<(usize, usize)> { + tree.into_iter() + .flat_map(imports::generate_blocks) + .collect() +} diff --git a/crates/celox-sv-analyzer/src/ast/imports.rs b/crates/celox-sv-analyzer/src/ast/imports.rs index ce221725316..25a526f4264 100644 --- a/crates/celox-sv-analyzer/src/ast/imports.rs +++ b/crates/celox-sv-analyzer/src/ast/imports.rs @@ -411,7 +411,7 @@ pub(super) fn node_range(node: RefNode<'_>) -> (usize, usize) { /// The source ranges of the generate blocks under a module `node`: each is a /// scope of its own (IEEE 1800-2023 27.5). -fn generate_blocks(node: RefNode<'_>) -> Vec<(usize, usize)> { +pub(super) fn generate_blocks(node: RefNode<'_>) -> Vec<(usize, usize)> { if !matches!( node, RefNode::ModuleDeclarationAnsi(_) | RefNode::ModuleDeclarationNonansi(_) diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 181729bf298..1799e71da3f 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -362,6 +362,7 @@ four-state expectations; the assertions remain enabled on all Celox variants. | Group | Stage | Tool | Cases | Reason | | --- | --- | --- | ---: | --- | +| `sv_icarus_qualified_unit_task` | compile | icarus | 1 | Icarus 13.0 rejects a `$unit::` qualified task call permitted by IEEE 1800-2023 3.12.1. Celox and Verilator pass the unchanged timed case. The [pre-exclusion diagnostic](verification/repros/sv_timed_unit_icarus.json) records the malformed-statement error. | | `sv_icarus_genvar_dimensions` | execute | icarus | 1 | Icarus 13.0 returns 0 for `$dimensions` of a generated loop index's implicit integer localparam; IEEE 1800-2023 27.4 and 20.7 require one packed dimension. Celox and Verilator pass the unchanged assertions. The [standalone reproducer and pre-exclusion result](verification/repros/sv_genvar_dimensions.json) retain the observed disagreement. | | `sv_icarus_constant_array_queries` | compile | icarus | 1 | Icarus 13.0 rejects array queries of variables in constant expressions and typedef operands; IEEE 1800-2023 20.7 permits them. Verilator passes. | | `sv_icarus_runtime_array_queries` | execute | icarus | 1 | Icarus 13.0 aborts on a runtime dimension argument. A standalone reproducer also rejects an integer variable as the dimension. IEEE 1800-2023 20.7 permits querying fixed-size dimensions with runtime expressions. | diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index 0c3054c6403..339252d3770 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -394,6 +394,9 @@ fn has_timing(source: &str) -> bool { #[derive(Default)] pub(super) struct TaskTiming { tasks: BTreeMap<(String, Vec, String), bool>, + generate_scopes: BTreeMap>, + imports: BTreeMap)>>, + exports: BTreeMap, Option)>>, } fn container_at(source: &str, at: usize) -> String { @@ -418,7 +421,7 @@ fn container_at(source: &str, at: usize) -> String { // Scope identities include their source offsets so closed sibling blocks // cannot make their imports visible at a later module item. -fn lexical_scope_at(source: &str, at: usize) -> Vec { +fn lexical_scope_at(source: &str, at: usize, generates: &[(usize, usize)]) -> Vec { let mut scopes = Vec::new(); for (start, _, word) in sv_words(&source[..at]) { match word { @@ -432,24 +435,135 @@ fn lexical_scope_at(source: &str, at: usize) -> Vec { _ => {} } } + scopes.extend( + generates + .iter() + .filter_map(|(start, end)| (*start <= at && at < *end).then_some(*start)), + ); + scopes.sort_unstable(); + scopes.dedup(); scopes } -fn callable_key(source: &str, at: usize, name: &str) -> (String, Vec, String) { - let container = container_at(source, at); - let mut scope = lexical_scope_at(source, at); - if !container.is_empty() && !scope.is_empty() { - scope.remove(0); +impl TaskTiming { + fn lexical_scope(&self, source: &str, at: usize) -> Vec { + lexical_scope_at( + source, + at, + self.generate_scopes.get(source).map_or(&[], Vec::as_slice), + ) } - (container, scope, name.to_owned()) -} -impl TaskTiming { + fn callable_key(&self, source: &str, at: usize, name: &str) -> (String, Vec, String) { + let container = container_at(source, at); + let mut scope = self.lexical_scope(source, at); + if !container.is_empty() && !scope.is_empty() { + scope.remove(0); + } + (container, scope, name.to_owned()) + } + + fn package_callable( + &self, + package: &str, + name: &str, + visiting: &mut std::collections::BTreeSet, + ) -> Option { + let package = if package == "$unit" { "" } else { package }; + if let Some(value) = self + .tasks + .get(&(package.to_owned(), Vec::new(), name.to_owned())) + { + return Some(*value); + } + if !visiting.insert(package.to_owned()) { + return None; + } + let mut result = None; + if let (Some(imports), Some(exports)) = + (self.imports.get(package), self.exports.get(package)) + { + for (origin, selected) in imports { + if selected.as_deref().is_some_and(|selected| selected != name) { + continue; + } + if !exports.iter().any(|(exported, member)| { + exported.as_deref().is_none_or(|p| p == origin) + && member.as_deref().is_none_or(|n| n == name) + }) { + continue; + } + if let Some(timed) = self.package_callable(origin, name, visiting) { + result = Some(result.unwrap_or(false) || timed); + } + } + } + visiting.remove(package); + result + } pub(super) fn new(sources: &[String]) -> Self { let mut result = Self::default(); let mut records = Vec::new(); for source in sources { + if let Ok(tree) = celox_sv_analyzer::syntax::parse_source(source, Path::new("timed.sv")) + { + result.generate_scopes.insert( + source.clone(), + celox_sv_analyzer::ast::generate_scope_ranges(&tree), + ); + } let words = sv_words(source); + for (start, end, word) in &words { + if !matches!(*word, "import" | "export") + || result.lexical_scope(source, *start).len() != 1 + { + continue; + } + let container = container_at(source, *start); + // Only package exports participate in qualified resolution. + if !sv_words(&source[..*start]) + .iter() + .rev() + .find(|(_, _, word)| { + matches!( + *word, + "package" + | "module" + | "interface" + | "endpackage" + | "endmodule" + | "endinterface" + ) + }) + .is_some_and(|(_, _, word)| *word == "package") + { + continue; + } + let tail = &source[*end..]; + let Some(end) = tail.find(';') else { + continue; + }; + for item in tail[..end].split(',') { + let item_words = sv_words(item); + let package = item_words.first().map(|x| x.2.to_owned()); + let selected = item_words.get(1).map(|x| x.2.to_owned()); + if *word == "import" { + if let Some(package) = package { + result + .imports + .entry(container.clone()) + .or_default() + .push((package, selected)); + } + } else { + result + .exports + .entry(container.clone()) + .or_default() + .push((package, selected)); + } + } + } for (index, (start, end, word)) in words.iter().enumerate() { if *word == "function" { let header_end = source[*end..] @@ -461,7 +575,7 @@ impl TaskTiming { if let Some((_, _, name)) = sv_words(&header[..name_end]).last() { result .tasks - .insert(callable_key(source, *start, name), false); + .insert(result.callable_key(source, *start, name), false); } continue; } @@ -479,7 +593,7 @@ impl TaskTiming { else { continue; }; - let key = callable_key(source, *start, name); + let key = result.callable_key(source, *start, name); let header_end = source[*end..*body_end] .find(';') .map_or(*end, |offset| end + offset + 1); @@ -507,10 +621,7 @@ impl TaskTiming { let prefix = source[..at].trim_end(); if let Some(prefix) = prefix.strip_suffix("::") { let package = sv_words(prefix).last()?.2; - return self - .tasks - .get(&(package.to_string(), Vec::new(), name.to_owned())) - .copied(); + return self.package_callable(package, name, &mut Default::default()); } if let Some(prefix) = prefix.strip_suffix('.') { let instance = sv_words(prefix).last()?.2; @@ -530,7 +641,7 @@ impl TaskTiming { return None; } let scope = container_at(source, at); - let mut key = callable_key(source, at, name); + let mut key = self.callable_key(source, at, name); loop { if let Some(value) = self.tasks.get(&key) { return Some(*value); @@ -539,7 +650,7 @@ impl TaskTiming { break; } } - let call_scope = lexical_scope_at(source, at); + let call_scope = self.lexical_scope(source, at); let mut imports: BTreeMap, Option)> = BTreeMap::new(); for (start, end, word) in sv_words(&source[..at]) { if word != "import" { @@ -549,7 +660,7 @@ impl TaskTiming { if !import_scope.is_empty() && import_scope != scope { continue; } - let lexical = lexical_scope_at(source, start); + let lexical = self.lexical_scope(source, start); if !call_scope.starts_with(&lexical) { continue; } @@ -564,13 +675,12 @@ impl TaskTiming { let selected = words.get(1).map(|word| word.2); if selected == Some(name) || (selected.is_none() && item.contains('*')) { if let Some(value) = - self.tasks - .get(&(package.to_string(), Vec::new(), name.to_owned())) + self.package_callable(package, name, &mut Default::default()) { if selected == Some(name) { - *explicit = Some(*value); + *explicit = Some(value); } else { - *wildcard = Some(wildcard.unwrap_or(false) || *value); + *wildcard = Some(wildcard.unwrap_or(false) || value); } } } @@ -630,6 +740,31 @@ mod callable_analysis_tests { &tasks )); } + #[test] + fn qualified_and_exported_callable_timing_uses_the_declaring_scope() { + for delay in ["", "#1;"] { + let source = format!( + "package A; task tick; {delay} endtask endpackage + package B; import A::tick; export A::*; endpackage + package C; import B::*; export B::tick; endpackage + module Top; import C::*; always @(posedge clk) tick(); endmodule" + ); + let tasks = TaskTiming::new(std::slice::from_ref(&source)); + assert_eq!( + tasks.package_callable("C", "tick", &mut Default::default()), + Some(!delay.is_empty()) + ); + let at = source.rfind("tick()").unwrap(); + assert_eq!(tasks.resolve(&source, at, "tick"), Some(!delay.is_empty())); + } + let source = "task tick; endtask module Top; task tick; #1; endtask always @(posedge clk) $unit::tick(); endmodule".to_owned(); + let tasks = TaskTiming::new(std::slice::from_ref(&source)); + assert_eq!( + tasks.resolve(&source, source.rfind("tick()").unwrap(), "tick"), + Some(false) + ); + } + #[test] fn escaped_callable_names_remain_whole_tokens() { let source = r"task \pause.task ; #1; endtask"; diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 5eb35c33ecf..8e7c8b1745b 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -752,3 +752,30 @@ endmodule"#) (source "escaped-control.sv" #"package \celox_suite_timed_control ;parameter bit Q=1;endpackage module Top(output bit q);initial q=\celox_suite_timed_control ::Q;endmodule"#) (top Top)(run_until 0)(assert_eq q 1)) + +(case single_item_generate_imports_do_not_leak + (source "imports.sv" #"package A; task automatic tick(output bit value); value=1; endtask endpackage + package B; task automatic tick(output bit value); #1 value=1; endtask endpackage + module Top(input bit clk,output bit q); + import A::tick; + if(1) import B::tick; + always @(posedge clk) tick(q); + endmodule"#) + (top Top)(set clk 1)(run_until 0)(assert_eq q 1)) + +(case exported_untimed_tasks_keep_setup_edges + (source "exports.sv" #"package A; task automatic tick(output bit value); value=1; endtask endpackage + package B; import A::tick; export A::*; endpackage + package C; import B::tick; export *::*; endpackage + module Top(input bit clk,output bit q); + import C::*; + always @(posedge clk) tick(q); + endmodule"#) + (top Top)(set clk 1)(run_until 0)(assert_eq q 1)) + +(case qualified_unit_tasks_keep_setup_edges + (source "unit.sv" #"task automatic tick(output bit value); value=1; endtask + module Top(input bit clk,output bit q); + always @(posedge clk) $unit::tick(q); + endmodule"#) + (top Top)(set clk 1)(run_until 0)(assert_eq q 1)) diff --git a/crates/celox-test-suite/verification/repros/sv_timed_unit_icarus.json b/crates/celox-test-suite/verification/repros/sv_timed_unit_icarus.json new file mode 100644 index 00000000000..48c33533071 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_timed_unit_icarus.json @@ -0,0 +1,33 @@ +{ + "suite": "sv", + "suite_version": "0.10.1", + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "include_ignored": false, + "schema_version": 3, + "cases": [ + { + "category": "Sequential", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Malformed statement\n", + "expectation": "Simulation", + "name": "timing::qualified_unit_tasks_keep_setup_edges", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ], + "counts": { + "passed": 0, + "rejected": 0, + "unexpected_accept": 0, + "mismatch": 0, + "emission_error": 0, + "compile_error": 1, + "runtime_error": 0, + "unsupported": 0, + "ignored": 0 + }, + "note": "Focused pre-exclusion result for the new qualified compilation-unit task case. IEEE 1800-2023 3.12.1 permits $unit:: qualification. Celox and Verilator pass the unchanged case; Icarus 13.0 rejects the qualified call." +} diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 632e6dace3e..7447ee7377a 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -1265,5 +1265,22 @@ "indexed_select::constant_parameter_initializers_preserve_unknown_indices" ] } + }, + { + "id": "sv_icarus_qualified_unit_task", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus 13.0 / Verilator 5.052", + "reason": "Icarus 13.0 rejects $unit::tick(q) as a malformed statement. IEEE 1800-2023 3.12.1 permits scope-qualified compilation-unit identifiers. Celox and Verilator pass the unchanged timed task case.", + "upstream": [], + "evidence": [ + "verification/repros/sv_timed_unit_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "timing::qualified_unit_tasks_keep_setup_edges" + ] + } } ] diff --git a/crates/celox/tests/systemverilog.rs b/crates/celox/tests/systemverilog.rs index bc967087e30..310eb967a7f 100644 --- a/crates/celox/tests/systemverilog.rs +++ b/crates/celox/tests/systemverilog.rs @@ -226,6 +226,9 @@ sv_backends! { fn attributes_preserve_single_generate_arms(sim) { @case "timing::attributes_preserve_single_generate_arms"; } fn adapter_defines_preserve_line_macros(sim) { @case "timing::adapter_defines_preserve_line_macros"; } fn callable_timing_keeps_generate_scope(sim) { @case "timing::callable_timing_keeps_generate_scope"; } + fn single_item_generate_imports_do_not_leak(sim) { @case "timing::single_item_generate_imports_do_not_leak"; } + fn exported_untimed_tasks_keep_setup_edges(sim) { @case "timing::exported_untimed_tasks_keep_setup_edges"; } + fn qualified_unit_tasks_keep_setup_edges(sim) { @case "timing::qualified_unit_tasks_keep_setup_edges"; } } sv_backends! { From 922fd8c49c8c51d8cb487c1bea17a429f1cd750d Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 07:15:28 +0900 Subject: [PATCH 27/75] fix(runtime): retain inactive edges and reconstruct legacy clock baselines --- crates/celox-runtime/src/simulation.rs | 12 +-- crates/celox-runtime/src/state_file.rs | 50 +++++++-- crates/celox/src/simulation.rs | 131 ++++++++++++++++++++++- crates/celox/src/simulator/state_file.rs | 5 +- 4 files changed, 176 insertions(+), 22 deletions(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index cab3978b36d..b4e367e3d62 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -421,14 +421,10 @@ impl SimulationState { pub fn has_unsettled_edges(&self, backend: &B) -> bool { self.topo_signals.iter().any(|(signal, id, _)| { *id != usize::MAX - && self.edge_triggers( - *id, - ( - self.last_clock_values.contains(*id), - self.unknown_clock_values.contains(*id), - ), - sample_event_signal(backend, *signal), - ) + && ( + self.last_clock_values.contains(*id), + self.unknown_clock_values.contains(*id), + ) != sample_event_signal(backend, *signal) }) } diff --git a/crates/celox-runtime/src/state_file.rs b/crates/celox-runtime/src/state_file.rs index 4c31ba9a53f..5dc72f3654d 100644 --- a/crates/celox-runtime/src/state_file.rs +++ b/crates/celox-runtime/src/state_file.rs @@ -78,8 +78,9 @@ pub struct ScheduleRecord { pub periodic: Vec<(ScheduledEvent, u64)>, /// Event paths whose signal was high when edge detection last sampled it. pub high_events: Vec, - /// Events whose baseline contains X/Z bits. - pub unknown_events: Vec, + /// Events whose baseline contains X/Z bits. Legacy version-1 files do + /// not carry this information; their baselines are reconstructed on load. + pub unknown_events: Option>, } /// Contents of a state file. @@ -122,7 +123,16 @@ impl StateFile { pub fn write_to(&self, mut writer: impl Write) -> io::Result<()> { let w = &mut writer; w.write_all(MAGIC)?; - put_u16(w, VERSION)?; + let version = if self + .schedule + .as_ref() + .is_some_and(|schedule| schedule.unknown_events.is_none()) + { + 1 + } else { + VERSION + }; + put_u16(w, version)?; let mut flags = 0; if self.four_state { flags |= FLAG_FOUR_STATE; @@ -171,9 +181,11 @@ impl StateFile { for event in &schedule.high_events { put_str(w, event)?; } - put_len(w, schedule.unknown_events.len())?; - for event in &schedule.unknown_events { - put_str(w, event)?; + if let Some(unknown_events) = &schedule.unknown_events { + put_len(w, unknown_events.len())?; + for event in unknown_events { + put_str(w, event)?; + } } } Ok(()) @@ -241,11 +253,13 @@ impl StateFile { .map(|_| get_str(r)) .collect::>()?; let unknown_events = if version >= 2 { - (0..get_u32(r)?) - .map(|_| get_str(r)) - .collect::>()? + Some( + (0..get_u32(r)?) + .map(|_| get_str(r)) + .collect::>()?, + ) } else { - Vec::new() + None }; Some(ScheduleRecord { unknown_events, @@ -455,11 +469,25 @@ mod tests { events: vec![event.clone()], periodic: vec![(event, 1)], high_events: vec!["clk".into()], - unknown_events: vec!["clk".into()], + unknown_events: Some(vec!["clk".into()]), }), } } + #[test] + fn legacy_schedule_round_trips_preserve_missing_mask_metadata() { + let mut file = sample(); + file.schedule.as_mut().unwrap().unknown_events = None; + let mut bytes = Vec::new(); + file.write_to(&mut bytes).unwrap(); + assert_eq!(&bytes[8..10], &1u16.to_le_bytes()); + let loaded = StateFile::read_from(bytes.as_slice()).unwrap(); + assert_eq!(loaded, file); + let mut again = Vec::new(); + loaded.write_to(&mut again).unwrap(); + assert_eq!(again, bytes); + } + #[test] fn round_trips() { let file = sample(); diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 81bc9b470ff..2ad98fec17f 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -327,8 +327,32 @@ impl Simulation { } let record = file.schedule.as_ref().ok_or(StateError::MissingSchedule)?; self.simulator.check_vcd_rewind(record.time)?; - let parts = self.simulator.resolve_schedule(record)?; + let mut parts = self.simulator.resolve_schedule(record)?; self.simulator.load_state(file)?; + if record.unknown_events.is_none() { + // Version 1 lacks masks for edge baselines. Resolve them from the + // loaded backend so aliases and two-state conversions agree too. + let samples: Vec<_> = self + .simulator + .backend + .id_to_event_slice() + .iter() + .copied() + .map(|event| { + let signal = self.simulator.backend.resolve_signal(&event.addr()); + let (value, mask) = self.simulator.backend.get_four_state(signal); + (event, value.bit(0), mask.bit(0)) + }) + .collect(); + parts.high_events = samples + .iter() + .filter_map(|(event, high, _)| high.then_some(*event)) + .collect(); + parts.unknown_events = samples + .iter() + .filter_map(|(event, _, unknown)| unknown.then_some(*event)) + .collect(); + } self.state.import_schedule(parts); Ok(()) } @@ -1761,3 +1785,108 @@ mod scheduled_pulse_tests { } } } + +#[cfg(all(test, feature = "systemverilog"))] +mod lazy_host_clock_review_tests { + use super::*; + fn check(mut sim: Simulation, mask: u8) { + let clk = sim.signal("clk"); + let q = sim.signal("q"); + sim.set_four_state(clk, 1u8.into(), 0u8.into()); + sim.settle().unwrap(); + assert_eq!(sim.get(q), 1u8.into()); + sim.set_four_state(clk, 0u8.into(), mask.into()); + let _ = sim.get(q); + sim.settle().unwrap(); + sim.set_four_state(clk, 1u8.into(), 0u8.into()); + let _ = sim.get(q); + sim.settle().unwrap(); + assert_eq!(sim.get(q), 2u8.into(), "inactive mask {mask}"); + } + #[test] + fn lazy_reads_do_not_hide_inactive_clock_transitions() { + let source = + "module Top(input logic clk,output int q);always @(posedge clk)q<=q+1;endmodule"; + let build = || { + Simulator::from_sv_sources(vec![(source, std::path::Path::new("lazy-clock.sv"))], "Top") + .four_state(true) + }; + for mask in [0, 1] { + check(Simulation::new(build().build_interpreter().unwrap()), mask); + check(Simulation::new(build().build_cranelift().unwrap()), mask); + check(Simulation::new(build().build_wasm().unwrap()), mask); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap()), mask); + } + } +} + +#[cfg(all(test, feature = "systemverilog"))] +mod legacy_clock_state_review_tests { + use super::*; + fn check(mut source: Simulation, mut target: Simulation, known: u8) { + let clk = source.signal("clk"); + source.set_four_state(clk, 1u8.into(), 0u8.into()); + source.settle().unwrap(); + source.set_four_state(clk, known.into(), 1u8.into()); + source.settle().unwrap(); + let file = source.save_state().unwrap(); + let unknown_bytes = 4 + file + .schedule + .as_ref() + .unwrap() + .unknown_events + .iter() + .flatten() + .map(|name| 4 + name.len()) + .sum::(); + let mut bytes = Vec::new(); + file.write_to(&mut bytes).unwrap(); + bytes[8..10].copy_from_slice(&1u16.to_le_bytes()); + bytes.truncate(bytes.len() - unknown_bytes); + let legacy = celox_runtime::StateFile::read_from(bytes.as_slice()).unwrap(); + target.load_state(&legacy).unwrap(); + let q = target.signal("q"); + let before = target.get(q); + let clk = target.signal("clk"); + target.set_four_state(clk, known.into(), 0u8.into()); + target.settle().unwrap(); + assert_eq!(target.get(q), before + 1u8); + } + #[test] + fn legacy_files_restore_unknown_clock_baselines() { + for (edge, known) in [("posedge", 1u8), ("negedge", 0u8)] { + let source = format!( + "module Top(input logic clk,output int q);always @({edge} clk)q<=q+1;endmodule" + ); + let build = || { + Simulator::from_sv_sources( + vec![(source.as_str(), std::path::Path::new("legacy-clock.sv"))], + "Top", + ) + .four_state(true) + }; + check( + Simulation::new(build().build_interpreter().unwrap()), + Simulation::new(build().build_interpreter().unwrap()), + known, + ); + check( + Simulation::new(build().build_cranelift().unwrap()), + Simulation::new(build().build_cranelift().unwrap()), + known, + ); + check( + Simulation::new(build().build_wasm().unwrap()), + Simulation::new(build().build_wasm().unwrap()), + known, + ); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check( + Simulation::new(build().build_native().unwrap()), + Simulation::new(build().build_native().unwrap()), + known, + ); + } + } +} diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index cb08ec47680..45a110191df 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -374,7 +374,7 @@ impl Simulator { .map(|(event, count)| (named(event), *count)) .collect(), high_events: parts.high_events.into_iter().map(event_path).collect(), - unknown_events: parts.unknown_events.into_iter().map(event_path).collect(), + unknown_events: Some(parts.unknown_events.into_iter().map(event_path).collect()), } } @@ -405,7 +405,7 @@ impl Simulator { .iter() .map(|(name, _)| name) .chain(&record.high_events) - .chain(&record.unknown_events) + .chain(record.unknown_events.iter().flatten()) .chain(scheduled.clone().map(|event| &event.event)) .filter(|name| !events.contains_key(*name)) .chain( @@ -446,6 +446,7 @@ impl Simulator { unknown_events: record .unknown_events .iter() + .flatten() .map(|name| events[name]) .collect(), // State files are rejected for designs with processes. From 7074d393d221ff1829d5f66b5668b70399c717c1 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 07:58:03 +0900 Subject: [PATCH 28/75] fix(suite): preserve callable and output identity during staging --- crates/celox-test-suite/src/frontend.rs | 24 ++++++++++- .../celox-test-suite/src/frontend/timed_ff.rs | 43 ++++++++++++++++--- crates/celox-test-suite/src/script/sv.rs | 12 +++--- .../src/sv/cases/timing.vtest | 14 ++++++ crates/celox-test-suite/src/verification.rs | 9 +++- crates/celox/tests/systemverilog.rs | 5 +++ 6 files changed, 93 insertions(+), 14 deletions(-) diff --git a/crates/celox-test-suite/src/frontend.rs b/crates/celox-test-suite/src/frontend.rs index 281e4d2af40..cd462b40af6 100644 --- a/crates/celox-test-suite/src/frontend.rs +++ b/crates/celox-test-suite/src/frontend.rs @@ -275,7 +275,7 @@ fn timed_content(source: &str, names: &TimedNames, tasks: &timed_ff::TaskTiming) } let replacement = match word { "initial" => format!("initial wait ({}::started)", names.package), - "always" if timed_ff::wildcard_control(source, end) => continue, + "always" if timed_ff::wildcard_control(source, end, tasks) => continue, "always" => { format!("always wait ({}::started)", names.package) } @@ -296,6 +296,28 @@ mod timed_staging_tests { use crate as celox_test_suite; use crate::{Backend, load_group, no_std_library}; + #[test] + #[ignore = "requires Icarus; Celox rejects timing in wildcard bodies and Verilator rejects nested implicit sensitivity"] + fn timed_wildcards_do_not_catch_setup_changes() { + let text = r##"(group wildcards (category sequential)) + (case setup (source "wildcards.sv" #"module Top(input bit go,output bit a,b,c); + task automatic tick(); #1 c=go; endtask + always @* begin #1 a=go; end + always @(*) begin wait(go); b=go; end + always @* tick(); + initial begin #3; $finish; end endmodule"#) + (top Top)(set go 1)(run_to_finish)(assert_eq a 0)(assert_eq b 0)(assert_eq c 0))"##; + let case = load_group("wildcards.vtest", text, no_std_library)[0]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../target/timed-wildcard-protocol") + .join(std::process::id().to_string()); + let frontend = crate::sv::verification::SvFrontend; + let mut icarus = + crate::icarus::Icarus::build_script(&frontend, case, &root.join("icarus")).unwrap(); + icarus.run_testbench().unwrap(); + std::fs::remove_dir_all(root).unwrap(); + } + #[test] #[ignore = "requires Icarus, Verilator and a C++ compiler; Celox does not yet support hierarchical task calls"] fn qualified_timed_tasks_do_not_use_same_named_local_tasks() { diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index 339252d3770..a88124c2371 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -352,16 +352,25 @@ pub(super) fn in_macro(source: &str, start: usize, replacement: String) -> Strin output } -pub(super) fn wildcard_control(source: &str, end: usize) -> bool { +pub(super) fn wildcard_control(source: &str, end: usize, tasks: &TaskTiming) -> bool { let at = trivia(source, end); if source.as_bytes().get(at) != Some(&b'@') { return false; } let begin = trivia(source, at + 1); - if source.as_bytes().get(begin) == Some(&b'*') { - return true; - } - parens(source, begin).is_some_and(|end| after_trivia(&source[begin + 1..end - 1]).trim() == "*") + let event_end = if source.as_bytes().get(begin) == Some(&b'*') { + begin + 1 + } else if let Some(end) = parens(source, begin) + && after_trivia(&source[begin + 1..end - 1]).trim() == "*" + { + end + } else { + return false; + }; + let Some(body_end) = statement_end(source, event_end) else { + return false; + }; + !has_timing(&source[event_end..body_end]) && !tasks.has_timed_call(source, event_end, body_end) } fn has_timing(source: &str) -> bool { @@ -571,7 +580,29 @@ impl TaskTiming { .map(|offset| end + offset) .unwrap_or(source.len()); let header = &source[*end..header_end]; - let name_end = header.find('(').unwrap_or(header.len()); + let mut name_end = header.len(); + let mut at = 0; + let mut brackets = 0usize; + while at < header.len() { + if skip_token(header, &mut at) { + continue; + } + match header.as_bytes()[at] { + b'[' => brackets += 1, + b']' => brackets = brackets.saturating_sub(1), + b'(' => { + if brackets == 0 { + name_end = at; + } + if let Some(end) = parens(header, at) { + at = end; + continue; + } + } + _ => {} + } + at += 1; + } if let Some((_, _, name)) = sv_words(&header[..name_end]).last() { result .tasks diff --git a/crates/celox-test-suite/src/script/sv.rs b/crates/celox-test-suite/src/script/sv.rs index 2a4e4b4b054..7f57fe298e0 100644 --- a/crates/celox-test-suite/src/script/sv.rs +++ b/crates/celox-test-suite/src/script/sv.rs @@ -133,7 +133,7 @@ fn icarus_finish_notice(line: &str) -> Option<(&str, &str)> { } /// Whether `line` is a simulator's notice of a `$finish` in one of the -/// simulation's source files `sources` (file names): a design may print a +/// simulation's source files `sources` (canonical paths): a design may print a /// line of the same shape, which is its output. fn is_source_finish_notice(line: &str, sources: &[String]) -> bool { is_finish_notice(line) @@ -142,7 +142,7 @@ fn is_source_finish_notice(line: &str, sources: &[String]) -> bool { .file_name() .map(|name| name.to_string_lossy().into_owned()) .unwrap_or_default(); - name == "timed_control.sv" && sources.contains(&name) + name == "timed_control.sv" && sources.iter().any(|source| source == file) }) } @@ -1158,14 +1158,14 @@ mod tests { #[test] fn finish_notices_are_not_design_output() { - let sources = vec!["timed_control.sv".to_string()]; + let sources = vec!["/stage/timed_control.sv".to_string()]; for log in [ - b"done\ntimed_control.sv:3: $finish called at 5 (1ns)\n".as_slice(), - b"done\n- timed_control.sv:3: Verilog $finish\n", + b"done\n/stage/timed_control.sv:3: $finish called at 5 (1ns)\n".as_slice(), + b"done\n- /stage/timed_control.sv:3: Verilog $finish\n", ] { assert_eq!(design_output(log, &sources), b"done\n"); } - let printed = b"\x80\xffsource_0.sv:3: $finish called at 5 (1ns)\n"; + let printed = b"\x80\xfftimed_control.sv:3: $finish called at 5 (1ns)\n"; assert_eq!(design_output(printed, &sources), printed); } diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 8e7c8b1745b..474b98d02a3 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -779,3 +779,17 @@ endmodule"#) always @(posedge clk) $unit::tick(q); endmodule"#) (top Top)(set clk 1)(run_until 0)(assert_eq q 1)) + +(case function_return_bounds_do_not_shadow_local_calls + (source "bounds.sv" #"module Other; task tick(); #1; endtask endmodule + module Top(input bit clk,output bit q); parameter N=2; + function logic [$clog2(N)-1:0] tick(); return 1; endfunction + always @(posedge clk) q<=tick(); endmodule"#) + (top Top)(set clk 1)(run_until 0)(assert_eq q 1)) + +(case control_shaped_display_is_design_output + (source "printed.sv" #"module Top; + initial begin $display("timed_control.sv:3: $finish called at 5 (1ns)"); + $display("- timed_control.sv:3: Verilog $finish"); #5; $finish; end endmodule"#) + (top Top)(run_to_finish) + (expect_output "timed_control.sv:3: $finish called at 5 (1ns)\n- timed_control.sv:3: Verilog $finish\n")) diff --git a/crates/celox-test-suite/src/verification.rs b/crates/celox-test-suite/src/verification.rs index 2a54c3452c4..1fbef4dbc30 100644 --- a/crates/celox-test-suite/src/verification.rs +++ b/crates/celox-test-suite/src/verification.rs @@ -621,7 +621,14 @@ fn run_script( .map(|entries| { entries .filter_map(|entry| entry.ok()) - .map(|entry| entry.file_name().to_string_lossy().into_owned()) + .map(|entry| { + entry + .path() + .canonicalize() + .unwrap_or_else(|_| entry.path()) + .to_string_lossy() + .into_owned() + }) .filter(|name| name.ends_with(".sv") || name.ends_with(".v")) .collect() }) diff --git a/crates/celox/tests/systemverilog.rs b/crates/celox/tests/systemverilog.rs index 310eb967a7f..60f7cc28eeb 100644 --- a/crates/celox/tests/systemverilog.rs +++ b/crates/celox/tests/systemverilog.rs @@ -235,3 +235,8 @@ sv_backends! { fn timed_file_macros_keep_each_source_path(sim) { @case "timing::timed_file_macros_keep_each_source_path"; } fn escaped_identifiers_do_not_collide_with_control_names(sim) { @case "timing::escaped_identifiers_do_not_collide_with_control_names"; } } + +sv_backends! { + fn function_return_bounds_do_not_shadow_local_calls(sim) { @case "timing::function_return_bounds_do_not_shadow_local_calls"; } + fn control_shaped_display_is_design_output(sim) { @case "timing::control_shaped_display_is_design_output"; } +} From 0848452d9191fe2edac035ded629e94e85cb685e Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 08:15:36 +0900 Subject: [PATCH 29/75] fix(runtime): preserve pending host edges across setup and restore --- crates/celox-runtime/src/simulation.rs | 17 +++++++ crates/celox-test-suite/src/frontend.rs | 9 +++- .../celox-test-suite/src/frontend/timed_ff.rs | 34 ++++++++++--- crates/celox-test-suite/src/script/sv.rs | 2 +- .../src/sv/cases/timing.vtest | 10 ++++ crates/celox/src/simulation.rs | 51 +++++++++++++++++-- .../tests/frontends/systemverilog/suite.rs | 2 + crates/celox/tests/systemverilog.rs | 5 ++ 8 files changed, 118 insertions(+), 12 deletions(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index b4e367e3d62..afda219e324 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -666,6 +666,23 @@ impl SimulationState { let num_events = executor.backend().num_events(); let mut scheduled_edges = BitSet::with_capacity(num_events); + // Pending host writes share this round with current-time scheduled + // edges. Record their net transitions before scheduled values replace + // them and before clearing the backend's transient trigger hints. + for (signal, id, _) in &self.topo_signals { + if *id != usize::MAX + && self.edge_triggers( + *id, + ( + self.last_clock_values.contains(*id), + self.unknown_clock_values.contains(*id), + ), + sample_event_signal(executor.backend(), *signal), + ) + { + scheduled_edges.insert(*id); + } + } for event in &events_to_process { let before = sample_event_signal(executor.backend(), event.signal); executor.backend_mut().set(event.signal, event.next_val); diff --git a/crates/celox-test-suite/src/frontend.rs b/crates/celox-test-suite/src/frontend.rs index cd462b40af6..169a5abb7ea 100644 --- a/crates/celox-test-suite/src/frontend.rs +++ b/crates/celox-test-suite/src/frontend.rs @@ -155,6 +155,10 @@ pub(crate) fn stage( const TIMED_CONTROL: &str = r#"package celox_suite_timed_control; bit started = 0; + bit setup_started = 0; + function automatic void celox_suite_begin_setup(); + setup_started = 1; + endfunction bit finished = 0; function automatic void celox_suite_start_design(); started = 1; @@ -173,6 +177,7 @@ endpackage struct TimedNames { package: String, start: String, + setup: String, finish: String, } @@ -196,9 +201,10 @@ fn timed_names(sources: &[String]) -> TimedNames { let names = TimedNames { package: name("celox_suite_timed_control"), start: name("celox_suite_start_design"), + setup: name("celox_suite_begin_setup"), finish: name("celox_suite_finish_design"), }; - if [&names.package, &names.start, &names.finish] + if [&names.package, &names.start, &names.finish, &names.setup] .into_iter() .all(|name| !words.contains(name.as_str())) { @@ -227,6 +233,7 @@ impl TimedNames { { &self.package } + "celox_suite_begin_setup" if tail.starts_with('(') => &self.setup, "celox_suite_start_design" if tail.starts_with('(') => &self.start, "celox_suite_finish_design" if tail.starts_with('(') => &self.finish, _ => continue, diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index a88124c2371..74817910cc8 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -256,13 +256,31 @@ pub(super) fn gated( unreachable!() }; let armed = fresh("armed"); - let pending = fresh("pending"); + let captured = fresh("captured"); let package = &names.package; let event = &source[begin + 1..event_end - 1]; let replacement_start = attributes_start(source, start); let attributes = &source[replacement_start..start]; + let mut declarations = String::new(); + let mut samples = Vec::new(); + let mut active = Vec::new(); + for (index, leaf) in event_leaves(event).into_iter().enumerate() { + let leaf = after_trivia(leaf); + let (_, end, edge) = *sv_words(leaf).first().ok_or("empty FF event")?; + if !matches!(edge, "posedge" | "negedge") { + return Err("FF staging requires edge-qualified events".into()); + } + let sample = format!("1'({})", &leaf[end..]); + let baseline = fresh(&format!("baseline_{index}")); + declarations.push_str(&format!("logic {baseline};\n")); + samples.push(format!("{baseline}={sample};")); + let (from, to) = if edge == "posedge" { (0, 1) } else { (1, 0) }; + active.push(format!("(({baseline}===1'b{from} && {sample}!==1'b{from}) || ({baseline}!==1'b{to} && {sample}===1'b{to}))")); + } + let samples = samples.join(" "); + let active = active.join(" || "); let staged = format!( - "bit {armed}=0;\nbit {pending}=0;\n{attributes}always @({event} or posedge {package}::started) begin\n if (!{package}::started) {pending}=1;\n else if ({armed} || {pending}) begin\n {pending}=0;\n {body}\n end\n {armed}={package}::started;\nend" + "bit {armed}=0;\nbit {captured}=0;\n{declarations}{attributes}always @({event} or posedge {package}::setup_started or posedge {package}::started) begin\n if (!{package}::started) begin\n if ({package}::setup_started && !{captured}) begin {samples} {captured}=1; end\n end\n else if ({armed} || ({active})) begin\n {body}\n end\n {armed}={package}::started;\nend" ); // A single generate item needs a block for the additional declarations. // Reuse that construct's unnamed body rather than inserting another if, @@ -294,6 +312,13 @@ pub(super) fn edge_control(source: &str, end: usize, tasks: &TaskTiming) -> bool return false; } let event = &source[begin + 1..end - 1]; + event_leaves(event).into_iter().all(|leaf| { + let leaf = after_trivia(leaf); + matches!(sv_words(leaf).first(), Some((0, _, "posedge" | "negedge"))) + }) +} + +fn event_leaves(event: &str) -> Vec<&str> { let ors = sv_words(event) .into_iter() .filter_map(|(start, _, word)| (word == "or").then_some(start)) @@ -320,10 +345,7 @@ pub(super) fn edge_control(source: &str, end: usize, tasks: &TaskTiming) -> bool at += 1; } leaves.push(&event[start..]); - leaves.into_iter().all(|leaf| { - let leaf = after_trivia(leaf); - matches!(sv_words(leaf).first(), Some((0, _, "posedge" | "negedge"))) - }) + leaves } /// Multiline macro replacements must keep every generated line in the diff --git a/crates/celox-test-suite/src/script/sv.rs b/crates/celox-test-suite/src/script/sv.rs index 7f57fe298e0..ca4eba62606 100644 --- a/crates/celox-test-suite/src/script/sv.rs +++ b/crates/celox-test-suite/src/script/sv.rs @@ -1146,7 +1146,7 @@ pub fn testbench(case: &ScriptCase, design: &DesignInfo) -> Result Simulation { (event, value.bit(0), mask.bit(0)) }) .collect(); - parts.high_events = samples - .iter() - .filter_map(|(event, high, _)| high.then_some(*event)) - .collect(); + parts.unknown_events = samples .iter() .filter_map(|(event, _, unknown)| unknown.then_some(*event)) @@ -1890,3 +1887,49 @@ mod legacy_clock_state_review_tests { } } } + +#[cfg(all(test, feature = "systemverilog"))] +mod staged_edge_review_tests { + use super::*; + fn check(mut sim: Simulation, mut restored: Simulation) { + let a = sim.signal("a"); + let qa = sim.signal("qa"); + let qb = sim.signal("qb"); + sim.set_wide(a, 1u8.into()); + let mut file = sim.save_state().unwrap(); + file.schedule.as_mut().unwrap().unknown_events = None; + let mut bytes = Vec::new(); + file.write_to(&mut bytes).unwrap(); + let file = celox_runtime::StateFile::read_from(bytes.as_slice()).unwrap(); + restored.load_state(&file).unwrap(); + restored.settle().unwrap(); + assert_eq!(restored.get(qa), 1u8.into()); + sim.schedule("b", 0, 1).unwrap(); + sim.settle().unwrap(); + assert_eq!(sim.get(qa), 1u8.into()); + assert_eq!(sim.get(qb), 1u8.into()); + } + #[test] + fn host_edges_join_current_time_events_and_survive_legacy_state_files() { + let source = "module Top(input bit a,b,output bit[7:0]qa,qb);always @(posedge a)qa<=qb+1;always @(posedge b)qb<=qa+1;endmodule"; + let build = + || Simulator::from_sv_sources(vec![(source, std::path::Path::new("staged.sv"))], "Top"); + check( + Simulation::new(build().build_interpreter().unwrap()), + Simulation::new(build().build_interpreter().unwrap()), + ); + check( + Simulation::new(build().build_cranelift().unwrap()), + Simulation::new(build().build_cranelift().unwrap()), + ); + check( + Simulation::new(build().build_wasm().unwrap()), + Simulation::new(build().build_wasm().unwrap()), + ); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check( + Simulation::new(build().build_native().unwrap()), + Simulation::new(build().build_native().unwrap()), + ); + } +} diff --git a/crates/celox/tests/frontends/systemverilog/suite.rs b/crates/celox/tests/frontends/systemverilog/suite.rs index 0c02a9b7e15..96634124ccb 100644 --- a/crates/celox/tests/frontends/systemverilog/suite.rs +++ b/crates/celox/tests/frontends/systemverilog/suite.rs @@ -131,6 +131,8 @@ impl Backend for TimedBackend { "run_to_finish: the design already finished before the operation began".into(), ); } + self.0.settle()?; + self.capture_events()?; while !self.finished() { let step = self.0.step()?; self.capture_events()?; diff --git a/crates/celox/tests/systemverilog.rs b/crates/celox/tests/systemverilog.rs index 60f7cc28eeb..6e886732732 100644 --- a/crates/celox/tests/systemverilog.rs +++ b/crates/celox/tests/systemverilog.rs @@ -240,3 +240,8 @@ sv_backends! { fn function_return_bounds_do_not_shadow_local_calls(sim) { @case "timing::function_return_bounds_do_not_shadow_local_calls"; } fn control_shaped_display_is_design_output(sim) { @case "timing::control_shaped_display_is_design_output"; } } + +sv_backends! { + fn staged_ff_edge_can_finish_without_scheduled_work(sim) { @case "timing::staged_ff_edge_can_finish_without_scheduled_work"; } + fn coalesced_setup_writes_do_not_invent_ff_edges(sim) { @case "timing::coalesced_setup_writes_do_not_invent_ff_edges"; } +} From 53a2bf01fa4c09f9d0ec021801079c0fed78dd96 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 08:49:16 +0900 Subject: [PATCH 30/75] fix(suite): share FF control classification with the analyzer --- crates/celox-test-suite/src/frontend/timed_ff.rs | 12 ++++++++++++ crates/celox-test-suite/src/sv/cases/timing.vtest | 13 +++++++++++++ crates/celox/tests/systemverilog.rs | 5 +++++ 3 files changed, 30 insertions(+) diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index 74817910cc8..84d2f39f2cb 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -296,6 +296,13 @@ pub(super) fn gated( /// The frontend classifies an ordinary always as FF only when every leaf /// of its event list is explicitly edge-qualified. pub(super) fn edge_control(source: &str, end: usize, tasks: &TaskTiming) -> bool { + if tasks + .ff_offsets + .get(source) + .is_some_and(|offsets| !offsets.contains(&end.saturating_sub("always".len()))) + { + return false; + } let at = trivia(source, end); if source.as_bytes().get(at) != Some(&b'@') { return false; @@ -426,6 +433,7 @@ fn has_timing(source: &str) -> bool { pub(super) struct TaskTiming { tasks: BTreeMap<(String, Vec, String), bool>, generate_scopes: BTreeMap>, + ff_offsets: BTreeMap>, imports: BTreeMap)>>, exports: BTreeMap, Option)>>, } @@ -538,6 +546,10 @@ impl TaskTiming { for source in sources { if let Ok(tree) = celox_sv_analyzer::syntax::parse_source(source, Path::new("timed.sv")) { + result.ff_offsets.insert( + source.clone(), + celox_sv_analyzer::ast::ff_always_offsets(&tree), + ); result.generate_scopes.insert( source.clone(), celox_sv_analyzer::ast::generate_scope_ranges(&tree), diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 8a34d4c529d..ecffda8df6d 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -803,3 +803,16 @@ endmodule"#) always @(posedge clk) q<=q+1;always @(negedge rst)r<=r+1;endmodule"#) (top Top)(set clk 1)(set clk 0)(set rst 1)(set rst 0) (run_until 0)(assert_eq q 0)(assert_eq r 0)) + +(case computed_edge_always_processes_arm_after_setup + (source "computed-always.sv" #"module Top(input bit a,b,output bit[7:0]seen); + always @(posedge (a|b))seen=seen+1;endmodule"#) + (top Top)(set a 1)(run_until 0)(assert_eq seen 0) + (set a 0)(eval)(set a 1)(eval)(assert_eq seen 1)) + +(case non_ff_multiple_edge_always_processes_arm_after_setup + (source "multi-always.sv" #"module Top(input bit a,b,output bit[7:0]seen); + always @(posedge a or negedge b)seen=seen+1;endmodule"#) + (top Top)(set a 1)(run_until 0)(assert_eq seen 0) + (set a 0)(eval)(set a 1)(eval)(assert_eq seen 1) + (set b 1)(eval)(set b 0)(eval)(assert_eq seen 2)) diff --git a/crates/celox/tests/systemverilog.rs b/crates/celox/tests/systemverilog.rs index 6e886732732..8e516abaef9 100644 --- a/crates/celox/tests/systemverilog.rs +++ b/crates/celox/tests/systemverilog.rs @@ -245,3 +245,8 @@ sv_backends! { fn staged_ff_edge_can_finish_without_scheduled_work(sim) { @case "timing::staged_ff_edge_can_finish_without_scheduled_work"; } fn coalesced_setup_writes_do_not_invent_ff_edges(sim) { @case "timing::coalesced_setup_writes_do_not_invent_ff_edges"; } } + +sv_backends! { + fn computed_edge_always_processes_arm_after_setup(sim) { @case "timing::computed_edge_always_processes_arm_after_setup"; } + fn non_ff_multiple_edge_always_processes_arm_after_setup(sim) { @case "timing::non_ff_multiple_edge_always_processes_arm_after_setup"; } +} From 203c7f22612c0ff9837768face4a0dfeda541999 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 09:37:30 +0900 Subject: [PATCH 31/75] fix(runtime): settle pending host edges and preserve legacy baselines --- .../celox-test-suite/src/frontend/timed_ff.rs | 21 ++- .../src/sv/cases/timing.vtest | 12 ++ crates/celox/src/simulation.rs | 161 +++++++++++++++--- crates/celox/tests/systemverilog.rs | 5 + 4 files changed, 171 insertions(+), 28 deletions(-) diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index 84d2f39f2cb..7745d2b721e 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -258,13 +258,14 @@ pub(super) fn gated( let armed = fresh("armed"); let captured = fresh("captured"); let package = &names.package; - let event = &source[begin + 1..event_end - 1]; + let original_event = &source[begin + 1..event_end - 1]; + let event = event_leaves(original_event).join(" or "); let replacement_start = attributes_start(source, start); let attributes = &source[replacement_start..start]; let mut declarations = String::new(); let mut samples = Vec::new(); let mut active = Vec::new(); - for (index, leaf) in event_leaves(event).into_iter().enumerate() { + for (index, leaf) in event_leaves(&event).into_iter().enumerate() { let leaf = after_trivia(leaf); let (_, end, edge) = *sv_words(leaf).first().ok_or("empty FF event")?; if !matches!(edge, "posedge" | "negedge") { @@ -326,6 +327,7 @@ pub(super) fn edge_control(source: &str, end: usize, tasks: &TaskTiming) -> bool } fn event_leaves(event: &str) -> Vec<&str> { + let event = unwrap_event_leaf(event); let ors = sv_words(event) .into_iter() .filter_map(|(start, _, word)| (word == "or").then_some(start)) @@ -352,7 +354,18 @@ fn event_leaves(event: &str) -> Vec<&str> { at += 1; } leaves.push(&event[start..]); - leaves + leaves.into_iter().map(unwrap_event_leaf).collect() +} + +fn unwrap_event_leaf(mut event: &str) -> &str { + event = after_trivia(event).trim(); + while let Some(end) = parens(event, 0) { + if !after_trivia(&event[end..]).is_empty() { + break; + } + event = after_trivia(&event[1..end - 1]).trim(); + } + event } /// Multiline macro replacements must keep every generated line in the @@ -775,7 +788,7 @@ impl TaskTiming { || prefix.ends_with([';', ')', ':', '.']) || sv_words(prefix) .last() - .is_some_and(|word| matches!(word.2, "begin" | "end" | "else")); + .is_some_and(|word| matches!(word.2, "begin" | "end" | "else" | "forever")); (tail.starts_with('(') || (tail.starts_with(';') && statement_start)) && self.resolve(source, start + at, name).unwrap_or(true) }) diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index ecffda8df6d..7e9a1614aba 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -816,3 +816,15 @@ endmodule"#) (top Top)(set a 1)(run_until 0)(assert_eq seen 0) (set a 0)(eval)(set a 1)(eval)(assert_eq seen 1) (set b 1)(eval)(set b 0)(eval)(assert_eq seen 2)) + +(case timed_calls_after_forever_do_not_replay_setup_edges + (source "forever-task.sv" #"module Top(input bit clk,output bit q); + task automatic tick();#1 q=1;endtask + always @(posedge clk)forever tick; + initial begin #3;$finish;end endmodule"#) + (top Top)(set clk 1)(run_to_finish)(assert_eq q 0)) + +(case parenthesized_ff_event_leaves_preserve_setup_edges + (source "parenthesized.sv" #"module Top(input bit clk,output bit q,r); + always @((posedge clk))q<=1;always_ff @((posedge clk))r<=1;endmodule"#) + (top Top)(set clk 1)(run_until 0)(assert_eq q 1)(assert_eq r 1)) diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 36e81c1d0a4..f76e76ee924 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -327,29 +327,11 @@ impl Simulation { } let record = file.schedule.as_ref().ok_or(StateError::MissingSchedule)?; self.simulator.check_vcd_rewind(record.time)?; - let mut parts = self.simulator.resolve_schedule(record)?; + let parts = self.simulator.resolve_schedule(record)?; self.simulator.load_state(file)?; - if record.unknown_events.is_none() { - // Version 1 lacks masks for edge baselines. Resolve them from the - // loaded backend so aliases and two-state conversions agree too. - let samples: Vec<_> = self - .simulator - .backend - .id_to_event_slice() - .iter() - .copied() - .map(|event| { - let signal = self.simulator.backend.resolve_signal(&event.addr()); - let (value, mask) = self.simulator.backend.get_four_state(signal); - (event, value.bit(0), mask.bit(0)) - }) - .collect(); - - parts.unknown_events = samples - .iter() - .filter_map(|(event, _, unknown)| unknown.then_some(*event)) - .collect(); - } + // V1 recorded Boolean (known) baselines. Masks of the restored + // current values may belong to a still-pending write and cannot be + // substituted for those historical baselines. self.state.import_schedule(parts); Ok(()) } @@ -451,6 +433,15 @@ impl Simulation { /// Schedule a one-shot event at a specific time. /// The signal must be registered as an event (clock or async reset) in the backend. pub fn schedule(&mut self, port: &str, time: u64, value: u64) -> Result<(), RuntimeErrorCode> { + if time < self.state.time() { + return Err(RuntimeErrorCode::Runtime { + message: format!( + "cannot schedule an event in the past: {time} before {}", + self.state.time() + ), + signals: Vec::new(), + }); + } let signal = self.simulator.signal(port); let addr = self.simulator.program.get_addr(&[], &[port]).unwrap(); let ev_opt = self.simulator.backend.resolve_event_opt(&addr); @@ -471,10 +462,22 @@ impl Simulation { /// instead: the call then returns the current time without advancing, /// so what the process did is observable at its own time. pub fn step(&mut self) -> Result, RuntimeErrorCode> { + if self.state.is_finished() { + return Ok(None); + } self.settle_host_writes()?; if self.state.poll_waiting(&mut self.simulator)? { return Ok(Some(self.state.time())); } + if self.state.has_unsettled_edges(&self.simulator.backend) { + let time = self.state.time(); + if self.state.next_event_time() == Some(time) { + self.state.step(&mut self.simulator)?; + } else { + self.state.settle_at(&mut self.simulator, time)?; + } + return Ok(Some(time)); + } self.state.step(&mut self.simulator) } @@ -534,6 +537,9 @@ impl Simulation { /// Run one step at or before `limit`, including processes a host write /// woke at the current time. Leave a later event queued. pub fn step_until(&mut self, limit: u64) -> Result, RuntimeErrorCode> { + if self.state.is_finished() { + return Ok(None); + } if self.state.time() > limit { return Ok(None); } @@ -541,6 +547,15 @@ impl Simulation { if self.state.poll_waiting(&mut self.simulator)? { return Ok(Some(self.state.time())); } + if self.state.has_unsettled_edges(&self.simulator.backend) { + let time = self.state.time(); + if self.state.next_event_time() == Some(time) { + self.state.step(&mut self.simulator)?; + } else { + self.state.settle_at(&mut self.simulator, time)?; + } + return Ok(Some(time)); + } if self .state .next_event_time() @@ -555,11 +570,22 @@ impl Simulation { /// Advance time and run until `end_time` (inclusive). As for /// [`Self::step`], processes that a host write woke resume first. pub fn run_until(&mut self, end_time: u64) -> Result<(), RuntimeErrorCode> { + if self.state.is_finished() { + return Ok(()); + } if self.state.time() > end_time { return Ok(()); } self.settle_host_writes()?; self.state.poll_waiting(&mut self.simulator)?; + if self.state.has_unsettled_edges(&self.simulator.backend) { + let time = self.state.time(); + if self.state.next_event_time() == Some(time) { + self.state.step(&mut self.simulator)?; + } else { + self.state.settle_at(&mut self.simulator, time)?; + } + } while let Some(next_time) = self.state.next_event_time() { if next_time > end_time { break; @@ -1851,10 +1877,10 @@ mod legacy_clock_state_review_tests { let clk = target.signal("clk"); target.set_four_state(clk, known.into(), 0u8.into()); target.settle().unwrap(); - assert_eq!(target.get(q), before + 1u8); + assert_eq!(target.get(q), before); } #[test] - fn legacy_files_restore_unknown_clock_baselines() { + fn legacy_files_keep_known_boolean_clock_baselines() { for (edge, known) in [("posedge", 1u8), ("negedge", 0u8)] { let source = format!( "module Top(input logic clk,output int q);always @({edge} clk)q<=q+1;endmodule" @@ -1976,3 +2002,90 @@ mod finished_host_write_review_tests { } } } + +#[cfg(all(test, feature = "systemverilog"))] +mod public_host_edge_review_tests { + use super::*; + fn check(mut sim: Simulation, operation: &str) { + let clk = sim.signal("clk"); + let q = sim.signal("q"); + sim.set_wide(clk, 1u8.into()); + match operation { + "step" => { + sim.step().unwrap(); + } + "step_until" => { + sim.step_until(0).unwrap(); + } + _ => sim.run_until(0).unwrap(), + }; + assert_eq!(sim.get(q), 1u8.into()); + assert_eq!(sim.time(), 0); + sim.run_until(10).unwrap(); + assert!(sim.schedule("clk", 5, 0).is_err()); + sim.settle().unwrap(); + assert_eq!(sim.time(), 10); + } + #[test] + fn public_runs_settle_host_edges_and_reject_past_schedules() { + let source = "module Top(input bit clk,output bit q);always @(posedge clk)q<=1;endmodule"; + for operation in ["step", "step_until", "run_until"] { + let build = || { + Simulator::from_sv_sources( + vec![(source, std::path::Path::new("host-edge.sv"))], + "Top", + ) + }; + check( + Simulation::new(build().build_interpreter().unwrap()), + operation, + ); + check( + Simulation::new(build().build_cranelift().unwrap()), + operation, + ); + check(Simulation::new(build().build_wasm().unwrap()), operation); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap()), operation); + } + } + #[test] + fn legacy_pending_known_to_unknown_edges_keep_their_known_baseline() { + let source = "module Top(input logic clk,output bit q);always @(posedge clk)q<=1;endmodule"; + let build = || { + Simulator::from_sv_sources( + vec![(source, std::path::Path::new("legacy-pending.sv"))], + "Top", + ) + .four_state(true) + }; + fn check(mut source: Simulation, mut target: Simulation) { + source.set_four_state(source.signal("clk"), 0u8.into(), 1u8.into()); + let mut file = source.save_state().unwrap(); + file.schedule.as_mut().unwrap().unknown_events = None; + let mut bytes = Vec::new(); + file.write_to(&mut bytes).unwrap(); + let file = celox_runtime::StateFile::read_from(bytes.as_slice()).unwrap(); + target.load_state(&file).unwrap(); + target.settle().unwrap(); + assert_eq!(target.get(target.signal("q")), 1u8.into()); + } + check( + Simulation::new(build().build_interpreter().unwrap()), + Simulation::new(build().build_interpreter().unwrap()), + ); + check( + Simulation::new(build().build_cranelift().unwrap()), + Simulation::new(build().build_cranelift().unwrap()), + ); + check( + Simulation::new(build().build_wasm().unwrap()), + Simulation::new(build().build_wasm().unwrap()), + ); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check( + Simulation::new(build().build_native().unwrap()), + Simulation::new(build().build_native().unwrap()), + ); + } +} diff --git a/crates/celox/tests/systemverilog.rs b/crates/celox/tests/systemverilog.rs index 8e516abaef9..a172ff228d5 100644 --- a/crates/celox/tests/systemverilog.rs +++ b/crates/celox/tests/systemverilog.rs @@ -250,3 +250,8 @@ sv_backends! { fn computed_edge_always_processes_arm_after_setup(sim) { @case "timing::computed_edge_always_processes_arm_after_setup"; } fn non_ff_multiple_edge_always_processes_arm_after_setup(sim) { @case "timing::non_ff_multiple_edge_always_processes_arm_after_setup"; } } + +sv_backends! { + fn timed_calls_after_forever_do_not_replay_setup_edges(sim) { @case "timing::timed_calls_after_forever_do_not_replay_setup_edges"; } + fn parenthesized_ff_event_leaves_preserve_setup_edges(sim) { @case "timing::parenthesized_ff_event_leaves_preserve_setup_edges"; } +} From ce623993ff5d270d4fefaa577f72b2dac697d0ed Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 09:44:09 +0900 Subject: [PATCH 32/75] fix(suite): distinguish named arguments from timed calls --- crates/celox-test-suite/src/frontend/timed_ff.rs | 7 +++++++ crates/celox-test-suite/src/sv/cases/timing.vtest | 7 +++++++ crates/celox/tests/systemverilog.rs | 3 +++ 3 files changed, 17 insertions(+) diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index 7745d2b721e..94c24380034 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -784,6 +784,13 @@ impl TaskTiming { } let tail = after_trivia(&source[start + word_end..end]); let prefix = source[start..start + at].trim_end(); + // .formal(expr) is a named actual, not a method call. A + // qualified call has an identifier before the dot. + if let Some(before_dot) = prefix.strip_suffix('.') + && before_dot.trim_end().ends_with(['(', ',']) + { + return false; + } let statement_start = prefix.is_empty() || prefix.ends_with([';', ')', ':', '.']) || sv_words(prefix) diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 7e9a1614aba..c5e697b29ab 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -828,3 +828,10 @@ endmodule"#) (source "parenthesized.sv" #"module Top(input bit clk,output bit q,r); always @((posedge clk))q<=1;always_ff @((posedge clk))r<=1;endmodule"#) (top Top)(set clk 1)(run_until 0)(assert_eq q 1)(assert_eq r 1)) + +(case named_arguments_do_not_invent_timed_calls + (source "named-call.sv" #"module Top(input bit clk,output bit q); + task automatic tick();#1;endtask + function automatic bit f(input bit tick);return tick;endfunction + always @(posedge clk)q<=f(.tick(1));endmodule"#) + (top Top)(set clk 1)(run_until 0)(assert_eq q 1)) diff --git a/crates/celox/tests/systemverilog.rs b/crates/celox/tests/systemverilog.rs index a172ff228d5..eba1612d9d2 100644 --- a/crates/celox/tests/systemverilog.rs +++ b/crates/celox/tests/systemverilog.rs @@ -255,3 +255,6 @@ sv_backends! { fn timed_calls_after_forever_do_not_replay_setup_edges(sim) { @case "timing::timed_calls_after_forever_do_not_replay_setup_edges"; } fn parenthesized_ff_event_leaves_preserve_setup_edges(sim) { @case "timing::parenthesized_ff_event_leaves_preserve_setup_edges"; } } +sv_backends! { + fn named_arguments_do_not_invent_timed_calls(sim) { @case "timing::named_arguments_do_not_invent_timed_calls"; } +} From 1237157c3a46197f1397d520168414dd0b5810b2 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 10:09:53 +0900 Subject: [PATCH 33/75] fix(suite): recognize bare timed calls after do --- crates/celox-test-suite/src/frontend/timed_ff.rs | 6 +++--- crates/celox-test-suite/src/sv/cases/timing.vtest | 7 +++++++ crates/celox/tests/systemverilog.rs | 3 +++ 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index 94c24380034..232eb12f6ea 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -793,9 +793,9 @@ impl TaskTiming { } let statement_start = prefix.is_empty() || prefix.ends_with([';', ')', ':', '.']) - || sv_words(prefix) - .last() - .is_some_and(|word| matches!(word.2, "begin" | "end" | "else" | "forever")); + || sv_words(prefix).last().is_some_and(|word| { + matches!(word.2, "begin" | "end" | "else" | "forever" | "do") + }); (tail.starts_with('(') || (tail.starts_with(';') && statement_start)) && self.resolve(source, start + at, name).unwrap_or(true) }) diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index c5e697b29ab..19b22272b81 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -835,3 +835,10 @@ endmodule"#) function automatic bit f(input bit tick);return tick;endfunction always @(posedge clk)q<=f(.tick(1));endmodule"#) (top Top)(set clk 1)(run_until 0)(assert_eq q 1)) + +(case timed_calls_after_do_do_not_replay_setup_edges + (source "do-task.sv" #"module Top(input bit clk,output bit q); + task automatic tick();#1 q=1;endtask + always @(posedge clk)do tick;while(0); + initial begin #3;$finish;end endmodule"#) + (top Top)(set clk 1)(run_to_finish)(assert_eq q 0)) diff --git a/crates/celox/tests/systemverilog.rs b/crates/celox/tests/systemverilog.rs index eba1612d9d2..56437b75ef2 100644 --- a/crates/celox/tests/systemverilog.rs +++ b/crates/celox/tests/systemverilog.rs @@ -258,3 +258,6 @@ sv_backends! { sv_backends! { fn named_arguments_do_not_invent_timed_calls(sim) { @case "timing::named_arguments_do_not_invent_timed_calls"; } } +sv_backends! { + fn timed_calls_after_do_do_not_replay_setup_edges(sim) { @case "timing::timed_calls_after_do_do_not_replay_setup_edges"; } +} From 561e95f3bb2b5e2c4b72b9e8ae3234ac7c6965b8 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 11:00:30 +0900 Subject: [PATCH 34/75] fix(suite): preserve named-block timing and reject past by-ID events --- .../celox-test-suite/src/frontend/timed_ff.rs | 10 ++- .../src/sv/cases/timing.vtest | 7 ++ crates/celox/src/simulation.rs | 74 ++++++++++++++++--- crates/celox/tests/systemverilog.rs | 3 + 4 files changed, 81 insertions(+), 13 deletions(-) diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index 232eb12f6ea..1ce3984c380 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -791,9 +791,15 @@ impl TaskTiming { { return false; } - let statement_start = prefix.is_empty() + let words = sv_words(prefix); + let named_block = words.len() >= 2 + && words[words.len() - 2].2 == "begin" + && after_trivia(&prefix[words[words.len() - 2].1..]).starts_with(':') + && after_trivia(&prefix[words[words.len() - 1].1..]).is_empty(); + let statement_start = named_block + || prefix.is_empty() || prefix.ends_with([';', ')', ':', '.']) - || sv_words(prefix).last().is_some_and(|word| { + || words.last().is_some_and(|word| { matches!(word.2, "begin" | "end" | "else" | "forever" | "do") }); (tail.starts_with('(') || (tail.starts_with(';') && statement_start)) diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 19b22272b81..a569cea3a7e 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -842,3 +842,10 @@ endmodule"#) always @(posedge clk)do tick;while(0); initial begin #3;$finish;end endmodule"#) (top Top)(set clk 1)(run_to_finish)(assert_eq q 0)) + +(case timed_calls_after_named_blocks_do_not_replay_setup_edges + (source "named-block-task.sv" #"module Top(input bit clk,output bit q); + task automatic tick();#1 q=1;endtask + always @(posedge clk)begin : work tick;end + initial begin #3;$finish;end endmodule"#) + (top Top)(set clk 1)(run_to_finish)(assert_eq q 0)) diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index a973c831519..e915d6b9ec3 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -418,11 +418,29 @@ impl Simulation { self.simulator.modify(f) } + fn validate_event_time(&self, time: u64) -> Result<(), RuntimeErrorCode> { + if time < self.state.time() { + return Err(RuntimeErrorCode::Runtime { + message: format!( + "cannot schedule an event in the past: {time} before {}", + self.state.time() + ), + signals: Vec::new(), + }); + } + Ok(()) + } + /// Register a clock signal and its period, enqueuing the first edge. /// Odd periods alternate floor/ceil half periods. Periods below two /// time units use a two-unit period so both phases advance time. - /// `initial_delay` specifies when the first rising edge occurs. + /// `initial_delay` specifies when the first rising edge occurs. Past + /// timestamps are ignored by this compatibility API; use + /// [`Self::try_add_clock_by_id`] for an error result. pub fn add_clock(&mut self, port: &str, period: u64, initial_delay: u64) { + if self.validate_event_time(initial_delay).is_err() { + return; + } let signal = self.simulator.signal(port); let addr = self.simulator.program.get_addr(&[], &[port]).unwrap(); if let Some(ev) = self.simulator.backend.resolve_event_opt(&addr) { @@ -433,15 +451,7 @@ impl Simulation { /// Schedule a one-shot event at a specific time. /// The signal must be registered as an event (clock or async reset) in the backend. pub fn schedule(&mut self, port: &str, time: u64, value: u64) -> Result<(), RuntimeErrorCode> { - if time < self.state.time() { - return Err(RuntimeErrorCode::Runtime { - message: format!( - "cannot schedule an event in the past: {time} before {}", - self.state.time() - ), - signals: Vec::new(), - }); - } + self.validate_event_time(time)?; let signal = self.simulator.signal(port); let addr = self.simulator.program.get_addr(&[], &[port]).unwrap(); let ev_opt = self.simulator.backend.resolve_event_opt(&addr); @@ -706,13 +716,15 @@ impl Simulation { /// # Errors /// /// Returns [`RuntimeErrorCode::NotAnEvent`] if `event_id` is unknown or - /// does not resolve to an event (clock or asynchronous reset). + /// does not resolve to an event (clock or asynchronous reset), or a runtime + /// error if the initial edge would precede the current time. pub fn try_add_clock_by_id( &mut self, event_id: u32, period: u64, initial_delay: u64, ) -> Result<(), RuntimeErrorCode> { + self.validate_event_time(initial_delay)?; let addr = self .simulator .backend @@ -741,6 +753,7 @@ impl Simulation { time: u64, value: u64, ) -> Result<(), RuntimeErrorCode> { + self.validate_event_time(time)?; let addr = self .simulator .backend @@ -2150,3 +2163,42 @@ mod scheduled_derived_concat_review_tests { } } } + +#[cfg(all(test, feature = "systemverilog"))] +mod past_by_id_review_tests { + use super::*; + fn check(mut sim: Simulation) { + sim.run_until(10).unwrap(); + let clk = sim.signal("clk"); + let id = sim + .simulator + .backend + .id_to_addr_slice() + .iter() + .position(|addr| sim.simulator.backend.resolve_signal(addr) == clk) + .unwrap() as u32; + assert!(sim.schedule_by_id(id, 5, 1).is_err()); + assert!(sim.try_add_clock_by_id(id, 4, 5).is_err()); + sim.add_clock("clk", 4, 5); + sim.add_clock_by_id(id, 4, 5); + sim.settle().unwrap(); + assert_eq!(sim.time(), 10); + assert_eq!(sim.next_event_time(), None); + sim.schedule_by_id(id, 10, 1).unwrap(); + sim.settle().unwrap(); + assert_eq!(sim.time(), 10); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + } + #[test] + fn by_id_schedules_and_clock_registration_cannot_rewind_time() { + let source = "module Top(input bit clk,output bit q);always @(posedge clk)q<=1;endmodule"; + let build = || { + Simulator::from_sv_sources(vec![(source, std::path::Path::new("past-id.sv"))], "Top") + }; + check(Simulation::new(build().build_interpreter().unwrap())); + check(Simulation::new(build().build_cranelift().unwrap())); + check(Simulation::new(build().build_wasm().unwrap())); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap())); + } +} diff --git a/crates/celox/tests/systemverilog.rs b/crates/celox/tests/systemverilog.rs index 56437b75ef2..37da5ed10f0 100644 --- a/crates/celox/tests/systemverilog.rs +++ b/crates/celox/tests/systemverilog.rs @@ -261,3 +261,6 @@ sv_backends! { sv_backends! { fn timed_calls_after_do_do_not_replay_setup_edges(sim) { @case "timing::timed_calls_after_do_do_not_replay_setup_edges"; } } +sv_backends! { + fn timed_calls_after_named_blocks_do_not_replay_setup_edges(sim) { @case "timing::timed_calls_after_named_blocks_do_not_replay_setup_edges"; } +} From 1a729ecdd280db386b8b8439a1b2e5578e558b0c Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 11:05:56 +0900 Subject: [PATCH 35/75] fix(suite): retain the reviewed Icarus unit-scope exclusion --- .../verification/sv/icarus/timing.json | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/crates/celox-test-suite/verification/sv/icarus/timing.json b/crates/celox-test-suite/verification/sv/icarus/timing.json index a3609e568e9..49f60cfd1a9 100644 --- a/crates/celox-test-suite/verification/sv/icarus/timing.json +++ b/crates/celox-test-suite/verification/sv/icarus/timing.json @@ -99,6 +99,29 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "Icarus 13.0 rejects $unit::tick(q) as a malformed statement. IEEE 1800-2023 3.12.1 permits scope-qualified compilation-unit identifiers. Celox and Verilator pass the unchanged timed task case.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_timed_unit_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_qualified_unit_task", + "observed_version": "Icarus 13.0 / Verilator 5.052", + "phase": "compile", + "reason": "Icarus 13.0 rejects $unit::tick(q) as a malformed statement. IEEE 1800-2023 3.12.1 permits scope-qualified compilation-unit identifiers. Celox and Verilator pass the unchanged timed task case.", + "upstream": [] + }, + "name": "timing::qualified_unit_tasks_keep_setup_edges", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", From d994f045b817e98e7c4f3dbfbf32aaf417bf2aa8 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 11:54:48 +0900 Subject: [PATCH 36/75] fix(suite): derive timing from parsed calls and active preprocessing --- Cargo.lock | 1 + crates/celox-runtime/src/simulation.rs | 15 ++++ crates/celox-sv-analyzer/src/ast.rs | 43 +++++++++++ crates/celox-test-suite/Cargo.toml | 1 + crates/celox-test-suite/src/frontend.rs | 4 +- .../celox-test-suite/src/frontend/timed_ff.rs | 18 ++++- crates/celox-test-suite/src/script/timed.rs | 61 ++++++++++++--- .../src/sv/cases/timing.vtest | 14 ++++ crates/celox/src/simulation.rs | 77 ++++++++++++++++++- crates/celox/tests/systemverilog.rs | 4 + 10 files changed, 220 insertions(+), 18 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 43ed14dc71e..b3352fcbc21 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -789,6 +789,7 @@ dependencies = [ "num-traits", "serde_json", "sha2 0.11.0", + "sv-parser", "veryl-analyzer", "veryl-emitter", "veryl-metadata", diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 13faba2ad4e..5ff00a40a62 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -434,6 +434,21 @@ impl SimulationState { }) } + /// Whether a pending transition activates its clock/reset domain. + pub fn has_unsettled_active_edges(&self, backend: &B) -> bool { + self.topo_signals.iter().any(|(signal, id, _)| { + *id != usize::MAX + && self.edge_triggers( + *id, + ( + self.last_clock_values.contains(*id), + self.unknown_clock_values.contains(*id), + ), + sample_event_signal(backend, *signal), + ) + }) + } + /// Whether any process is suspended on an event or a condition. pub fn has_waiting_processes(&self) -> bool { !self.waiting.is_empty() diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 91e5115b8dd..77434cae7e5 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -2467,3 +2467,46 @@ pub fn ff_always_offsets(syntax_tree: &SyntaxTree) -> Vec { }) .collect() } + +/// Actual call identifiers, excluding named argument labels and declarations. +/// Bare identifiers in expressions are not call sites; bare statement calls are. +pub fn procedural_call_sites(tree: &SyntaxTree) -> Vec<(usize, String)> { + let mut sites = Vec::new(); + for node in tree { + let identifier = match node { + RefNode::TfCall(call) if call.nodes.2.is_some() => { + Some(RefNode::PsOrHierarchicalTfIdentifier(&call.nodes.0)) + } + RefNode::SubroutineCallStatement( + sv_parser::SubroutineCallStatement::SubroutineCall(statement), + ) => match &statement.0 { + sv_parser::SubroutineCall::TfCall(call) => { + Some(RefNode::PsOrHierarchicalTfIdentifier(&call.nodes.0)) + } + _ => None, + }, + RefNode::MethodCallBodyUser(call) => Some(RefNode::MethodIdentifier(&call.nodes.0)), + _ => None, + }; + if let Some(identifier) = identifier { + let name = identifier + .into_iter() + .filter_map(|node| match node { + RefNode::SimpleIdentifier(id) => tree + .get_str(&id.nodes.0) + .map(|text| (id.nodes.0.offset, text.trim().to_owned())), + RefNode::EscapedIdentifier(id) => tree + .get_str(&id.nodes.0) + .map(|text| (id.nodes.0.offset, text.trim().to_owned())), + _ => None, + }) + .last(); + if let Some(name) = name { + sites.push(name); + } + } + } + sites.sort_unstable(); + sites.dedup(); + sites +} diff --git a/crates/celox-test-suite/Cargo.toml b/crates/celox-test-suite/Cargo.toml index fefcf2c2ada..82d8c390624 100644 --- a/crates/celox-test-suite/Cargo.toml +++ b/crates/celox-test-suite/Cargo.toml @@ -45,6 +45,7 @@ name = "inspect-mismatch-ir" required-features = ["emit"] [dependencies] +sv-parser.workspace = true veryl-analyzer = { workspace = true, optional = true } veryl-emitter = { workspace = true, optional = true } veryl-parser = { workspace = true, optional = true } diff --git a/crates/celox-test-suite/src/frontend.rs b/crates/celox-test-suite/src/frontend.rs index 169a5abb7ea..f17deb87237 100644 --- a/crates/celox-test-suite/src/frontend.rs +++ b/crates/celox-test-suite/src/frontend.rs @@ -5,8 +5,8 @@ mod timed_ff; use crate::process::write_if_changed; use crate::script::ScriptCase; use crate::script::sv::{DesignInfo, TESTBENCH_TOP, testbench as generate_testbench}; +use crate::script::timed::validate_timed_design_with_defines; use crate::script::timed::{after_trivia, sv_words}; -use crate::validate_timed_design; use crate::verification::{EmissionError, panic_message}; use crate::{Design, Expectation, Result}; use std::collections::BTreeMap; @@ -62,7 +62,7 @@ pub(crate) fn stage( script: Option<&ScriptCase>, defines: &[&str], ) -> Result { - validate_timed_design(design)?; + validate_timed_design_with_defines(design, defines)?; fs::create_dir_all(directory)?; let directory = fs::canonicalize(directory)?; for (index, source) in design.sources.iter().enumerate() { diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index 1ce3984c380..6d109b4d8d8 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -447,6 +447,7 @@ pub(super) struct TaskTiming { tasks: BTreeMap<(String, Vec, String), bool>, generate_scopes: BTreeMap>, ff_offsets: BTreeMap>, + calls: BTreeMap>, imports: BTreeMap)>>, exports: BTreeMap, Option)>>, } @@ -559,6 +560,10 @@ impl TaskTiming { for source in sources { if let Ok(tree) = celox_sv_analyzer::syntax::parse_source(source, Path::new("timed.sv")) { + result.calls.insert( + source.clone(), + celox_sv_analyzer::ast::procedural_call_sites(&tree), + ); result.ff_offsets.insert( source.clone(), celox_sv_analyzer::ast::ff_always_offsets(&tree), @@ -776,6 +781,14 @@ impl TaskTiming { } fn has_timed_call(&self, source: &str, start: usize, end: usize) -> bool { + if let Some(calls) = self.calls.get(source) { + return calls.iter().any(|(at, name)| { + *at >= start + && *at < end + && self.tasks.keys().any(|key| key.2 == *name) + && self.resolve(source, *at, name).unwrap_or(true) + }); + } sv_words(&source[start..end]) .iter() .any(|(at, word_end, name)| { @@ -800,7 +813,10 @@ impl TaskTiming { || prefix.is_empty() || prefix.ends_with([';', ')', ':', '.']) || words.last().is_some_and(|word| { - matches!(word.2, "begin" | "end" | "else" | "forever" | "do") + matches!( + word.2, + "begin" | "end" | "else" | "forever" | "do" | "endcase" + ) }); (tail.starts_with('(') || (tail.starts_with(';') && statement_start)) && self.resolve(source, start + at, name).unwrap_or(true) diff --git a/crates/celox-test-suite/src/script/timed.rs b/crates/celox-test-suite/src/script/timed.rs index ddab0c4f9a7..27570719ff8 100644 --- a/crates/celox-test-suite/src/script/timed.rs +++ b/crates/celox-test-suite/src/script/timed.rs @@ -3,19 +3,43 @@ use crate::{Design, Result}; /// Raw scheduler units are portable only with the suite's injected scale. /// Comments, strings and escaped identifiers are not declarations. pub fn validate_timed_design(design: &Design) -> Result<()> { - if design.timed - && design.sources.iter().any(|source| { - sv_words(&source.text).iter().any(|(start, _, word)| { - matches!(*word, "timeunit" | "timeprecision") - || (matches!(*word, "timescale" | "resetall") - && source.text[..*start].ends_with('`')) - }) - }) - { - return Err( - "explicit time scales and resetall are not supported in timed shared cases".into(), + validate_timed_design_with_defines(design, &[]) +} + +pub(crate) fn validate_timed_design_with_defines(design: &Design, names: &[&str]) -> Result<()> { + if !design.timed { + return Ok(()); + } + let mut defines: sv_parser::Defines = Default::default(); + for name in names { + defines.insert( + (*name).to_owned(), + Some(sv_parser::Define::new((*name).to_owned(), Vec::new(), None)), ); } + let includes: Vec<&std::path::Path> = Vec::new(); + for source in &design.sources { + let (active, _) = sv_parser::preprocess_str( + &source.text, + &source.path, + &defines, + &includes, + true, + false, + 0, + 0, + ) + .map_err(|error| format!("timed source preprocessing: {error}"))?; + let text = active.text(); + if sv_words(text).iter().any(|(start, _, word)| { + matches!(*word, "timeunit" | "timeprecision") + || (matches!(*word, "timescale" | "resetall") && text[..*start].ends_with('`')) + }) { + return Err( + "explicit time scales and resetall are not supported in timed shared cases".into(), + ); + } + } Ok(()) } @@ -113,4 +137,19 @@ mod tests { let source = "// `timescale 10ns/1ps\nmodule Top; bit timescale; initial $display(\"timeunit 10ns\"); endmodule"; assert!(validate_timed_design(&design(source)).is_ok()); } + #[test] + fn scales_follow_active_preprocessor_defines() { + for directive in [ + "`timescale 10ns/1ps", + "`resetall", + "timeunit 10ns;", + "timeprecision 1fs;", + ] { + let source = format!("`ifdef TOOL_ACTIVE\n{directive}\n`endif\nmodule Top;endmodule"); + assert!(validate_timed_design(&design(&source)).is_ok()); + assert!( + validate_timed_design_with_defines(&design(&source), &["TOOL_ACTIVE"]).is_err() + ); + } + } } diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index a569cea3a7e..282a34bbcf4 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -849,3 +849,17 @@ endmodule"#) always @(posedge clk)begin : work tick;end initial begin #3;$finish;end endmodule"#) (top Top)(set clk 1)(run_to_finish)(assert_eq q 0)) + +(case timed_calls_after_endcase_do_not_replay_setup_edges + (source "endcase-task.sv" #"module Top(input bit clk,sel,output bit q); + task automatic tick();#1 q=1;endtask + always @(posedge clk)begin case(sel)0:;default:;endcase tick;end + initial begin #3;$finish;end endmodule"#) + (top Top)(set clk 1)(run_to_finish)(assert_eq q 0)) + +(case inactive_time_directives_do_not_change_scheduler_units + (source "inactive-scale.sv" #"`ifdef NEVER_DEFINED + `timescale 10ns/1ps + `endif + module Top(output bit q);initial begin #1;q=1;end endmodule"#) + (top Top)(run_until 1)(assert_eq q 1)) diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 3d103f6d162..4efbb676e92 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -492,12 +492,18 @@ impl Simulation { } if self.state.has_unsettled_edges(&self.simulator.backend) { let time = self.state.time(); - if self.state.next_event_time() == Some(time) { + let active = self + .state + .has_unsettled_active_edges(&self.simulator.backend); + let queued = self.state.next_event_time() == Some(time); + if queued { self.state.step(&mut self.simulator)?; } else { self.state.settle_at(&mut self.simulator, time)?; } - return Ok(Some(time)); + if active || queued { + return Ok(Some(time)); + } } self.state.step(&mut self.simulator) } @@ -570,12 +576,18 @@ impl Simulation { } if self.state.has_unsettled_edges(&self.simulator.backend) { let time = self.state.time(); - if self.state.next_event_time() == Some(time) { + let active = self + .state + .has_unsettled_active_edges(&self.simulator.backend); + let queued = self.state.next_event_time() == Some(time); + if queued { self.state.step(&mut self.simulator)?; } else { self.state.settle_at(&mut self.simulator, time)?; } - return Ok(Some(time)); + if active || queued { + return Ok(Some(time)); + } } if self .state @@ -2265,3 +2277,60 @@ mod finish_during_round_review_tests { nba_finish(Simulation::new(build().build_native().unwrap())); } } + +#[cfg(all(test, feature = "systemverilog"))] +mod inactive_host_transition_review_tests { + use super::*; + fn check(mut sim: Simulation, method: &str, future: bool) { + let clk = sim.signal("clk"); + sim.set_wide(clk, 1u8.into()); + sim.run_until(0).unwrap(); + sim.set_wide(clk, 0u8.into()); + if future { + sim.schedule("clk", 5, 1).unwrap(); + } + if method == "step" { + assert_eq!(sim.step().unwrap(), future.then_some(5)); + } else { + assert_eq!(sim.step_until(4).unwrap(), None); + if future { + assert_eq!(sim.step_until(5).unwrap(), Some(5)); + } + } + } + #[test] + fn inactive_host_edges_do_not_fabricate_steps() { + let source = "module Top(input bit clk,output bit q);always @(posedge clk)q<=1;endmodule"; + for method in ["step", "step_until"] { + for future in [false, true] { + let build = || { + Simulator::from_sv_sources( + vec![(source, std::path::Path::new("inactive-host.sv"))], + "Top", + ) + }; + check( + Simulation::new(build().build_interpreter().unwrap()), + method, + future, + ); + check( + Simulation::new(build().build_cranelift().unwrap()), + method, + future, + ); + check( + Simulation::new(build().build_wasm().unwrap()), + method, + future, + ); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check( + Simulation::new(build().build_native().unwrap()), + method, + future, + ); + } + } + } +} diff --git a/crates/celox/tests/systemverilog.rs b/crates/celox/tests/systemverilog.rs index 37da5ed10f0..95fde02a7c1 100644 --- a/crates/celox/tests/systemverilog.rs +++ b/crates/celox/tests/systemverilog.rs @@ -264,3 +264,7 @@ sv_backends! { sv_backends! { fn timed_calls_after_named_blocks_do_not_replay_setup_edges(sim) { @case "timing::timed_calls_after_named_blocks_do_not_replay_setup_edges"; } } +sv_backends! { + fn timed_calls_after_endcase_do_not_replay_setup_edges(sim) { @case "timing::timed_calls_after_endcase_do_not_replay_setup_edges"; } + fn inactive_time_directives_do_not_change_scheduler_units(sim) { @case "timing::inactive_time_directives_do_not_change_scheduler_units"; } +} From 843e54d6ad04293dcc6c69ec3f2358a708ffd9e0 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 12:16:47 +0900 Subject: [PATCH 37/75] test(vcd): sample inactive host transitions at their timestamp --- crates/celox/tests/vcd.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/celox/tests/vcd.rs b/crates/celox/tests/vcd.rs index ef85a06d05a..eff566c2131 100644 --- a/crates/celox/tests/vcd.rs +++ b/crates/celox/tests/vcd.rs @@ -558,6 +558,14 @@ mod activity { if step == 2 { let rst = sim.signal("rst"); sim.modify(|io| io.set(rst, 1u8)).unwrap(); + // An inactive host transition settles at the current time + // without fabricating a scheduler event. Sample that boundary + // in both writers before step advances to the next event. + sim.dump(sim.time()); + let (ptr, size) = sim.memory_as_ptr(); + reference + .dump(sim.time(), unsafe { std::slice::from_raw_parts(ptr, size) }) + .unwrap(); } let time = sim.step().unwrap().unwrap(); sim.dump(time); From 5db4882a671c7e631df2e4c1bfa604cd89d0f3b9 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 12:33:35 +0900 Subject: [PATCH 38/75] fix(suite): preserve commented callable headers and finish stepping --- .../celox-test-suite/src/frontend/timed_ff.rs | 26 +++++++---- .../src/sv/cases/timing.vtest | 7 +++ crates/celox/src/simulation.rs | 45 +++++++++++++++++++ .../tests/frontends/systemverilog/timing.rs | 4 ++ 4 files changed, 73 insertions(+), 9 deletions(-) diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index 6d109b4d8d8..534c9e4f6a7 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -35,6 +35,18 @@ fn skip_token(source: &str, at: &mut usize) -> bool { } true } +fn semicolon(source: &str, mut at: usize) -> Option { + while at < source.len() { + if skip_token(source, &mut at) { + continue; + } + if source.as_bytes()[at] == b';' { + return Some(at); + } + at += 1; + } + None +} fn parens(source: &str, begin: usize) -> Option { if source.as_bytes().get(begin) != Some(&b'(') { return None; @@ -601,7 +613,7 @@ impl TaskTiming { continue; } let tail = &source[*end..]; - let Some(end) = tail.find(';') else { + let Some(end) = semicolon(tail, 0) else { continue; }; for item in tail[..end].split(',') { @@ -627,10 +639,7 @@ impl TaskTiming { } for (index, (start, end, word)) in words.iter().enumerate() { if *word == "function" { - let header_end = source[*end..] - .find(';') - .map(|offset| end + offset) - .unwrap_or(source.len()); + let header_end = semicolon(source, *end).unwrap_or(source.len()); let header = &source[*end..header_end]; let mut name_end = header.len(); let mut at = 0; @@ -677,9 +686,8 @@ impl TaskTiming { continue; }; let key = result.callable_key(source, *start, name); - let header_end = source[*end..*body_end] - .find(';') - .map_or(*end, |offset| end + offset + 1); + let header_end = + semicolon(&source[..*body_end], *end).map_or(*end, |offset| offset + 1); result .tasks .insert(key.clone(), has_timing(&source[header_end..*body_end])); @@ -749,7 +757,7 @@ impl TaskTiming { } let (explicit, wildcard) = imports.entry(lexical.len()).or_default(); let tail = &source[end..]; - let clause = &tail[..tail.find(';')?]; + let clause = &tail[..semicolon(tail, 0)?]; for item in clause.split(',') { let words = sv_words(item); let Some((_, _, package)) = words.first() else { diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 282a34bbcf4..94d8ee666e4 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -863,3 +863,10 @@ endmodule"#) `endif module Top(output bit q);initial begin #1;q=1;end endmodule"#) (top Top)(run_until 1)(assert_eq q 1)) + +(case comment_semicolons_in_function_headers_preserve_setup_edges + (source "function-comment.sv" #"module Other;task automatic tick();#1;endtask endmodule + module Top(input bit clk,output bit q); + function int /* ; */ tick();return 1;endfunction + always @(posedge clk)q<=tick();endmodule"#) + (top Top)(set clk 1)(run_until 0)(assert_eq q 1)) diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 927c9fdbe7b..fc2fb7cefb3 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -487,6 +487,9 @@ impl Simulation { return Ok(None); } self.settle_host_writes()?; + if self.state.is_finished() { + return Ok(None); + } if self.state.poll_waiting(&mut self.simulator)? { return Ok(Some(self.state.time())); } @@ -571,6 +574,9 @@ impl Simulation { return Ok(None); } self.settle_host_writes()?; + if self.state.is_finished() { + return Ok(None); + } if self.state.poll_waiting(&mut self.simulator)? { return Ok(Some(self.state.time())); } @@ -2370,3 +2376,42 @@ mod queued_derived_ff_review_tests { check(Simulation::new(build().build_native().unwrap())); } } + +#[cfg(all(test, feature = "systemverilog"))] +mod host_finish_edge_review_tests { + use super::*; + #[test] + fn host_finish_and_edge_do_not_report_a_step() { + let source = "module Top(input bit a,output bit q);always_comb if(a)$finish;always @(posedge a)q<=1;endmodule"; + fn check(mut sim: Simulation, bounded: bool) { + sim.run_until(0).unwrap(); + assert!(!sim.is_finished()); + sim.set_wide(sim.signal("a"), 1u8.into()); + let result = if bounded { + sim.step_until(0) + } else { + sim.step() + }; + assert_eq!(result.unwrap(), None); + assert!(sim.is_finished()); + assert_eq!(sim.get(sim.signal("q")), 0u8.into()); + assert_eq!(sim.time(), 0); + } + for bounded in [false, true] { + let build = || { + Simulator::from_sv_sources( + vec![(source, std::path::Path::new("host-finish-edge.sv"))], + "Top", + ) + }; + check( + Simulation::new(build().build_interpreter().unwrap()), + bounded, + ); + check(Simulation::new(build().build_cranelift().unwrap()), bounded); + check(Simulation::new(build().build_wasm().unwrap()), bounded); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap()), bounded); + } + } +} diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 861f7e3f61c..90cecc031a5 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -152,3 +152,7 @@ sv_backends! { fn single_item_case_generate_ff_is_staged_together(sim){@case "timing::single_item_case_generate_ff_is_staged_together";} fn timed_expansion_preserves_adapter_macros(sim){@case "timing::timed_expansion_preserves_adapter_macros";} } + +sv_backends! { + fn comment_semicolons_in_function_headers_preserve_setup_edges(sim){@case "timing::comment_semicolons_in_function_headers_preserve_setup_edges";} +} From 721d8a05f18aae00227c0432ecb05091a7e6aa23 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 13:06:46 +0900 Subject: [PATCH 39/75] fix(suite): resolve imports from AST within source units --- crates/celox-sv-analyzer/src/ast.rs | 45 ++++ .../celox-test-suite/src/frontend/timed_ff.rs | 217 ++++++++++++++---- .../src/sv/cases/timing.vtest | 14 ++ .../tests/frontends/systemverilog/timing.rs | 8 + 4 files changed, 244 insertions(+), 40 deletions(-) diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 77434cae7e5..cb87eda00ea 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -2510,3 +2510,48 @@ pub fn procedural_call_sites(tree: &SyntaxTree) -> Vec<(usize, String)> { sites.dedup(); sites } + +/// Parsed import/export clauses, keyed by the declaration keyword offset. +/// A missing package/member denotes a wildcard; comments never become items. +pub fn package_import_export_clauses( + tree: &SyntaxTree, +) -> std::collections::BTreeMap, Option)>> { + let mut clauses = std::collections::BTreeMap::new(); + for node in tree { + let (offset, declaration) = match node { + RefNode::PackageImportDeclaration(item) => ( + item.nodes.0.nodes.0.offset, + RefNode::PackageImportDeclaration(item), + ), + RefNode::PackageExportDeclaration(sv_parser::PackageExportDeclaration::Item(item)) => ( + item.nodes.0.nodes.0.offset, + RefNode::PackageExportDeclarationItem(item), + ), + RefNode::PackageExportDeclaration(sv_parser::PackageExportDeclaration::Asterisk( + item, + )) => { + clauses.insert(item.nodes.0.nodes.0.offset, vec![(None, None)]); + continue; + } + _ => continue, + }; + let items = declaration + .into_iter() + .filter_map(|node| match node { + RefNode::PackageImportItem(sv_parser::PackageImportItem::Identifier(item)) => { + Some(( + identifier_text(RefNode::PackageIdentifier(&item.nodes.0), tree), + identifier_text(RefNode::Identifier(&item.nodes.2), tree), + )) + } + RefNode::PackageImportItem(sv_parser::PackageImportItem::Asterisk(item)) => Some(( + identifier_text(RefNode::PackageIdentifier(&item.nodes.0), tree), + None, + )), + _ => None, + }) + .collect(); + clauses.insert(offset, items); + } + clauses +} diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index 534c9e4f6a7..75715d6dbef 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -454,9 +454,13 @@ fn has_timing(source: &str) -> bool { false } +type CallableKey = (String, Option, Vec, String); + #[derive(Default)] pub(super) struct TaskTiming { - tasks: BTreeMap<(String, Vec, String), bool>, + tasks: BTreeMap, + units: BTreeMap, + import_clauses: BTreeMap, Option)>>>, generate_scopes: BTreeMap>, ff_offsets: BTreeMap>, calls: BTreeMap>, @@ -474,7 +478,7 @@ fn container_at(source: &str, at: usize) -> String { .iter() .find(|word| !matches!(word.2, "static" | "automatic")) { - scope = name.to_string(); + scope = name.trim_start_matches('\\').to_owned(); } } "endmodule" | "endinterface" | "endpackage" => scope.clear(), @@ -519,25 +523,80 @@ impl TaskTiming { ) } - fn callable_key(&self, source: &str, at: usize, name: &str) -> (String, Vec, String) { + fn unit(&self, source: &str) -> Option { + self.units.get(source).copied() + } + fn clause_items( + &self, + source: &str, + start: usize, + end: usize, + ) -> Vec<(Option, Option)> { + if let Some(clauses) = self.import_clauses.get(source) { + return clauses.get(&start).cloned().unwrap_or_default(); + } + // Only malformed sources use the lexical fallback. Split separators + // outside comments, strings and escaped identifiers. + let tail = &source[end..]; + let clause = &tail[..semicolon(tail, 0).unwrap_or(tail.len())]; + let mut parts = Vec::new(); + let mut begin = 0; + let mut at = 0; + while at < clause.len() { + if skip_token(clause, &mut at) { + continue; + } + if clause.as_bytes()[at] == b',' { + parts.push(&clause[begin..at]); + begin = at + 1; + } + at += 1; + } + parts.push(&clause[begin..]); + parts + .into_iter() + .map(|item| { + let words = sv_words(item); + ( + words.first().map(|x| x.2.to_owned()), + words.get(1).map(|x| x.2.to_owned()), + ) + }) + .collect() + } + + fn callable_key(&self, source: &str, at: usize, name: &str) -> CallableKey { let container = container_at(source, at); let mut scope = self.lexical_scope(source, at); if !container.is_empty() && !scope.is_empty() { scope.remove(0); } - (container, scope, name.to_owned()) + let unit = container.is_empty().then(|| self.unit(source)).flatten(); + ( + container, + unit, + scope, + name.trim_start_matches('\\').to_owned(), + ) } fn package_callable( &self, + source: &str, package: &str, name: &str, visiting: &mut std::collections::BTreeSet, ) -> Option { - let package = if package == "$unit" { "" } else { package }; - if let Some(value) = self - .tasks - .get(&(package.to_owned(), Vec::new(), name.to_owned())) + let package = package.trim_start_matches('\\'); + let name = name.trim_start_matches('\\'); + let (package, unit) = if package == "$unit" { + ("", self.unit(source)) + } else { + (package, None) + }; + if let Some(value) = + self.tasks + .get(&(package.to_owned(), unit, Vec::new(), name.to_owned())) { return Some(*value); } @@ -558,7 +617,7 @@ impl TaskTiming { }) { continue; } - if let Some(timed) = self.package_callable(origin, name, visiting) { + if let Some(timed) = self.package_callable(source, origin, name, visiting) { result = Some(result.unwrap_or(false) || timed); } } @@ -569,20 +628,46 @@ impl TaskTiming { pub(super) fn new(sources: &[String]) -> Self { let mut result = Self::default(); let mut records = Vec::new(); - for source in sources { + for (index, source) in sources.iter().enumerate() { + result.units.insert(source.clone(), index); if let Ok(tree) = celox_sv_analyzer::syntax::parse_source(source, Path::new("timed.sv")) { + // Re-preprocessing can add whitespace after escaped names. + // All lexical joins use offsets of the source passed here. + let origin = |offset| { + tree.get_origin(&sv_parser::Locate { + offset, + ..Default::default() + }) + .map_or(offset, |(_, origin)| origin) + }; + result.import_clauses.insert( + source.clone(), + celox_sv_analyzer::ast::package_import_export_clauses(&tree) + .into_iter() + .map(|(offset, items)| (origin(offset), items)) + .collect(), + ); result.calls.insert( source.clone(), - celox_sv_analyzer::ast::procedural_call_sites(&tree), + celox_sv_analyzer::ast::procedural_call_sites(&tree) + .into_iter() + .map(|(offset, name)| (origin(offset), name)) + .collect(), ); result.ff_offsets.insert( source.clone(), - celox_sv_analyzer::ast::ff_always_offsets(&tree), + celox_sv_analyzer::ast::ff_always_offsets(&tree) + .into_iter() + .map(origin) + .collect(), ); result.generate_scopes.insert( source.clone(), - celox_sv_analyzer::ast::generate_scope_ranges(&tree), + celox_sv_analyzer::ast::generate_scope_ranges(&tree) + .into_iter() + .map(|(start, end)| (origin(start), origin(end.saturating_sub(1)) + 1)) + .collect(), ); } let words = sv_words(source); @@ -612,14 +697,7 @@ impl TaskTiming { { continue; } - let tail = &source[*end..]; - let Some(end) = semicolon(tail, 0) else { - continue; - }; - for item in tail[..end].split(',') { - let item_words = sv_words(item); - let package = item_words.first().map(|x| x.2.to_owned()); - let selected = item_words.get(1).map(|x| x.2.to_owned()); + for (package, selected) in result.clause_items(source, *start, *end) { if *word == "import" { if let Some(package) = package { result @@ -709,10 +787,11 @@ impl TaskTiming { } fn resolve(&self, source: &str, at: usize, name: &str) -> Option { + let name = name.trim_start_matches('\\'); let prefix = source[..at].trim_end(); if let Some(prefix) = prefix.strip_suffix("::") { let package = sv_words(prefix).last()?.2; - return self.package_callable(package, name, &mut Default::default()); + return self.package_callable(source, package, name, &mut Default::default()); } if let Some(prefix) = prefix.strip_suffix('.') { let instance = sv_words(prefix).last()?.2; @@ -720,10 +799,12 @@ impl TaskTiming { let words = sv_words(&source[..at]); for pair in words.windows(2) { if pair[1].2 == instance && container_at(source, pair[0].0) == scope { - if let Some(value) = - self.tasks - .get(&(pair[0].2.to_owned(), Vec::new(), name.to_owned())) - { + if let Some(value) = self.tasks.get(&( + pair[0].2.trim_start_matches('\\').to_owned(), + None, + Vec::new(), + name.to_owned(), + )) { return Some(*value); } } @@ -737,7 +818,7 @@ impl TaskTiming { if let Some(value) = self.tasks.get(&key) { return Some(*value); } - if key.1.pop().is_none() { + if key.2.pop().is_none() { break; } } @@ -756,19 +837,15 @@ impl TaskTiming { continue; } let (explicit, wildcard) = imports.entry(lexical.len()).or_default(); - let tail = &source[end..]; - let clause = &tail[..semicolon(tail, 0)?]; - for item in clause.split(',') { - let words = sv_words(item); - let Some((_, _, package)) = words.first() else { + for (package, selected) in self.clause_items(source, start, end) { + let Some(package) = package else { continue; }; - let selected = words.get(1).map(|word| word.2); - if selected == Some(name) || (selected.is_none() && item.contains('*')) { + if selected.as_deref() == Some(name) || selected.is_none() { if let Some(value) = - self.package_callable(package, name, &mut Default::default()) + self.package_callable(source, &package, name, &mut Default::default()) { - if selected == Some(name) { + if selected.as_deref() == Some(name) { *explicit = Some(value); } else { *wildcard = Some(wildcard.unwrap_or(false) || value); @@ -783,7 +860,12 @@ impl TaskTiming { .find_map(|(explicit, wildcard)| explicit.or(wildcard)) .or_else(|| { self.tasks - .get(&(String::new(), Vec::new(), name.to_owned())) + .get(&( + String::new(), + self.unit(source), + Vec::new(), + name.to_owned(), + )) .copied() }) } @@ -793,14 +875,21 @@ impl TaskTiming { return calls.iter().any(|(at, name)| { *at >= start && *at < end - && self.tasks.keys().any(|key| key.2 == *name) + && self + .tasks + .keys() + .any(|key| key.3 == name.trim_start_matches('\\')) && self.resolve(source, *at, name).unwrap_or(true) }); } sv_words(&source[start..end]) .iter() .any(|(at, word_end, name)| { - if !self.tasks.keys().any(|key| key.2 == *name) { + if !self + .tasks + .keys() + .any(|key| key.3 == name.trim_start_matches('\\')) + { return false; } let tail = after_trivia(&source[start + word_end..end]); @@ -836,6 +925,54 @@ impl TaskTiming { mod callable_analysis_tests { use super::*; #[test] + fn parsed_imports_keep_escaped_names_and_comment_commas_whole() { + for imports in [ + "import B::*, A /*,*/ :: tick;", + r"import B::*, \A,items ::tick;", + ] { + let package = if imports.contains("items") { + r"\A,items " + } else { + "A" + }; + let source = format!( + "package {package};function bit tick();return 1;endfunction endpackage package B;task tick;#1;endtask endpackage module Top;{imports}always @(posedge clk)q<=tick();endmodule" + ); + let tasks = TaskTiming::new(std::slice::from_ref(&source)); + assert_eq!( + tasks.resolve(&source, source.rfind("tick()").unwrap(), "tick"), + Some(false) + ); + assert!(edge_control( + &source, + source.find("always").unwrap() + 6, + &tasks + )); + } + } + #[test] + fn compilation_units_keep_callable_timing_separate() { + for qualified in [false, true] { + let first = + "task tick;#1;endtask module Top;always @(posedge clk)tick();endmodule".to_owned(); + let second = + "task tick;endtask module Other;always @(posedge clk)tick();endmodule".to_owned(); + let first = if qualified { + first.replace("tick();endmodule", "$unit::tick();endmodule") + } else { + first + }; + let second = if qualified { + second.replace("tick();endmodule", "$unit::tick();endmodule") + } else { + second + }; + let timing = TaskTiming::new(&[first.clone(), second.clone()]); + assert!(timing.has_timed_call(&first, first.find("always").unwrap(), first.len())); + assert!(!timing.has_timed_call(&second, second.find("always").unwrap(), second.len())); + } + } + #[test] fn local_declarations_are_not_no_argument_task_calls() { for body in ["int tick; q<=1;", "int value, tick; q<=1;"] { let source = format!( @@ -866,7 +1003,7 @@ mod callable_analysis_tests { ); let tasks = TaskTiming::new(std::slice::from_ref(&source)); assert_eq!( - tasks.package_callable("C", "tick", &mut Default::default()), + tasks.package_callable(&source, "C", "tick", &mut Default::default()), Some(!delay.is_empty()) ); let at = source.rfind("tick()").unwrap(); diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 94d8ee666e4..280b2ffa2c0 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -870,3 +870,17 @@ endmodule"#) function int /* ; */ tick();return 1;endfunction always @(posedge clk)q<=tick();endmodule"#) (top Top)(set clk 1)(run_until 0)(assert_eq q 1)) + +(case import_comment_commas_do_not_change_visible_callables + (source "import-comment.sv" #"package A;task automatic tick();#1;endtask task automatic other();endtask endpackage + package B;function automatic bit tick();return 1;endfunction endpackage + module Top(input bit clk,output bit q);import B::*, A /*,*/ :: other; + always @(posedge clk)q<=tick();endmodule"#) + (top Top)(set clk 1)(run_until 0)(assert_eq q 1)) + +(case escaped_import_commas_keep_explicit_callable_selection + (source "escaped-import.sv" #"package \A,items ;function automatic bit tick();return 1;endfunction endpackage + package B;task automatic tick();#1;endtask endpackage + module Top(input bit clk,output bit q);import \A,items ::tick; + always @(posedge clk)q<=tick();endmodule"#) + (top Top)(set clk 1)(run_until 0)(assert_eq q 1)) diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 90cecc031a5..838a57ca165 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -156,3 +156,11 @@ sv_backends! { sv_backends! { fn comment_semicolons_in_function_headers_preserve_setup_edges(sim){@case "timing::comment_semicolons_in_function_headers_preserve_setup_edges";} } + +sv_backends! { + fn import_comment_commas_do_not_change_visible_callables(sim){@case "timing::import_comment_commas_do_not_change_visible_callables";} +} + +sv_backends! { + fn escaped_import_commas_keep_explicit_callable_selection(sim){@case "timing::escaped_import_commas_keep_explicit_callable_selection";} +} From f6dd4f6df9d01ac7dd52412c176dc02884012b22 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 14:21:53 +0900 Subject: [PATCH 40/75] fix(runtime): coerce saved edge baselines and resolve interface methods --- crates/celox-sv-analyzer/src/ast.rs | 32 ++++++++ .../celox-test-suite/src/frontend/timed_ff.rs | 38 ++++++++++ .../src/sv/cases/timing.vtest | 14 ++++ crates/celox/src/simulation.rs | 75 +++++++++++++++++++ crates/celox/src/simulator/state_file.rs | 21 +++++- .../tests/frontends/systemverilog/timing.rs | 4 + 6 files changed, 183 insertions(+), 1 deletion(-) diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index cb87eda00ea..2b367c7f544 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -2555,3 +2555,35 @@ pub fn package_import_export_clauses( } clauses } + +/// Instance bindings retain their declared type across parameter assignments. +pub fn instance_type_sites(tree: &SyntaxTree) -> Vec<(usize, String, String)> { + let mut sites = Vec::new(); + for node in tree { + let RefNode::ModuleInstantiation(instance) = node else { + continue; + }; + let Some(module) = identifier_text(RefNode::ModuleIdentifier(&instance.nodes.0), tree) + else { + continue; + }; + for child in RefNode::ModuleInstantiation(instance) { + if let RefNode::NameOfInstance(name) = child { + let node = RefNode::InstanceIdentifier(&name.nodes.0); + let Some(identifier) = identifier_text(node.clone(), tree) else { + continue; + }; + if let Some(offset) = node.into_iter().find_map(|node| { + if let RefNode::Locate(loc) = node { + Some(loc.offset) + } else { + None + } + }) { + sites.push((offset, identifier, module.clone())); + } + } + } + } + sites +} diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index 75715d6dbef..562c0ed442a 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -464,6 +464,7 @@ pub(super) struct TaskTiming { generate_scopes: BTreeMap>, ff_offsets: BTreeMap>, calls: BTreeMap>, + instance_types: BTreeMap>, imports: BTreeMap)>>, exports: BTreeMap, Option)>>, } @@ -641,6 +642,13 @@ impl TaskTiming { }) .map_or(offset, |(_, origin)| origin) }; + result.instance_types.insert( + source.clone(), + celox_sv_analyzer::ast::instance_type_sites(&tree) + .into_iter() + .map(|(offset, name, typ)| (origin(offset), name, typ)) + .collect(), + ); result.import_clauses.insert( source.clone(), celox_sv_analyzer::ast::package_import_export_clauses(&tree) @@ -796,6 +804,27 @@ impl TaskTiming { if let Some(prefix) = prefix.strip_suffix('.') { let instance = sv_words(prefix).last()?.2; let scope = container_at(source, at); + if let Some(instances) = self.instance_types.get(source) { + let call_scope = self.lexical_scope(source, at); + let found = instances + .iter() + .filter(|(offset, n, _)| { + n.trim_start_matches('\\') == instance.trim_start_matches('\\') + && container_at(source, *offset) == scope + && call_scope.starts_with(&self.lexical_scope(source, *offset)) + }) + .max_by_key(|(offset, _, _)| self.lexical_scope(source, *offset).len()); + return found.and_then(|(_, _, typ)| { + self.tasks + .get(&( + typ.trim_start_matches('\\').to_owned(), + None, + Vec::new(), + name.to_owned(), + )) + .copied() + }); + } let words = sv_words(&source[..at]); for pair in words.windows(2) { if pair[1].2 == instance && container_at(source, pair[0].0) == scope { @@ -925,6 +954,15 @@ impl TaskTiming { mod callable_analysis_tests { use super::*; #[test] + fn parameterized_instances_resolve_their_declared_method_type() { + let source="interface Scale #(parameter int K=1);function automatic bit scaled(input bit v);return v;endfunction endinterface module Top;Scale #(.K(5)) s();always @(posedge clk)q<=s.scaled(v);endmodule".to_owned(); + let tasks = TaskTiming::new(std::slice::from_ref(&source)); + assert_eq!( + tasks.resolve(&source, source.rfind("scaled(v)").unwrap(), "scaled"), + Some(false) + ); + } + #[test] fn parsed_imports_keep_escaped_names_and_comment_commas_whole() { for imports in [ "import B::*, A /*,*/ :: tick;", diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 280b2ffa2c0..b013399736e 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -884,3 +884,17 @@ endmodule"#) module Top(input bit clk,output bit q);import \A,items ::tick; always @(posedge clk)q<=tick();endmodule"#) (top Top)(set clk 1)(run_until 0)(assert_eq q 1)) + +(case parameterized_interface_methods_keep_setup_edges + (source "interface-method.sv" #" + interface Scale #(parameter int K=1); + function automatic logic [3:0] scaled(input logic [3:0] v); + return v*K; + endfunction + endinterface + module Top(input bit clk,input logic [3:0] v,output logic [3:0] q); + Scale #(.K(5)) s(); + always @(posedge clk) q <= s.scaled(v); + endmodule + "#) + (top Top)(set v 2)(set clk 1)(run_until 0)(assert_eq q 10)) diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index fc2fb7cefb3..5345bf1f944 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -2415,3 +2415,78 @@ mod host_finish_edge_review_tests { } } } + +#[cfg(all(test, feature = "systemverilog"))] +mod cross_mode_clock_baseline_review_tests { + use super::*; + #[test] + fn unknown_clock_baselines_coerce_with_loaded_state() { + let source = + "module Top(input logic clk,output bit[7:0]q);always @(negedge clk)q<=q+1;endmodule"; + fn check(mut source: Simulation, mut target: Simulation, payload: u8) { + let clk = source.signal("clk"); + source + .modify(|io| io.set_four_state(clk, payload.into(), 1u8.into())) + .unwrap(); + source.run_until(0).unwrap(); + assert_eq!(source.get(source.signal("q")), 0u8.into()); + let file = source.save_state().unwrap(); + target.load_state(&file).unwrap(); + target.settle().unwrap(); + assert_eq!(target.get(target.signal("q")), 0u8.into()); + let clk = target.signal("clk"); + target.set_wide(clk, 1u8.into()); + target.settle().unwrap(); + target.set_wide(clk, 0u8.into()); + target.settle().unwrap(); + assert_eq!(target.get(target.signal("q")), 1u8.into()); + } + let bit_source = source.replace("input logic clk", "input bit clk"); + for (payload, target_four_state, target_bit) in [ + (0, false, false), + (1, false, false), + (0, true, true), + (1, true, true), + (0, true, false), + (1, true, false), + ] { + let build = |four_state, bit| { + let code = if bit { bit_source.as_str() } else { source }; + Simulator::from_sv_sources( + vec![(code, std::path::Path::new("baseline-coercion.sv"))], + "Top", + ) + .four_state(four_state) + }; + check( + Simulation::new(build(true, false).build_interpreter().unwrap()), + Simulation::new( + build(target_four_state, target_bit) + .build_interpreter() + .unwrap(), + ), + payload, + ); + check( + Simulation::new(build(true, false).build_cranelift().unwrap()), + Simulation::new( + build(target_four_state, target_bit) + .build_cranelift() + .unwrap(), + ), + payload, + ); + check( + Simulation::new(build(true, false).build_wasm().unwrap()), + Simulation::new(build(target_four_state, target_bit).build_wasm().unwrap()), + payload, + ); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check( + Simulation::new(build(true, false).build_native().unwrap()), + Simulation::new(build(target_four_state, target_bit).build_native().unwrap()), + payload, + ); + } + } +} diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index 45a110191df..8e6a7f32e2a 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -429,6 +429,19 @@ impl Simulator { signal: signals[&event.signal], next_val: event.value, }; + // Loading unknown state into a two-state object coerces it to zero. + // Apply that coercion to its historical edge sample too, while V1 + // known-Boolean baselines retain their pending known transitions. + let saved_unknown: std::collections::BTreeSet<&str> = record + .unknown_events + .iter() + .flatten() + .map(String::as_str) + .collect(); + let supports_unknown = |name: &str| { + self.backend.layout().four_state + && self.backend.resolve_signal(&events[name].addr()).is_4state + }; Ok(ScheduleParts { time: record.time, clocks: record @@ -442,11 +455,17 @@ impl Simulator { .iter() .map(|(event, count)| (resolve(event), *count)) .collect(), - high_events: record.high_events.iter().map(|name| events[name]).collect(), + high_events: record + .high_events + .iter() + .filter(|name| !saved_unknown.contains(name.as_str()) || supports_unknown(name)) + .map(|name| events[name]) + .collect(), unknown_events: record .unknown_events .iter() .flatten() + .filter(|name| supports_unknown(name)) .map(|name| events[name]) .collect(), // State files are rejected for designs with processes. diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 838a57ca165..ebb935a1ece 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -164,3 +164,7 @@ sv_backends! { sv_backends! { fn escaped_import_commas_keep_explicit_callable_selection(sim){@case "timing::escaped_import_commas_keep_explicit_callable_selection";} } + +sv_backends! { + fn parameterized_interface_methods_keep_setup_edges(sim){@case "timing::parameterized_interface_methods_keep_setup_edges";} +} From c427930998b075770abc5c28fc697e8a23c0de58 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 22:41:09 +0900 Subject: [PATCH 41/75] test(suite): cover atomic blocking concatenations and finite feedback --- .../src/sv/cases/timing.vtest | 45 +++++++++++++++++++ .../tests/frontends/systemverilog/timing.rs | 9 ++++ 2 files changed, 54 insertions(+) diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index b013399736e..54c877616d9 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -898,3 +898,48 @@ endmodule"#) endmodule "#) (top Top)(set v 2)(set clk 1)(run_until 0)(assert_eq q 10)) + + +(case blocking_concatenation_publishes_one_event_update + ; IEEE 1800-2023 4.9.3 and 10.4.1: enable events from the LHS update. + (source "blocking_concat_events.sv" #" + module Top(output bit [1:0] q, r, output bit seen, ff_seen); + bit clk; + bit [1:0] data; + initial begin data = 3; #2; data = 2; end + initial begin #1; {q[1], q[0]} = 2'b11; #1; q[0] = 0; end + initial begin @(posedge (q[1] ^ q[0])); seen = 1; end + initial begin #1; clk = 1; #1; clk = 0; #1; clk = 1; end + always @(posedge clk) {r[1], r[0]} = data; + initial begin @(posedge (r[1] ^ r[0])); ff_seen = 1; end + endmodule + "#) + (top Top) + (run_until 1) + (assert_eq q 3) + (assert_eq r 3) + (assert_eq seen 0) + (assert_eq ff_seen 0) + (run_until 2) + (assert_eq q 2) + (assert_eq seen 1) + (assert_eq ff_seen 0) + (run_until 3) + (assert_eq r 2) + (assert_eq ff_seen 1)) + +(case finite_active_feedback_preserves_convergence + (source "finite_feedback.sv" #" + module Top(output bit [7:0] a, b); + initial begin #1; a = 1; end + always @(a) if (a < 4) b = a; + always @(b) if (b < 4) a = b + 1; + endmodule + "#) + (top Top) + (run_until 1) + (assert_eq a 4) + (assert_eq b 3) + (run_until 2) + (assert_eq a 4) + (assert_eq b 3)) diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index ebb935a1ece..e86a8f5f54a 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -168,3 +168,12 @@ sv_backends! { sv_backends! { fn parameterized_interface_methods_keep_setup_edges(sim){@case "timing::parameterized_interface_methods_keep_setup_edges";} } + +sv_backends! { + fn blocking_concatenation_publishes_one_event_update(sim) { + @case "timing::blocking_concatenation_publishes_one_event_update"; + } + fn finite_active_feedback_preserves_convergence(sim) { + @case "timing::finite_active_feedback_preserves_convergence"; + } +} From 30d87d32bd7beca9dd756b9f0015bf9e73fbf55e Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 00:02:10 +0900 Subject: [PATCH 42/75] fix(suite): resolve interface modport receivers for timed staging --- crates/celox-sv-analyzer/src/ast.rs | 21 + .../celox-test-suite/src/frontend/timed_ff.rs | 9 + .../src/sv/cases/timing.vtest | 31 + .../verification/sv/limitations.json | 3 +- .../verification/sv/limitations/icarus.json | 686 +++++++++--------- .../tests/frontends/systemverilog/timing.rs | 4 + 6 files changed, 414 insertions(+), 340 deletions(-) diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 2b367c7f544..e93636e930d 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -2560,6 +2560,27 @@ pub fn package_import_export_clauses( pub fn instance_type_sites(tree: &SyntaxTree) -> Vec<(usize, String, String)> { let mut sites = Vec::new(); for node in tree { + if let RefNode::AnsiPortDeclarationNet(port) = node.clone() + && let Some(sv_parser::NetPortHeaderOrInterfacePortHeader::InterfacePortHeader(header)) = + &port.nodes.0 + && let sv_parser::InterfacePortHeader::Identifier(header) = &**header + && let Some(module) = + identifier_text(RefNode::InterfaceIdentifier(&header.nodes.0), tree) + && let Some(identifier) = identifier_text(RefNode::PortIdentifier(&port.nodes.1), tree) + && let Some(offset) = + RefNode::PortIdentifier(&port.nodes.1) + .into_iter() + .find_map(|node| { + if let RefNode::Locate(loc) = node { + Some(loc.offset) + } else { + None + } + }) + { + sites.push((offset, identifier, module)); + } + let RefNode::ModuleInstantiation(instance) = node else { continue; }; diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index 562c0ed442a..d6b1b743f65 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -954,6 +954,15 @@ impl TaskTiming { mod callable_analysis_tests { use super::*; #[test] + fn modport_formals_resolve_their_interface_methods() { + let source="interface Scale;function automatic bit scaled(input bit v);return v;endfunction modport user(import scaled);endinterface module User(Scale.user s,input bit clk, v,output bit q);always @(posedge clk)q<=s.scaled(v);endmodule".to_owned(); + let tasks = TaskTiming::new(std::slice::from_ref(&source)); + assert_eq!( + tasks.resolve(&source, source.rfind("scaled(v)").unwrap(), "scaled"), + Some(false) + ); + } + #[test] fn parameterized_instances_resolve_their_declared_method_type() { let source="interface Scale #(parameter int K=1);function automatic bit scaled(input bit v);return v;endfunction endinterface module Top;Scale #(.K(5)) s();always @(posedge clk)q<=s.scaled(v);endmodule".to_owned(); let tasks = TaskTiming::new(std::slice::from_ref(&source)); diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 54c877616d9..5dc3f476c2a 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -943,3 +943,34 @@ endmodule"#) (run_until 2) (assert_eq a 4) (assert_eq b 3)) + +(case interface_modport_methods_keep_setup_edges + (source "modport-method.sv" #" + interface Scale #(parameter int K=5); + logic[3:0] base; + function automatic logic[3:0] scaled(input logic[3:0] v);return base+v*K;endfunction + modport user(import scaled); + endinterface + module User(Scale.user s,input bit clk,input logic[3:0] v,output logic[3:0] q); + always @(posedge clk)q<=s.scaled(v); + endmodule + module Top(input bit clk,input logic[3:0] v,output logic[3:0] q); + Scale #(.K(5)) s(); + assign s.base=0; + User u(.s(s),.clk(clk),.v(v),.q(q)); + endmodule + "#) + (top Top)(set v 2)(set clk 1)(run_until 0)(assert_eq q 10)) + +(case inactive_phases_preserve_cross_instance_edges + (source "inactive-phases.sv" #" + module Child(output bit[1:0] q); + initial begin #1;q[0]=1;end + initial begin #1;#0;q[1]=1;end + endmodule + module Top(output bit[7:0] seen); + wire[1:0] q;Child u(.q(q)); + initial forever begin @(q[0]^q[1]);seen=seen+1;end + endmodule + "#) + (top Top)(run_until 1)(assert_eq seen 2)) diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 7447ee7377a..fb0bb74c785 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -613,7 +613,8 @@ "interfaces::overrides_body_parameters_and_drives_members_from_imported_functions", "interfaces::reads_undriven_interface_members_as_unknown", "interfaces::rewrites_nested_references_and_keeps_declaration_functions", - "interfaces::runs_interface_processes_once_per_array_element" + "interfaces::runs_interface_processes_once_per_array_element", + "timing::interface_modport_methods_keep_setup_edges" ] } }, diff --git a/crates/celox-test-suite/verification/sv/limitations/icarus.json b/crates/celox-test-suite/verification/sv/limitations/icarus.json index 33a06fd54ef..6c4678aff9a 100644 --- a/crates/celox-test-suite/verification/sv/limitations/icarus.json +++ b/crates/celox-test-suite/verification/sv/limitations/icarus.json @@ -9,7 +9,7 @@ "unexpected_accept": 1, "mismatch": 14, "emission_error": 0, - "compile_error": 104, + "compile_error": 105, "runtime_error": 3, "unsupported": 0, "ignored": 0 @@ -96,194 +96,173 @@ "status": "mismatch" }, { - "category": "Arrays", - "detail": "Icarus build exit status: 12; see /build.log\n/source_0.sv:5: syntax error\n/source_0.sv:5: error: Invalid module item.\n/source_0.sv:6: syntax error\n/source_0.sv:6: error: Syntax error in continuous assignment\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Syntax error in continuous assignment\n/source_0.sv:8: syntax error\n/source_0.sv:8: error: Syntax error in continuous assignment\n/source_0.sv:9: syntax error\n/source_0.sv:9: error: Syntax error in continuous assignment\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Syntax error in continuous assignment\n", - "expectation": "Simulation", - "name": "indexed_select::indexed_constants_lower_selected_concatenations", - "phase": "compile", - "status": "compile_error" - }, - { - "category": "Arrays", - "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:9: syntax error\n/source_0.sv:9: error: Syntax error in continuous assignment\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Syntax error in continuous assignment\n", - "expectation": "Simulation", - "name": "indexed_select::indexed_constants_work_in_ordinary_selection_indices", - "phase": "compile", - "status": "compile_error" - }, - { - "category": "Arrays", - "detail": "Icarus build exit status: 8; see /build.log\n/source_0.sv:4: syntax error\n/source_0.sv:4: error: Syntax error in continuous assignment\n/source_0.sv:5: syntax error\n/source_0.sv:5: error: Syntax error in continuous assignment\n/source_0.sv:6: syntax error\n/source_0.sv:6: error: Syntax error in continuous assignment\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Syntax error in continuous assignment\n", + "category": "Hierarchy", + "detail": "Icarus build exit status: 7; see /build.log\n/source_0.sv:2: sorry: unpacked array parameters are not supported yet.\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Syntax error in parameter value assignment list.\n/source_0.sv:10: error: Invalid module instantiation\n/source_0.sv:11: syntax error\n/source_0.sv:11: error: Syntax error in parameter value assignment list.\n/source_0.sv:11: error: Invalid module instantiation\n", "expectation": "Simulation", - "name": "indexed_select::indexed_runtime_replications_preserve_attached_selections", + "name": "hierarchy::parameter_patterns_bind_caller_types", "phase": "compile", - "status": "compile_error" + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] }, { - "category": "Arrays", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:6: syntax error\n/source_0.sv:6: error: Syntax error in continuous assignment\n", + "category": "Hierarchy", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:2: syntax error\nI give up.\n", "expectation": "Simulation", - "name": "indexed_select::indexed_select_multidimensional_packed_reads", + "name": "hierarchy::parameter_patterns_bind_nested_caller_types", "phase": "compile", - "status": "compile_error" + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] }, { - "category": "Arrays", - "detail": "Icarus build exit status: 139; see /build.log\nSegmentation fault (core dumped)\n", + "category": "Hierarchy", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:2: sorry: unpacked array parameters are not supported yet.\n", "expectation": "Simulation", - "name": "indexed_select::indexed_select_parameterized_generate_and_ff", + "name": "hierarchy::parameter_patterns_evaluate_caller_constant_functions", "phase": "compile", - "status": "compile_error" + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] }, { - "category": "Arrays", - "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:2: sorry: packed array parameters are not supported yet.\n/source_0.sv:3: sorry: packed array parameters are not supported yet.\n/source_0.sv:4: sorry: packed array parameters are not supported yet.\n", + "category": "Hierarchy", + "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:2: sorry: unpacked array parameters are not supported yet.\n/source_0.sv:7: syntax error\nI give up.\n", "expectation": "Simulation", - "name": "indexed_select::indexed_size_queries_preserve_parameter_dimensions", + "name": "hierarchy::parameter_patterns_keep_fill_and_arithmetic_context", "phase": "compile", - "status": "compile_error" - }, - { - "category": "Operators", - "detail": "operators::propagates_child_input_width_into_connection_expressions at 1116:3: assert_eq y: expected 0x100, got 0x0", - "expectation": "Simulation", - "name": "operators::propagates_child_input_width_into_connection_expressions", - "phase": "execute", - "status": "mismatch" + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] }, { - "category": "ControlFlow", - "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:6: sorry: unpacked array parameters are not supported yet.\n/source_0.sv:7: sorry: unpacked array parameters are not supported yet.\n/source_0.sv:8: syntax error\n/source_0.sv:8: error: Invalid module item.\n", + "category": "Hierarchy", + "detail": "Icarus build exit status: 7; see /build.log\n/source_0.sv:2: sorry: unpacked array parameters are not supported yet.\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Syntax error in parameter value assignment list.\n/source_0.sv:7: error: Invalid module instantiation\n/source_0.sv:8: syntax error\n/source_0.sv:8: error: Syntax error in parameter value assignment list.\n/source_0.sv:8: error: Invalid module instantiation\n", "expectation": "Simulation", - "name": "procedural::aggregate_parameters_are_constant_tables", + "name": "hierarchy::parameter_patterns_keep_unknown_fill", "phase": "compile", - "status": "compile_error" + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] }, { - "category": "ControlFlow", - "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:4: error: Function celox_suite_tb.dut.pick port y is not an input port.\n/source_0.sv:4: : Function arguments must be input ports.\n1 error(s) during elaboration.\n", + "category": "Hierarchy", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:3: sorry: unpacked array parameters are not supported yet.\n", "expectation": "Simulation", - "name": "procedural::select_indices_call_functions", + "name": "hierarchy::parameter_patterns_override_body_declarations", "phase": "compile", - "status": "compile_error" + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] }, { - "category": "Regression", - "detail": "Icarus build exit status: 139; see /build.log\nSegmentation fault (core dumped)\n", + "category": "Hierarchy", + "detail": "Icarus build exit status: 9; see /build.log\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Syntax error in parameter value assignment list.\n/source_0.sv:10: error: Invalid module instantiation\n/source_0.sv:11: syntax error\n/source_0.sv:11: error: Syntax error in parameter value assignment list.\n/source_0.sv:11: error: Invalid module instantiation\n/source_0.sv:12: syntax error\n/source_0.sv:12: error: Syntax error in parameter value assignment list.\n/source_0.sv:12: error: Invalid module instantiation\n", "expectation": "Simulation", - "name": "review_regressions::preserves_size_cast_dimensions_in_declarations_and_selections", + "name": "hierarchy::parameter_patterns_override_scalar_defaults", "phase": "compile", - "status": "compile_error" + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] }, { - "category": "Regression", - "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:33: error: Cast size expression must be constant and greater than zero.\n1 error(s) during elaboration.\n", + "category": "Hierarchy", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:5: syntax error\nI give up.\n", "expectation": "Simulation", - "name": "review_regressions::preserves_use_site_dimensions_in_function_alias_types", + "name": "hierarchy::parameter_patterns_preserve_packed_member_states", "phase": "compile", - "status": "compile_error" + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] }, { - "category": "Combinational", - "detail": "Icarus build exit status: 7; see /build.log\n/source_0.sv:13: error: Function celox_suite_tb.dut.bump port v is not an input port.\n/source_0.sv:13: : Function arguments must be input ports.\n/source_0.sv:9: error: Function celox_suite_tb.dut.clamp port l is not an input port.\n/source_0.sv:9: : Function arguments must be input ports.\n/source_0.sv:9: error: Function celox_suite_tb.dut.clamp port h is not an input port.\n/source_0.sv:9: : Function arguments must be input ports.\n/source_0.sv:16: error: Function celox_suite_tb.dut.invert port z is not an input port.\n/source_0.sv:16: : Function arguments must be input ports.\n/source_0.sv:19: error: Function celox_suite_tb.dut.shift port z is not an input port.\n/source_0.sv:19: : Function arguments must be input ports.\n/source_0.sv:5: error: Function celox_suite_tb.dut.sum_diff port s is not an input port.\n/source_0.sv:5: : Function arguments must be input ports.\n/source_0.sv:5: error: Function celox_suite_tb.dut.sum_diff port d is not an input port.\n/source_0.sv:5: : Function arguments must be input ports.\n/source_0.sv:29: sorry: constant selects in always_* processes are not fully supported (the process will be sensitive to all bits in 'a[7:0]').\n7 error(s) during elaboration.\n", + "category": "Hierarchy", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:5: syntax error\nI give up.\n", "expectation": "Simulation", - "name": "synthesizable::function_output_and_inout_arguments_are_written_back", + "name": "hierarchy::parameter_patterns_transfer_packed_values", "phase": "compile", - "status": "compile_error" + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] }, { - "category": "Combinational", - "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:6: vvp.tgt error: uwire \"lanes\" must have a single driver, found (4).\nerror: Code generation had 1 error(s).\n", + "category": "Arrays", + "detail": "Icarus build exit status: 18; see /build.log\n/source_0.sv:13: syntax error\n/source_0.sv:13: Syntax in assignment statement l-value.\n/source_0.sv:17: syntax error\n/source_0.sv:17: Syntax in assignment statement l-value.\n/source_0.sv:19: syntax error\n/source_0.sv:19: error: Syntax error in continuous assignment\n/source_0.sv:20: syntax error\n/source_0.sv:20: error: Syntax error in continuous assignment\n/source_0.sv:21: syntax error\n/source_0.sv:21: error: Syntax error in continuous assignment\n/source_0.sv:22: syntax error\n/source_0.sv:22: error: Syntax error in continuous assignment\n/source_0.sv:23: syntax error\n/source_0.sv:23: error: Syntax error in continuous assignment\n/source_0.sv:24: syntax error\n/source_0.sv:24: error: Syntax error in continuous assignment\n/source_0.sv:25: syntax error\n/source_0.sv:25: error: Syntax error in continuous assignment\n", "expectation": "Simulation", - "name": "synthesizable::instance_array_unpacked_connection_ascending_to_descending", + "name": "indexed_select::constant_part_select_indices_of_concatenations", "phase": "compile", "status": "compile_error" }, { - "category": "Combinational", - "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:6: vvp.tgt error: uwire \"lanes\" must have a single driver, found (4).\nerror: Code generation had 1 error(s).\n", + "category": "Arrays", + "detail": "Icarus build exit status: 12; see /build.log\n/source_0.sv:5: syntax error\n/source_0.sv:5: error: Invalid module item.\n/source_0.sv:6: syntax error\n/source_0.sv:6: error: Syntax error in continuous assignment\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Syntax error in continuous assignment\n/source_0.sv:8: syntax error\n/source_0.sv:8: error: Syntax error in continuous assignment\n/source_0.sv:9: syntax error\n/source_0.sv:9: error: Syntax error in continuous assignment\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Syntax error in continuous assignment\n", "expectation": "Simulation", - "name": "synthesizable::instance_array_unpacked_connection_descending_to_ascending", + "name": "indexed_select::indexed_constants_lower_selected_concatenations", "phase": "compile", "status": "compile_error" }, { - "category": "Combinational", - "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:6: vvp.tgt error: uwire \"lanes\" must have a single driver, found (4).\nerror: Code generation had 1 error(s).\n", + "category": "Arrays", + "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:9: syntax error\n/source_0.sv:9: error: Syntax error in continuous assignment\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Syntax error in continuous assignment\n", "expectation": "Simulation", - "name": "synthesizable::instance_array_unpacked_connection_descending_to_descending", + "name": "indexed_select::indexed_constants_work_in_ordinary_selection_indices", "phase": "compile", "status": "compile_error" }, { - "category": "Combinational", - "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:6: vvp.tgt error: uwire \"lanes\" must have a single driver, found (4).\nerror: Code generation had 1 error(s).\n", + "category": "Arrays", + "detail": "Icarus build exit status: 8; see /build.log\n/source_0.sv:4: syntax error\n/source_0.sv:4: error: Syntax error in continuous assignment\n/source_0.sv:5: syntax error\n/source_0.sv:5: error: Syntax error in continuous assignment\n/source_0.sv:6: syntax error\n/source_0.sv:6: error: Syntax error in continuous assignment\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Syntax error in continuous assignment\n", "expectation": "Simulation", - "name": "synthesizable::instance_array_unpacked_connection_offset_ranges", + "name": "indexed_select::indexed_runtime_replications_preserve_attached_selections", "phase": "compile", "status": "compile_error" }, { - "category": "Combinational", - "detail": "invalid design was accepted: synthesizable::instance_arrays_reject_a_fill_literal_tie_off", - "expectation": "CompilationError", - "name": "synthesizable::instance_arrays_reject_a_fill_literal_tie_off", - "phase": "execute", - "status": "unexpected_accept" - }, - { - "category": "Combinational", - "detail": "Icarus build exit status: 6; see /build.log\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Syntax error in continuous assignment\n/source_0.sv:9: syntax error\n/source_0.sv:9: error: Malformed statement\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Malformed statement\n", + "category": "Arrays", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:6: syntax error\n/source_0.sv:6: error: Syntax error in continuous assignment\n", "expectation": "Simulation", - "name": "synthesizable::struct_assignment_patterns_follow_the_target_layout", + "name": "indexed_select::indexed_select_multidimensional_packed_reads", "phase": "compile", "status": "compile_error" }, { - "category": "Combinational", - "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:3: sorry: \"inside\" expressions not supported yet.\n/source_0.sv:5: sorry: \"inside\" expressions not supported yet.\n/source_0.sv:6: sorry: \"inside\" expressions not supported yet.\n", + "category": "Arrays", + "detail": "Icarus build exit status: 139; see /build.log\nSegmentation fault (core dumped)\n", "expectation": "Simulation", - "name": "synthesizable::inside_matches_values_ranges_and_wildcards", + "name": "indexed_select::indexed_select_parameterized_generate_and_ff", "phase": "compile", "status": "compile_error" }, { - "category": "Regression", - "detail": "Icarus build exit status: 158; see /build.log\n/source_0.sv:7: syntax error\n/source_0.sv:7: Syntax in assignment statement l-value.\n/source_0.sv:7: syntax error\n/source_0.sv:8: Syntax in assignment statement l-value.\n/source_0.sv:8: syntax error\n/source_0.sv:9: Syntax in assignment statement l-value.\n/source_0.sv:9: syntax error\n/testbench.sv:3: error: Malformed statement\n/testbench.sv:4: syntax error\n/testbench.sv:4: error: Malformed statement\n/testbench.sv:5: syntax error\n/testbench.sv:5: error: Malformed statement\n/testbench.sv:6: syntax error\n/testbench.sv:6: error: Malformed statement\n/testbench.sv:7: syntax error\n/testbench.sv:7: error: Malformed statement\n/testbench.sv:8: syntax error\n/testbench.sv:8: error: Malformed statement\n/testbench.sv:10: syntax error\n/testbench.sv:10: error: Malformed statement\n/testbench.sv:13: syntax error\n/testbench.sv:15: error: Malformed statement\n/testbench.sv:17: syntax error\n/testbench.sv:19: error: Invalid module item.\n/tmp/nix-shell.S1fXMv/claude-1000", + "category": "Arrays", + "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:2: sorry: packed array parameters are not supported yet.\n/source_0.sv:3: sorry: packed array parameters are not supported yet.\n/source_0.sv:4: sorry: packed array parameters are not supported yet.\n", "expectation": "Simulation", - "name": "review_regressions::preserves_four_state_shift_and_bit_select_constants", + "name": "indexed_select::indexed_size_queries_preserve_parameter_dimensions", "phase": "compile", "status": "compile_error" }, { - "category": "Types", - "detail": "packed_structs::packed_struct_bounds_and_type_queries at 232:5: assert_eq widths: expected 0x22, got 0x20", - "expectation": "Simulation", - "name": "packed_structs::packed_struct_bounds_and_type_queries", - "phase": "execute", - "status": "mismatch" - }, - { - "category": "Types", - "detail": "packed_structs::packed_struct_mixed_state_members at 178:7: assert_eq compound_result: expected 0xx1, got 0xxx", - "expectation": "Simulation", - "name": "packed_structs::packed_struct_mixed_state_members", - "phase": "execute", - "status": "mismatch" - }, - { - "category": "Regression", - "detail": "review_regressions::preserves_four_state_arithmetic_case_constants at 306:7: assert_eq y11: expected 0x1, got 0xX (y11)", + "category": "Arrays", + "detail": "indexed_select::out_of_range_inner_indices_stay_in_their_element at 742:7: assert_eq b: expected 0xX, got 0x0 (b)", "expectation": "Simulation", - "name": "review_regressions::preserves_four_state_arithmetic_case_constants", + "name": "indexed_select::out_of_range_inner_indices_stay_in_their_element", "phase": "execute", "status": "mismatch" }, { - "category": "Types", - "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:7: sorry: packed array parameters are not supported yet.\n", + "category": "Arrays", + "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:11: error: A reference to a net or variable (`k') is not allowed in a constant expression.\n/source_0.sv:11: error: Array index expressions must be constant here.\n/source_0.sv:11: error: Unable to elaborate r-value: u[j][k][i]\n/source_0.sv:5: warning: always_comb process has no sensitivities.\n3 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "types::packed_parameters_of_signed_named_types_have_signed_elements", + "name": "indexed_select::out_of_range_inner_indices_stay_in_their_multidimensional_unpacked_element", "phase": "compile", "status": "compile_error" }, @@ -295,14 +274,6 @@ "phase": "compile", "status": "compile_error" }, - { - "category": "Arrays", - "detail": "indexed_select::out_of_range_inner_indices_stay_in_their_element at 742:7: assert_eq b: expected 0xX, got 0x0 (b)", - "expectation": "Simulation", - "name": "indexed_select::out_of_range_inner_indices_stay_in_their_element", - "phase": "execute", - "status": "mismatch" - }, { "category": "Hierarchy", "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:14: syntax error\n/source_0.sv:14: Errors in port declarations.\n/source_0.sv:17: syntax error\n/source_0.sv:17: Errors in port declarations.\n", @@ -391,43 +362,67 @@ "phase": "compile", "status": "compile_error" }, + { + "category": "Operators", + "detail": "operators::propagates_child_input_width_into_connection_expressions at 1116:3: assert_eq y: expected 0x100, got 0x0", + "expectation": "Simulation", + "name": "operators::propagates_child_input_width_into_connection_expressions", + "phase": "execute", + "status": "mismatch" + }, { "category": "Types", - "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:3: sorry: Subroutine ports with unpacked dimensions are not yet supported.\n/source_0.sv:10: error: Array v needs an array index here.\n/source_0.sv:11: error: Array v needs an array index here.\n/source_0.sv:8: sorry: constant selects in always_* processes are not fully supported (the process will be sensitive to all bits in 'd[15:0]').\n/source_0.sv:9: sorry: constant selects in always_* processes are not fully supported (the process will be sensitive to all bits in 'd[15:0]').\n3 error(s) during elaboration.\n", + "detail": "packed_structs::packed_struct_bounds_and_type_queries at 232:5: assert_eq widths: expected 0x22, got 0x20", "expectation": "Simulation", - "name": "types::passes_unpacked_arguments_of_equivalent_element_types", + "name": "packed_structs::packed_struct_bounds_and_type_queries", + "phase": "execute", + "status": "mismatch" + }, + { + "category": "Types", + "detail": "packed_structs::packed_struct_mixed_state_members at 178:7: assert_eq compound_result: expected 0xx1, got 0xxx", + "expectation": "Simulation", + "name": "packed_structs::packed_struct_mixed_state_members", + "phase": "execute", + "status": "mismatch" + }, + { + "category": "ControlFlow", + "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:6: sorry: unpacked array parameters are not supported yet.\n/source_0.sv:7: sorry: unpacked array parameters are not supported yet.\n/source_0.sv:8: syntax error\n/source_0.sv:8: error: Invalid module item.\n", + "expectation": "Simulation", + "name": "procedural::aggregate_parameters_are_constant_tables", "phase": "compile", "status": "compile_error" }, { - "category": "Types", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:7: sorry: Procedural assignment of array or array slice is not yet supported.\n/source_0.sv:7: sorry: Procedural assignment of array or array slice is not yet supported.\n2 error(s) during elaboration.\n", - "expectation": "CompilationError", - "name": "types::rejects_assignment_pattern_item_of_a_narrower_array_type", + "category": "ControlFlow", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:6: error: Function celox_suite_tb.dut.bump port after is not an input port.\n/source_0.sv:6: : Function arguments must be input ports.\n1 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "procedural::concatenated_targets_fix_their_positions_first", "phase": "compile", "status": "compile_error" }, { - "category": "Types", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:3: sorry: Subroutine ports with unpacked dimensions are not yet supported.\n/source_0.sv:10: error: Array narrow needs an array index here.\n/source_0.sv:7: warning: always_comb process has no sensitivities.\n2 error(s) during elaboration.\n", - "expectation": "CompilationError", - "name": "types::rejects_unpacked_argument_of_a_wider_element_type", + "category": "ControlFlow", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:5: error: Function celox_suite_tb.dut.tick port after is not an input port.\n/source_0.sv:5: : Function arguments must be input ports.\n1 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "procedural::ff_select_index_calls_write_state_and_run_once", "phase": "compile", "status": "compile_error" }, { - "category": "Regression", - "detail": "Icarus build exit status: 6; see /build.log\n/source_0.sv:9: syntax error\n/source_0.sv:9: error: Malformed statement\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Malformed statement\n/source_0.sv:18: syntax error\n/source_0.sv:18: error: Malformed statement\n", + "category": "ControlFlow", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:6: error: Function celox_suite_tb.dut.inner port after is not an input port.\n/source_0.sv:6: : Function arguments must be input ports.\n1 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "review_regressions::default_pattern_fills_each_element_of_unpacked_subarrays", + "name": "procedural::function_bodies_run_their_index_calls_each_time", "phase": "compile", "status": "compile_error" }, { - "category": "Regression", - "detail": "Icarus build exit status: 18; see /build.log\n/source_0.sv:4: error: Type names are not valid expressions here.\n/source_0.sv:4: internal error: I do not know how to elaborate this expression. \n/source_0.sv:4: : Expression is: \n/source_0.sv:4: : Expression type: 10PETypename\n/source_0.sv:4: error: Unable to elaborate r-value: $size(, 'sd1)\n/source_0.sv:5: error: Type names are not valid expressions here.\n/source_0.sv:5: internal error: I do not know how to elaborate this expression. \n/source_0.sv:5: : Expression is: \n/source_0.sv:5: : Expression type: 10PETypename\n/source_0.sv:5: error: Unable to elaborate r-value: $size(, 'sd2)\n/source_0.sv:6: error: Type names are not valid expressions here.\n/source_0.sv:6: internal error: I do not know how to elaborate this expression. \n/source_0.sv:6: : Expression is: \n/source_0.sv:6: : Expression type: 10PETypename\n/source_0.sv:6: error: Unable to elaborate r-value: $size(, 'sd1)\n/source_0.sv:7: error: Type names are not valid expressions here.\n/source_0.sv:7: internal error: I do not know how to elaborate this expression. \n/source_0.sv:7: : Expression is: \n/source_0.sv:7: : Expression type: 10PETypename\n/source_0.sv:7: error: Unable to elaborate r-value: $size(, 'sd2)\n/source_0.sv:8: error: Type names are not valid expressions here.\n/source_0.sv:8: internal error: I do not know how to elaborate this expression. \n/source_0.sv:8: : Expression is: \n/source_0.sv:8: : Expression type: 10PETypename\n/source_0.sv:8: error:", + "category": "ControlFlow", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:5: error: Function celox_suite_tb.dut.tick port after is not an input port.\n/source_0.sv:5: : Function arguments must be input ports.\n1 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "review_regressions::size_of_a_type_uses_the_dimension_argument", + "name": "procedural::select_index_call_skipped_by_logical_and", "phase": "compile", "status": "compile_error" }, @@ -441,100 +436,121 @@ }, { "category": "ControlFlow", - "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:5: error: Function celox_suite_tb.dut.tick port after is not an input port.\n/source_0.sv:5: : Function arguments must be input ports.\n1 error(s) during elaboration.\n", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:4: error: Function celox_suite_tb.dut.pick port y is not an input port.\n/source_0.sv:4: : Function arguments must be input ports.\n1 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "procedural::select_index_call_skipped_by_logical_and", + "name": "procedural::select_indices_call_functions", "phase": "compile", "status": "compile_error" }, { - "category": "ControlFlow", - "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:6: error: Function celox_suite_tb.dut.bump port after is not an input port.\n/source_0.sv:6: : Function arguments must be input ports.\n1 error(s) during elaboration.\n", + "category": "Regression", + "detail": "Icarus build exit status: 6; see /build.log\n/source_0.sv:9: syntax error\n/source_0.sv:9: error: Malformed statement\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Malformed statement\n/source_0.sv:18: syntax error\n/source_0.sv:18: error: Malformed statement\n", "expectation": "Simulation", - "name": "procedural::concatenated_targets_fix_their_positions_first", + "name": "review_regressions::default_pattern_fills_each_element_of_unpacked_subarrays", "phase": "compile", "status": "compile_error" }, { - "category": "ControlFlow", - "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:5: error: Function celox_suite_tb.dut.tick port after is not an input port.\n/source_0.sv:5: : Function arguments must be input ports.\n1 error(s) during elaboration.\n", + "category": "Regression", + "detail": "review_regressions::preserves_four_state_arithmetic_case_constants at 306:7: assert_eq y11: expected 0x1, got 0xX (y11)", "expectation": "Simulation", - "name": "procedural::ff_select_index_calls_write_state_and_run_once", + "name": "review_regressions::preserves_four_state_arithmetic_case_constants", + "phase": "execute", + "status": "mismatch" + }, + { + "category": "Regression", + "detail": "Icarus build exit status: 158; see /build.log\n/source_0.sv:7: syntax error\n/source_0.sv:7: Syntax in assignment statement l-value.\n/source_0.sv:7: syntax error\n/source_0.sv:8: Syntax in assignment statement l-value.\n/source_0.sv:8: syntax error\n/source_0.sv:9: Syntax in assignment statement l-value.\n/source_0.sv:9: syntax error\n/testbench.sv:3: error: Malformed statement\n/testbench.sv:4: syntax error\n/testbench.sv:4: error: Malformed statement\n/testbench.sv:5: syntax error\n/testbench.sv:5: error: Malformed statement\n/testbench.sv:6: syntax error\n/testbench.sv:6: error: Malformed statement\n/testbench.sv:7: syntax error\n/testbench.sv:7: error: Malformed statement\n/testbench.sv:8: syntax error\n/testbench.sv:8: error: Malformed statement\n/testbench.sv:10: syntax error\n/testbench.sv:10: error: Malformed statement\n/testbench.sv:13: syntax error\n/testbench.sv:15: error: Malformed statement\n/testbench.sv:17: syntax error\n/testbench.sv:19: error: Invalid module item.\n/tmp/nix-shell.S1fXMv/claude-1000", + "expectation": "Simulation", + "name": "review_regressions::preserves_four_state_shift_and_bit_select_constants", "phase": "compile", "status": "compile_error" }, { - "category": "ControlFlow", - "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:6: error: Function celox_suite_tb.dut.inner port after is not an input port.\n/source_0.sv:6: : Function arguments must be input ports.\n1 error(s) during elaboration.\n", + "category": "Regression", + "detail": "Icarus build exit status: 139; see /build.log\nSegmentation fault (core dumped)\n", "expectation": "Simulation", - "name": "procedural::function_bodies_run_their_index_calls_each_time", + "name": "review_regressions::preserves_size_cast_dimensions_in_declarations_and_selections", "phase": "compile", "status": "compile_error" }, { - "category": "Arrays", - "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:11: error: A reference to a net or variable (`k') is not allowed in a constant expression.\n/source_0.sv:11: error: Array index expressions must be constant here.\n/source_0.sv:11: error: Unable to elaborate r-value: u[j][k][i]\n/source_0.sv:5: warning: always_comb process has no sensitivities.\n3 error(s) during elaboration.\n", + "category": "Regression", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:33: error: Cast size expression must be constant and greater than zero.\n1 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "indexed_select::out_of_range_inner_indices_stay_in_their_multidimensional_unpacked_element", + "name": "review_regressions::preserves_use_site_dimensions_in_function_alias_types", "phase": "compile", "status": "compile_error" }, { - "category": "Functions", - "detail": "system_functions::display_field_widths_expand_to_the_value at 245:3: expect_output: expected \":1234:11064:\\n\", got \":00001234:00000011064:\\n\"", + "category": "Regression", + "detail": "Icarus build exit status: 18; see /build.log\n/source_0.sv:4: error: Type names are not valid expressions here.\n/source_0.sv:4: internal error: I do not know how to elaborate this expression. \n/source_0.sv:4: : Expression is: \n/source_0.sv:4: : Expression type: 10PETypename\n/source_0.sv:4: error: Unable to elaborate r-value: $size(, 'sd1)\n/source_0.sv:5: error: Type names are not valid expressions here.\n/source_0.sv:5: internal error: I do not know how to elaborate this expression. \n/source_0.sv:5: : Expression is: \n/source_0.sv:5: : Expression type: 10PETypename\n/source_0.sv:5: error: Unable to elaborate r-value: $size(, 'sd2)\n/source_0.sv:6: error: Type names are not valid expressions here.\n/source_0.sv:6: internal error: I do not know how to elaborate this expression. \n/source_0.sv:6: : Expression is: \n/source_0.sv:6: : Expression type: 10PETypename\n/source_0.sv:6: error: Unable to elaborate r-value: $size(, 'sd1)\n/source_0.sv:7: error: Type names are not valid expressions here.\n/source_0.sv:7: internal error: I do not know how to elaborate this expression. \n/source_0.sv:7: : Expression is: \n/source_0.sv:7: : Expression type: 10PETypename\n/source_0.sv:7: error: Unable to elaborate r-value: $size(, 'sd2)\n/source_0.sv:8: error: Type names are not valid expressions here.\n/source_0.sv:8: internal error: I do not know how to elaborate this expression. \n/source_0.sv:8: : Expression is: \n/source_0.sv:8: : Expression type: 10PETypename\n/source_0.sv:8: error:", "expectation": "Simulation", - "name": "system_functions::display_field_widths_expand_to_the_value", - "phase": "execute", - "status": "mismatch" + "name": "review_regressions::size_of_a_type_uses_the_dimension_argument", + "phase": "compile", + "status": "compile_error" }, { - "category": "Functions", - "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:4: sorry: packed array parameters are not supported yet.\n", + "category": "Combinational", + "detail": "Icarus build exit status: 7; see /build.log\n/source_0.sv:13: error: Function celox_suite_tb.dut.bump port v is not an input port.\n/source_0.sv:13: : Function arguments must be input ports.\n/source_0.sv:9: error: Function celox_suite_tb.dut.clamp port l is not an input port.\n/source_0.sv:9: : Function arguments must be input ports.\n/source_0.sv:9: error: Function celox_suite_tb.dut.clamp port h is not an input port.\n/source_0.sv:9: : Function arguments must be input ports.\n/source_0.sv:16: error: Function celox_suite_tb.dut.invert port z is not an input port.\n/source_0.sv:16: : Function arguments must be input ports.\n/source_0.sv:19: error: Function celox_suite_tb.dut.shift port z is not an input port.\n/source_0.sv:19: : Function arguments must be input ports.\n/source_0.sv:5: error: Function celox_suite_tb.dut.sum_diff port s is not an input port.\n/source_0.sv:5: : Function arguments must be input ports.\n/source_0.sv:5: error: Function celox_suite_tb.dut.sum_diff port d is not an input port.\n/source_0.sv:5: : Function arguments must be input ports.\n/source_0.sv:29: sorry: constant selects in always_* processes are not fully supported (the process will be sensitive to all bits in 'a[7:0]').\n7 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "system_functions::dimensions_is_independent_of_unknown_values", + "name": "synthesizable::function_output_and_inout_arguments_are_written_back", "phase": "compile", "status": "compile_error" }, { - "category": "Functions", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:3: syntax error\n/source_0.sv:3: error: Syntax error in continuous assignment\n", + "category": "Combinational", + "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:3: sorry: \"inside\" expressions not supported yet.\n/source_0.sv:5: sorry: \"inside\" expressions not supported yet.\n/source_0.sv:6: sorry: \"inside\" expressions not supported yet.\n", "expectation": "Simulation", - "name": "system_functions::dimensions_of_nonarray_handle_types", + "name": "synthesizable::inside_matches_values_ranges_and_wildcards", "phase": "compile", "status": "compile_error" }, { - "category": "Functions", - "detail": "Icarus build exit status: 5; see /build.log\n/source_0.sv:16: error: A reference to a net or variable (`index') is not allowed in a constant expression.\n/source_0.sv:16: error: Array index expressions must be constant here.\n/source_0.sv:16: error: Unable to elaborate r-value: $dimensions(a[index]['sd0])\n/source_0.sv:19: error: Array memory[index] needs 2 indices, but got only 1.\n/source_0.sv:19: error: Unable to elaborate r-value: $dimensions(memory[index])\n5 error(s) during elaboration.\n", + "category": "Combinational", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:6: vvp.tgt error: uwire \"lanes\" must have a single driver, found (4).\nerror: Code generation had 1 error(s).\n", "expectation": "Simulation", - "name": "system_functions::dimensions_preserves_selected_and_expression_types", + "name": "synthesizable::instance_array_unpacked_connection_ascending_to_descending", "phase": "compile", "status": "compile_error" }, { - "category": "Functions", - "detail": "Icarus build exit status: 134; see /build.log\n/source_0.sv:4: error: Type names are not valid expressions here.\n/source_0.sv:4: internal error: I do not know how to elaborate this expression. \n/source_0.sv:4: : Expression is: \n/source_0.sv:4: : Expression type: 10PETypename\n/source_0.sv:4: error: Type names are not valid expressions here.\n/source_0.sv:4: internal error: I do not know how to elaborate this expression. \n/source_0.sv:4: : Expression is: \n/source_0.sv:4: : Expression type: 10PETypename\n/source_0.sv:33: assert: netmisc.cc:1860: failed assertion packed_dims.size() == 1\nAborted (core dumped)\n", + "category": "Combinational", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:6: vvp.tgt error: uwire \"lanes\" must have a single driver, found (4).\nerror: Code generation had 1 error(s).\n", "expectation": "Simulation", - "name": "system_functions::dimensions_resolves_types_and_constant_scopes", + "name": "synthesizable::instance_array_unpacked_connection_descending_to_ascending", "phase": "compile", "status": "compile_error" }, { - "category": "Functions", - "detail": "system_functions::dimensions_preserves_one_bit_vectors at 889:5: assert_eq literal_rank: expected 0x1, got 0x0", + "category": "Combinational", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:6: vvp.tgt error: uwire \"lanes\" must have a single driver, found (4).\nerror: Code generation had 1 error(s).\n", "expectation": "Simulation", - "name": "system_functions::dimensions_preserves_one_bit_vectors", + "name": "synthesizable::instance_array_unpacked_connection_descending_to_descending", + "phase": "compile", + "status": "compile_error" + }, + { + "category": "Combinational", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:6: vvp.tgt error: uwire \"lanes\" must have a single driver, found (4).\nerror: Code generation had 1 error(s).\n", + "expectation": "Simulation", + "name": "synthesizable::instance_array_unpacked_connection_offset_ranges", + "phase": "compile", + "status": "compile_error" + }, + { + "category": "Combinational", + "detail": "invalid design was accepted: synthesizable::instance_arrays_reject_a_fill_literal_tie_off", + "expectation": "CompilationError", + "name": "synthesizable::instance_arrays_reject_a_fill_literal_tie_off", "phase": "execute", - "status": "mismatch", - "stronger_than_sv": false, - "tag_reasons": {}, - "tags": [] + "status": "unexpected_accept" }, { - "category": "Functions", - "detail": "system_functions::dimensions_resolves_imported_function_returns at 925:3: assert_eq imported_rank: expected 0x2, got 0x0", + "category": "Combinational", + "detail": "synthesizable::named_calls_in_constant_contexts at 686:3: assert_eq query: expected 0x10, got 0x0", "expectation": "Simulation", - "name": "system_functions::dimensions_resolves_imported_function_returns", + "name": "synthesizable::named_calls_in_constant_contexts", "phase": "execute", "status": "mismatch", "stronger_than_sv": false, @@ -542,43 +558,45 @@ "tags": [] }, { - "category": "Functions", - "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:3: sorry: unpacked array parameters are not supported yet.\n", + "category": "Combinational", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:4: error: A reference to a net or variable (`a') is not allowed in a constant expression.\n/source_0.sv:4: error: Unable to evaluate a as a port default expression.\n2 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "system_functions::dimensions_resolves_package_array_constants", + "name": "synthesizable::named_calls_preserve_defaults_and_declaration_scope", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, "tag_reasons": {}, "tags": [] }, + { + "category": "Combinational", + "detail": "Icarus build exit status: 6; see /build.log\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Syntax error in continuous assignment\n/source_0.sv:9: syntax error\n/source_0.sv:9: error: Malformed statement\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Malformed statement\n", + "expectation": "Simulation", + "name": "synthesizable::struct_assignment_patterns_follow_the_target_layout", + "phase": "compile", + "status": "compile_error" + }, { "category": "Functions", - "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:8: sorry: Subroutine ports with unpacked dimensions are not yet supported.\n/source_0.sv:4: sorry: Subroutine ports with unpacked dimensions are not yet supported.\n/source_0.sv:23: error: Array argument needs an array index here.\n/source_0.sv:24: error: Array argument needs an array index here.\n4 error(s) during elaboration.\n", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:4: sorry: packed array parameters are not supported yet.\n", "expectation": "Simulation", - "name": "system_functions::dimensions_resolves_procedural_scopes", + "name": "system_functions::dimensions_is_independent_of_unknown_values", "phase": "compile", - "status": "compile_error", - "stronger_than_sv": false, - "tag_reasons": {}, - "tags": [] + "status": "compile_error" }, { "category": "Functions", - "detail": "system_functions::dimensions_resolves_procedural_parameters_and_indices at 1009:3: assert_eq local_parameter: expected 0x1, got 0x0", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:3: syntax error\n/source_0.sv:3: error: Syntax error in continuous assignment\n", "expectation": "Simulation", - "name": "system_functions::dimensions_resolves_procedural_parameters_and_indices", - "phase": "execute", - "status": "mismatch", - "stronger_than_sv": false, - "tag_reasons": {}, - "tags": [] + "name": "system_functions::dimensions_of_nonarray_handle_types", + "phase": "compile", + "status": "compile_error" }, { "category": "Functions", - "detail": "system_functions::dimensions_signing_conversions_are_vectors at 986:3: assert_eq signed_scalar: expected 0x1, got 0x0", + "detail": "system_functions::dimensions_preserves_one_bit_vectors at 889:5: assert_eq literal_rank: expected 0x1, got 0x0", "expectation": "Simulation", - "name": "system_functions::dimensions_signing_conversions_are_vectors", + "name": "system_functions::dimensions_preserves_one_bit_vectors", "phase": "execute", "status": "mismatch", "stronger_than_sv": false, @@ -587,31 +605,28 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:3: sorry: Subroutine ports with unpacked dimensions are not yet supported.\n/source_0.sv:7: error: Packed array assignment pattern expects 8 element(s) in this context.\n/source_0.sv:7: : Found 2 element(s).\n2 error(s) during elaboration.\n", + "detail": "Icarus build exit status: 5; see /build.log\n/source_0.sv:16: error: A reference to a net or variable (`index') is not allowed in a constant expression.\n/source_0.sv:16: error: Array index expressions must be constant here.\n/source_0.sv:16: error: Unable to elaborate r-value: $dimensions(a[index]['sd0])\n/source_0.sv:19: error: Array memory[index] needs 2 indices, but got only 1.\n/source_0.sv:19: error: Unable to elaborate r-value: $dimensions(memory[index])\n5 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "system_functions::dimensions_types_function_pattern_arguments", + "name": "system_functions::dimensions_preserves_selected_and_expression_types", "phase": "compile", - "status": "compile_error", - "stronger_than_sv": false, - "tag_reasons": {}, - "tags": [] + "status": "compile_error" }, { "category": "Functions", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:2: syntax error\nI give up.\n", + "detail": "system_functions::dimensions_resolves_imported_function_returns at 925:3: assert_eq imported_rank: expected 0x2, got 0x0", "expectation": "Simulation", - "name": "system_functions::isunbounded_handles_overrides_and_forwarding", - "phase": "compile", - "status": "compile_error", + "name": "system_functions::dimensions_resolves_imported_function_returns", + "phase": "execute", + "status": "mismatch", "stronger_than_sv": false, "tag_reasons": {}, "tags": [] }, { "category": "Functions", - "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:4: syntax error\n/source_0.sv:4: error: Invalid module item.\n/source_0.sv:23: syntax error\n/source_0.sv:22: error: Syntax error defining function.\n", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:3: sorry: unpacked array parameters are not supported yet.\n", "expectation": "Simulation", - "name": "system_functions::isunbounded_preserves_lexical_scopes_and_short_circuits", + "name": "system_functions::dimensions_resolves_package_array_constants", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -620,20 +635,20 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:5: syntax error\n/source_0.sv:5: error: Invalid module item.\n/source_0.sv:6: syntax error\n/source_0.sv:6: error: Invalid module item.\n", + "detail": "system_functions::dimensions_resolves_procedural_parameters_and_indices at 1009:3: assert_eq local_parameter: expected 0x1, got 0x0", "expectation": "Simulation", - "name": "system_functions::isunbounded_preserves_parameter_values_and_result_type", - "phase": "compile", - "status": "compile_error", + "name": "system_functions::dimensions_resolves_procedural_parameters_and_indices", + "phase": "execute", + "status": "mismatch", "stronger_than_sv": false, "tag_reasons": {}, "tags": [] }, { "category": "Functions", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:3: sorry: unpacked array parameters are not supported yet.\n/source_0.sv:6: sorry: unpacked array parameters are not supported yet.\n", + "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:8: sorry: Subroutine ports with unpacked dimensions are not yet supported.\n/source_0.sv:4: sorry: Subroutine ports with unpacked dimensions are not yet supported.\n/source_0.sv:23: error: Array argument needs an array index here.\n/source_0.sv:24: error: Array argument needs an array index here.\n4 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "system_functions::isunbounded_reports_bounded_array_parameters", + "name": "system_functions::dimensions_resolves_procedural_scopes", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -642,26 +657,42 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:8: error: Unable to evaluate parameter Q value: $isunbounded()\n1 error(s) during elaboration.\n", + "detail": "Icarus build exit status: 134; see /build.log\n/source_0.sv:4: error: Type names are not valid expressions here.\n/source_0.sv:4: internal error: I do not know how to elaborate this expression. \n/source_0.sv:4: : Expression is: \n/source_0.sv:4: : Expression type: 10PETypename\n/source_0.sv:4: error: Type names are not valid expressions here.\n/source_0.sv:4: internal error: I do not know how to elaborate this expression. \n/source_0.sv:4: : Expression is: \n/source_0.sv:4: : Expression type: 10PETypename\n/source_0.sv:33: assert: netmisc.cc:1860: failed assertion packed_dims.size() == 1\nAborted (core dumped)\n", "expectation": "Simulation", - "name": "system_functions::isunbounded_reports_bounded_parameters", + "name": "system_functions::dimensions_resolves_types_and_constant_scopes", "phase": "compile", - "status": "compile_error", + "status": "compile_error" + }, + { + "category": "Functions", + "detail": "system_functions::dimensions_signing_conversions_are_vectors at 986:3: assert_eq signed_scalar: expected 0x1, got 0x0", + "expectation": "Simulation", + "name": "system_functions::dimensions_signing_conversions_are_vectors", + "phase": "execute", + "status": "mismatch", "stronger_than_sv": false, "tag_reasons": {}, "tags": [] }, { "category": "Functions", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:3: syntax error\nI give up.\n", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:3: sorry: Subroutine ports with unpacked dimensions are not yet supported.\n/source_0.sv:7: error: Packed array assignment pattern expects 8 element(s) in this context.\n/source_0.sv:7: : Found 2 element(s).\n2 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "system_functions::isunbounded_resolves_package_and_local_parameters", + "name": "system_functions::dimensions_types_function_pattern_arguments", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, "tag_reasons": {}, "tags": [] }, + { + "category": "Functions", + "detail": "system_functions::display_field_widths_expand_to_the_value at 245:3: expect_output: expected \":1234:11064:\\n\", got \":00001234:00000011064:\\n\"", + "expectation": "Simulation", + "name": "system_functions::display_field_widths_expand_to_the_value", + "phase": "execute", + "status": "mismatch" + }, { "category": "Functions", "detail": "Icarus build exit status: 134; see /build.log\n/source_0.sv:5: syntax error\n/source_0.sv:4: error: Syntax error defining function.\n/source_0.sv:9: syntax error\n/source_0.sv:9: Syntax in assignment statement l-value.\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Invalid module instantiation\n/source_0.sv:13: error: Invalid module item.\n/source_0.sv:14: syntax error\n/source_0.sv:14: error: Invalid module instantiation\n/source_0.sv:17: error: Invalid module item.\n/source_0.sv:18: syntax error\n/source_0.sv:18: error: Invalid module instantiation\n/source_0.sv:20: error: Invalid module item.\n/source_0.sv:2: assert: pform.cc:1478: failed assertion lexical_scope == cur_module\nAborted (core dumped)\n", @@ -675,9 +706,9 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 134; see /build.log\n/source_0.sv:8: syntax error\n/source_0.sv:8: error: Malformed statement\n/source_0.sv:16: syntax error\n/source_0.sv:16: error: Invalid module instantiation\n/source_0.sv:17: error: Invalid module instantiation\n/source_0.sv:18: error: Invalid module instantiation\n/source_0.sv:19: error: Invalid module instantiation\n/testbench.sv:3: error: Invalid module item.\n/source_0.sv:2: assert: pform.cc:1478: failed assertion lexical_scope == cur_module\nAborted (core dumped)\n", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:5: syntax error\n/source_0.sv:5: error: Invalid module item.\n", "expectation": "Simulation", - "name": "system_functions::isunbounded_restores_procedural_parameter_bindings", + "name": "system_functions::isunbounded_generate_guards_preserve_short_circuit_bounds", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -686,9 +717,9 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 134; see /build.log\n/source_0.sv:6: syntax error\n/source_0.sv:6: error: Malformed statement\n/source_0.sv:8: syntax error\n/source_0.sv:3: error: Syntax error defining function.\n/source_0.sv:2: assert: pform.cc:1478: failed assertion lexical_scope == cur_module\nAborted (core dumped)\n", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:2: syntax error\nI give up.\n", "expectation": "Simulation", - "name": "system_functions::isunbounded_restores_shadowed_function_arguments", + "name": "system_functions::isunbounded_handles_overrides_and_forwarding", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -697,9 +728,9 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:3: sorry: packed array parameters are not supported yet.\n", + "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:4: syntax error\n/source_0.sv:4: error: Invalid module item.\n/source_0.sv:23: syntax error\n/source_0.sv:22: error: Syntax error defining function.\n", "expectation": "Simulation", - "name": "system_functions::isunbounded_restores_procedural_parameter_type_metadata", + "name": "system_functions::isunbounded_preserves_lexical_scopes_and_short_circuits", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -708,9 +739,9 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:5: syntax error\n/source_0.sv:5: error: Invalid module item.\n", + "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:5: syntax error\n/source_0.sv:5: error: Invalid module item.\n/source_0.sv:6: syntax error\n/source_0.sv:6: error: Invalid module item.\n", "expectation": "Simulation", - "name": "system_functions::isunbounded_generate_guards_preserve_short_circuit_bounds", + "name": "system_functions::isunbounded_preserves_parameter_values_and_result_type", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -719,9 +750,9 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:5: error: Unable to evaluate parameter P value: bool<32>($timeprecision())\n/source_0.sv:4: error: Unable to evaluate parameter U value: bool<32>($timeunit())\n2 error(s) during elaboration.\n", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:3: sorry: unpacked array parameters are not supported yet.\n/source_0.sv:6: sorry: unpacked array parameters are not supported yet.\n", "expectation": "Simulation", - "name": "system_functions::timescale_queries_are_constant_in_unqualified_calls", + "name": "system_functions::isunbounded_reports_bounded_array_parameters", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -730,9 +761,9 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:8: syntax error\n/source_0.sv:8: error: Syntax error in continuous assignment\n", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:8: error: Unable to evaluate parameter Q value: $isunbounded()\n1 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "system_functions::timescale_queries_distinguish_unit_and_global_precision", + "name": "system_functions::isunbounded_reports_bounded_parameters", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -741,9 +772,9 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 9; see /build.log\n/source_0.sv:8: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:8: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:9: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:9: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:10: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:10: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:11: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:11: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:8: internal error: Failed to synthesize expression: (((((((($timeunit())==(32'b11111111111111111111111111111000))&&(($timeprecision())==(32'b11111111111111111111111111110101)))&&(($timeunit())==(32'b11111111111111111111111111111001)))&&(($timeprecision())==(32'b11111111111111111111111111110100)))&&(($timeunit())==(32'b11111111111111111111111111110111)))&&(($timeprecision())==(32'b11111111111111111111111111110100)))&&(($timeunit())==(32'b11111111111111111111111111111001)))&&(($timeprecision())==(32'b11111111111111111111111111110101))\n9 error(s) during elaboration.\n", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:3: syntax error\nI give up.\n", "expectation": "Simulation", - "name": "system_functions::timescale_queries_follow_partial_declarations_and_resetall", + "name": "system_functions::isunbounded_resolves_package_and_local_parameters", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -752,9 +783,9 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 12; see /build.log\n/source_0.sv:8: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:8: internal error: Failed to synthesize expression: \n/source_0.sv:9: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:9: internal error: Failed to synthesize expression: $timeprecision()\n/source_0.sv:10: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:10: internal error: Failed to synthesize expression: bool<32>((a) ? ($timeprecision()) : (celox_suite_tb.dut.unit_value()))\n/source_0.sv:11: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:11: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:12: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:13: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:14: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:11: internal error: Failed to synthesize expression: (((((($timeunit())==(32'b11111111111111111111111111110110))&&(($timeprecision())==(32'b11111111111111111111111111110010)))&&(1'd1))&&(($timeunit())<(32'b00000000000000000000000000000000)))&&((($timeunit())>>(32'b00000000000000000000000000000001))==(32'b01111111111111111111111111111011)))&&((($timeunit())>>>(32'b00000000000000000000000000000001))==(32'b11111111111111111111111111111011))\n12 error(s) during elaboration.\n", + "detail": "Icarus build exit status: 134; see /build.log\n/source_0.sv:8: syntax error\n/source_0.sv:8: error: Malformed statement\n/source_0.sv:16: syntax error\n/source_0.sv:16: error: Invalid module instantiation\n/source_0.sv:17: error: Invalid module instantiation\n/source_0.sv:18: error: Invalid module instantiation\n/source_0.sv:19: error: Invalid module instantiation\n/testbench.sv:3: error: Invalid module item.\n/source_0.sv:2: assert: pform.cc:1478: failed assertion lexical_scope == cur_module\nAborted (core dumped)\n", "expectation": "Simulation", - "name": "system_functions::timescale_queries_resolve_declarations_and_return_types", + "name": "system_functions::isunbounded_restores_procedural_parameter_bindings", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -763,9 +794,9 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 15; see /build.log\n/source_0.sv:4: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:4: internal error: Failed to synthesize expression: bool<32>($timeunit())\n/source_0.sv:5: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:5: internal error: Failed to synthesize expression: bool<32>($timeprecision())\n/source_0.sv:10: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:10: internal error: Failed to synthesize expression: bool<32>($timeunit())\n/source_0.sv:11: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:11: internal error: Failed to synthesize expression: bool<32>($timeprecision())\n/source_0.sv:16: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:16: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:17: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:17: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:18: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:18: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:16: internal error: Failed to synthesize expression: (((((($timeunit())==(32'b11111111111111111111111111111101))&&(($timeprecision())==(32'b11111111111111111111111111111010)))&&(($timeunit())==(32'b11111111111111111111111111111010)))&&(($timeprecision())==(32'b11111111111111111111111111110111)))&&(($timeunit())==(32'b11111111111111111111111111111000)))&&(($timeprecision())==(32'b11111111111111111111111111110110))\n15 error(s) during elaboration.\n", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:3: sorry: packed array parameters are not supported yet.\n", "expectation": "Simulation", - "name": "system_functions::timescale_queries_resolve_directives_and_hierarchy", + "name": "system_functions::isunbounded_restores_procedural_parameter_type_metadata", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -774,20 +805,20 @@ }, { "category": "Functions", - "detail": "native testbench failed: exit status: 6; see runtime.log and protocol.log\n/source_0.sv:5: Error: System task/function $timeprecision() is not defined by any module.\n/source_0.sv:9: Error: System task/function $timeunit() is not defined by any module.\n/source_0.sv:11: Error: System task/function $timeunit() is not defined by any module.\n/source_0.sv:12: Error: System task/function $timeprecision() is not defined by any module.\n/source_0.sv:15: Error: System task/function $timeunit() is not defined by any module.\n/source_0.sv:19: Error: System task/function $timeprecision() is not defined by any module.\n", + "detail": "Icarus build exit status: 134; see /build.log\n/source_0.sv:6: syntax error\n/source_0.sv:6: error: Malformed statement\n/source_0.sv:8: syntax error\n/source_0.sv:3: error: Syntax error defining function.\n/source_0.sv:2: assert: pform.cc:1478: failed assertion lexical_scope == cur_module\nAborted (core dumped)\n", "expectation": "Simulation", - "name": "system_functions::timescale_queries_preserve_procedural_and_package_scopes", - "phase": "execute", - "status": "runtime_error", + "name": "system_functions::isunbounded_restores_shadowed_function_arguments", + "phase": "compile", + "status": "compile_error", "stronger_than_sv": false, "tag_reasons": {}, "tags": [] }, { "category": "Functions", - "detail": "Icarus build exit status: 9; see /build.log\n/source_0.sv:3: error: A timeprecision is missing or is too large!\n/source_0.sv:4: error: Repeat timeprecision found and the initial timeprecision for this scope is missing.\n/source_0.sv:7: error: A timeprecision is missing or is too large!\n/source_0.sv:8: error: Repeat timeunit found and the initial timeunit for this scope is missing.\n/source_0.sv:14: error: A timeprecision is missing or is too large!\n/source_0.sv:15: error: Repeat timeprecision found and the initial timeprecision for this scope is missing.\n/source_0.sv:19: error: Repeat timeprecision found and the initial timeprecision for this scope is missing.\n/source_0.sv:21: syntax error\n/source_0.sv:20: error: Syntax error in continuous assignment\n", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Malformed statement\n", "expectation": "Simulation", - "name": "system_functions::timescale_queries_accept_separate_initial_declarations", + "name": "system_functions::printtimescale_displays_unit_and_global_precision", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -796,9 +827,9 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:13: syntax error\nI give up.\n", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:12: syntax error\n/source_0.sv:12: error: Malformed statement\n", "expectation": "Simulation", - "name": "system_functions::timescale_queries_keep_module_and_package_names_independent", + "name": "system_functions::printtimescale_preserves_package_subroutine_scope", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -818,9 +849,9 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:5: syntax error\nI give up.\n", + "detail": "Icarus build exit status: 8; see /build.log\n/source_0.sv:2: error: Invalid timeunit constant (1st digit).\n/source_0.sv:2: error: Invalid timeprecision constant (1st digit).\n/source_0.sv:4: error: Invalid timeunit constant (1st digit).\n/source_0.sv:4: error: Invalid timeprecision constant (1st digit).\n/source_0.sv:9: error: Invalid timeunit constant (1st digit).\n/source_0.sv:9: error: Invalid timeprecision constant (1st digit).\n/source_0.sv:13: error: Invalid timeunit constant (1st digit).\n/source_0.sv:13: error: Invalid timeprecision constant (1st digit).\n", "expectation": "Simulation", - "name": "system_functions::timescale_queries_resolve_packages_with_instantiated_namesakes", + "name": "system_functions::timescale_queries_accept_leading_zero_magnitudes", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -829,9 +860,9 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 12; see /build.log\n/source_0.sv:11: syntax error\n/source_0.sv:11: error: Malformed statement\n/source_0.sv:12: syntax error\n/source_0.sv:12: error: Malformed statement\n/source_0.sv:13: sorry: modport task/function ports are not yet supported.\n/source_0.sv:13: sorry: modport task/function ports are not yet supported.\n/source_1.sv:2: error: Repeat timeunit does not match the initial timeunit for this scope.\n/source_1.sv:2: error: Repeat timeprecision does not match the initial timeprecision for this scope.\n/source_1.sv:3: syntax error\n/source_1.sv:3: Errors in port declarations.\n/source_1.sv:16: syntax error\n/source_1.sv:15: error: Syntax error in continuous assignment\n", + "detail": "Icarus build exit status: 9; see /build.log\n/source_0.sv:3: error: A timeprecision is missing or is too large!\n/source_0.sv:4: error: Repeat timeprecision found and the initial timeprecision for this scope is missing.\n/source_0.sv:7: error: A timeprecision is missing or is too large!\n/source_0.sv:8: error: Repeat timeunit found and the initial timeunit for this scope is missing.\n/source_0.sv:14: error: A timeprecision is missing or is too large!\n/source_0.sv:15: error: Repeat timeprecision found and the initial timeprecision for this scope is missing.\n/source_0.sv:19: error: Repeat timeprecision found and the initial timeprecision for this scope is missing.\n/source_0.sv:21: syntax error\n/source_0.sv:20: error: Syntax error in continuous assignment\n", "expectation": "Simulation", - "name": "system_functions::timescale_queries_preserve_interface_scopes_when_flattened", + "name": "system_functions::timescale_queries_accept_separate_initial_declarations", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -840,9 +871,9 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 8; see /build.log\n/source_0.sv:2: error: Invalid timeunit constant (1st digit).\n/source_0.sv:2: error: Invalid timeprecision constant (1st digit).\n/source_0.sv:4: error: Invalid timeunit constant (1st digit).\n/source_0.sv:4: error: Invalid timeprecision constant (1st digit).\n/source_0.sv:9: error: Invalid timeunit constant (1st digit).\n/source_0.sv:9: error: Invalid timeprecision constant (1st digit).\n/source_0.sv:13: error: Invalid timeunit constant (1st digit).\n/source_0.sv:13: error: Invalid timeprecision constant (1st digit).\n", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:5: error: Unable to evaluate parameter P value: bool<32>($timeprecision())\n/source_0.sv:4: error: Unable to evaluate parameter U value: bool<32>($timeunit())\n2 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "system_functions::timescale_queries_accept_leading_zero_magnitudes", + "name": "system_functions::timescale_queries_are_constant_in_unqualified_calls", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -851,9 +882,9 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:6: error: Unable to evaluate parameter P value: bool<32>($timeprecision())\n/source_0.sv:5: error: Unable to evaluate parameter U value: bool<32>($timeunit())\n/source_0.sv:6: error: Unable to evaluate parameter P value: bool<32>($timeprecision())\n/source_0.sv:5: error: Unable to evaluate parameter U value: bool<32>($timeunit())\n4 error(s) during elaboration.\n", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:8: syntax error\n/source_0.sv:8: error: Syntax error in continuous assignment\n", "expectation": "Simulation", - "name": "system_functions::timescale_queries_survive_type_parameter_specialization", + "name": "system_functions::timescale_queries_distinguish_unit_and_global_precision", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -862,28 +893,20 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:9: syntax error\n/source_0.sv:9: Errors in port declarations.\n/source_0.sv:14: syntax error\n/source_0.sv:14: Errors in port declarations.\n", + "detail": "Icarus build exit status: 9; see /build.log\n/source_0.sv:8: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:8: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:9: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:9: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:10: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:10: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:11: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:11: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:8: internal error: Failed to synthesize expression: (((((((($timeunit())==(32'b11111111111111111111111111111000))&&(($timeprecision())==(32'b11111111111111111111111111110101)))&&(($timeunit())==(32'b11111111111111111111111111111001)))&&(($timeprecision())==(32'b11111111111111111111111111110100)))&&(($timeunit())==(32'b11111111111111111111111111110111)))&&(($timeprecision())==(32'b11111111111111111111111111110100)))&&(($timeunit())==(32'b11111111111111111111111111111001)))&&(($timeprecision())==(32'b11111111111111111111111111110101))\n9 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "system_functions::timescale_queries_resolve_interface_instances_and_ports", + "name": "system_functions::timescale_queries_follow_partial_declarations_and_resetall", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, "tag_reasons": {}, "tags": [] }, - { - "category": "Arrays", - "detail": "Icarus build exit status: 18; see /build.log\n/source_0.sv:13: syntax error\n/source_0.sv:13: Syntax in assignment statement l-value.\n/source_0.sv:17: syntax error\n/source_0.sv:17: Syntax in assignment statement l-value.\n/source_0.sv:19: syntax error\n/source_0.sv:19: error: Syntax error in continuous assignment\n/source_0.sv:20: syntax error\n/source_0.sv:20: error: Syntax error in continuous assignment\n/source_0.sv:21: syntax error\n/source_0.sv:21: error: Syntax error in continuous assignment\n/source_0.sv:22: syntax error\n/source_0.sv:22: error: Syntax error in continuous assignment\n/source_0.sv:23: syntax error\n/source_0.sv:23: error: Syntax error in continuous assignment\n/source_0.sv:24: syntax error\n/source_0.sv:24: error: Syntax error in continuous assignment\n/source_0.sv:25: syntax error\n/source_0.sv:25: error: Syntax error in continuous assignment\n", - "expectation": "Simulation", - "name": "indexed_select::constant_part_select_indices_of_concatenations", - "phase": "compile", - "status": "compile_error" - }, { "category": "Functions", - "detail": "Icarus build exit status: 8; see /build.log\n/source_0.sv:23: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:23: internal error: Failed to synthesize expression: bool<32>($timeunit())\n/source_0.sv:24: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:24: internal error: Failed to synthesize expression: bool<32>($timeprecision())\n/source_0.sv:25: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:25: internal error: Failed to synthesize expression: bool<32>($timeunit())\n/source_0.sv:26: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:26: internal error: Failed to synthesize expression: bool<32>($timeprecision())\n/source_0.sv:27: warning: always_comb process has no sensitivities.\n/source_0.sv:28: warning: System task ($timeunit) cannot be synthesized in an always_comb process.\n8 error(s) during elaboration.\n", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:13: syntax error\nI give up.\n", "expectation": "Simulation", - "name": "system_functions::timescale_queries_resolve_hierarchical_interface_instances", + "name": "system_functions::timescale_queries_keep_module_and_package_names_independent", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -891,10 +914,10 @@ "tags": [] }, { - "category": "Hierarchy", - "detail": "Icarus build exit status: 7; see /build.log\n/source_0.sv:2: sorry: unpacked array parameters are not supported yet.\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Syntax error in parameter value assignment list.\n/source_0.sv:10: error: Invalid module instantiation\n/source_0.sv:11: syntax error\n/source_0.sv:11: error: Syntax error in parameter value assignment list.\n/source_0.sv:11: error: Invalid module instantiation\n", + "category": "Functions", + "detail": "Icarus build exit status: 12; see /build.log\n/source_0.sv:11: syntax error\n/source_0.sv:11: error: Malformed statement\n/source_0.sv:12: syntax error\n/source_0.sv:12: error: Malformed statement\n/source_0.sv:13: sorry: modport task/function ports are not yet supported.\n/source_0.sv:13: sorry: modport task/function ports are not yet supported.\n/source_1.sv:2: error: Repeat timeunit does not match the initial timeunit for this scope.\n/source_1.sv:2: error: Repeat timeprecision does not match the initial timeprecision for this scope.\n/source_1.sv:3: syntax error\n/source_1.sv:3: Errors in port declarations.\n/source_1.sv:16: syntax error\n/source_1.sv:15: error: Syntax error in continuous assignment\n", "expectation": "Simulation", - "name": "hierarchy::parameter_patterns_bind_caller_types", + "name": "system_functions::timescale_queries_preserve_interface_scopes_when_flattened", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -902,21 +925,21 @@ "tags": [] }, { - "category": "Hierarchy", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:2: syntax error\nI give up.\n", + "category": "Functions", + "detail": "native testbench failed: exit status: 6; see runtime.log and protocol.log\n/source_0.sv:5: Error: System task/function $timeprecision() is not defined by any module.\n/source_0.sv:9: Error: System task/function $timeunit() is not defined by any module.\n/source_0.sv:11: Error: System task/function $timeunit() is not defined by any module.\n/source_0.sv:12: Error: System task/function $timeprecision() is not defined by any module.\n/source_0.sv:15: Error: System task/function $timeunit() is not defined by any module.\n/source_0.sv:19: Error: System task/function $timeprecision() is not defined by any module.\n", "expectation": "Simulation", - "name": "hierarchy::parameter_patterns_bind_nested_caller_types", - "phase": "compile", - "status": "compile_error", + "name": "system_functions::timescale_queries_preserve_procedural_and_package_scopes", + "phase": "execute", + "status": "runtime_error", "stronger_than_sv": false, "tag_reasons": {}, "tags": [] }, { - "category": "Hierarchy", - "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:2: sorry: unpacked array parameters are not supported yet.\n/source_0.sv:7: syntax error\nI give up.\n", + "category": "Functions", + "detail": "Icarus build exit status: 12; see /build.log\n/source_0.sv:8: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:8: internal error: Failed to synthesize expression: \n/source_0.sv:9: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:9: internal error: Failed to synthesize expression: $timeprecision()\n/source_0.sv:10: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:10: internal error: Failed to synthesize expression: bool<32>((a) ? ($timeprecision()) : (celox_suite_tb.dut.unit_value()))\n/source_0.sv:11: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:11: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:12: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:13: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:14: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:11: internal error: Failed to synthesize expression: (((((($timeunit())==(32'b11111111111111111111111111110110))&&(($timeprecision())==(32'b11111111111111111111111111110010)))&&(1'd1))&&(($timeunit())<(32'b00000000000000000000000000000000)))&&((($timeunit())>>(32'b00000000000000000000000000000001))==(32'b01111111111111111111111111111011)))&&((($timeunit())>>>(32'b00000000000000000000000000000001))==(32'b11111111111111111111111111111011))\n12 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "hierarchy::parameter_patterns_keep_fill_and_arithmetic_context", + "name": "system_functions::timescale_queries_resolve_declarations_and_return_types", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -924,10 +947,10 @@ "tags": [] }, { - "category": "Hierarchy", - "detail": "Icarus build exit status: 7; see /build.log\n/source_0.sv:2: sorry: unpacked array parameters are not supported yet.\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Syntax error in parameter value assignment list.\n/source_0.sv:7: error: Invalid module instantiation\n/source_0.sv:8: syntax error\n/source_0.sv:8: error: Syntax error in parameter value assignment list.\n/source_0.sv:8: error: Invalid module instantiation\n", + "category": "Functions", + "detail": "Icarus build exit status: 15; see /build.log\n/source_0.sv:4: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:4: internal error: Failed to synthesize expression: bool<32>($timeunit())\n/source_0.sv:5: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:5: internal error: Failed to synthesize expression: bool<32>($timeprecision())\n/source_0.sv:10: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:10: internal error: Failed to synthesize expression: bool<32>($timeunit())\n/source_0.sv:11: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:11: internal error: Failed to synthesize expression: bool<32>($timeprecision())\n/source_0.sv:16: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:16: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:17: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:17: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:18: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:18: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:16: internal error: Failed to synthesize expression: (((((($timeunit())==(32'b11111111111111111111111111111101))&&(($timeprecision())==(32'b11111111111111111111111111111010)))&&(($timeunit())==(32'b11111111111111111111111111111010)))&&(($timeprecision())==(32'b11111111111111111111111111110111)))&&(($timeunit())==(32'b11111111111111111111111111111000)))&&(($timeprecision())==(32'b11111111111111111111111111110110))\n15 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "hierarchy::parameter_patterns_keep_unknown_fill", + "name": "system_functions::timescale_queries_resolve_directives_and_hierarchy", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -936,9 +959,9 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Malformed statement\n", + "detail": "Icarus build exit status: 8; see /build.log\n/source_0.sv:23: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:23: internal error: Failed to synthesize expression: bool<32>($timeunit())\n/source_0.sv:24: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:24: internal error: Failed to synthesize expression: bool<32>($timeprecision())\n/source_0.sv:25: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:25: internal error: Failed to synthesize expression: bool<32>($timeunit())\n/source_0.sv:26: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:26: internal error: Failed to synthesize expression: bool<32>($timeprecision())\n/source_0.sv:27: warning: always_comb process has no sensitivities.\n/source_0.sv:28: warning: System task ($timeunit) cannot be synthesized in an always_comb process.\n8 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "system_functions::printtimescale_displays_unit_and_global_precision", + "name": "system_functions::timescale_queries_resolve_hierarchical_interface_instances", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -947,9 +970,9 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:12: syntax error\n/source_0.sv:12: error: Malformed statement\n", + "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:9: syntax error\n/source_0.sv:9: Errors in port declarations.\n/source_0.sv:14: syntax error\n/source_0.sv:14: Errors in port declarations.\n", "expectation": "Simulation", - "name": "system_functions::printtimescale_preserves_package_subroutine_scope", + "name": "system_functions::timescale_queries_resolve_interface_instances_and_ports", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -957,10 +980,10 @@ "tags": [] }, { - "category": "Hierarchy", - "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:2: sorry: unpacked array parameters are not supported yet.\n", + "category": "Functions", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:5: syntax error\nI give up.\n", "expectation": "Simulation", - "name": "hierarchy::parameter_patterns_evaluate_caller_constant_functions", + "name": "system_functions::timescale_queries_resolve_packages_with_instantiated_namesakes", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -968,10 +991,10 @@ "tags": [] }, { - "category": "Hierarchy", - "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:3: sorry: unpacked array parameters are not supported yet.\n", + "category": "Functions", + "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:6: error: Unable to evaluate parameter P value: bool<32>($timeprecision())\n/source_0.sv:5: error: Unable to evaluate parameter U value: bool<32>($timeunit())\n/source_0.sv:6: error: Unable to evaluate parameter P value: bool<32>($timeprecision())\n/source_0.sv:5: error: Unable to evaluate parameter U value: bool<32>($timeunit())\n4 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "hierarchy::parameter_patterns_override_body_declarations", + "name": "system_functions::timescale_queries_survive_type_parameter_specialization", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -979,10 +1002,10 @@ "tags": [] }, { - "category": "Combinational", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:4: error: A reference to a net or variable (`a') is not allowed in a constant expression.\n/source_0.sv:4: error: Unable to evaluate a as a port default expression.\n2 error(s) during elaboration.\n", + "category": "Functions", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:7: error: Function celox_suite_tb.dut.g port x is not an input port.\n/source_0.sv:7: : Function arguments must be input ports.\n/source_0.sv:12: error: Function celox_suite_tb.dut.update port x is not an input port.\n/source_0.sv:12: : Function arguments must be input ports.\n2 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "synthesizable::named_calls_preserve_defaults_and_declaration_scope", + "name": "system_functions::unpacked_dimensions_accepts_function_result_arguments", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -1038,6 +1061,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Functions", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:3: syntax error\nI give up.\n", + "expectation": "Simulation", + "name": "system_functions::unpacked_dimensions_publishes_dependent_array_parameters", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Functions", "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:3: sorry: unpacked array parameters are not supported yet.\n", @@ -1091,70 +1125,44 @@ "tags": [] }, { - "category": "Functions", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:7: error: Function celox_suite_tb.dut.g port x is not an input port.\n/source_0.sv:7: : Function arguments must be input ports.\n/source_0.sv:12: error: Function celox_suite_tb.dut.update port x is not an input port.\n/source_0.sv:12: : Function arguments must be input ports.\n2 error(s) during elaboration.\n", + "category": "Sequential", + "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:6: sorry: modport task/function ports are not yet supported.\n/source_0.sv:8: syntax error\n/source_0.sv:8: Errors in port declarations.\n", "expectation": "Simulation", - "name": "system_functions::unpacked_dimensions_accepts_function_result_arguments", + "name": "timing::interface_modport_methods_keep_setup_edges", "phase": "compile", - "status": "compile_error", - "stronger_than_sv": false, - "tag_reasons": {}, - "tags": [] + "status": "compile_error" }, { - "category": "Functions", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:3: syntax error\nI give up.\n", + "category": "Types", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:7: sorry: packed array parameters are not supported yet.\n", "expectation": "Simulation", - "name": "system_functions::unpacked_dimensions_publishes_dependent_array_parameters", + "name": "types::packed_parameters_of_signed_named_types_have_signed_elements", "phase": "compile", - "status": "compile_error", - "stronger_than_sv": false, - "tag_reasons": {}, - "tags": [] + "status": "compile_error" }, { - "category": "Hierarchy", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:5: syntax error\nI give up.\n", + "category": "Types", + "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:3: sorry: Subroutine ports with unpacked dimensions are not yet supported.\n/source_0.sv:10: error: Array v needs an array index here.\n/source_0.sv:11: error: Array v needs an array index here.\n/source_0.sv:8: sorry: constant selects in always_* processes are not fully supported (the process will be sensitive to all bits in 'd[15:0]').\n/source_0.sv:9: sorry: constant selects in always_* processes are not fully supported (the process will be sensitive to all bits in 'd[15:0]').\n3 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "hierarchy::parameter_patterns_transfer_packed_values", + "name": "types::passes_unpacked_arguments_of_equivalent_element_types", "phase": "compile", - "status": "compile_error", - "stronger_than_sv": false, - "tag_reasons": {}, - "tags": [] + "status": "compile_error" }, { - "category": "Hierarchy", - "detail": "Icarus build exit status: 9; see /build.log\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Syntax error in parameter value assignment list.\n/source_0.sv:10: error: Invalid module instantiation\n/source_0.sv:11: syntax error\n/source_0.sv:11: error: Syntax error in parameter value assignment list.\n/source_0.sv:11: error: Invalid module instantiation\n/source_0.sv:12: syntax error\n/source_0.sv:12: error: Syntax error in parameter value assignment list.\n/source_0.sv:12: error: Invalid module instantiation\n", - "expectation": "Simulation", - "name": "hierarchy::parameter_patterns_override_scalar_defaults", + "category": "Types", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:7: sorry: Procedural assignment of array or array slice is not yet supported.\n/source_0.sv:7: sorry: Procedural assignment of array or array slice is not yet supported.\n2 error(s) during elaboration.\n", + "expectation": "CompilationError", + "name": "types::rejects_assignment_pattern_item_of_a_narrower_array_type", "phase": "compile", - "status": "compile_error", - "stronger_than_sv": false, - "tag_reasons": {}, - "tags": [] + "status": "compile_error" }, { - "category": "Hierarchy", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:5: syntax error\nI give up.\n", - "expectation": "Simulation", - "name": "hierarchy::parameter_patterns_preserve_packed_member_states", + "category": "Types", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:3: sorry: Subroutine ports with unpacked dimensions are not yet supported.\n/source_0.sv:10: error: Array narrow needs an array index here.\n/source_0.sv:7: warning: always_comb process has no sensitivities.\n2 error(s) during elaboration.\n", + "expectation": "CompilationError", + "name": "types::rejects_unpacked_argument_of_a_wider_element_type", "phase": "compile", - "status": "compile_error", - "stronger_than_sv": false, - "tag_reasons": {}, - "tags": [] - }, - { - "category": "Combinational", - "detail": "synthesizable::named_calls_in_constant_contexts at 686:3: assert_eq query: expected 0x10, got 0x0", - "expectation": "Simulation", - "name": "synthesizable::named_calls_in_constant_contexts", - "phase": "execute", - "status": "mismatch", - "stronger_than_sv": false, - "tag_reasons": {}, - "tags": [] + "status": "compile_error" } ] } diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index e86a8f5f54a..b0422bedb5b 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -177,3 +177,7 @@ sv_backends! { @case "timing::finite_active_feedback_preserves_convergence"; } } + +sv_backends! { fn interface_modport_methods_keep_setup_edges(sim) { @case "timing::interface_modport_methods_keep_setup_edges"; } } + +sv_backends! { fn inactive_phases_preserve_cross_instance_edges(sim) { @case "timing::inactive_phases_preserve_cross_instance_edges"; } } From 91c2b8970ea5a63264f71aed3235db66103e55f7 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 00:02:38 +0900 Subject: [PATCH 43/75] test(suite): retain reviewed interface evidence formatting --- .../src/sv/cases/timing.vtest | 13 - .../verification/sv/limitations/icarus.json | 690 +++++++++--------- 2 files changed, 345 insertions(+), 358 deletions(-) diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 5dc3f476c2a..9bc75dd8472 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -961,16 +961,3 @@ endmodule"#) endmodule "#) (top Top)(set v 2)(set clk 1)(run_until 0)(assert_eq q 10)) - -(case inactive_phases_preserve_cross_instance_edges - (source "inactive-phases.sv" #" - module Child(output bit[1:0] q); - initial begin #1;q[0]=1;end - initial begin #1;#0;q[1]=1;end - endmodule - module Top(output bit[7:0] seen); - wire[1:0] q;Child u(.q(q)); - initial forever begin @(q[0]^q[1]);seen=seen+1;end - endmodule - "#) - (top Top)(run_until 1)(assert_eq seen 2)) diff --git a/crates/celox-test-suite/verification/sv/limitations/icarus.json b/crates/celox-test-suite/verification/sv/limitations/icarus.json index 6c4678aff9a..2b215ffadff 100644 --- a/crates/celox-test-suite/verification/sv/limitations/icarus.json +++ b/crates/celox-test-suite/verification/sv/limitations/icarus.json @@ -96,173 +96,194 @@ "status": "mismatch" }, { - "category": "Hierarchy", - "detail": "Icarus build exit status: 7; see /build.log\n/source_0.sv:2: sorry: unpacked array parameters are not supported yet.\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Syntax error in parameter value assignment list.\n/source_0.sv:10: error: Invalid module instantiation\n/source_0.sv:11: syntax error\n/source_0.sv:11: error: Syntax error in parameter value assignment list.\n/source_0.sv:11: error: Invalid module instantiation\n", + "category": "Arrays", + "detail": "Icarus build exit status: 12; see /build.log\n/source_0.sv:5: syntax error\n/source_0.sv:5: error: Invalid module item.\n/source_0.sv:6: syntax error\n/source_0.sv:6: error: Syntax error in continuous assignment\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Syntax error in continuous assignment\n/source_0.sv:8: syntax error\n/source_0.sv:8: error: Syntax error in continuous assignment\n/source_0.sv:9: syntax error\n/source_0.sv:9: error: Syntax error in continuous assignment\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Syntax error in continuous assignment\n", "expectation": "Simulation", - "name": "hierarchy::parameter_patterns_bind_caller_types", + "name": "indexed_select::indexed_constants_lower_selected_concatenations", "phase": "compile", - "status": "compile_error", - "stronger_than_sv": false, - "tag_reasons": {}, - "tags": [] + "status": "compile_error" }, { - "category": "Hierarchy", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:2: syntax error\nI give up.\n", + "category": "Arrays", + "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:9: syntax error\n/source_0.sv:9: error: Syntax error in continuous assignment\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Syntax error in continuous assignment\n", "expectation": "Simulation", - "name": "hierarchy::parameter_patterns_bind_nested_caller_types", + "name": "indexed_select::indexed_constants_work_in_ordinary_selection_indices", "phase": "compile", - "status": "compile_error", - "stronger_than_sv": false, - "tag_reasons": {}, - "tags": [] + "status": "compile_error" }, { - "category": "Hierarchy", - "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:2: sorry: unpacked array parameters are not supported yet.\n", + "category": "Arrays", + "detail": "Icarus build exit status: 8; see /build.log\n/source_0.sv:4: syntax error\n/source_0.sv:4: error: Syntax error in continuous assignment\n/source_0.sv:5: syntax error\n/source_0.sv:5: error: Syntax error in continuous assignment\n/source_0.sv:6: syntax error\n/source_0.sv:6: error: Syntax error in continuous assignment\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Syntax error in continuous assignment\n", "expectation": "Simulation", - "name": "hierarchy::parameter_patterns_evaluate_caller_constant_functions", + "name": "indexed_select::indexed_runtime_replications_preserve_attached_selections", "phase": "compile", - "status": "compile_error", - "stronger_than_sv": false, - "tag_reasons": {}, - "tags": [] + "status": "compile_error" }, { - "category": "Hierarchy", - "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:2: sorry: unpacked array parameters are not supported yet.\n/source_0.sv:7: syntax error\nI give up.\n", + "category": "Arrays", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:6: syntax error\n/source_0.sv:6: error: Syntax error in continuous assignment\n", "expectation": "Simulation", - "name": "hierarchy::parameter_patterns_keep_fill_and_arithmetic_context", + "name": "indexed_select::indexed_select_multidimensional_packed_reads", "phase": "compile", - "status": "compile_error", - "stronger_than_sv": false, - "tag_reasons": {}, - "tags": [] + "status": "compile_error" }, { - "category": "Hierarchy", - "detail": "Icarus build exit status: 7; see /build.log\n/source_0.sv:2: sorry: unpacked array parameters are not supported yet.\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Syntax error in parameter value assignment list.\n/source_0.sv:7: error: Invalid module instantiation\n/source_0.sv:8: syntax error\n/source_0.sv:8: error: Syntax error in parameter value assignment list.\n/source_0.sv:8: error: Invalid module instantiation\n", + "category": "Arrays", + "detail": "Icarus build exit status: 139; see /build.log\nSegmentation fault (core dumped)\n", "expectation": "Simulation", - "name": "hierarchy::parameter_patterns_keep_unknown_fill", + "name": "indexed_select::indexed_select_parameterized_generate_and_ff", "phase": "compile", - "status": "compile_error", - "stronger_than_sv": false, - "tag_reasons": {}, - "tags": [] + "status": "compile_error" }, { - "category": "Hierarchy", - "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:3: sorry: unpacked array parameters are not supported yet.\n", + "category": "Arrays", + "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:2: sorry: packed array parameters are not supported yet.\n/source_0.sv:3: sorry: packed array parameters are not supported yet.\n/source_0.sv:4: sorry: packed array parameters are not supported yet.\n", "expectation": "Simulation", - "name": "hierarchy::parameter_patterns_override_body_declarations", + "name": "indexed_select::indexed_size_queries_preserve_parameter_dimensions", "phase": "compile", - "status": "compile_error", - "stronger_than_sv": false, - "tag_reasons": {}, - "tags": [] + "status": "compile_error" }, { - "category": "Hierarchy", - "detail": "Icarus build exit status: 9; see /build.log\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Syntax error in parameter value assignment list.\n/source_0.sv:10: error: Invalid module instantiation\n/source_0.sv:11: syntax error\n/source_0.sv:11: error: Syntax error in parameter value assignment list.\n/source_0.sv:11: error: Invalid module instantiation\n/source_0.sv:12: syntax error\n/source_0.sv:12: error: Syntax error in parameter value assignment list.\n/source_0.sv:12: error: Invalid module instantiation\n", + "category": "Operators", + "detail": "operators::propagates_child_input_width_into_connection_expressions at 1116:3: assert_eq y: expected 0x100, got 0x0", "expectation": "Simulation", - "name": "hierarchy::parameter_patterns_override_scalar_defaults", + "name": "operators::propagates_child_input_width_into_connection_expressions", + "phase": "execute", + "status": "mismatch" + }, + { + "category": "ControlFlow", + "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:6: sorry: unpacked array parameters are not supported yet.\n/source_0.sv:7: sorry: unpacked array parameters are not supported yet.\n/source_0.sv:8: syntax error\n/source_0.sv:8: error: Invalid module item.\n", + "expectation": "Simulation", + "name": "procedural::aggregate_parameters_are_constant_tables", "phase": "compile", - "status": "compile_error", - "stronger_than_sv": false, - "tag_reasons": {}, - "tags": [] + "status": "compile_error" }, { - "category": "Hierarchy", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:5: syntax error\nI give up.\n", + "category": "ControlFlow", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:4: error: Function celox_suite_tb.dut.pick port y is not an input port.\n/source_0.sv:4: : Function arguments must be input ports.\n1 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "hierarchy::parameter_patterns_preserve_packed_member_states", + "name": "procedural::select_indices_call_functions", "phase": "compile", - "status": "compile_error", - "stronger_than_sv": false, - "tag_reasons": {}, - "tags": [] + "status": "compile_error" }, { - "category": "Hierarchy", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:5: syntax error\nI give up.\n", + "category": "Regression", + "detail": "Icarus build exit status: 139; see /build.log\nSegmentation fault (core dumped)\n", "expectation": "Simulation", - "name": "hierarchy::parameter_patterns_transfer_packed_values", + "name": "review_regressions::preserves_size_cast_dimensions_in_declarations_and_selections", "phase": "compile", - "status": "compile_error", - "stronger_than_sv": false, - "tag_reasons": {}, - "tags": [] + "status": "compile_error" }, { - "category": "Arrays", - "detail": "Icarus build exit status: 18; see /build.log\n/source_0.sv:13: syntax error\n/source_0.sv:13: Syntax in assignment statement l-value.\n/source_0.sv:17: syntax error\n/source_0.sv:17: Syntax in assignment statement l-value.\n/source_0.sv:19: syntax error\n/source_0.sv:19: error: Syntax error in continuous assignment\n/source_0.sv:20: syntax error\n/source_0.sv:20: error: Syntax error in continuous assignment\n/source_0.sv:21: syntax error\n/source_0.sv:21: error: Syntax error in continuous assignment\n/source_0.sv:22: syntax error\n/source_0.sv:22: error: Syntax error in continuous assignment\n/source_0.sv:23: syntax error\n/source_0.sv:23: error: Syntax error in continuous assignment\n/source_0.sv:24: syntax error\n/source_0.sv:24: error: Syntax error in continuous assignment\n/source_0.sv:25: syntax error\n/source_0.sv:25: error: Syntax error in continuous assignment\n", + "category": "Regression", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:33: error: Cast size expression must be constant and greater than zero.\n1 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "indexed_select::constant_part_select_indices_of_concatenations", + "name": "review_regressions::preserves_use_site_dimensions_in_function_alias_types", "phase": "compile", "status": "compile_error" }, { - "category": "Arrays", - "detail": "Icarus build exit status: 12; see /build.log\n/source_0.sv:5: syntax error\n/source_0.sv:5: error: Invalid module item.\n/source_0.sv:6: syntax error\n/source_0.sv:6: error: Syntax error in continuous assignment\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Syntax error in continuous assignment\n/source_0.sv:8: syntax error\n/source_0.sv:8: error: Syntax error in continuous assignment\n/source_0.sv:9: syntax error\n/source_0.sv:9: error: Syntax error in continuous assignment\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Syntax error in continuous assignment\n", + "category": "Combinational", + "detail": "Icarus build exit status: 7; see /build.log\n/source_0.sv:13: error: Function celox_suite_tb.dut.bump port v is not an input port.\n/source_0.sv:13: : Function arguments must be input ports.\n/source_0.sv:9: error: Function celox_suite_tb.dut.clamp port l is not an input port.\n/source_0.sv:9: : Function arguments must be input ports.\n/source_0.sv:9: error: Function celox_suite_tb.dut.clamp port h is not an input port.\n/source_0.sv:9: : Function arguments must be input ports.\n/source_0.sv:16: error: Function celox_suite_tb.dut.invert port z is not an input port.\n/source_0.sv:16: : Function arguments must be input ports.\n/source_0.sv:19: error: Function celox_suite_tb.dut.shift port z is not an input port.\n/source_0.sv:19: : Function arguments must be input ports.\n/source_0.sv:5: error: Function celox_suite_tb.dut.sum_diff port s is not an input port.\n/source_0.sv:5: : Function arguments must be input ports.\n/source_0.sv:5: error: Function celox_suite_tb.dut.sum_diff port d is not an input port.\n/source_0.sv:5: : Function arguments must be input ports.\n/source_0.sv:29: sorry: constant selects in always_* processes are not fully supported (the process will be sensitive to all bits in 'a[7:0]').\n7 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "indexed_select::indexed_constants_lower_selected_concatenations", + "name": "synthesizable::function_output_and_inout_arguments_are_written_back", "phase": "compile", "status": "compile_error" }, { - "category": "Arrays", - "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:9: syntax error\n/source_0.sv:9: error: Syntax error in continuous assignment\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Syntax error in continuous assignment\n", + "category": "Combinational", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:6: vvp.tgt error: uwire \"lanes\" must have a single driver, found (4).\nerror: Code generation had 1 error(s).\n", "expectation": "Simulation", - "name": "indexed_select::indexed_constants_work_in_ordinary_selection_indices", + "name": "synthesizable::instance_array_unpacked_connection_ascending_to_descending", "phase": "compile", "status": "compile_error" }, { - "category": "Arrays", - "detail": "Icarus build exit status: 8; see /build.log\n/source_0.sv:4: syntax error\n/source_0.sv:4: error: Syntax error in continuous assignment\n/source_0.sv:5: syntax error\n/source_0.sv:5: error: Syntax error in continuous assignment\n/source_0.sv:6: syntax error\n/source_0.sv:6: error: Syntax error in continuous assignment\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Syntax error in continuous assignment\n", + "category": "Combinational", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:6: vvp.tgt error: uwire \"lanes\" must have a single driver, found (4).\nerror: Code generation had 1 error(s).\n", "expectation": "Simulation", - "name": "indexed_select::indexed_runtime_replications_preserve_attached_selections", + "name": "synthesizable::instance_array_unpacked_connection_descending_to_ascending", "phase": "compile", "status": "compile_error" }, { - "category": "Arrays", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:6: syntax error\n/source_0.sv:6: error: Syntax error in continuous assignment\n", + "category": "Combinational", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:6: vvp.tgt error: uwire \"lanes\" must have a single driver, found (4).\nerror: Code generation had 1 error(s).\n", "expectation": "Simulation", - "name": "indexed_select::indexed_select_multidimensional_packed_reads", + "name": "synthesizable::instance_array_unpacked_connection_descending_to_descending", "phase": "compile", "status": "compile_error" }, { - "category": "Arrays", - "detail": "Icarus build exit status: 139; see /build.log\nSegmentation fault (core dumped)\n", + "category": "Combinational", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:6: vvp.tgt error: uwire \"lanes\" must have a single driver, found (4).\nerror: Code generation had 1 error(s).\n", "expectation": "Simulation", - "name": "indexed_select::indexed_select_parameterized_generate_and_ff", + "name": "synthesizable::instance_array_unpacked_connection_offset_ranges", "phase": "compile", "status": "compile_error" }, { - "category": "Arrays", - "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:2: sorry: packed array parameters are not supported yet.\n/source_0.sv:3: sorry: packed array parameters are not supported yet.\n/source_0.sv:4: sorry: packed array parameters are not supported yet.\n", + "category": "Combinational", + "detail": "invalid design was accepted: synthesizable::instance_arrays_reject_a_fill_literal_tie_off", + "expectation": "CompilationError", + "name": "synthesizable::instance_arrays_reject_a_fill_literal_tie_off", + "phase": "execute", + "status": "unexpected_accept" + }, + { + "category": "Combinational", + "detail": "Icarus build exit status: 6; see /build.log\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Syntax error in continuous assignment\n/source_0.sv:9: syntax error\n/source_0.sv:9: error: Malformed statement\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Malformed statement\n", "expectation": "Simulation", - "name": "indexed_select::indexed_size_queries_preserve_parameter_dimensions", + "name": "synthesizable::struct_assignment_patterns_follow_the_target_layout", "phase": "compile", "status": "compile_error" }, { - "category": "Arrays", - "detail": "indexed_select::out_of_range_inner_indices_stay_in_their_element at 742:7: assert_eq b: expected 0xX, got 0x0 (b)", + "category": "Combinational", + "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:3: sorry: \"inside\" expressions not supported yet.\n/source_0.sv:5: sorry: \"inside\" expressions not supported yet.\n/source_0.sv:6: sorry: \"inside\" expressions not supported yet.\n", "expectation": "Simulation", - "name": "indexed_select::out_of_range_inner_indices_stay_in_their_element", + "name": "synthesizable::inside_matches_values_ranges_and_wildcards", + "phase": "compile", + "status": "compile_error" + }, + { + "category": "Regression", + "detail": "Icarus build exit status: 158; see /build.log\n/source_0.sv:7: syntax error\n/source_0.sv:7: Syntax in assignment statement l-value.\n/source_0.sv:7: syntax error\n/source_0.sv:8: Syntax in assignment statement l-value.\n/source_0.sv:8: syntax error\n/source_0.sv:9: Syntax in assignment statement l-value.\n/source_0.sv:9: syntax error\n/testbench.sv:3: error: Malformed statement\n/testbench.sv:4: syntax error\n/testbench.sv:4: error: Malformed statement\n/testbench.sv:5: syntax error\n/testbench.sv:5: error: Malformed statement\n/testbench.sv:6: syntax error\n/testbench.sv:6: error: Malformed statement\n/testbench.sv:7: syntax error\n/testbench.sv:7: error: Malformed statement\n/testbench.sv:8: syntax error\n/testbench.sv:8: error: Malformed statement\n/testbench.sv:10: syntax error\n/testbench.sv:10: error: Malformed statement\n/testbench.sv:13: syntax error\n/testbench.sv:15: error: Malformed statement\n/testbench.sv:17: syntax error\n/testbench.sv:19: error: Invalid module item.\n/tmp/nix-shell.S1fXMv/claude-1000", + "expectation": "Simulation", + "name": "review_regressions::preserves_four_state_shift_and_bit_select_constants", + "phase": "compile", + "status": "compile_error" + }, + { + "category": "Types", + "detail": "packed_structs::packed_struct_bounds_and_type_queries at 232:5: assert_eq widths: expected 0x22, got 0x20", + "expectation": "Simulation", + "name": "packed_structs::packed_struct_bounds_and_type_queries", "phase": "execute", "status": "mismatch" }, { - "category": "Arrays", - "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:11: error: A reference to a net or variable (`k') is not allowed in a constant expression.\n/source_0.sv:11: error: Array index expressions must be constant here.\n/source_0.sv:11: error: Unable to elaborate r-value: u[j][k][i]\n/source_0.sv:5: warning: always_comb process has no sensitivities.\n3 error(s) during elaboration.\n", + "category": "Types", + "detail": "packed_structs::packed_struct_mixed_state_members at 178:7: assert_eq compound_result: expected 0xx1, got 0xxx", "expectation": "Simulation", - "name": "indexed_select::out_of_range_inner_indices_stay_in_their_multidimensional_unpacked_element", + "name": "packed_structs::packed_struct_mixed_state_members", + "phase": "execute", + "status": "mismatch" + }, + { + "category": "Regression", + "detail": "review_regressions::preserves_four_state_arithmetic_case_constants at 306:7: assert_eq y11: expected 0x1, got 0xX (y11)", + "expectation": "Simulation", + "name": "review_regressions::preserves_four_state_arithmetic_case_constants", + "phase": "execute", + "status": "mismatch" + }, + { + "category": "Types", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:7: sorry: packed array parameters are not supported yet.\n", + "expectation": "Simulation", + "name": "types::packed_parameters_of_signed_named_types_have_signed_elements", "phase": "compile", "status": "compile_error" }, @@ -274,6 +295,14 @@ "phase": "compile", "status": "compile_error" }, + { + "category": "Arrays", + "detail": "indexed_select::out_of_range_inner_indices_stay_in_their_element at 742:7: assert_eq b: expected 0xX, got 0x0 (b)", + "expectation": "Simulation", + "name": "indexed_select::out_of_range_inner_indices_stay_in_their_element", + "phase": "execute", + "status": "mismatch" + }, { "category": "Hierarchy", "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:14: syntax error\n/source_0.sv:14: Errors in port declarations.\n/source_0.sv:17: syntax error\n/source_0.sv:17: Errors in port declarations.\n", @@ -362,67 +391,43 @@ "phase": "compile", "status": "compile_error" }, - { - "category": "Operators", - "detail": "operators::propagates_child_input_width_into_connection_expressions at 1116:3: assert_eq y: expected 0x100, got 0x0", - "expectation": "Simulation", - "name": "operators::propagates_child_input_width_into_connection_expressions", - "phase": "execute", - "status": "mismatch" - }, { "category": "Types", - "detail": "packed_structs::packed_struct_bounds_and_type_queries at 232:5: assert_eq widths: expected 0x22, got 0x20", - "expectation": "Simulation", - "name": "packed_structs::packed_struct_bounds_and_type_queries", - "phase": "execute", - "status": "mismatch" - }, - { - "category": "Types", - "detail": "packed_structs::packed_struct_mixed_state_members at 178:7: assert_eq compound_result: expected 0xx1, got 0xxx", - "expectation": "Simulation", - "name": "packed_structs::packed_struct_mixed_state_members", - "phase": "execute", - "status": "mismatch" - }, - { - "category": "ControlFlow", - "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:6: sorry: unpacked array parameters are not supported yet.\n/source_0.sv:7: sorry: unpacked array parameters are not supported yet.\n/source_0.sv:8: syntax error\n/source_0.sv:8: error: Invalid module item.\n", + "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:3: sorry: Subroutine ports with unpacked dimensions are not yet supported.\n/source_0.sv:10: error: Array v needs an array index here.\n/source_0.sv:11: error: Array v needs an array index here.\n/source_0.sv:8: sorry: constant selects in always_* processes are not fully supported (the process will be sensitive to all bits in 'd[15:0]').\n/source_0.sv:9: sorry: constant selects in always_* processes are not fully supported (the process will be sensitive to all bits in 'd[15:0]').\n3 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "procedural::aggregate_parameters_are_constant_tables", + "name": "types::passes_unpacked_arguments_of_equivalent_element_types", "phase": "compile", "status": "compile_error" }, { - "category": "ControlFlow", - "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:6: error: Function celox_suite_tb.dut.bump port after is not an input port.\n/source_0.sv:6: : Function arguments must be input ports.\n1 error(s) during elaboration.\n", - "expectation": "Simulation", - "name": "procedural::concatenated_targets_fix_their_positions_first", + "category": "Types", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:7: sorry: Procedural assignment of array or array slice is not yet supported.\n/source_0.sv:7: sorry: Procedural assignment of array or array slice is not yet supported.\n2 error(s) during elaboration.\n", + "expectation": "CompilationError", + "name": "types::rejects_assignment_pattern_item_of_a_narrower_array_type", "phase": "compile", "status": "compile_error" }, { - "category": "ControlFlow", - "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:5: error: Function celox_suite_tb.dut.tick port after is not an input port.\n/source_0.sv:5: : Function arguments must be input ports.\n1 error(s) during elaboration.\n", - "expectation": "Simulation", - "name": "procedural::ff_select_index_calls_write_state_and_run_once", + "category": "Types", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:3: sorry: Subroutine ports with unpacked dimensions are not yet supported.\n/source_0.sv:10: error: Array narrow needs an array index here.\n/source_0.sv:7: warning: always_comb process has no sensitivities.\n2 error(s) during elaboration.\n", + "expectation": "CompilationError", + "name": "types::rejects_unpacked_argument_of_a_wider_element_type", "phase": "compile", "status": "compile_error" }, { - "category": "ControlFlow", - "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:6: error: Function celox_suite_tb.dut.inner port after is not an input port.\n/source_0.sv:6: : Function arguments must be input ports.\n1 error(s) during elaboration.\n", + "category": "Regression", + "detail": "Icarus build exit status: 6; see /build.log\n/source_0.sv:9: syntax error\n/source_0.sv:9: error: Malformed statement\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Malformed statement\n/source_0.sv:18: syntax error\n/source_0.sv:18: error: Malformed statement\n", "expectation": "Simulation", - "name": "procedural::function_bodies_run_their_index_calls_each_time", + "name": "review_regressions::default_pattern_fills_each_element_of_unpacked_subarrays", "phase": "compile", "status": "compile_error" }, { - "category": "ControlFlow", - "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:5: error: Function celox_suite_tb.dut.tick port after is not an input port.\n/source_0.sv:5: : Function arguments must be input ports.\n1 error(s) during elaboration.\n", + "category": "Regression", + "detail": "Icarus build exit status: 18; see /build.log\n/source_0.sv:4: error: Type names are not valid expressions here.\n/source_0.sv:4: internal error: I do not know how to elaborate this expression. \n/source_0.sv:4: : Expression is: \n/source_0.sv:4: : Expression type: 10PETypename\n/source_0.sv:4: error: Unable to elaborate r-value: $size(, 'sd1)\n/source_0.sv:5: error: Type names are not valid expressions here.\n/source_0.sv:5: internal error: I do not know how to elaborate this expression. \n/source_0.sv:5: : Expression is: \n/source_0.sv:5: : Expression type: 10PETypename\n/source_0.sv:5: error: Unable to elaborate r-value: $size(, 'sd2)\n/source_0.sv:6: error: Type names are not valid expressions here.\n/source_0.sv:6: internal error: I do not know how to elaborate this expression. \n/source_0.sv:6: : Expression is: \n/source_0.sv:6: : Expression type: 10PETypename\n/source_0.sv:6: error: Unable to elaborate r-value: $size(, 'sd1)\n/source_0.sv:7: error: Type names are not valid expressions here.\n/source_0.sv:7: internal error: I do not know how to elaborate this expression. \n/source_0.sv:7: : Expression is: \n/source_0.sv:7: : Expression type: 10PETypename\n/source_0.sv:7: error: Unable to elaborate r-value: $size(, 'sd2)\n/source_0.sv:8: error: Type names are not valid expressions here.\n/source_0.sv:8: internal error: I do not know how to elaborate this expression. \n/source_0.sv:8: : Expression is: \n/source_0.sv:8: : Expression type: 10PETypename\n/source_0.sv:8: error:", "expectation": "Simulation", - "name": "procedural::select_index_call_skipped_by_logical_and", + "name": "review_regressions::size_of_a_type_uses_the_dimension_argument", "phase": "compile", "status": "compile_error" }, @@ -436,121 +441,100 @@ }, { "category": "ControlFlow", - "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:4: error: Function celox_suite_tb.dut.pick port y is not an input port.\n/source_0.sv:4: : Function arguments must be input ports.\n1 error(s) during elaboration.\n", - "expectation": "Simulation", - "name": "procedural::select_indices_call_functions", - "phase": "compile", - "status": "compile_error" - }, - { - "category": "Regression", - "detail": "Icarus build exit status: 6; see /build.log\n/source_0.sv:9: syntax error\n/source_0.sv:9: error: Malformed statement\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Malformed statement\n/source_0.sv:18: syntax error\n/source_0.sv:18: error: Malformed statement\n", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:5: error: Function celox_suite_tb.dut.tick port after is not an input port.\n/source_0.sv:5: : Function arguments must be input ports.\n1 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "review_regressions::default_pattern_fills_each_element_of_unpacked_subarrays", + "name": "procedural::select_index_call_skipped_by_logical_and", "phase": "compile", "status": "compile_error" }, { - "category": "Regression", - "detail": "review_regressions::preserves_four_state_arithmetic_case_constants at 306:7: assert_eq y11: expected 0x1, got 0xX (y11)", - "expectation": "Simulation", - "name": "review_regressions::preserves_four_state_arithmetic_case_constants", - "phase": "execute", - "status": "mismatch" - }, - { - "category": "Regression", - "detail": "Icarus build exit status: 158; see /build.log\n/source_0.sv:7: syntax error\n/source_0.sv:7: Syntax in assignment statement l-value.\n/source_0.sv:7: syntax error\n/source_0.sv:8: Syntax in assignment statement l-value.\n/source_0.sv:8: syntax error\n/source_0.sv:9: Syntax in assignment statement l-value.\n/source_0.sv:9: syntax error\n/testbench.sv:3: error: Malformed statement\n/testbench.sv:4: syntax error\n/testbench.sv:4: error: Malformed statement\n/testbench.sv:5: syntax error\n/testbench.sv:5: error: Malformed statement\n/testbench.sv:6: syntax error\n/testbench.sv:6: error: Malformed statement\n/testbench.sv:7: syntax error\n/testbench.sv:7: error: Malformed statement\n/testbench.sv:8: syntax error\n/testbench.sv:8: error: Malformed statement\n/testbench.sv:10: syntax error\n/testbench.sv:10: error: Malformed statement\n/testbench.sv:13: syntax error\n/testbench.sv:15: error: Malformed statement\n/testbench.sv:17: syntax error\n/testbench.sv:19: error: Invalid module item.\n/tmp/nix-shell.S1fXMv/claude-1000", + "category": "ControlFlow", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:6: error: Function celox_suite_tb.dut.bump port after is not an input port.\n/source_0.sv:6: : Function arguments must be input ports.\n1 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "review_regressions::preserves_four_state_shift_and_bit_select_constants", + "name": "procedural::concatenated_targets_fix_their_positions_first", "phase": "compile", "status": "compile_error" }, { - "category": "Regression", - "detail": "Icarus build exit status: 139; see /build.log\nSegmentation fault (core dumped)\n", + "category": "ControlFlow", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:5: error: Function celox_suite_tb.dut.tick port after is not an input port.\n/source_0.sv:5: : Function arguments must be input ports.\n1 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "review_regressions::preserves_size_cast_dimensions_in_declarations_and_selections", + "name": "procedural::ff_select_index_calls_write_state_and_run_once", "phase": "compile", "status": "compile_error" }, { - "category": "Regression", - "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:33: error: Cast size expression must be constant and greater than zero.\n1 error(s) during elaboration.\n", + "category": "ControlFlow", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:6: error: Function celox_suite_tb.dut.inner port after is not an input port.\n/source_0.sv:6: : Function arguments must be input ports.\n1 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "review_regressions::preserves_use_site_dimensions_in_function_alias_types", + "name": "procedural::function_bodies_run_their_index_calls_each_time", "phase": "compile", "status": "compile_error" }, { - "category": "Regression", - "detail": "Icarus build exit status: 18; see /build.log\n/source_0.sv:4: error: Type names are not valid expressions here.\n/source_0.sv:4: internal error: I do not know how to elaborate this expression. \n/source_0.sv:4: : Expression is: \n/source_0.sv:4: : Expression type: 10PETypename\n/source_0.sv:4: error: Unable to elaborate r-value: $size(, 'sd1)\n/source_0.sv:5: error: Type names are not valid expressions here.\n/source_0.sv:5: internal error: I do not know how to elaborate this expression. \n/source_0.sv:5: : Expression is: \n/source_0.sv:5: : Expression type: 10PETypename\n/source_0.sv:5: error: Unable to elaborate r-value: $size(, 'sd2)\n/source_0.sv:6: error: Type names are not valid expressions here.\n/source_0.sv:6: internal error: I do not know how to elaborate this expression. \n/source_0.sv:6: : Expression is: \n/source_0.sv:6: : Expression type: 10PETypename\n/source_0.sv:6: error: Unable to elaborate r-value: $size(, 'sd1)\n/source_0.sv:7: error: Type names are not valid expressions here.\n/source_0.sv:7: internal error: I do not know how to elaborate this expression. \n/source_0.sv:7: : Expression is: \n/source_0.sv:7: : Expression type: 10PETypename\n/source_0.sv:7: error: Unable to elaborate r-value: $size(, 'sd2)\n/source_0.sv:8: error: Type names are not valid expressions here.\n/source_0.sv:8: internal error: I do not know how to elaborate this expression. \n/source_0.sv:8: : Expression is: \n/source_0.sv:8: : Expression type: 10PETypename\n/source_0.sv:8: error:", + "category": "Arrays", + "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:11: error: A reference to a net or variable (`k') is not allowed in a constant expression.\n/source_0.sv:11: error: Array index expressions must be constant here.\n/source_0.sv:11: error: Unable to elaborate r-value: u[j][k][i]\n/source_0.sv:5: warning: always_comb process has no sensitivities.\n3 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "review_regressions::size_of_a_type_uses_the_dimension_argument", + "name": "indexed_select::out_of_range_inner_indices_stay_in_their_multidimensional_unpacked_element", "phase": "compile", "status": "compile_error" }, { - "category": "Combinational", - "detail": "Icarus build exit status: 7; see /build.log\n/source_0.sv:13: error: Function celox_suite_tb.dut.bump port v is not an input port.\n/source_0.sv:13: : Function arguments must be input ports.\n/source_0.sv:9: error: Function celox_suite_tb.dut.clamp port l is not an input port.\n/source_0.sv:9: : Function arguments must be input ports.\n/source_0.sv:9: error: Function celox_suite_tb.dut.clamp port h is not an input port.\n/source_0.sv:9: : Function arguments must be input ports.\n/source_0.sv:16: error: Function celox_suite_tb.dut.invert port z is not an input port.\n/source_0.sv:16: : Function arguments must be input ports.\n/source_0.sv:19: error: Function celox_suite_tb.dut.shift port z is not an input port.\n/source_0.sv:19: : Function arguments must be input ports.\n/source_0.sv:5: error: Function celox_suite_tb.dut.sum_diff port s is not an input port.\n/source_0.sv:5: : Function arguments must be input ports.\n/source_0.sv:5: error: Function celox_suite_tb.dut.sum_diff port d is not an input port.\n/source_0.sv:5: : Function arguments must be input ports.\n/source_0.sv:29: sorry: constant selects in always_* processes are not fully supported (the process will be sensitive to all bits in 'a[7:0]').\n7 error(s) during elaboration.\n", + "category": "Functions", + "detail": "system_functions::display_field_widths_expand_to_the_value at 245:3: expect_output: expected \":1234:11064:\\n\", got \":00001234:00000011064:\\n\"", "expectation": "Simulation", - "name": "synthesizable::function_output_and_inout_arguments_are_written_back", - "phase": "compile", - "status": "compile_error" + "name": "system_functions::display_field_widths_expand_to_the_value", + "phase": "execute", + "status": "mismatch" }, { - "category": "Combinational", - "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:3: sorry: \"inside\" expressions not supported yet.\n/source_0.sv:5: sorry: \"inside\" expressions not supported yet.\n/source_0.sv:6: sorry: \"inside\" expressions not supported yet.\n", + "category": "Functions", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:4: sorry: packed array parameters are not supported yet.\n", "expectation": "Simulation", - "name": "synthesizable::inside_matches_values_ranges_and_wildcards", + "name": "system_functions::dimensions_is_independent_of_unknown_values", "phase": "compile", "status": "compile_error" }, { - "category": "Combinational", - "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:6: vvp.tgt error: uwire \"lanes\" must have a single driver, found (4).\nerror: Code generation had 1 error(s).\n", + "category": "Functions", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:3: syntax error\n/source_0.sv:3: error: Syntax error in continuous assignment\n", "expectation": "Simulation", - "name": "synthesizable::instance_array_unpacked_connection_ascending_to_descending", + "name": "system_functions::dimensions_of_nonarray_handle_types", "phase": "compile", "status": "compile_error" }, { - "category": "Combinational", - "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:6: vvp.tgt error: uwire \"lanes\" must have a single driver, found (4).\nerror: Code generation had 1 error(s).\n", + "category": "Functions", + "detail": "Icarus build exit status: 5; see /build.log\n/source_0.sv:16: error: A reference to a net or variable (`index') is not allowed in a constant expression.\n/source_0.sv:16: error: Array index expressions must be constant here.\n/source_0.sv:16: error: Unable to elaborate r-value: $dimensions(a[index]['sd0])\n/source_0.sv:19: error: Array memory[index] needs 2 indices, but got only 1.\n/source_0.sv:19: error: Unable to elaborate r-value: $dimensions(memory[index])\n5 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "synthesizable::instance_array_unpacked_connection_descending_to_ascending", + "name": "system_functions::dimensions_preserves_selected_and_expression_types", "phase": "compile", "status": "compile_error" }, { - "category": "Combinational", - "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:6: vvp.tgt error: uwire \"lanes\" must have a single driver, found (4).\nerror: Code generation had 1 error(s).\n", + "category": "Functions", + "detail": "Icarus build exit status: 134; see /build.log\n/source_0.sv:4: error: Type names are not valid expressions here.\n/source_0.sv:4: internal error: I do not know how to elaborate this expression. \n/source_0.sv:4: : Expression is: \n/source_0.sv:4: : Expression type: 10PETypename\n/source_0.sv:4: error: Type names are not valid expressions here.\n/source_0.sv:4: internal error: I do not know how to elaborate this expression. \n/source_0.sv:4: : Expression is: \n/source_0.sv:4: : Expression type: 10PETypename\n/source_0.sv:33: assert: netmisc.cc:1860: failed assertion packed_dims.size() == 1\nAborted (core dumped)\n", "expectation": "Simulation", - "name": "synthesizable::instance_array_unpacked_connection_descending_to_descending", + "name": "system_functions::dimensions_resolves_types_and_constant_scopes", "phase": "compile", "status": "compile_error" }, { - "category": "Combinational", - "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:6: vvp.tgt error: uwire \"lanes\" must have a single driver, found (4).\nerror: Code generation had 1 error(s).\n", + "category": "Functions", + "detail": "system_functions::dimensions_preserves_one_bit_vectors at 889:5: assert_eq literal_rank: expected 0x1, got 0x0", "expectation": "Simulation", - "name": "synthesizable::instance_array_unpacked_connection_offset_ranges", - "phase": "compile", - "status": "compile_error" - }, - { - "category": "Combinational", - "detail": "invalid design was accepted: synthesizable::instance_arrays_reject_a_fill_literal_tie_off", - "expectation": "CompilationError", - "name": "synthesizable::instance_arrays_reject_a_fill_literal_tie_off", + "name": "system_functions::dimensions_preserves_one_bit_vectors", "phase": "execute", - "status": "unexpected_accept" + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] }, { - "category": "Combinational", - "detail": "synthesizable::named_calls_in_constant_contexts at 686:3: assert_eq query: expected 0x10, got 0x0", + "category": "Functions", + "detail": "system_functions::dimensions_resolves_imported_function_returns at 925:3: assert_eq imported_rank: expected 0x2, got 0x0", "expectation": "Simulation", - "name": "synthesizable::named_calls_in_constant_contexts", + "name": "system_functions::dimensions_resolves_imported_function_returns", "phase": "execute", "status": "mismatch", "stronger_than_sv": false, @@ -558,45 +542,43 @@ "tags": [] }, { - "category": "Combinational", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:4: error: A reference to a net or variable (`a') is not allowed in a constant expression.\n/source_0.sv:4: error: Unable to evaluate a as a port default expression.\n2 error(s) during elaboration.\n", + "category": "Functions", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:3: sorry: unpacked array parameters are not supported yet.\n", "expectation": "Simulation", - "name": "synthesizable::named_calls_preserve_defaults_and_declaration_scope", + "name": "system_functions::dimensions_resolves_package_array_constants", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, "tag_reasons": {}, "tags": [] }, - { - "category": "Combinational", - "detail": "Icarus build exit status: 6; see /build.log\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Syntax error in continuous assignment\n/source_0.sv:9: syntax error\n/source_0.sv:9: error: Malformed statement\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Malformed statement\n", - "expectation": "Simulation", - "name": "synthesizable::struct_assignment_patterns_follow_the_target_layout", - "phase": "compile", - "status": "compile_error" - }, { "category": "Functions", - "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:4: sorry: packed array parameters are not supported yet.\n", + "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:8: sorry: Subroutine ports with unpacked dimensions are not yet supported.\n/source_0.sv:4: sorry: Subroutine ports with unpacked dimensions are not yet supported.\n/source_0.sv:23: error: Array argument needs an array index here.\n/source_0.sv:24: error: Array argument needs an array index here.\n4 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "system_functions::dimensions_is_independent_of_unknown_values", + "name": "system_functions::dimensions_resolves_procedural_scopes", "phase": "compile", - "status": "compile_error" + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] }, { "category": "Functions", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:3: syntax error\n/source_0.sv:3: error: Syntax error in continuous assignment\n", + "detail": "system_functions::dimensions_resolves_procedural_parameters_and_indices at 1009:3: assert_eq local_parameter: expected 0x1, got 0x0", "expectation": "Simulation", - "name": "system_functions::dimensions_of_nonarray_handle_types", - "phase": "compile", - "status": "compile_error" + "name": "system_functions::dimensions_resolves_procedural_parameters_and_indices", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] }, { "category": "Functions", - "detail": "system_functions::dimensions_preserves_one_bit_vectors at 889:5: assert_eq literal_rank: expected 0x1, got 0x0", + "detail": "system_functions::dimensions_signing_conversions_are_vectors at 986:3: assert_eq signed_scalar: expected 0x1, got 0x0", "expectation": "Simulation", - "name": "system_functions::dimensions_preserves_one_bit_vectors", + "name": "system_functions::dimensions_signing_conversions_are_vectors", "phase": "execute", "status": "mismatch", "stronger_than_sv": false, @@ -605,28 +587,31 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 5; see /build.log\n/source_0.sv:16: error: A reference to a net or variable (`index') is not allowed in a constant expression.\n/source_0.sv:16: error: Array index expressions must be constant here.\n/source_0.sv:16: error: Unable to elaborate r-value: $dimensions(a[index]['sd0])\n/source_0.sv:19: error: Array memory[index] needs 2 indices, but got only 1.\n/source_0.sv:19: error: Unable to elaborate r-value: $dimensions(memory[index])\n5 error(s) during elaboration.\n", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:3: sorry: Subroutine ports with unpacked dimensions are not yet supported.\n/source_0.sv:7: error: Packed array assignment pattern expects 8 element(s) in this context.\n/source_0.sv:7: : Found 2 element(s).\n2 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "system_functions::dimensions_preserves_selected_and_expression_types", + "name": "system_functions::dimensions_types_function_pattern_arguments", "phase": "compile", - "status": "compile_error" + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] }, { "category": "Functions", - "detail": "system_functions::dimensions_resolves_imported_function_returns at 925:3: assert_eq imported_rank: expected 0x2, got 0x0", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:2: syntax error\nI give up.\n", "expectation": "Simulation", - "name": "system_functions::dimensions_resolves_imported_function_returns", - "phase": "execute", - "status": "mismatch", + "name": "system_functions::isunbounded_handles_overrides_and_forwarding", + "phase": "compile", + "status": "compile_error", "stronger_than_sv": false, "tag_reasons": {}, "tags": [] }, { "category": "Functions", - "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:3: sorry: unpacked array parameters are not supported yet.\n", + "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:4: syntax error\n/source_0.sv:4: error: Invalid module item.\n/source_0.sv:23: syntax error\n/source_0.sv:22: error: Syntax error defining function.\n", "expectation": "Simulation", - "name": "system_functions::dimensions_resolves_package_array_constants", + "name": "system_functions::isunbounded_preserves_lexical_scopes_and_short_circuits", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -635,20 +620,20 @@ }, { "category": "Functions", - "detail": "system_functions::dimensions_resolves_procedural_parameters_and_indices at 1009:3: assert_eq local_parameter: expected 0x1, got 0x0", + "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:5: syntax error\n/source_0.sv:5: error: Invalid module item.\n/source_0.sv:6: syntax error\n/source_0.sv:6: error: Invalid module item.\n", "expectation": "Simulation", - "name": "system_functions::dimensions_resolves_procedural_parameters_and_indices", - "phase": "execute", - "status": "mismatch", + "name": "system_functions::isunbounded_preserves_parameter_values_and_result_type", + "phase": "compile", + "status": "compile_error", "stronger_than_sv": false, "tag_reasons": {}, "tags": [] }, { "category": "Functions", - "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:8: sorry: Subroutine ports with unpacked dimensions are not yet supported.\n/source_0.sv:4: sorry: Subroutine ports with unpacked dimensions are not yet supported.\n/source_0.sv:23: error: Array argument needs an array index here.\n/source_0.sv:24: error: Array argument needs an array index here.\n4 error(s) during elaboration.\n", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:3: sorry: unpacked array parameters are not supported yet.\n/source_0.sv:6: sorry: unpacked array parameters are not supported yet.\n", "expectation": "Simulation", - "name": "system_functions::dimensions_resolves_procedural_scopes", + "name": "system_functions::isunbounded_reports_bounded_array_parameters", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -657,42 +642,26 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 134; see /build.log\n/source_0.sv:4: error: Type names are not valid expressions here.\n/source_0.sv:4: internal error: I do not know how to elaborate this expression. \n/source_0.sv:4: : Expression is: \n/source_0.sv:4: : Expression type: 10PETypename\n/source_0.sv:4: error: Type names are not valid expressions here.\n/source_0.sv:4: internal error: I do not know how to elaborate this expression. \n/source_0.sv:4: : Expression is: \n/source_0.sv:4: : Expression type: 10PETypename\n/source_0.sv:33: assert: netmisc.cc:1860: failed assertion packed_dims.size() == 1\nAborted (core dumped)\n", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:8: error: Unable to evaluate parameter Q value: $isunbounded()\n1 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "system_functions::dimensions_resolves_types_and_constant_scopes", + "name": "system_functions::isunbounded_reports_bounded_parameters", "phase": "compile", - "status": "compile_error" - }, - { - "category": "Functions", - "detail": "system_functions::dimensions_signing_conversions_are_vectors at 986:3: assert_eq signed_scalar: expected 0x1, got 0x0", - "expectation": "Simulation", - "name": "system_functions::dimensions_signing_conversions_are_vectors", - "phase": "execute", - "status": "mismatch", + "status": "compile_error", "stronger_than_sv": false, "tag_reasons": {}, "tags": [] }, { "category": "Functions", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:3: sorry: Subroutine ports with unpacked dimensions are not yet supported.\n/source_0.sv:7: error: Packed array assignment pattern expects 8 element(s) in this context.\n/source_0.sv:7: : Found 2 element(s).\n2 error(s) during elaboration.\n", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:3: syntax error\nI give up.\n", "expectation": "Simulation", - "name": "system_functions::dimensions_types_function_pattern_arguments", + "name": "system_functions::isunbounded_resolves_package_and_local_parameters", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, "tag_reasons": {}, "tags": [] }, - { - "category": "Functions", - "detail": "system_functions::display_field_widths_expand_to_the_value at 245:3: expect_output: expected \":1234:11064:\\n\", got \":00001234:00000011064:\\n\"", - "expectation": "Simulation", - "name": "system_functions::display_field_widths_expand_to_the_value", - "phase": "execute", - "status": "mismatch" - }, { "category": "Functions", "detail": "Icarus build exit status: 134; see /build.log\n/source_0.sv:5: syntax error\n/source_0.sv:4: error: Syntax error defining function.\n/source_0.sv:9: syntax error\n/source_0.sv:9: Syntax in assignment statement l-value.\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Invalid module instantiation\n/source_0.sv:13: error: Invalid module item.\n/source_0.sv:14: syntax error\n/source_0.sv:14: error: Invalid module instantiation\n/source_0.sv:17: error: Invalid module item.\n/source_0.sv:18: syntax error\n/source_0.sv:18: error: Invalid module instantiation\n/source_0.sv:20: error: Invalid module item.\n/source_0.sv:2: assert: pform.cc:1478: failed assertion lexical_scope == cur_module\nAborted (core dumped)\n", @@ -706,9 +675,9 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:5: syntax error\n/source_0.sv:5: error: Invalid module item.\n", + "detail": "Icarus build exit status: 134; see /build.log\n/source_0.sv:8: syntax error\n/source_0.sv:8: error: Malformed statement\n/source_0.sv:16: syntax error\n/source_0.sv:16: error: Invalid module instantiation\n/source_0.sv:17: error: Invalid module instantiation\n/source_0.sv:18: error: Invalid module instantiation\n/source_0.sv:19: error: Invalid module instantiation\n/testbench.sv:3: error: Invalid module item.\n/source_0.sv:2: assert: pform.cc:1478: failed assertion lexical_scope == cur_module\nAborted (core dumped)\n", "expectation": "Simulation", - "name": "system_functions::isunbounded_generate_guards_preserve_short_circuit_bounds", + "name": "system_functions::isunbounded_restores_procedural_parameter_bindings", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -717,9 +686,9 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:2: syntax error\nI give up.\n", + "detail": "Icarus build exit status: 134; see /build.log\n/source_0.sv:6: syntax error\n/source_0.sv:6: error: Malformed statement\n/source_0.sv:8: syntax error\n/source_0.sv:3: error: Syntax error defining function.\n/source_0.sv:2: assert: pform.cc:1478: failed assertion lexical_scope == cur_module\nAborted (core dumped)\n", "expectation": "Simulation", - "name": "system_functions::isunbounded_handles_overrides_and_forwarding", + "name": "system_functions::isunbounded_restores_shadowed_function_arguments", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -728,9 +697,9 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:4: syntax error\n/source_0.sv:4: error: Invalid module item.\n/source_0.sv:23: syntax error\n/source_0.sv:22: error: Syntax error defining function.\n", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:3: sorry: packed array parameters are not supported yet.\n", "expectation": "Simulation", - "name": "system_functions::isunbounded_preserves_lexical_scopes_and_short_circuits", + "name": "system_functions::isunbounded_restores_procedural_parameter_type_metadata", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -739,9 +708,9 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:5: syntax error\n/source_0.sv:5: error: Invalid module item.\n/source_0.sv:6: syntax error\n/source_0.sv:6: error: Invalid module item.\n", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:5: syntax error\n/source_0.sv:5: error: Invalid module item.\n", "expectation": "Simulation", - "name": "system_functions::isunbounded_preserves_parameter_values_and_result_type", + "name": "system_functions::isunbounded_generate_guards_preserve_short_circuit_bounds", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -750,9 +719,9 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:3: sorry: unpacked array parameters are not supported yet.\n/source_0.sv:6: sorry: unpacked array parameters are not supported yet.\n", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:5: error: Unable to evaluate parameter P value: bool<32>($timeprecision())\n/source_0.sv:4: error: Unable to evaluate parameter U value: bool<32>($timeunit())\n2 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "system_functions::isunbounded_reports_bounded_array_parameters", + "name": "system_functions::timescale_queries_are_constant_in_unqualified_calls", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -761,9 +730,9 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:8: error: Unable to evaluate parameter Q value: $isunbounded()\n1 error(s) during elaboration.\n", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:8: syntax error\n/source_0.sv:8: error: Syntax error in continuous assignment\n", "expectation": "Simulation", - "name": "system_functions::isunbounded_reports_bounded_parameters", + "name": "system_functions::timescale_queries_distinguish_unit_and_global_precision", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -772,9 +741,9 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:3: syntax error\nI give up.\n", + "detail": "Icarus build exit status: 9; see /build.log\n/source_0.sv:8: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:8: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:9: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:9: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:10: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:10: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:11: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:11: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:8: internal error: Failed to synthesize expression: (((((((($timeunit())==(32'b11111111111111111111111111111000))&&(($timeprecision())==(32'b11111111111111111111111111110101)))&&(($timeunit())==(32'b11111111111111111111111111111001)))&&(($timeprecision())==(32'b11111111111111111111111111110100)))&&(($timeunit())==(32'b11111111111111111111111111110111)))&&(($timeprecision())==(32'b11111111111111111111111111110100)))&&(($timeunit())==(32'b11111111111111111111111111111001)))&&(($timeprecision())==(32'b11111111111111111111111111110101))\n9 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "system_functions::isunbounded_resolves_package_and_local_parameters", + "name": "system_functions::timescale_queries_follow_partial_declarations_and_resetall", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -783,9 +752,9 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 134; see /build.log\n/source_0.sv:8: syntax error\n/source_0.sv:8: error: Malformed statement\n/source_0.sv:16: syntax error\n/source_0.sv:16: error: Invalid module instantiation\n/source_0.sv:17: error: Invalid module instantiation\n/source_0.sv:18: error: Invalid module instantiation\n/source_0.sv:19: error: Invalid module instantiation\n/testbench.sv:3: error: Invalid module item.\n/source_0.sv:2: assert: pform.cc:1478: failed assertion lexical_scope == cur_module\nAborted (core dumped)\n", + "detail": "Icarus build exit status: 12; see /build.log\n/source_0.sv:8: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:8: internal error: Failed to synthesize expression: \n/source_0.sv:9: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:9: internal error: Failed to synthesize expression: $timeprecision()\n/source_0.sv:10: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:10: internal error: Failed to synthesize expression: bool<32>((a) ? ($timeprecision()) : (celox_suite_tb.dut.unit_value()))\n/source_0.sv:11: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:11: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:12: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:13: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:14: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:11: internal error: Failed to synthesize expression: (((((($timeunit())==(32'b11111111111111111111111111110110))&&(($timeprecision())==(32'b11111111111111111111111111110010)))&&(1'd1))&&(($timeunit())<(32'b00000000000000000000000000000000)))&&((($timeunit())>>(32'b00000000000000000000000000000001))==(32'b01111111111111111111111111111011)))&&((($timeunit())>>>(32'b00000000000000000000000000000001))==(32'b11111111111111111111111111111011))\n12 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "system_functions::isunbounded_restores_procedural_parameter_bindings", + "name": "system_functions::timescale_queries_resolve_declarations_and_return_types", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -794,9 +763,9 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:3: sorry: packed array parameters are not supported yet.\n", + "detail": "Icarus build exit status: 15; see /build.log\n/source_0.sv:4: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:4: internal error: Failed to synthesize expression: bool<32>($timeunit())\n/source_0.sv:5: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:5: internal error: Failed to synthesize expression: bool<32>($timeprecision())\n/source_0.sv:10: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:10: internal error: Failed to synthesize expression: bool<32>($timeunit())\n/source_0.sv:11: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:11: internal error: Failed to synthesize expression: bool<32>($timeprecision())\n/source_0.sv:16: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:16: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:17: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:17: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:18: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:18: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:16: internal error: Failed to synthesize expression: (((((($timeunit())==(32'b11111111111111111111111111111101))&&(($timeprecision())==(32'b11111111111111111111111111111010)))&&(($timeunit())==(32'b11111111111111111111111111111010)))&&(($timeprecision())==(32'b11111111111111111111111111110111)))&&(($timeunit())==(32'b11111111111111111111111111111000)))&&(($timeprecision())==(32'b11111111111111111111111111110110))\n15 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "system_functions::isunbounded_restores_procedural_parameter_type_metadata", + "name": "system_functions::timescale_queries_resolve_directives_and_hierarchy", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -805,20 +774,20 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 134; see /build.log\n/source_0.sv:6: syntax error\n/source_0.sv:6: error: Malformed statement\n/source_0.sv:8: syntax error\n/source_0.sv:3: error: Syntax error defining function.\n/source_0.sv:2: assert: pform.cc:1478: failed assertion lexical_scope == cur_module\nAborted (core dumped)\n", + "detail": "native testbench failed: exit status: 6; see runtime.log and protocol.log\n/source_0.sv:5: Error: System task/function $timeprecision() is not defined by any module.\n/source_0.sv:9: Error: System task/function $timeunit() is not defined by any module.\n/source_0.sv:11: Error: System task/function $timeunit() is not defined by any module.\n/source_0.sv:12: Error: System task/function $timeprecision() is not defined by any module.\n/source_0.sv:15: Error: System task/function $timeunit() is not defined by any module.\n/source_0.sv:19: Error: System task/function $timeprecision() is not defined by any module.\n", "expectation": "Simulation", - "name": "system_functions::isunbounded_restores_shadowed_function_arguments", - "phase": "compile", - "status": "compile_error", + "name": "system_functions::timescale_queries_preserve_procedural_and_package_scopes", + "phase": "execute", + "status": "runtime_error", "stronger_than_sv": false, "tag_reasons": {}, "tags": [] }, { "category": "Functions", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Malformed statement\n", + "detail": "Icarus build exit status: 9; see /build.log\n/source_0.sv:3: error: A timeprecision is missing or is too large!\n/source_0.sv:4: error: Repeat timeprecision found and the initial timeprecision for this scope is missing.\n/source_0.sv:7: error: A timeprecision is missing or is too large!\n/source_0.sv:8: error: Repeat timeunit found and the initial timeunit for this scope is missing.\n/source_0.sv:14: error: A timeprecision is missing or is too large!\n/source_0.sv:15: error: Repeat timeprecision found and the initial timeprecision for this scope is missing.\n/source_0.sv:19: error: Repeat timeprecision found and the initial timeprecision for this scope is missing.\n/source_0.sv:21: syntax error\n/source_0.sv:20: error: Syntax error in continuous assignment\n", "expectation": "Simulation", - "name": "system_functions::printtimescale_displays_unit_and_global_precision", + "name": "system_functions::timescale_queries_accept_separate_initial_declarations", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -827,9 +796,9 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:12: syntax error\n/source_0.sv:12: error: Malformed statement\n", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:13: syntax error\nI give up.\n", "expectation": "Simulation", - "name": "system_functions::printtimescale_preserves_package_subroutine_scope", + "name": "system_functions::timescale_queries_keep_module_and_package_names_independent", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -849,9 +818,9 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 8; see /build.log\n/source_0.sv:2: error: Invalid timeunit constant (1st digit).\n/source_0.sv:2: error: Invalid timeprecision constant (1st digit).\n/source_0.sv:4: error: Invalid timeunit constant (1st digit).\n/source_0.sv:4: error: Invalid timeprecision constant (1st digit).\n/source_0.sv:9: error: Invalid timeunit constant (1st digit).\n/source_0.sv:9: error: Invalid timeprecision constant (1st digit).\n/source_0.sv:13: error: Invalid timeunit constant (1st digit).\n/source_0.sv:13: error: Invalid timeprecision constant (1st digit).\n", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:5: syntax error\nI give up.\n", "expectation": "Simulation", - "name": "system_functions::timescale_queries_accept_leading_zero_magnitudes", + "name": "system_functions::timescale_queries_resolve_packages_with_instantiated_namesakes", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -860,9 +829,9 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 9; see /build.log\n/source_0.sv:3: error: A timeprecision is missing or is too large!\n/source_0.sv:4: error: Repeat timeprecision found and the initial timeprecision for this scope is missing.\n/source_0.sv:7: error: A timeprecision is missing or is too large!\n/source_0.sv:8: error: Repeat timeunit found and the initial timeunit for this scope is missing.\n/source_0.sv:14: error: A timeprecision is missing or is too large!\n/source_0.sv:15: error: Repeat timeprecision found and the initial timeprecision for this scope is missing.\n/source_0.sv:19: error: Repeat timeprecision found and the initial timeprecision for this scope is missing.\n/source_0.sv:21: syntax error\n/source_0.sv:20: error: Syntax error in continuous assignment\n", + "detail": "Icarus build exit status: 12; see /build.log\n/source_0.sv:11: syntax error\n/source_0.sv:11: error: Malformed statement\n/source_0.sv:12: syntax error\n/source_0.sv:12: error: Malformed statement\n/source_0.sv:13: sorry: modport task/function ports are not yet supported.\n/source_0.sv:13: sorry: modport task/function ports are not yet supported.\n/source_1.sv:2: error: Repeat timeunit does not match the initial timeunit for this scope.\n/source_1.sv:2: error: Repeat timeprecision does not match the initial timeprecision for this scope.\n/source_1.sv:3: syntax error\n/source_1.sv:3: Errors in port declarations.\n/source_1.sv:16: syntax error\n/source_1.sv:15: error: Syntax error in continuous assignment\n", "expectation": "Simulation", - "name": "system_functions::timescale_queries_accept_separate_initial_declarations", + "name": "system_functions::timescale_queries_preserve_interface_scopes_when_flattened", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -871,9 +840,9 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:5: error: Unable to evaluate parameter P value: bool<32>($timeprecision())\n/source_0.sv:4: error: Unable to evaluate parameter U value: bool<32>($timeunit())\n2 error(s) during elaboration.\n", + "detail": "Icarus build exit status: 8; see /build.log\n/source_0.sv:2: error: Invalid timeunit constant (1st digit).\n/source_0.sv:2: error: Invalid timeprecision constant (1st digit).\n/source_0.sv:4: error: Invalid timeunit constant (1st digit).\n/source_0.sv:4: error: Invalid timeprecision constant (1st digit).\n/source_0.sv:9: error: Invalid timeunit constant (1st digit).\n/source_0.sv:9: error: Invalid timeprecision constant (1st digit).\n/source_0.sv:13: error: Invalid timeunit constant (1st digit).\n/source_0.sv:13: error: Invalid timeprecision constant (1st digit).\n", "expectation": "Simulation", - "name": "system_functions::timescale_queries_are_constant_in_unqualified_calls", + "name": "system_functions::timescale_queries_accept_leading_zero_magnitudes", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -882,9 +851,9 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:8: syntax error\n/source_0.sv:8: error: Syntax error in continuous assignment\n", + "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:6: error: Unable to evaluate parameter P value: bool<32>($timeprecision())\n/source_0.sv:5: error: Unable to evaluate parameter U value: bool<32>($timeunit())\n/source_0.sv:6: error: Unable to evaluate parameter P value: bool<32>($timeprecision())\n/source_0.sv:5: error: Unable to evaluate parameter U value: bool<32>($timeunit())\n4 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "system_functions::timescale_queries_distinguish_unit_and_global_precision", + "name": "system_functions::timescale_queries_survive_type_parameter_specialization", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -893,20 +862,28 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 9; see /build.log\n/source_0.sv:8: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:8: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:9: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:9: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:10: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:10: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:11: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:11: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:8: internal error: Failed to synthesize expression: (((((((($timeunit())==(32'b11111111111111111111111111111000))&&(($timeprecision())==(32'b11111111111111111111111111110101)))&&(($timeunit())==(32'b11111111111111111111111111111001)))&&(($timeprecision())==(32'b11111111111111111111111111110100)))&&(($timeunit())==(32'b11111111111111111111111111110111)))&&(($timeprecision())==(32'b11111111111111111111111111110100)))&&(($timeunit())==(32'b11111111111111111111111111111001)))&&(($timeprecision())==(32'b11111111111111111111111111110101))\n9 error(s) during elaboration.\n", + "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:9: syntax error\n/source_0.sv:9: Errors in port declarations.\n/source_0.sv:14: syntax error\n/source_0.sv:14: Errors in port declarations.\n", "expectation": "Simulation", - "name": "system_functions::timescale_queries_follow_partial_declarations_and_resetall", + "name": "system_functions::timescale_queries_resolve_interface_instances_and_ports", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, "tag_reasons": {}, "tags": [] }, + { + "category": "Arrays", + "detail": "Icarus build exit status: 18; see /build.log\n/source_0.sv:13: syntax error\n/source_0.sv:13: Syntax in assignment statement l-value.\n/source_0.sv:17: syntax error\n/source_0.sv:17: Syntax in assignment statement l-value.\n/source_0.sv:19: syntax error\n/source_0.sv:19: error: Syntax error in continuous assignment\n/source_0.sv:20: syntax error\n/source_0.sv:20: error: Syntax error in continuous assignment\n/source_0.sv:21: syntax error\n/source_0.sv:21: error: Syntax error in continuous assignment\n/source_0.sv:22: syntax error\n/source_0.sv:22: error: Syntax error in continuous assignment\n/source_0.sv:23: syntax error\n/source_0.sv:23: error: Syntax error in continuous assignment\n/source_0.sv:24: syntax error\n/source_0.sv:24: error: Syntax error in continuous assignment\n/source_0.sv:25: syntax error\n/source_0.sv:25: error: Syntax error in continuous assignment\n", + "expectation": "Simulation", + "name": "indexed_select::constant_part_select_indices_of_concatenations", + "phase": "compile", + "status": "compile_error" + }, { "category": "Functions", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:13: syntax error\nI give up.\n", + "detail": "Icarus build exit status: 8; see /build.log\n/source_0.sv:23: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:23: internal error: Failed to synthesize expression: bool<32>($timeunit())\n/source_0.sv:24: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:24: internal error: Failed to synthesize expression: bool<32>($timeprecision())\n/source_0.sv:25: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:25: internal error: Failed to synthesize expression: bool<32>($timeunit())\n/source_0.sv:26: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:26: internal error: Failed to synthesize expression: bool<32>($timeprecision())\n/source_0.sv:27: warning: always_comb process has no sensitivities.\n/source_0.sv:28: warning: System task ($timeunit) cannot be synthesized in an always_comb process.\n8 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "system_functions::timescale_queries_keep_module_and_package_names_independent", + "name": "system_functions::timescale_queries_resolve_hierarchical_interface_instances", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -914,10 +891,10 @@ "tags": [] }, { - "category": "Functions", - "detail": "Icarus build exit status: 12; see /build.log\n/source_0.sv:11: syntax error\n/source_0.sv:11: error: Malformed statement\n/source_0.sv:12: syntax error\n/source_0.sv:12: error: Malformed statement\n/source_0.sv:13: sorry: modport task/function ports are not yet supported.\n/source_0.sv:13: sorry: modport task/function ports are not yet supported.\n/source_1.sv:2: error: Repeat timeunit does not match the initial timeunit for this scope.\n/source_1.sv:2: error: Repeat timeprecision does not match the initial timeprecision for this scope.\n/source_1.sv:3: syntax error\n/source_1.sv:3: Errors in port declarations.\n/source_1.sv:16: syntax error\n/source_1.sv:15: error: Syntax error in continuous assignment\n", + "category": "Hierarchy", + "detail": "Icarus build exit status: 7; see /build.log\n/source_0.sv:2: sorry: unpacked array parameters are not supported yet.\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Syntax error in parameter value assignment list.\n/source_0.sv:10: error: Invalid module instantiation\n/source_0.sv:11: syntax error\n/source_0.sv:11: error: Syntax error in parameter value assignment list.\n/source_0.sv:11: error: Invalid module instantiation\n", "expectation": "Simulation", - "name": "system_functions::timescale_queries_preserve_interface_scopes_when_flattened", + "name": "hierarchy::parameter_patterns_bind_caller_types", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -925,21 +902,21 @@ "tags": [] }, { - "category": "Functions", - "detail": "native testbench failed: exit status: 6; see runtime.log and protocol.log\n/source_0.sv:5: Error: System task/function $timeprecision() is not defined by any module.\n/source_0.sv:9: Error: System task/function $timeunit() is not defined by any module.\n/source_0.sv:11: Error: System task/function $timeunit() is not defined by any module.\n/source_0.sv:12: Error: System task/function $timeprecision() is not defined by any module.\n/source_0.sv:15: Error: System task/function $timeunit() is not defined by any module.\n/source_0.sv:19: Error: System task/function $timeprecision() is not defined by any module.\n", + "category": "Hierarchy", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:2: syntax error\nI give up.\n", "expectation": "Simulation", - "name": "system_functions::timescale_queries_preserve_procedural_and_package_scopes", - "phase": "execute", - "status": "runtime_error", + "name": "hierarchy::parameter_patterns_bind_nested_caller_types", + "phase": "compile", + "status": "compile_error", "stronger_than_sv": false, "tag_reasons": {}, "tags": [] }, { - "category": "Functions", - "detail": "Icarus build exit status: 12; see /build.log\n/source_0.sv:8: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:8: internal error: Failed to synthesize expression: \n/source_0.sv:9: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:9: internal error: Failed to synthesize expression: $timeprecision()\n/source_0.sv:10: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:10: internal error: Failed to synthesize expression: bool<32>((a) ? ($timeprecision()) : (celox_suite_tb.dut.unit_value()))\n/source_0.sv:11: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:11: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:12: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:13: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:14: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:11: internal error: Failed to synthesize expression: (((((($timeunit())==(32'b11111111111111111111111111110110))&&(($timeprecision())==(32'b11111111111111111111111111110010)))&&(1'd1))&&(($timeunit())<(32'b00000000000000000000000000000000)))&&((($timeunit())>>(32'b00000000000000000000000000000001))==(32'b01111111111111111111111111111011)))&&((($timeunit())>>>(32'b00000000000000000000000000000001))==(32'b11111111111111111111111111111011))\n12 error(s) during elaboration.\n", + "category": "Hierarchy", + "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:2: sorry: unpacked array parameters are not supported yet.\n/source_0.sv:7: syntax error\nI give up.\n", "expectation": "Simulation", - "name": "system_functions::timescale_queries_resolve_declarations_and_return_types", + "name": "hierarchy::parameter_patterns_keep_fill_and_arithmetic_context", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -947,10 +924,10 @@ "tags": [] }, { - "category": "Functions", - "detail": "Icarus build exit status: 15; see /build.log\n/source_0.sv:4: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:4: internal error: Failed to synthesize expression: bool<32>($timeunit())\n/source_0.sv:5: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:5: internal error: Failed to synthesize expression: bool<32>($timeprecision())\n/source_0.sv:10: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:10: internal error: Failed to synthesize expression: bool<32>($timeunit())\n/source_0.sv:11: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:11: internal error: Failed to synthesize expression: bool<32>($timeprecision())\n/source_0.sv:16: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:16: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:17: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:17: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:18: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:18: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:16: internal error: Failed to synthesize expression: (((((($timeunit())==(32'b11111111111111111111111111111101))&&(($timeprecision())==(32'b11111111111111111111111111111010)))&&(($timeunit())==(32'b11111111111111111111111111111010)))&&(($timeprecision())==(32'b11111111111111111111111111110111)))&&(($timeunit())==(32'b11111111111111111111111111111000)))&&(($timeprecision())==(32'b11111111111111111111111111110110))\n15 error(s) during elaboration.\n", + "category": "Hierarchy", + "detail": "Icarus build exit status: 7; see /build.log\n/source_0.sv:2: sorry: unpacked array parameters are not supported yet.\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Syntax error in parameter value assignment list.\n/source_0.sv:7: error: Invalid module instantiation\n/source_0.sv:8: syntax error\n/source_0.sv:8: error: Syntax error in parameter value assignment list.\n/source_0.sv:8: error: Invalid module instantiation\n", "expectation": "Simulation", - "name": "system_functions::timescale_queries_resolve_directives_and_hierarchy", + "name": "hierarchy::parameter_patterns_keep_unknown_fill", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -959,9 +936,9 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 8; see /build.log\n/source_0.sv:23: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:23: internal error: Failed to synthesize expression: bool<32>($timeunit())\n/source_0.sv:24: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:24: internal error: Failed to synthesize expression: bool<32>($timeprecision())\n/source_0.sv:25: error: System function $timeunit not defined in system table or SFT file(s).\n/source_0.sv:25: internal error: Failed to synthesize expression: bool<32>($timeunit())\n/source_0.sv:26: error: System function $timeprecision not defined in system table or SFT file(s).\n/source_0.sv:26: internal error: Failed to synthesize expression: bool<32>($timeprecision())\n/source_0.sv:27: warning: always_comb process has no sensitivities.\n/source_0.sv:28: warning: System task ($timeunit) cannot be synthesized in an always_comb process.\n8 error(s) during elaboration.\n", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Malformed statement\n", "expectation": "Simulation", - "name": "system_functions::timescale_queries_resolve_hierarchical_interface_instances", + "name": "system_functions::printtimescale_displays_unit_and_global_precision", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -970,9 +947,9 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:9: syntax error\n/source_0.sv:9: Errors in port declarations.\n/source_0.sv:14: syntax error\n/source_0.sv:14: Errors in port declarations.\n", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:12: syntax error\n/source_0.sv:12: error: Malformed statement\n", "expectation": "Simulation", - "name": "system_functions::timescale_queries_resolve_interface_instances_and_ports", + "name": "system_functions::printtimescale_preserves_package_subroutine_scope", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -980,10 +957,10 @@ "tags": [] }, { - "category": "Functions", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:5: syntax error\nI give up.\n", + "category": "Hierarchy", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:2: sorry: unpacked array parameters are not supported yet.\n", "expectation": "Simulation", - "name": "system_functions::timescale_queries_resolve_packages_with_instantiated_namesakes", + "name": "hierarchy::parameter_patterns_evaluate_caller_constant_functions", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -991,10 +968,10 @@ "tags": [] }, { - "category": "Functions", - "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:6: error: Unable to evaluate parameter P value: bool<32>($timeprecision())\n/source_0.sv:5: error: Unable to evaluate parameter U value: bool<32>($timeunit())\n/source_0.sv:6: error: Unable to evaluate parameter P value: bool<32>($timeprecision())\n/source_0.sv:5: error: Unable to evaluate parameter U value: bool<32>($timeunit())\n4 error(s) during elaboration.\n", + "category": "Hierarchy", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:3: sorry: unpacked array parameters are not supported yet.\n", "expectation": "Simulation", - "name": "system_functions::timescale_queries_survive_type_parameter_specialization", + "name": "hierarchy::parameter_patterns_override_body_declarations", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -1002,10 +979,10 @@ "tags": [] }, { - "category": "Functions", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:7: error: Function celox_suite_tb.dut.g port x is not an input port.\n/source_0.sv:7: : Function arguments must be input ports.\n/source_0.sv:12: error: Function celox_suite_tb.dut.update port x is not an input port.\n/source_0.sv:12: : Function arguments must be input ports.\n2 error(s) during elaboration.\n", + "category": "Combinational", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:4: error: A reference to a net or variable (`a') is not allowed in a constant expression.\n/source_0.sv:4: error: Unable to evaluate a as a port default expression.\n2 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "system_functions::unpacked_dimensions_accepts_function_result_arguments", + "name": "synthesizable::named_calls_preserve_defaults_and_declaration_scope", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -1061,17 +1038,6 @@ "tag_reasons": {}, "tags": [] }, - { - "category": "Functions", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:3: syntax error\nI give up.\n", - "expectation": "Simulation", - "name": "system_functions::unpacked_dimensions_publishes_dependent_array_parameters", - "phase": "compile", - "status": "compile_error", - "stronger_than_sv": false, - "tag_reasons": {}, - "tags": [] - }, { "category": "Functions", "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:3: sorry: unpacked array parameters are not supported yet.\n", @@ -1125,42 +1091,76 @@ "tags": [] }, { - "category": "Sequential", - "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:6: sorry: modport task/function ports are not yet supported.\n/source_0.sv:8: syntax error\n/source_0.sv:8: Errors in port declarations.\n", + "category": "Functions", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:7: error: Function celox_suite_tb.dut.g port x is not an input port.\n/source_0.sv:7: : Function arguments must be input ports.\n/source_0.sv:12: error: Function celox_suite_tb.dut.update port x is not an input port.\n/source_0.sv:12: : Function arguments must be input ports.\n2 error(s) during elaboration.\n", "expectation": "Simulation", - "name": "timing::interface_modport_methods_keep_setup_edges", + "name": "system_functions::unpacked_dimensions_accepts_function_result_arguments", "phase": "compile", - "status": "compile_error" + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] }, { - "category": "Types", - "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:7: sorry: packed array parameters are not supported yet.\n", + "category": "Functions", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:3: syntax error\nI give up.\n", "expectation": "Simulation", - "name": "types::packed_parameters_of_signed_named_types_have_signed_elements", + "name": "system_functions::unpacked_dimensions_publishes_dependent_array_parameters", "phase": "compile", - "status": "compile_error" + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] }, { - "category": "Types", - "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:3: sorry: Subroutine ports with unpacked dimensions are not yet supported.\n/source_0.sv:10: error: Array v needs an array index here.\n/source_0.sv:11: error: Array v needs an array index here.\n/source_0.sv:8: sorry: constant selects in always_* processes are not fully supported (the process will be sensitive to all bits in 'd[15:0]').\n/source_0.sv:9: sorry: constant selects in always_* processes are not fully supported (the process will be sensitive to all bits in 'd[15:0]').\n3 error(s) during elaboration.\n", + "category": "Hierarchy", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:5: syntax error\nI give up.\n", "expectation": "Simulation", - "name": "types::passes_unpacked_arguments_of_equivalent_element_types", + "name": "hierarchy::parameter_patterns_transfer_packed_values", "phase": "compile", - "status": "compile_error" + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] }, { - "category": "Types", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:7: sorry: Procedural assignment of array or array slice is not yet supported.\n/source_0.sv:7: sorry: Procedural assignment of array or array slice is not yet supported.\n2 error(s) during elaboration.\n", - "expectation": "CompilationError", - "name": "types::rejects_assignment_pattern_item_of_a_narrower_array_type", + "category": "Hierarchy", + "detail": "Icarus build exit status: 9; see /build.log\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Syntax error in parameter value assignment list.\n/source_0.sv:10: error: Invalid module instantiation\n/source_0.sv:11: syntax error\n/source_0.sv:11: error: Syntax error in parameter value assignment list.\n/source_0.sv:11: error: Invalid module instantiation\n/source_0.sv:12: syntax error\n/source_0.sv:12: error: Syntax error in parameter value assignment list.\n/source_0.sv:12: error: Invalid module instantiation\n", + "expectation": "Simulation", + "name": "hierarchy::parameter_patterns_override_scalar_defaults", "phase": "compile", - "status": "compile_error" + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] }, { - "category": "Types", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:3: sorry: Subroutine ports with unpacked dimensions are not yet supported.\n/source_0.sv:10: error: Array narrow needs an array index here.\n/source_0.sv:7: warning: always_comb process has no sensitivities.\n2 error(s) during elaboration.\n", - "expectation": "CompilationError", - "name": "types::rejects_unpacked_argument_of_a_wider_element_type", + "category": "Hierarchy", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:5: syntax error\nI give up.\n", + "expectation": "Simulation", + "name": "hierarchy::parameter_patterns_preserve_packed_member_states", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Combinational", + "detail": "synthesizable::named_calls_in_constant_contexts at 686:3: assert_eq query: expected 0x10, got 0x0", + "expectation": "Simulation", + "name": "synthesizable::named_calls_in_constant_contexts", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:6: sorry: modport task/function ports are not yet supported.\n/source_0.sv:8: syntax error\n/source_0.sv:8: Errors in port declarations.\n", + "expectation": "Simulation", + "name": "timing::interface_modport_methods_keep_setup_edges", "phase": "compile", "status": "compile_error" } From 70b902ce37ca62a72b3af7b8ec5c5452efcbc91b Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 00:03:13 +0900 Subject: [PATCH 44/75] test(suite): keep simulator phase disagreement outside portable cases --- crates/celox/tests/frontends/systemverilog/timing.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index b0422bedb5b..435cb96d329 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -179,5 +179,3 @@ sv_backends! { } sv_backends! { fn interface_modport_methods_keep_setup_edges(sim) { @case "timing::interface_modport_methods_keep_setup_edges"; } } - -sv_backends! { fn inactive_phases_preserve_cross_instance_edges(sim) { @case "timing::inactive_phases_preserve_cross_instance_edges"; } } From 8612b020e3317eff71953bc1e81474dd6d81888e Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 00:50:02 +0900 Subject: [PATCH 45/75] fix(suite): use specialized generic and inherited interface bindings --- crates/celox-sv-analyzer/src/ast.rs | 53 ++++++++++----- .../celox-sv-analyzer/src/ast/interfaces.rs | 14 +++- .../celox-test-suite/src/frontend/timed_ff.rs | 66 ++++++++++++++++++- .../src/sv/cases/timing.vtest | 36 ++++++++++ .../verification/sv/limitations.json | 2 + .../verification/sv/limitations/icarus.json | 18 ++++- .../tests/frontends/systemverilog/timing.rs | 4 ++ 7 files changed, 172 insertions(+), 21 deletions(-) diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index e93636e930d..6b89eeb8602 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -2559,26 +2559,43 @@ pub fn package_import_export_clauses( /// Instance bindings retain their declared type across parameter assignments. pub fn instance_type_sites(tree: &SyntaxTree) -> Vec<(usize, String, String)> { let mut sites = Vec::new(); + let mut inherited = None; for node in tree { - if let RefNode::AnsiPortDeclarationNet(port) = node.clone() - && let Some(sv_parser::NetPortHeaderOrInterfacePortHeader::InterfacePortHeader(header)) = - &port.nodes.0 - && let sv_parser::InterfacePortHeader::Identifier(header) = &**header - && let Some(module) = - identifier_text(RefNode::InterfaceIdentifier(&header.nodes.0), tree) - && let Some(identifier) = identifier_text(RefNode::PortIdentifier(&port.nodes.1), tree) - && let Some(offset) = - RefNode::PortIdentifier(&port.nodes.1) - .into_iter() - .find_map(|node| { - if let RefNode::Locate(loc) = node { - Some(loc.offset) - } else { - None + if matches!(node, RefNode::ModuleDeclarationAnsi(_)) { + inherited = None; + } + if let RefNode::AnsiPortDeclarationNet(port) = node.clone() { + if let Some(header) = &port.nodes.0 { + inherited = match header { + sv_parser::NetPortHeaderOrInterfacePortHeader::InterfacePortHeader(header) => { + match &**header { + sv_parser::InterfacePortHeader::Identifier(header) => { + identifier_text(RefNode::InterfaceIdentifier(&header.nodes.0), tree) + } + _ => None, } - }) - { - sites.push((offset, identifier, module)); + } + _ => None, + }; + } + if let Some(module) = inherited.clone() + && let Some(identifier) = + identifier_text(RefNode::PortIdentifier(&port.nodes.1), tree) + && let Some(offset) = + RefNode::PortIdentifier(&port.nodes.1) + .into_iter() + .find_map(|node| { + if let RefNode::Locate(loc) = node { + Some(loc.offset) + } else { + None + } + }) + { + sites.push((offset, identifier, module)); + } + } else if matches!(node, RefNode::AnsiPortDeclarationVariable(_)) { + inherited = None; } let RefNode::ModuleInstantiation(instance) = node else { diff --git a/crates/celox-sv-analyzer/src/ast/interfaces.rs b/crates/celox-sv-analyzer/src/ast/interfaces.rs index ce7978aa4d6..8f69c64792a 100644 --- a/crates/celox-sv-analyzer/src/ast/interfaces.rs +++ b/crates/celox-sv-analyzer/src/ast/interfaces.rs @@ -249,6 +249,8 @@ pub struct InterfaceElaboration { pub sources: Option>, pub root_names: HashMap, pub interface_ports: HashMap>, + /// Concrete generic port types encountered during specialization. + pub generic_bindings: HashMap<(String, String), HashSet>, } pub fn elaborate_interfaces_with_metadata( @@ -398,8 +400,11 @@ pub fn elaborate_interfaces_with_metadata_and_roots( ) }) .collect(); + let mut generic_bindings = HashMap::default(); + let sources = design.elaborate_with_roots(clones, scales, &mut generic_bindings)?; Ok(InterfaceElaboration { - sources: Some(design.elaborate_with_roots(clones, scales)?), + sources: Some(sources), + generic_bindings, root_names: names, interface_ports, }) @@ -1520,6 +1525,7 @@ impl<'a> Design<'a> { &self, mut clones: Vec<(String, Vec<(String, String)>)>, scales: &super::timescales::Timescales, + generic_bindings: &mut HashMap<(String, String), HashSet>, ) -> Result, AnalyzerError> { let mut edits: Vec> = vec![Vec::new(); self.files.len()]; let mut names: Vec = self.modules.keys().cloned().collect(); @@ -1544,6 +1550,12 @@ impl<'a> Design<'a> { } } while let Some((name, bindings)) = clones.pop() { + for (port, interface) in &bindings { + generic_bindings + .entry((name.clone(), port.clone())) + .or_default() + .insert(interface.clone()); + } let clone_name = clone_module_name(&name, &bindings); if !cloned.insert(clone_name.clone()) { continue; diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index d6b1b743f65..add7d399462 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -465,14 +465,36 @@ pub(super) struct TaskTiming { ff_offsets: BTreeMap>, calls: BTreeMap>, instance_types: BTreeMap>, + generic_bindings: BTreeMap<(String, String), std::collections::BTreeSet>, imports: BTreeMap)>>, exports: BTreeMap, Option)>>, } +// `interface` inside an ANSI header is a generic formal, not a container. +fn generic_interface_keyword(source: &str, start: usize) -> bool { + let mut at = 0; + let mut depth = 0usize; + while at < start { + if skip_token(source, &mut at) { + continue; + } + match source.as_bytes()[at] { + b'(' => depth += 1, + b')' => depth = depth.saturating_sub(1), + _ => {} + } + at += 1; + } + depth > 0 +} + fn container_at(source: &str, at: usize) -> String { let words = sv_words(&source[..at]); let mut scope = String::new(); - for (index, (_, _, word)) in words.iter().enumerate() { + for (index, (start, _, word)) in words.iter().enumerate() { + if *word == "interface" && generic_interface_keyword(source, *start) { + continue; + } match *word { "module" | "interface" | "package" => { if let Some((_, _, name)) = words[index + 1..] @@ -494,6 +516,9 @@ fn container_at(source: &str, at: usize) -> String { fn lexical_scope_at(source: &str, at: usize, generates: &[(usize, usize)]) -> Vec { let mut scopes = Vec::new(); for (start, _, word) in sv_words(&source[..at]) { + if word == "interface" && generic_interface_keyword(source, start) { + continue; + } match word { "module" | "interface" | "package" | "begin" | "fork" | "task" | "function" => { scopes.push(start) @@ -628,6 +653,18 @@ impl TaskTiming { } pub(super) fn new(sources: &[String]) -> Self { let mut result = Self::default(); + let paths: Vec<_> = sources + .iter() + .map(|s| (s.as_str(), Path::new("timed.sv"))) + .collect(); + if let Ok(elaboration) = celox_sv_analyzer::elaborate_interfaces_with_metadata(&paths, &[]) + { + result.generic_bindings = elaboration + .generic_bindings + .into_iter() + .map(|(key, types)| (key, types.into_iter().collect())) + .collect(); + } let mut records = Vec::new(); for (index, source) in sources.iter().enumerate() { result.units.insert(source.clone(), index); @@ -804,6 +841,18 @@ impl TaskTiming { if let Some(prefix) = prefix.strip_suffix('.') { let instance = sv_words(prefix).last()?.2; let scope = container_at(source, at); + if let Some(types) = self + .generic_bindings + .get(&(scope.clone(), instance.to_owned())) + { + let mut timed = false; + for typ in types { + timed |= *self + .tasks + .get(&(typ.clone(), None, Vec::new(), name.to_owned()))?; + } + return Some(timed); + } if let Some(instances) = self.instance_types.get(source) { let call_scope = self.lexical_scope(source, at); let found = instances @@ -954,6 +1003,21 @@ impl TaskTiming { mod callable_analysis_tests { use super::*; #[test] + fn generic_interface_formals_resolve_from_specialized_bindings() { + let source="interface Scale;function automatic bit scaled(input bit v);return v;endfunction endinterface\nmodule User(interface s,input bit clk,v,output bit q);always @(posedge clk)q<=s.scaled(v);endmodule\nmodule Top(input bit clk,v,output bit q);Scale s();\nUser u(.s(s),.clk(clk),.v(v),.q(q));endmodule".to_owned(); + let e = celox_sv_analyzer::elaborate_interfaces_with_metadata( + &[(source.as_str(), Path::new("test.sv"))], + &[], + ) + .unwrap(); + assert!(!e.generic_bindings.is_empty()); + let tasks = TaskTiming::new(std::slice::from_ref(&source)); + assert_eq!( + tasks.resolve(&source, source.find("scaled(v)").unwrap(), "scaled"), + Some(false) + ); + } + #[test] fn modport_formals_resolve_their_interface_methods() { let source="interface Scale;function automatic bit scaled(input bit v);return v;endfunction modport user(import scaled);endinterface module User(Scale.user s,input bit clk, v,output bit q);always @(posedge clk)q<=s.scaled(v);endmodule".to_owned(); let tasks = TaskTiming::new(std::slice::from_ref(&source)); diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 9bc75dd8472..aff9c5f226d 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -961,3 +961,39 @@ endmodule"#) endmodule "#) (top Top)(set v 2)(set clk 1)(run_until 0)(assert_eq q 10)) + +(case generic_interface_methods_keep_setup_edges + (source "generic_interface_methods_keep_setup_edges.sv" #" + interface Scale #(parameter int K=5); + logic[3:0] base; + function automatic logic[3:0] scaled(input logic[3:0] v);return base+v*K;endfunction + modport user(import scaled); + endinterface + module User(interface s,input bit clk,input logic[3:0] v,output logic[3:0] q); + always @(posedge clk)q<=s.scaled(v); + endmodule + module Top(input bit clk,input logic[3:0] v,output logic[3:0] q); + Scale #(.K(5)) s(); + assign s.base=0; + User u(.s(s),.clk(clk),.v(v),.q(q)); + endmodule + "#) + (top Top)(set v 2)(set clk 1)(run_until 0)(assert_eq q 10)) + +(case inherited_interface_methods_keep_setup_edges + (source "inherited_interface_methods_keep_setup_edges.sv" #" + interface Scale #(parameter int K=5); + logic[3:0] base; + function automatic logic[3:0] scaled(input logic[3:0] v);return base+v*K;endfunction + modport user(import scaled); + endinterface + module User(Scale.user unused, s,input bit clk,input logic[3:0] v,output logic[3:0] q); + always @(posedge clk)q<=s.scaled(v); + endmodule + module Top(input bit clk,input logic[3:0] v,output logic[3:0] q); + Scale #(.K(5)) s(); + assign s.base=0; + User u(.unused(s),.s(s),.clk(clk),.v(v),.q(q)); + endmodule + "#) + (top Top)(set v 2)(set clk 1)(run_until 0)(assert_eq q 10)) diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index fb0bb74c785..4f18957498c 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -614,6 +614,8 @@ "interfaces::reads_undriven_interface_members_as_unknown", "interfaces::rewrites_nested_references_and_keeps_declaration_functions", "interfaces::runs_interface_processes_once_per_array_element", + "timing::generic_interface_methods_keep_setup_edges", + "timing::inherited_interface_methods_keep_setup_edges", "timing::interface_modport_methods_keep_setup_edges" ] } diff --git a/crates/celox-test-suite/verification/sv/limitations/icarus.json b/crates/celox-test-suite/verification/sv/limitations/icarus.json index 2b215ffadff..45d032cb203 100644 --- a/crates/celox-test-suite/verification/sv/limitations/icarus.json +++ b/crates/celox-test-suite/verification/sv/limitations/icarus.json @@ -9,7 +9,7 @@ "unexpected_accept": 1, "mismatch": 14, "emission_error": 0, - "compile_error": 105, + "compile_error": 107, "runtime_error": 3, "unsupported": 0, "ignored": 0 @@ -1163,6 +1163,22 @@ "name": "timing::interface_modport_methods_keep_setup_edges", "phase": "compile", "status": "compile_error" + }, + { + "category": "Sequential", + "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:6: sorry: modport task/function ports are not yet supported.\n/source_0.sv:8: syntax error\n/source_0.sv:8: Errors in port declarations.\n", + "expectation": "Simulation", + "name": "timing::generic_interface_methods_keep_setup_edges", + "phase": "compile", + "status": "compile_error" + }, + { + "category": "Sequential", + "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:6: sorry: modport task/function ports are not yet supported.\n/source_0.sv:8: syntax error\n/source_0.sv:8: Errors in port declarations.\n", + "expectation": "Simulation", + "name": "timing::inherited_interface_methods_keep_setup_edges", + "phase": "compile", + "status": "compile_error" } ] } diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 435cb96d329..23605bf10c4 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -179,3 +179,7 @@ sv_backends! { } sv_backends! { fn interface_modport_methods_keep_setup_edges(sim) { @case "timing::interface_modport_methods_keep_setup_edges"; } } + +sv_backends! { fn generic_interface_methods_keep_setup_edges(sim) { @case "timing::generic_interface_methods_keep_setup_edges"; } } + +sv_backends! { fn inherited_interface_methods_keep_setup_edges(sim) { @case "timing::inherited_interface_methods_keep_setup_edges"; } } From 9fa23635b19a24dc5c5381991abc8046ffb35970 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 01:17:36 +0900 Subject: [PATCH 46/75] fix(runtime): synchronize lazy-read finish when settling --- .../src/sv/cases/timing.vtest | 14 +++++++ crates/celox/src/simulation.rs | 38 +++++++++++++++++++ .../tests/frontends/systemverilog/timing.rs | 2 + 3 files changed, 54 insertions(+) diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index aff9c5f226d..e1579894035 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -997,3 +997,17 @@ endmodule"#) endmodule "#) (top Top)(set v 2)(set clk 1)(run_until 0)(assert_eq q 10)) + +(case pure_function_rhs_preserves_distinct_write_times + (source "pure-timed-writes.sv" #" + module Child(output bit[1:0]q); + function automatic bit one();return 1;endfunction + initial begin #1;q[0]=one();end + initial begin #2;q[1]=one();end + endmodule + module Top(output bit[7:0]seen); + wire[1:0]q;Child u(.q(q)); + initial forever begin @(q[0]^q[1]);seen=seen+1;end + endmodule + "#) + (top Top)(run_until 1)(assert_eq seen 1)(run_until 2)(assert_eq seen 2)) diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 2455a4e8cfc..62b7452751f 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -516,6 +516,14 @@ impl Simulation { /// follow, as [`Self::step`] does before advancing. Time does not /// advance. pub fn settle(&mut self) -> Result<(), RuntimeErrorCode> { + // A lazy output read can settle the host write and leave only its + // finish event pending. Synchronize termination before the clean path. + if self.simulator.has_pending_runtime_finish() { + self.state.finish(); + } + if self.state.is_finished() { + return Ok(()); + } let time = self.state.time(); if self.simulator.dirty || !self.simulator.backend.get_triggered_bits().is_empty() @@ -2682,3 +2690,33 @@ mod active_feedback_review_tests { } } } + +#[cfg(all(test, feature = "systemverilog"))] +mod lazy_finish_settle_review { + use super::*; + #[test] + fn settle_recognizes_finish_after_lazy_reads() { + let source = "module Top(input bit go,output bit y);always_comb begin y=go;if(go)$finish;end endmodule"; + fn check(mut sim: Simulation) { + sim.run_until(0).unwrap(); + let go = sim.signal("go"); + let y = sim.signal("y"); + sim.modify(|io| io.set(go, 1u8)).unwrap(); + assert_eq!(sim.get(y), 1u8.into()); + sim.settle().unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.step().unwrap(), None); + } + let build = || { + Simulator::from_sv_sources( + vec![(source, std::path::Path::new("lazy-finish.sv"))], + "Top", + ) + }; + check(Simulation::new(build().build_interpreter().unwrap())); + check(Simulation::new(build().build_cranelift().unwrap())); + check(Simulation::new(build().build_wasm().unwrap())); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap())); + } +} diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 23605bf10c4..de58f7dd268 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -183,3 +183,5 @@ sv_backends! { fn interface_modport_methods_keep_setup_edges(sim) { @case "timin sv_backends! { fn generic_interface_methods_keep_setup_edges(sim) { @case "timing::generic_interface_methods_keep_setup_edges"; } } sv_backends! { fn inherited_interface_methods_keep_setup_edges(sim) { @case "timing::inherited_interface_methods_keep_setup_edges"; } } + +sv_backends! { fn pure_function_rhs_preserves_distinct_write_times(sim) { @case "timing::pure_function_rhs_preserves_distinct_write_times"; } } From c904573ac7b32ccf3bb337c4a3a4c4cb0fc7a5b6 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 01:44:50 +0900 Subject: [PATCH 47/75] test(sv): cover conditional writes at distinct activation times --- crates/celox-test-suite/src/sv/cases/timing.vtest | 13 +++++++++++++ .../celox/tests/frontends/systemverilog/timing.rs | 2 ++ 2 files changed, 15 insertions(+) diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index e1579894035..fba86cc5923 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -1011,3 +1011,16 @@ endmodule"#) endmodule "#) (top Top)(run_until 1)(assert_eq seen 1)(run_until 2)(assert_eq seen 2)) + +(case conditional_writes_preserve_distinct_activation_times + (source "conditional-writes.sv" #" + module Child(input bit sel,output bit[1:0]q); + initial begin #1;if(sel)q[0]=1;else q[0]=0;end + initial begin #2;q[1]=1;end + endmodule + module Top(input bit sel,output bit[7:0]seen); + wire[1:0]q;Child u(.sel(sel),.q(q)); + initial forever begin @(q[0]^q[1]);seen=seen+1;end + endmodule + "#) + (top Top)(set sel 1)(run_until 1)(assert_eq seen 1)(run_until 2)(assert_eq seen 2)) diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index de58f7dd268..681d6316039 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -185,3 +185,5 @@ sv_backends! { fn generic_interface_methods_keep_setup_edges(sim) { @case "timin sv_backends! { fn inherited_interface_methods_keep_setup_edges(sim) { @case "timing::inherited_interface_methods_keep_setup_edges"; } } sv_backends! { fn pure_function_rhs_preserves_distinct_write_times(sim) { @case "timing::pure_function_rhs_preserves_distinct_write_times"; } } + +sv_backends! { fn conditional_writes_preserve_distinct_activation_times(sim) { @case "timing::conditional_writes_preserve_distinct_activation_times"; } } From 81929f9e52883b21dde4291a7c93c160052b4723 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 01:59:16 +0900 Subject: [PATCH 48/75] test(sv): cover fixed activation times across case branches --- crates/celox-test-suite/src/sv/cases/timing.vtest | 13 +++++++++++++ .../celox/tests/frontends/systemverilog/timing.rs | 2 ++ 2 files changed, 15 insertions(+) diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index fba86cc5923..88a69cca9c2 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -1024,3 +1024,16 @@ endmodule"#) endmodule "#) (top Top)(set sel 1)(run_until 1)(assert_eq seen 1)(run_until 2)(assert_eq seen 2)) + +(case case_writes_preserve_distinct_activation_times + (source "case-writes.sv" #" + module Child(input bit[1:0]sel,output bit[1:0]q); + initial begin #1;case(sel) 0:q[0]=0;1:q[0]=1;default:q[0]=1;endcase end + initial begin #2;q[1]=1;end + endmodule + module Top(input bit[1:0]sel,output bit[7:0]seen); + wire[1:0]q;Child u(.sel(sel),.q(q)); + initial forever begin @(q[0]^q[1]);seen=seen+1;end + endmodule + "#) + (top Top)(set sel 1)(run_until 1)(assert_eq seen 1)(run_until 2)(assert_eq seen 2)) diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 681d6316039..d87408675a7 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -187,3 +187,5 @@ sv_backends! { fn inherited_interface_methods_keep_setup_edges(sim) { @case "tim sv_backends! { fn pure_function_rhs_preserves_distinct_write_times(sim) { @case "timing::pure_function_rhs_preserves_distinct_write_times"; } } sv_backends! { fn conditional_writes_preserve_distinct_activation_times(sim) { @case "timing::conditional_writes_preserve_distinct_activation_times"; } } + +sv_backends! { fn case_writes_preserve_distinct_activation_times(sim) { @case "timing::case_writes_preserve_distinct_activation_times"; } } From 7fab9384569764af808051743541261eebc638ac Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 02:39:24 +0900 Subject: [PATCH 49/75] fix(test): settle staged finish within run_to_finish and cover process waves --- crates/celox-test-suite/src/sv/cases/timing.vtest | 12 ++++++++++++ crates/celox/tests/frontends/systemverilog/suite.rs | 3 ++- crates/celox/tests/frontends/systemverilog/timing.rs | 6 ++++++ 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 88a69cca9c2..a2242d3268b 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -1037,3 +1037,15 @@ endmodule"#) endmodule "#) (top Top)(set sel 1)(run_until 1)(assert_eq seen 1)(run_until 2)(assert_eq seen 2)) + +(case staged_wildcard_finish_waits_for_startup + (source "staged-finish.sv" #"module Top(input bit go,output bit seen);always @* begin seen=go;if(go)$finish;end endmodule"#) + (top Top)(set go 1)(run_to_finish)(assert_eq seen 1)) + +(case constant_repeat_writes_preserve_distinct_activation_times + (source "constant_repeat_writes_preserve_distinct_activation_times.sv" #"module Child(output bit[1:0]q);initial begin #1;repeat(1)q[0]=1;end initial begin #2;q[1]=1;end endmodule module Top(output bit[7:0]seen);wire[1:0]q;Child u(.q(q));initial forever begin @(q[0]^q[1]);seen=seen+1;end endmodule"#) + (top Top)(run_until 1)(assert_eq seen 1)(run_until 2)(assert_eq seen 2)) + +(case separate_comb_assignments_preserve_selected_dependencies + (source "separate_comb_assignments_preserve_selected_dependencies.sv" #"module Child(input bit a,b,output bit[1:0]q);always_comb begin q[0]=a;q[1]=b;end endmodule module Top(output bit[7:0]seen);bit a,b;wire[1:0]q;Child u(.a(a),.b(b),.q(q));initial begin #1;b=1;b=0;#1;a=1;end initial forever begin @(q[0]);seen=seen+1;end endmodule"#) + (top Top)(run_until 1)(assert_eq seen 0)(run_until 2)(assert_eq seen 1)) diff --git a/crates/celox/tests/frontends/systemverilog/suite.rs b/crates/celox/tests/frontends/systemverilog/suite.rs index 96634124ccb..beaef179704 100644 --- a/crates/celox/tests/frontends/systemverilog/suite.rs +++ b/crates/celox/tests/frontends/systemverilog/suite.rs @@ -125,7 +125,8 @@ impl Backend for TimedBackend { } fn run_to_finish(&mut self) -> Result<()> { - self.capture_events()?; + // Draining dirty state would evaluate staged writes before this + // operation begins. Check prior finish, then settle within the run. if self.finished() { return Err( "run_to_finish: the design already finished before the operation began".into(), diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index d87408675a7..259aabbf9aa 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -189,3 +189,9 @@ sv_backends! { fn pure_function_rhs_preserves_distinct_write_times(sim) { @case sv_backends! { fn conditional_writes_preserve_distinct_activation_times(sim) { @case "timing::conditional_writes_preserve_distinct_activation_times"; } } sv_backends! { fn case_writes_preserve_distinct_activation_times(sim) { @case "timing::case_writes_preserve_distinct_activation_times"; } } + +sv_backends! { fn staged_wildcard_finish_waits_for_startup(sim) { @case "timing::staged_wildcard_finish_waits_for_startup"; } } + +sv_backends! { fn constant_repeat_writes_preserve_distinct_activation_times(sim) { @case "timing::constant_repeat_writes_preserve_distinct_activation_times"; } } + +sv_backends! { fn separate_comb_assignments_preserve_selected_dependencies(sim) { @case "timing::separate_comb_assignments_preserve_selected_dependencies"; } } From f972be42dd64d5dec4f0d01f92e457b0b2d73212 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 03:53:41 +0900 Subject: [PATCH 50/75] fix(runtime): report falling any-change host domains as active --- crates/celox-runtime/src/simulation.rs | 14 ++---- crates/celox/src/simulation.rs | 67 ++++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 11 deletions(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 2bc3fbe7459..96af7918160 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -450,17 +450,9 @@ impl SimulationState { /// Whether a pending transition activates its clock/reset domain. pub fn has_unsettled_active_edges(&self, backend: &B) -> bool { - self.topo_signals.iter().any(|(signal, id, _)| { - *id != usize::MAX - && self.edge_triggers( - *id, - ( - self.last_clock_values.contains(*id), - self.unknown_clock_values.contains(*id), - ), - sample_event_signal(backend, *signal), - ) - }) + self.topo_signals + .iter() + .any(|(_, id, _)| *id != usize::MAX && self.stable_edge_triggered(backend, *id)) } /// Whether any process is suspended on an event or a condition. diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index afbe4d8403f..4884dfdcce4 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -2805,3 +2805,70 @@ mod post_nba_retrigger_review_tests { check(Simulation::new(build().build_native().unwrap())); } } + +#[cfg(all(test, feature = "systemverilog"))] +mod other_domain_host_step_review { + use super::*; + #[test] + fn any_change_runtime_domains_report_host_falls_at_current_time() { + let source = "module Top(input bit clk,output bit[7:0]count);always @(posedge clk)count<=count+1;endmodule"; + fn check(simulator: Simulator, bounded: bool) { + // The compiled event entry is the FF operation. Its edge policy + // comes from runtime metadata; exercise an any-change domain here. + let signal = simulator.signal("clk"); + let address = simulator.program.get_addr(&[], &["clk"]).unwrap(); + let event = simulator.backend.resolve_event(&address); + let mut kinds = vec![None; simulator.backend.num_events()]; + kinds[event.id()] = Some(celox_design::DomainKind::Other); + let mut info = vec![ + EventInfo { + canonical_id: usize::MAX, + is_cascaded: false, + eval_ff_event: None, + eval_only_event: None, + apply_event: None + }; + simulator.backend.num_events() + ]; + info[event.id()] = EventInfo { + canonical_id: event.id(), + is_cascaded: false, + eval_ff_event: Some(event), + eval_only_event: simulator.backend.resolve_eval_only_event(&address), + apply_event: simulator.backend.resolve_apply_event(&address), + }; + let state = SimulationState::new( + &simulator.backend, + vec![(signal, event.id(), event.id())], + kinds, + info, + Vec::new(), + ); + let mut sim = Simulation { simulator, state }; + sim.set_wide(signal, 1u8.into()); + assert_eq!(sim.step().unwrap(), Some(0)); + assert_eq!(sim.get(sim.signal("count")), 1u8.into()); + sim.set_wide(signal, 0u8.into()); + let time = if bounded { + sim.step_until(0).unwrap() + } else { + sim.step().unwrap() + }; + assert_eq!(sim.get(sim.signal("count")), 2u8.into()); + assert_eq!(time, Some(0)); + } + for bounded in [false, true] { + let build = || { + Simulator::from_sv_sources( + vec![(source, std::path::Path::new("any-change-operation.sv"))], + "Top", + ) + }; + check(build().build_interpreter().unwrap(), bounded); + check(build().build_cranelift().unwrap(), bounded); + check(build().build_wasm().unwrap(), bounded); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap(), bounded); + } + } +} From 97e0c8f91b7f74eb1d01d4e6b2a8dfb1a28216a6 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 04:42:56 +0900 Subject: [PATCH 51/75] fix(timing): defer initial comb finish until design startup --- crates/celox-test-suite/src/frontend.rs | 19 +++++++++-- .../celox-test-suite/src/frontend/timed_ff.rs | 2 +- .../src/sv/cases/timing.vtest | 4 +++ crates/celox/src/simulation.rs | 34 +++++++++++++++++++ .../tests/frontends/systemverilog/timing.rs | 2 ++ 5 files changed, 58 insertions(+), 3 deletions(-) diff --git a/crates/celox-test-suite/src/frontend.rs b/crates/celox-test-suite/src/frontend.rs index f17deb87237..e6645581f97 100644 --- a/crates/celox-test-suite/src/frontend.rs +++ b/crates/celox-test-suite/src/frontend.rs @@ -164,6 +164,7 @@ const TIMED_CONTROL: &str = r#"package celox_suite_timed_control; started = 1; endfunction function automatic void celox_suite_finish_design(input int code = 1); + if (!started) return; finished = 1; case (code) 0: $finish(0); @@ -280,14 +281,28 @@ fn timed_content(source: &str, names: &TimedNames, tasks: &timed_ff::TaskTiming) previous = body_end; continue; } + // Keep the startup dependency in the caller: @* excludes globals + // read only inside a function, unlike always_comb. + if word == "$finish" { + let body_end = + timed_ff::statement_end(source, start).ok_or("unterminated $finish statement")?; + let call = if after_trivia(&source[end..]).starts_with('(') { + format!("{}{}", names.finish, &source[end..body_end]) + } else { + format!("{}();", names.finish) + }; + let replacement = format!("begin if ({}::started) {call} end ", names.package); + output.push_str(&source[previous..start]); + output.push_str(&timed_ff::in_macro(source, start, replacement)); + previous = body_end; + continue; + } let replacement = match word { "initial" => format!("initial wait ({}::started)", names.package), "always" if timed_ff::wildcard_control(source, end, tasks) => continue, "always" => { format!("always wait ({}::started)", names.package) } - "$finish" if after_trivia(&source[end..]).starts_with('(') => names.finish.clone(), - "$finish" => format!("{}()", names.finish), _ => continue, }; output.push_str(&source[previous..start]); diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index add7d399462..cb9915fb94b 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -71,7 +71,7 @@ fn parens(source: &str, begin: usize) -> Option { } None } -fn statement_end(source: &str, at: usize) -> Option { +pub(super) fn statement_end(source: &str, at: usize) -> Option { let at = trivia(source, at); if source[at..].starts_with("(*") { return statement_end(source, parens(source, at)?); diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index a2242d3268b..1d7af74b952 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -1049,3 +1049,7 @@ endmodule"#) (case separate_comb_assignments_preserve_selected_dependencies (source "separate_comb_assignments_preserve_selected_dependencies.sv" #"module Child(input bit a,b,output bit[1:0]q);always_comb begin q[0]=a;q[1]=b;end endmodule module Top(output bit[7:0]seen);bit a,b;wire[1:0]q;Child u(.a(a),.b(b),.q(q));initial begin #1;b=1;b=0;#1;a=1;end initial forever begin @(q[0]);seen=seen+1;end endmodule"#) (top Top)(run_until 1)(assert_eq seen 0)(run_until 2)(assert_eq seen 1)) + +(case staged_always_comb_finish_ignores_initial_inputs + (source "initial-comb-finish.sv" #"module Top(input bit go,output bit seen);always_comb begin seen=go;if(!go)$finish;end initial begin #1;$finish;end endmodule"#) + (top Top)(set go 1)(run_to_finish)(assert_eq seen 1)) diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 004aff248c7..0894b5aaa59 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -558,6 +558,9 @@ impl Simulation { .is_some_and(|next| next <= time) { self.settle_host_writes()?; + if self.state.is_finished() { + return Ok(()); + } let mut drained = false; while self .state @@ -3004,3 +3007,34 @@ mod additional_host_edge_reviews { } } } + +#[cfg(all(test, feature = "systemverilog"))] +mod host_finish_queued_settle_review { + use super::*; + #[test] + fn host_finish_prevents_a_queued_current_time_edge() { + let source = "module Top(input bit go,clk,output bit q);always @(posedge clk)q<=1;always_comb if(go)$finish;endmodule"; + fn check(mut sim: Simulation) { + sim.run_until(0).unwrap(); + let go = sim.signal("go"); + let q = sim.signal("q"); + sim.schedule("clk", 0, 1).unwrap(); + sim.set_wide(go, 1u8.into()); + sim.settle().unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.get(q), 0u8.into()); + assert_eq!(sim.get(sim.signal("clk")), 0u8.into()); + } + let build = || { + Simulator::from_sv_sources( + vec![(source, std::path::Path::new("queued-finish.sv"))], + "Top", + ) + }; + check(Simulation::new(build().build_interpreter().unwrap())); + check(Simulation::new(build().build_cranelift().unwrap())); + check(Simulation::new(build().build_wasm().unwrap())); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap())); + } +} diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 259aabbf9aa..8439b4bb6e2 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -195,3 +195,5 @@ sv_backends! { fn staged_wildcard_finish_waits_for_startup(sim) { @case "timing: sv_backends! { fn constant_repeat_writes_preserve_distinct_activation_times(sim) { @case "timing::constant_repeat_writes_preserve_distinct_activation_times"; } } sv_backends! { fn separate_comb_assignments_preserve_selected_dependencies(sim) { @case "timing::separate_comb_assignments_preserve_selected_dependencies"; } } + +sv_backends! { fn staged_always_comb_finish_ignores_initial_inputs(sim) { @case "timing::staged_always_comb_finish_ignores_initial_inputs"; } } From ed95110952a1e0f18447ae2dd1a99d5fc7e2f9f1 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 05:37:49 +0900 Subject: [PATCH 52/75] test(timing): cover bounded for waves and saved host edges --- crates/celox-runtime/src/state_file.rs | 19 ++++++++++++++ .../src/sv/cases/timing.vtest | 4 +++ crates/celox/src/simulation.rs | 25 ++++++++++++------- .../tests/frontends/systemverilog/timing.rs | 2 ++ 4 files changed, 41 insertions(+), 9 deletions(-) diff --git a/crates/celox-runtime/src/state_file.rs b/crates/celox-runtime/src/state_file.rs index 4d1052c0b10..a12230995a4 100644 --- a/crates/celox-runtime/src/state_file.rs +++ b/crates/celox-runtime/src/state_file.rs @@ -540,6 +540,25 @@ mod tests { assert_eq!(again, bytes); } + #[test] + fn captured_edges_preserve_legacy_and_explicit_unknown_baselines() { + for unknown in [None, Some(vec!["clk".into()])] { + let mut file = sample(); + let schedule = file.schedule.as_mut().unwrap(); + schedule.captured_edges = vec!["clk".into()]; + schedule.unknown_events = unknown; + let mut bytes = Vec::new(); + file.write_to(&mut bytes).unwrap(); + assert_eq!(StateFile::read_from(bytes.as_slice()).unwrap(), file); + if file.schedule.as_ref().unwrap().unknown_events.is_none() { + // #1158's version-2 captured-edge encoding has no unknown marker. + assert_eq!(bytes.pop(), Some(0)); + bytes[8..10].copy_from_slice(&2u16.to_le_bytes()); + assert_eq!(StateFile::read_from(bytes.as_slice()).unwrap(), file); + } + } + } + #[test] fn round_trips() { let file = sample(); diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 1d7af74b952..2bf17f245af 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -1053,3 +1053,7 @@ endmodule"#) (case staged_always_comb_finish_ignores_initial_inputs (source "initial-comb-finish.sv" #"module Top(input bit go,output bit seen);always_comb begin seen=go;if(!go)$finish;end initial begin #1;$finish;end endmodule"#) (top Top)(set go 1)(run_to_finish)(assert_eq seen 1)) + +(case constant_for_writes_preserve_distinct_activation_times + (source "constant-for-times.sv" #"module Child(output bit[1:0]q);initial begin #1;for(int i=0;i<1;i++)q[0]=1;end initial begin #2;q[1]=1;end endmodule module Top(output bit[7:0]seen);wire[1:0]q;Child u(.q(q));initial forever begin @(q[0]^q[1]);seen=seen+1;end endmodule"#) + (top Top)(run_until 1)(assert_eq seen 1)(run_until 2)(assert_eq seen 2)) diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index d1eb1cd75eb..08d08aac618 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -323,8 +323,9 @@ impl Simulation { if self.has_processes() { return Err(StateError::Processes); } + let was_dirty = self.simulator.dirty; let mut file = self.simulator.save_state()?; - self.synchronize_runtime_finish(); + self.synchronize_runtime_finish(was_dirty); let parts = self.state.export_schedule(&self.simulator.backend); file.schedule = Some(self.simulator.name_schedule(parts)); Ok(file) @@ -371,14 +372,16 @@ impl Simulation { /// Captures the current state of all signals and writes them to the VCD file. pub fn dump(&mut self, timestamp: u64) { + let was_dirty = self.simulator.dirty; self.simulator.dump(timestamp); - self.synchronize_runtime_finish(); + self.synchronize_runtime_finish(was_dirty); } /// See [`Simulator::try_dump`]. pub fn try_dump(&mut self, timestamp: u64) -> Result<(), crate::simulator::DumpError> { + let was_dirty = self.simulator.dirty; let result = self.simulator.try_dump(timestamp); - self.synchronize_runtime_finish(); + self.synchronize_runtime_finish(was_dirty); result } @@ -396,10 +399,10 @@ impl Simulation { self.simulator.signal(path) } - fn synchronize_runtime_finish(&mut self) { + fn synchronize_runtime_finish(&mut self, was_dirty: bool) { if self.simulator.has_pending_runtime_finish() { self.state.finish(); - } else if !self.simulator.dirty && !self.state.is_finished() { + } else if was_dirty && !self.simulator.dirty && !self.state.is_finished() { self.state .sample_waiting_events(&mut self.simulator) .unwrap(); @@ -409,12 +412,13 @@ impl Simulation { /// Retrieves the current value of a variable using a pre-resolved [`SignalRef`] handle. pub fn get(&mut self, signal: SignalRef) -> num_bigint::BigUint { + let was_dirty = self.simulator.dirty; let value = if self.state.is_finished() { self.simulator.backend.get(signal) } else { self.simulator.get(signal) }; - self.synchronize_runtime_finish(); + self.synchronize_runtime_finish(was_dirty); value } @@ -423,12 +427,13 @@ impl Simulation { &mut self, signal: SignalRef, ) -> (num_bigint::BigUint, num_bigint::BigUint) { + let was_dirty = self.simulator.dirty; let value = if self.state.is_finished() { self.simulator.backend.get_four_state(signal) } else { self.simulator.get_four_state(signal) }; - self.synchronize_runtime_finish(); + self.synchronize_runtime_finish(was_dirty); value } @@ -453,8 +458,9 @@ impl Simulation { where F: FnOnce(&mut crate::IOContext), { + let was_dirty = self.simulator.dirty; let result = self.simulator.modify(f); - self.synchronize_runtime_finish(); + self.synchronize_runtime_finish(was_dirty); result } @@ -704,12 +710,13 @@ impl Simulation { /// Takes the runtime events (`$display`, messages, `$finish`, ...) the /// design emitted since the last call, in emission order. pub fn drain_runtime_events(&mut self) -> Vec { + let was_dirty = self.simulator.dirty; let events = if self.state.is_finished() { self.simulator.drain_runtime_events_without_evaluation() } else { self.simulator.drain_runtime_events() }; - self.synchronize_runtime_finish(); + self.synchronize_runtime_finish(was_dirty); events } diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 8439b4bb6e2..a8fc3bce533 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -197,3 +197,5 @@ sv_backends! { fn constant_repeat_writes_preserve_distinct_activation_times(sim) sv_backends! { fn separate_comb_assignments_preserve_selected_dependencies(sim) { @case "timing::separate_comb_assignments_preserve_selected_dependencies"; } } sv_backends! { fn staged_always_comb_finish_ignores_initial_inputs(sim) { @case "timing::staged_always_comb_finish_ignores_initial_inputs"; } } + +sv_backends! { fn constant_for_writes_preserve_distinct_activation_times(sim) { @case "timing::constant_for_writes_preserve_distinct_activation_times"; } } From f1e05de4bff4a3874501cb5bd63a7bcbca44bc81 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 06:52:45 +0900 Subject: [PATCH 53/75] test(sv): share untimed task activation regressions --- crates/celox-test-suite/src/sv/cases/timing.vtest | 8 ++++++++ crates/celox/tests/frontends/systemverilog/timing.rs | 4 ++++ 2 files changed, 12 insertions(+) diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 2bf17f245af..a0bf0f847c3 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -1057,3 +1057,11 @@ endmodule"#) (case constant_for_writes_preserve_distinct_activation_times (source "constant-for-times.sv" #"module Child(output bit[1:0]q);initial begin #1;for(int i=0;i<1;i++)q[0]=1;end initial begin #2;q[1]=1;end endmodule module Top(output bit[7:0]seen);wire[1:0]q;Child u(.q(q));initial forever begin @(q[0]^q[1]);seen=seen+1;end endmodule"#) (top Top)(run_until 1)(assert_eq seen 1)(run_until 2)(assert_eq seen 2)) + +(case untimed_tasks_preserve_distinct_activation_times + (source "untimed_tasks_preserve_distinct_activation_times.sv" #"module Child(output bit[1:0]q);task automatic noop();endtask initial begin #1;noop();q[0]=1;end initial begin #2;noop();q[1]=1;end endmodule module Top(output bit[7:0]seen);wire[1:0]q;Child u(.q(q));initial forever begin @(q[0]^q[1]);seen=seen+1;end endmodule"#) + (top Top)(run_until 1)(assert_eq seen 1)(run_until 2)(assert_eq seen 2)) + +(case untimed_task_copyback_preserves_distinct_activation_times + (source "untimed_task_copyback_preserves_distinct_activation_times.sv" #"module Child(output bit[1:0]q);task automatic drive(output bit x);x=1;endtask initial begin #1;drive(q[0]);end initial begin #2;drive(q[1]);end endmodule module Top(output bit[7:0]seen);wire[1:0]q;Child u(.q(q));initial forever begin @(q[0]^q[1]);seen=seen+1;end endmodule"#) + (top Top)(run_until 1)(assert_eq seen 1)(run_until 2)(assert_eq seen 2)) diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index a8fc3bce533..9ff045b59ea 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -199,3 +199,7 @@ sv_backends! { fn separate_comb_assignments_preserve_selected_dependencies(sim) sv_backends! { fn staged_always_comb_finish_ignores_initial_inputs(sim) { @case "timing::staged_always_comb_finish_ignores_initial_inputs"; } } sv_backends! { fn constant_for_writes_preserve_distinct_activation_times(sim) { @case "timing::constant_for_writes_preserve_distinct_activation_times"; } } + +sv_backends! { fn untimed_tasks_preserve_distinct_activation_times(sim) { @case "timing::untimed_tasks_preserve_distinct_activation_times"; } } + +sv_backends! { fn untimed_task_copyback_preserves_distinct_activation_times(sim) { @case "timing::untimed_task_copyback_preserves_distinct_activation_times"; } } From e3c4b914a5e63a5b0e4d1d6066b40471b9df7e13 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 07:09:01 +0900 Subject: [PATCH 54/75] fix(timing): stage combinational effects and validate loaded schedules --- crates/celox-test-suite/src/frontend.rs | 13 ++++ .../src/sv/cases/timing.vtest | 4 ++ crates/celox/src/simulation.rs | 72 +++++++++++++++++++ crates/celox/src/simulator/state_file.rs | 14 ++++ 4 files changed, 103 insertions(+) diff --git a/crates/celox-test-suite/src/frontend.rs b/crates/celox-test-suite/src/frontend.rs index e6645581f97..1359a1a6a85 100644 --- a/crates/celox-test-suite/src/frontend.rs +++ b/crates/celox-test-suite/src/frontend.rs @@ -281,6 +281,19 @@ fn timed_content(source: &str, names: &TimedNames, tasks: &timed_ff::TaskTiming) previous = body_end; continue; } + if word == "always_comb" { + let body_end = + timed_ff::statement_end(source, end).ok_or("unterminated always_comb statement")?; + let body = timed_content(&source[end..body_end], names, tasks)?; + let replacement = format!( + "always_comb begin if ({}::started) begin {body} end end", + names.package + ); + output.push_str(&source[previous..start]); + output.push_str(&timed_ff::in_macro(source, start, replacement)); + previous = body_end; + continue; + } // Keep the startup dependency in the caller: @* excludes globals // read only inside a function, unlike always_comb. if word == "$finish" { diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index a0bf0f847c3..e784d04f099 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -1065,3 +1065,7 @@ endmodule"#) (case untimed_task_copyback_preserves_distinct_activation_times (source "untimed_task_copyback_preserves_distinct_activation_times.sv" #"module Child(output bit[1:0]q);task automatic drive(output bit x);x=1;endtask initial begin #1;drive(q[0]);end initial begin #2;drive(q[1]);end endmodule module Top(output bit[7:0]seen);wire[1:0]q;Child u(.q(q));initial forever begin @(q[0]^q[1]);seen=seen+1;end endmodule"#) (top Top)(run_until 1)(assert_eq seen 1)(run_until 2)(assert_eq seen 2)) + +(case staged_always_comb_side_effects_wait_for_setup + (source "staged-comb-effects.sv" #"module Top(input bit go,output bit seen);always_comb begin seen=go;if(!go)begin $display("early");$fatal(1,"early");end end initial begin #1;$finish;end endmodule"#) + (top Top)(set go 1)(run_to_finish)(assert_eq seen 1)(expect_output "")) diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 08d08aac618..53f54738d38 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -671,6 +671,9 @@ impl Simulation { self.state.settle_at(&mut self.simulator, time)?; } } + if self.state.is_finished() { + return Ok(()); + } while let Some(next_time) = self.state.next_event_time() { if next_time > end_time { break; @@ -3149,3 +3152,72 @@ mod lazy_read_and_ff_edges_review { check(Simulation::new(build().build_native().unwrap())); } } + +#[cfg(all(test, feature = "systemverilog"))] +mod loaded_schedule_and_finish_review { + use super::*; + #[test] + fn ff_finish_keeps_later_queued_event_unapplied() { + let source = "module Top(input bit clk,output bit q);always @(posedge clk)begin q=1;$finish;end endmodule"; + fn check(mut sim: Simulation) { + sim.run_until(0).unwrap(); + sim.schedule("clk", 1, 0).unwrap(); + let clk = sim.signal("clk"); + sim.modify(|io| io.set(clk, 1u8)).unwrap(); + sim.run_until(2).unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.time(), 0); + assert_eq!(sim.get(clk), 1u8.into()); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + } + let build = || { + Simulator::from_sv_sources( + vec![(source, std::path::Path::new("queued-after-finish.sv"))], + "Top", + ) + }; + check(Simulation::new(build().build_interpreter().unwrap())); + check(Simulation::new(build().build_cranelift().unwrap())); + check(Simulation::new(build().build_wasm().unwrap())); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap())); + } + #[test] + fn state_load_rejects_past_events_atomically() { + let source = "module Top(input bit clk,output bit q);always @(posedge clk)q<=!q;endmodule"; + fn check(mut sim: Simulation) { + sim.run_until(5).unwrap(); + sim.schedule("clk", 6, 1).unwrap(); + let file = sim.save_state().unwrap(); + for periodic in [false, true] { + let mut corrupt = file.clone(); + let record = corrupt.schedule.as_mut().unwrap(); + if periodic { + let mut e = record.events[0].clone(); + e.time = 4; + record.periodic.push((e, 1)); + } else { + record.events[0].time = 4; + } + let before = sim.save_state().unwrap(); + assert!(sim.load_state(&corrupt).is_err()); + assert_eq!(sim.save_state().unwrap(), before); + assert_eq!(sim.time(), 5); + } + sim.load_state(&file).unwrap(); + sim.run_until(6).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + } + let build = || { + Simulator::from_sv_sources( + vec![(source, std::path::Path::new("past-loaded-event.sv"))], + "Top", + ) + }; + check(Simulation::new(build().build_interpreter().unwrap())); + check(Simulation::new(build().build_cranelift().unwrap())); + check(Simulation::new(build().build_wasm().unwrap())); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap())); + } +} diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index 8cbec48a622..232a09bf780 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -385,6 +385,20 @@ impl Simulator { &self, record: &ScheduleRecord, ) -> Result, StateError> { + if let Some(event) = record + .events + .iter() + .chain(record.periodic.iter().map(|(event, _)| event)) + .find(|event| event.time < record.time) + { + return Err(StateError::Runtime(RuntimeErrorCode::Runtime { + message: format!( + "cannot load an event in the past: {} before {}", + event.time, record.time + ), + signals: Vec::new(), + })); + } let events: HashMap = self .backend .id_to_event_slice() From 4a593458e13bc7cacbbd0dc31c44e2990328cb25 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 07:59:55 +0900 Subject: [PATCH 55/75] test(suite): fail timed runs on continuing assertions --- .../src/sv/cases/timing.vtest | 8 ++++++ .../tests/frontends/systemverilog/suite.rs | 28 +++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index e784d04f099..1698d8c2903 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -1069,3 +1069,11 @@ endmodule"#) (case staged_always_comb_side_effects_wait_for_setup (source "staged-comb-effects.sv" #"module Top(input bit go,output bit seen);always_comb begin seen=go;if(!go)begin $display("early");$fatal(1,"early");end end initial begin #1;$finish;end endmodule"#) (top Top)(set go 1)(run_to_finish)(assert_eq seen 1)(expect_output "")) + +(case statically_satisfied_waits_preserve_distinct_activation_times + (source "true-wait.sv" #"module Child(output bit[1:0]q);initial begin #1;wait(1);q[0]=1;end initial begin #2;q[1]=1;end endmodule module Top(output bit[7:0]seen);wire[1:0]q;Child u(.q(q));initial forever begin @(q[0]^q[1]);seen=seen+1;end endmodule"#) + (top Top)(run_until 1)(assert_eq seen 1)(run_until 2)(assert_eq seen 2)) + +(case nba_woken_waiters_sample_before_continuations + (source "nba-waiter-sampling.sv" #"module Child(input bit clk,output bit go);always_ff @(posedge clk)go<=1;endmodule module Top(output bit a,b);bit clk;bit enable=1;wire go;Child child(.clk(clk),.go(go));initial begin #1;clk=1;end initial begin @(posedge(go&enable));a=1;enable=0;end initial begin @(posedge(go&enable));b=1;end endmodule"#) + (top Top)(run_until 1)(assert_eq a 1)(assert_eq b 1)) diff --git a/crates/celox/tests/frontends/systemverilog/suite.rs b/crates/celox/tests/frontends/systemverilog/suite.rs index beaef179704..24c289786a5 100644 --- a/crates/celox/tests/frontends/systemverilog/suite.rs +++ b/crates/celox/tests/frontends/systemverilog/suite.rs @@ -21,6 +21,10 @@ impl TimedBackend { "fatal assertion: {}", String::from_utf8(message.clone()).unwrap_or_else(|_| format!("{message:?}")) )), + RuntimeEvent::AssertContinue { message } => Some(format!( + "failed assertion: {}", + String::from_utf8(message.clone()).unwrap_or_else(|_| format!("{message:?}")) + )), RuntimeEvent::Missed { count } => Some(format!("{count} runtime events were missed")), _ => None, }); @@ -415,3 +419,27 @@ fn buffered_host_fatal_cannot_be_hidden_by_a_later_finish() { ); } } + +#[test] +fn continuing_assertions_cannot_pass_a_timed_finish() { + let source = "module Top;initial begin #1;$error(\"timed failure\");#1;$finish;end endmodule"; + let text = format!( + "(group protocol (category sequential))(case assertion (source \"assertion.sv\" #\"{source}\"#)(top Top)(run_to_finish))" + ); + let case = + celox_test_suite::load_group("assertion.vtest", &text, celox_test_suite::no_std_library)[0]; + for name in [ + "native", + "cranelift", + "native-parallel", + "cranelift-parallel", + "wasm", + ] { + let mut backend = build(&case.design(), name).unwrap(); + let result = backend.run_to_finish(); + assert!( + result.unwrap_err().to_string().contains("timed failure"), + "{name}" + ); + } +} From b8a2e153c0098e68954c8d124f1c2f2a226d8126 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 08:11:44 +0900 Subject: [PATCH 56/75] test(suite): register staged and NBA waiter timing cases --- crates/celox/tests/frontends/systemverilog/timing.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 9ff045b59ea..84640b6a12f 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -203,3 +203,7 @@ sv_backends! { fn constant_for_writes_preserve_distinct_activation_times(sim) { sv_backends! { fn untimed_tasks_preserve_distinct_activation_times(sim) { @case "timing::untimed_tasks_preserve_distinct_activation_times"; } } sv_backends! { fn untimed_task_copyback_preserves_distinct_activation_times(sim) { @case "timing::untimed_task_copyback_preserves_distinct_activation_times"; } } + +sv_backends! { fn statically_satisfied_waits_preserve_distinct_activation_times(sim) { @case "timing::statically_satisfied_waits_preserve_distinct_activation_times"; } } +sv_backends! { fn nba_woken_waiters_sample_before_continuations(sim) { @case "timing::nba_woken_waiters_sample_before_continuations"; } } +sv_backends! { fn staged_always_comb_side_effects_wait_for_setup(sim) { @case "timing::staged_always_comb_side_effects_wait_for_setup"; } } From a650205c4769c5169464a80737a90cb958d554e1 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 08:46:09 +0900 Subject: [PATCH 57/75] fix(runtime): preserve any-change domains in mixed event batches --- crates/celox-runtime/src/simulation.rs | 13 +--- crates/celox/src/simulation.rs | 83 ++++++++++++++++++++++++++ 2 files changed, 85 insertions(+), 11 deletions(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index cd624bb1c37..02fe134c662 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -743,17 +743,8 @@ impl SimulationState { // Pending host writes share this round with current-time scheduled // edges. Record their net transitions before scheduled values replace // them and before clearing the backend's transient trigger hints. - for (signal, id, _) in &self.topo_signals { - if *id != usize::MAX - && self.edge_triggers( - *id, - ( - self.last_clock_values.contains(*id), - self.unknown_clock_values.contains(*id), - ), - sample_event_signal(executor.backend(), *signal), - ) - { + for (_, id, _) in &self.topo_signals { + if *id != usize::MAX && self.stable_edge_triggered(executor.backend(), *id) { scheduled_edges.insert(*id); } } diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 7f8013e4d68..09dc796eb42 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -3464,3 +3464,86 @@ mod nba_waiter_sampling_review { check(Simulation::new(build().build_native().unwrap())); } } + +#[cfg(all(test, feature = "systemverilog"))] +mod mixed_other_domain_host_review { + use super::*; + #[test] + fn any_change_host_falls_join_current_time_batches() { + let source = "module Top(input bit clk,queued,output bit[7:0]count,queued_count);always @(posedge clk)count<=count+1;always @(posedge queued)queued_count<=queued_count+1;endmodule"; + fn check(simulator: Simulator, mode: u8) { + // The compiled event entry is the FF operation. Its edge policy + // comes from runtime metadata; exercise an any-change domain here. + let signal = simulator.signal("clk"); + let address = simulator.program.get_addr(&[], &["clk"]).unwrap(); + let event = simulator.backend.resolve_event(&address); + let mut kinds = vec![None; simulator.backend.num_events()]; + kinds[event.id()] = Some(celox_design::DomainKind::Other); + let queued_address = simulator.program.get_addr(&[], &["queued"]).unwrap(); + let queued_event = simulator.backend.resolve_event(&queued_address); + let queued_signal = simulator.signal("queued"); + kinds[queued_event.id()] = Some(celox_design::DomainKind::ClockPosedge); + let mut info = vec![ + EventInfo { + canonical_id: usize::MAX, + is_cascaded: false, + eval_ff_event: None, + eval_only_event: None, + apply_event: None + }; + simulator.backend.num_events() + ]; + info[event.id()] = EventInfo { + canonical_id: event.id(), + is_cascaded: false, + eval_ff_event: Some(event), + eval_only_event: simulator.backend.resolve_eval_only_event(&address), + apply_event: simulator.backend.resolve_apply_event(&address), + }; + info[queued_event.id()] = EventInfo { + canonical_id: queued_event.id(), + is_cascaded: false, + eval_ff_event: Some(queued_event), + eval_only_event: simulator.backend.resolve_eval_only_event(&queued_address), + apply_event: simulator.backend.resolve_apply_event(&queued_address), + }; + let state = SimulationState::new( + &simulator.backend, + vec![ + (signal, event.id(), event.id()), + (queued_signal, queued_event.id(), queued_event.id()), + ], + kinds, + info, + Vec::new(), + ); + let mut sim = Simulation { simulator, state }; + sim.set_wide(signal, 1u8.into()); + assert_eq!(sim.step().unwrap(), Some(0)); + assert_eq!(sim.get(sim.signal("count")), 1u8.into()); + sim.set_wide(signal, 0u8.into()); + sim.schedule("queued", 0, 1).unwrap(); + let time = match mode { + 0 => sim.step().unwrap(), + 1 => sim.step_until(0).unwrap(), + _ => sim.state.step(&mut sim.simulator).unwrap(), + }; + assert_eq!(sim.get(sim.signal("count")), 2u8.into()); + assert_eq!(time, Some(0)); + assert_eq!(sim.get(sim.signal("queued_count")), 1u8.into()); + } + for mode in [0, 1, 2] { + let build = || { + Simulator::from_sv_sources( + vec![(source, std::path::Path::new("any-change-operation.sv"))], + "Top", + ) + }; + check(build().build_interpreter().unwrap(), mode); + check(build().build_cranelift().unwrap(), mode); + check(build().build_wasm().unwrap(), mode); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap(), mode); + } + } +} From c5160a8de07ecedb6bd9ad56357fb4ac5d1e768d Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 16:11:25 +0900 Subject: [PATCH 58/75] test(sv): cover signed repeat counts and retain timing exclusions --- .../src/sv/cases/timing.vtest | 21 ++++++ .../verification/sv/icarus/timing.json | 69 +++++++++++++++++++ .../tests/frontends/systemverilog/timing.rs | 6 ++ 3 files changed, 96 insertions(+) diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 1698d8c2903..482d77ce2cf 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -1077,3 +1077,24 @@ endmodule"#) (case nba_woken_waiters_sample_before_continuations (source "nba-waiter-sampling.sv" #"module Child(input bit clk,output bit go);always_ff @(posedge clk)go<=1;endmodule module Top(output bit a,b);bit clk;bit enable=1;wire go;Child child(.clk(clk),.go(go));initial begin #1;clk=1;end initial begin @(posedge(go&enable));a=1;enable=0;end initial begin @(posedge(go&enable));b=1;end endmodule"#) (top Top)(run_until 1)(assert_eq a 1)(assert_eq b 1)) + +(case negative_repeat_counts_do_not_run_the_body + (source "negative_repeat_counts.sv" #" + module Top(input integer n, output bit [7:0] dynamic_count, literal_count, + zero_count, positive_count); + initial begin + #1; + repeat(n) begin #1; dynamic_count++; end + repeat(-1) begin #1; literal_count++; end + repeat(0) begin #1; zero_count++; end + repeat(2) begin #1; positive_count++; end + end + endmodule + "#) + (top Top) + (set n 0xfffffffe) + (run_until 4) + (assert_eq dynamic_count 0) + (assert_eq literal_count 0) + (assert_eq zero_count 0) + (assert_eq positive_count 2)) diff --git a/crates/celox-test-suite/verification/sv/icarus/timing.json b/crates/celox-test-suite/verification/sv/icarus/timing.json index 49f60cfd1a9..3f34d276c91 100644 --- a/crates/celox-test-suite/verification/sv/icarus/timing.json +++ b/crates/celox-test-suite/verification/sv/icarus/timing.json @@ -77,6 +77,75 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "Icarus 13.0 rejects interface port declarations (syntax error in port declarations), modport function imports (\"sorry: modport task/function ports are not yet supported\") and multidimensional interface instance arrays (\"sorry: Multi-dimensional arrays of instances are not yet supported\"). Verilator passes these cases.", + "expectation": "Simulation", + "known_issue": { + "id": "sv_icarus_interfaces", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 rejects interface port declarations (syntax error in port declarations), modport function imports (\"sorry: modport task/function ports are not yet supported\") and multidimensional interface instance arrays (\"sorry: Multi-dimensional arrays of instances are not yet supported\"). Verilator passes these cases.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "name": "timing::generic_interface_methods_keep_setup_edges", + "phase": "compile", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Icarus 13.0 rejects interface port declarations (syntax error in port declarations), modport function imports (\"sorry: modport task/function ports are not yet supported\") and multidimensional interface instance arrays (\"sorry: Multi-dimensional arrays of instances are not yet supported\"). Verilator passes these cases.", + "expectation": "Simulation", + "known_issue": { + "id": "sv_icarus_interfaces", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 rejects interface port declarations (syntax error in port declarations), modport function imports (\"sorry: modport task/function ports are not yet supported\") and multidimensional interface instance arrays (\"sorry: Multi-dimensional arrays of instances are not yet supported\"). Verilator passes these cases.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "name": "timing::inherited_interface_methods_keep_setup_edges", + "phase": "compile", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Icarus 13.0 rejects interface port declarations (syntax error in port declarations), modport function imports (\"sorry: modport task/function ports are not yet supported\") and multidimensional interface instance arrays (\"sorry: Multi-dimensional arrays of instances are not yet supported\"). Verilator passes these cases.", + "expectation": "Simulation", + "known_issue": { + "id": "sv_icarus_interfaces", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 rejects interface port declarations (syntax error in port declarations), modport function imports (\"sorry: modport task/function ports are not yet supported\") and multidimensional interface instance arrays (\"sorry: Multi-dimensional arrays of instances are not yet supported\"). Verilator passes these cases.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "name": "timing::interface_modport_methods_keep_setup_edges", + "phase": "compile", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 84640b6a12f..ae14dc647af 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -207,3 +207,9 @@ sv_backends! { fn untimed_task_copyback_preserves_distinct_activation_times(sim) sv_backends! { fn statically_satisfied_waits_preserve_distinct_activation_times(sim) { @case "timing::statically_satisfied_waits_preserve_distinct_activation_times"; } } sv_backends! { fn nba_woken_waiters_sample_before_continuations(sim) { @case "timing::nba_woken_waiters_sample_before_continuations"; } } sv_backends! { fn staged_always_comb_side_effects_wait_for_setup(sim) { @case "timing::staged_always_comb_side_effects_wait_for_setup"; } } + +sv_backends! { + fn negative_repeat_counts_do_not_run_the_body(sim) { + @case "timing::negative_repeat_counts_do_not_run_the_body"; + } +} From b7388a963f23ba5256ae5360316c03506ad204f0 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 18:20:43 +0900 Subject: [PATCH 59/75] fix(simulation): report finish after current-time dispatch --- crates/celox/src/simulation.rs | 60 ++++++++++++++++++++++++++++++++-- 1 file changed, 58 insertions(+), 2 deletions(-) diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 17780f8304a..cc521417447 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -536,7 +536,7 @@ impl Simulation { return Ok(None); } if self.state.poll_waiting(&mut self.simulator)? { - return Ok(Some(self.state.time())); + return Ok((!self.state.is_finished()).then_some(self.state.time())); } if self.state.has_unsettled_edges(&self.simulator.backend) { let time = self.state.time(); @@ -549,6 +549,9 @@ impl Simulation { } else { self.state.settle_at(&mut self.simulator, time)?; } + if self.state.is_finished() { + return Ok(None); + } if active || queued { return Ok(Some(time)); } @@ -634,7 +637,7 @@ impl Simulation { return Ok(None); } if self.state.poll_waiting(&mut self.simulator)? { - return Ok(Some(self.state.time())); + return Ok((!self.state.is_finished()).then_some(self.state.time())); } if self.state.has_unsettled_edges(&self.simulator.backend) { let time = self.state.time(); @@ -647,6 +650,9 @@ impl Simulation { } else { self.state.settle_at(&mut self.simulator, time)?; } + if self.state.is_finished() { + return Ok(None); + } if active || queued { return Ok(Some(time)); } @@ -3907,3 +3913,53 @@ mod sampled_host_review { ); } } + +#[cfg(all(test, feature = "systemverilog"))] +mod host_finish_step_review { + use super::*; + + #[test] + fn host_dispatch_reports_finished_without_returning_a_time() { + fn check(mut sim: Simulation) { + sim.run_until(0).unwrap(); + let initial = sim.checkpoint().unwrap(); + let clk = sim.signal("clk"); + for bounded in [false, true] { + sim.restore(&initial).unwrap(); + sim.modify(|io| io.set(clk, 1u8)).unwrap(); + let result = if bounded { + sim.step_until(10) + } else { + sim.step() + }; + assert_eq!(result.unwrap(), None); + assert!(sim.is_finished()); + assert_eq!(sim.time(), 0); + assert_eq!(sim.step().unwrap(), None); + } + } + for body in [ + "initial @(posedge clk)$finish;", + "always @(posedge clk)$finish;", + ] { + let source = format!("module Top(input bit clk);{body} endmodule"); + macro_rules! build { + ($method:ident) => { + check(Simulation::new( + Simulator::from_sv_sources( + vec![(source.as_str(), std::path::Path::new("host-finish.sv"))], + "Top", + ) + .$method() + .unwrap(), + )); + }; + } + build!(build_interpreter); + build!(build_cranelift); + build!(build_wasm); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + build!(build_native); + } + } +} From 23fb4ad2099e6f885f1f22461fefc7ff001958f6 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 19:46:15 +0900 Subject: [PATCH 60/75] fix(suite): gate untimed wildcard effects until setup completes --- crates/celox-test-suite/src/frontend.rs | 16 ++++++++++------ .../celox-test-suite/src/frontend/timed_ff.rs | 14 +++++++------- .../src/sv/cases/timing.vtest | 19 +++++++++++++++++++ .../tests/frontends/systemverilog/timing.rs | 6 ++++++ 4 files changed, 42 insertions(+), 13 deletions(-) diff --git a/crates/celox-test-suite/src/frontend.rs b/crates/celox-test-suite/src/frontend.rs index 1359a1a6a85..ec25a063bfb 100644 --- a/crates/celox-test-suite/src/frontend.rs +++ b/crates/celox-test-suite/src/frontend.rs @@ -281,12 +281,17 @@ fn timed_content(source: &str, names: &TimedNames, tasks: &timed_ff::TaskTiming) previous = body_end; continue; } - if word == "always_comb" { - let body_end = - timed_ff::statement_end(source, end).ok_or("unterminated always_comb statement")?; - let body = timed_content(&source[end..body_end], names, tasks)?; + let wildcard_body = (word == "always") + .then(|| timed_ff::wildcard_body(source, end, tasks)) + .flatten(); + if word == "always_comb" || wildcard_body.is_some() { + let body_start = wildcard_body.unwrap_or(end); + let body_end = timed_ff::statement_end(source, body_start) + .ok_or("unterminated combinational statement")?; + let body = timed_content(&source[body_start..body_end], names, tasks)?; let replacement = format!( - "always_comb begin if ({}::started) begin {body} end end", + "{} begin if ({}::started) begin {body} end end", + &source[start..body_start], names.package ); output.push_str(&source[previous..start]); @@ -312,7 +317,6 @@ fn timed_content(source: &str, names: &TimedNames, tasks: &timed_ff::TaskTiming) } let replacement = match word { "initial" => format!("initial wait ({}::started)", names.package), - "always" if timed_ff::wildcard_control(source, end, tasks) => continue, "always" => { format!("always wait ({}::started)", names.package) } diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index cb9915fb94b..8ec9f961bf1 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -406,10 +406,10 @@ pub(super) fn in_macro(source: &str, start: usize, replacement: String) -> Strin output } -pub(super) fn wildcard_control(source: &str, end: usize, tasks: &TaskTiming) -> bool { +pub(super) fn wildcard_body(source: &str, end: usize, tasks: &TaskTiming) -> Option { let at = trivia(source, end); if source.as_bytes().get(at) != Some(&b'@') { - return false; + return None; } let begin = trivia(source, at + 1); let event_end = if source.as_bytes().get(begin) == Some(&b'*') { @@ -419,12 +419,12 @@ pub(super) fn wildcard_control(source: &str, end: usize, tasks: &TaskTiming) -> { end } else { - return false; - }; - let Some(body_end) = statement_end(source, event_end) else { - return false; + return None; }; - !has_timing(&source[event_end..body_end]) && !tasks.has_timed_call(source, event_end, body_end) + let body_end = statement_end(source, event_end)?; + (!has_timing(&source[event_end..body_end]) + && !tasks.has_timed_call(source, event_end, body_end)) + .then_some(event_end) } fn has_timing(source: &str) -> bool { diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 482d77ce2cf..1384183cee9 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -1098,3 +1098,22 @@ endmodule"#) (assert_eq literal_count 0) (assert_eq zero_count 0) (assert_eq positive_count 2)) + +(case staged_wildcard_side_effects_wait_for_setup + (source "staged-wildcard-effects.sv" #" + module Top(input bit[1:0]go,output bit[1:0]a,b); + wire ready=1'b1; + always @* begin + a=ready?go:0; + if(ready&&!go)begin $display("early star");$fatal(1,"early star");end + end + always @(*) begin + b=ready?go:0; + if(ready&&!go)begin $display("early parens");$fatal(1,"early parens");end + end + initial begin #2;$finish;end + endmodule + "#) + (top Top)(set go 1)(run_until 0)(assert_eq a 1)(assert_eq b 1) + (set go 2)(run_until 1)(assert_eq a 2)(assert_eq b 2) + (run_to_finish)(expect_output "")) diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index ae14dc647af..eb39be831ef 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -213,3 +213,9 @@ sv_backends! { @case "timing::negative_repeat_counts_do_not_run_the_body"; } } + +sv_backends! { + fn staged_wildcard_side_effects_wait_for_setup(sim) { + @case "timing::staged_wildcard_side_effects_wait_for_setup"; + } +} From 13ad4e826baf5e0aff89d36f9cad8f5ea3ad4247 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 21:25:26 +0900 Subject: [PATCH 61/75] fix(suite): defer continuous driver calls until staged startup --- crates/celox-test-suite/src/frontend.rs | 11 +++ .../celox-test-suite/src/frontend/timed_ff.rs | 97 +++++++++++++++++++ .../src/sv/cases/timing.vtest | 36 +++++++ .../tests/frontends/systemverilog/timing.rs | 13 +++ 4 files changed, 157 insertions(+) diff --git a/crates/celox-test-suite/src/frontend.rs b/crates/celox-test-suite/src/frontend.rs index ec25a063bfb..5b550f7bace 100644 --- a/crates/celox-test-suite/src/frontend.rs +++ b/crates/celox-test-suite/src/frontend.rs @@ -273,6 +273,17 @@ fn timed_content(source: &str, names: &TimedNames, tasks: &timed_ff::TaskTiming) if start < previous { continue; } + if matches!( + word, + "assign" | "wire" | "tri" | "tri0" | "tri1" | "wand" | "wor" | "triand" | "trior" + ) && let Some((body_end, replacement)) = + timed_ff::gated_continuous(source, start, end, names) + { + output.push_str(&source[previous..start]); + output.push_str(&timed_ff::in_macro(source, start, replacement)); + previous = body_end; + continue; + } if word == "always_ff" || (word == "always" && timed_ff::edge_control(source, end, tasks)) { let (replacement_start, body_end, replacement) = timed_ff::gated(source, start, end, names, tasks)?; diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index 8ec9f961bf1..10da132d867 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -71,6 +71,103 @@ fn parens(source: &str, begin: usize) -> Option { } None } +// Icarus evaluates function operands in a continuous ternary eagerly. Use +// a procedural gate and retain the original net driver (and its delays and +// strengths). The temporary has the destination's packed assignment width. +pub(super) fn gated_continuous( + source: &str, + start: usize, + end: usize, + names: &TimedNames, +) -> Option<(usize, String)> { + let net_declaration = &source[start..end] != "assign"; + let mut at = end; + let mut depth = 0usize; + let mut lhs_start = end; + let mut lhs_name = None; + let mut rhs = None; + let mut previous = start; + let mut output = String::new(); + let mut drivers = String::new(); + while at < source.len() { + if skip_token(source, &mut at) { + continue; + } + match source.as_bytes()[at] { + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' => depth = depth.checked_sub(1)?, + b'=' if depth == 0 && rhs.is_none() => { + let left = source[lhs_start..at].trim(); + lhs_name = Some(if net_declaration { + // Net declaration assignments name an entire net. + sv_words(left).last()?.2.to_owned() + } else { + // Skip optional drive strength and delay controls. + let mut begin = trivia(left, 0); + if left.as_bytes().get(begin) == Some(&b'(') { + begin = trivia(left, parens(left, begin)?); + } + if left.as_bytes().get(begin) == Some(&b'#') { + begin = trivia(left, begin + 1); + begin = if left.as_bytes().get(begin) == Some(&b'(') { + trivia(left, parens(left, begin)?) + } else { + let tail = &left[begin..]; + begin + tail.find(char::is_whitespace)? + }; + } + left[begin..].trim().to_owned() + }); + rhs = Some(at + 1); + } + b',' | b';' if depth == 0 => { + if let Some(begin) = rhs.take() { + let expression = &source[begin..at]; + let calls = sv_words(expression) + .into_iter() + .any(|(_, end, _)| after_trivia(&expression[end..]).starts_with('(')); + if calls { + let lhs = lhs_name.take()?; + let mut suffix = at; + let name = loop { + let name = format!("{}_driver_{suffix}", names.package); + if !sv_words(source).iter().any(|(_, _, word)| *word == name) { + break name; + } + suffix += 1; + }; + drivers.push_str(&format!( + "reg [$bits({lhs})-1:0] {name};\nalways @* begin if ({}::started) {name} = {expression}; end\n", names.package + )); + output.push_str(&source[previous..begin]); + output.push_str(&format!(" {name}")); + previous = at; + } + } + lhs_start = at + 1; + if source.as_bytes()[at] == b';' { + if previous == start { + return None; + } + output.push_str(&source[previous..=at]); + let replacement = format!("{drivers}{output}"); + return Some(( + at + 1, + if single_generate_body(source, start) { + format!("begin\n{replacement}\nend") + } else { + replacement + }, + )); + } + } + _ => {} + } + at += 1; + } + None +} + pub(super) fn statement_end(source: &str, at: usize) -> Option { let at = trivia(source, at); if source[at..].starts_with("(*") { diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 1384183cee9..9729f2b65d4 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -1117,3 +1117,39 @@ endmodule"#) (top Top)(set go 1)(run_until 0)(assert_eq a 1)(assert_eq b 1) (set go 2)(run_until 1)(assert_eq a 2)(assert_eq b 2) (run_to_finish)(expect_output "")) + +(case staged_continuous_side_effects_wait_for_setup + (source "staged-continuous-effects.sv" #" + module Top(input bit[7:0]go,output wire[7:0]a,b); + function automatic bit[7:0]checked(input bit[7:0]value); + if(value==0)begin $display("early continuous");$fatal(1,"early continuous");end + return value; + endfunction + assign a=checked(go); + wire[7:0]other=checked(go); + assign b=other; + initial begin #2;$finish;end + endmodule + "#) + (top Top)(set go 1)(run_until 0)(assert_eq a 1)(assert_eq b 1) + (set go 2)(run_until 1)(assert_eq a 2)(assert_eq b 2) + (run_to_finish)(expect_output "")) + +(case continuous_call_drivers_preserve_assignment_context + (source "continuous-driver-context.sv" #" + module Top(input bit[7:0]go,output wire[7:0]a,b,c,output wire ready); + function automatic bit[1:0]checked(input bit[7:0]value); + if(value==0)$fatal(1,"early driver"); + return value; + endfunction + if(1) assign a=checked(go)+2'd3,c=checked({go[7:4],go[3:0]}); + wire[7:0]x=checked(go),y=checked(go); + assign b=x+y; + wire constant_ready=1; + assign ready=constant_ready; + initial begin #2;$finish;end + endmodule + "#) + (top Top)(set go 1)(run_until 0)(assert_eq a 4)(assert_eq b 2)(assert_eq c 1)(assert_eq ready 1) + (set go 2)(run_until 1)(assert_eq a 5)(assert_eq b 4)(assert_eq c 2) + (run_to_finish)(expect_output "")) diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index eb39be831ef..68039987cd1 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -219,3 +219,16 @@ sv_backends! { @case "timing::staged_wildcard_side_effects_wait_for_setup"; } } + +sv_backends! { + fn staged_continuous_side_effects_wait_for_setup(sim) { + @case "timing::staged_continuous_side_effects_wait_for_setup"; + } + +} + +sv_backends! { + fn continuous_call_drivers_preserve_assignment_context(sim) { + @case "timing::continuous_call_drivers_preserve_assignment_context"; + } +} From b9930d24b96b635207ce62d425b61361379b5ba2 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 21:53:42 +0900 Subject: [PATCH 62/75] test(suite): preserve all waiters on propagated blocking FF edges --- crates/celox-test-suite/src/sv/cases/timing.vtest | 4 ++++ crates/celox/tests/frontends/systemverilog/timing.rs | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 9729f2b65d4..f9e6e60e507 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -1153,3 +1153,7 @@ endmodule"#) (top Top)(set go 1)(run_until 0)(assert_eq a 4)(assert_eq b 2)(assert_eq c 1)(assert_eq ready 1) (set go 2)(run_until 1)(assert_eq a 5)(assert_eq b 4)(assert_eq c 2) (run_to_finish)(expect_output "")) + +(case blocking_ff_woken_waiters_sample_before_continuations + (source "blocking-ff-waiter-sampling.sv" #"module Child(input bit clk,output bit go);always_ff @(posedge clk)go=1;endmodule module Top(output bit a,b);bit clk;bit enable=1;wire go;Child child(.clk(clk),.go(go));initial begin #1;clk=1;end initial begin @(posedge(go&enable));a=1;enable=0;end initial begin @(posedge(go&enable));b=1;end endmodule"#) + (top Top)(run_until 1)(assert_eq a 1)(assert_eq b 1)) diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 68039987cd1..45bce48c0a8 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -232,3 +232,7 @@ sv_backends! { @case "timing::continuous_call_drivers_preserve_assignment_context"; } } + +sv_backends! { fn blocking_ff_woken_waiters_sample_before_continuations(sim) { + @case "timing::blocking_ff_woken_waiters_sample_before_continuations"; +} } From 6a44fa4df50a44ffd4d262b63733cc8eca267338 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 22:00:18 +0900 Subject: [PATCH 63/75] test(suite): cover direct blocking FF waiters alongside hierarchy --- crates/celox-test-suite/src/sv/cases/timing.vtest | 4 ++++ crates/celox/tests/frontends/systemverilog/timing.rs | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index f9e6e60e507..037f6a149fc 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -1157,3 +1157,7 @@ endmodule"#) (case blocking_ff_woken_waiters_sample_before_continuations (source "blocking-ff-waiter-sampling.sv" #"module Child(input bit clk,output bit go);always_ff @(posedge clk)go=1;endmodule module Top(output bit a,b);bit clk;bit enable=1;wire go;Child child(.clk(clk),.go(go));initial begin #1;clk=1;end initial begin @(posedge(go&enable));a=1;enable=0;end initial begin @(posedge(go&enable));b=1;end endmodule"#) (top Top)(run_until 1)(assert_eq a 1)(assert_eq b 1)) + +(case direct_blocking_ff_woken_waiters_sample_before_continuations + (source "direct-blocking-ff-waiter-sampling.sv" #"module Top(output bit a,b);bit clk;bit enable=1;bit go;always_ff @(posedge clk)go=1;initial begin #1;clk=1;end initial begin @(posedge(go&enable));a=1;enable=0;end initial begin @(posedge(go&enable));b=1;end endmodule"#) + (top Top)(run_until 1)(assert_eq a 1)(assert_eq b 1)) diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 45bce48c0a8..9c3cc2f6add 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -236,3 +236,7 @@ sv_backends! { sv_backends! { fn blocking_ff_woken_waiters_sample_before_continuations(sim) { @case "timing::blocking_ff_woken_waiters_sample_before_continuations"; } } + +sv_backends! { fn direct_blocking_ff_woken_waiters_sample_before_continuations(sim) { + @case "timing::direct_blocking_ff_woken_waiters_sample_before_continuations"; +} } From 0a3349e476ec435971c7a85d5530eb6713d6e400 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 23:08:32 +0900 Subject: [PATCH 64/75] fix(suite): stage dynamic declaration initialization before procedures --- crates/celox-test-suite/src/frontend.rs | 36 +- .../celox-test-suite/src/frontend/timed_ff.rs | 2 +- .../src/frontend/timed_initializers.rs | 413 ++++++++++++++++++ crates/celox-test-suite/src/script/sv.rs | 2 + .../src/sv/cases/timing.vtest | 51 +++ .../tests/frontends/systemverilog/timing.rs | 15 + 6 files changed, 512 insertions(+), 7 deletions(-) create mode 100644 crates/celox-test-suite/src/frontend/timed_initializers.rs diff --git a/crates/celox-test-suite/src/frontend.rs b/crates/celox-test-suite/src/frontend.rs index 5b550f7bace..f4cc3f2e2be 100644 --- a/crates/celox-test-suite/src/frontend.rs +++ b/crates/celox-test-suite/src/frontend.rs @@ -1,6 +1,7 @@ //! What a suite supplies to build its designs with an external simulator. mod timed_ff; +mod timed_initializers; use crate::process::write_if_changed; use crate::script::ScriptCase; @@ -156,15 +157,19 @@ pub(crate) fn stage( const TIMED_CONTROL: &str = r#"package celox_suite_timed_control; bit started = 0; bit setup_started = 0; + bit initializing = 0; + function automatic void celox_suite_begin_initializers(); + initializing = 1; + endfunction function automatic void celox_suite_begin_setup(); setup_started = 1; endfunction bit finished = 0; function automatic void celox_suite_start_design(); - started = 1; + if (!finished) started = 1; endfunction function automatic void celox_suite_finish_design(input int code = 1); - if (!started) return; + if (!started && !initializing) return; finished = 1; case (code) 0: $finish(0); @@ -179,6 +184,7 @@ struct TimedNames { package: String, start: String, setup: String, + initialize: String, finish: String, } @@ -203,11 +209,18 @@ fn timed_names(sources: &[String]) -> TimedNames { package: name("celox_suite_timed_control"), start: name("celox_suite_start_design"), setup: name("celox_suite_begin_setup"), + initialize: name("celox_suite_begin_initializers"), finish: name("celox_suite_finish_design"), }; - if [&names.package, &names.start, &names.finish, &names.setup] - .into_iter() - .all(|name| !words.contains(name.as_str())) + if [ + &names.package, + &names.start, + &names.finish, + &names.setup, + &names.initialize, + ] + .into_iter() + .all(|name| !words.contains(name.as_str())) { return names; } @@ -235,6 +248,7 @@ impl TimedNames { &self.package } "celox_suite_begin_setup" if tail.starts_with('(') => &self.setup, + "celox_suite_begin_initializers" if tail.starts_with('(') => &self.initialize, "celox_suite_start_design" if tail.starts_with('(') => &self.start, "celox_suite_finish_design" if tail.starts_with('(') => &self.finish, _ => continue, @@ -269,10 +283,17 @@ fn timed_source(source: &str, names: &TimedNames, tasks: &timed_ff::TaskTiming) fn timed_content(source: &str, names: &TimedNames, tasks: &timed_ff::TaskTiming) -> Result { let mut output = String::new(); let mut previous = 0; + let initializers = timed_initializers::rewrites(source, names)?; for (start, end, word) in sv_words(source) { if start < previous { continue; } + if let Some((body_end, replacement)) = initializers.get(&start) { + output.push_str(&source[previous..start]); + output.push_str(&timed_ff::in_macro(source, start, replacement.clone())); + previous = *body_end; + continue; + } if matches!( word, "assign" | "wire" | "tri" | "tri0" | "tri1" | "wand" | "wor" | "triand" | "trior" @@ -320,7 +341,10 @@ fn timed_content(source: &str, names: &TimedNames, tasks: &timed_ff::TaskTiming) } else { format!("{}();", names.finish) }; - let replacement = format!("begin if ({}::started) {call} end ", names.package); + let replacement = format!( + "begin if ({0}::started || {0}::initializing) {call} end ", + names.package + ); output.push_str(&source[previous..start]); output.push_str(&timed_ff::in_macro(source, start, replacement)); previous = body_end; diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index 10da132d867..ef720589f3e 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -260,7 +260,7 @@ pub(super) fn statement_end(source: &str, at: usize) -> Option { } } -fn single_generate_body(source: &str, start: usize) -> bool { +pub(super) fn single_generate_body(source: &str, start: usize) -> bool { let mut at = 0; let mut last_word = ""; let mut control_end = None; diff --git a/crates/celox-test-suite/src/frontend/timed_initializers.rs b/crates/celox-test-suite/src/frontend/timed_initializers.rs new file mode 100644 index 00000000000..a3352f9376d --- /dev/null +++ b/crates/celox-test-suite/src/frontend/timed_initializers.rs @@ -0,0 +1,413 @@ +//! Stage mutable module/generate declaration initializers before procedures. +use super::*; +use sv_parser::{NodeEvent, RefNode, SyntaxTree}; + +fn span(tree: &SyntaxTree, node: RefNode<'_>) -> Option<(usize, usize)> { + let origin = |offset| { + tree.get_origin(&sv_parser::Locate { + offset, + len: 1, + line: 0, + }) + }; + let mut range: Option<(usize, usize)> = None; + for child in node { + if let RefNode::Locate(locate) = child + && locate.len > 0 + && let Some((_, start)) = origin(locate.offset) + && let Some((_, last)) = origin(locate.offset + locate.len - 1) + { + range = Some(match range { + None => (start, last + 1), + Some((low, high)) => (low.min(start), high.max(last + 1)), + }); + } + } + range +} + +fn expression_calls( + expr: &celox_sv_analyzer::ir::Expr, + calls: &mut std::collections::BTreeSet, +) { + use celox_sv_analyzer::ir::Expr; + match expr { + Expr::Call { name, args, .. } => { + calls.insert(name.clone()); + for arg in args.iter().flatten() { + expression_calls(arg, calls); + } + } + Expr::Select { expr, .. } | Expr::Resize { expr, .. } | Expr::Unary { expr, .. } => { + expression_calls(expr, calls) + } + Expr::Concat(parts) | Expr::RepeatConcat { parts, .. } => { + for part in parts { + expression_calls(part, calls); + } + } + Expr::Binary { left, right, .. } => { + expression_calls(left, calls); + expression_calls(right, calls); + } + Expr::Mux { + condition, + then_expr, + else_expr, + } => { + expression_calls(condition, calls); + expression_calls(then_expr, calls); + expression_calls(else_expr, calls); + } + Expr::Inside { expr, items } => { + expression_calls(expr, calls); + for item in items { + for expr in item.exprs() { + expression_calls(expr, calls); + } + } + } + Expr::Ident(_) | Expr::Literal(_) => {} + } +} + +fn effectful_functions(source: &str) -> std::collections::BTreeSet { + use celox_sv_analyzer::ir::Stmt; + let mut functions = BTreeMap::new(); + if let Ok(ir) = celox_sv_analyzer::analyze_source(source, Path::new("timed.sv")) { + for module in ir.modules() { + for subroutine in module + .declaration_subroutines() + .iter() + .chain(module.subroutines()) + { + let mut local_names = subroutine + .params + .iter() + .map(|p| p.name.clone()) + .collect::>(); + local_names.insert(subroutine.name.clone()); + local_names.extend(subroutine.return_var.iter().cloned()); + for statement in &subroutine.body { + statement.walk(&mut |stmt| { + if let Stmt::Local { name, .. } = stmt { + local_names.insert(name.clone()); + } + }); + } + let mut effect = subroutine.params.iter().any(|p| p.direction.is_written()); + let mut calls = std::collections::BTreeSet::new(); + for statement in &subroutine.body { + statement.walk(&mut |stmt| match stmt { + Stmt::SystemTask { .. } => effect = true, + Stmt::Assign { lhs, .. } => effect |= !local_names.contains(lhs.name()), + Stmt::AssignConcat { parts, .. } => { + effect |= parts.iter().any(|lhs| !local_names.contains(lhs.name())) + } + Stmt::Call { name, .. } => { + calls.insert(name.clone()); + } + _ => {} + }); + let _ = statement.clone().map( + &mut |expr| { + expression_calls(&expr, &mut calls); + expr + }, + &mut |lhs| lhs, + ); + } + functions + .entry(subroutine.name.clone()) + .or_insert((effect, calls)); + } + } + } + loop { + let known = functions + .iter() + .filter(|(_, (effect, _))| *effect) + .map(|(name, _)| name.clone()) + .collect::>(); + let mut changed = false; + for (effect, calls) in functions.values_mut() { + if !*effect && calls.iter().any(|name| known.contains(name)) { + *effect = true; + changed = true; + } + } + if !changed { + return known; + } + } +} + +// Ask the declaration analyzer whether a value can be elaborated, while +// leaving the simulator to evaluate the original expression. A fixed-width +// two-state parameter also classifies wide and X/Z constants without making +// their numerical value part of this rewrite. +fn elaboration_constant( + source: &str, + start: usize, + end: usize, + expression: &str, + seeds: &[String], +) -> bool { + let mut suffix = start; + let (name, guard) = loop { + let name = format!("__celox_initializer_constant_{suffix}"); + let guard = format!("{name}_range"); + if !sv_words(source) + .iter() + .any(|(_, _, word)| *word == name || *word == guard || *word == format!("{name}_value")) + { + break (name, guard); + } + suffix += 1; + }; + let function = format!("{name}_value"); + let probe = format!( + "function automatic bit [127:0] {function}();\n{}\nreturn ({expression}); endfunction\nlocalparam bit [127:0] {name} = {function}(); wire [{name}:{name}] {guard}='0;\n", + seeds.join("\n") + ); + let candidate = if timed_ff::single_generate_body(source, start) { + format!( + "{}begin\n{probe}{}\nend\n{}", + &source[..start], + &source[start..end], + &source[end..] + ) + } else { + format!("{}{probe}{}", &source[..start], &source[start..]) + }; + celox_sv_analyzer::analyze_source(&candidate, Path::new("timed.sv")).is_ok_and(|ir| { + ir.modules() + .iter() + .flat_map(|module| module.signals()) + .any(|signal| { + signal.name().rsplit('.').next() == Some(guard.as_str()) + && signal.r#type().resolved_width() == Some(1) + }) + }) +} + +pub(super) fn rewrites( + source: &str, + names: &TimedNames, +) -> Result> { + let mut result = BTreeMap::new(); + // Recursive statement rewrites do not contain module declarations. + if !sv_words(source) + .iter() + .any(|(_, _, word)| matches!(*word, "module" | "interface")) + { + return Ok(result); + } + let tree = celox_sv_analyzer::syntax::parse_source(source, Path::new("timed.sv"))?; + let effects = effectful_functions(source); + let mut scopes = Vec::new(); + let mut records = Vec::new(); + let mut used_names = sv_words(source) + .into_iter() + .map(|(_, _, word)| word.to_owned()) + .collect::>(); + let mut groups = BTreeMap::::new(); + let mut static_seeds = BTreeMap::>::new(); + let mut modules = 0usize; + let mut procedures = 0usize; + for event in (&tree).into_iter().event() { + let (entering, node) = match event { + NodeEvent::Enter(node) => (true, node), + NodeEvent::Leave(node) => (false, node), + }; + if matches!( + node, + RefNode::ModuleDeclaration(_) + | RefNode::InterfaceDeclaration(_) + | RefNode::GenerateBlock(_) + ) { + if entering { + scopes.push( + span(&tree, node.clone()) + .ok_or("missing initializer scope")? + .0, + ); + } else { + scopes.pop(); + } + } + if matches!( + node, + RefNode::ModuleDeclaration(_) | RefNode::InterfaceDeclaration(_) + ) { + if entering { + modules += 1; + } else { + modules -= 1; + } + } + if matches!( + node, + RefNode::InitialConstruct(_) + | RefNode::AlwaysConstruct(_) + | RefNode::FinalConstruct(_) + | RefNode::FunctionDeclaration(_) + | RefNode::TaskDeclaration(_) + | RefNode::ClassDeclaration(_) + ) { + if entering { + procedures += 1; + } else { + procedures -= 1; + } + } + if !entering || modules == 0 || procedures != 0 { + continue; + } + let RefNode::DataDeclaration(sv_parser::DataDeclaration::Variable(variable)) = node else { + continue; + }; + // Const declarations cannot be assigned procedurally. + if variable.nodes.0.is_some() { + continue; + } + let (start, end) = span(&tree, node).ok_or("missing declaration source span")?; + let mut removals = Vec::new(); + let mut assignments = String::new(); + let mut temporaries = String::new(); + let datatype = span(&tree, RefNode::DataTypeOrImplicit(&variable.nodes.3)) + .and_then(|(begin, end)| source.get(begin..end)) + .unwrap_or("logic"); + for declaration in variable.nodes.4.nodes.0.contents() { + let sv_parser::VariableDeclAssignment::Variable(declaration) = declaration else { + continue; + }; + let Some((equal, expression)) = &declaration.nodes.2 else { + continue; + }; + let (name_start, name_end) = + span(&tree, RefNode::VariableIdentifier(&declaration.nodes.0)) + .ok_or("missing initializer name")?; + let (equal_start, _) = + span(&tree, RefNode::Symbol(equal)).ok_or("missing initializer assignment")?; + let literal_expression = !RefNode::Expression(expression).into_iter().any(|node| { + matches!( + node, + RefNode::SimpleIdentifier(_) + | RefNode::EscapedIdentifier(_) + | RefNode::SystemTfIdentifier(_) + ) + }); + let (expr_start, expr_end) = span(&tree, RefNode::Expression(expression)) + .ok_or("missing initializer expression")?; + let name = source + .get(name_start..name_end) + .ok_or("initializer name span exceeds source")?; + let expression = source + .get(expr_start..expr_end) + .ok_or("initializer expression span exceeds source")?; + let mut dimensions = String::new(); + for dimension in &declaration.nodes.1 { + let (begin, end) = span(&tree, RefNode::VariableDimension(dimension)) + .ok_or("missing initializer dimensions")?; + dimensions.push_str( + source + .get(begin..end) + .ok_or("initializer dimensions exceed source")?, + ); + } + + let mut known = Vec::<(String, String)>::new(); + for scope in &scopes { + for (name, value) in static_seeds.get(scope).into_iter().flatten() { + known.retain(|(previous, _)| previous != name); + known.push((name.clone(), value.clone())); + } + } + let seeds = known + .into_iter() + .map(|(_, declaration)| declaration) + .collect::>(); + // Keep constant initialization before FF listeners are armed; + // moving an already-high clock into setup would invent an edge. + let effectful_call = sv_words(expression).iter().any(|(_, end, name)| { + effects.contains(*name) && after_trivia(&expression[*end..]).starts_with('(') + }); + if !effectful_call + && (literal_expression + || elaboration_constant(source, start, end, expression, &seeds)) + { + let scope = *scopes + .last() + .ok_or("constant initializer outside module scope")?; + static_seeds.entry(scope).or_default().push(( + name.trim().to_owned(), + format!("localparam {datatype} {name}{dimensions} = {expression};"), + )); + continue; + } + let mut suffix = equal_start; + let temporary = loop { + let temporary = format!("{}_initializer_value_{suffix}", names.package); + if used_names.insert(temporary.clone()) { + break temporary; + } + suffix += 1; + }; + temporaries.push_str(&format!(", {temporary}{dimensions}")); + assignments.push_str(&format!("if (!{0}::finished) begin {temporary} = {expression}; if (!{0}::finished) {name} = {temporary}; end\n", names.package)); + removals.push((equal_start, expr_end)); + } + if removals.is_empty() { + continue; + } + let (semicolon, _) = span(&tree, RefNode::Symbol(&variable.nodes.5)) + .ok_or("missing declaration terminator")?; + let mut declaration = source + .get(start..semicolon) + .ok_or("declaration span exceeds source")? + .to_owned(); + for (begin, end) in removals.into_iter().rev() { + declaration.replace_range(begin - start..end - start, ""); + } + declaration.push_str(&temporaries); + declaration.push_str( + source + .get(semicolon..end) + .ok_or("declaration terminator exceeds source")?, + ); + let scope = *scopes.last().ok_or("initializer outside module scope")?; + let index = records.len(); + groups + .entry(scope) + .and_modify(|(last, body)| { + *last = index; + body.push_str(&assignments); + }) + .or_insert((index, assignments)); + records.push((start, end, declaration)); + } + // One activation per lexical scope preserves declaration order across + // declarations as well as within a multi-variable declaration. + for (index, (start, end, declaration)) in records.into_iter().enumerate() { + let body = groups + .values() + .find(|(last, _)| *last == index) + .map(|(_, body)| body.as_str()); + let replacement = if let Some(body) = body { + format!( + "{declaration}\ninitial begin wait ({}::initializing);\n{body}end\n", + names.package + ) + } else { + declaration + }; + let replacement = if timed_ff::single_generate_body(source, start) { + format!("begin\n{replacement}end\n") + } else { + replacement + }; + result.insert(start, (end, replacement)); + } + Ok(result) +} diff --git a/crates/celox-test-suite/src/script/sv.rs b/crates/celox-test-suite/src/script/sv.rs index ca4eba62606..20985317415 100644 --- a/crates/celox-test-suite/src/script/sv.rs +++ b/crates/celox-test-suite/src/script/sv.rs @@ -1137,6 +1137,8 @@ pub fn testbench(case: &ScriptCase, design: &DesignInfo) -> Result Date: Thu, 15 Oct 2026 23:44:24 +0900 Subject: [PATCH 65/75] fix(suite): preserve bare calls and escaped continuous destinations --- crates/celox-test-suite/src/frontend.rs | 2 +- .../celox-test-suite/src/frontend/timed_ff.rs | 23 ++++++++-- .../src/sv/cases/timing.vtest | 19 ++++++++ .../celox-test-suite/tests/timed_protocol.rs | 43 +++++++++++++++++++ .../tests/frontends/systemverilog/timing.rs | 4 ++ 5 files changed, 86 insertions(+), 5 deletions(-) diff --git a/crates/celox-test-suite/src/frontend.rs b/crates/celox-test-suite/src/frontend.rs index f4cc3f2e2be..e4942c8fc20 100644 --- a/crates/celox-test-suite/src/frontend.rs +++ b/crates/celox-test-suite/src/frontend.rs @@ -298,7 +298,7 @@ fn timed_content(source: &str, names: &TimedNames, tasks: &timed_ff::TaskTiming) word, "assign" | "wire" | "tri" | "tri0" | "tri1" | "wand" | "wor" | "triand" | "trior" ) && let Some((body_end, replacement)) = - timed_ff::gated_continuous(source, start, end, names) + timed_ff::gated_continuous(source, start, end, names, tasks) { output.push_str(&source[previous..start]); output.push_str(&timed_ff::in_macro(source, start, replacement)); diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index ef720589f3e..3a1b3cb6fce 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -79,6 +79,7 @@ pub(super) fn gated_continuous( start: usize, end: usize, names: &TimedNames, + tasks: &TaskTiming, ) -> Option<(usize, String)> { let net_declaration = &source[start..end] != "assign"; let mut at = end; @@ -123,9 +124,23 @@ pub(super) fn gated_continuous( b',' | b';' if depth == 0 => { if let Some(begin) = rhs.take() { let expression = &source[begin..at]; - let calls = sv_words(expression) - .into_iter() - .any(|(_, end, _)| after_trivia(&expression[end..]).starts_with('(')); + let mut calls = false; + let mut bare_calls = Vec::new(); + for (offset, end, word) in sv_words(expression) { + if after_trivia(&expression[end..]).starts_with('(') { + calls = true; + } else if tasks.resolve(source, begin + offset, word).is_some() { + calls = true; + bare_calls.push(end); + } + } + // Both external tools require parentheses for a resolved + // zero-argument function in an expression. Normalize only + // callable identifiers; ordinary variable drivers stay live. + let mut expression = expression.to_owned(); + for end in bare_calls.into_iter().rev() { + expression.insert_str(end, " ()"); + } if calls { let lhs = lhs_name.take()?; let mut suffix = at; @@ -137,7 +152,7 @@ pub(super) fn gated_continuous( suffix += 1; }; drivers.push_str(&format!( - "reg [$bits({lhs})-1:0] {name};\nalways @* begin if ({}::started) {name} = {expression}; end\n", names.package + "reg [$bits({lhs} )-1:0] {name};\nalways_comb begin if ({}::started) {name} = {expression}; end\n", names.package )); output.push_str(&source[previous..begin]); output.push_str(&format!(" {name}")); diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 8bcf950041a..e1e3d66b494 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -1212,3 +1212,22 @@ endmodule"#) endmodule "#) (top Top)(run_to_finish)(assert_eq seen 0)(expect_output "")) + + +(case escaped_continuous_destinations_preserve_identifier_terminators + (source "escaped-continuous-function.sv" #" + module Top(input bit go,output wire y,z); + wire \out ; + wire \other = checked(go); + function automatic bit checked(input bit value); + if(!value)$fatal(1,"escaped function ran before setup"); + return value; + endfunction + assign \out =checked(go); + assign y=\out ; + assign z=\other ; + initial begin #2;$finish;end + endmodule + "#) + (top Top)(set go 1)(run_until 0)(assert_eq y 1)(assert_eq z 1) + (run_to_finish)(expect_output "")) diff --git a/crates/celox-test-suite/tests/timed_protocol.rs b/crates/celox-test-suite/tests/timed_protocol.rs index 5ec1fb866a8..0b886098dbd 100644 --- a/crates/celox-test-suite/tests/timed_protocol.rs +++ b/crates/celox-test-suite/tests/timed_protocol.rs @@ -73,3 +73,46 @@ fn qualified_ff_if_actions_are_not_truncated_during_staging() { celox_test_suite::script::sv::check_output(&log, &[]).unwrap(); std::fs::remove_dir_all(root).unwrap(); } + +#[test] +#[ignore = "requires Icarus, Verilator and a C++ compiler"] +fn bare_continuous_function_calls_observe_staged_inputs() { + // Exercise the adapter directly: Celox currently rejects bare function + // values in continuous assignments, while the adapter normalizes them + // to explicit calls for the external simulators. + let text = r##"(group protocol (category sequential)) + (case bare (source "bare.sv" #" + module Top(input bit[7:0] go,output wire[7:0] y,z,output wire ready); + function automatic bit[7:0] checked; + if(!go)$fatal(1,"bare function ran before setup"); + return go; + endfunction + assign y=checked; + wire[7:0] other=checked; + assign z=other; + wire constant_ready=1; + assign ready=constant_ready; + initial begin #2;$finish;end + endmodule + "#) (top Top)(set go 1)(run_until 0)(assert_eq y 1)(assert_eq z 1)(assert_eq ready 1) + (set go 2)(run_until 1)(assert_eq y 2)(assert_eq z 2))"##; + let case = load_group("bare.vtest", text, no_std_library)[0]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../target/bare-continuous-protocol") + .join(std::process::id().to_string()); + let frontend = celox_test_suite::sv::verification::SvFrontend; + let mut icarus = + celox_test_suite::icarus::Icarus::build_script(&frontend, case, &root.join("icarus")) + .unwrap(); + icarus.run_testbench().unwrap(); + let mut verilator = celox_test_suite::verilator::Verilator::build_script( + &frontend, + case, + &root.join("verilator"), + ) + .unwrap(); + verilator.run_testbench().unwrap(); + let log = std::fs::read(root.join("verilator/protocol.log")).unwrap(); + celox_test_suite::script::sv::check_output(&log, &[]).unwrap(); + std::fs::remove_dir_all(root).unwrap(); +} diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 4457d1829e2..cde6d59dc04 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -255,3 +255,7 @@ sv_backends! { fn variable_initializer_dependencies_and_automatic_locals_preserv sv_backends! { fn variable_initializer_finish_prevents_procedural_start(sim) { @case "timing::variable_initializer_finish_prevents_procedural_start"; } } + +sv_backends! { fn escaped_continuous_destinations_preserve_identifier_terminators(sim) { + @case "timing::escaped_continuous_destinations_preserve_identifier_terminators"; +} } From 7f0b83c06fdc92ed48b838d4bb48307f0d1b84a6 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 23:45:37 +0900 Subject: [PATCH 66/75] test(suite): cover active batches and terminal waits portably --- crates/celox-test-suite/src/sv/cases/timing.vtest | 12 ++++++++++++ crates/celox/tests/frontends/systemverilog/timing.rs | 12 ++++++++++++ 2 files changed, 24 insertions(+) diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index e1e3d66b494..ba181b27f41 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -1231,3 +1231,15 @@ endmodule"#) "#) (top Top)(set go 1)(run_until 0)(assert_eq y 1)(assert_eq z 1) (run_to_finish)(expect_output "")) + +(case repeated_active_edges_share_one_nba_batch + (source "repeated_active_edges_share_one_nba_batch.sv" #"module Top(output bit[7:0]q);bit d;initial begin #1;d=1;d=0;d=1;end always @(posedge d)q<=q+1;endmodule"#) + (top Top)(run_until 1)(assert_eq q 1)) + +(case false_wait_preserves_separate_hierarchical_write_times + (source "false_wait_preserves_separate_hierarchical_write_times.sv" #"module Child(output bit[1:0]v);initial begin #1;v[0]=1;wait(0);end initial begin #2;v[1]=1;end endmodule module Top(output bit[7:0]q);wire[1:0]v;Child c(.v(v));initial forever begin @(v[0]^v[1]);q++;end endmodule"#) + (top Top)(run_until 1)(assert_eq q 1)(run_until 2)(assert_eq q 2)) + +(case always_timed_task_without_inline_timing_executes + (source "always_timed_task_without_inline_timing_executes.sv" #"module Top(output bit q);task tick;#1;q=~q;endtask always tick();endmodule"#) + (top Top)(run_until 1)(assert_eq q 1)(run_until 2)(assert_eq q 0)(run_until 3)(assert_eq q 1)) diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index cde6d59dc04..c7b097f4f4a 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -259,3 +259,15 @@ sv_backends! { fn variable_initializer_finish_prevents_procedural_start(sim) { sv_backends! { fn escaped_continuous_destinations_preserve_identifier_terminators(sim) { @case "timing::escaped_continuous_destinations_preserve_identifier_terminators"; } } + +sv_backends! { fn repeated_active_edges_share_one_nba_batch(sim) { + @case "timing::repeated_active_edges_share_one_nba_batch"; +} } + +sv_backends! { fn false_wait_preserves_separate_hierarchical_write_times(sim) { + @case "timing::false_wait_preserves_separate_hierarchical_write_times"; +} } + +sv_backends! { fn always_timed_task_without_inline_timing_executes(sim) { + @case "timing::always_timed_task_without_inline_timing_executes"; +} } From f48ea9d8a8fdb0d43a5b6bfbd07baa7e788647b9 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 23:54:15 +0900 Subject: [PATCH 67/75] fix(suite): keep value bindings from becoming bare calls --- .../celox-test-suite/src/frontend/timed_ff.rs | 67 ++++++++++++++++++- .../celox-test-suite/tests/timed_protocol.rs | 2 + 2 files changed, 68 insertions(+), 1 deletion(-) diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index 3a1b3cb6fce..9f233e13bfb 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -129,7 +129,7 @@ pub(super) fn gated_continuous( for (offset, end, word) in sv_words(expression) { if after_trivia(&expression[end..]).starts_with('(') { calls = true; - } else if tasks.resolve(source, begin + offset, word).is_some() { + } else if tasks.bare_callable(source, begin + offset, word) { calls = true; bare_calls.push(end); } @@ -571,6 +571,7 @@ type CallableKey = (String, Option, Vec, String); #[derive(Default)] pub(super) struct TaskTiming { tasks: BTreeMap, + values: BTreeMap>, units: BTreeMap, import_clauses: BTreeMap, Option)>>>, generate_scopes: BTreeMap>, @@ -791,6 +792,52 @@ impl TaskTiming { }) .map_or(offset, |(_, origin)| origin) }; + let mut values = Vec::new(); + for node in &tree { + use sv_parser::RefNode; + let identifier = match node { + RefNode::VariableDeclAssignmentVariable(n) => { + RefNode::VariableIdentifier(&n.nodes.0) + } + RefNode::NetDeclAssignment(n) => RefNode::NetIdentifier(&n.nodes.0), + RefNode::ParamAssignment(n) => RefNode::ParameterIdentifier(&n.nodes.0), + RefNode::AnsiPortDeclarationNet(n) => RefNode::PortIdentifier(&n.nodes.1), + RefNode::AnsiPortDeclarationVariable(n) => { + RefNode::PortIdentifier(&n.nodes.1) + } + RefNode::AnsiPortDeclarationParen(n) => RefNode::PortIdentifier(&n.nodes.2), + RefNode::EnumNameDeclaration(n) => RefNode::EnumIdentifier(&n.nodes.0), + RefNode::ListOfPortIdentifiers(n) => { + for (name, _) in n.nodes.0.contents() { + if let Some(RefNode::Locate(locate)) = RefNode::PortIdentifier(name) + .into_iter() + .find(|n| matches!(n, RefNode::Locate(_))) + { + let offset = origin(locate.offset); + if let Some((_, _, name)) = sv_words(&source[offset..]).first() + { + values.push(( + offset, + name.trim_start_matches('\\').to_owned(), + )); + } + } + } + continue; + } + _ => continue, + }; + if let Some(RefNode::Locate(locate)) = identifier + .into_iter() + .find(|n| matches!(n, RefNode::Locate(_))) + { + let offset = origin(locate.offset); + if let Some((_, _, name)) = sv_words(&source[offset..]).first() { + values.push((offset, name.trim_start_matches('\\').to_owned())); + } + } + } + result.values.insert(source.clone(), values); result.instance_types.insert( source.clone(), celox_sv_analyzer::ast::instance_type_sites(&tree) @@ -943,6 +990,24 @@ impl TaskTiming { } } + fn bare_callable(&self, source: &str, at: usize, name: &str) -> bool { + let prefix = source[..at].trim_end(); + if !prefix.ends_with('.') && !prefix.ends_with("::") { + let scope = self.lexical_scope(source, at); + let container = container_at(source, at); + if self.values.get(source).is_some_and(|values| { + values.iter().any(|(offset, value)| { + value == name.trim_start_matches('\\') + && container_at(source, *offset) == container + && scope.starts_with(&self.lexical_scope(source, *offset)) + }) + }) { + return false; + } + } + self.resolve(source, at, name).is_some() + } + fn resolve(&self, source: &str, at: usize, name: &str) -> Option { let name = name.trim_start_matches('\\'); let prefix = source[..at].trim_end(); diff --git a/crates/celox-test-suite/tests/timed_protocol.rs b/crates/celox-test-suite/tests/timed_protocol.rs index 0b886098dbd..4acc4eadd21 100644 --- a/crates/celox-test-suite/tests/timed_protocol.rs +++ b/crates/celox-test-suite/tests/timed_protocol.rs @@ -82,7 +82,9 @@ fn bare_continuous_function_calls_observe_staged_inputs() { // to explicit calls for the external simulators. let text = r##"(group protocol (category sequential)) (case bare (source "bare.sv" #" + package bare_shadow_pkg; function automatic bit constant_ready; return 0; endfunction endpackage module Top(input bit[7:0] go,output wire[7:0] y,z,output wire ready); + import bare_shadow_pkg::*; function automatic bit[7:0] checked; if(!go)$fatal(1,"bare function ran before setup"); return go; From c5affcfdea037d0fa758858af6984266b8df9b7e Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 16 Oct 2026 00:12:45 +0900 Subject: [PATCH 68/75] fix(suite): scope initializer effects and stage callable input connections --- crates/celox-test-suite/src/frontend.rs | 6 +- .../src/frontend/timed_connections.rs | 126 +++++++++++ .../celox-test-suite/src/frontend/timed_ff.rs | 83 ++++++-- .../src/frontend/timed_initializers.rs | 198 ++++++++++-------- .../src/sv/cases/timing.vtest | 56 +++++ .../celox-test-suite/tests/timed_protocol.rs | 44 ++++ .../tests/frontends/systemverilog/timing.rs | 16 ++ 7 files changed, 427 insertions(+), 102 deletions(-) create mode 100644 crates/celox-test-suite/src/frontend/timed_connections.rs diff --git a/crates/celox-test-suite/src/frontend.rs b/crates/celox-test-suite/src/frontend.rs index e4942c8fc20..c62d4fbd04d 100644 --- a/crates/celox-test-suite/src/frontend.rs +++ b/crates/celox-test-suite/src/frontend.rs @@ -1,5 +1,6 @@ //! What a suite supplies to build its designs with an external simulator. +mod timed_connections; mod timed_ff; mod timed_initializers; @@ -284,11 +285,14 @@ fn timed_content(source: &str, names: &TimedNames, tasks: &timed_ff::TaskTiming) let mut output = String::new(); let mut previous = 0; let initializers = timed_initializers::rewrites(source, names)?; + let connections = timed_connections::rewrites(source, names, tasks)?; for (start, end, word) in sv_words(source) { if start < previous { continue; } - if let Some((body_end, replacement)) = initializers.get(&start) { + if let Some((body_end, replacement)) = + initializers.get(&start).or_else(|| connections.get(&start)) + { output.push_str(&source[previous..start]); output.push_str(&timed_ff::in_macro(source, start, replacement.clone())); previous = *body_end; diff --git a/crates/celox-test-suite/src/frontend/timed_connections.rs b/crates/celox-test-suite/src/frontend/timed_connections.rs new file mode 100644 index 00000000000..10ebd3367fa --- /dev/null +++ b/crates/celox-test-suite/src/frontend/timed_connections.rs @@ -0,0 +1,126 @@ +//! Defer implicit continuous drivers on callable input-port actuals. +use super::*; +use sv_parser::{ListOfPortConnections, NamedPortConnection, RefNode}; + +pub(super) fn rewrites( + source: &str, + names: &TimedNames, + tasks: &timed_ff::TaskTiming, +) -> Result> { + let mut result = BTreeMap::new(); + if !sv_words(source) + .iter() + .any(|(_, _, word)| matches!(*word, "module" | "interface")) + { + return Ok(result); + } + let tree = celox_sv_analyzer::syntax::parse_source(source, Path::new("timed.sv"))?; + let mut used_names = sv_words(source) + .into_iter() + .map(|(_, _, name)| name.to_owned()) + .collect::>(); + for node in &tree { + let RefNode::ModuleInstantiation(module) = node else { + continue; + }; + let (start, end) = timed_initializers::span(&tree, node).ok_or("missing instance span")?; + let module_name = tree + .get_str(&module.nodes.0) + .unwrap_or("") + .trim() + .trim_start_matches('\\'); + let mut replacements = Vec::new(); + let mut drivers = String::new(); + for instance in module.nodes.2.contents() { + // Array connections have separate broadcast/distribution rules. + if !instance.nodes.0.nodes.1.is_empty() { + continue; + } + let Some(connections) = &instance.nodes.1.nodes.1 else { + continue; + }; + let (name_start, name_end) = timed_initializers::span( + &tree, + RefNode::InstanceIdentifier(&instance.nodes.0.nodes.0), + ) + .ok_or("missing instance name")?; + let instance_name = &source[name_start..name_end]; + let connections: Vec<_> = match connections { + ListOfPortConnections::Ordered(ordered) => ordered + .nodes + .0 + .contents() + .into_iter() + .enumerate() + .filter_map(|(index, connection)| { + Some(( + tasks.ports.get(module_name)?.get(index)?.clone(), + connection.nodes.1.as_ref()?, + )) + }) + .collect(), + ListOfPortConnections::Named(named) => named + .nodes + .0 + .contents() + .into_iter() + .filter_map(|connection| { + let NamedPortConnection::Identifier(connection) = connection else { + return None; + }; + Some(( + tree.get_str(&connection.nodes.2)?.trim().to_owned(), + connection.nodes.3.as_ref()?.nodes.1.as_ref()?, + )) + }) + .collect(), + }; + for (port, expression) in connections { + if !tasks + .inputs + .get(module_name) + .is_some_and(|inputs| inputs.contains(port.trim_start_matches('\\'))) + { + continue; + } + let (begin, finish) = + timed_initializers::span(&tree, RefNode::Expression(expression)) + .ok_or("missing connection expression")?; + let Some(expression) = timed_ff::gated_rhs(source, begin, finish, tasks) else { + continue; + }; + let mut suffix = begin; + let name = loop { + let name = format!("{}_connection_{suffix}", names.package); + if used_names.insert(name.clone()) { + break name; + } + suffix += 1; + }; + drivers.push_str(&format!("reg [$bits({instance_name} .{port} )-1:0] {name};\nalways_comb begin if ({}::started) {name} = {expression}; end\n", names.package)); + replacements.push((begin, finish, name)); + } + } + if replacements.is_empty() { + continue; + } + replacements.sort_by_key(|r| r.0); + let mut body = source[start..end].to_owned(); + for (begin, finish, name) in replacements.into_iter().rev() { + body.replace_range(begin - start..finish - start, &name); + } + let body = format!("{drivers}{body}"); + result.insert( + start, + ( + end, + if timed_ff::single_generate_body(source, start) { + format!("begin\n{body}\nend") + } else { + body + }, + ), + ); + } + Ok(result) +} diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index 9f233e13bfb..4e059617a68 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -71,6 +71,34 @@ fn parens(source: &str, begin: usize) -> Option { } None } +// Resolve callable operands while preserving ordinary value references. +pub(super) fn gated_rhs( + source: &str, + begin: usize, + end: usize, + tasks: &TaskTiming, +) -> Option { + let expression = &source[begin..end]; + let mut calls = false; + let mut bare_calls = Vec::new(); + for (offset, end, word) in sv_words(expression) { + if after_trivia(&expression[end..]).starts_with('(') { + calls = true; + } else if tasks.bare_callable(source, begin + offset, word) { + calls = true; + bare_calls.push(end); + } + } + if !calls { + return None; + } + let mut expression = expression.to_owned(); + for end in bare_calls.into_iter().rev() { + expression.insert_str(end, " ()"); + } + Some(expression) +} + // Icarus evaluates function operands in a continuous ternary eagerly. Use // a procedural gate and retain the original net driver (and its delays and // strengths). The temporary has the destination's packed assignment width. @@ -123,25 +151,7 @@ pub(super) fn gated_continuous( } b',' | b';' if depth == 0 => { if let Some(begin) = rhs.take() { - let expression = &source[begin..at]; - let mut calls = false; - let mut bare_calls = Vec::new(); - for (offset, end, word) in sv_words(expression) { - if after_trivia(&expression[end..]).starts_with('(') { - calls = true; - } else if tasks.bare_callable(source, begin + offset, word) { - calls = true; - bare_calls.push(end); - } - } - // Both external tools require parentheses for a resolved - // zero-argument function in an expression. Normalize only - // callable identifiers; ordinary variable drivers stay live. - let mut expression = expression.to_owned(); - for end in bare_calls.into_iter().rev() { - expression.insert_str(end, " ()"); - } - if calls { + if let Some(expression) = gated_rhs(source, begin, at, tasks) { let lhs = lhs_name.take()?; let mut suffix = at; let name = loop { @@ -571,6 +581,8 @@ type CallableKey = (String, Option, Vec, String); #[derive(Default)] pub(super) struct TaskTiming { tasks: BTreeMap, + pub(super) ports: BTreeMap>, + pub(super) inputs: BTreeMap>, values: BTreeMap>, units: BTreeMap, import_clauses: BTreeMap, Option)>>>, @@ -778,6 +790,39 @@ impl TaskTiming { .map(|(key, types)| (key, types.into_iter().collect())) .collect(); } + if let Ok(packages) = celox_sv_analyzer::analyze_packages(&paths) { + for source in sources { + if let Ok(interfaces) = + celox_sv_analyzer::source_module_interfaces(source, Path::new("timed.sv")) + { + for (name, interface) in interfaces { + if let Ok(ir) = celox_sv_analyzer::analyze_source_module_with_packages( + source, + Path::new("timed.sv"), + &name, + &Default::default(), + &packages, + ) { + for module in ir.modules() { + result.inputs.insert( + module.name().to_owned(), + module + .ports() + .iter() + .filter(|port| { + port.direction() + == celox_sv_analyzer::ir::PortDirection::Input + }) + .map(|port| port.name().to_owned()) + .collect(), + ); + } + } + result.ports.insert(name, interface.ports); + } + } + } + } let mut records = Vec::new(); for (index, source) in sources.iter().enumerate() { result.units.insert(source.clone(), index); diff --git a/crates/celox-test-suite/src/frontend/timed_initializers.rs b/crates/celox-test-suite/src/frontend/timed_initializers.rs index a3352f9376d..94e003c5550 100644 --- a/crates/celox-test-suite/src/frontend/timed_initializers.rs +++ b/crates/celox-test-suite/src/frontend/timed_initializers.rs @@ -2,7 +2,7 @@ use super::*; use sv_parser::{NodeEvent, RefNode, SyntaxTree}; -fn span(tree: &SyntaxTree, node: RefNode<'_>) -> Option<(usize, usize)> { +pub(super) fn span(tree: &SyntaxTree, node: RefNode<'_>) -> Option<(usize, usize)> { let origin = |offset| { tree.get_origin(&sv_parser::Locate { offset, @@ -26,14 +26,13 @@ fn span(tree: &SyntaxTree, node: RefNode<'_>) -> Option<(usize, usize)> { range } -fn expression_calls( - expr: &celox_sv_analyzer::ir::Expr, - calls: &mut std::collections::BTreeSet, -) { +type Calls = std::collections::BTreeSet<(String, Vec)>; + +fn expression_calls(expr: &celox_sv_analyzer::ir::Expr, calls: &mut Calls) { use celox_sv_analyzer::ir::Expr; match expr { Expr::Call { name, args, .. } => { - calls.insert(name.clone()); + calls.insert((name.clone(), args.iter().map(Option::is_some).collect())); for arg in args.iter().flatten() { expression_calls(arg, calls); } @@ -71,75 +70,110 @@ fn expression_calls( } } -fn effectful_functions(source: &str) -> std::collections::BTreeSet { +fn effectful_functions( + ir: &celox_sv_analyzer::ir::Ir, +) -> std::collections::BTreeSet<(String, String)> { use celox_sv_analyzer::ir::Stmt; let mut functions = BTreeMap::new(); - if let Ok(ir) = celox_sv_analyzer::analyze_source(source, Path::new("timed.sv")) { - for module in ir.modules() { - for subroutine in module - .declaration_subroutines() + for module in ir.modules() { + for subroutine in module + .declaration_subroutines() + .iter() + .chain(module.subroutines()) + { + let mut local_names = subroutine + .params .iter() - .chain(module.subroutines()) - { - let mut local_names = subroutine - .params - .iter() - .map(|p| p.name.clone()) - .collect::>(); - local_names.insert(subroutine.name.clone()); - local_names.extend(subroutine.return_var.iter().cloned()); - for statement in &subroutine.body { - statement.walk(&mut |stmt| { - if let Stmt::Local { name, .. } = stmt { - local_names.insert(name.clone()); - } - }); - } - let mut effect = subroutine.params.iter().any(|p| p.direction.is_written()); - let mut calls = std::collections::BTreeSet::new(); - for statement in &subroutine.body { - statement.walk(&mut |stmt| match stmt { - Stmt::SystemTask { .. } => effect = true, - Stmt::Assign { lhs, .. } => effect |= !local_names.contains(lhs.name()), - Stmt::AssignConcat { parts, .. } => { - effect |= parts.iter().any(|lhs| !local_names.contains(lhs.name())) - } - Stmt::Call { name, .. } => { - calls.insert(name.clone()); - } - _ => {} - }); - let _ = statement.clone().map( - &mut |expr| { - expression_calls(&expr, &mut calls); - expr - }, - &mut |lhs| lhs, - ); - } - functions - .entry(subroutine.name.clone()) - .or_insert((effect, calls)); + .map(|p| p.name.clone()) + .collect::>(); + local_names.insert(subroutine.name.clone()); + local_names.extend(subroutine.return_var.iter().cloned()); + for statement in &subroutine.body { + statement.walk(&mut |stmt| { + if let Stmt::Local { name, .. } = stmt { + local_names.insert(name.clone()); + } + }); } - } - } - loop { - let known = functions - .iter() - .filter(|(_, (effect, _))| *effect) - .map(|(name, _)| name.clone()) - .collect::>(); - let mut changed = false; - for (effect, calls) in functions.values_mut() { - if !*effect && calls.iter().any(|name| known.contains(name)) { - *effect = true; - changed = true; + let mut effect = subroutine.params.iter().any(|p| p.direction.is_written()); + let mut calls = std::collections::BTreeSet::new(); + let defaults = subroutine + .params + .iter() + .map(|param| { + let mut calls = Calls::new(); + if let Some(default) = ¶m.default { + expression_calls(default, &mut calls); + } + calls + }) + .collect(); + for statement in &subroutine.body { + statement.walk(&mut |stmt| match stmt { + Stmt::SystemTask { .. } => effect = true, + Stmt::Assign { lhs, .. } => effect |= !local_names.contains(lhs.name()), + Stmt::AssignConcat { parts, .. } => { + effect |= parts.iter().any(|lhs| !local_names.contains(lhs.name())) + } + Stmt::Call { name, args, .. } => { + calls.insert((name.clone(), args.iter().map(Option::is_some).collect())); + } + _ => {} + }); + let _ = statement.clone().map( + &mut |expr| { + expression_calls(&expr, &mut calls); + expr + }, + &mut |lhs| lhs, + ); } + functions + .entry((module.name().to_owned(), subroutine.name.clone())) + .or_insert((effect, calls, defaults)); } - if !changed { - return known; + } + type Effects = BTreeMap<(String, String), (bool, Calls, Vec)>; + fn reaches_effect( + functions: &Effects, + module: &str, + name: &str, + provided: &[bool], + visiting: &mut std::collections::BTreeSet<(String, String, Vec)>, + ) -> bool { + let key = (module.to_owned(), name.to_owned(), provided.to_vec()); + if !visiting.insert(key.clone()) { + return false; } + let result = functions + .get(&(module.to_owned(), name.to_owned())) + .is_some_and(|(effect, calls, defaults)| { + *effect + || calls + .iter() + .chain( + defaults + .iter() + .enumerate() + .filter(|(index, _)| { + !provided.get(*index).copied().unwrap_or(false) + }) + .flat_map(|(_, calls)| calls), + ) + .any(|(callee, supplied)| { + reaches_effect(functions, module, callee, supplied, visiting) + }) + }); + visiting.remove(&key); + result } + functions + .keys() + .filter(|(module, name)| { + reaches_effect(&functions, module, name, &[], &mut Default::default()) + }) + .cloned() + .collect() } // Ask the declaration analyzer whether a value can be elaborated, while @@ -181,13 +215,20 @@ fn elaboration_constant( format!("{}{probe}{}", &source[..start], &source[start..]) }; celox_sv_analyzer::analyze_source(&candidate, Path::new("timed.sv")).is_ok_and(|ir| { - ir.modules() - .iter() - .flat_map(|module| module.signals()) - .any(|signal| { - signal.name().rsplit('.').next() == Some(guard.as_str()) - && signal.r#type().resolved_width() == Some(1) - }) + // Inspect the probe's resolved calls in its declaring module and + // generate scope. A constant evaluator may ignore side effects; + // effectful bodies or omitted defaults still require staged execution. + let effects = effectful_functions(&ir); + ir.modules().iter().any(|module| { + let effectful = effects.iter().any(|(owner, name)| { + owner == module.name() && name.rsplit('.').next() == Some(function.as_str()) + }); + !effectful + && module.signals().iter().any(|signal| { + signal.name().rsplit('.').next() == Some(guard.as_str()) + && signal.r#type().resolved_width() == Some(1) + }) + }) }) } @@ -204,7 +245,6 @@ pub(super) fn rewrites( return Ok(result); } let tree = celox_sv_analyzer::syntax::parse_source(source, Path::new("timed.sv"))?; - let effects = effectful_functions(source); let mut scopes = Vec::new(); let mut records = Vec::new(); let mut used_names = sv_words(source) @@ -330,13 +370,7 @@ pub(super) fn rewrites( .collect::>(); // Keep constant initialization before FF listeners are armed; // moving an already-high clock into setup would invent an edge. - let effectful_call = sv_words(expression).iter().any(|(_, end, name)| { - effects.contains(*name) && after_trivia(&expression[*end..]).starts_with('(') - }); - if !effectful_call - && (literal_expression - || elaboration_constant(source, start, end, expression, &seeds)) - { + if literal_expression || elaboration_constant(source, start, end, expression, &seeds) { let scope = *scopes .last() .ok_or("constant initializer outside module scope")?; diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index ba181b27f41..70026ad889f 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -1243,3 +1243,59 @@ endmodule"#) (case always_timed_task_without_inline_timing_executes (source "always_timed_task_without_inline_timing_executes.sv" #"module Top(output bit q);task tick;#1;q=~q;endtask always tick();endmodule"#) (top Top)(run_until 1)(assert_eq q 1)(run_until 2)(assert_eq q 0)(run_until 3)(assert_eq q 1)) + + +(case initializer_function_effects_are_scoped_to_each_module + (source "initializer-module-effects.sv" #" + module Effectful(output bit value); + function automatic bit high_value();$display("effectful");return 0;endfunction + initial begin #1;value=high_value();end + endmodule + module Pure(output bit seen); + function automatic bit high_value();return 1;endfunction + bit clk=high_value(); + always_ff @(posedge clk)seen=1; + endmodule + module Top(output wire seen,output wire value); + Effectful effectful(.value(value));Pure pure_unit(.seen(seen)); + initial begin #2;$finish;end + endmodule + "#) + (top Top)(run_until 0)(assert_eq seen 0)(run_to_finish)(expect_output "effectful\n")) + +(case initializer_default_argument_effects_run_during_initialization + (source "initializer-default-effects.sv" #" + module Top(output wire seen); + function automatic bit stop_now();$finish;return 1;endfunction + function automatic bit wrapper(input bit x=stop_now());return x;endfunction + bit saved=wrapper(); + assign seen=saved; + initial $fatal(1,"initial ran after default argument finish"); + endmodule + "#) + (top Top)(run_to_finish)(assert_eq seen 0)(expect_output "")) + +(case continuous_zero_argument_function_tracks_global_reads + (source "continuous-function-dependencies.sv" #" + module Top(input bit[7:0]go,output wire[7:0]y,z); + function automatic bit[7:0]checked();if(go==0)$fatal(1,"early zero-argument call");return go;endfunction + assign y=checked(); + wire[7:0]other=checked();assign z=other; + initial begin #2;$finish;end + endmodule + "#) + (top Top)(set go 1)(run_until 0)(assert_eq y 1)(assert_eq z 1) + (set go 2)(run_until 1)(assert_eq y 2)(assert_eq z 2)(run_to_finish)(expect_output "")) + + +(case initializer_explicit_arguments_skip_effectful_defaults + (source "initializer-explicit-default.sv" #" + module Top(output bit seen); + function automatic bit side_effect();$fatal(1,"unused default ran");return 0;endfunction + function automatic bit wrapper(input bit value=side_effect());return value;endfunction + bit clk=wrapper(1); + always_ff @(posedge clk)seen=1; + initial begin #2;$finish;end + endmodule + "#) + (top Top)(run_until 0)(assert_eq seen 0)(run_to_finish)(expect_output "")) diff --git a/crates/celox-test-suite/tests/timed_protocol.rs b/crates/celox-test-suite/tests/timed_protocol.rs index 4acc4eadd21..90117dfc115 100644 --- a/crates/celox-test-suite/tests/timed_protocol.rs +++ b/crates/celox-test-suite/tests/timed_protocol.rs @@ -118,3 +118,47 @@ fn bare_continuous_function_calls_observe_staged_inputs() { celox_test_suite::script::sv::check_output(&log, &[]).unwrap(); std::fs::remove_dir_all(root).unwrap(); } + +#[test] +#[ignore = "requires Icarus, Verilator and a C++ compiler"] +fn callable_instance_connections_wait_for_staged_inputs() { + let text = r##"(group protocol (category sequential)) + +(case callable_instance_inputs_wait_for_staged_values + (source "instance-connection-effects.sv" #" + module Child #(parameter W=8)(input bit[W-1:0]value,output wire[W-1:0]seen);assign seen=value;endmodule + module Top(input bit[7:0]go,output wire[7:0]a,b); + function automatic bit[1:0]checked(input bit[7:0]value);if(!value)$fatal(1,"early instance connection");return value;endfunction + Child #(.W(8)) named(.value(checked(go)+2'd3),.seen(a)); + Child #(8) ordered(checked(go)+2'd3,b); + initial begin #2;$finish;end + endmodule + "#) + (top Top)(set go 1)(run_until 0)(assert_eq a 4)(assert_eq b 4) + (set go 2)(run_until 1)(assert_eq a 5)(assert_eq b 5)) + +"##; + let case = load_group("connections.vtest", text, no_std_library)[0]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../target/callable-connection-protocol") + .join(std::process::id().to_string()); + let frontend = celox_test_suite::sv::verification::SvFrontend; + let mut icarus = + celox_test_suite::icarus::Icarus::build_script(&frontend, case, &root.join("icarus")) + .unwrap(); + let icarus_result = icarus.run_testbench(); + let mut verilator = celox_test_suite::verilator::Verilator::build_script( + &frontend, + case, + &root.join("verilator"), + ) + .unwrap(); + let verilator_result = verilator.run_testbench(); + assert!( + icarus_result.is_ok() && verilator_result.is_ok(), + "Icarus: {icarus_result:?}; Verilator: {verilator_result:?}" + ); + let log = std::fs::read(root.join("verilator/protocol.log")).unwrap(); + celox_test_suite::script::sv::check_output(&log, &[]).unwrap(); + std::fs::remove_dir_all(root).unwrap(); +} diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index c7b097f4f4a..abbe12b3784 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -271,3 +271,19 @@ sv_backends! { fn false_wait_preserves_separate_hierarchical_write_times(sim) { sv_backends! { fn always_timed_task_without_inline_timing_executes(sim) { @case "timing::always_timed_task_without_inline_timing_executes"; } } + +sv_backends! { fn initializer_function_effects_are_scoped_to_each_module(sim) { + @case "timing::initializer_function_effects_are_scoped_to_each_module"; +} } + +sv_backends! { fn initializer_default_argument_effects_run_during_initialization(sim) { + @case "timing::initializer_default_argument_effects_run_during_initialization"; +} } + +sv_backends! { fn continuous_zero_argument_function_tracks_global_reads(sim) { + @case "timing::continuous_zero_argument_function_tracks_global_reads"; +} } + +sv_backends! { fn initializer_explicit_arguments_skip_effectful_defaults(sim) { + @case "timing::initializer_explicit_arguments_skip_effectful_defaults"; +} } From a51bc365d800835f71d7c5b1fddd0537d781b118 Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 16 Oct 2026 00:30:20 +0900 Subject: [PATCH 69/75] fix(suite): reject dynamic const initialization during timed staging --- .../src/frontend/timed_initializers.rs | 12 ++++--- .../src/sv/cases/timing.vtest | 25 +++++++++++++++ .../celox-test-suite/tests/timed_protocol.rs | 32 +++++++++++++++++++ .../tests/frontends/systemverilog/timing.rs | 8 +++++ 4 files changed, 73 insertions(+), 4 deletions(-) diff --git a/crates/celox-test-suite/src/frontend/timed_initializers.rs b/crates/celox-test-suite/src/frontend/timed_initializers.rs index 94e003c5550..e5015537644 100644 --- a/crates/celox-test-suite/src/frontend/timed_initializers.rs +++ b/crates/celox-test-suite/src/frontend/timed_initializers.rs @@ -307,10 +307,7 @@ pub(super) fn rewrites( let RefNode::DataDeclaration(sv_parser::DataDeclaration::Variable(variable)) = node else { continue; }; - // Const declarations cannot be assigned procedurally. - if variable.nodes.0.is_some() { - continue; - } + let is_const = variable.nodes.0.is_some(); let (start, end) = span(&tree, node).ok_or("missing declaration source span")?; let mut removals = Vec::new(); let mut assignments = String::new(); @@ -380,6 +377,13 @@ pub(super) fn rewrites( )); continue; } + if is_const { + return Err(crate::script::sv::Unsupported(format!( + "dynamic const initializer `{}` cannot be staged after host setup", + name.trim() + )) + .into()); + } let mut suffix = equal_start; let temporary = loop { let temporary = format!("{}_initializer_value_{suffix}", names.package); diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 70026ad889f..5f10bf77507 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -1299,3 +1299,28 @@ endmodule"#) endmodule "#) (top Top)(run_until 0)(assert_eq seen 0)(run_to_finish)(expect_output "")) + + +(case constant_continuous_function_edges_match_staged_startup + (source "constant-continuous-clocks.sv" #" + module Top(output bit net_seen,assign_seen); + function automatic bit high_value();return 1;endfunction + wire net_clock=high_value(); + wire assign_clock;assign assign_clock=high_value(); + always_ff @(posedge net_clock)net_seen=1; + always_ff @(posedge assign_clock)assign_seen=1; + initial begin #2;$finish;end + endmodule + "#) + (top Top)(run_until 0)(assert_eq net_seen 1)(assert_eq assign_seen 1)(run_to_finish)) + +(case escaped_initializer_function_effects_finish_during_initialization + (source "escaped-initializer-effect.sv" #" + module Top(output wire seen); + function automatic bit \stop_now ();$finish;return 1;endfunction + bit saved=\stop_now (); + assign seen=saved; + initial $fatal(1,"initial ran after escaped initializer finish"); + endmodule + "#) + (top Top)(run_to_finish)(assert_eq seen 0)(expect_output "")) diff --git a/crates/celox-test-suite/tests/timed_protocol.rs b/crates/celox-test-suite/tests/timed_protocol.rs index 90117dfc115..8d304e5c297 100644 --- a/crates/celox-test-suite/tests/timed_protocol.rs +++ b/crates/celox-test-suite/tests/timed_protocol.rs @@ -162,3 +162,35 @@ fn callable_instance_connections_wait_for_staged_inputs() { celox_test_suite::script::sv::check_output(&log, &[]).unwrap(); std::fs::remove_dir_all(root).unwrap(); } + +#[test] +fn dynamic_const_initializers_are_rejected_before_tool_invocation() { + let text = r##"(group protocol (category sequential)) + (case dynamic_const (source "const.sv" #"module Top(input bit a,output wire seen);const bit saved=a;assign seen=saved;initial #2 $finish;endmodule"#) + (top Top)(set a 1)(run_until 0)(assert_eq seen 1))"##; + let case = load_group("const.vtest", text, no_std_library)[0]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../target/const-initializer-protocol") + .join(std::process::id().to_string()); + let frontend = celox_test_suite::sv::verification::SvFrontend; + let icarus = + celox_test_suite::icarus::Icarus::build_script(&frontend, case, &root.join("icarus")) + .err() + .expect("dynamic const reached Icarus compilation"); + assert!( + icarus.is::(), + "{icarus}" + ); + let verilator = celox_test_suite::verilator::Verilator::build_script( + &frontend, + case, + &root.join("verilator"), + ) + .err() + .expect("dynamic const reached Verilator compilation"); + assert!( + verilator.is::(), + "{verilator}" + ); + std::fs::remove_dir_all(root).unwrap(); +} diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index abbe12b3784..871a78dddb9 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -287,3 +287,11 @@ sv_backends! { fn continuous_zero_argument_function_tracks_global_reads(sim) { sv_backends! { fn initializer_explicit_arguments_skip_effectful_defaults(sim) { @case "timing::initializer_explicit_arguments_skip_effectful_defaults"; } } + +sv_backends! { fn constant_continuous_function_edges_match_staged_startup(sim) { + @case "timing::constant_continuous_function_edges_match_staged_startup"; +} } + +sv_backends! { fn escaped_initializer_function_effects_finish_during_initialization(sim) { + @case "timing::escaped_initializer_function_effects_finish_during_initialization"; +} } From 78e91c71c97c44d2bb8fb649ef68cc9ef61a3b96 Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 16 Oct 2026 01:12:56 +0900 Subject: [PATCH 70/75] fix(suite): preserve callable connection shapes and driver types --- .../src/frontend/timed_connections.rs | 16 +- .../celox-test-suite/src/frontend/timed_ff.rs | 174 +++++++++++++++++- .../src/sv/cases/timing.vtest | 26 +++ .../celox-test-suite/tests/timed_protocol.rs | 69 ++++++- 4 files changed, 274 insertions(+), 11 deletions(-) diff --git a/crates/celox-test-suite/src/frontend/timed_connections.rs b/crates/celox-test-suite/src/frontend/timed_connections.rs index 10ebd3367fa..51e7feb6261 100644 --- a/crates/celox-test-suite/src/frontend/timed_connections.rs +++ b/crates/celox-test-suite/src/frontend/timed_connections.rs @@ -32,10 +32,7 @@ pub(super) fn rewrites( let mut replacements = Vec::new(); let mut drivers = String::new(); for instance in module.nodes.2.contents() { - // Array connections have separate broadcast/distribution rules. - if !instance.nodes.0.nodes.1.is_empty() { - continue; - } + let array = !instance.nodes.0.nodes.1.is_empty(); let Some(connections) = &instance.nodes.1.nodes.1 else { continue; }; @@ -97,7 +94,16 @@ pub(super) fn rewrites( } suffix += 1; }; - drivers.push_str(&format!("reg [$bits({instance_name} .{port} )-1:0] {name};\nalways_comb begin if ({}::started) {name} = {expression}; end\n", names.package)); + // Preserve the actual's self-determined width for instance + // arrays: one port width broadcasts, the aggregate width + // distributes (IEEE 1800-2023 23.3.3.5). A scalar connection + // instead supplies its port's assignment context. + let width = if array { + expression.clone() + } else { + format!("{instance_name} .{port} ") + }; + drivers.push_str(&format!("reg [$bits({width} )-1:0] {name};\nalways_comb begin if ({}::started) {name} = {expression}; end\n", names.package)); replacements.push((begin, finish, name)); } } diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index 4e059617a68..6708caab2c6 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -101,7 +101,7 @@ pub(super) fn gated_rhs( // Icarus evaluates function operands in a continuous ternary eagerly. Use // a procedural gate and retain the original net driver (and its delays and -// strengths). The temporary has the destination's packed assignment width. +// strengths). Named destinations retain their declared assignment type. pub(super) fn gated_continuous( source: &str, start: usize, @@ -129,7 +129,14 @@ pub(super) fn gated_continuous( let left = source[lhs_start..at].trim(); lhs_name = Some(if net_declaration { // Net declaration assignments name an entire net. - sv_words(left).last()?.2.to_owned() + tasks + .driver_types + .get(source) + .into_iter() + .flatten() + .find(|(offset, _, _, _)| lhs_start <= *offset && *offset < at) + .map(|(_, id, _, _)| id.clone()) + .or_else(|| sv_words(left).last().map(|word| word.2.to_owned()))? } else { // Skip optional drive strength and delay controls. let mut begin = trivia(left, 0); @@ -161,8 +168,9 @@ pub(super) fn gated_continuous( } suffix += 1; }; + let declaration = tasks.driver_declaration(source, start, &lhs, &name); drivers.push_str(&format!( - "reg [$bits({lhs} )-1:0] {name};\nalways_comb begin if ({}::started) {name} = {expression}; end\n", names.package + "{declaration}\nalways_comb begin if ({}::started) {name} = {expression}; end\n", names.package )); output.push_str(&source[previous..begin]); output.push_str(&format!(" {name}")); @@ -584,6 +592,7 @@ pub(super) struct TaskTiming { pub(super) ports: BTreeMap>, pub(super) inputs: BTreeMap>, values: BTreeMap>, + driver_types: BTreeMap>, units: BTreeMap, import_clauses: BTreeMap, Option)>>>, generate_scopes: BTreeMap>, @@ -666,6 +675,33 @@ fn lexical_scope_at(source: &str, at: usize, generates: &[(usize, usize)]) -> Ve } impl TaskTiming { + fn driver_declaration(&self, source: &str, at: usize, lhs: &str, name: &str) -> String { + let scope = self.lexical_scope(source, at); + let declaration = self + .driver_types + .get(source) + .into_iter() + .flatten() + .filter(|(offset, id, _, _)| { + id.trim().trim_start_matches('\\') == lhs.trim().trim_start_matches('\\') + && scope.starts_with(&self.lexical_scope(source, *offset)) + }) + .max_by_key(|(offset, _, _, _)| self.lexical_scope(source, *offset).len()); + if let Some((_, _, datatype, dimensions)) = declaration { + let datatype = datatype.trim(); + let implicit = datatype.is_empty() + || datatype.starts_with('[') + || datatype.starts_with("signed") + || datatype.starts_with("unsigned"); + return format!( + "{}{datatype} {name} {dimensions};", + if implicit { "logic " } else { "" } + ); + } + // Part-selects and concatenations have their packed assignment type. + format!("reg [$bits({lhs} )-1:0] {name};") + } + fn lexical_scope(&self, source: &str, at: usize) -> Vec { lexical_scope_at( source, @@ -837,6 +873,138 @@ impl TaskTiming { }) .map_or(offset, |(_, origin)| origin) }; + let mut driver_types = Vec::new(); + let mut inherited_port_type = None; + let text = |node| { + timed_initializers::span(&tree, node) + .map(|(a, b)| source[a..b].to_owned()) + .unwrap_or_default() + }; + let identifier = |offset| { + sv_words(&source[offset..]) + .first() + .map(|word| word.2.to_owned()) + .unwrap_or_default() + }; + for node in &tree { + use sv_parser::RefNode; + match node { + RefNode::NetDeclaration(sv_parser::NetDeclaration::NetType(n)) => { + let datatype = text(RefNode::DataTypeOrImplicit(&n.nodes.3)); + for declaration in n.nodes.5.nodes.0.contents() { + if let Some((offset, _)) = timed_initializers::span( + &tree, + RefNode::NetIdentifier(&declaration.nodes.0), + ) { + let id = identifier(offset); + let dimensions = declaration + .nodes + .1 + .iter() + .map(|d| text(RefNode::UnpackedDimension(d))) + .collect::>() + .join(" "); + driver_types.push((offset, id, datatype.clone(), dimensions)); + } + } + } + RefNode::ModuleDeclaration(_) | RefNode::InterfaceDeclaration(_) => { + inherited_port_type = None; + } + RefNode::AnsiPortDeclarationNet(n) => { + if let Some(header) = &n.nodes.0 { + inherited_port_type=match header { + sv_parser::NetPortHeaderOrInterfacePortHeader::NetPortHeader(header) => match &header.nodes.1 { + sv_parser::NetPortType::DataType(port) => Some(text(RefNode::DataTypeOrImplicit(&port.nodes.1))), + _ => None, + }, + _ => None, + }; + } + if let (Some(datatype), Some((offset, _))) = ( + &inherited_port_type, + timed_initializers::span( + &tree, + RefNode::PortIdentifier(&n.nodes.1), + ), + ) { + let dimensions = n + .nodes + .2 + .iter() + .map(|d| text(RefNode::UnpackedDimension(d))) + .collect::>() + .join(" "); + driver_types.push(( + offset, + identifier(offset), + datatype.clone(), + dimensions, + )); + } + } + RefNode::AnsiPortDeclarationVariable(n) => { + if let Some(header) = &n.nodes.0 { + inherited_port_type = Some( + text(RefNode::VarDataType(&header.nodes.1.nodes.0)) + .trim_start_matches("var ") + .to_owned(), + ); + } + if let (Some(datatype), Some((offset, _))) = ( + &inherited_port_type, + timed_initializers::span( + &tree, + RefNode::PortIdentifier(&n.nodes.1), + ), + ) { + let dimensions = n + .nodes + .2 + .iter() + .map(|d| text(RefNode::VariableDimension(d))) + .collect::>() + .join(" "); + driver_types.push(( + offset, + identifier(offset), + datatype.clone(), + dimensions, + )); + } + } + RefNode::DataDeclaration(sv_parser::DataDeclaration::Variable(n)) => { + let datatype = text(RefNode::DataTypeOrImplicit(&n.nodes.3)); + for declaration in n.nodes.4.nodes.0.contents() { + if let sv_parser::VariableDeclAssignment::Variable(declaration) = + declaration + { + if let Some((offset, _)) = timed_initializers::span( + &tree, + RefNode::VariableIdentifier(&declaration.nodes.0), + ) { + let id = identifier(offset); + let dimensions = declaration + .nodes + .1 + .iter() + .map(|d| text(RefNode::VariableDimension(d))) + .collect::>() + .join(" "); + driver_types.push(( + offset, + id, + datatype.clone(), + dimensions, + )); + } + } + } + } + _ => {} + } + } + result.driver_types.insert(source.clone(), driver_types); let mut values = Vec::new(); for node in &tree { use sv_parser::RefNode; diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 5f10bf77507..366af06ca86 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -1324,3 +1324,29 @@ endmodule"#) endmodule "#) (top Top)(run_to_finish)(assert_eq seen 0)(expect_output "")) + +(case constant_comb_if_discards_unreachable_pulse_branch + (source "constant-comb-if.sv" #"module Top(input bit go,output bit[7:0]q);bit v; + always_comb if(1'b1)v=go;else begin v=0;v=1;end + initial forever begin @(v);q++;end endmodule"#) + (top Top)(run_until 0)(assert_eq q 0)(set go 1)(run_until 1)(assert_eq q 1) + (set go 0)(run_until 2)(assert_eq q 2)) + +(case constant_child_ff_case_discards_unreachable_pulse_arm + (source "constant-child-ff-case.sv" #"module Child(input bit clk,output bit v); + always @(posedge clk) case(2'd1) 2'd1:v<=~v;default:begin v<=0;v<=1;end endcase endmodule + module Top(input bit clk,output bit[7:0]q);wire v;Child c(clk,v); + initial forever begin @(v);q++;end endmodule"#) + (top Top)(run_until 0)(assert_eq q 0)(set clk 1)(run_until 1)(assert_eq q 1) + (set clk 0)(run_until 2)(set clk 1)(run_until 3)(assert_eq q 2)) + +(case typed_continuous_enum_drivers_preserve_assignment_types + (source "typed-continuous-enum.sv" #"module Top(input bit[1:0]go,output wire a,b); + typedef enum logic {LOW,HIGH} level_t; + function automatic level_t checked(input bit[1:0]value); + if(!value)$fatal(1,"early enum driver");if(value[0])return HIGH;return LOW;endfunction + wire level_t first=checked(go); + wire level_t second;assign second=checked(go); + assign a=first;assign b=second;initial #2 $finish;endmodule"#) + (top Top)(set go 1)(run_until 0)(assert_eq a 1)(assert_eq b 1) + (set go 2)(run_until 1)(assert_eq a 0)(assert_eq b 0)) diff --git a/crates/celox-test-suite/tests/timed_protocol.rs b/crates/celox-test-suite/tests/timed_protocol.rs index 8d304e5c297..2ab0428842f 100644 --- a/crates/celox-test-suite/tests/timed_protocol.rs +++ b/crates/celox-test-suite/tests/timed_protocol.rs @@ -127,15 +127,22 @@ fn callable_instance_connections_wait_for_staged_inputs() { (case callable_instance_inputs_wait_for_staged_values (source "instance-connection-effects.sv" #" module Child #(parameter W=8)(input bit[W-1:0]value,output wire[W-1:0]seen);assign seen=value;endmodule - module Top(input bit[7:0]go,output wire[7:0]a,b); + module Top(input bit[7:0]go,output wire[7:0]a,b,output wire[15:0]broadcast,distributed,ordered_array,signed_array); function automatic bit[1:0]checked(input bit[7:0]value);if(!value)$fatal(1,"early instance connection");return value;endfunction Child #(.W(8)) named(.value(checked(go)+2'd3),.seen(a)); Child #(8) ordered(checked(go)+2'd3,b); + function automatic bit[7:0]broadcast_value(input bit[7:0]value);if(!value)$fatal(1,"early array broadcast");return value+8'd3;endfunction + function automatic bit[15:0]distributed_value(input bit[7:0]value);if(!value)$fatal(1,"early array distribution");return {value+8'd1,value};endfunction + function automatic bit signed[7:0]negative_value(input bit[7:0]value);if(!value)$fatal(1,"early signed broadcast");return -value;endfunction + Child #(8) bn[1:0](.value(broadcast_value(go)),.seen(broadcast)); + Child #(8) dn[0:1](.value(distributed_value(go)),.seen(distributed)); + Child #(8) dp[1:0](distributed_value(go),ordered_array); + Child #(8) sn[1:0](negative_value(go),signed_array); initial begin #2;$finish;end endmodule "#) - (top Top)(set go 1)(run_until 0)(assert_eq a 4)(assert_eq b 4) - (set go 2)(run_until 1)(assert_eq a 5)(assert_eq b 5)) + (top Top)(set go 1)(run_until 0)(assert_eq a 4)(assert_eq b 4)(assert_eq broadcast 1028)(assert_eq distributed 513)(assert_eq ordered_array 513)(assert_eq signed_array 65535) + (set go 2)(run_until 1)(assert_eq a 5)(assert_eq b 5)(assert_eq broadcast 1285)(assert_eq distributed 770)(assert_eq ordered_array 770)(assert_eq signed_array 65278)) "##; let case = load_group("connections.vtest", text, no_std_library)[0]; @@ -163,6 +170,37 @@ fn callable_instance_connections_wait_for_staged_inputs() { std::fs::remove_dir_all(root).unwrap(); } +#[test] +#[ignore = "requires Icarus, Verilator and a C++ compiler"] +fn typed_continuous_drivers_preserve_enum_assignment_type() { + let text = r##"(group protocol (category sequential)) + (case typed_driver (source "typed-driver.sv" #" + module Top(input bit go,output wire a,b); + typedef enum logic {LOW,HIGH} level_t; + function automatic level_t checked(input bit value); if(!value)$fatal(1,"early enum driver");return HIGH;endfunction + wire level_t first=checked(go); + wire level_t second;assign second=checked(go); + assign a=first;assign b=second;initial #2 $finish; + endmodule"#)(top Top)(set go 1)(run_until 0)(assert_eq a 1)(assert_eq b 1))"##; + let case = load_group("typed.vtest", text, no_std_library)[0]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../target/typed-driver-protocol") + .join(std::process::id().to_string()); + let frontend = celox_test_suite::sv::verification::SvFrontend; + let mut icarus = + celox_test_suite::icarus::Icarus::build_script(&frontend, case, &root.join("icarus")) + .unwrap(); + let mut verilator = celox_test_suite::verilator::Verilator::build_script( + &frontend, + case, + &root.join("verilator"), + ) + .unwrap(); + assert!(icarus.run_testbench().is_ok()); + assert!(verilator.run_testbench().is_ok()); + std::fs::remove_dir_all(root).unwrap(); +} + #[test] fn dynamic_const_initializers_are_rejected_before_tool_invocation() { let text = r##"(group protocol (category sequential)) @@ -194,3 +232,28 @@ fn dynamic_const_initializers_are_rejected_before_tool_invocation() { ); std::fs::remove_dir_all(root).unwrap(); } + +#[test] +#[ignore = "requires Verilator and a C++ compiler; Icarus lacks unpacked function returns"] +fn unpacked_continuous_drivers_preserve_destination_shape() { + let text = r##"(group protocol (category sequential)) + (case unpacked_driver (source "unpacked-driver.sv" #" + module Child(input bit[7:0]go,output wire[7:0]a,b); + typedef logic[7:0] pair_t[0:1]; + function automatic pair_t checked(input bit[7:0]value); if(!value)$fatal(1,"early array driver");return '{value,value+8'd1};endfunction + wire logic[7:0] first[0:1]=checked(go); + wire pair_t second;assign second=checked(go); + assign a=first[0]+first[1];assign b=second[0]+second[1];initial #2 $finish; + endmodule + module Top(input bit[7:0]go,output wire[7:0]a,b);Child c(go,a,b);endmodule"#)(top Top)(set go 1)(run_until 0)(assert_eq a 3)(assert_eq b 3) + (set go 2)(run_until 1)(assert_eq a 5)(assert_eq b 5))"##; + let case = load_group("unpacked.vtest", text, no_std_library)[0]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../target/unpacked-driver-protocol") + .join(std::process::id().to_string()); + let frontend = celox_test_suite::sv::verification::SvFrontend; + let mut verilator = + celox_test_suite::verilator::Verilator::build_script(&frontend, case, &root).unwrap(); + assert!(verilator.run_testbench().is_ok()); + std::fs::remove_dir_all(root).unwrap(); +} From 24c0a54aee263ebe43f121876e39ce08aab70bf7 Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 16 Oct 2026 01:17:39 +0900 Subject: [PATCH 71/75] test(sv): register constant pulse and typed driver regressions --- crates/celox/tests/frontends/systemverilog/timing.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 871a78dddb9..c550bc41003 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -295,3 +295,15 @@ sv_backends! { fn constant_continuous_function_edges_match_staged_startup(sim) { sv_backends! { fn escaped_initializer_function_effects_finish_during_initialization(sim) { @case "timing::escaped_initializer_function_effects_finish_during_initialization"; } } + +sv_backends! { fn constant_comb_if_discards_unreachable_pulse_branch(sim) { + @case "timing::constant_comb_if_discards_unreachable_pulse_branch"; +} } + +sv_backends! { fn constant_child_ff_case_discards_unreachable_pulse_arm(sim) { + @case "timing::constant_child_ff_case_discards_unreachable_pulse_arm"; +} } + +sv_backends! { fn typed_continuous_enum_drivers_preserve_assignment_types(sim) { + @case "timing::typed_continuous_enum_drivers_preserve_assignment_types"; +} } From dfa26c1f017cb54e537208578be89a77f093a042 Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 16 Oct 2026 02:21:07 +0900 Subject: [PATCH 72/75] fix(suite): preserve ordered macros throughout timed staging --- crates/celox-test-suite/src/frontend.rs | 93 +++++++++++++++---- crates/celox-test-suite/src/script/timed.rs | 34 ++++++- .../src/sv/cases/timing.vtest | 24 +++++ .../celox-test-suite/src/sv/verification.rs | 18 +++- .../celox-test-suite/tests/timed_protocol.rs | 45 +++++++++ .../tests/frontends/systemverilog/timing.rs | 12 +++ 6 files changed, 208 insertions(+), 18 deletions(-) diff --git a/crates/celox-test-suite/src/frontend.rs b/crates/celox-test-suite/src/frontend.rs index c62d4fbd04d..d4b00e3e708 100644 --- a/crates/celox-test-suite/src/frontend.rs +++ b/crates/celox-test-suite/src/frontend.rs @@ -44,6 +44,11 @@ pub trait Frontend: Sync { fn source_extension(&self) -> &'static str; fn prepare(&self, design: &Design) -> Result; + + /// Prepare declarations and sources using the external adapter's macros. + fn prepare_with_defines(&self, design: &Design, _defines: &[&str]) -> Result { + self.prepare(design) + } } /// The files and settings an adapter compiles. @@ -73,17 +78,26 @@ pub(crate) fn stage( source.text.as_bytes(), )?; } - let mut prepared = - std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| frontend.prepare(design))) - .map_err(|error| EmissionError(panic_message(error.as_ref())))??; + let mut prepared = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + frontend.prepare_with_defines(design, defines) + })) + .map_err(|error| EmissionError(panic_message(error.as_ref())))??; if design.timed { - for (index, source) in prepared.sources.iter_mut().enumerate() { - let path = design - .sources - .get(index) - .map_or(Path::new("timed.sv"), |source| source.path.as_path()); - *source = expanded_timed_source(source, defines, path)?; - } + let paths = prepared + .sources + .iter() + .enumerate() + .map(|(index, source)| { + ( + source.as_str(), + design + .sources + .get(index) + .map_or(Path::new("timed.sv"), |source| source.path.as_path()), + ) + }) + .collect::>(); + prepared.sources = expanded_timed_sources(&paths, defines)?; } let task_timing = timed_ff::TaskTiming::new(&prepared.sources); let control_names = timed_names(&prepared.sources); @@ -263,13 +277,60 @@ impl TimedNames { } } +#[cfg(test)] +mod ordered_macro_tests { + use super::*; + #[test] + fn definitions_redefinitions_and_undef_follow_source_order() { + let sources = [ + ("`define ENABLED\n`define VALUE 1\n", Path::new("header.sv")), + ( + "`ifdef ENABLED\nmodule First;initial $display(`VALUE);endmodule\n`endif\n`undef VALUE\n`define VALUE 2\n", + Path::new("first.sv"), + ), + ( + "module Second;initial $display(`VALUE);endmodule\n`undef ENABLED\n", + Path::new("second.sv"), + ), + ( + "`ifdef ENABLED\nmodule Wrong;endmodule\n`else\nmodule Last;endmodule\n`endif\n", + Path::new("last.sv"), + ), + ]; + let expanded = expanded_timed_sources(&sources, &[]).unwrap(); + assert!(expanded[1].contains("$display(1)")); + assert!(expanded[2].contains("$display(2)")); + assert!(expanded[3].contains("module Last")); + assert!(!expanded[3].contains("module Wrong")); + } +} + +#[cfg(test)] fn expanded_timed_source(source: &str, defines: &[&str], path: &Path) -> Result { - let syntax = celox_sv_analyzer::syntax::parse_source_with_defines(source, path, defines)?; - let root = (&syntax).into_iter().next().ok_or("empty timed source")?; - Ok(syntax - .get_str(vec![root]) - .ok_or("missing timed source text")? - .to_owned()) + Ok(expanded_timed_sources(&[(source, path)], defines)?.remove(0)) +} + +pub(crate) fn expanded_timed_sources( + sources: &[(&str, &Path)], + names: &[&str], +) -> Result> { + let mut defines: sv_parser::Defines = Default::default(); + for name in names { + defines.insert( + (*name).to_owned(), + Some(sv_parser::Define::new((*name).to_owned(), Vec::new(), None)), + ); + } + let includes: Vec<&Path> = Vec::new(); + let mut result = Vec::new(); + for (source, path) in sources { + let (expanded, next) = + sv_parser::preprocess_str(source, path, &defines, &includes, true, false, 0, 0) + .map_err(|error| format!("timed source preprocessing: {error}"))?; + defines = next; + result.push(expanded.text().to_owned()); + } + Ok(result) } fn timed_source(source: &str, names: &TimedNames, tasks: &timed_ff::TaskTiming) -> Result { diff --git a/crates/celox-test-suite/src/script/timed.rs b/crates/celox-test-suite/src/script/timed.rs index 27570719ff8..3c492d2945b 100644 --- a/crates/celox-test-suite/src/script/timed.rs +++ b/crates/celox-test-suite/src/script/timed.rs @@ -19,7 +19,7 @@ pub(crate) fn validate_timed_design_with_defines(design: &Design, names: &[&str] } let includes: Vec<&std::path::Path> = Vec::new(); for source in &design.sources { - let (active, _) = sv_parser::preprocess_str( + let (active, next_defines) = sv_parser::preprocess_str( &source.text, &source.path, &defines, @@ -30,6 +30,7 @@ pub(crate) fn validate_timed_design_with_defines(design: &Design, names: &[&str] 0, ) .map_err(|error| format!("timed source preprocessing: {error}"))?; + defines = next_defines; let text = active.text(); if sv_words(text).iter().any(|(start, _, word)| { matches!(*word, "timeunit" | "timeprecision") @@ -137,6 +138,37 @@ mod tests { let source = "// `timescale 10ns/1ps\nmodule Top; bit timescale; initial $display(\"timeunit 10ns\"); endmodule"; assert!(validate_timed_design(&design(source)).is_ok()); } + #[test] + fn source_order_controls_macro_hidden_scale_validation() { + for directive in [ + "`timescale 10ns/1ps", + "`resetall", + "timeunit 10ns;", + "timeprecision 1fs;", + ] { + for undef in [false, true] { + let text = format!( + r##"(group timing (category sequential)) + (case scale (source "header.sv" #"`define SCALE_ON +module Header;endmodule"#) + (source "top.sv" #"{} +`ifdef SCALE_ON +{} +`endif +module Top;endmodule"#) (top Top)(run_until 0))"##, + if undef { "`undef SCALE_ON" } else { "" }, + directive + ); + let case = crate::load_group("timing.vtest", &text, crate::no_std_library)[0]; + assert_eq!( + validate_timed_design(&case.design()).is_ok(), + undef, + "{directive}" + ); + } + } + } + #[test] fn scales_follow_active_preprocessor_defines() { for directive in [ diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 366af06ca86..db0fab4cc7c 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -1350,3 +1350,27 @@ endmodule"#) assign a=first;assign b=second;initial #2 $finish;endmodule"#) (top Top)(set go 1)(run_until 0)(assert_eq a 1)(assert_eq b 1) (set go 2)(run_until 1)(assert_eq a 0)(assert_eq b 0)) + +(case constant_child_loop_exit_keeps_one_write + (source "constant_child_loop_exit_keeps_one_write.sv" #"module Child(input bit clk,output bit v); + always @(posedge clk)begin repeat(2)begin v=~v;if(1'b1)break;end end endmodule + module Top(input bit clk,output bit[7:0]q);wire v;Child c(clk,v); + initial forever begin @(v);q++;end endmodule"#) + (top Top)(run_until 0)(assert_eq q 0)(set clk 1)(run_until 1)(assert_eq q 1) + (set clk 0)(run_until 2)(set clk 1)(run_until 3)(assert_eq q 2)) + +(case constant_child_case_exit_keeps_one_write + (source "constant_child_case_exit_keeps_one_write.sv" #"module Child(input bit clk,output bit v); + always @(posedge clk)begin repeat(2)begin v=~v;case(1)1:break;default:;endcase end end endmodule + module Top(input bit clk,output bit[7:0]q);wire v;Child c(clk,v); + initial forever begin @(v);q++;end endmodule"#) + (top Top)(run_until 0)(assert_eq q 0)(set clk 1)(run_until 1)(assert_eq q 1) + (set clk 0)(run_until 2)(set clk 1)(run_until 3)(assert_eq q 2)) + +(case four_state_child_if_keeps_one_write + (source "four_state_child_if_keeps_one_write.sv" #"module Child(input bit clk,output bit v); + always @(posedge clk)begin if(4'bx001)v=~v;else begin v=0;v=1;end end endmodule + module Top(input bit clk,output bit[7:0]q);wire v;Child c(clk,v); + initial forever begin @(v);q++;end endmodule"#) + (top Top)(run_until 0)(assert_eq q 0)(set clk 1)(run_until 1)(assert_eq q 1) + (set clk 0)(run_until 2)(set clk 1)(run_until 3)(assert_eq q 2)) diff --git a/crates/celox-test-suite/src/sv/verification.rs b/crates/celox-test-suite/src/sv/verification.rs index bae5ce0ad28..6f197332d0e 100644 --- a/crates/celox-test-suite/src/sv/verification.rs +++ b/crates/celox-test-suite/src/sv/verification.rs @@ -156,7 +156,23 @@ impl Frontend for SvFrontend { } fn prepare(&self, design: &Design) -> Result { - let info = design_info(design); + self.prepare_with_defines(design, &[]) + } + + fn prepare_with_defines(&self, design: &Design, defines: &[&str]) -> Result { + let mut analyzed = design.clone(); + if design.timed { + let sources = design + .sources + .iter() + .map(|s| (s.text.as_str(), s.path.as_path())) + .collect::>(); + let expanded = crate::frontend::expanded_timed_sources(&sources, defines)?; + for (source, text) in analyzed.sources.iter_mut().zip(expanded) { + source.text = text; + } + } + let info = design_info(&analyzed); Ok(PreparedDesign { sources: design .sources diff --git a/crates/celox-test-suite/tests/timed_protocol.rs b/crates/celox-test-suite/tests/timed_protocol.rs index 2ab0428842f..65d955ffabc 100644 --- a/crates/celox-test-suite/tests/timed_protocol.rs +++ b/crates/celox-test-suite/tests/timed_protocol.rs @@ -257,3 +257,48 @@ fn unpacked_continuous_drivers_preserve_destination_shape() { assert!(verilator.run_testbench().is_ok()); std::fs::remove_dir_all(root).unwrap(); } + +#[test] +#[ignore = "requires Icarus, Verilator and a C++ compiler"] +fn timed_sources_share_ordered_macro_definitions() { + let text = r##"(group protocol (category sequential)) + (case ordered_macros + (source "defines.sv" #"`define ENABLE_WRITE +`define WIDTH 4 +`define STORE(v) q=(v) +module Definitions;endmodule"#) + (source "top.sv" #"module Top(input bit[`WIDTH-1:0]go,output bit[`WIDTH-1:0]q); +initial begin #1; +`ifdef ENABLE_WRITE +`STORE(go); +`else +q=0; +`endif +end endmodule"#) + (source "tail.sv" #"`undef ENABLE_WRITE +module Tail(output wire value); +`ifdef ENABLE_WRITE +assign value=0; +`else +assign value=1; +`endif +endmodule"#) + (top Top)(set go 3)(run_until 1)(assert_eq q 3))"##; + let case = load_group("macros.vtest", text, no_std_library)[0]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../target/ordered-macro-protocol") + .join(std::process::id().to_string()); + let frontend = celox_test_suite::sv::verification::SvFrontend; + let mut icarus = + celox_test_suite::icarus::Icarus::build_script(&frontend, case, &root.join("icarus")) + .unwrap(); + let mut verilator = celox_test_suite::verilator::Verilator::build_script( + &frontend, + case, + &root.join("verilator"), + ) + .unwrap(); + assert!(icarus.run_testbench().is_ok()); + assert!(verilator.run_testbench().is_ok()); + std::fs::remove_dir_all(root).unwrap(); +} diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index c550bc41003..8b29bfa1285 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -307,3 +307,15 @@ sv_backends! { fn constant_child_ff_case_discards_unreachable_pulse_arm(sim) { sv_backends! { fn typed_continuous_enum_drivers_preserve_assignment_types(sim) { @case "timing::typed_continuous_enum_drivers_preserve_assignment_types"; } } + +sv_backends! { fn constant_child_loop_exit_keeps_one_write(sim) { + @case "timing::constant_child_loop_exit_keeps_one_write"; +} } + +sv_backends! { fn constant_child_case_exit_keeps_one_write(sim) { + @case "timing::constant_child_case_exit_keeps_one_write"; +} } + +sv_backends! { fn four_state_child_if_keeps_one_write(sim) { + @case "timing::four_state_child_if_keeps_one_write"; +} } From ea9be79124e19593833298456fbf4b0312821cd0 Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 16 Oct 2026 03:31:54 +0900 Subject: [PATCH 73/75] fix(suite): retain nominal types in callable input drivers --- .../src/frontend/timed_connections.rs | 15 +++-- .../celox-test-suite/src/frontend/timed_ff.rs | 64 +++++++++++++++++++ .../src/sv/cases/timing.vtest | 8 +++ .../celox-test-suite/tests/timed_protocol.rs | 52 +++++++++++++++ .../tests/frontends/systemverilog/timing.rs | 6 ++ 5 files changed, 139 insertions(+), 6 deletions(-) diff --git a/crates/celox-test-suite/src/frontend/timed_connections.rs b/crates/celox-test-suite/src/frontend/timed_connections.rs index 51e7feb6261..27752b1b2b7 100644 --- a/crates/celox-test-suite/src/frontend/timed_connections.rs +++ b/crates/celox-test-suite/src/frontend/timed_connections.rs @@ -98,12 +98,15 @@ pub(super) fn rewrites( // arrays: one port width broadcasts, the aggregate width // distributes (IEEE 1800-2023 23.3.3.5). A scalar connection // instead supplies its port's assignment context. - let width = if array { - expression.clone() - } else { - format!("{instance_name} .{port} ") - }; - drivers.push_str(&format!("reg [$bits({width} )-1:0] {name};\nalways_comb begin if ({}::started) {name} = {expression}; end\n", names.package)); + let declaration = tasks.connection_declaration( + module_name, + &port, + instance_name, + array, + &expression, + &name, + )?; + drivers.push_str(&format!("{declaration}\nalways_comb begin if ({}::started) {name} = {expression}; end\n", names.package)); replacements.push((begin, finish, name)); } } diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index 6708caab2c6..1f42bf8268c 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -702,6 +702,70 @@ impl TaskTiming { format!("reg [$bits({lhs} )-1:0] {name};") } + pub(super) fn connection_declaration( + &self, + module: &str, + port: &str, + instance: &str, + array: bool, + expression: &str, + name: &str, + ) -> Result { + let declaration = self.driver_types.iter().find_map(|(source, declarations)| { + declarations.iter().find(|(offset, id, _, _)| { + id.trim_start_matches('\\') == port.trim().trim_start_matches('\\') + && container_at(source, *offset) == module + && self.lexical_scope(source, *offset).len() == 1 + }) + }); + if declaration.is_none() { + return Err(format!( + "missing input-port type for {module}.{port} in timed callable staging" + ) + .into()); + } + if let Some((_, _, datatype, dimensions)) = declaration { + let datatype = datatype.trim(); + let builtin = datatype.is_empty() + || datatype.starts_with('[') + || sv_words(datatype).first().is_some_and(|w| { + matches!( + w.2, + "bit" + | "logic" + | "reg" + | "signed" + | "unsigned" + | "byte" + | "shortint" + | "int" + | "longint" + | "integer" + | "time" + ) + }); + if !builtin || !dimensions.is_empty() { + // A package-qualified typedef keeps nominal enum/struct identity, + // signedness and unpacked shape without relying on type(expr), + // which the available Icarus adapter does not implement. + if !array + && datatype.contains("::") + && !datatype.contains(['[', '{', '(']) + && dimensions.is_empty() + { + return Ok(format!("{datatype} {name};")); + } + return Err(format!("cannot preserve callable input-port type `{datatype} {dimensions}` for {module}.{port} in timed staging").into()); + } + } + let width = if array { + expression.to_owned() + } else { + format!("{instance} .{port} ") + }; + Ok(format!("reg [$bits({width} )-1:0] {name};")) + } + fn lexical_scope(&self, source: &str, at: usize) -> Vec { lexical_scope_at( source, diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index db0fab4cc7c..d623282d342 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -1374,3 +1374,11 @@ endmodule"#) initial forever begin @(v);q++;end endmodule"#) (top Top)(run_until 0)(assert_eq q 0)(set clk 1)(run_until 1)(assert_eq q 1) (set clk 0)(run_until 2)(set clk 1)(run_until 3)(assert_eq q 2)) + +(case selected_child_dependency_ignores_unreachable_reads(source "selected_child_dependency_ignores_unreachable_reads.sv" #"module Child(input bit a,output bit q);always_comb case(1)1:q=0;default:q=a;endcase endmodule +module Top(output bit[7:0]seen);bit a;wire q;Child c(a,q);initial begin #1;a=1;a=0;end initial forever begin @(q);seen++;end endmodule"#)(top Top)(run_until 0)(assert_eq seen 0)(run_until 1)(assert_eq seen 0)) + +(case selected_child_loop_exit_ignores_unreachable_suffix(source "selected_child_loop_exit_ignores_unreachable_suffix.sv" #"module Child(input bit clk,output bit q);always @(posedge clk)repeat(2)begin q=~q;if(1)break;q=~q;end endmodule +module Top(input bit clk,output bit[7:0]seen);wire q;Child c(clk,q);initial forever begin @(q);seen++;end endmodule"#)(top Top)(run_until 0)(assert_eq seen 0)(set clk 1)(run_until 1)(assert_eq seen 1)) + +(case finite_process_loop_preserves_continuation_values(source "finite_process_loop_preserves_continuation_values.sv" #"module Top(output bit[7:0]q,output bit done);initial begin repeat(4)q++;if(q!=4)$fatal(1,"finite loop state lost");#1;done=1;end endmodule"#)(top Top)(run_until 0)(assert_eq q 4)(assert_eq done 0)(run_until 1)(assert_eq done 1)) diff --git a/crates/celox-test-suite/tests/timed_protocol.rs b/crates/celox-test-suite/tests/timed_protocol.rs index 65d955ffabc..0ed010ad6ba 100644 --- a/crates/celox-test-suite/tests/timed_protocol.rs +++ b/crates/celox-test-suite/tests/timed_protocol.rs @@ -302,3 +302,55 @@ endmodule"#) assert!(verilator.run_testbench().is_ok()); std::fs::remove_dir_all(root).unwrap(); } + +#[test] +#[ignore = "requires Icarus, Verilator and a C++ compiler"] +fn callable_input_connections_preserve_package_enum_type() { + let text = r##"(group protocol(category sequential)) + (case typed_port(source "typed_port.sv" #" + package P;typedef enum logic[1:0]{LOW=0,HIGH=2} level_t;endpackage + module Child(input P::level_t mode,output wire q);assign q=(mode==P::HIGH);endmodule + module Top(input bit go,output wire a,b); + function automatic P::level_t checked();if(!go)$fatal(1,"called before setup");return P::HIGH;endfunction + Child first(.mode(checked()),.q(a));Child second(checked(),b); + initial #2 $finish;endmodule"#)(top Top)(set go 1)(run_until 0)(assert_eq a 1)(assert_eq b 1))"##; + let case = load_group("typed_port.vtest", text, no_std_library)[0]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../target/typed-port-protocol") + .join(std::process::id().to_string()); + let frontend = celox_test_suite::sv::verification::SvFrontend; + let mut icarus = + celox_test_suite::icarus::Icarus::build_script(&frontend, case, &root.join("icarus")) + .unwrap(); + icarus.run_testbench().unwrap(); + let mut verilator = celox_test_suite::verilator::Verilator::build_script( + &frontend, + case, + &root.join("verilator"), + ) + .unwrap(); + verilator.run_testbench().unwrap(); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +#[ignore = "requires Verilator and a C++ compiler; Icarus rejects unpacked function return values"] +fn callable_input_connections_preserve_unpacked_typedef_shape() { + let text = r##"(group protocol(category sequential)) + (case typed_array_port(source "typed_array_port.sv" #" + package P;typedef logic[3:0] pair_t[2];endpackage + module Child(input P::pair_t mode,output wire[7:0]q);assign q={mode[0],mode[1]};endmodule + module Top(input bit[3:0]go,output wire[7:0]q); + function automatic P::pair_t checked();P::pair_t result;if(!go)$fatal(1,"called before setup");result[0]=go;result[1]=go+1;return result;endfunction + Child first(.mode(checked()),.q(q));initial #2 $finish;endmodule"#) + (top Top)(set go 2)(run_until 0)(assert_eq q 35)(set go 3)(run_until 1)(assert_eq q 52))"##; + let case = load_group("typed_array_port.vtest", text, no_std_library)[0]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../target/typed-array-port-protocol") + .join(std::process::id().to_string()); + let frontend = celox_test_suite::sv::verification::SvFrontend; + let mut verilator = + celox_test_suite::verilator::Verilator::build_script(&frontend, case, &root).unwrap(); + verilator.run_testbench().unwrap(); + std::fs::remove_dir_all(root).unwrap(); +} diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 8b29bfa1285..1b5403f1f95 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -319,3 +319,9 @@ sv_backends! { fn constant_child_case_exit_keeps_one_write(sim) { sv_backends! { fn four_state_child_if_keeps_one_write(sim) { @case "timing::four_state_child_if_keeps_one_write"; } } + +sv_backends! {fn selected_child_dependency_ignores_unreachable_reads(sim) { @case "timing::selected_child_dependency_ignores_unreachable_reads"; } } + +sv_backends! {fn selected_child_loop_exit_ignores_unreachable_suffix(sim) { @case "timing::selected_child_loop_exit_ignores_unreachable_suffix"; } } + +sv_backends! {fn finite_process_loop_preserves_continuation_values(sim) { @case "timing::finite_process_loop_preserves_continuation_values"; } } From e87c219a5278db9e54b648488df3c7965db278d6 Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 16 Oct 2026 03:37:00 +0900 Subject: [PATCH 74/75] test(runtime): initialize host readiness in custom states --- crates/celox/src/simulation.rs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index d35b898ba45..02fe730c0ab 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -2939,7 +2939,11 @@ mod other_domain_host_step_review { info, Vec::new(), ); - let mut sim = Simulation { simulator, state }; + let mut sim = Simulation { + simulator, + state, + pending_host_work: false, + }; sim.set_wide(signal, 1u8.into()); assert_eq!(sim.step().unwrap(), Some(0)); assert_eq!(sim.get(sim.signal("count")), 1u8.into()); @@ -3603,7 +3607,11 @@ mod mixed_other_domain_host_review { info, Vec::new(), ); - let mut sim = Simulation { simulator, state }; + let mut sim = Simulation { + simulator, + state, + pending_host_work: false, + }; sim.set_wide(signal, 1u8.into()); assert_eq!(sim.step().unwrap(), Some(0)); assert_eq!(sim.get(sim.signal("count")), 1u8.into()); From 48a50be7c939a74a9bc0294d91f32037adb14d85 Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 16 Oct 2026 04:07:34 +0900 Subject: [PATCH 75/75] fix(suite): retain package context and publish direct host writes --- crates/celox-test-suite/src/frontend.rs | 2 +- .../celox-test-suite/src/frontend/timed_ff.rs | 2 + .../src/frontend/timed_initializers.rs | 32 ++++++++++-- .../src/sv/cases/timing.vtest | 19 +++++++ .../celox-test-suite/tests/timed_protocol.rs | 27 ++++++++++ crates/celox/src/simulation.rs | 51 +++++++++++++++++++ .../tests/frontends/systemverilog/timing.rs | 4 ++ 7 files changed, 132 insertions(+), 5 deletions(-) diff --git a/crates/celox-test-suite/src/frontend.rs b/crates/celox-test-suite/src/frontend.rs index d4b00e3e708..d074ff5a133 100644 --- a/crates/celox-test-suite/src/frontend.rs +++ b/crates/celox-test-suite/src/frontend.rs @@ -345,7 +345,7 @@ fn timed_source(source: &str, names: &TimedNames, tasks: &timed_ff::TaskTiming) fn timed_content(source: &str, names: &TimedNames, tasks: &timed_ff::TaskTiming) -> Result { let mut output = String::new(); let mut previous = 0; - let initializers = timed_initializers::rewrites(source, names)?; + let initializers = timed_initializers::rewrites(source, names, tasks.packages.as_ref())?; let connections = timed_connections::rewrites(source, names, tasks)?; for (start, end, word) in sv_words(source) { if start < previous { diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index 1f42bf8268c..ee1f2d424c1 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -588,6 +588,7 @@ type CallableKey = (String, Option, Vec, String); #[derive(Default)] pub(super) struct TaskTiming { + pub(super) packages: Option, tasks: BTreeMap, pub(super) ports: BTreeMap>, pub(super) inputs: BTreeMap>, @@ -922,6 +923,7 @@ impl TaskTiming { } } } + result.packages = Some(packages); } let mut records = Vec::new(); for (index, source) in sources.iter().enumerate() { diff --git a/crates/celox-test-suite/src/frontend/timed_initializers.rs b/crates/celox-test-suite/src/frontend/timed_initializers.rs index e5015537644..4b252e7d4e3 100644 --- a/crates/celox-test-suite/src/frontend/timed_initializers.rs +++ b/crates/celox-test-suite/src/frontend/timed_initializers.rs @@ -186,6 +186,7 @@ fn elaboration_constant( end: usize, expression: &str, seeds: &[String], + packages: Option<&celox_sv_analyzer::Packages>, ) -> bool { let mut suffix = start; let (name, guard) = loop { @@ -214,11 +215,12 @@ fn elaboration_constant( } else { format!("{}{probe}{}", &source[..start], &source[start..]) }; - celox_sv_analyzer::analyze_source(&candidate, Path::new("timed.sv")).is_ok_and(|ir| { + let path = Path::new("timed.sv"); + let probe_is_constant = |ir: &celox_sv_analyzer::ir::Ir| { // Inspect the probe's resolved calls in its declaring module and // generate scope. A constant evaluator may ignore side effects; // effectful bodies or omitted defaults still require staged execution. - let effects = effectful_functions(&ir); + let effects = effectful_functions(ir); ir.modules().iter().any(|module| { let effectful = effects.iter().any(|(owner, name)| { owner == module.name() && name.rsplit('.').next() == Some(function.as_str()) @@ -229,12 +231,32 @@ fn elaboration_constant( && signal.r#type().resolved_width() == Some(1) }) }) - }) + }; + if let Some(packages) = packages { + // Reuse all preprocessed compilation units' packages. Analyzing only + // this file mistakes external constant calls for dynamic values and + // moves their initialization across the FF listener baseline. + celox_sv_analyzer::source_module_interfaces(&candidate, path).is_ok_and(|modules| { + modules.keys().any(|module| { + celox_sv_analyzer::analyze_source_module_with_packages( + &candidate, + path, + module, + &Default::default(), + packages, + ) + .is_ok_and(|ir| probe_is_constant(&ir)) + }) + }) + } else { + celox_sv_analyzer::analyze_source(&candidate, path).is_ok_and(|ir| probe_is_constant(&ir)) + } } pub(super) fn rewrites( source: &str, names: &TimedNames, + packages: Option<&celox_sv_analyzer::Packages>, ) -> Result> { let mut result = BTreeMap::new(); // Recursive statement rewrites do not contain module declarations. @@ -367,7 +389,9 @@ pub(super) fn rewrites( .collect::>(); // Keep constant initialization before FF listeners are armed; // moving an already-high clock into setup would invent an edge. - if literal_expression || elaboration_constant(source, start, end, expression, &seeds) { + if literal_expression + || elaboration_constant(source, start, end, expression, &seeds, packages) + { let scope = *scopes .last() .ok_or("constant initializer outside module scope")?; diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index d623282d342..8f019d114e3 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -1382,3 +1382,22 @@ module Top(output bit[7:0]seen);bit a;wire q;Child c(a,q);initial begin #1;a=1;a module Top(input bit clk,output bit[7:0]seen);wire q;Child c(clk,q);initial forever begin @(q);seen++;end endmodule"#)(top Top)(run_until 0)(assert_eq seen 0)(set clk 1)(run_until 1)(assert_eq seen 1)) (case finite_process_loop_preserves_continuation_values(source "finite_process_loop_preserves_continuation_values.sv" #"module Top(output bit[7:0]q,output bit done);initial begin repeat(4)q++;if(q!=4)$fatal(1,"finite loop state lost");#1;done=1;end endmodule"#)(top Top)(run_until 0)(assert_eq q 4)(assert_eq done 0)(run_until 1)(assert_eq done 1)) + +(case zero_trip_child_dependencies_ignore_body_and_step + (source "zero-trip-child.sv" #" + module Child(input bit a,output bit q); + function bit read_a();return a;endfunction + always_comb begin q=0;repeat(0)q=a;while(1'b0)q=read_a();for(int i=0;1'b0;i=read_a())q=a;end + endmodule + module Top(output bit[7:0]seen);bit a;wire q;Child c(a,q); + initial begin #1;a=1;a=0;end initial forever begin @(q);seen++;end endmodule + "#)(top Top)(run_until 0)(assert_eq seen 0)(run_until 2)(assert_eq seen 0)) + +(case cross_file_package_initializers_keep_static_clock_baseline + (source "base.sv" #"package Base;function automatic bit one();return 1;endfunction endpackage"#) + (source "values.sv" #"package P;function automatic bit high_value();return Base::one();endfunction endpackage"#) + (source "clocks.sv" #" + module Qualified(output bit[7:0]q);bit clk=P::high_value();always @(posedge clk)q++;endmodule + module Imported(output bit[7:0]q);import P::*;bit clk=high_value();always @(posedge clk)q++;endmodule + module Top(output wire[7:0]qualified,imported);Qualified a(qualified);Imported b(imported);initial #2 $finish;endmodule + "#)(top Top)(run_until 0)(assert_eq qualified 0)(assert_eq imported 0)(run_until 1)(assert_eq qualified 0)(assert_eq imported 0)(run_to_finish)) diff --git a/crates/celox-test-suite/tests/timed_protocol.rs b/crates/celox-test-suite/tests/timed_protocol.rs index 0ed010ad6ba..544a20b311d 100644 --- a/crates/celox-test-suite/tests/timed_protocol.rs +++ b/crates/celox-test-suite/tests/timed_protocol.rs @@ -354,3 +354,30 @@ fn callable_input_connections_preserve_unpacked_typedef_shape() { verilator.run_testbench().unwrap(); std::fs::remove_dir_all(root).unwrap(); } + +#[test] +#[ignore = "requires Icarus, Verilator and a C++ compiler"] +fn cross_file_constant_initializers_do_not_create_startup_edges() { + let text = r##"(group protocol(category sequential)) + (case cross_file_initializer + (source "values.sv" #"package P;function automatic bit high_value();return 1;endfunction endpackage"#) + (source "top.sv" #"module Top(output bit[7:0]q);bit clk=P::high_value();always @(posedge clk)q++;initial #2 $finish;endmodule"#) + (top Top)(run_until 0)(assert_eq q 0)(run_until 1)(assert_eq q 0))"##; + let case = load_group("cross_file_initializer.vtest", text, no_std_library)[0]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../target/cross-file-initializer-protocol") + .join(std::process::id().to_string()); + let frontend = celox_test_suite::sv::verification::SvFrontend; + let mut icarus = + celox_test_suite::icarus::Icarus::build_script(&frontend, case, &root.join("icarus")) + .unwrap(); + icarus.run_testbench().unwrap(); + let mut verilator = celox_test_suite::verilator::Verilator::build_script( + &frontend, + case, + &root.join("verilator"), + ) + .unwrap(); + verilator.run_testbench().unwrap(); + std::fs::remove_dir_all(root).unwrap(); +} diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 02fe730c0ab..37585fbde80 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -434,6 +434,14 @@ impl Simulation { } } + // A write itself can settle eagerly while a RuntimeEventDrain is active. + // In that case publish its edges even if the simulator was clean before + // the write; otherwise retain the notification until the next settle. + fn synchronize_host_write(&mut self) { + self.pending_host_work = true; + self.synchronize_runtime_finish(true); + } + /// Retrieves the current value of a variable using a pre-resolved [`SignalRef`] handle. pub fn get(&mut self, signal: SignalRef) -> num_bigint::BigUint { let was_dirty = self.simulator.dirty; @@ -465,6 +473,7 @@ impl Simulation { /// time: processes waiting for it resume when the simulation next runs. pub fn set_wide(&mut self, signal: SignalRef, value: num_bigint::BigUint) { self.simulator.set_wide(signal, value); + self.synchronize_host_write(); } /// Sets a signal's value and unknown-bit mask, like [`Self::set_wide`]. @@ -475,6 +484,7 @@ impl Simulation { mask: num_bigint::BigUint, ) { self.simulator.set_four_state(signal, value, mask); + self.synchronize_host_write(); } /// Modifies internal state via a callback and re-stabilizes combinational logic. @@ -5150,4 +5160,45 @@ mod round62_review_tests { backends!(&source, arm); } } + #[test] + fn direct_host_setters_expose_pending_process_work() { + fn check(mut sim: Simulation) { + sim.run_until(0).unwrap(); + let clean = sim.checkpoint().unwrap(); + let go = sim.signal("go"); + for active_drain in [false, true] { + for four in [false, true] { + for observe in 0..3 { + sim.restore(&clean).unwrap(); + sim.eval_comb().unwrap(); + let _drain = active_drain + .then(|| sim.simulator.runtime_event_drain()) + .flatten(); + if four { + sim.set_four_state(go, 1u8.into(), 0u8.into()); + } else { + sim.set_wide(go, 1u8.into()); + } + match observe { + 1 => { + sim.get(go); + } + 2 => { + sim.eval_comb().unwrap(); + } + _ => {} + } + assert_eq!(sim.next_event_time(), Some(0)); + assert_eq!(sim.step().unwrap(), Some(0)); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + assert_eq!(sim.next_event_time(), None); + } + } + } + } + backends!( + "module Top(input bit go,output bit q);initial begin @(posedge go);q=1;end endmodule", + check + ); + } } diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 1b5403f1f95..c67f43c4330 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -325,3 +325,7 @@ sv_backends! {fn selected_child_dependency_ignores_unreachable_reads(sim) { @cas sv_backends! {fn selected_child_loop_exit_ignores_unreachable_suffix(sim) { @case "timing::selected_child_loop_exit_ignores_unreachable_suffix"; } } sv_backends! {fn finite_process_loop_preserves_continuation_values(sim) { @case "timing::finite_process_loop_preserves_continuation_values"; } } + +sv_backends! {fn zero_trip_child_dependencies_ignore_body_and_step(sim) { @case "timing::zero_trip_child_dependencies_ignore_body_and_step"; } } + +sv_backends! {fn cross_file_package_initializers_keep_static_clock_baseline(sim) { @case "timing::cross_file_package_initializers_keep_static_clock_baseline"; } }