diff --git a/Cargo.lock b/Cargo.lock index 7e22d7e0485..53ff84aee25 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -789,6 +789,7 @@ dependencies = [ "num-traits", "serde_json", "sha2 0.11.1", + "sv-parser", "veryl-analyzer", "veryl-emitter", "veryl-metadata", 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/README.md b/crates/celox-test-suite/README.md index 2834e66e035..237d2d45acc 100644 --- a/crates/celox-test-suite/README.md +++ b/crates/celox-test-suite/README.md @@ -90,6 +90,17 @@ 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` 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 + 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 @@ -237,6 +248,36 @@ 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 with the injected 1 ns / 1 ps scale. Explicit `timescale`, `timeunit` +and `timeprecision` declarations, and `resetall`, are rejected consistently by +the Celox and external adapters, with each simulator's predefined macros +applied. A timed design has no `final` procedures: they would run in an +arbitrary order relative to the checks after `run_to_finish`. `tick` cannot be +mixed with timed operations. + +A timed script begins with `run_until` or `run_to_finish`; the parser rejects +any other first statement. Time zero starts the design's `initial` and +`always` processes, `always_ff` listeners and variable initializers in an order +the standard leaves open relative to the testbench, so a timed case never +depends on host inputs written before them: every input keeps its fresh value +(zero, or X with four-state) until time zero has been drained. Drive stimulus +after the first `run_until`, or generate it in the design. For the same +reason the design does not call `$finish` at time zero, and the target of the +first `run_until` does not read the design. + +After that, 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; they compile the design sources unchanged. +`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. They run only when the script reached the operation and +the design called `$finish`; a design that idles or is still running at +`RUN_UNTIL_LIMIT` fails the case. + 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 8990e0c592f..9a96fa113ae 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..0e43db543a9 100644 --- a/crates/celox-test-suite/src/frontend.rs +++ b/crates/celox-test-suite/src/frontend.rs @@ -3,6 +3,7 @@ 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::verification::{EmissionError, panic_message}; use crate::{Design, Expectation, Result}; use std::collections::BTreeMap; @@ -12,6 +13,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 a timed design is compiled with: a script time unit is +/// 1 ns, and the generated testbench settles without advancing time. 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. @@ -45,13 +51,16 @@ pub(crate) struct Staged { } /// Write the original and translated sources of `design`, and for a script -/// case that simulates, the generated testbench, into `directory`. +/// case that simulates, the generated testbench, into `directory`. `defines` +/// are the macros the adapter's compiler predefines. pub(crate) fn stage( frontend: &dyn Frontend, design: &Design, directory: &Path, script: Option<&ScriptCase>, + defines: &[&str], ) -> Result { + 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() { @@ -64,6 +73,11 @@ pub(crate) fn stage( std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| frontend.prepare(design))) .map_err(|error| EmissionError(panic_message(error.as_ref())))??; let mut paths = Vec::new(); + if design.timed { + let timescale = directory.join("timescale.sv"); + write_if_changed(×cale, TIMESCALE.as_bytes())?; + paths.push(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/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/icarus.rs b/crates/celox-test-suite/src/icarus.rs index 318685ba76b..bbc0228d82e 100644 --- a/crates/celox-test-suite/src/icarus.rs +++ b/crates/celox-test-suite/src/icarus.rs @@ -41,7 +41,14 @@ impl Icarus { top, testbench, edges, - } = stage(frontend, design, directory, script)?; + } = stage( + frontend, + design, + directory, + script, + // `__ICARUS__` is predefined by Icarus. + &["CELOX_SUITE_ICARUS", "__ICARUS__"], + )?; write_if_changed( &directory.join("vpi_bits.hpp"), include_bytes!("vpi_bits.hpp"), diff --git a/crates/celox-test-suite/src/lib.rs b/crates/celox-test-suite/src/lib.rs index b137f7e1871..a11eab1ca15 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. @@ -233,6 +234,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 44efd9feede..4a143d38b8c 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. @@ -208,6 +213,40 @@ pub enum StmtKind { /// `(expect_output TEXT)`: the design printed exactly TEXT with /// `$display`/`$write` since the start or the previous `expect_output`. ExpectOutput(Vec), + /// `(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 +275,68 @@ 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 reads_design(expr: &Expr) -> bool { + match expr { + Expr::Get(_) => true, + Expr::Op(_, operands) => operands.iter().any(reads_design), + Expr::Literal(_) | Expr::Var(_) => false, + } +} + +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, @@ -597,6 +698,14 @@ pub fn stmt(form: &Sexpr) -> Result { string(&items[1], "output")?.into_bytes() }) } + "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 }) @@ -781,6 +890,41 @@ 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", + ); + } + // Time zero starts the design's initial and always processes in + // an unspecified order relative to the testbench, so the script + // touches the design only once that time has been drained. + if let Some(first) = case.body.first() + && !matches!(first.kind, StmtKind::RunUntil(_) | StmtKind::RunToFinish) + { + return error( + first.pos, + "a timed case begins with run_until or run_to_finish", + ); + } + // Adapters evaluate that first target at different points of + // time zero, so it must not depend on the design. + if let Some(first) = case.body.first() + && let StmtKind::RunUntil(time) = &first.kind + && reads_design(time) + { + return error( + first.pos, + "the first run_until target cannot read the design", + ); + } + } + validate_finish(&case.body)?; parsed.push(case); } Ok((group_name, parsed)) @@ -874,3 +1018,60 @@ 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}"); + } + } + + #[test] + fn timed_cases_drive_and_read_the_design_only_after_time_zero_drains() { + for body in [ + "(set a 1) (run_until 0)", + "(eval) (run_until 0)", + "(assert_eq y 0) (run_to_finish)", + "(let v 1) (run_until v)", + "(do (run_until 0) (set a 1)) (run_until 1)", + ] { + 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("begins with run_until"), "{error}"); + } + let text = "(group mode (category sequential)) (case test (source \"test.sv\" \"module Top; endmodule\") (top Top) (run_until 0) (set a 1) (run_to_finish))"; + assert!(group(text).is_ok()); + } + + #[test] + fn the_first_run_until_target_does_not_read_the_design() { + for (body, ok) in [ + ("(run_until (get y))", false), + ("(run_until (+ 1 (get y)))", false), + ("(run_until (+ 1 2)) (run_until (get y))", true), + ] { + let text = format!( + "(group mode (category sequential)) (case test (source \"test.sv\" \"module Top; endmodule\") (top Top) {body})" + ); + match group(&text) { + Ok(_) => assert!(ok, "{body}"), + Err(error) => { + assert!(!ok, "{body}: {error}"); + assert!(error.message.contains("cannot read the design"), "{error}"); + } + } + } + } +} diff --git a/crates/celox-test-suite/src/script/interp.rs b/crates/celox-test-suite/src/script/interp.rs index 06367874114..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}; @@ -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().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) { + 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 fd8fb3256fa..1ee961ffbf4 100644 --- a/crates/celox-test-suite/src/script/mod.rs +++ b/crates/celox-test-suite/src/script/mod.rs @@ -24,6 +24,16 @@ //! | `(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)` | TEXT is UTF-8, or `(bytes 128 255 0)` specifies raw bytes. 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. Its first statement is `run_until` or `run_to_finish`, so +//! no input is written before the design's time-zero processes and variable +//! initializers have run. 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. //! @@ -53,3 +63,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 dcd119038d2..a1812fd7f92 100644 --- a/crates/celox-test-suite/src/script/sv.rs +++ b/crates/celox-test-suite/src/script/sv.rs @@ -8,12 +8,21 @@ //! 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 timing of an untimed case 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 timed case settles without advancing time: Icarus resumes from a +//! read/write synchronization callback and Verilator from a clocking event in +//! the observed region. Its script begins with `run_until` or +//! `run_to_finish`, so the design's time-zero processes have run before the +//! testbench touches it. `run_until` drains its target timestamp before the +//! next script operation. The checks after `run_to_finish` run in a `final` +//! block, only when the script reached that operation and the design ended the +//! run with `$finish`; a design still running at `RUN_UNTIL_LIMIT` fails. -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}; @@ -90,23 +99,144 @@ const OUTPUT_MARKER: &str = "@suite output "; /// the whole script has run. const END_MARKER: &str = "@suite end"; +/// The line a generated timed testbench prints, after a newline of its own, +/// when the script reaches `run_to_finish`: from there the design may end +/// the run. +const FINISHING_MARKER: &str = "@suite finishing"; + fn hex_encode(text: &[u8]) -> String { text.iter().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)) = 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` (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) + && notice_file(line).is_some_and(|file| sources.iter().any(|source| source == file)) +} + +/// 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 => icarus_finish_notice(line)?.0, + }; + Some(location.rsplit_once(':')?.0) +} + +/// Check the log of a generated testbench that ran in `directory` with +/// [`check_output`]. The simulators' `$finish` notices name the sources +/// staged there. +pub fn check_run(directory: &std::path::Path) -> Result<(), String> { + let log = std::fs::read(directory.join("protocol.log")).unwrap_or_default(); + let sources: Vec = std::fs::read_dir(directory) + .map(|entries| { + entries + .filter_map(|entry| entry.ok()) + .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() + }) + .unwrap_or_default(); + check_output(&log, &sources) +} + +/// `text` without the simulators' `$finish` notices for `sources`. +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() + .is_some_and(|line| is_source_finish_notice(line, sources)); + if !notice { + output.extend_from_slice(chunk); + } + } + 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. -pub fn check_output(log: &[u8]) -> Result<(), String> { +/// the previous one, must equal the text the marker encodes. A simulator +/// may complete the time slot of a design's `$finish`, so the script can +/// still reach its end: a `$finish` notice for one of `sources` before the +/// script reached `run_to_finish` fails the run. +pub fn check_output(log: &[u8], sources: &[String]) -> Result<(), String> { fn find(haystack: &[u8], needle: &[u8]) -> Option { haystack .windows(needle.len()) .position(|window| window == needle) } + let finishing = format!("\n{FINISHING_MARKER}\n"); + let (log, finishing_at) = match find(log, finishing.as_bytes()) { + // The simulator's notice follows the marker on a line of its own; + // drop it before splicing, or it would join a partial last line. + Some(at) => ( + [ + &log[..at], + &design_output(&log[at + finishing.len()..], sources)[..], + ] + .concat(), + at, + ), + None => (log.to_vec(), log.len()), + }; + let log = log.as_slice(); let Some(end) = find(log, format!("\n{END_MARKER}\n").as_bytes()) else { return Err("the simulation ended before the script did".into()); }; + let early_finish = log[..finishing_at.min(end)] + .split(|byte| *byte == b'\n') + .filter_map(|line| std::str::from_utf8(line).ok()) + .any(|line| is_source_finish_notice(line, sources)); + if early_finish { + return Err("the design called $finish before the script reached run_to_finish".into()); + } let separator = format!("\n{OUTPUT_MARKER}"); let mut rest = &log[..end]; while let Some(at) = find(rest, separator.as_bytes()) { @@ -129,6 +259,7 @@ pub fn check_output(log: &[u8]) -> Result<(), String> { }) .collect::>>() .ok_or("malformed output marker")?; + let output = design_output(output, sources); if output != expected { return Err(format!( "{location}: expect_output: expected {expected:?}, got {output:?}" @@ -164,6 +295,15 @@ struct Generator<'a> { out: String, indent: usize, temps: usize, + /// Whether the case is timed: the design runs its own processes, and + /// settling synchronizes with the scheduler without advancing time. + timed: bool, + /// 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 { @@ -244,7 +384,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(_) => {} } } @@ -495,12 +639,19 @@ impl Generator<'_> { } fn settle_for(&mut self, exprs: &[&Expr]) { - if reads(exprs) { + if reads(exprs) && !self.in_final { self.line("settle();"); } } 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; @@ -516,11 +667,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)?; } @@ -793,10 +954,60 @@ 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"); + 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", + self.width + )); + self.indent += 1; + self.fail(pos, "time %0d is out of range", std::slice::from_ref(&time)); + self.indent -= 1; + self.line("end"); + let temp = self.temp(); + self.line("begin"); + self.indent += 1; + 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; + 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("settle_now();"); + 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.timed && !self.in_final { + self.line("settle();"); + } self.line(format!( "$write(\"\\n{OUTPUT_MARKER}{} {}\\n\");", hex_encode(text), @@ -825,15 +1036,54 @@ pub fn testbench(case: &ScriptCase, design: &DesignInfo) -> Result { + generator.in_final = true; + generator.block_at(after, true)?; + Some(std::mem::take(&mut generator.out)) + } + None => None, + }; + (body, final_checks) + } else { + generator.block(&case.body)?; + (std::mem::take(&mut generator.out), None) }; - generator.block(&case.body)?; - let body = generator.out; + let timed = generator.timed; + 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); // Script values are deliberately wider than the signals they meet. let _ = writeln!(out, "/* verilator lint_off WIDTH */"); let _ = writeln!(out, "module {TESTBENCH_TOP};"); + if timed { + let _ = writeln!(out, " timeunit 1ps;"); + let _ = writeln!(out, " timeprecision 1ps;"); + } for port in &design.inputs { let range = port .array @@ -868,6 +1118,15 @@ 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_reached_finish || suite_timed_out) 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\n end\nendmodule\n"); + } + None => { + out.push_str(&end); + out.push_str(" $finish;\n end\nendmodule\n"); + } + } + if timed { + // Settling waits until the scheduler has run everything due at the + // current time, without advancing it: Icarus resumes from a + // read/write synchronization callback, Verilator from a clocking + // event sampled in the observed region. + 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_now; +`ifdef CELOX_SUITE_ICARUS + suite_progress = 0; + $celox_suite_settle(suite_progress); + wait (suite_progress); +`else + suite_progress <= ~suite_progress; + @(suite_settled); +`endif + settled = 1; + endtask"#, + ); + } Ok(out) } @@ -919,6 +1220,71 @@ pub fn testbench(case: &ScriptCase, design: &DesignInfo) -> Result 128'sd{RUN_UNTIL_LIMIT}) begin"))); + assert!(text.contains("time %0d is out of range")); + } + fn case(text: &str) -> ScriptCase { let source = format!( "(group g (category operators)) (case t (source \"test.veryl\" \"\") (top Top) {text})" @@ -978,14 +1344,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.as_bytes()), Ok(())); + assert_eq!(check_output(log.as_bytes(), &[]), Ok(())); assert_eq!( - check_output(b"a\n@suite output 610a62 here\n\n@suite end\n"), + check_output(b"a\n@suite output 610a62 here\n\n@suite end\n", &[]), Err("here: expect_output: expected [97, 10, 98], got [97]".into()) ); // A design's $finish ended the run before the script did. assert_eq!( - check_output(b"a\nb\n@suite output 610a62 here\n"), + check_output(b"a\nb\n@suite output 610a62 here\n", &[]), Err("the simulation ended before the script did".into()) ); } @@ -993,11 +1359,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-test-suite/src/script/timed.rs b/crates/celox-test-suite/src/script/timed.rs new file mode 100644 index 00000000000..13b5c1583ee --- /dev/null +++ b/crates/celox-test-suite/src/script/timed.rs @@ -0,0 +1,216 @@ +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<()> { + validate_timed_design_with_defines(design, &[]) +} + +/// `names` are the macros the simulator predefines. A timed source must +/// not depend on them: the testbench is generated from the source as +/// preprocessed without them. +pub(crate) fn validate_timed_design_with_defines(design: &Design, names: &[&str]) -> Result<()> { + if !design.timed { + return Ok(()); + } + let texts = active_texts(design, names)?; + if !names.is_empty() && texts != active_texts(design, &[])? { + return Err( + "timed shared sources cannot depend on the simulator's predefined macros".into(), + ); + } + for text in &texts { + 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(), + ); + } + // Final procedures run in an unspecified order relative to the + // testbench's checks after run_to_finish (IEEE 1800-2023 9.2.3). + if sv_words(text).iter().any(|(_, _, word)| *word == "final") { + return Err("final procedures are not supported in timed shared cases".into()); + } + } + Ok(()) +} + +/// The active text of each source, preprocessed in order with `names` +/// defined. +fn active_texts(design: &Design, 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<&std::path::Path> = Vec::new(); + let mut texts = Vec::new(); + for source in &design.sources { + let (active, next_defines) = sv_parser::preprocess_str( + &source.text, + &source.path, + &defines, + &includes, + true, + false, + 0, + 0, + ) + .map_err(|error| format!("timed source preprocessing: {error}"))?; + defines = next_defines; + texts.push(active.text().to_owned()); + } + Ok(texts) +} + +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'\\' => { + 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; + 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(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", + "`resetall\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()); + } + + #[test] + fn final_procedures_are_rejected() { + let source = "module Top; bit done; final done = 1; endmodule"; + assert!(validate_timed_design(&design(source)).is_err()); + let source = "module Top; initial $display(\"final\"); 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 [ + "`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() + ); + } + } + + #[test] + fn sources_cannot_depend_on_predefined_macros() { + let source = + "module Top(\n`ifdef VERILATOR\ninput bit a,\n`endif\noutput bit y);\nendmodule"; + let error = + validate_timed_design_with_defines(&design(source), &["VERILATOR"]).unwrap_err(); + assert!(error.to_string().contains("predefined macros"), "{error}"); + assert!(validate_timed_design(&design(source)).is_ok()); + let source = "module Top; endmodule"; + assert!(validate_timed_design_with_defines(&design(source), &["VERILATOR"]).is_ok()); + } +} 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..e441ec138e7 --- /dev/null +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -0,0 +1,719 @@ +(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. +; Every script begins with one of them, so the design's time-zero initial +; blocks, `always` processes and variable initializers have run before the +; script drives an input: no case depends on host values staged before them. + +(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) + (run_until 0) + (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(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; + #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_until 0) + ; x -> 0 is a negedge. + (set host_clk 0)(eval)(assert_eq host_count 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) + (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)) + +(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) + (run_until 0) + (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)) + +(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)) + +(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)) + +(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)) + +(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)) + +(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 #2;q[0]=one();end + initial begin #3;q[1]=one();end + endmodule + module Top(output bit[7:0]seen); + bit[1:0]q;Child u(.q(q)); + initial begin #1;forever begin @(q[0]^q[1]);seen=seen+1;end end + endmodule + "#) + (top Top)(run_until 2)(assert_eq seen 1)(run_until 3)(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 #2;if(sel)q[0]=1;else q[0]=0;end + initial begin #3;q[1]=1;end + endmodule + module Top(input bit sel,output bit[7:0]seen); + bit[1:0]q;Child u(.sel(sel),.q(q)); + initial begin #1;forever begin @(q[0]^q[1]);seen=seen+1;end end + endmodule + "#) + (top Top)(run_until 0)(set sel 1)(run_until 2)(assert_eq seen 1)(run_until 3)(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 #2;case(sel) 0:q[0]=0;1:q[0]=1;default:q[0]=1;endcase end + initial begin #3;q[1]=1;end + endmodule + module Top(input bit[1:0]sel,output bit[7:0]seen); + bit[1:0]q;Child u(.sel(sel),.q(q)); + initial begin #1;forever begin @(q[0]^q[1]);seen=seen+1;end end + endmodule + "#) + (top Top)(run_until 0)(set sel 1)(run_until 2)(assert_eq seen 1)(run_until 3)(assert_eq seen 2)) + +(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 #2;repeat(1)q[0]=1;end initial begin #3;q[1]=1;end endmodule module Top(output bit[7:0]seen);bit[1:0]q;Child u(.q(q));initial begin #1;forever begin @(q[0]^q[1]);seen=seen+1;end end endmodule"#) + (top Top)(run_until 2)(assert_eq seen 1)(run_until 3)(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;bit[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 constant_for_writes_preserve_distinct_activation_times + (source "constant-for-times.sv" #"module Child(output bit[1:0]q);initial begin #2;for(int i=0;i<1;i++)q[0]=1;end initial begin #3;q[1]=1;end endmodule module Top(output bit[7:0]seen);bit[1:0]q;Child u(.q(q));initial begin #1;forever begin @(q[0]^q[1]);seen=seen+1;end end endmodule"#) + (top Top)(run_until 2)(assert_eq seen 1)(run_until 3)(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 #2;noop();q[0]=1;end initial begin #3;noop();q[1]=1;end endmodule module Top(output bit[7:0]seen);bit[1:0]q;Child u(.q(q));initial begin #1;forever begin @(q[0]^q[1]);seen=seen+1;end end endmodule"#) + (top Top)(run_until 2)(assert_eq seen 1)(run_until 3)(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 #2;drive(q[0]);end initial begin #3;drive(q[1]);end endmodule module Top(output bit[7:0]seen);bit[1:0]q;Child u(.q(q));initial begin #1;forever begin @(q[0]^q[1]);seen=seen+1;end end endmodule"#) + (top Top)(run_until 2)(assert_eq seen 1)(run_until 3)(assert_eq seen 2)) + +(case statically_satisfied_waits_preserve_distinct_activation_times + (source "true-wait.sv" #"module Child(output bit[1:0]q);initial begin #2;wait(1);q[0]=1;end initial begin #3;q[1]=1;end endmodule module Top(output bit[7:0]seen);bit[1:0]q;Child u(.q(q));initial begin #1;forever begin @(q[0]^q[1]);seen=seen+1;end end endmodule"#) + (top Top)(run_until 2)(assert_eq seen 1)(run_until 3)(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;bit 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) + (run_until 0) + (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)) + +(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;bit 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)) + +(case constant_variable_initializers_do_not_invent_clock_edges + (source "constant-initializer-edges.sv" #" + module Top(output bit literal_seen,parameter_seen,function_seen,copy_seen); + parameter bit HIGH=1; + function automatic bit high_value();return 1;endfunction + bit literal_clock=1,parameter_clock=HIGH,function_clock=high_value(); + bit copied_clock=literal_clock; + always_ff @(posedge literal_clock)literal_seen=1; + always_ff @(posedge parameter_clock)parameter_seen=1; + always_ff @(posedge function_clock)function_seen=1; + always_ff @(posedge copied_clock)copy_seen=1; + initial begin #2;$finish;end + endmodule + "#) + (top Top)(run_until 0)(assert_eq literal_seen 0)(assert_eq parameter_seen 0)(assert_eq function_seen 0)(assert_eq copy_seen 0) + (run_to_finish)) + +(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 #2;v[0]=1;wait(0);end initial begin #3;v[1]=1;end endmodule module Top(output bit[7:0]q);bit[1:0]v;Child c(.v(v));initial begin #1;forever begin @(v[0]^v[1]);q++;end end endmodule"#) + (top Top)(run_until 2)(assert_eq q 1)(run_until 3)(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)) + +(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);bit 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_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);bit 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);bit 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);bit 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 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;bit 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);bit 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;bit 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)) + +(case initial_blocks_run_at_time_zero + (source "time_zero.sv" #" + module Top(output bit [7:0] y); + initial begin + y = 8'd7; + $display("y=%0d", y); + end + endmodule + "#) + (top Top) + (run_until 0) + (assert_eq y 7) + (expect_output "y=7\n") + (run_until 10) + (assert_eq y 7)) + +(case host_edges_after_time_zero_clock_flip_flops + (source "host_edges.sv" #" + module Top(input bit clk, output bit [7:0] q); + always_ff @(posedge clk) q <= q + 8'd1; + endmodule + "#) + (top Top) + (run_until 0) + (set clk 1) + (run_until 1) + (assert_eq q 1) + (set clk 0) + (run_until 2) + (assert_eq q 1) + (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..e275a92f1a6 100644 --- a/crates/celox-test-suite/src/sv/verification.rs +++ b/crates/celox-test-suite/src/sv/verification.rs @@ -38,7 +38,64 @@ fn element_width(r#type: &Type) -> Option { } } +/// The preprocessed `sources` with every procedure and task blanked out, for +/// a timed design's declarations: the analyzer does not lower every timing +/// control, and port shapes do not depend on process bodies. Blanking keeps +/// line breaks, so declaration positions are unchanged. +fn declarations_only(design: &Design) -> Option { + let mut defines = sv_parser::Defines::default(); + let mut declarations = design.clone(); + for source in &mut declarations.sources { + let includes: Vec<&std::path::Path> = Vec::new(); + let (text, next) = sv_parser::preprocess_str( + &source.text, + &source.path, + &defines, + &includes, + true, + false, + 0, + 0, + ) + .ok()?; + let mut blanked = text.text().as_bytes().to_vec(); + let (tree, _) = sv_parser::parse_sv_pp(text, next.clone(), false).ok()?; + defines = next; + for node in &tree { + if !matches!( + node, + sv_parser::RefNode::InitialConstruct(_) + | sv_parser::RefNode::AlwaysConstruct(_) + | sv_parser::RefNode::FinalConstruct(_) + | sv_parser::RefNode::TaskDeclaration(_) + ) { + continue; + } + let locates = node.into_iter().filter_map(|inner| match inner { + sv_parser::RefNode::Locate(locate) => Some(*locate), + _ => None, + }); + for locate in locates { + for byte in &mut blanked[locate.offset..locate.offset + locate.len] { + if *byte != b'\n' { + *byte = b' '; + } + } + } + } + source.text = String::from_utf8(blanked).ok()?; + } + Some(declarations) +} + fn design_info(design: &Design) -> Option { + if design.timed { + return analyzed_info(&declarations_only(design)?); + } + analyzed_info(design) +} + +fn analyzed_info(design: &Design) -> Option { // Interfaces are expanded as the Celox frontend does; the tools still // compile the sources as written. let paths: Vec<_> = design diff --git a/crates/celox-test-suite/src/verification.rs b/crates/celox-test-suite/src/verification.rs index 18459ff42aa..26545904877 100644 --- a/crates/celox-test-suite/src/verification.rs +++ b/crates/celox-test-suite/src/verification.rs @@ -555,6 +555,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 @@ -604,13 +614,10 @@ 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(&log) { - Ok(()) => ("passed", "execute", String::new()), - Err(detail) => ("mismatch", "execute", detail), - } - } + Ok(()) => match crate::script::sv::check_run(directory) { + Ok(()) => ("passed", "execute", String::new()), + Err(detail) => ("mismatch", "execute", detail), + }, Err(error) => { // HDL output can contain arbitrary bytes. Decode only assertion // diagnostics so unrelated binary output cannot discard markers. diff --git a/crates/celox-test-suite/src/verilator.rs b/crates/celox-test-suite/src/verilator.rs index 63023805f19..dbb29bc889d 100644 --- a/crates/celox-test-suite/src/verilator.rs +++ b/crates/celox-test-suite/src/verilator.rs @@ -41,7 +41,14 @@ impl Verilator { top, testbench, edges, - } = stage(frontend, design, directory, script)?; + } = stage( + frontend, + design, + directory, + script, + // Predefined by Verilator, and by `--timing`. + &["VERILATOR", "VERILATOR_TIMING"], + )?; write_if_changed( &directory.join("vpi_bits.hpp"), include_bytes!("vpi_bits.hpp"), 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..81ac1406806 --- /dev/null +++ b/crates/celox-test-suite/tests/timed_protocol.rs @@ -0,0 +1,67 @@ +#![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)", + ), + ( + // A design that finishes at the target time of run_until. + "finish_at_target", + "module Top(output bit done); initial #5 $finish; endmodule", + "(run_until 5) (assert_eq done 0)", + ), + ( + "finish_on_eval", + "module Top(input bit go); initial begin wait(go); $finish; end endmodule", + "(run_until 0) (set go 1) (eval) (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(); + let result = icarus.run_testbench(); + assert!( + result.is_err() + || celox_test_suite::script::sv::check_run(&root.join(name).join("icarus")) + .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(); + assert!( + result.is_err() + || celox_test_suite::script::sv::check_run(&root.join(name).join("verilator")) + .is_err(), + "Verilator accepted {name}" + ); + } + std::fs::remove_dir_all(root).unwrap(); +} diff --git a/crates/celox-test-suite/verification/sv/icarus.json b/crates/celox-test-suite/verification/sv/icarus.json index af177f582a0..3633efb3b55 100644 --- a/crates/celox-test-suite/verification/sv/icarus.json +++ b/crates/celox-test-suite/verification/sv/icarus.json @@ -12,6 +12,7 @@ "icarus/review_regressions.json", "icarus/synthesizable.json", "icarus/system_functions.json", + "icarus/timing.json", "icarus/types.json" ], "exclude_stronger_than_sv": false, diff --git a/crates/celox-test-suite/verification/sv/icarus/timing.json b/crates/celox-test-suite/verification/sv/icarus/timing.json new file mode 100644 index 00000000000..3065bcd96ac --- /dev/null +++ b/crates/celox-test-suite/verification/sv/icarus/timing.json @@ -0,0 +1,609 @@ +{ + "cases": [ + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::always_timed_task_without_inline_timing_executes", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "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::blocking_concatenation_publishes_one_event_update", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::blocking_ff_stores_are_visible_before_inactive_work", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::blocking_ff_woken_waiters_sample_before_continuations", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::case_writes_preserve_distinct_activation_times", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::combinational_finish_ends_timed_execution", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::conditional_writes_preserve_distinct_activation_times", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::constant_child_case_exit_keeps_one_write", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::constant_child_ff_case_discards_unreachable_pulse_arm", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::constant_child_loop_exit_keeps_one_write", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::constant_comb_if_discards_unreachable_pulse_branch", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::constant_for_writes_preserve_distinct_activation_times", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::constant_repeat_writes_preserve_distinct_activation_times", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::constant_variable_initializers_do_not_invent_clock_edges", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::cross_file_package_initializers_keep_static_clock_baseline", + "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::direct_blocking_ff_woken_waiters_sample_before_continuations", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::direct_reads_settle_waiting_processes", + "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::false_wait_preserves_separate_hierarchical_write_times", + "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::finite_active_feedback_preserves_convergence", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::finite_process_loop_preserves_continuation_values", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::four_state_child_if_keeps_one_write", + "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::host_edges_after_time_zero_clock_flip_flops", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::inactive_time_directives_do_not_change_scheduler_units", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::initial_blocks_run_at_time_zero", + "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::mixed_ff_stores_keep_their_active_and_nba_values", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::nba_woken_waiters_sample_before_continuations", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::negative_repeat_counts_do_not_run_the_body", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::nonblocking_ff_stores_remain_pending_during_inactive_work", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::output_reads_settle_waiting_processes", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::printed_finish_notice_is_design_output", + "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::pure_function_rhs_preserves_distinct_write_times", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::repeated_active_edges_share_one_nba_batch", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::repeated_settles_do_not_advance_design_time", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::run_to_finish_has_no_simulated_time_deadline", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::run_until_drains_target_time_before_later_writes", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::selected_child_dependency_ignores_unreachable_reads", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::selected_child_loop_exit_ignores_unreachable_suffix", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::separate_comb_assignments_preserve_selected_dependencies", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::statically_satisfied_waits_preserve_distinct_activation_times", + "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::untimed_task_copyback_preserves_distinct_activation_times", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::untimed_tasks_preserve_distinct_activation_times", + "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": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::zero_trip_child_dependencies_ignore_body_and_step", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ] +} diff --git a/crates/celox-test-suite/verification/sv/verilator.json b/crates/celox-test-suite/verification/sv/verilator.json index 4bb7c931b4b..ed19732a9a2 100644 --- a/crates/celox-test-suite/verification/sv/verilator.json +++ b/crates/celox-test-suite/verification/sv/verilator.json @@ -12,6 +12,7 @@ "verilator/review_regressions.json", "verilator/synthesizable.json", "verilator/system_functions.json", + "verilator/timing.json", "verilator/types.json" ], "exclude_stronger_than_sv": false, diff --git a/crates/celox-test-suite/verification/sv/verilator/timing.json b/crates/celox-test-suite/verification/sv/verilator/timing.json new file mode 100644 index 00000000000..cb0f410c3ea --- /dev/null +++ b/crates/celox-test-suite/verification/sv/verilator/timing.json @@ -0,0 +1,609 @@ +{ + "cases": [ + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::always_timed_task_without_inline_timing_executes", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "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::blocking_concatenation_publishes_one_event_update", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::blocking_ff_stores_are_visible_before_inactive_work", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::blocking_ff_woken_waiters_sample_before_continuations", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::case_writes_preserve_distinct_activation_times", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::combinational_finish_ends_timed_execution", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::conditional_writes_preserve_distinct_activation_times", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::constant_child_case_exit_keeps_one_write", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::constant_child_ff_case_discards_unreachable_pulse_arm", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::constant_child_loop_exit_keeps_one_write", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::constant_comb_if_discards_unreachable_pulse_branch", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::constant_for_writes_preserve_distinct_activation_times", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::constant_repeat_writes_preserve_distinct_activation_times", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::constant_variable_initializers_do_not_invent_clock_edges", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::cross_file_package_initializers_keep_static_clock_baseline", + "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::direct_blocking_ff_woken_waiters_sample_before_continuations", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::direct_reads_settle_waiting_processes", + "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::false_wait_preserves_separate_hierarchical_write_times", + "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::finite_active_feedback_preserves_convergence", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::finite_process_loop_preserves_continuation_values", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::four_state_child_if_keeps_one_write", + "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::host_edges_after_time_zero_clock_flip_flops", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::inactive_time_directives_do_not_change_scheduler_units", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::initial_blocks_run_at_time_zero", + "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::mixed_ff_stores_keep_their_active_and_nba_values", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::nba_woken_waiters_sample_before_continuations", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::negative_repeat_counts_do_not_run_the_body", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::nonblocking_ff_stores_remain_pending_during_inactive_work", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::output_reads_settle_waiting_processes", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::printed_finish_notice_is_design_output", + "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::pure_function_rhs_preserves_distinct_write_times", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::repeated_active_edges_share_one_nba_batch", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::repeated_settles_do_not_advance_design_time", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::run_to_finish_has_no_simulated_time_deadline", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::run_until_drains_target_time_before_later_writes", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::selected_child_dependency_ignores_unreachable_reads", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::selected_child_loop_exit_ignores_unreachable_suffix", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::separate_comb_assignments_preserve_selected_dependencies", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::statically_satisfied_waits_preserve_distinct_activation_times", + "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::untimed_task_copyback_preserves_distinct_activation_times", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::untimed_tasks_preserve_distinct_activation_times", + "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": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::zero_trip_child_dependencies_ignore_body_and_step", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ] +} diff --git a/crates/celox/tests/frontends/systemverilog/suite.rs b/crates/celox/tests/frontends/systemverilog/suite.rs index 2e3578f14a4..417df5e169a 100644 --- a/crates/celox/tests/frontends/systemverilog/suite.rs +++ b/crates/celox/tests/frontends/systemverilog/suite.rs @@ -1,10 +1,172 @@ //! 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 in a +/// [`Simulation`]. The runtime does not yet resume the processes a host write +/// wakes until time advances, and offers no four-state read; the cases that +/// need either are excluded in `timing.rs`. +struct TimedBackend { + sim: Simulation, + four_state: bool, + /// Runtime events not yet taken as output. + events: Vec, + finished: bool, +} + +impl TimedBackend { + fn new(sim: Simulation, four_state: bool) -> Self { + Self { + sim, + four_state, + events: Vec::new(), + finished: false, + } + } + + fn signal(&self, path: &SignalPath) -> celox::SignalRef { + let instances: Vec<_> = path + .instances + .iter() + .map(|i| (i.name.as_str(), i.index.unwrap_or(0))) + .collect(); + self.sim.child_signal(&instances, &path.name) + } + + /// Collect the design's runtime events; a failed assertion fails the + /// case, and a `$finish` outside the run operations is an error. + fn capture_events(&mut self) -> Result<()> { + let events = self.sim.drain_runtime_events(); + let error = events.iter().find_map(|event| match event { + RuntimeEvent::AssertFatal { message } => Some(format!( + "fatal assertion: {}", + String::from_utf8_lossy(message) + )), + RuntimeEvent::AssertContinue { message } => Some(format!( + "failed assertion: {}", + String::from_utf8_lossy(message) + )), + RuntimeEvent::Missed { count } => Some(format!("{count} runtime events were missed")), + _ => None, + }); + self.finished |= self.sim.is_finished() + || events + .iter() + .any(|event| matches!(event, RuntimeEvent::Finish)); + self.events.extend(events); + match error { + Some(error) => Err(error.into()), + None => Ok(()), + } + } + + /// Capture events after an operation that does not advance time. + fn checked(&mut self, operation: &str) -> Result<()> { + let finished = self.finished; + self.capture_events()?; + if !finished && self.finished { + return Err(format!("the design finished during {operation}").into()); + } + Ok(()) + } +} + +fn collect_output(events: Vec) -> Result> { + let mut output = Vec::new(); + for event in events { + match event { + RuntimeEvent::Display { message } => { + output.extend_from_slice(&message); + output.push(b'\n'); + } + RuntimeEvent::Write { message } => output.extend_from_slice(&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 = self.signal(path); + self.sim.modify(|io| { + if mask == BigUint::default() { + io.set_wide(signal, payload); + } else { + io.set_four_state(signal, payload, mask); + } + })?; + self.checked("a write") + } + + fn read(&mut self, path: &SignalPath) -> Result<(BigUint, BigUint)> { + if self.four_state { + return Err("a timed simulation has no four-state read".into()); + } + self.checked("a read")?; + let signal = self.signal(path); + Ok((self.sim.get(signal), BigUint::default())) + } + + fn eval_comb(&mut self) -> Result<()> { + self.sim.eval_comb()?; + self.checked("eval") + } + + 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> { + self.checked("output collection")?; + collect_output(std::mem::take(&mut self.events)) + } + + fn run_until(&mut self, time: u64) -> Result<()> { + let now = self.sim.time(); + if time < now { + return Err(format!("run_until {time}: the simulation is already at {now}").into()); + } + self.sim.run_until(time)?; + self.capture_events()?; + if self.finished { + return Err(format!( + "run_until {time}: the design finished the simulation at {}", + self.sim.time() + ) + .into()); + } + Ok(()) + } + + fn run_to_finish(&mut self) -> Result<()> { + if self.finished { + return Err("run_to_finish: the design had already finished".into()); + } + while !self.finished { + let step = self.sim.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(), + ); + } + Ok(()) + } +} + impl CeloxBackend { fn signal(&self, path: &SignalPath) -> celox::SignalRef { let instances: Vec<_> = path @@ -40,31 +202,31 @@ impl Backend for CeloxBackend { } fn take_output(&mut self) -> Result> { - let mut output = Vec::new(); - for event in self.0.drain_runtime_events() { - match event { - celox::RuntimeEvent::Display { message } => { - output.extend_from_slice(&message); - output.push(b'\n'); - } - celox::RuntimeEvent::Write { message } => output.extend_from_slice(&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()) } } fn build(design: &Design, backend: &str) -> Result> { + celox_test_suite::validate_timed_design(design)?; let sources = design .sources .iter() .map(|source| (source.text.as_str(), source.path.as_path())) .collect::>(); + if design.timed { + // `Simulation` builds only the default backend. + if backend != "native" { + return Err(format!("no timed simulation for the {backend} backend").into()); + } + 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(Box::new(TimedBackend::new( + builder.build()?, + design.four_state, + ))); + } 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..14536b199d6 --- /dev/null +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -0,0 +1,162 @@ +//! Shared timing-control cases: `#delay`, `@(event)` and `wait` in +//! processes, driven through the timed `Simulation`. +//! +//! Every exclusion names what Celox lacks for the case, so the change that +//! adds it removes the exclusion. `Simulation` builds only the default +//! (native) backend, so the other backends are excluded for every case. + +macro_rules! timed_cases { + () => {}; + ( + $(#[$attr:meta])* + fn $name:ident = $case:literal; + $($rest:tt)* + ) => { + mod $name { + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + #[test] + $(#[$attr])* + fn native() { + crate::suite::run_case($case, "native"); + } + + #[test] + #[ignore = "a timed Simulation builds only the default backend"] + fn cranelift() { + crate::suite::run_case($case, "cranelift"); + } + + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + #[test] + #[ignore = "a timed Simulation builds only the default backend"] + fn native_parallel() { + crate::suite::run_case($case, "native-parallel"); + } + + #[test] + #[ignore = "a timed Simulation builds only the default backend"] + fn cranelift_parallel() { + crate::suite::run_case($case, "cranelift-parallel"); + } + + #[test] + #[ignore = "a timed Simulation builds only the default backend"] + fn wasm() { + crate::suite::run_case($case, "wasm"); + } + } + timed_cases! { $($rest)* } + }; +} + +timed_cases! { + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn delays_resume_initial_blocks_at_later_times = "timing::delays_resume_initial_blocks_at_later_times"; + #[ignore = "the SV analyzer rejects plain always processes (#431)"] + fn always_with_a_delay_generates_a_clock = "timing::always_with_a_delay_generates_a_clock"; + #[ignore = "the SV analyzer rejects plain always processes (#431)"] + fn edge_waits_resume_before_the_registers_of_that_edge_update = "timing::edge_waits_resume_before_the_registers_of_that_edge_update"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn any_change_waits_wake_on_every_value_change = "timing::any_change_waits_wake_on_every_value_change"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn wait_statements_block_until_their_condition_holds = "timing::wait_statements_block_until_their_condition_holds"; + #[ignore = "the SV analyzer rejects plain always processes (#431)"] + fn level_sensitive_always_runs_as_a_process = "timing::level_sensitive_always_runs_as_a_process"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn processes_wake_each_other_at_the_same_time = "timing::processes_wake_each_other_at_the_same_time"; + #[ignore = "the SV analyzer rejects plain always processes (#431)"] + fn tasks_with_timing_controls_run_in_processes = "timing::tasks_with_timing_controls_run_in_processes"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn edge_waits_see_the_signals_the_script_drives = "timing::edge_waits_see_the_signals_the_script_drives"; + #[ignore = "the SV analyzer rejects plain always processes (#431)"] + fn finish_in_an_always_process_ends_the_simulation = "timing::finish_in_an_always_process_ends_the_simulation"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn waiting_processes_do_not_keep_an_idle_simulation_running = "timing::waiting_processes_do_not_keep_an_idle_simulation_running"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88); a timed Simulation has no four-state read"] + fn four_state_edges_count_transitions_through_unknown = "timing::four_state_edges_count_transitions_through_unknown"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88); a timed Simulation has no four-state read"] + fn unknown_delays_and_conditions_count_as_zero_and_false = "timing::unknown_delays_and_conditions_count_as_zero_and_false"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn direct_reads_settle_waiting_processes = "timing::direct_reads_settle_waiting_processes"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn output_reads_settle_waiting_processes = "timing::output_reads_settle_waiting_processes"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn run_until_drains_target_time_before_later_writes = "timing::run_until_drains_target_time_before_later_writes"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn repeated_settles_do_not_advance_design_time = "timing::repeated_settles_do_not_advance_design_time"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn run_to_finish_has_no_simulated_time_deadline = "timing::run_to_finish_has_no_simulated_time_deadline"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn blocking_ff_stores_are_visible_before_inactive_work = "timing::blocking_ff_stores_are_visible_before_inactive_work"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn nonblocking_ff_stores_remain_pending_during_inactive_work = "timing::nonblocking_ff_stores_remain_pending_during_inactive_work"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn mixed_ff_stores_keep_their_active_and_nba_values = "timing::mixed_ff_stores_keep_their_active_and_nba_values"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn printed_finish_notice_is_design_output = "timing::printed_finish_notice_is_design_output"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn combinational_finish_ends_timed_execution = "timing::combinational_finish_ends_timed_execution"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn inactive_time_directives_do_not_change_scheduler_units = "timing::inactive_time_directives_do_not_change_scheduler_units"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn blocking_concatenation_publishes_one_event_update = "timing::blocking_concatenation_publishes_one_event_update"; + #[ignore = "the SV analyzer rejects plain always processes (#431)"] + fn finite_active_feedback_preserves_convergence = "timing::finite_active_feedback_preserves_convergence"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn pure_function_rhs_preserves_distinct_write_times = "timing::pure_function_rhs_preserves_distinct_write_times"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn conditional_writes_preserve_distinct_activation_times = "timing::conditional_writes_preserve_distinct_activation_times"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn case_writes_preserve_distinct_activation_times = "timing::case_writes_preserve_distinct_activation_times"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn constant_repeat_writes_preserve_distinct_activation_times = "timing::constant_repeat_writes_preserve_distinct_activation_times"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn separate_comb_assignments_preserve_selected_dependencies = "timing::separate_comb_assignments_preserve_selected_dependencies"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn constant_for_writes_preserve_distinct_activation_times = "timing::constant_for_writes_preserve_distinct_activation_times"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn untimed_tasks_preserve_distinct_activation_times = "timing::untimed_tasks_preserve_distinct_activation_times"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn untimed_task_copyback_preserves_distinct_activation_times = "timing::untimed_task_copyback_preserves_distinct_activation_times"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn statically_satisfied_waits_preserve_distinct_activation_times = "timing::statically_satisfied_waits_preserve_distinct_activation_times"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn nba_woken_waiters_sample_before_continuations = "timing::nba_woken_waiters_sample_before_continuations"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn negative_repeat_counts_do_not_run_the_body = "timing::negative_repeat_counts_do_not_run_the_body"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn blocking_ff_woken_waiters_sample_before_continuations = "timing::blocking_ff_woken_waiters_sample_before_continuations"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn direct_blocking_ff_woken_waiters_sample_before_continuations = "timing::direct_blocking_ff_woken_waiters_sample_before_continuations"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn constant_variable_initializers_do_not_invent_clock_edges = "timing::constant_variable_initializers_do_not_invent_clock_edges"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn repeated_active_edges_share_one_nba_batch = "timing::repeated_active_edges_share_one_nba_batch"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn false_wait_preserves_separate_hierarchical_write_times = "timing::false_wait_preserves_separate_hierarchical_write_times"; + #[ignore = "the SV analyzer rejects plain always processes (#431)"] + fn always_timed_task_without_inline_timing_executes = "timing::always_timed_task_without_inline_timing_executes"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn constant_comb_if_discards_unreachable_pulse_branch = "timing::constant_comb_if_discards_unreachable_pulse_branch"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn constant_child_ff_case_discards_unreachable_pulse_arm = "timing::constant_child_ff_case_discards_unreachable_pulse_arm"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn constant_child_loop_exit_keeps_one_write = "timing::constant_child_loop_exit_keeps_one_write"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn constant_child_case_exit_keeps_one_write = "timing::constant_child_case_exit_keeps_one_write"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn four_state_child_if_keeps_one_write = "timing::four_state_child_if_keeps_one_write"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn selected_child_dependency_ignores_unreachable_reads = "timing::selected_child_dependency_ignores_unreachable_reads"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn selected_child_loop_exit_ignores_unreachable_suffix = "timing::selected_child_loop_exit_ignores_unreachable_suffix"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn finite_process_loop_preserves_continuation_values = "timing::finite_process_loop_preserves_continuation_values"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn zero_trip_child_dependencies_ignore_body_and_step = "timing::zero_trip_child_dependencies_ignore_body_and_step"; + #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + fn cross_file_package_initializers_keep_static_clock_baseline = "timing::cross_file_package_initializers_keep_static_clock_baseline"; + fn initial_blocks_run_at_time_zero = "timing::initial_blocks_run_at_time_zero"; + #[ignore = "a host write to a clock does not trigger its flip-flops in a timed Simulation"] + fn host_edges_after_time_zero_clock_flip_flops = "timing::host_edges_after_time_zero_clock_flip_flops"; +} diff --git a/crates/celox/tests/systemverilog.rs b/crates/celox/tests/systemverilog.rs index 649a55dcd42..a033aa691ff 100644 --- a/crates/celox/tests/systemverilog.rs +++ b/crates/celox/tests/systemverilog.rs @@ -126,6 +126,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;