diff --git a/Cargo.lock b/Cargo.lock index f22c647f6de..f534f506ccf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -789,6 +789,7 @@ dependencies = [ "num-traits", "serde_json", "sha2 0.11.0", + "sv-parser", "veryl-analyzer", "veryl-emitter", "veryl-metadata", diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 0bbbd6f34c7..805a5d38a00 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -511,6 +511,25 @@ impl SimulationState { Ok(()) } + /// Whether a clock/reset differs from the last settled scheduler state. + /// Host reads may have already cleared backend trigger bits. + pub fn has_unsettled_edges(&self, backend: &B) -> bool { + self.topo_signals.iter().any(|(signal, id, _)| { + *id != usize::MAX + && ( + self.last_clock_values.contains(*id), + self.unknown_clock_values.contains(*id), + ) != sample_event_signal(backend, *signal) + }) + } + + /// Whether a pending transition activates its clock/reset domain. + pub fn has_unsettled_active_edges(&self, backend: &B) -> bool { + self.topo_signals + .iter() + .any(|(_, id, _)| *id != usize::MAX && self.stable_edge_triggered(backend, *id)) + } + /// Whether any process is suspended on an event or a condition. pub fn has_waiting_processes(&self) -> bool { !self.waiting.is_empty() @@ -528,8 +547,6 @@ impl SimulationState { return Ok(false); } let time = self.scheduler.time; - // A due clock belongs to the same batch; consume its periodic marker - // through step before processing captured host edges or continuations. if self .scheduler .next_event_time() @@ -809,6 +826,14 @@ impl SimulationState { } let mut scheduled_edges: BitSet = host_edges.keys().copied().collect(); let mut early_settle_edges = BitSet::with_capacity(num_events); + // Pending host writes share this round with current-time scheduled + // edges. Record their net transitions before scheduled values replace + // them and before clearing the backend's transient trigger hints. + for (_, id, _) in &self.topo_signals { + if *id != usize::MAX && self.stable_edge_triggered(executor.backend(), *id) { + scheduled_edges.insert(*id); + } + } // Early settling can expose a derived edge that a later source store // or awakened process restores. Capture every update we settle early. let capture_batch_edges = events_to_process.len() > 1 || !host_edges.is_empty(); diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 63e979fa12a..7e10e2dce55 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -2441,6 +2441,14 @@ fn generate_scope_head(name: &str) -> Option<&str> { Some(&name[..end]) } +/// Source ranges of generate scopes, including single-item bodies. +/// Offsets refer to the parsed, preprocessed source text. +pub fn generate_scope_ranges(tree: &SyntaxTree) -> Vec<(usize, usize)> { + tree.into_iter() + .flat_map(imports::generate_blocks) + .collect() +} + /// Source offsets of always constructs whose controls have the supported FF /// shape. Adapter callable analysis separately excludes timed task calls. pub fn ff_always_offsets(syntax_tree: &SyntaxTree) -> Vec { @@ -2465,3 +2473,161 @@ pub fn ff_always_offsets(syntax_tree: &SyntaxTree) -> Vec { }) .collect() } + +/// Actual call identifiers, excluding named argument labels and declarations. +/// Bare identifiers in expressions are not call sites; bare statement calls are. +pub fn procedural_call_sites(tree: &SyntaxTree) -> Vec<(usize, String)> { + let mut sites = Vec::new(); + for node in tree { + let identifier = match node { + RefNode::TfCall(call) if call.nodes.2.is_some() => { + Some(RefNode::PsOrHierarchicalTfIdentifier(&call.nodes.0)) + } + RefNode::SubroutineCallStatement( + sv_parser::SubroutineCallStatement::SubroutineCall(statement), + ) => match &statement.0 { + sv_parser::SubroutineCall::TfCall(call) => { + Some(RefNode::PsOrHierarchicalTfIdentifier(&call.nodes.0)) + } + _ => None, + }, + RefNode::MethodCallBodyUser(call) => Some(RefNode::MethodIdentifier(&call.nodes.0)), + _ => None, + }; + if let Some(identifier) = identifier { + let name = identifier + .into_iter() + .filter_map(|node| match node { + RefNode::SimpleIdentifier(id) => tree + .get_str(&id.nodes.0) + .map(|text| (id.nodes.0.offset, text.trim().to_owned())), + RefNode::EscapedIdentifier(id) => tree + .get_str(&id.nodes.0) + .map(|text| (id.nodes.0.offset, text.trim().to_owned())), + _ => None, + }) + .last(); + if let Some(name) = name { + sites.push(name); + } + } + } + sites.sort_unstable(); + sites.dedup(); + sites +} + +/// Parsed import/export clauses, keyed by the declaration keyword offset. +/// A missing package/member denotes a wildcard; comments never become items. +pub fn package_import_export_clauses( + tree: &SyntaxTree, +) -> std::collections::BTreeMap, Option)>> { + let mut clauses = std::collections::BTreeMap::new(); + for node in tree { + let (offset, declaration) = match node { + RefNode::PackageImportDeclaration(item) => ( + item.nodes.0.nodes.0.offset, + RefNode::PackageImportDeclaration(item), + ), + RefNode::PackageExportDeclaration(sv_parser::PackageExportDeclaration::Item(item)) => ( + item.nodes.0.nodes.0.offset, + RefNode::PackageExportDeclarationItem(item), + ), + RefNode::PackageExportDeclaration(sv_parser::PackageExportDeclaration::Asterisk( + item, + )) => { + clauses.insert(item.nodes.0.nodes.0.offset, vec![(None, None)]); + continue; + } + _ => continue, + }; + let items = declaration + .into_iter() + .filter_map(|node| match node { + RefNode::PackageImportItem(sv_parser::PackageImportItem::Identifier(item)) => { + Some(( + identifier_text(RefNode::PackageIdentifier(&item.nodes.0), tree), + identifier_text(RefNode::Identifier(&item.nodes.2), tree), + )) + } + RefNode::PackageImportItem(sv_parser::PackageImportItem::Asterisk(item)) => Some(( + identifier_text(RefNode::PackageIdentifier(&item.nodes.0), tree), + None, + )), + _ => None, + }) + .collect(); + clauses.insert(offset, items); + } + clauses +} + +/// Instance bindings retain their declared type across parameter assignments. +pub fn instance_type_sites(tree: &SyntaxTree) -> Vec<(usize, String, String)> { + let mut sites = Vec::new(); + let mut inherited = None; + for node in tree { + if matches!(node, RefNode::ModuleDeclarationAnsi(_)) { + inherited = None; + } + if let RefNode::AnsiPortDeclarationNet(port) = node.clone() { + if let Some(header) = &port.nodes.0 { + inherited = match header { + sv_parser::NetPortHeaderOrInterfacePortHeader::InterfacePortHeader(header) => { + match &**header { + sv_parser::InterfacePortHeader::Identifier(header) => { + identifier_text(RefNode::InterfaceIdentifier(&header.nodes.0), tree) + } + _ => None, + } + } + _ => None, + }; + } + if let Some(module) = inherited.clone() + && let Some(identifier) = + identifier_text(RefNode::PortIdentifier(&port.nodes.1), tree) + && let Some(offset) = + RefNode::PortIdentifier(&port.nodes.1) + .into_iter() + .find_map(|node| { + if let RefNode::Locate(loc) = node { + Some(loc.offset) + } else { + None + } + }) + { + sites.push((offset, identifier, module)); + } + } else if matches!(node, RefNode::AnsiPortDeclarationVariable(_)) { + inherited = None; + } + + let RefNode::ModuleInstantiation(instance) = node else { + continue; + }; + let Some(module) = identifier_text(RefNode::ModuleIdentifier(&instance.nodes.0), tree) + else { + continue; + }; + for child in RefNode::ModuleInstantiation(instance) { + if let RefNode::NameOfInstance(name) = child { + let node = RefNode::InstanceIdentifier(&name.nodes.0); + let Some(identifier) = identifier_text(node.clone(), tree) else { + continue; + }; + if let Some(offset) = node.into_iter().find_map(|node| { + if let RefNode::Locate(loc) = node { + Some(loc.offset) + } else { + None + } + }) { + sites.push((offset, identifier, module.clone())); + } + } + } + } + sites +} diff --git a/crates/celox-sv-analyzer/src/ast/imports.rs b/crates/celox-sv-analyzer/src/ast/imports.rs index ce221725316..25a526f4264 100644 --- a/crates/celox-sv-analyzer/src/ast/imports.rs +++ b/crates/celox-sv-analyzer/src/ast/imports.rs @@ -411,7 +411,7 @@ pub(super) fn node_range(node: RefNode<'_>) -> (usize, usize) { /// The source ranges of the generate blocks under a module `node`: each is a /// scope of its own (IEEE 1800-2023 27.5). -fn generate_blocks(node: RefNode<'_>) -> Vec<(usize, usize)> { +pub(super) fn generate_blocks(node: RefNode<'_>) -> Vec<(usize, usize)> { if !matches!( node, RefNode::ModuleDeclarationAnsi(_) | RefNode::ModuleDeclarationNonansi(_) diff --git a/crates/celox-sv-analyzer/src/ast/interfaces.rs b/crates/celox-sv-analyzer/src/ast/interfaces.rs index ce7978aa4d6..8f69c64792a 100644 --- a/crates/celox-sv-analyzer/src/ast/interfaces.rs +++ b/crates/celox-sv-analyzer/src/ast/interfaces.rs @@ -249,6 +249,8 @@ pub struct InterfaceElaboration { pub sources: Option>, pub root_names: HashMap, pub interface_ports: HashMap>, + /// Concrete generic port types encountered during specialization. + pub generic_bindings: HashMap<(String, String), HashSet>, } pub fn elaborate_interfaces_with_metadata( @@ -398,8 +400,11 @@ pub fn elaborate_interfaces_with_metadata_and_roots( ) }) .collect(); + let mut generic_bindings = HashMap::default(); + let sources = design.elaborate_with_roots(clones, scales, &mut generic_bindings)?; Ok(InterfaceElaboration { - sources: Some(design.elaborate_with_roots(clones, scales)?), + sources: Some(sources), + generic_bindings, root_names: names, interface_ports, }) @@ -1520,6 +1525,7 @@ impl<'a> Design<'a> { &self, mut clones: Vec<(String, Vec<(String, String)>)>, scales: &super::timescales::Timescales, + generic_bindings: &mut HashMap<(String, String), HashSet>, ) -> Result, AnalyzerError> { let mut edits: Vec> = vec![Vec::new(); self.files.len()]; let mut names: Vec = self.modules.keys().cloned().collect(); @@ -1544,6 +1550,12 @@ impl<'a> Design<'a> { } } while let Some((name, bindings)) = clones.pop() { + for (port, interface) in &bindings { + generic_bindings + .entry((name.clone(), port.clone())) + .or_default() + .insert(interface.clone()); + } let clone_name = clone_module_name(&name, &bindings); if !cloned.insert(clone_name.clone()) { continue; diff --git a/crates/celox-sv-analyzer/src/syntax.rs b/crates/celox-sv-analyzer/src/syntax.rs index 0f11640e107..8dca2a6d482 100644 --- a/crates/celox-sv-analyzer/src/syntax.rs +++ b/crates/celox-sv-analyzer/src/syntax.rs @@ -9,7 +9,22 @@ use crate::AnalyzerError; /// Parse a SystemVerilog source string into an `sv-parser` syntax tree. pub fn parse_source(code: &str, path: &Path) -> Result { - let defines: Defines = HashMap::>::default(); + parse_source_with_defines(code, path, &[]) +} + +/// Parse with predefined empty macros without adding lines to the source. +pub fn parse_source_with_defines( + code: &str, + path: &Path, + names: &[&str], +) -> Result { + let mut defines: Defines = HashMap::default(); + for name in names { + defines.insert( + (*name).to_owned(), + Some(Define::new((*name).to_owned(), Vec::new(), None)), + ); + } let includes: Vec<&Path> = Vec::new(); let (syntax_tree, _) = parse_sv_str(code, path, &defines, &includes, true, false) .map_err(|error| AnalyzerError::Parse(error.to_string()))?; diff --git a/crates/celox-test-suite/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/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 181729bf298..1799e71da3f 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -362,6 +362,7 @@ four-state expectations; the assertions remain enabled on all Celox variants. | Group | Stage | Tool | Cases | Reason | | --- | --- | --- | ---: | --- | +| `sv_icarus_qualified_unit_task` | compile | icarus | 1 | Icarus 13.0 rejects a `$unit::` qualified task call permitted by IEEE 1800-2023 3.12.1. Celox and Verilator pass the unchanged timed case. The [pre-exclusion diagnostic](verification/repros/sv_timed_unit_icarus.json) records the malformed-statement error. | | `sv_icarus_genvar_dimensions` | execute | icarus | 1 | Icarus 13.0 returns 0 for `$dimensions` of a generated loop index's implicit integer localparam; IEEE 1800-2023 27.4 and 20.7 require one packed dimension. Celox and Verilator pass the unchanged assertions. The [standalone reproducer and pre-exclusion result](verification/repros/sv_genvar_dimensions.json) retain the observed disagreement. | | `sv_icarus_constant_array_queries` | compile | icarus | 1 | Icarus 13.0 rejects array queries of variables in constant expressions and typedef operands; IEEE 1800-2023 20.7 permits them. Verilator passes. | | `sv_icarus_runtime_array_queries` | execute | icarus | 1 | Icarus 13.0 aborts on a runtime dimension argument. A standalone reproducer also rejects an integer variable as the dimension. IEEE 1800-2023 20.7 permits querying fixed-size dimensions with runtime expressions. | diff --git a/crates/celox-test-suite/README.md b/crates/celox-test-suite/README.md index 2834e66e035..78581db48a1 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,26 @@ 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. `tick` cannot be mixed with timed operations. + +Reads, output collection and `eval` settle processes due at the current +timestamp without advancing time. External scripted adapters use an Icarus +read/write synchronization callback or a Verilator clocking event sampled in +the observed region. Initial blocks and all `always` processes start after +pre-run input writes settle. `always_ff` listeners retain setup edges and defer +their actions until startup, preserving initial reads before queued NBAs. Internal control names are chosen to avoid source +identifiers. +`run_until` drains its target timestamp before subsequent writes. Only checks +may follow `run_to_finish`; they run in a `final` block that sees the script's +top-level bindings. There is no simulated-time deadline: final checks require +that the script reached the operation and that the design called `$finish`. +Event exhaustion before explicit completion fails the case. + For an invalid design, write `(expect reject)` and no statements. `TestCase::expectation` lets consumers select these separately. For additional 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..d074ff5a133 100644 --- a/crates/celox-test-suite/src/frontend.rs +++ b/crates/celox-test-suite/src/frontend.rs @@ -1,8 +1,14 @@ //! What a suite supplies to build its designs with an external simulator. +mod timed_connections; +mod timed_ff; +mod timed_initializers; + use crate::process::write_if_changed; use crate::script::ScriptCase; use crate::script::sv::{DesignInfo, TESTBENCH_TOP, testbench as generate_testbench}; +use crate::script::timed::validate_timed_design_with_defines; +use crate::script::timed::{after_trivia, sv_words}; use crate::verification::{EmissionError, panic_message}; use crate::{Design, Expectation, Result}; use std::collections::BTreeMap; @@ -12,6 +18,11 @@ use std::path::{Path, PathBuf}; /// The module that instantiates the top with a rejection case's parameters. const PARAMETERS_TOP: &str = "celox_suite_parameters"; +/// The time scale every compiled source gets: a script time unit is 1 ns, +/// and the generated timed testbench settles without advancing time. The +/// directive persists across the files that follow it in one compilation. +const TIMESCALE: &str = "`timescale 1ns/1ps\n"; + /// A design translated to SystemVerilog for an external simulator. pub struct PreparedDesign { /// SystemVerilog sources to compile, in order. @@ -33,6 +44,11 @@ pub trait Frontend: Sync { fn source_extension(&self) -> &'static str; fn prepare(&self, design: &Design) -> Result; + + /// Prepare declarations and sources using the external adapter's macros. + fn prepare_with_defines(&self, design: &Design, _defines: &[&str]) -> Result { + self.prepare(design) + } } /// The files and settings an adapter compiles. @@ -51,7 +67,9 @@ pub(crate) fn stage( 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() { @@ -60,12 +78,44 @@ pub(crate) fn stage( source.text.as_bytes(), )?; } - let prepared = - std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| frontend.prepare(design))) - .map_err(|error| EmissionError(panic_message(error.as_ref())))??; - let mut paths = Vec::new(); + let mut prepared = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + frontend.prepare_with_defines(design, defines) + })) + .map_err(|error| EmissionError(panic_message(error.as_ref())))??; + if design.timed { + let paths = prepared + .sources + .iter() + .enumerate() + .map(|(index, source)| { + ( + source.as_str(), + design + .sources + .get(index) + .map_or(Path::new("timed.sv"), |source| source.path.as_path()), + ) + }) + .collect::>(); + prepared.sources = expanded_timed_sources(&paths, defines)?; + } + let task_timing = timed_ff::TaskTiming::new(&prepared.sources); + let control_names = timed_names(&prepared.sources); + let timescale = directory.join("timescale.sv"); + write_if_changed(×cale, TIMESCALE.as_bytes())?; + let mut paths = vec![timescale]; + if design.timed { + let control = directory.join("timed_control.sv"); + write_if_changed(&control, control_names.generated(TIMED_CONTROL).as_bytes())?; + paths.push(control); + } for (index, source) in prepared.sources.iter().enumerate() { let path = directory.join(format!("source_{index}.sv")); + let source = if design.timed { + timed_source(source, &control_names, &task_timing)? + } else { + source.clone() + }; write_if_changed(&path, source.as_bytes())?; paths.push(path); } @@ -99,7 +149,13 @@ pub(crate) fn stage( .as_ref() .ok_or("the frontend gives no port information for a generated testbench")?; let path = directory.join("testbench.sv"); - write_if_changed(&path, generate_testbench(case, info)?.as_bytes())?; + let bench = generate_testbench(case, info)?; + let bench = if design.timed { + control_names.generated(&bench) + } else { + bench + }; + write_if_changed(&path, bench.as_bytes())?; paths.push(path); top = TESTBENCH_TOP.to_string(); testbench = true; @@ -112,3 +168,492 @@ pub(crate) fn stage( edges: prepared.edges, }) } + +const TIMED_CONTROL: &str = r#"package celox_suite_timed_control; + bit started = 0; + bit setup_started = 0; + bit initializing = 0; + function automatic void celox_suite_begin_initializers(); + initializing = 1; + endfunction + function automatic void celox_suite_begin_setup(); + setup_started = 1; + endfunction + bit finished = 0; + function automatic void celox_suite_start_design(); + if (!finished) started = 1; + endfunction + function automatic void celox_suite_finish_design(input int code = 1); + if (!started && !initializing) return; + finished = 1; + case (code) + 0: $finish(0); + 2: $finish(2); + default: $finish(1); + endcase + endfunction +endpackage +"#; + +struct TimedNames { + package: String, + start: String, + setup: String, + initialize: String, + finish: String, +} + +fn timed_names(sources: &[String]) -> TimedNames { + let words = sources + .iter() + .flat_map(|source| { + sv_words(source) + .into_iter() + .map(|(_, _, word)| word.strip_prefix('\\').unwrap_or(word)) + }) + .collect::>(); + for suffix in 0u64.. { + let name = |base: &str| { + if suffix == 0 { + base.to_string() + } else { + format!("{base}_{suffix}") + } + }; + let names = TimedNames { + package: name("celox_suite_timed_control"), + start: name("celox_suite_start_design"), + setup: name("celox_suite_begin_setup"), + initialize: name("celox_suite_begin_initializers"), + finish: name("celox_suite_finish_design"), + }; + if [ + &names.package, + &names.start, + &names.finish, + &names.setup, + &names.initialize, + ] + .into_iter() + .all(|name| !words.contains(name.as_str())) + { + return names; + } + } + unreachable!() +} +impl TimedNames { + fn generated(&self, source: &str) -> String { + let mut output = String::new(); + let mut previous = 0; + for (start, end, word) in sv_words(source) { + // Generated package references and unqualified helper calls; leave + // source signal paths (dut.name) and quoted script text intact. + if source[..start].trim_end().ends_with('.') { + continue; + } + let prefix = source[..start].trim_end(); + let tail = after_trivia(&source[end..]); + let previous_word = sv_words(prefix).last().map(|word| word.2); + let replacement = match word { + "celox_suite_timed_control" + if tail.starts_with("::") + || matches!(previous_word, Some("package" | "import")) => + { + &self.package + } + "celox_suite_begin_setup" if tail.starts_with('(') => &self.setup, + "celox_suite_begin_initializers" if tail.starts_with('(') => &self.initialize, + "celox_suite_start_design" if tail.starts_with('(') => &self.start, + "celox_suite_finish_design" if tail.starts_with('(') => &self.finish, + _ => continue, + }; + output.push_str(&source[previous..start]); + output.push_str(replacement); + previous = end; + } + output.push_str(&source[previous..]); + output + } +} + +#[cfg(test)] +mod ordered_macro_tests { + use super::*; + #[test] + fn definitions_redefinitions_and_undef_follow_source_order() { + let sources = [ + ("`define ENABLED\n`define VALUE 1\n", Path::new("header.sv")), + ( + "`ifdef ENABLED\nmodule First;initial $display(`VALUE);endmodule\n`endif\n`undef VALUE\n`define VALUE 2\n", + Path::new("first.sv"), + ), + ( + "module Second;initial $display(`VALUE);endmodule\n`undef ENABLED\n", + Path::new("second.sv"), + ), + ( + "`ifdef ENABLED\nmodule Wrong;endmodule\n`else\nmodule Last;endmodule\n`endif\n", + Path::new("last.sv"), + ), + ]; + let expanded = expanded_timed_sources(&sources, &[]).unwrap(); + assert!(expanded[1].contains("$display(1)")); + assert!(expanded[2].contains("$display(2)")); + assert!(expanded[3].contains("module Last")); + assert!(!expanded[3].contains("module Wrong")); + } +} + +#[cfg(test)] +fn expanded_timed_source(source: &str, defines: &[&str], path: &Path) -> Result { + Ok(expanded_timed_sources(&[(source, path)], defines)?.remove(0)) +} + +pub(crate) fn expanded_timed_sources( + sources: &[(&str, &Path)], + names: &[&str], +) -> Result> { + let mut defines: sv_parser::Defines = Default::default(); + for name in names { + defines.insert( + (*name).to_owned(), + Some(sv_parser::Define::new((*name).to_owned(), Vec::new(), None)), + ); + } + let includes: Vec<&Path> = Vec::new(); + let mut result = Vec::new(); + for (source, path) in sources { + let (expanded, next) = + sv_parser::preprocess_str(source, path, &defines, &includes, true, false, 0, 0) + .map_err(|error| format!("timed source preprocessing: {error}"))?; + defines = next; + result.push(expanded.text().to_owned()); + } + Ok(result) +} + +fn timed_source(source: &str, names: &TimedNames, tasks: &timed_ff::TaskTiming) -> Result { + Ok(format!( + "import {}::{};\n{}", + names.package, + names.finish, + timed_content(source, names, tasks)? + )) +} + +fn timed_content(source: &str, names: &TimedNames, tasks: &timed_ff::TaskTiming) -> Result { + let mut output = String::new(); + let mut previous = 0; + let initializers = timed_initializers::rewrites(source, names, tasks.packages.as_ref())?; + let connections = timed_connections::rewrites(source, names, tasks)?; + for (start, end, word) in sv_words(source) { + if start < previous { + continue; + } + if let Some((body_end, replacement)) = + initializers.get(&start).or_else(|| connections.get(&start)) + { + output.push_str(&source[previous..start]); + output.push_str(&timed_ff::in_macro(source, start, replacement.clone())); + previous = *body_end; + continue; + } + if matches!( + word, + "assign" | "wire" | "tri" | "tri0" | "tri1" | "wand" | "wor" | "triand" | "trior" + ) && let Some((body_end, replacement)) = + timed_ff::gated_continuous(source, start, end, names, tasks) + { + output.push_str(&source[previous..start]); + output.push_str(&timed_ff::in_macro(source, start, replacement)); + previous = body_end; + continue; + } + if word == "always_ff" || (word == "always" && timed_ff::edge_control(source, end, tasks)) { + let (replacement_start, body_end, replacement) = + timed_ff::gated(source, start, end, names, tasks)?; + output.push_str(&source[previous..replacement_start]); + output.push_str(&timed_ff::in_macro(source, replacement_start, replacement)); + previous = body_end; + continue; + } + let wildcard_body = (word == "always") + .then(|| timed_ff::wildcard_body(source, end, tasks)) + .flatten(); + if word == "always_comb" || wildcard_body.is_some() { + let body_start = wildcard_body.unwrap_or(end); + let body_end = timed_ff::statement_end(source, body_start) + .ok_or("unterminated combinational statement")?; + let body = timed_content(&source[body_start..body_end], names, tasks)?; + let replacement = format!( + "{} begin if ({}::started) begin {body} end end", + &source[start..body_start], + names.package + ); + output.push_str(&source[previous..start]); + output.push_str(&timed_ff::in_macro(source, start, replacement)); + previous = body_end; + continue; + } + // Keep the startup dependency in the caller: @* excludes globals + // read only inside a function, unlike always_comb. + if word == "$finish" { + let body_end = + timed_ff::statement_end(source, start).ok_or("unterminated $finish statement")?; + let call = if after_trivia(&source[end..]).starts_with('(') { + format!("{}{}", names.finish, &source[end..body_end]) + } else { + format!("{}();", names.finish) + }; + let replacement = format!( + "begin if ({0}::started || {0}::initializing) {call} end ", + names.package + ); + output.push_str(&source[previous..start]); + output.push_str(&timed_ff::in_macro(source, start, replacement)); + previous = body_end; + continue; + } + let replacement = match word { + "initial" => format!("initial wait ({}::started)", names.package), + "always" => { + format!("always wait ({}::started)", names.package) + } + _ => continue, + }; + output.push_str(&source[previous..start]); + output.push_str(&replacement); + previous = end; + } + output.push_str(&source[previous..]); + Ok(output) +} + +#[cfg(all(test, feature = "icarus", feature = "verilator"))] +mod timed_staging_tests { + use crate as celox_test_suite; + use crate::{Backend, load_group, no_std_library}; + + #[test] + #[ignore = "requires Icarus; Celox rejects timing in wildcard bodies and Verilator rejects nested implicit sensitivity"] + fn timed_wildcards_do_not_catch_setup_changes() { + let text = r##"(group wildcards (category sequential)) + (case setup (source "wildcards.sv" #"module Top(input bit go,output bit a,b,c); + task automatic tick(); #1 c=go; endtask + always @* begin #1 a=go; end + always @(*) begin wait(go); b=go; end + always @* tick(); + initial begin #3; $finish; end endmodule"#) + (top Top)(set go 1)(run_to_finish)(assert_eq a 0)(assert_eq b 0)(assert_eq c 0))"##; + let case = load_group("wildcards.vtest", text, no_std_library)[0]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../target/timed-wildcard-protocol") + .join(std::process::id().to_string()); + let frontend = crate::sv::verification::SvFrontend; + let mut icarus = + crate::icarus::Icarus::build_script(&frontend, case, &root.join("icarus")).unwrap(); + icarus.run_testbench().unwrap(); + std::fs::remove_dir_all(root).unwrap(); + } + + #[test] + #[ignore = "requires Icarus, Verilator and a C++ compiler; Celox does not yet support hierarchical task calls"] + fn qualified_timed_tasks_do_not_use_same_named_local_tasks() { + let text = r##"(group qualified (category sequential)) + (case task (source "task.sv" #"module Worker(output bit q); + task tick; #1 q=1; endtask + endmodule + module Top(input bit clk, output bit q); + Worker worker(.q(q)); bit dummy; + task tick; dummy=1; endtask + always @(posedge clk) worker.tick(); + endmodule"#) + (top Top) (set clk 1) (run_until 1) (assert_eq q 0) + (set clk 0) (eval) (set clk 1) (run_until 2) (assert_eq q 1))"##; + let case = load_group("qualified-task.vtest", text, no_std_library)[0]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../target/qualified-task-protocol") + .join(std::process::id().to_string()); + struct TaskFrontend; + impl celox_test_suite::frontend::Frontend for TaskFrontend { + fn source_extension(&self) -> &'static str { + "sv" + } + fn prepare( + &self, + design: &celox_test_suite::Design, + ) -> celox_test_suite::Result { + let frontend = celox_test_suite::sv::verification::SvFrontend; + let mut actual = frontend.prepare(design)?; + // Port shapes are known independently of unsupported method-call + // analysis; this test exercises the external staging adapter. + let stub = celox_test_suite::Design::new( + "module Top(input bit clk, output bit q); endmodule", + "Top", + ); + actual.info = frontend.prepare(&stub)?.info; + Ok(actual) + } + } + let frontend = TaskFrontend; + let mut icarus = + celox_test_suite::icarus::Icarus::build_script(&frontend, case, &root.join("icarus")) + .unwrap(); + icarus.run_testbench().unwrap(); + let mut verilator = celox_test_suite::verilator::Verilator::build_script( + &frontend, + case, + &root.join("verilator"), + ) + .unwrap(); + verilator.run_testbench().unwrap(); + let log = std::fs::read(root.join("verilator/protocol.log")).unwrap(); + celox_test_suite::script::sv::check_output(&log, &[]).unwrap(); + std::fs::remove_dir_all(root).unwrap(); + } + #[test] + #[ignore = "requires Icarus, Verilator and a C++ compiler; frontend lacks implicit generate hierarchy analysis"] + fn ff_staging_preserves_implicit_generate_names() { + let text = r##"(group names (category sequential)) +(case names (source "names.sv" #"module Top(input bit clk,output bit q,y); + always_ff @(posedge clk) q<=1; + if(1) begin bit x;assign x=1;end + assign y=genblk1.x; + endmodule"#)(top Top)(set clk 1)(run_until 0)(assert_eq q 1)(assert_eq y 1))"##; + let case = load_group("names.vtest", text, no_std_library)[0]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../target/generate-name-protocol") + .join(std::process::id().to_string()); + struct NamesFrontend; + impl celox_test_suite::frontend::Frontend for NamesFrontend { + fn source_extension(&self) -> &'static str { + "sv" + } + fn prepare( + &self, + design: &celox_test_suite::Design, + ) -> celox_test_suite::Result { + let frontend = celox_test_suite::sv::verification::SvFrontend; + let mut actual = frontend.prepare(design)?; + // The adapter preserves names even when the frontend cannot + // analyze the original implicit generate hierarchy. + let stub = celox_test_suite::Design::new( + "module Top(input bit clk, output bit q,y); endmodule", + "Top", + ); + actual.info = frontend.prepare(&stub)?.info; + Ok(actual) + } + } + let frontend = NamesFrontend; + let mut icarus = + celox_test_suite::icarus::Icarus::build_script(&frontend, case, &root.join("icarus")) + .unwrap(); + icarus.run_testbench().unwrap(); + let mut verilator = celox_test_suite::verilator::Verilator::build_script( + &frontend, + case, + &root.join("verilator"), + ) + .unwrap(); + verilator.run_testbench().unwrap(); + let log = std::fs::read(root.join("verilator/protocol.log")).unwrap(); + celox_test_suite::script::sv::check_output(&log, &[]).unwrap(); + std::fs::remove_dir_all(root).unwrap(); + } + #[test] + #[ignore = "requires Icarus, Verilator and a C++ compiler; tests external compilation-unit startup staging"] + fn compilation_unit_callables_retain_staged_edges() { + let text = r##"(group unit (category sequential)) + (case callable (source "unit.sv" #"function bit tick();return 1;endfunction + module Top(input bit clk,output bit q,seen);always @(posedge clk)q<=tick();initial seen=q;endmodule"#) + (top Top)(set clk 1)(run_until 0)(assert_eq seen 0)(assert_eq q 1))"##; + let case = load_group("unit.vtest", text, no_std_library)[0]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../target/unit-callable-protocol") + .join(std::process::id().to_string()); + let frontend = celox_test_suite::sv::verification::SvFrontend; + let mut icarus = + celox_test_suite::icarus::Icarus::build_script(&frontend, case, &root.join("icarus")) + .unwrap(); + icarus.run_testbench().unwrap(); + let mut verilator = celox_test_suite::verilator::Verilator::build_script( + &frontend, + case, + &root.join("verilator"), + ) + .unwrap(); + verilator.run_testbench().unwrap(); + let log = std::fs::read(root.join("verilator/protocol.log")).unwrap(); + celox_test_suite::script::sv::check_output(&log, &[]).unwrap(); + std::fs::remove_dir_all(root).unwrap(); + } + #[test] + #[ignore = "requires Icarus, Verilator and a C++ compiler; exercises external declaration staging"] + fn local_declarations_retain_staged_edges() { + let text = r##"(group declarations (category sequential)) + (case local (source "decl.sv" #"module Top(input bit clk,output bit q); + task tick; #1; endtask + always @(posedge clk)begin int tick; q<=1; end endmodule"#) + (top Top)(set clk 1)(run_until 0)(assert_eq q 1))"##; + let case = load_group("decl.vtest", text, no_std_library)[0]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../target/declaration-staging") + .join(std::process::id().to_string()); + let frontend = celox_test_suite::sv::verification::SvFrontend; + let mut icarus = + celox_test_suite::icarus::Icarus::build_script(&frontend, case, &root.join("icarus")) + .unwrap(); + icarus.run_testbench().unwrap(); + let mut verilator = celox_test_suite::verilator::Verilator::build_script( + &frontend, + case, + &root.join("verilator"), + ) + .unwrap(); + verilator.run_testbench().unwrap(); + let log = std::fs::read(root.join("verilator/protocol.log")).unwrap(); + celox_test_suite::script::sv::check_output(&log, &[]).unwrap(); + std::fs::remove_dir_all(root).unwrap(); + } + #[test] + #[ignore = "requires Verilator and a C++ compiler; Icarus rejects deferred assertions"] + fn deferred_assertions_retain_staged_edges() { + let text = r##"(group deferred (category sequential)) + (case assertion (source "assert.sv" #"module Top(input bit clk,output bit q,seen); + task accept; q<=1; endtask + task reject; q<=0; endtask + always @(posedge clk) assert #0 (1) accept(); else reject(); + initial seen=q; + endmodule"#) (top Top) (set clk 1) (run_until 0) (assert_eq seen 0) (assert_eq q 1))"##; + let case = load_group("deferred.vtest", text, no_std_library)[0]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../target/deferred-assertion-protocol") + .join(std::process::id().to_string()); + let mut backend = celox_test_suite::verilator::Verilator::build_script( + &celox_test_suite::sv::verification::SvFrontend, + case, + &root, + ) + .unwrap(); + backend.run_testbench().unwrap(); + std::fs::remove_dir_all(root).unwrap(); + } +} + +#[cfg(test)] +mod adapter_define_tests { + use super::*; + #[test] + fn timed_macro_expansion_uses_the_adapter_define_set() { + let source = "module Top;\n`ifdef CELOX_SUITE_ICARUS\ninitial q=1;\n`else\ninitial q=0;\n`endif\nendmodule"; + let icarus = + expanded_timed_source(source, &["CELOX_SUITE_ICARUS"], Path::new("timed.sv")).unwrap(); + let other = expanded_timed_source(source, &[], Path::new("timed.sv")).unwrap(); + assert!(icarus.contains("q=1")); + assert!(!icarus.contains("q=0")); + assert!(other.contains("q=0")); + assert!(!other.contains("q=1")); + } +} diff --git a/crates/celox-test-suite/src/frontend/timed_connections.rs b/crates/celox-test-suite/src/frontend/timed_connections.rs new file mode 100644 index 00000000000..27752b1b2b7 --- /dev/null +++ b/crates/celox-test-suite/src/frontend/timed_connections.rs @@ -0,0 +1,135 @@ +//! Defer implicit continuous drivers on callable input-port actuals. +use super::*; +use sv_parser::{ListOfPortConnections, NamedPortConnection, RefNode}; + +pub(super) fn rewrites( + source: &str, + names: &TimedNames, + tasks: &timed_ff::TaskTiming, +) -> Result> { + let mut result = BTreeMap::new(); + if !sv_words(source) + .iter() + .any(|(_, _, word)| matches!(*word, "module" | "interface")) + { + return Ok(result); + } + let tree = celox_sv_analyzer::syntax::parse_source(source, Path::new("timed.sv"))?; + let mut used_names = sv_words(source) + .into_iter() + .map(|(_, _, name)| name.to_owned()) + .collect::>(); + for node in &tree { + let RefNode::ModuleInstantiation(module) = node else { + continue; + }; + let (start, end) = timed_initializers::span(&tree, node).ok_or("missing instance span")?; + let module_name = tree + .get_str(&module.nodes.0) + .unwrap_or("") + .trim() + .trim_start_matches('\\'); + let mut replacements = Vec::new(); + let mut drivers = String::new(); + for instance in module.nodes.2.contents() { + let array = !instance.nodes.0.nodes.1.is_empty(); + let Some(connections) = &instance.nodes.1.nodes.1 else { + continue; + }; + let (name_start, name_end) = timed_initializers::span( + &tree, + RefNode::InstanceIdentifier(&instance.nodes.0.nodes.0), + ) + .ok_or("missing instance name")?; + let instance_name = &source[name_start..name_end]; + let connections: Vec<_> = match connections { + ListOfPortConnections::Ordered(ordered) => ordered + .nodes + .0 + .contents() + .into_iter() + .enumerate() + .filter_map(|(index, connection)| { + Some(( + tasks.ports.get(module_name)?.get(index)?.clone(), + connection.nodes.1.as_ref()?, + )) + }) + .collect(), + ListOfPortConnections::Named(named) => named + .nodes + .0 + .contents() + .into_iter() + .filter_map(|connection| { + let NamedPortConnection::Identifier(connection) = connection else { + return None; + }; + Some(( + tree.get_str(&connection.nodes.2)?.trim().to_owned(), + connection.nodes.3.as_ref()?.nodes.1.as_ref()?, + )) + }) + .collect(), + }; + for (port, expression) in connections { + if !tasks + .inputs + .get(module_name) + .is_some_and(|inputs| inputs.contains(port.trim_start_matches('\\'))) + { + continue; + } + let (begin, finish) = + timed_initializers::span(&tree, RefNode::Expression(expression)) + .ok_or("missing connection expression")?; + let Some(expression) = timed_ff::gated_rhs(source, begin, finish, tasks) else { + continue; + }; + let mut suffix = begin; + let name = loop { + let name = format!("{}_connection_{suffix}", names.package); + if used_names.insert(name.clone()) { + break name; + } + suffix += 1; + }; + // Preserve the actual's self-determined width for instance + // arrays: one port width broadcasts, the aggregate width + // distributes (IEEE 1800-2023 23.3.3.5). A scalar connection + // instead supplies its port's assignment context. + let declaration = tasks.connection_declaration( + module_name, + &port, + instance_name, + array, + &expression, + &name, + )?; + drivers.push_str(&format!("{declaration}\nalways_comb begin if ({}::started) {name} = {expression}; end\n", names.package)); + replacements.push((begin, finish, name)); + } + } + if replacements.is_empty() { + continue; + } + replacements.sort_by_key(|r| r.0); + let mut body = source[start..end].to_owned(); + for (begin, finish, name) in replacements.into_iter().rev() { + body.replace_range(begin - start..finish - start, &name); + } + let body = format!("{drivers}{body}"); + result.insert( + start, + ( + end, + if timed_ff::single_generate_body(source, start) { + format!("begin\n{body}\nend") + } else { + body + }, + ), + ); + } + Ok(result) +} diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs new file mode 100644 index 00000000000..ee1f2d424c1 --- /dev/null +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -0,0 +1,1599 @@ +//! Keep FF listeners armed during setup, deferring their actions until startup. +use super::*; + +fn trivia(source: &str, at: usize) -> usize { + source.len() - after_trivia(&source[at..]).len() +} +fn skip_token(source: &str, at: &mut usize) -> bool { + let bytes = source.as_bytes(); + if bytes.get(*at..*at + 2) == Some(b"//") { + *at = source[*at..] + .find('\n') + .map_or(bytes.len(), |end| *at + end); + } else if bytes.get(*at..*at + 2) == Some(b"/*") { + *at = source[*at + 2..] + .find("*/") + .map_or(bytes.len(), |end| *at + end + 4); + } else if bytes.get(*at) == Some(&b'"') { + *at += 1; + while *at < bytes.len() { + match bytes[*at] { + b'\\' => *at = (*at + 2).min(bytes.len()), + b'"' => { + *at += 1; + break; + } + _ => *at += 1, + } + } + } else if bytes.get(*at) == Some(&b'\\') { + while *at < bytes.len() && !bytes[*at].is_ascii_whitespace() { + *at += 1; + } + } else { + return false; + } + true +} +fn semicolon(source: &str, mut at: usize) -> Option { + while at < source.len() { + if skip_token(source, &mut at) { + continue; + } + if source.as_bytes()[at] == b';' { + return Some(at); + } + at += 1; + } + None +} +fn parens(source: &str, begin: usize) -> Option { + if source.as_bytes().get(begin) != Some(&b'(') { + return None; + } + let mut at = begin; + let mut depth = 0; + while at < source.len() { + if skip_token(source, &mut at) { + continue; + } + match source.as_bytes()[at] { + b'(' => depth += 1, + b')' => { + depth -= 1; + if depth == 0 { + return Some(at + 1); + } + } + _ => {} + } + at += 1; + } + None +} +// Resolve callable operands while preserving ordinary value references. +pub(super) fn gated_rhs( + source: &str, + begin: usize, + end: usize, + tasks: &TaskTiming, +) -> Option { + let expression = &source[begin..end]; + let mut calls = false; + let mut bare_calls = Vec::new(); + for (offset, end, word) in sv_words(expression) { + if after_trivia(&expression[end..]).starts_with('(') { + calls = true; + } else if tasks.bare_callable(source, begin + offset, word) { + calls = true; + bare_calls.push(end); + } + } + if !calls { + return None; + } + let mut expression = expression.to_owned(); + for end in bare_calls.into_iter().rev() { + expression.insert_str(end, " ()"); + } + Some(expression) +} + +// Icarus evaluates function operands in a continuous ternary eagerly. Use +// a procedural gate and retain the original net driver (and its delays and +// strengths). Named destinations retain their declared assignment type. +pub(super) fn gated_continuous( + source: &str, + start: usize, + end: usize, + names: &TimedNames, + tasks: &TaskTiming, +) -> Option<(usize, String)> { + let net_declaration = &source[start..end] != "assign"; + let mut at = end; + let mut depth = 0usize; + let mut lhs_start = end; + let mut lhs_name = None; + let mut rhs = None; + let mut previous = start; + let mut output = String::new(); + let mut drivers = String::new(); + while at < source.len() { + if skip_token(source, &mut at) { + continue; + } + match source.as_bytes()[at] { + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' => depth = depth.checked_sub(1)?, + b'=' if depth == 0 && rhs.is_none() => { + let left = source[lhs_start..at].trim(); + lhs_name = Some(if net_declaration { + // Net declaration assignments name an entire net. + tasks + .driver_types + .get(source) + .into_iter() + .flatten() + .find(|(offset, _, _, _)| lhs_start <= *offset && *offset < at) + .map(|(_, id, _, _)| id.clone()) + .or_else(|| sv_words(left).last().map(|word| word.2.to_owned()))? + } else { + // Skip optional drive strength and delay controls. + let mut begin = trivia(left, 0); + if left.as_bytes().get(begin) == Some(&b'(') { + begin = trivia(left, parens(left, begin)?); + } + if left.as_bytes().get(begin) == Some(&b'#') { + begin = trivia(left, begin + 1); + begin = if left.as_bytes().get(begin) == Some(&b'(') { + trivia(left, parens(left, begin)?) + } else { + let tail = &left[begin..]; + begin + tail.find(char::is_whitespace)? + }; + } + left[begin..].trim().to_owned() + }); + rhs = Some(at + 1); + } + b',' | b';' if depth == 0 => { + if let Some(begin) = rhs.take() { + if let Some(expression) = gated_rhs(source, begin, at, tasks) { + let lhs = lhs_name.take()?; + let mut suffix = at; + let name = loop { + let name = format!("{}_driver_{suffix}", names.package); + if !sv_words(source).iter().any(|(_, _, word)| *word == name) { + break name; + } + suffix += 1; + }; + let declaration = tasks.driver_declaration(source, start, &lhs, &name); + drivers.push_str(&format!( + "{declaration}\nalways_comb begin if ({}::started) {name} = {expression}; end\n", names.package + )); + output.push_str(&source[previous..begin]); + output.push_str(&format!(" {name}")); + previous = at; + } + } + lhs_start = at + 1; + if source.as_bytes()[at] == b';' { + if previous == start { + return None; + } + output.push_str(&source[previous..=at]); + let replacement = format!("{drivers}{output}"); + return Some(( + at + 1, + if single_generate_body(source, start) { + format!("begin\n{replacement}\nend") + } else { + replacement + }, + )); + } + } + _ => {} + } + at += 1; + } + None +} + +pub(super) fn statement_end(source: &str, at: usize) -> Option { + let at = trivia(source, at); + if source[at..].starts_with("(*") { + return statement_end(source, parens(source, at)?); + } + let words = sv_words(&source[at..]); + let keyword = words.first().filter(|word| word.0 == 0).map(|word| word.2); + match keyword { + Some("unique" | "unique0" | "priority") => statement_end(source, at + words.first()?.1), + Some("begin" | "case" | "casez" | "casex") => { + let is_block = keyword == Some("begin"); + let mut depth = 0; + for (_, end, word) in &words { + if (is_block && *word == "begin") + || (!is_block && matches!(*word, "case" | "casez" | "casex")) + { + depth += 1; + } + if (is_block && *word == "end") || (!is_block && *word == "endcase") { + depth -= 1; + if depth == 0 { + let end = at + end; + let label = trivia(source, end); + if source.as_bytes().get(label) == Some(&b':') { + let start = trivia(source, label + 1); + let name = sv_words(&source[start..]).first().copied()?; + return Some(start + name.1); + } + return Some(end); + } + } + } + None + } + Some("if" | "for" | "foreach" | "while" | "repeat" | "assert" | "assume" | "cover") => { + let word = words.first()?; + let mut control = trivia(source, at + word.1); + if matches!(keyword, Some("assert" | "assume" | "cover")) { + if source[control..].starts_with("#0") { + control = trivia(source, control + 2); + } else if sv_words(&source[control..]) + .first() + .is_some_and(|word| word.0 == 0 && word.2 == "final") + { + control = trivia(source, control + 5); + } + } + let end = parens(source, control)?; + let body = statement_end(source, end)?; + let next = trivia(source, body); + if matches!(keyword, Some("if" | "assert" | "assume")) + && sv_words(&source[next..]) + .first() + .is_some_and(|word| word.0 == 0 && word.2 == "else") + { + statement_end(source, next + 4) + } else { + Some(body) + } + } + Some("do") => { + let body = statement_end(source, at + words.first()?.1)?; + let next = trivia(source, body); + let word = sv_words(&source[next..]).first().copied()?; + if word.0 != 0 || word.2 != "while" { + return None; + } + let end = parens(source, trivia(source, next + word.1))?; + let semicolon = trivia(source, end); + (source.as_bytes().get(semicolon) == Some(&b';')).then_some(semicolon + 1) + } + Some("forever") => statement_end(source, at + words.first()?.1), + _ => { + let mut cursor = at; + let mut depth = 0; + while cursor < source.len() { + if skip_token(source, &mut cursor) { + continue; + } + match source.as_bytes()[cursor] { + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' => depth -= 1, + b';' if depth == 0 => return Some(cursor + 1), + _ => {} + } + cursor += 1; + } + None + } + } +} + +pub(super) fn single_generate_body(source: &str, start: usize) -> bool { + let mut at = 0; + let mut last_word = ""; + let mut control_end = None; + while at < start { + if skip_token(source, &mut at) { + continue; + } + if source.as_bytes()[at] == b'(' { + if let Some(end) = parens(source, at) { + if source[at..].starts_with("(*") { + at = end; + continue; + } + control_end = matches!(last_word, "if" | "for").then_some(end); + at = end; + continue; + } + } + if source.as_bytes()[at].is_ascii_alphabetic() || source.as_bytes()[at] == b'_' { + let begin = at; + at += 1; + while at < start + && (source.as_bytes()[at].is_ascii_alphanumeric() || source.as_bytes()[at] == b'_') + { + at += 1; + } + last_word = &source[begin..at]; + control_end = (last_word == "else").then_some(at); + } else { + if source.as_bytes()[at] == b':' { + control_end = Some(at + 1); + } else if !source.as_bytes()[at].is_ascii_whitespace() { + control_end = None; + last_word = ""; + } + at += 1; + } + } + control_end.is_some_and(|end| { + let mut at = trivia(source, end); + while source[at..].starts_with("(*") { + let Some(end) = parens(source, at) else { + return false; + }; + at = trivia(source, end); + } + at == start + }) +} + +// Keep attributes on the generated always item, inside a generated block +// when the original listener was a single generate arm. +fn attributes_start(source: &str, start: usize) -> usize { + let mut at = 0; + let mut attributes = start; + while at < start { + at = trivia(source, at); + if at >= start { + break; + } + if source[at..].starts_with("(*") { + attributes = attributes.min(at); + at = parens(source, at).expect("parsed attribute"); + } else { + attributes = start; + if !skip_token(source, &mut at) { + at += 1; + } + } + } + attributes +} + +pub(super) fn gated( + source: &str, + start: usize, + end: usize, + names: &TimedNames, + tasks: &TaskTiming, +) -> Result<(usize, usize, String)> { + let at = trivia(source, end); + if source.as_bytes().get(at) != Some(&b'@') { + return Err("timed always_ff requires an explicit event control".into()); + } + let begin = trivia(source, at + 1); + let event_end = parens(source, begin).ok_or("unsupported timed always_ff event control")?; + let body_start = trivia(source, event_end); + let body_end = + statement_end(source, body_start).ok_or("unsupported timed always_ff statement")?; + let body = timed_content(&source[body_start..body_end], names, tasks)?; + let identifiers = sv_words(source) + .into_iter() + .map(|word| word.2.strip_prefix('\\').unwrap_or(word.2)) + .collect::>(); + let fresh = |kind: &str| { + for suffix in 0.. { + let name = format!("celox_suite_ff_{kind}_{start}_{suffix}"); + if !identifiers.contains(name.as_str()) { + return name; + } + } + unreachable!() + }; + let armed = fresh("armed"); + let captured = fresh("captured"); + let package = &names.package; + let original_event = &source[begin + 1..event_end - 1]; + let event = event_leaves(original_event).join(" or "); + let replacement_start = attributes_start(source, start); + let attributes = &source[replacement_start..start]; + let mut declarations = String::new(); + let mut samples = Vec::new(); + let mut active = Vec::new(); + for (index, leaf) in event_leaves(&event).into_iter().enumerate() { + let leaf = after_trivia(leaf); + let (_, end, edge) = *sv_words(leaf).first().ok_or("empty FF event")?; + if !matches!(edge, "posedge" | "negedge") { + return Err("FF staging requires edge-qualified events".into()); + } + let sample = format!("1'({})", &leaf[end..]); + let baseline = fresh(&format!("baseline_{index}")); + declarations.push_str(&format!("logic {baseline};\n")); + samples.push(format!("{baseline}={sample};")); + let (from, to) = if edge == "posedge" { (0, 1) } else { (1, 0) }; + active.push(format!("(({baseline}===1'b{from} && {sample}!==1'b{from}) || ({baseline}!==1'b{to} && {sample}===1'b{to}))")); + } + let samples = samples.join(" "); + let active = active.join(" || "); + let staged = format!( + "bit {armed}=0;\nbit {captured}=0;\n{declarations}{attributes}always @({event} or posedge {package}::setup_started or posedge {package}::started) begin\n if (!{package}::started) begin\n if ({package}::setup_started && !{captured}) begin {samples} {captured}=1; end\n end\n else if ({armed} || ({active})) begin\n {body}\n end\n {armed}={package}::started;\nend" + ); + // A single generate item needs a block for the additional declarations. + // Reuse that construct's unnamed body rather than inserting another if, + // which would change the user's implicit genblkN numbering. + let staged = if single_generate_body(source, start) { + format!("begin\n{staged}\nend") + } else { + staged + }; + Ok((replacement_start, body_end, format!("{staged}\n"))) +} + +/// The frontend classifies an ordinary always as FF only when every leaf +/// of its event list is explicitly edge-qualified. +pub(super) fn edge_control(source: &str, end: usize, tasks: &TaskTiming) -> bool { + if tasks + .ff_offsets + .get(source) + .is_some_and(|offsets| !offsets.contains(&end.saturating_sub("always".len()))) + { + return false; + } + let at = trivia(source, end); + if source.as_bytes().get(at) != Some(&b'@') { + return false; + } + let begin = trivia(source, at + 1); + let Some(end) = parens(source, begin) else { + return false; + }; + let Some(body_end) = statement_end(source, end) else { + return false; + }; + let body = &source[end..body_end]; + if has_timing(body) || tasks.has_timed_call(source, end, body_end) { + return false; + } + let event = &source[begin + 1..end - 1]; + event_leaves(event).into_iter().all(|leaf| { + let leaf = after_trivia(leaf); + matches!(sv_words(leaf).first(), Some((0, _, "posedge" | "negedge"))) + }) +} + +fn event_leaves(event: &str) -> Vec<&str> { + let event = unwrap_event_leaf(event); + let ors = sv_words(event) + .into_iter() + .filter_map(|(start, _, word)| (word == "or").then_some(start)) + .collect::>(); + let mut at = 0; + let mut start = 0; + let mut depth = 0; + let mut leaves = Vec::new(); + while at < event.len() { + if skip_token(event, &mut at) { + continue; + } + if depth == 0 && (event.as_bytes()[at] == b',' || ors.contains(&at)) { + leaves.push(&event[start..at]); + at += if ors.contains(&at) { 2 } else { 1 }; + start = at; + continue; + } + match event.as_bytes()[at] { + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' => depth -= 1, + _ => {} + } + at += 1; + } + leaves.push(&event[start..]); + leaves.into_iter().map(unwrap_event_leaf).collect() +} + +fn unwrap_event_leaf(mut event: &str) -> &str { + event = after_trivia(event).trim(); + while let Some(end) = parens(event, 0) { + if !after_trivia(&event[end..]).is_empty() { + break; + } + event = after_trivia(&event[1..end - 1]).trim(); + } + event +} + +/// Multiline macro replacements must keep every generated line in the +/// original definition. Existing continuation lines already have a slash. +pub(super) fn in_macro(source: &str, start: usize, replacement: String) -> String { + let lines = source[..start].split('\n').collect::>(); + let mut first = lines.len() - 1; + while first > 0 && lines[first - 1].trim_end().ends_with('\\') { + first -= 1; + } + if !lines[first].trim_start().starts_with("`define") { + return replacement; + } + let mut output = String::new(); + for line in replacement.split_inclusive('\n') { + if let Some(content) = line.strip_suffix('\n') { + output.push_str(content); + if !content.trim_end().ends_with('\\') { + output.push_str(" \\"); + } + output.push('\n'); + } else { + output.push_str(line); + } + } + output +} + +pub(super) fn wildcard_body(source: &str, end: usize, tasks: &TaskTiming) -> Option { + let at = trivia(source, end); + if source.as_bytes().get(at) != Some(&b'@') { + return None; + } + let begin = trivia(source, at + 1); + let event_end = if source.as_bytes().get(begin) == Some(&b'*') { + begin + 1 + } else if let Some(end) = parens(source, begin) + && after_trivia(&source[begin + 1..end - 1]).trim() == "*" + { + end + } else { + return None; + }; + let body_end = statement_end(source, event_end)?; + (!has_timing(&source[event_end..body_end]) + && !tasks.has_timed_call(source, event_end, body_end)) + .then_some(event_end) +} + +fn has_timing(source: &str) -> bool { + if sv_words(source).iter().any(|word| word.2 == "wait") { + return true; + } + let mut at = 0; + while at < source.len() { + if skip_token(source, &mut at) { + continue; + } + if source.as_bytes()[at] == b'#' + && sv_words(&source[..at]) + .last() + .is_some_and(|word| matches!(word.2, "assert" | "assume" | "cover")) + && source[at..].starts_with("#0") + && source.as_bytes().get(trivia(source, at + 2)) == Some(&b'(') + { + at += 2; + continue; + } + if matches!(source.as_bytes()[at], b'#' | b'@') { + return true; + } + at += 1; + } + false +} + +type CallableKey = (String, Option, Vec, String); + +#[derive(Default)] +pub(super) struct TaskTiming { + pub(super) packages: Option, + tasks: BTreeMap, + pub(super) ports: BTreeMap>, + pub(super) inputs: BTreeMap>, + values: BTreeMap>, + driver_types: BTreeMap>, + units: BTreeMap, + import_clauses: BTreeMap, Option)>>>, + generate_scopes: BTreeMap>, + ff_offsets: BTreeMap>, + calls: BTreeMap>, + instance_types: BTreeMap>, + generic_bindings: BTreeMap<(String, String), std::collections::BTreeSet>, + imports: BTreeMap)>>, + exports: BTreeMap, Option)>>, +} + +// `interface` inside an ANSI header is a generic formal, not a container. +fn generic_interface_keyword(source: &str, start: usize) -> bool { + let mut at = 0; + let mut depth = 0usize; + while at < start { + if skip_token(source, &mut at) { + continue; + } + match source.as_bytes()[at] { + b'(' => depth += 1, + b')' => depth = depth.saturating_sub(1), + _ => {} + } + at += 1; + } + depth > 0 +} + +fn container_at(source: &str, at: usize) -> String { + let words = sv_words(&source[..at]); + let mut scope = String::new(); + for (index, (start, _, word)) in words.iter().enumerate() { + if *word == "interface" && generic_interface_keyword(source, *start) { + continue; + } + match *word { + "module" | "interface" | "package" => { + if let Some((_, _, name)) = words[index + 1..] + .iter() + .find(|word| !matches!(word.2, "static" | "automatic")) + { + scope = name.trim_start_matches('\\').to_owned(); + } + } + "endmodule" | "endinterface" | "endpackage" => scope.clear(), + _ => {} + } + } + scope +} + +// Scope identities include their source offsets so closed sibling blocks +// cannot make their imports visible at a later module item. +fn lexical_scope_at(source: &str, at: usize, generates: &[(usize, usize)]) -> Vec { + let mut scopes = Vec::new(); + for (start, _, word) in sv_words(&source[..at]) { + if word == "interface" && generic_interface_keyword(source, start) { + continue; + } + match word { + "module" | "interface" | "package" | "begin" | "fork" | "task" | "function" => { + scopes.push(start) + } + "endmodule" | "endinterface" | "endpackage" | "end" | "join" | "join_any" + | "join_none" | "endtask" | "endfunction" => { + scopes.pop(); + } + _ => {} + } + } + scopes.extend( + generates + .iter() + .filter_map(|(start, end)| (*start <= at && at < *end).then_some(*start)), + ); + scopes.sort_unstable(); + scopes.dedup(); + scopes +} + +impl TaskTiming { + fn driver_declaration(&self, source: &str, at: usize, lhs: &str, name: &str) -> String { + let scope = self.lexical_scope(source, at); + let declaration = self + .driver_types + .get(source) + .into_iter() + .flatten() + .filter(|(offset, id, _, _)| { + id.trim().trim_start_matches('\\') == lhs.trim().trim_start_matches('\\') + && scope.starts_with(&self.lexical_scope(source, *offset)) + }) + .max_by_key(|(offset, _, _, _)| self.lexical_scope(source, *offset).len()); + if let Some((_, _, datatype, dimensions)) = declaration { + let datatype = datatype.trim(); + let implicit = datatype.is_empty() + || datatype.starts_with('[') + || datatype.starts_with("signed") + || datatype.starts_with("unsigned"); + return format!( + "{}{datatype} {name} {dimensions};", + if implicit { "logic " } else { "" } + ); + } + // Part-selects and concatenations have their packed assignment type. + format!("reg [$bits({lhs} )-1:0] {name};") + } + + pub(super) fn connection_declaration( + &self, + module: &str, + port: &str, + instance: &str, + array: bool, + expression: &str, + name: &str, + ) -> Result { + let declaration = self.driver_types.iter().find_map(|(source, declarations)| { + declarations.iter().find(|(offset, id, _, _)| { + id.trim_start_matches('\\') == port.trim().trim_start_matches('\\') + && container_at(source, *offset) == module + && self.lexical_scope(source, *offset).len() == 1 + }) + }); + if declaration.is_none() { + return Err(format!( + "missing input-port type for {module}.{port} in timed callable staging" + ) + .into()); + } + if let Some((_, _, datatype, dimensions)) = declaration { + let datatype = datatype.trim(); + let builtin = datatype.is_empty() + || datatype.starts_with('[') + || sv_words(datatype).first().is_some_and(|w| { + matches!( + w.2, + "bit" + | "logic" + | "reg" + | "signed" + | "unsigned" + | "byte" + | "shortint" + | "int" + | "longint" + | "integer" + | "time" + ) + }); + if !builtin || !dimensions.is_empty() { + // A package-qualified typedef keeps nominal enum/struct identity, + // signedness and unpacked shape without relying on type(expr), + // which the available Icarus adapter does not implement. + if !array + && datatype.contains("::") + && !datatype.contains(['[', '{', '(']) + && dimensions.is_empty() + { + return Ok(format!("{datatype} {name};")); + } + return Err(format!("cannot preserve callable input-port type `{datatype} {dimensions}` for {module}.{port} in timed staging").into()); + } + } + let width = if array { + expression.to_owned() + } else { + format!("{instance} .{port} ") + }; + Ok(format!("reg [$bits({width} )-1:0] {name};")) + } + + fn lexical_scope(&self, source: &str, at: usize) -> Vec { + lexical_scope_at( + source, + at, + self.generate_scopes.get(source).map_or(&[], Vec::as_slice), + ) + } + + fn unit(&self, source: &str) -> Option { + self.units.get(source).copied() + } + fn clause_items( + &self, + source: &str, + start: usize, + end: usize, + ) -> Vec<(Option, Option)> { + if let Some(clauses) = self.import_clauses.get(source) { + return clauses.get(&start).cloned().unwrap_or_default(); + } + // Only malformed sources use the lexical fallback. Split separators + // outside comments, strings and escaped identifiers. + let tail = &source[end..]; + let clause = &tail[..semicolon(tail, 0).unwrap_or(tail.len())]; + let mut parts = Vec::new(); + let mut begin = 0; + let mut at = 0; + while at < clause.len() { + if skip_token(clause, &mut at) { + continue; + } + if clause.as_bytes()[at] == b',' { + parts.push(&clause[begin..at]); + begin = at + 1; + } + at += 1; + } + parts.push(&clause[begin..]); + parts + .into_iter() + .map(|item| { + let words = sv_words(item); + ( + words.first().map(|x| x.2.to_owned()), + words.get(1).map(|x| x.2.to_owned()), + ) + }) + .collect() + } + + fn callable_key(&self, source: &str, at: usize, name: &str) -> CallableKey { + let container = container_at(source, at); + let mut scope = self.lexical_scope(source, at); + if !container.is_empty() && !scope.is_empty() { + scope.remove(0); + } + let unit = container.is_empty().then(|| self.unit(source)).flatten(); + ( + container, + unit, + scope, + name.trim_start_matches('\\').to_owned(), + ) + } + + fn package_callable( + &self, + source: &str, + package: &str, + name: &str, + visiting: &mut std::collections::BTreeSet, + ) -> Option { + let package = package.trim_start_matches('\\'); + let name = name.trim_start_matches('\\'); + let (package, unit) = if package == "$unit" { + ("", self.unit(source)) + } else { + (package, None) + }; + if let Some(value) = + self.tasks + .get(&(package.to_owned(), unit, Vec::new(), name.to_owned())) + { + return Some(*value); + } + if !visiting.insert(package.to_owned()) { + return None; + } + let mut result = None; + if let (Some(imports), Some(exports)) = + (self.imports.get(package), self.exports.get(package)) + { + for (origin, selected) in imports { + if selected.as_deref().is_some_and(|selected| selected != name) { + continue; + } + if !exports.iter().any(|(exported, member)| { + exported.as_deref().is_none_or(|p| p == origin) + && member.as_deref().is_none_or(|n| n == name) + }) { + continue; + } + if let Some(timed) = self.package_callable(source, origin, name, visiting) { + result = Some(result.unwrap_or(false) || timed); + } + } + } + visiting.remove(package); + result + } + pub(super) fn new(sources: &[String]) -> Self { + let mut result = Self::default(); + let paths: Vec<_> = sources + .iter() + .map(|s| (s.as_str(), Path::new("timed.sv"))) + .collect(); + if let Ok(elaboration) = celox_sv_analyzer::elaborate_interfaces_with_metadata(&paths, &[]) + { + result.generic_bindings = elaboration + .generic_bindings + .into_iter() + .map(|(key, types)| (key, types.into_iter().collect())) + .collect(); + } + if let Ok(packages) = celox_sv_analyzer::analyze_packages(&paths) { + for source in sources { + if let Ok(interfaces) = + celox_sv_analyzer::source_module_interfaces(source, Path::new("timed.sv")) + { + for (name, interface) in interfaces { + if let Ok(ir) = celox_sv_analyzer::analyze_source_module_with_packages( + source, + Path::new("timed.sv"), + &name, + &Default::default(), + &packages, + ) { + for module in ir.modules() { + result.inputs.insert( + module.name().to_owned(), + module + .ports() + .iter() + .filter(|port| { + port.direction() + == celox_sv_analyzer::ir::PortDirection::Input + }) + .map(|port| port.name().to_owned()) + .collect(), + ); + } + } + result.ports.insert(name, interface.ports); + } + } + } + result.packages = Some(packages); + } + let mut records = Vec::new(); + for (index, source) in sources.iter().enumerate() { + result.units.insert(source.clone(), index); + if let Ok(tree) = celox_sv_analyzer::syntax::parse_source(source, Path::new("timed.sv")) + { + // Re-preprocessing can add whitespace after escaped names. + // All lexical joins use offsets of the source passed here. + let origin = |offset| { + tree.get_origin(&sv_parser::Locate { + offset, + ..Default::default() + }) + .map_or(offset, |(_, origin)| origin) + }; + let mut driver_types = Vec::new(); + let mut inherited_port_type = None; + let text = |node| { + timed_initializers::span(&tree, node) + .map(|(a, b)| source[a..b].to_owned()) + .unwrap_or_default() + }; + let identifier = |offset| { + sv_words(&source[offset..]) + .first() + .map(|word| word.2.to_owned()) + .unwrap_or_default() + }; + for node in &tree { + use sv_parser::RefNode; + match node { + RefNode::NetDeclaration(sv_parser::NetDeclaration::NetType(n)) => { + let datatype = text(RefNode::DataTypeOrImplicit(&n.nodes.3)); + for declaration in n.nodes.5.nodes.0.contents() { + if let Some((offset, _)) = timed_initializers::span( + &tree, + RefNode::NetIdentifier(&declaration.nodes.0), + ) { + let id = identifier(offset); + let dimensions = declaration + .nodes + .1 + .iter() + .map(|d| text(RefNode::UnpackedDimension(d))) + .collect::>() + .join(" "); + driver_types.push((offset, id, datatype.clone(), dimensions)); + } + } + } + RefNode::ModuleDeclaration(_) | RefNode::InterfaceDeclaration(_) => { + inherited_port_type = None; + } + RefNode::AnsiPortDeclarationNet(n) => { + if let Some(header) = &n.nodes.0 { + inherited_port_type=match header { + sv_parser::NetPortHeaderOrInterfacePortHeader::NetPortHeader(header) => match &header.nodes.1 { + sv_parser::NetPortType::DataType(port) => Some(text(RefNode::DataTypeOrImplicit(&port.nodes.1))), + _ => None, + }, + _ => None, + }; + } + if let (Some(datatype), Some((offset, _))) = ( + &inherited_port_type, + timed_initializers::span( + &tree, + RefNode::PortIdentifier(&n.nodes.1), + ), + ) { + let dimensions = n + .nodes + .2 + .iter() + .map(|d| text(RefNode::UnpackedDimension(d))) + .collect::>() + .join(" "); + driver_types.push(( + offset, + identifier(offset), + datatype.clone(), + dimensions, + )); + } + } + RefNode::AnsiPortDeclarationVariable(n) => { + if let Some(header) = &n.nodes.0 { + inherited_port_type = Some( + text(RefNode::VarDataType(&header.nodes.1.nodes.0)) + .trim_start_matches("var ") + .to_owned(), + ); + } + if let (Some(datatype), Some((offset, _))) = ( + &inherited_port_type, + timed_initializers::span( + &tree, + RefNode::PortIdentifier(&n.nodes.1), + ), + ) { + let dimensions = n + .nodes + .2 + .iter() + .map(|d| text(RefNode::VariableDimension(d))) + .collect::>() + .join(" "); + driver_types.push(( + offset, + identifier(offset), + datatype.clone(), + dimensions, + )); + } + } + RefNode::DataDeclaration(sv_parser::DataDeclaration::Variable(n)) => { + let datatype = text(RefNode::DataTypeOrImplicit(&n.nodes.3)); + for declaration in n.nodes.4.nodes.0.contents() { + if let sv_parser::VariableDeclAssignment::Variable(declaration) = + declaration + { + if let Some((offset, _)) = timed_initializers::span( + &tree, + RefNode::VariableIdentifier(&declaration.nodes.0), + ) { + let id = identifier(offset); + let dimensions = declaration + .nodes + .1 + .iter() + .map(|d| text(RefNode::VariableDimension(d))) + .collect::>() + .join(" "); + driver_types.push(( + offset, + id, + datatype.clone(), + dimensions, + )); + } + } + } + } + _ => {} + } + } + result.driver_types.insert(source.clone(), driver_types); + let mut values = Vec::new(); + for node in &tree { + use sv_parser::RefNode; + let identifier = match node { + RefNode::VariableDeclAssignmentVariable(n) => { + RefNode::VariableIdentifier(&n.nodes.0) + } + RefNode::NetDeclAssignment(n) => RefNode::NetIdentifier(&n.nodes.0), + RefNode::ParamAssignment(n) => RefNode::ParameterIdentifier(&n.nodes.0), + RefNode::AnsiPortDeclarationNet(n) => RefNode::PortIdentifier(&n.nodes.1), + RefNode::AnsiPortDeclarationVariable(n) => { + RefNode::PortIdentifier(&n.nodes.1) + } + RefNode::AnsiPortDeclarationParen(n) => RefNode::PortIdentifier(&n.nodes.2), + RefNode::EnumNameDeclaration(n) => RefNode::EnumIdentifier(&n.nodes.0), + RefNode::ListOfPortIdentifiers(n) => { + for (name, _) in n.nodes.0.contents() { + if let Some(RefNode::Locate(locate)) = RefNode::PortIdentifier(name) + .into_iter() + .find(|n| matches!(n, RefNode::Locate(_))) + { + let offset = origin(locate.offset); + if let Some((_, _, name)) = sv_words(&source[offset..]).first() + { + values.push(( + offset, + name.trim_start_matches('\\').to_owned(), + )); + } + } + } + continue; + } + _ => continue, + }; + if let Some(RefNode::Locate(locate)) = identifier + .into_iter() + .find(|n| matches!(n, RefNode::Locate(_))) + { + let offset = origin(locate.offset); + if let Some((_, _, name)) = sv_words(&source[offset..]).first() { + values.push((offset, name.trim_start_matches('\\').to_owned())); + } + } + } + result.values.insert(source.clone(), values); + result.instance_types.insert( + source.clone(), + celox_sv_analyzer::ast::instance_type_sites(&tree) + .into_iter() + .map(|(offset, name, typ)| (origin(offset), name, typ)) + .collect(), + ); + result.import_clauses.insert( + source.clone(), + celox_sv_analyzer::ast::package_import_export_clauses(&tree) + .into_iter() + .map(|(offset, items)| (origin(offset), items)) + .collect(), + ); + result.calls.insert( + source.clone(), + celox_sv_analyzer::ast::procedural_call_sites(&tree) + .into_iter() + .map(|(offset, name)| (origin(offset), name)) + .collect(), + ); + result.ff_offsets.insert( + source.clone(), + celox_sv_analyzer::ast::ff_always_offsets(&tree) + .into_iter() + .map(origin) + .collect(), + ); + result.generate_scopes.insert( + source.clone(), + celox_sv_analyzer::ast::generate_scope_ranges(&tree) + .into_iter() + .map(|(start, end)| (origin(start), origin(end.saturating_sub(1)) + 1)) + .collect(), + ); + } + let words = sv_words(source); + for (start, end, word) in &words { + if !matches!(*word, "import" | "export") + || result.lexical_scope(source, *start).len() != 1 + { + continue; + } + let container = container_at(source, *start); + // Only package exports participate in qualified resolution. + if !sv_words(&source[..*start]) + .iter() + .rev() + .find(|(_, _, word)| { + matches!( + *word, + "package" + | "module" + | "interface" + | "endpackage" + | "endmodule" + | "endinterface" + ) + }) + .is_some_and(|(_, _, word)| *word == "package") + { + continue; + } + for (package, selected) in result.clause_items(source, *start, *end) { + if *word == "import" { + if let Some(package) = package { + result + .imports + .entry(container.clone()) + .or_default() + .push((package, selected)); + } + } else { + result + .exports + .entry(container.clone()) + .or_default() + .push((package, selected)); + } + } + } + for (index, (start, end, word)) in words.iter().enumerate() { + if *word == "function" { + let header_end = semicolon(source, *end).unwrap_or(source.len()); + let header = &source[*end..header_end]; + let mut name_end = header.len(); + let mut at = 0; + let mut brackets = 0usize; + while at < header.len() { + if skip_token(header, &mut at) { + continue; + } + match header.as_bytes()[at] { + b'[' => brackets += 1, + b']' => brackets = brackets.saturating_sub(1), + b'(' => { + if brackets == 0 { + name_end = at; + } + if let Some(end) = parens(header, at) { + at = end; + continue; + } + } + _ => {} + } + at += 1; + } + if let Some((_, _, name)) = sv_words(&header[..name_end]).last() { + result + .tasks + .insert(result.callable_key(source, *start, name), false); + } + continue; + } + if *word != "task" { + continue; + } + let Some((_, body_end, _)) = + words[index + 1..].iter().find(|word| word.2 == "endtask") + else { + continue; + }; + let Some((_, _, name)) = words[index + 1..] + .iter() + .find(|word| !matches!(word.2, "automatic" | "static")) + else { + continue; + }; + let key = result.callable_key(source, *start, name); + let header_end = + semicolon(&source[..*body_end], *end).map_or(*end, |offset| offset + 1); + result + .tasks + .insert(key.clone(), has_timing(&source[header_end..*body_end])); + records.push((key, source.as_str(), header_end, *body_end)); + } + } + loop { + let mut changed = false; + for (key, source, start, end) in &records { + if !result.tasks[key] && result.has_timed_call(source, *start, *end) { + result.tasks.insert(key.clone(), true); + changed = true; + } + } + if !changed { + return result; + } + } + } + + fn bare_callable(&self, source: &str, at: usize, name: &str) -> bool { + let prefix = source[..at].trim_end(); + if !prefix.ends_with('.') && !prefix.ends_with("::") { + let scope = self.lexical_scope(source, at); + let container = container_at(source, at); + if self.values.get(source).is_some_and(|values| { + values.iter().any(|(offset, value)| { + value == name.trim_start_matches('\\') + && container_at(source, *offset) == container + && scope.starts_with(&self.lexical_scope(source, *offset)) + }) + }) { + return false; + } + } + self.resolve(source, at, name).is_some() + } + + fn resolve(&self, source: &str, at: usize, name: &str) -> Option { + let name = name.trim_start_matches('\\'); + let prefix = source[..at].trim_end(); + if let Some(prefix) = prefix.strip_suffix("::") { + let package = sv_words(prefix).last()?.2; + return self.package_callable(source, package, name, &mut Default::default()); + } + if let Some(prefix) = prefix.strip_suffix('.') { + let instance = sv_words(prefix).last()?.2; + let scope = container_at(source, at); + if let Some(types) = self + .generic_bindings + .get(&(scope.clone(), instance.to_owned())) + { + let mut timed = false; + for typ in types { + timed |= *self + .tasks + .get(&(typ.clone(), None, Vec::new(), name.to_owned()))?; + } + return Some(timed); + } + if let Some(instances) = self.instance_types.get(source) { + let call_scope = self.lexical_scope(source, at); + let found = instances + .iter() + .filter(|(offset, n, _)| { + n.trim_start_matches('\\') == instance.trim_start_matches('\\') + && container_at(source, *offset) == scope + && call_scope.starts_with(&self.lexical_scope(source, *offset)) + }) + .max_by_key(|(offset, _, _)| self.lexical_scope(source, *offset).len()); + return found.and_then(|(_, _, typ)| { + self.tasks + .get(&( + typ.trim_start_matches('\\').to_owned(), + None, + Vec::new(), + name.to_owned(), + )) + .copied() + }); + } + let words = sv_words(&source[..at]); + for pair in words.windows(2) { + if pair[1].2 == instance && container_at(source, pair[0].0) == scope { + if let Some(value) = self.tasks.get(&( + pair[0].2.trim_start_matches('\\').to_owned(), + None, + Vec::new(), + name.to_owned(), + )) { + return Some(*value); + } + } + } + // An unresolved qualified call cannot use a same-named local task. + return None; + } + let scope = container_at(source, at); + let mut key = self.callable_key(source, at, name); + loop { + if let Some(value) = self.tasks.get(&key) { + return Some(*value); + } + if key.2.pop().is_none() { + break; + } + } + let call_scope = self.lexical_scope(source, at); + let mut imports: BTreeMap, Option)> = BTreeMap::new(); + for (start, end, word) in sv_words(&source[..at]) { + if word != "import" { + continue; + } + let import_scope = container_at(source, start); + if !import_scope.is_empty() && import_scope != scope { + continue; + } + let lexical = self.lexical_scope(source, start); + if !call_scope.starts_with(&lexical) { + continue; + } + let (explicit, wildcard) = imports.entry(lexical.len()).or_default(); + for (package, selected) in self.clause_items(source, start, end) { + let Some(package) = package else { + continue; + }; + if selected.as_deref() == Some(name) || selected.is_none() { + if let Some(value) = + self.package_callable(source, &package, name, &mut Default::default()) + { + if selected.as_deref() == Some(name) { + *explicit = Some(value); + } else { + *wildcard = Some(wildcard.unwrap_or(false) || value); + } + } + } + } + } + imports + .into_values() + .rev() + .find_map(|(explicit, wildcard)| explicit.or(wildcard)) + .or_else(|| { + self.tasks + .get(&( + String::new(), + self.unit(source), + Vec::new(), + name.to_owned(), + )) + .copied() + }) + } + + fn has_timed_call(&self, source: &str, start: usize, end: usize) -> bool { + if let Some(calls) = self.calls.get(source) { + return calls.iter().any(|(at, name)| { + *at >= start + && *at < end + && self + .tasks + .keys() + .any(|key| key.3 == name.trim_start_matches('\\')) + && self.resolve(source, *at, name).unwrap_or(true) + }); + } + sv_words(&source[start..end]) + .iter() + .any(|(at, word_end, name)| { + if !self + .tasks + .keys() + .any(|key| key.3 == name.trim_start_matches('\\')) + { + return false; + } + let tail = after_trivia(&source[start + word_end..end]); + let prefix = source[start..start + at].trim_end(); + // .formal(expr) is a named actual, not a method call. A + // qualified call has an identifier before the dot. + if let Some(before_dot) = prefix.strip_suffix('.') + && before_dot.trim_end().ends_with(['(', ',']) + { + return false; + } + let words = sv_words(prefix); + let named_block = words.len() >= 2 + && words[words.len() - 2].2 == "begin" + && after_trivia(&prefix[words[words.len() - 2].1..]).starts_with(':') + && after_trivia(&prefix[words[words.len() - 1].1..]).is_empty(); + let statement_start = named_block + || prefix.is_empty() + || prefix.ends_with([';', ')', ':', '.']) + || words.last().is_some_and(|word| { + matches!( + word.2, + "begin" | "end" | "else" | "forever" | "do" | "endcase" + ) + }); + (tail.starts_with('(') || (tail.starts_with(';') && statement_start)) + && self.resolve(source, start + at, name).unwrap_or(true) + }) + } +} + +#[cfg(test)] +mod callable_analysis_tests { + use super::*; + #[test] + fn generic_interface_formals_resolve_from_specialized_bindings() { + let source="interface Scale;function automatic bit scaled(input bit v);return v;endfunction endinterface\nmodule User(interface s,input bit clk,v,output bit q);always @(posedge clk)q<=s.scaled(v);endmodule\nmodule Top(input bit clk,v,output bit q);Scale s();\nUser u(.s(s),.clk(clk),.v(v),.q(q));endmodule".to_owned(); + let e = celox_sv_analyzer::elaborate_interfaces_with_metadata( + &[(source.as_str(), Path::new("test.sv"))], + &[], + ) + .unwrap(); + assert!(!e.generic_bindings.is_empty()); + let tasks = TaskTiming::new(std::slice::from_ref(&source)); + assert_eq!( + tasks.resolve(&source, source.find("scaled(v)").unwrap(), "scaled"), + Some(false) + ); + } + #[test] + fn modport_formals_resolve_their_interface_methods() { + let source="interface Scale;function automatic bit scaled(input bit v);return v;endfunction modport user(import scaled);endinterface module User(Scale.user s,input bit clk, v,output bit q);always @(posedge clk)q<=s.scaled(v);endmodule".to_owned(); + let tasks = TaskTiming::new(std::slice::from_ref(&source)); + assert_eq!( + tasks.resolve(&source, source.rfind("scaled(v)").unwrap(), "scaled"), + Some(false) + ); + } + #[test] + fn parameterized_instances_resolve_their_declared_method_type() { + let source="interface Scale #(parameter int K=1);function automatic bit scaled(input bit v);return v;endfunction endinterface module Top;Scale #(.K(5)) s();always @(posedge clk)q<=s.scaled(v);endmodule".to_owned(); + let tasks = TaskTiming::new(std::slice::from_ref(&source)); + assert_eq!( + tasks.resolve(&source, source.rfind("scaled(v)").unwrap(), "scaled"), + Some(false) + ); + } + #[test] + fn parsed_imports_keep_escaped_names_and_comment_commas_whole() { + for imports in [ + "import B::*, A /*,*/ :: tick;", + r"import B::*, \A,items ::tick;", + ] { + let package = if imports.contains("items") { + r"\A,items " + } else { + "A" + }; + let source = format!( + "package {package};function bit tick();return 1;endfunction endpackage package B;task tick;#1;endtask endpackage module Top;{imports}always @(posedge clk)q<=tick();endmodule" + ); + let tasks = TaskTiming::new(std::slice::from_ref(&source)); + assert_eq!( + tasks.resolve(&source, source.rfind("tick()").unwrap(), "tick"), + Some(false) + ); + assert!(edge_control( + &source, + source.find("always").unwrap() + 6, + &tasks + )); + } + } + #[test] + fn compilation_units_keep_callable_timing_separate() { + for qualified in [false, true] { + let first = + "task tick;#1;endtask module Top;always @(posedge clk)tick();endmodule".to_owned(); + let second = + "task tick;endtask module Other;always @(posedge clk)tick();endmodule".to_owned(); + let first = if qualified { + first.replace("tick();endmodule", "$unit::tick();endmodule") + } else { + first + }; + let second = if qualified { + second.replace("tick();endmodule", "$unit::tick();endmodule") + } else { + second + }; + let timing = TaskTiming::new(&[first.clone(), second.clone()]); + assert!(timing.has_timed_call(&first, first.find("always").unwrap(), first.len())); + assert!(!timing.has_timed_call(&second, second.find("always").unwrap(), second.len())); + } + } + #[test] + fn local_declarations_are_not_no_argument_task_calls() { + for body in ["int tick; q<=1;", "int value, tick; q<=1;"] { + let source = format!( + "module Top;task tick;#1;endtask always @(posedge clk)begin {body} end endmodule" + ); + let tasks = TaskTiming::new(std::slice::from_ref(&source)); + let at = source.find("always").unwrap() + 6; + assert!(edge_control(&source, at, &tasks), "{body}"); + } + let source = + "module Top;task tick;#1;endtask always @(posedge clk)begin tick; end endmodule" + .to_string(); + let tasks = TaskTiming::new(std::slice::from_ref(&source)); + assert!(!edge_control( + &source, + source.find("always").unwrap() + 6, + &tasks + )); + } + #[test] + fn qualified_and_exported_callable_timing_uses_the_declaring_scope() { + for delay in ["", "#1;"] { + let source = format!( + "package A; task tick; {delay} endtask endpackage + package B; import A::tick; export A::*; endpackage + package C; import B::*; export B::tick; endpackage + module Top; import C::*; always @(posedge clk) tick(); endmodule" + ); + let tasks = TaskTiming::new(std::slice::from_ref(&source)); + assert_eq!( + tasks.package_callable(&source, "C", "tick", &mut Default::default()), + Some(!delay.is_empty()) + ); + let at = source.rfind("tick()").unwrap(); + assert_eq!(tasks.resolve(&source, at, "tick"), Some(!delay.is_empty())); + } + let source = "task tick; endtask module Top; task tick; #1; endtask always @(posedge clk) $unit::tick(); endmodule".to_owned(); + let tasks = TaskTiming::new(std::slice::from_ref(&source)); + assert_eq!( + tasks.resolve(&source, source.rfind("tick()").unwrap(), "tick"), + Some(false) + ); + } + + #[test] + fn escaped_callable_names_remain_whole_tokens() { + let source = r"task \pause.task ; #1; endtask"; + assert_eq!( + sv_words(source) + .iter() + .filter(|x| x.2.starts_with('\\')) + .map(|x| x.2) + .collect::>(), + vec![r"\pause.task"] + ); + } +} diff --git a/crates/celox-test-suite/src/frontend/timed_initializers.rs b/crates/celox-test-suite/src/frontend/timed_initializers.rs new file mode 100644 index 00000000000..4b252e7d4e3 --- /dev/null +++ b/crates/celox-test-suite/src/frontend/timed_initializers.rs @@ -0,0 +1,475 @@ +//! Stage mutable module/generate declaration initializers before procedures. +use super::*; +use sv_parser::{NodeEvent, RefNode, SyntaxTree}; + +pub(super) fn span(tree: &SyntaxTree, node: RefNode<'_>) -> Option<(usize, usize)> { + let origin = |offset| { + tree.get_origin(&sv_parser::Locate { + offset, + len: 1, + line: 0, + }) + }; + let mut range: Option<(usize, usize)> = None; + for child in node { + if let RefNode::Locate(locate) = child + && locate.len > 0 + && let Some((_, start)) = origin(locate.offset) + && let Some((_, last)) = origin(locate.offset + locate.len - 1) + { + range = Some(match range { + None => (start, last + 1), + Some((low, high)) => (low.min(start), high.max(last + 1)), + }); + } + } + range +} + +type Calls = std::collections::BTreeSet<(String, Vec)>; + +fn expression_calls(expr: &celox_sv_analyzer::ir::Expr, calls: &mut Calls) { + use celox_sv_analyzer::ir::Expr; + match expr { + Expr::Call { name, args, .. } => { + calls.insert((name.clone(), args.iter().map(Option::is_some).collect())); + for arg in args.iter().flatten() { + expression_calls(arg, calls); + } + } + Expr::Select { expr, .. } | Expr::Resize { expr, .. } | Expr::Unary { expr, .. } => { + expression_calls(expr, calls) + } + Expr::Concat(parts) | Expr::RepeatConcat { parts, .. } => { + for part in parts { + expression_calls(part, calls); + } + } + Expr::Binary { left, right, .. } => { + expression_calls(left, calls); + expression_calls(right, calls); + } + Expr::Mux { + condition, + then_expr, + else_expr, + } => { + expression_calls(condition, calls); + expression_calls(then_expr, calls); + expression_calls(else_expr, calls); + } + Expr::Inside { expr, items } => { + expression_calls(expr, calls); + for item in items { + for expr in item.exprs() { + expression_calls(expr, calls); + } + } + } + Expr::Ident(_) | Expr::Literal(_) => {} + } +} + +fn effectful_functions( + ir: &celox_sv_analyzer::ir::Ir, +) -> std::collections::BTreeSet<(String, String)> { + use celox_sv_analyzer::ir::Stmt; + let mut functions = BTreeMap::new(); + for module in ir.modules() { + for subroutine in module + .declaration_subroutines() + .iter() + .chain(module.subroutines()) + { + let mut local_names = subroutine + .params + .iter() + .map(|p| p.name.clone()) + .collect::>(); + local_names.insert(subroutine.name.clone()); + local_names.extend(subroutine.return_var.iter().cloned()); + for statement in &subroutine.body { + statement.walk(&mut |stmt| { + if let Stmt::Local { name, .. } = stmt { + local_names.insert(name.clone()); + } + }); + } + let mut effect = subroutine.params.iter().any(|p| p.direction.is_written()); + let mut calls = std::collections::BTreeSet::new(); + let defaults = subroutine + .params + .iter() + .map(|param| { + let mut calls = Calls::new(); + if let Some(default) = ¶m.default { + expression_calls(default, &mut calls); + } + calls + }) + .collect(); + for statement in &subroutine.body { + statement.walk(&mut |stmt| match stmt { + Stmt::SystemTask { .. } => effect = true, + Stmt::Assign { lhs, .. } => effect |= !local_names.contains(lhs.name()), + Stmt::AssignConcat { parts, .. } => { + effect |= parts.iter().any(|lhs| !local_names.contains(lhs.name())) + } + Stmt::Call { name, args, .. } => { + calls.insert((name.clone(), args.iter().map(Option::is_some).collect())); + } + _ => {} + }); + let _ = statement.clone().map( + &mut |expr| { + expression_calls(&expr, &mut calls); + expr + }, + &mut |lhs| lhs, + ); + } + functions + .entry((module.name().to_owned(), subroutine.name.clone())) + .or_insert((effect, calls, defaults)); + } + } + type Effects = BTreeMap<(String, String), (bool, Calls, Vec)>; + fn reaches_effect( + functions: &Effects, + module: &str, + name: &str, + provided: &[bool], + visiting: &mut std::collections::BTreeSet<(String, String, Vec)>, + ) -> bool { + let key = (module.to_owned(), name.to_owned(), provided.to_vec()); + if !visiting.insert(key.clone()) { + return false; + } + let result = functions + .get(&(module.to_owned(), name.to_owned())) + .is_some_and(|(effect, calls, defaults)| { + *effect + || calls + .iter() + .chain( + defaults + .iter() + .enumerate() + .filter(|(index, _)| { + !provided.get(*index).copied().unwrap_or(false) + }) + .flat_map(|(_, calls)| calls), + ) + .any(|(callee, supplied)| { + reaches_effect(functions, module, callee, supplied, visiting) + }) + }); + visiting.remove(&key); + result + } + functions + .keys() + .filter(|(module, name)| { + reaches_effect(&functions, module, name, &[], &mut Default::default()) + }) + .cloned() + .collect() +} + +// Ask the declaration analyzer whether a value can be elaborated, while +// leaving the simulator to evaluate the original expression. A fixed-width +// two-state parameter also classifies wide and X/Z constants without making +// their numerical value part of this rewrite. +fn elaboration_constant( + source: &str, + start: usize, + end: usize, + expression: &str, + seeds: &[String], + packages: Option<&celox_sv_analyzer::Packages>, +) -> bool { + let mut suffix = start; + let (name, guard) = loop { + let name = format!("__celox_initializer_constant_{suffix}"); + let guard = format!("{name}_range"); + if !sv_words(source) + .iter() + .any(|(_, _, word)| *word == name || *word == guard || *word == format!("{name}_value")) + { + break (name, guard); + } + suffix += 1; + }; + let function = format!("{name}_value"); + let probe = format!( + "function automatic bit [127:0] {function}();\n{}\nreturn ({expression}); endfunction\nlocalparam bit [127:0] {name} = {function}(); wire [{name}:{name}] {guard}='0;\n", + seeds.join("\n") + ); + let candidate = if timed_ff::single_generate_body(source, start) { + format!( + "{}begin\n{probe}{}\nend\n{}", + &source[..start], + &source[start..end], + &source[end..] + ) + } else { + format!("{}{probe}{}", &source[..start], &source[start..]) + }; + let path = Path::new("timed.sv"); + let probe_is_constant = |ir: &celox_sv_analyzer::ir::Ir| { + // Inspect the probe's resolved calls in its declaring module and + // generate scope. A constant evaluator may ignore side effects; + // effectful bodies or omitted defaults still require staged execution. + let effects = effectful_functions(ir); + ir.modules().iter().any(|module| { + let effectful = effects.iter().any(|(owner, name)| { + owner == module.name() && name.rsplit('.').next() == Some(function.as_str()) + }); + !effectful + && module.signals().iter().any(|signal| { + signal.name().rsplit('.').next() == Some(guard.as_str()) + && signal.r#type().resolved_width() == Some(1) + }) + }) + }; + if let Some(packages) = packages { + // Reuse all preprocessed compilation units' packages. Analyzing only + // this file mistakes external constant calls for dynamic values and + // moves their initialization across the FF listener baseline. + celox_sv_analyzer::source_module_interfaces(&candidate, path).is_ok_and(|modules| { + modules.keys().any(|module| { + celox_sv_analyzer::analyze_source_module_with_packages( + &candidate, + path, + module, + &Default::default(), + packages, + ) + .is_ok_and(|ir| probe_is_constant(&ir)) + }) + }) + } else { + celox_sv_analyzer::analyze_source(&candidate, path).is_ok_and(|ir| probe_is_constant(&ir)) + } +} + +pub(super) fn rewrites( + source: &str, + names: &TimedNames, + packages: Option<&celox_sv_analyzer::Packages>, +) -> Result> { + let mut result = BTreeMap::new(); + // Recursive statement rewrites do not contain module declarations. + if !sv_words(source) + .iter() + .any(|(_, _, word)| matches!(*word, "module" | "interface")) + { + return Ok(result); + } + let tree = celox_sv_analyzer::syntax::parse_source(source, Path::new("timed.sv"))?; + let mut scopes = Vec::new(); + let mut records = Vec::new(); + let mut used_names = sv_words(source) + .into_iter() + .map(|(_, _, word)| word.to_owned()) + .collect::>(); + let mut groups = BTreeMap::::new(); + let mut static_seeds = BTreeMap::>::new(); + let mut modules = 0usize; + let mut procedures = 0usize; + for event in (&tree).into_iter().event() { + let (entering, node) = match event { + NodeEvent::Enter(node) => (true, node), + NodeEvent::Leave(node) => (false, node), + }; + if matches!( + node, + RefNode::ModuleDeclaration(_) + | RefNode::InterfaceDeclaration(_) + | RefNode::GenerateBlock(_) + ) { + if entering { + scopes.push( + span(&tree, node.clone()) + .ok_or("missing initializer scope")? + .0, + ); + } else { + scopes.pop(); + } + } + if matches!( + node, + RefNode::ModuleDeclaration(_) | RefNode::InterfaceDeclaration(_) + ) { + if entering { + modules += 1; + } else { + modules -= 1; + } + } + if matches!( + node, + RefNode::InitialConstruct(_) + | RefNode::AlwaysConstruct(_) + | RefNode::FinalConstruct(_) + | RefNode::FunctionDeclaration(_) + | RefNode::TaskDeclaration(_) + | RefNode::ClassDeclaration(_) + ) { + if entering { + procedures += 1; + } else { + procedures -= 1; + } + } + if !entering || modules == 0 || procedures != 0 { + continue; + } + let RefNode::DataDeclaration(sv_parser::DataDeclaration::Variable(variable)) = node else { + continue; + }; + let is_const = variable.nodes.0.is_some(); + let (start, end) = span(&tree, node).ok_or("missing declaration source span")?; + let mut removals = Vec::new(); + let mut assignments = String::new(); + let mut temporaries = String::new(); + let datatype = span(&tree, RefNode::DataTypeOrImplicit(&variable.nodes.3)) + .and_then(|(begin, end)| source.get(begin..end)) + .unwrap_or("logic"); + for declaration in variable.nodes.4.nodes.0.contents() { + let sv_parser::VariableDeclAssignment::Variable(declaration) = declaration else { + continue; + }; + let Some((equal, expression)) = &declaration.nodes.2 else { + continue; + }; + let (name_start, name_end) = + span(&tree, RefNode::VariableIdentifier(&declaration.nodes.0)) + .ok_or("missing initializer name")?; + let (equal_start, _) = + span(&tree, RefNode::Symbol(equal)).ok_or("missing initializer assignment")?; + let literal_expression = !RefNode::Expression(expression).into_iter().any(|node| { + matches!( + node, + RefNode::SimpleIdentifier(_) + | RefNode::EscapedIdentifier(_) + | RefNode::SystemTfIdentifier(_) + ) + }); + let (expr_start, expr_end) = span(&tree, RefNode::Expression(expression)) + .ok_or("missing initializer expression")?; + let name = source + .get(name_start..name_end) + .ok_or("initializer name span exceeds source")?; + let expression = source + .get(expr_start..expr_end) + .ok_or("initializer expression span exceeds source")?; + let mut dimensions = String::new(); + for dimension in &declaration.nodes.1 { + let (begin, end) = span(&tree, RefNode::VariableDimension(dimension)) + .ok_or("missing initializer dimensions")?; + dimensions.push_str( + source + .get(begin..end) + .ok_or("initializer dimensions exceed source")?, + ); + } + + let mut known = Vec::<(String, String)>::new(); + for scope in &scopes { + for (name, value) in static_seeds.get(scope).into_iter().flatten() { + known.retain(|(previous, _)| previous != name); + known.push((name.clone(), value.clone())); + } + } + let seeds = known + .into_iter() + .map(|(_, declaration)| declaration) + .collect::>(); + // Keep constant initialization before FF listeners are armed; + // moving an already-high clock into setup would invent an edge. + if literal_expression + || elaboration_constant(source, start, end, expression, &seeds, packages) + { + let scope = *scopes + .last() + .ok_or("constant initializer outside module scope")?; + static_seeds.entry(scope).or_default().push(( + name.trim().to_owned(), + format!("localparam {datatype} {name}{dimensions} = {expression};"), + )); + continue; + } + if is_const { + return Err(crate::script::sv::Unsupported(format!( + "dynamic const initializer `{}` cannot be staged after host setup", + name.trim() + )) + .into()); + } + let mut suffix = equal_start; + let temporary = loop { + let temporary = format!("{}_initializer_value_{suffix}", names.package); + if used_names.insert(temporary.clone()) { + break temporary; + } + suffix += 1; + }; + temporaries.push_str(&format!(", {temporary}{dimensions}")); + assignments.push_str(&format!("if (!{0}::finished) begin {temporary} = {expression}; if (!{0}::finished) {name} = {temporary}; end\n", names.package)); + removals.push((equal_start, expr_end)); + } + if removals.is_empty() { + continue; + } + let (semicolon, _) = span(&tree, RefNode::Symbol(&variable.nodes.5)) + .ok_or("missing declaration terminator")?; + let mut declaration = source + .get(start..semicolon) + .ok_or("declaration span exceeds source")? + .to_owned(); + for (begin, end) in removals.into_iter().rev() { + declaration.replace_range(begin - start..end - start, ""); + } + declaration.push_str(&temporaries); + declaration.push_str( + source + .get(semicolon..end) + .ok_or("declaration terminator exceeds source")?, + ); + let scope = *scopes.last().ok_or("initializer outside module scope")?; + let index = records.len(); + groups + .entry(scope) + .and_modify(|(last, body)| { + *last = index; + body.push_str(&assignments); + }) + .or_insert((index, assignments)); + records.push((start, end, declaration)); + } + // One activation per lexical scope preserves declaration order across + // declarations as well as within a multi-variable declaration. + for (index, (start, end, declaration)) in records.into_iter().enumerate() { + let body = groups + .values() + .find(|(last, _)| *last == index) + .map(|(_, body)| body.as_str()); + let replacement = if let Some(body) = body { + format!( + "{declaration}\ninitial begin wait ({}::initializing);\n{body}end\n", + names.package + ) + } else { + declaration + }; + let replacement = if timed_ff::single_generate_body(source, start) { + format!("begin\n{replacement}end\n") + } else { + replacement + }; + result.insert(start, (end, replacement)); + } + Ok(result) +} diff --git a/crates/celox-test-suite/src/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..8a45208050d 100644 --- a/crates/celox-test-suite/src/icarus.rs +++ b/crates/celox-test-suite/src/icarus.rs @@ -41,7 +41,7 @@ impl Icarus { top, testbench, edges, - } = stage(frontend, design, directory, script)?; + } = stage(frontend, design, directory, script, &["CELOX_SUITE_ICARUS"])?; write_if_changed( &directory.join("vpi_bits.hpp"), include_bytes!("vpi_bits.hpp"), diff --git a/crates/celox-test-suite/src/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..ee9768c7a8b 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,60 @@ pub struct ScriptCase { pub pos: Pos, } +impl ScriptCase { + /// Whether the case advances simulation time, so the design's own + /// processes, delays and clocks run. + pub fn is_timed(&self) -> bool { + let mut timed = false; + for stmt in &self.body { + stmt.walk(&mut |stmt| { + timed |= matches!(stmt.kind, StmtKind::RunUntil(_) | StmtKind::RunToFinish); + }); + } + timed + } + + /// The statements before and after a top-level `(run_to_finish)`. + pub fn split_at_finish(&self) -> (&[Stmt], Option<&[Stmt]>) { + match self + .body + .iter() + .position(|stmt| stmt.kind == StmtKind::RunToFinish) + { + Some(at) => (&self.body[..at], Some(&self.body[at + 1..])), + None => (&self.body, None), + } + } +} + +/// `(run_to_finish)` is a top-level statement, at most once, and only +/// checks follow it: after the design has finished, nothing can drive it. +fn validate_finish(body: &[Stmt]) -> Result<(), ScriptError> { + let mut finished = false; + for stmt in body { + if finished && !stmt.is_check() { + return error( + stmt.pos, + "only assert_eq, assert and expect_output may follow run_to_finish", + ); + } + if stmt.kind == StmtKind::RunToFinish { + finished = true; + continue; + } + let mut nested = None; + stmt.walk(&mut |inner| { + if inner.kind == StmtKind::RunToFinish && nested.is_none() { + nested = Some(inner.pos); + } + }); + if let Some(pos) = nested { + return error(pos, "run_to_finish must be a top-level statement"); + } + } + Ok(()) +} + #[derive(Debug)] pub struct ScriptError { pub pos: Pos, @@ -597,6 +690,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 +882,19 @@ pub fn group(text: &str) -> Result<(String, Vec), ScriptError> { if case.expectation == Expectation::CompilationError && !case.body.is_empty() { return error(pos, "a rejected case has no statements"); } + if case.is_timed() { + let mut tick = false; + for stmt in &case.body { + stmt.walk(&mut |stmt| tick |= matches!(stmt.kind, StmtKind::Tick(..))); + } + if tick { + return error( + pos, + "tick cannot be combined with run_until or run_to_finish", + ); + } + } + validate_finish(&case.body)?; parsed.push(case); } Ok((group_name, parsed)) @@ -874,3 +988,21 @@ mod tests { assert_eq!(cases[1].expectation, Expectation::CompilationError); } } + +#[cfg(test)] +mod timing_mode_tests { + use super::*; + #[test] + fn mixed_tick_and_time_controls_are_rejected_even_in_nested_blocks() { + for body in [ + "(tick clk) (run_until 1)", + "(if 0 (tick clk)) (run_to_finish)", + ] { + let text = format!( + "(group mode (category sequential)) (case test (source \"test.sv\" \"module Top; endmodule\") (top Top) {body})" + ); + let error = group(&text).unwrap_err(); + assert!(error.message.contains("tick cannot be combined"), "{error}"); + } + } +} diff --git a/crates/celox-test-suite/src/script/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..0c4b30e3a12 100644 --- a/crates/celox-test-suite/src/script/mod.rs +++ b/crates/celox-test-suite/src/script/mod.rs @@ -24,6 +24,14 @@ //! | `(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. 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 +61,6 @@ pub mod sexpr; pub mod sv; pub use ast::{ScriptCase, ScriptError}; + +pub(crate) mod timed; +pub use timed::validate_timed_design; diff --git a/crates/celox-test-suite/src/script/sv.rs b/crates/celox-test-suite/src/script/sv.rs index dcd119038d2..20985317415 100644 --- a/crates/celox-test-suite/src/script/sv.rs +++ b/crates/celox-test-suite/src/script/sv.rs @@ -8,12 +8,15 @@ //! 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. +//! Untimed cases use one-step settling between driver operations. Timed +//! cases synchronize with the scheduler without advancing time: Icarus uses +//! a read/write callback and Verilator a clocking event in the observed +//! region. Their initial blocks start after pre-run inputs settle. +//! `run_until` drains its target timestamp before the next script operation. +//! After `run_to_finish`, read-only final checks require both reaching that +//! operation and explicit design completion; event exhaustion is a failure. -use super::ast::{Actual, Expr, Op, 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}; @@ -94,11 +97,84 @@ 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| { + let name = std::path::Path::new(file) + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_default(); + name == "timed_control.sv" && 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) +} + +/// `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> { +pub fn check_output(log: &[u8], sources: &[String]) -> Result<(), String> { fn find(haystack: &[u8], needle: &[u8]) -> Option { haystack .windows(needle.len()) @@ -129,6 +205,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 +241,12 @@ struct Generator<'a> { out: String, indent: usize, temps: usize, + /// Generating the checks after `run_to_finish`, which run in a `final` + /// block: time cannot advance there, and the state is final. + in_final: bool, + /// 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 +327,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 +582,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 +610,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 +897,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.in_final { + self.line("settle();"); + } self.line(format!( "$write(\"\\n{OUTPUT_MARKER}{} {}\\n\");", hex_encode(text), @@ -825,15 +979,38 @@ 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, }; - generator.block(&case.body)?; - let body = generator.out; + 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};"); + let _ = writeln!(out, " timeunit 1ps;"); + let _ = writeln!(out, " timeprecision 1ps;"); for port in &design.inputs { let range = port .array @@ -868,6 +1045,11 @@ 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 || !celox_suite_timed_control::finished) begin\n", + ); + out.push_str(" $display(\"@suite assert run_to_finish was not reached or the design did not finish\");\n end else begin\n"); + out.push_str(&checks); + out.push_str(&end); + out.push_str(" end\n end\nendmodule\n"); + } + None => { + out.push_str(&end); + out.push_str(" $finish;\n end\nendmodule\n"); + } + } + if case.is_timed() { + out = out.replace( + " timeprecision 1ps;", + " timeprecision 1ps;\n import celox_suite_timed_control::*;", + ); + out = out.replace( + " task automatic settle_now;\n #1;\n settled = 1;\n endtask", + r#" bit suite_progress = 0; +`ifndef CELOX_SUITE_ICARUS + clocking suite_settled @(suite_progress); + input #0 progress = suite_progress; + endclocking +`endif + task automatic settle_queues; +`ifdef CELOX_SUITE_ICARUS + suite_progress = 0; + $celox_suite_settle(suite_progress); + wait (suite_progress); +`else + suite_progress <= ~suite_progress; + @(suite_settled); +`endif + endtask + task automatic settle_now; + if (!celox_suite_timed_control::started) begin + settle_queues(); + celox_suite_begin_initializers(); + settle_queues(); + celox_suite_start_design(); + end + settle_queues(); + settled = 1; + endtask"#, + ); + out = out.replace( + " initial begin\n", + " initial begin\n settle_queues();\n celox_suite_begin_setup();\n settle_queues();\n", + ); + } Ok(out) } @@ -919,6 +1158,41 @@ 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 +1252,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 +1267,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..3c492d2945b --- /dev/null +++ b/crates/celox-test-suite/src/script/timed.rs @@ -0,0 +1,187 @@ +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, &[]) +} + +pub(crate) fn validate_timed_design_with_defines(design: &Design, names: &[&str]) -> Result<()> { + if !design.timed { + return Ok(()); + } + let mut defines: sv_parser::Defines = Default::default(); + for name in names { + defines.insert( + (*name).to_owned(), + Some(sv_parser::Define::new((*name).to_owned(), Vec::new(), None)), + ); + } + let includes: Vec<&std::path::Path> = Vec::new(); + for source in &design.sources { + let (active, 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; + let text = active.text(); + if sv_words(text).iter().any(|(start, _, word)| { + matches!(*word, "timeunit" | "timeprecision") + || (matches!(*word, "timescale" | "resetall") && text[..*start].ends_with('`')) + }) { + return Err( + "explicit time scales and resetall are not supported in timed shared cases".into(), + ); + } + } + Ok(()) +} + +pub(crate) fn sv_words(source: &str) -> Vec<(usize, usize, &str)> { + let bytes = source.as_bytes(); + let mut words = Vec::new(); + let mut at = 0; + while at < bytes.len() { + match bytes[at] { + b'/' if bytes.get(at + 1) == Some(&b'/') => { + at += 2; + while at < bytes.len() && bytes[at] != b'\n' { + at += 1; + } + } + b'/' if bytes.get(at + 1) == Some(&b'*') => { + at += 2; + while at + 1 < bytes.len() && &bytes[at..at + 2] != b"*/" { + at += 1; + } + at = (at + 2).min(bytes.len()); + } + b'"' => { + at += 1; + while at < bytes.len() { + match bytes[at] { + b'\\' => at = (at + 2).min(bytes.len()), + b'"' => { + at += 1; + break; + } + _ => at += 1, + } + } + } + b'\\' => { + 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(feature = "external")] +pub(crate) fn after_trivia(mut source: &str) -> &str { + loop { + source = source.trim_start(); + if source.starts_with("//") { + source = source.find('\n').map_or("", |at| &source[at + 1..]); + } else if source.starts_with("/*") { + source = source.find("*/").map_or("", |at| &source[at + 2..]); + } else { + return source; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn design(source: &str) -> Design { + let text = format!( + "(group timing (category sequential)) (case scale (source \"test.sv\" #\"{source}\"#) (top Top) (run_until 0))" + ); + crate::load_group("timing.vtest", &text, crate::no_std_library)[0].design() + } + + #[test] + fn explicit_scales_are_rejected_without_rejecting_literal_text() { + for source in [ + "`timescale 10ns/1ps\nmodule Top; endmodule", + "`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 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() + ); + } + } +} 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..8f019d114e3 --- /dev/null +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -0,0 +1,1403 @@ +(group timing (category sequential)) + +; Procedural timing controls: `#delay`, `@(event)` and `wait (condition)` in +; `initial` blocks and `always` processes. The script advances time with +; `run_until` and `run_to_finish`; the design generates its own clocks. + +(case delays_resume_initial_blocks_at_later_times + (source "delays.sv" #" + module Top(output logic [7:0] a); + parameter int GAP = 4; + logic [7:0] pause = 8'd3; + initial begin + a = 8'd1; + #10 a = 8'd2; + #GAP a = 8'd3; + #(pause) a = 8'd4; + #0 a = 8'd5; + #pause; + $finish; + end + endmodule + "#) + (top Top) + (run_until 0) + (assert_eq a 1) + (run_until 10) + (assert_eq a 2) + (run_until 14) + (assert_eq a 3) + (run_until 17) + (assert_eq a 5 "the zero delay resumes at the same time") + (run_to_finish) + (assert_eq a 5)) + +(case always_with_a_delay_generates_a_clock + (source "clock.sv" #" + module Top(output logic [7:0] count, output logic clk); + initial clk = 1'b0; + initial count = 8'd0; + always #5 clk = ~clk; + always_ff @(posedge clk) count <= count + 8'd1; + endmodule + "#) + (top Top) + (run_until 4) + (assert_eq clk 0) + (assert_eq count 0) + ; Rising edges at 5, 15, ..., 95. + (run_until 100) + (assert_eq count 10) + (assert_eq clk 0)) + +(case edge_waits_resume_before_the_registers_of_that_edge_update + (source "edges.sv" #" + module Top(output logic [7:0] q); + logic clk = 1'b0; + logic [7:0] d = 8'd0; + initial q = 8'd0; + always #5 clk = ~clk; + always_ff @(posedge clk) q <= d; + initial begin + d = 8'd1; + @(posedge clk); + $display("first q=%0d", q); + #1 d = 8'd2; + @(posedge clk); + $display("second q=%0d", q); + @(negedge clk); + $display("negedge q=%0d", q); + repeat (2) @(posedge clk); + $display("repeat q=%0d", q); + $finish; + end + endmodule + "#) + (top Top) + ; A process woken by an edge runs in the active region, before the + ; nonblocking updates of that edge (IEEE 1800-2023 4.4). + (run_to_finish) + (expect_output "first q=0\nsecond q=1\nnegedge q=2\nrepeat q=2\n") + (assert_eq q 2)) + +(case any_change_waits_wake_on_every_value_change + (source "changes.sv" #" + module Top(output logic [7:0] data, output logic flag); + logic [7:0] other = 8'd0; + initial begin + data = 8'd0; + flag = 1'b0; + #3 data = 8'd7; + #4 data = 8'd7; + #1 data = 8'd9; + #2 other = 8'd1; + #2 flag = 1'b1; + #1 $finish; + end + initial forever begin + @(data); + $display("data=%0d", data); + end + initial forever begin + @(other or flag); + $display("other=%0d flag=%0d", other, flag); + end + initial forever begin + @(flag, data); + $display("either"); + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "data=7\neither\ndata=9\neither\nother=1 flag=0\nother=1 flag=1\neither\n")) + +(case wait_statements_block_until_their_condition_holds + (source "wait.sv" #" + module Top(output logic [7:0] y); + logic go = 1'b0; + logic [7:0] level = 8'd0; + initial begin + y = 8'd0; + #7 go = 1'b1; + #5 level = 8'd3; + #5 level = 8'd5; + end + initial begin + wait (go) $display("go"); + wait (go); + $display("still go"); + wait (level > 8'd4) y = level; + $display("level=%0d", level); + #1 $finish; + end + endmodule + "#) + (top Top) + (run_until 6) + (expect_output "") + (run_until 7) + (expect_output "go\nstill go\n") + (run_to_finish) + (expect_output "level=5\n") + (assert_eq y 5)) + +(case level_sensitive_always_runs_as_a_process + (source "level.sv" #" + module Top(output logic [7:0] y); + logic [7:0] a = 8'd0; + logic [7:0] b = 8'd0; + initial y = 8'd0; + always @(a or b) y = a + b; + initial begin + #2 a = 8'd3; + #2 b = 8'd4; + #2 a = 8'd5; + #2 $finish; + end + endmodule + "#) + (top Top) + (run_until 1) + (assert_eq y 0) + (run_until 3) + (assert_eq y 3) + (run_until 5) + (assert_eq y 7) + (run_to_finish) + (assert_eq y 9)) + +(case processes_wake_each_other_at_the_same_time + (source "handshake.sv" #" + module Top(output logic [7:0] y); + logic start = 1'b0; + logic done = 1'b0; + initial begin + y = 8'd0; + #3 start = 1'b1; + @(posedge done); + $display("done at y=%0d", y); + $finish; + end + initial begin + @(posedge start); + y = 8'd1; + #0 y = 8'd2; + done = 1'b1; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "done at y=2\n")) + +(case tasks_with_timing_controls_run_in_processes + (source "tasks.sv" #" + module Top(output logic [7:0] y); + logic clk = 1'b0; + always #5 clk = ~clk; + task automatic pulse(input logic [7:0] value, input int cycles); + y = value; + repeat (cycles) @(posedge clk); + #1 y = 8'd0; + endtask + initial begin + y = 8'd0; + pulse(8'd7, 2); + $display("y=%0d", y); + pulse(8'd9, 1); + $display("y=%0d", y); + $finish; + end + endmodule + "#) + (top Top) + (run_until 10) + (assert_eq y 7) + ; The first pulse ends at 16, when the second one starts. + (run_until 16) + (assert_eq y 9) + (expect_output "y=0\n") + (run_until 25) + (assert_eq y 9) + (run_to_finish) + (expect_output "y=0\n") + (assert_eq y 0)) + +(case edge_waits_see_the_signals_the_script_drives + (source "driven.sv" #" + module Top(input logic a, output logic [7:0] seen); + initial begin + seen = 8'd0; + forever begin + @(posedge a); + seen = seen + 8'd1; + end + end + endmodule + "#) + (top Top) + (modify (set a 0)) + (run_until 1) + (for value (list 1 0 1 1 0) + (modify (set a value)) + (run_until 2)) + (assert_eq seen 2) + (modify (set a 1)) + (run_until 3) + (assert_eq seen 3)) + +(case finish_in_an_always_process_ends_the_simulation + (source "finish.sv" #" + module Top(output logic [7:0] ticks); + initial ticks = 8'd0; + always begin + #3 ticks = ticks + 8'd1; + if (ticks == 8'd4) $finish; + end + endmodule + "#) + (top Top) + (run_until 7) + (assert_eq ticks 2) + (run_to_finish) + (assert_eq ticks 4)) + +(case waiting_processes_do_not_keep_an_idle_simulation_running + (source "idle.sv" #" + module Top(output logic [7:0] y); + logic never = 1'b0; + initial begin + y = 8'd1; + @(posedge never); + y = 8'd2; + end + initial #5 y = 8'd3; + endmodule + "#) + (top Top) + (run_until 5) + (assert_eq y 3) + (run_until 100) + (assert_eq y 3)) + +(case four_state_edges_count_transitions_through_unknown + (source "four_state_edges.sv" #" + module Top(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) + (set host_clk 0) + (run_until 0) + (set host_clk 1'bz)(eval)(assert_eq host_count 1) + (set host_clk 1'bx)(eval)(assert_eq host_count 1) + (set host_clk 1)(eval)(assert_eq host_count 2) + (set host_clk 0)(eval) + (set host_clk 1'bz)(eval)(assert_eq host_count 3) + (run_to_finish) + (assert_eq pos 3) + (assert_eq neg 3) + (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 host_inputs_are_staged_before_time_zero_initial_blocks + (source "setup.sv" #"module Top(input bit a, output bit y); initial y = a; endmodule"#) + (top Top) + (set a 1) + (run_until 0) + (assert_eq y 1)) + +(case eval_starts_due_time_zero_processes + (source "eval.sv" #"module Top(output bit [7:0] y); initial y = 7; endmodule"#) + (top Top) + (eval) + (assert_eq y 7) + (run_until 0)) + +(case direct_reads_settle_waiting_processes + (source "read.sv" #"module Top(input bit go, output bit [7:0] seen); + initial begin wait (go); seen = 1; #0; seen = 2; end + endmodule"#) + (top Top) + (run_until 0) + (set go 1) + (assert_eq seen 2)) + +(case output_reads_settle_waiting_processes + (source "output.sv" #"module Top(input bit go); + initial begin wait (go); $display("woke"); end + endmodule"#) + (top Top) + (run_until 0) + (set go 1) + (expect_output "woke\n")) + +(case run_until_drains_target_time_before_later_writes + (source "boundary.sv" #"module Top(input bit [7:0] a, output bit [7:0] y); + initial #10 y = a; + endmodule"#) + (top Top) + (set a 1) + (run_until 10) + (set a 2) + (assert_eq y 1)) + +(case repeated_settles_do_not_advance_design_time + (source "settles.sv" #"module Top(output bit seen); initial #1 seen = 1; endmodule"#) + (top Top) + (run_until 0) + (for i (range 0 1001) (eval)) + (assert_eq seen 0) + (run_until 1) + (assert_eq seen 1)) + +(case run_to_finish_has_no_simulated_time_deadline + (source "late.sv" #"module Top(output bit done); + initial begin #1000001; done = 1; $finish; end + endmodule"#) + (top Top) + (run_to_finish) + (assert_eq done 1)) + +(case plain_always_processes_start_after_host_inputs + (source "always.sv" #"module Top(input bit a, output bit y); always begin y=a; #1; end endmodule"#) + (top Top) + (set a 1) + (run_until 0) + (assert_eq y 1)) + +(case timed_control_names_do_not_collide_with_design_names + (source "names.sv" #"package celox_suite_timed_control; localparam int N=1; endpackage + module Top(output bit done); + function void celox_suite_finish_design(); done=0; endfunction + initial begin #1; done=1; $finish; end + endmodule"#) + (top Top) + (run_to_finish) + (assert_eq done 1)) + +(case event_always_processes_start_after_host_inputs + (source "event_start.sv" #"module Top(input bit a, output bit y); + bit seen=0; + always @(a) seen=1; + initial y=seen; + endmodule"#) + (top Top) + (set a 1) + (run_until 0) + (assert_eq y 0)) + +(case ff_actions_wait_for_staged_startup + (source "ff_start.sv" #"module Top(input bit clk, output bit y, output bit seen); + always_ff @(posedge clk) seen<=1; + initial y=seen; + endmodule"#) + (top Top) + (set clk 1) + (run_until 0) + (assert_eq y 0) + (assert_eq seen 1)) + +(case ff_startup_does_not_invent_an_unstaged_edge + (source "ff_idle.sv" #"module Top(input bit clk, output bit seen); + always_ff @(posedge clk) begin if (clk) seen<=1; end + endmodule"#) + (top Top) + (set clk 0) + (run_until 0) + (assert_eq seen 0) + (set clk 1) + (run_until 0) + (assert_eq seen 1)) + +(case ff_startup_preserves_nested_if_case_actions + (source "ff_nested.sv" #"module Top(input bit clk, en, output bit [7:0] seen, output bit flag, y); + always_ff @(posedge clk) if (en) begin : update + seen<=seen+1; + case(en) 1: flag<=1; default: flag<=0; endcase + end else begin seen<=0; flag<=0; end + initial y=flag; + endmodule"#) + (top Top) + (set en 1) + (set clk 1) + (run_until 0) + (assert_eq y 0) + (assert_eq seen 1) + (assert_eq flag 1) + (set en 0) + (set clk 0) + (eval) + (set clk 1) + (run_until 0) + (assert_eq seen 0) + (assert_eq flag 0)) + +(case qualified_ff_startup_actions + (source "qualified.sv" #"module Top(input bit clk, en, output bit q, y); + always_ff @(posedge clk) priority case(en) 1: q<=1; default: q<=0; endcase + initial y=q; + endmodule"#) + (top Top) (set en 1) (set clk 1) (run_until 0) + (assert_eq y 0) (assert_eq q 1)) + +(case ordinary_edge_always_retains_staged_startup_edges + (source "ordinary.sv" #"module Top(input bit clk, output bit q, y); + always @(posedge clk) q<=1; + initial y=q; + endmodule"#) + (top Top) (set clk 1) (run_until 0) + (assert_eq y 0) (assert_eq q 1)) + +(case macro_ff_startup_actions + (source "macro.sv" #"`define FF always_ff @(posedge clk) q<=1; + module Top(input bit clk, output bit q, y); + `FF + initial y=q; + endmodule"#) + (top Top) (set clk 1) (run_until 0) + (assert_eq y 0) (assert_eq q 1)) + +(case macro_argument_process_keywords_are_expanded_before_staging + (source "macro_arg.sv" #"`define FF(kind) kind @(posedge clk) q <= d; + module Top(input bit clk, d, output bit q, seen); + `FF(always_ff) + initial seen=q; + endmodule"#) + (top Top) + (set d 1) (set clk 1) (run_until 0) + (assert_eq seen 0) (assert_eq q 1)) + +(case do_while_ff_bodies_are_staged_in_full + (source "do_while.sv" #"module Top(input bit clk, d, output bit q, seen); + always_ff @(posedge clk) do q <= d; while (0); + initial seen=q; + endmodule"#) + (top Top) + (set d 1) (set clk 1) (run_until 0) + (assert_eq seen 0) (assert_eq q 1)) + +(case wildcard_always_blocks_settle_staged_inputs + (source "wildcard.sv" #"module Top(input bit a, output bit y, z); + always @(*) y=a; + always @* z=a; + initial #1; + endmodule"#) + (top Top) + (set a 1) (run_until 0) (assert_eq y 1) (assert_eq z 1)) + +(case timed_edge_always_bodies_do_not_replay_setup_edges + (source "delayed.sv" #"module Top(input bit clk, output bit q); + always @(posedge clk) #1 q=1; + endmodule"#) + (top Top) + (set clk 1) (run_until 1) (assert_eq q 0) + (set clk 0) (eval) (set clk 1) (run_until 2) (assert_eq q 1)) + +(case timed_edge_always_task_calls_do_not_replay_setup_edges + (source "task.sv" #"module Top(input bit clk, output bit q); + task tick; #1 q=1; endtask + task relay; tick(); endtask + always @(posedge clk) relay(); + endmodule"#) + (top Top) + (set clk 1) (run_until 1) (assert_eq q 0) + (set clk 0) (eval) (set clk 1) (run_until 2) (assert_eq q 1)) + +(case imported_timed_tasks_do_not_replay_setup_edges + (source "delays.sv" #"package delays; + task automatic tick(output bit value); #1 value=1; endtask + endpackage"#) + (source "imported.sv" #"module Top(input bit clk, output bit q); + import delays::*; + always @(posedge clk) tick(q); + endmodule"#) + (top Top) + (set clk 1) (run_until 1) (assert_eq q 0) + (set clk 0) (eval) (set clk 1) (run_until 2) (assert_eq q 1)) + +(case untimed_local_tasks_shadow_timed_tasks_in_other_scopes + (source "slow.sv" #"package slow; + task automatic tick(output bit value); #1 value=1; endtask + endpackage"#) + (source "local.sv" #"module Top(input bit clk, output bit q, seen); + task tick; q<=1; endtask + always @(posedge clk) tick(); + initial seen=q; + endmodule"#) + (top Top) + (set clk 1) (run_until 0) (assert_eq seen 0) (assert_eq q 1)) + +(case automatic_module_ff_staging_keeps_its_state + (source "automatic.sv" #"module automatic Top(input bit clk, output bit q, seen); + always_ff @(posedge clk) q<=1; + initial seen=q; + endmodule"#) + (top Top) + (set clk 1) (run_until 0) (assert_eq seen 0) (assert_eq q 1) + (set clk 0) (eval) (set clk 1) (run_until 1) (assert_eq q 1)) + +(case control_members_do_not_pollute_user_package_imports + (source "user.sv" #"package user_values; localparam bit started=1; localparam bit finished=1; endpackage"#) + (source "top.sv" #"module Top(output bit q); import user_values::*; + initial begin q=started & finished; #1; $finish; end + endmodule"#) + (top Top) + (run_until 0) (assert_eq q 1) (run_to_finish)) + +(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 single_item_generate_ff_rewrites_keep_their_else + (source "generate_ff.sv" #"module Top(input bit clk, output bit [1:0] q, seen); + if (0) always_ff @(posedge clk) q<=1; + else always_ff @(posedge clk) q<=2; + initial seen=q; + endmodule"#) + (top Top) (set clk 1) (run_until 0) (assert_eq seen 0) (assert_eq q 2)) + +(case immediate_assertion_ff_keeps_both_actions + (source "assert_ff.sv" #"module Top(input bit clk, en, output bit q); + always_ff @(posedge clk) assert (en) q<=1; else q<=0; + endmodule"#) + (top Top) (set en 0) (set clk 1) (run_until 0) (assert_eq q 0) + (set clk 0) (eval) (set en 1) (set clk 1) (run_until 1) (assert_eq q 1)) + +(case printed_finish_notice_is_design_output + (source "printed.sv" #"module Top; + initial begin $display("source_0.sv:17: $finish called at 0 (1ps)"); #1; $finish; end + endmodule"#) + (top Top) (run_until 0) (expect_output "source_0.sv:17: $finish called at 0 (1ps)\n") (run_to_finish)) + +(case combinational_finish_ends_timed_execution + (source "comb_finish.sv" #"module Top(output bit done); + initial begin #1; done=1; end + always_comb if(done) $finish; + endmodule"#) + (top Top) (run_to_finish) (assert_eq done 1)) + +(case local_function_shadows_unrelated_timed_task + (source "function.sv" #"package UnrelatedTasks; task tick; #1; endtask endpackage + module Top(input bit clk,output bit q,seen); + function bit tick(); return 1; endfunction + always @(posedge clk) q<=tick(); initial seen=q; + endmodule"#) + (top Top) (set clk 1) (run_until 0) (assert_eq seen 0) (assert_eq q 1)) + +(case explicit_timed_import_overrides_earlier_wildcard + (source "imports.sv" #"package A; task tick; endtask endpackage + package B; task tick; #1; endtask endpackage + module Top(input bit clk,output bit q); import A::*; import B::tick; + always @(posedge clk) begin tick(); q=1; end + endmodule"#) + (top Top) (set clk 1) (run_until 0) (assert_eq q 0) + (set clk 0) (eval) (set clk 1) (run_until 2) (assert_eq q 1)) + +(case else_prefixed_instance_is_not_an_else_action + (source "elsewhere.sv" #"module elsewhere; endmodule + module Top(input bit clk,en,output bit q); + always_ff @(posedge clk) if(en) q<=1; + elsewhere u(); + endmodule"#) + (top Top) (set en 1) (set clk 1) (run_until 0) (assert_eq q 1)) + +(case nested_imports_do_not_leak_into_module_edge_processes + (source "imports.sv" #"package A; + task automatic tick(output bit value); value=1; endtask + endpackage + package B; + task automatic tick(output bit value); #1 value=1; endtask + endpackage + module Top(input bit clk,output bit q); + import A::tick; + if(1) begin : nested import B::tick; end + always @(posedge clk) tick(q); + endmodule"#) + (top Top) (set clk 1) (run_until 0) (assert_eq q 1)) + +(case single_item_case_generate_ff_is_staged_together + (source "case.sv" #"module Top(input bit clk,output bit q,seen); + localparam MODE=0; + case(MODE) 0:always_ff @(posedge clk)q<=1;default:always_ff @(posedge clk)q<=0;endcase + initial seen=q; + endmodule"#) + (top Top)(set clk 1)(run_until 0)(assert_eq seen 0)(assert_eq q 1)) + +(case timed_expansion_preserves_adapter_macros + (source "macros.sv" #"module Top(output bit q); + `ifdef CELOX_SUITE_ICARUS + initial begin q=1;#1;$finish;end + `else + initial begin q=1;#1;$finish;end + `endif + endmodule"#) + (top Top)(run_to_finish)(assert_eq q 1)) + +(case multiple_import_items_preserve_untimed_edges + (source "imports.sv" #"package A; task other; #1; endtask endpackage + package B; int result; task tick; result=1; endtask endpackage + module Top(input bit clk,output int q); import A::other, B::tick; + always @(posedge clk) tick(); assign q=B::result; endmodule"#) + (top Top)(set clk 1)(run_until 0)(assert_eq q 1)) +(case escaped_timed_tasks_do_not_replay_setup_edges + (source "escaped.sv" #"module Top(input bit clk,output bit q); + task \pause.task ; #1 q=1; endtask + always @(posedge clk) \pause.task ; endmodule"#) + (top Top)(set clk 1)(run_until 1)(assert_eq q 0) + (set clk 0)(eval)(set clk 1)(run_until 2)(assert_eq q 1)) +(case control_names_do_not_rewrite_the_dut_type + (source "collision.sv" #"module celox_suite_timed_control(output bit q);initial q=1;endmodule"#) + (top celox_suite_timed_control)(run_until 0)(assert_eq q 1)) + +(case attributes_preserve_single_generate_arms + (source "attributes.sv" #"module Top(input bit clk,output bit q,r); + if(0) always_ff @(posedge clk)q<=0; + else (* keep *) always_ff @(posedge clk)q<=1; + case(0) + 0: (* keep *) always_ff @(posedge clk)r<=1; + default: (* keep *) always_ff @(posedge clk)r<=0; + endcase endmodule"#) + (top Top)(set clk 1)(run_until 0)(assert_eq q 1)(assert_eq r 1)) +(case adapter_defines_preserve_line_macros + (source "line.sv" #"module Top(output int q); +initial q=`__LINE__; +endmodule"#) + (top Top)(run_until 0)(assert_eq q 2)) +(case callable_timing_keeps_generate_scope + (source "scopes.sv" #"module Top(input bit clk,output bit q,r); + if(1) begin:untimed task tick;q=1;endtask always @(posedge clk)tick();end + if(1) begin:timed task tick;#1 r=1;endtask always @(posedge clk)tick();end + endmodule"#) + (top Top)(set clk 1)(run_until 1)(assert_eq q 1)(assert_eq r 0) + (set clk 0)(eval)(set clk 1)(run_until 2)(assert_eq r 1)) + +(case timed_file_macros_keep_each_source_path + (source "first.sv" #"module Leaf;initial $display("%s",`__FILE__);endmodule"#) + (source "second.sv" #"module Top;Leaf u();initial #1 $display("%s",`__FILE__);endmodule"#) + (top Top)(run_until 1)(expect_output "first.sv\nsecond.sv\n")) +(case escaped_identifiers_do_not_collide_with_control_names + (source "escaped-control.sv" #"package \celox_suite_timed_control ;parameter bit Q=1;endpackage + module Top(output bit q);initial q=\celox_suite_timed_control ::Q;endmodule"#) + (top Top)(run_until 0)(assert_eq q 1)) + +(case single_item_generate_imports_do_not_leak + (source "imports.sv" #"package A; task automatic tick(output bit value); value=1; endtask endpackage + package B; task automatic tick(output bit value); #1 value=1; endtask endpackage + module Top(input bit clk,output bit q); + import A::tick; + if(1) import B::tick; + always @(posedge clk) tick(q); + endmodule"#) + (top Top)(set clk 1)(run_until 0)(assert_eq q 1)) + +(case exported_untimed_tasks_keep_setup_edges + (source "exports.sv" #"package A; task automatic tick(output bit value); value=1; endtask endpackage + package B; import A::tick; export A::*; endpackage + package C; import B::tick; export *::*; endpackage + module Top(input bit clk,output bit q); + import C::*; + always @(posedge clk) tick(q); + endmodule"#) + (top Top)(set clk 1)(run_until 0)(assert_eq q 1)) + +(case qualified_unit_tasks_keep_setup_edges + (source "unit.sv" #"task automatic tick(output bit value); value=1; endtask + module Top(input bit clk,output bit q); + always @(posedge clk) $unit::tick(q); + endmodule"#) + (top Top)(set clk 1)(run_until 0)(assert_eq q 1)) + +(case function_return_bounds_do_not_shadow_local_calls + (source "bounds.sv" #"module Other; task tick(); #1; endtask endmodule + module Top(input bit clk,output bit q); parameter N=2; + function logic [$clog2(N)-1:0] tick(); return 1; endfunction + always @(posedge clk) q<=tick(); endmodule"#) + (top Top)(set clk 1)(run_until 0)(assert_eq q 1)) + +(case control_shaped_display_is_design_output + (source "printed.sv" #"module Top; + initial begin $display("timed_control.sv:3: $finish called at 5 (1ns)"); + $display("- timed_control.sv:3: Verilog $finish"); #5; $finish; end endmodule"#) + (top Top)(run_to_finish) + (expect_output "timed_control.sv:3: $finish called at 5 (1ns)\n- timed_control.sv:3: Verilog $finish\n")) + +(case staged_ff_edge_can_finish_without_scheduled_work + (source "host-finish.sv" #"module Top(input bit clk);always @(posedge clk)$finish;endmodule"#) + (top Top)(set clk 1)(run_to_finish)) + +(case coalesced_setup_writes_do_not_invent_ff_edges + (source "setup-pulse.sv" #"module Top(input bit clk,rst,output bit [7:0] q,r); + always @(posedge clk) q<=q+1;always @(negedge rst)r<=r+1;endmodule"#) + (top Top)(set clk 1)(set clk 0)(set rst 1)(set rst 0) + (run_until 0)(assert_eq q 0)(assert_eq r 0)) + +(case computed_edge_always_processes_arm_after_setup + (source "computed-always.sv" #"module Top(input bit a,b,output bit[7:0]seen); + always @(posedge (a|b))seen=seen+1;endmodule"#) + (top Top)(set a 1)(run_until 0)(assert_eq seen 0) + (set a 0)(eval)(set a 1)(eval)(assert_eq seen 1)) + +(case non_ff_multiple_edge_always_processes_arm_after_setup + (source "multi-always.sv" #"module Top(input bit a,b,output bit[7:0]seen); + always @(posedge a or negedge b)seen=seen+1;endmodule"#) + (top Top)(set a 1)(run_until 0)(assert_eq seen 0) + (set a 0)(eval)(set a 1)(eval)(assert_eq seen 1) + (set b 1)(eval)(set b 0)(eval)(assert_eq seen 2)) + +(case timed_calls_after_forever_do_not_replay_setup_edges + (source "forever-task.sv" #"module Top(input bit clk,output bit q); + task automatic tick();#1 q=1;endtask + always @(posedge clk)forever tick; + initial begin #3;$finish;end endmodule"#) + (top Top)(set clk 1)(run_to_finish)(assert_eq q 0)) + +(case parenthesized_ff_event_leaves_preserve_setup_edges + (source "parenthesized.sv" #"module Top(input bit clk,output bit q,r); + always @((posedge clk))q<=1;always_ff @((posedge clk))r<=1;endmodule"#) + (top Top)(set clk 1)(run_until 0)(assert_eq q 1)(assert_eq r 1)) + +(case named_arguments_do_not_invent_timed_calls + (source "named-call.sv" #"module Top(input bit clk,output bit q); + task automatic tick();#1;endtask + function automatic bit f(input bit tick);return tick;endfunction + always @(posedge clk)q<=f(.tick(1));endmodule"#) + (top Top)(set clk 1)(run_until 0)(assert_eq q 1)) + +(case timed_calls_after_do_do_not_replay_setup_edges + (source "do-task.sv" #"module Top(input bit clk,output bit q); + task automatic tick();#1 q=1;endtask + always @(posedge clk)do tick;while(0); + initial begin #3;$finish;end endmodule"#) + (top Top)(set clk 1)(run_to_finish)(assert_eq q 0)) + +(case timed_calls_after_named_blocks_do_not_replay_setup_edges + (source "named-block-task.sv" #"module Top(input bit clk,output bit q); + task automatic tick();#1 q=1;endtask + always @(posedge clk)begin : work tick;end + initial begin #3;$finish;end endmodule"#) + (top Top)(set clk 1)(run_to_finish)(assert_eq q 0)) + +(case timed_calls_after_endcase_do_not_replay_setup_edges + (source "endcase-task.sv" #"module Top(input bit clk,sel,output bit q); + task automatic tick();#1 q=1;endtask + always @(posedge clk)begin case(sel)0:;default:;endcase tick;end + initial begin #3;$finish;end endmodule"#) + (top Top)(set clk 1)(run_to_finish)(assert_eq q 0)) + +(case inactive_time_directives_do_not_change_scheduler_units + (source "inactive-scale.sv" #"`ifdef NEVER_DEFINED + `timescale 10ns/1ps + `endif + module Top(output bit q);initial begin #1;q=1;end endmodule"#) + (top Top)(run_until 1)(assert_eq q 1)) + +(case comment_semicolons_in_function_headers_preserve_setup_edges + (source "function-comment.sv" #"module Other;task automatic tick();#1;endtask endmodule + module Top(input bit clk,output bit q); + function int /* ; */ tick();return 1;endfunction + always @(posedge clk)q<=tick();endmodule"#) + (top Top)(set clk 1)(run_until 0)(assert_eq q 1)) + +(case import_comment_commas_do_not_change_visible_callables + (source "import-comment.sv" #"package A;task automatic tick();#1;endtask task automatic other();endtask endpackage + package B;function automatic bit tick();return 1;endfunction endpackage + module Top(input bit clk,output bit q);import B::*, A /*,*/ :: other; + always @(posedge clk)q<=tick();endmodule"#) + (top Top)(set clk 1)(run_until 0)(assert_eq q 1)) + +(case escaped_import_commas_keep_explicit_callable_selection + (source "escaped-import.sv" #"package \A,items ;function automatic bit tick();return 1;endfunction endpackage + package B;task automatic tick();#1;endtask endpackage + module Top(input bit clk,output bit q);import \A,items ::tick; + always @(posedge clk)q<=tick();endmodule"#) + (top Top)(set clk 1)(run_until 0)(assert_eq q 1)) + +(case parameterized_interface_methods_keep_setup_edges + (source "interface-method.sv" #" + interface Scale #(parameter int K=1); + function automatic logic [3:0] scaled(input logic [3:0] v); + return v*K; + endfunction + endinterface + module Top(input bit clk,input logic [3:0] v,output logic [3:0] q); + Scale #(.K(5)) s(); + always @(posedge clk) q <= s.scaled(v); + endmodule + "#) + (top Top)(set v 2)(set clk 1)(run_until 0)(assert_eq q 10)) + + +(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 interface_modport_methods_keep_setup_edges + (source "modport-method.sv" #" + interface Scale #(parameter int K=5); + logic[3:0] base; + function automatic logic[3:0] scaled(input logic[3:0] v);return base+v*K;endfunction + modport user(import scaled); + endinterface + module User(Scale.user s,input bit clk,input logic[3:0] v,output logic[3:0] q); + always @(posedge clk)q<=s.scaled(v); + endmodule + module Top(input bit clk,input logic[3:0] v,output logic[3:0] q); + Scale #(.K(5)) s(); + assign s.base=0; + User u(.s(s),.clk(clk),.v(v),.q(q)); + endmodule + "#) + (top Top)(set v 2)(set clk 1)(run_until 0)(assert_eq q 10)) + +(case generic_interface_methods_keep_setup_edges + (source "generic_interface_methods_keep_setup_edges.sv" #" + interface Scale #(parameter int K=5); + logic[3:0] base; + function automatic logic[3:0] scaled(input logic[3:0] v);return base+v*K;endfunction + modport user(import scaled); + endinterface + module User(interface s,input bit clk,input logic[3:0] v,output logic[3:0] q); + always @(posedge clk)q<=s.scaled(v); + endmodule + module Top(input bit clk,input logic[3:0] v,output logic[3:0] q); + Scale #(.K(5)) s(); + assign s.base=0; + User u(.s(s),.clk(clk),.v(v),.q(q)); + endmodule + "#) + (top Top)(set v 2)(set clk 1)(run_until 0)(assert_eq q 10)) + +(case inherited_interface_methods_keep_setup_edges + (source "inherited_interface_methods_keep_setup_edges.sv" #" + interface Scale #(parameter int K=5); + logic[3:0] base; + function automatic logic[3:0] scaled(input logic[3:0] v);return base+v*K;endfunction + modport user(import scaled); + endinterface + module User(Scale.user unused, s,input bit clk,input logic[3:0] v,output logic[3:0] q); + always @(posedge clk)q<=s.scaled(v); + endmodule + module Top(input bit clk,input logic[3:0] v,output logic[3:0] q); + Scale #(.K(5)) s(); + assign s.base=0; + User u(.unused(s),.s(s),.clk(clk),.v(v),.q(q)); + endmodule + "#) + (top Top)(set v 2)(set clk 1)(run_until 0)(assert_eq q 10)) + +(case pure_function_rhs_preserves_distinct_write_times + (source "pure-timed-writes.sv" #" + module Child(output bit[1:0]q); + function automatic bit one();return 1;endfunction + initial begin #1;q[0]=one();end + initial begin #2;q[1]=one();end + endmodule + module Top(output bit[7:0]seen); + wire[1:0]q;Child u(.q(q)); + initial forever begin @(q[0]^q[1]);seen=seen+1;end + endmodule + "#) + (top Top)(run_until 1)(assert_eq seen 1)(run_until 2)(assert_eq seen 2)) + +(case conditional_writes_preserve_distinct_activation_times + (source "conditional-writes.sv" #" + module Child(input bit sel,output bit[1:0]q); + initial begin #1;if(sel)q[0]=1;else q[0]=0;end + initial begin #2;q[1]=1;end + endmodule + module Top(input bit sel,output bit[7:0]seen); + wire[1:0]q;Child u(.sel(sel),.q(q)); + initial forever begin @(q[0]^q[1]);seen=seen+1;end + endmodule + "#) + (top Top)(set sel 1)(run_until 1)(assert_eq seen 1)(run_until 2)(assert_eq seen 2)) + +(case case_writes_preserve_distinct_activation_times + (source "case-writes.sv" #" + module Child(input bit[1:0]sel,output bit[1:0]q); + initial begin #1;case(sel) 0:q[0]=0;1:q[0]=1;default:q[0]=1;endcase end + initial begin #2;q[1]=1;end + endmodule + module Top(input bit[1:0]sel,output bit[7:0]seen); + wire[1:0]q;Child u(.sel(sel),.q(q)); + initial forever begin @(q[0]^q[1]);seen=seen+1;end + endmodule + "#) + (top Top)(set sel 1)(run_until 1)(assert_eq seen 1)(run_until 2)(assert_eq seen 2)) + +(case staged_wildcard_finish_waits_for_startup + (source "staged-finish.sv" #"module Top(input bit go,output bit seen);always @* begin seen=go;if(go)$finish;end endmodule"#) + (top Top)(set go 1)(run_to_finish)(assert_eq seen 1)) + +(case constant_repeat_writes_preserve_distinct_activation_times + (source "constant_repeat_writes_preserve_distinct_activation_times.sv" #"module Child(output bit[1:0]q);initial begin #1;repeat(1)q[0]=1;end initial begin #2;q[1]=1;end endmodule module Top(output bit[7:0]seen);wire[1:0]q;Child u(.q(q));initial forever begin @(q[0]^q[1]);seen=seen+1;end endmodule"#) + (top Top)(run_until 1)(assert_eq seen 1)(run_until 2)(assert_eq seen 2)) + +(case separate_comb_assignments_preserve_selected_dependencies + (source "separate_comb_assignments_preserve_selected_dependencies.sv" #"module Child(input bit a,b,output bit[1:0]q);always_comb begin q[0]=a;q[1]=b;end endmodule module Top(output bit[7:0]seen);bit a,b;wire[1:0]q;Child u(.a(a),.b(b),.q(q));initial begin #1;b=1;b=0;#1;a=1;end initial forever begin @(q[0]);seen=seen+1;end endmodule"#) + (top Top)(run_until 1)(assert_eq seen 0)(run_until 2)(assert_eq seen 1)) + +(case staged_always_comb_finish_ignores_initial_inputs + (source "initial-comb-finish.sv" #"module Top(input bit go,output bit seen);always_comb begin seen=go;if(!go)$finish;end initial begin #1;$finish;end endmodule"#) + (top Top)(set go 1)(run_to_finish)(assert_eq seen 1)) + +(case constant_for_writes_preserve_distinct_activation_times + (source "constant-for-times.sv" #"module Child(output bit[1:0]q);initial begin #1;for(int i=0;i<1;i++)q[0]=1;end initial begin #2;q[1]=1;end endmodule module Top(output bit[7:0]seen);wire[1:0]q;Child u(.q(q));initial forever begin @(q[0]^q[1]);seen=seen+1;end endmodule"#) + (top Top)(run_until 1)(assert_eq seen 1)(run_until 2)(assert_eq seen 2)) + +(case untimed_tasks_preserve_distinct_activation_times + (source "untimed_tasks_preserve_distinct_activation_times.sv" #"module Child(output bit[1:0]q);task automatic noop();endtask initial begin #1;noop();q[0]=1;end initial begin #2;noop();q[1]=1;end endmodule module Top(output bit[7:0]seen);wire[1:0]q;Child u(.q(q));initial forever begin @(q[0]^q[1]);seen=seen+1;end endmodule"#) + (top Top)(run_until 1)(assert_eq seen 1)(run_until 2)(assert_eq seen 2)) + +(case untimed_task_copyback_preserves_distinct_activation_times + (source "untimed_task_copyback_preserves_distinct_activation_times.sv" #"module Child(output bit[1:0]q);task automatic drive(output bit x);x=1;endtask initial begin #1;drive(q[0]);end initial begin #2;drive(q[1]);end endmodule module Top(output bit[7:0]seen);wire[1:0]q;Child u(.q(q));initial forever begin @(q[0]^q[1]);seen=seen+1;end endmodule"#) + (top Top)(run_until 1)(assert_eq seen 1)(run_until 2)(assert_eq seen 2)) + +(case staged_always_comb_side_effects_wait_for_setup + (source "staged-comb-effects.sv" #"module Top(input bit go,output bit seen);always_comb begin seen=go;if(!go)begin $display("early");$fatal(1,"early");end end initial begin #1;$finish;end endmodule"#) + (top Top)(set go 1)(run_to_finish)(assert_eq seen 1)(expect_output "")) + +(case statically_satisfied_waits_preserve_distinct_activation_times + (source "true-wait.sv" #"module Child(output bit[1:0]q);initial begin #1;wait(1);q[0]=1;end initial begin #2;q[1]=1;end endmodule module Top(output bit[7:0]seen);wire[1:0]q;Child u(.q(q));initial forever begin @(q[0]^q[1]);seen=seen+1;end endmodule"#) + (top Top)(run_until 1)(assert_eq seen 1)(run_until 2)(assert_eq seen 2)) + +(case nba_woken_waiters_sample_before_continuations + (source "nba-waiter-sampling.sv" #"module Child(input bit clk,output bit go);always_ff @(posedge clk)go<=1;endmodule module Top(output bit a,b);bit clk;bit enable=1;wire go;Child child(.clk(clk),.go(go));initial begin #1;clk=1;end initial begin @(posedge(go&enable));a=1;enable=0;end initial begin @(posedge(go&enable));b=1;end endmodule"#) + (top Top)(run_until 1)(assert_eq a 1)(assert_eq b 1)) + +(case negative_repeat_counts_do_not_run_the_body + (source "negative_repeat_counts.sv" #" + module Top(input integer n, output bit [7:0] dynamic_count, literal_count, + zero_count, positive_count); + initial begin + #1; + repeat(n) begin #1; dynamic_count++; end + repeat(-1) begin #1; literal_count++; end + repeat(0) begin #1; zero_count++; end + repeat(2) begin #1; positive_count++; end + end + endmodule + "#) + (top Top) + (set n 0xfffffffe) + (run_until 4) + (assert_eq dynamic_count 0) + (assert_eq literal_count 0) + (assert_eq zero_count 0) + (assert_eq positive_count 2)) + +(case staged_wildcard_side_effects_wait_for_setup + (source "staged-wildcard-effects.sv" #" + module Top(input bit[1:0]go,output bit[1:0]a,b); + wire ready=1'b1; + always @* begin + a=ready?go:0; + if(ready&&!go)begin $display("early star");$fatal(1,"early star");end + end + always @(*) begin + b=ready?go:0; + if(ready&&!go)begin $display("early parens");$fatal(1,"early parens");end + end + initial begin #2;$finish;end + endmodule + "#) + (top Top)(set go 1)(run_until 0)(assert_eq a 1)(assert_eq b 1) + (set go 2)(run_until 1)(assert_eq a 2)(assert_eq b 2) + (run_to_finish)(expect_output "")) + +(case staged_continuous_side_effects_wait_for_setup + (source "staged-continuous-effects.sv" #" + module Top(input bit[7:0]go,output wire[7:0]a,b); + function automatic bit[7:0]checked(input bit[7:0]value); + if(value==0)begin $display("early continuous");$fatal(1,"early continuous");end + return value; + endfunction + assign a=checked(go); + wire[7:0]other=checked(go); + assign b=other; + initial begin #2;$finish;end + endmodule + "#) + (top Top)(set go 1)(run_until 0)(assert_eq a 1)(assert_eq b 1) + (set go 2)(run_until 1)(assert_eq a 2)(assert_eq b 2) + (run_to_finish)(expect_output "")) + +(case continuous_call_drivers_preserve_assignment_context + (source "continuous-driver-context.sv" #" + module Top(input bit[7:0]go,output wire[7:0]a,b,c,output wire ready); + function automatic bit[1:0]checked(input bit[7:0]value); + if(value==0)$fatal(1,"early driver"); + return value; + endfunction + if(1) assign a=checked(go)+2'd3,c=checked({go[7:4],go[3:0]}); + wire[7:0]x=checked(go),y=checked(go); + assign b=x+y; + wire constant_ready=1; + assign ready=constant_ready; + initial begin #2;$finish;end + endmodule + "#) + (top Top)(set go 1)(run_until 0)(assert_eq a 4)(assert_eq b 2)(assert_eq c 1)(assert_eq ready 1) + (set go 2)(run_until 1)(assert_eq a 5)(assert_eq b 4)(assert_eq c 2) + (run_to_finish)(expect_output "")) + +(case blocking_ff_woken_waiters_sample_before_continuations + (source "blocking-ff-waiter-sampling.sv" #"module Child(input bit clk,output bit go);always_ff @(posedge clk)go=1;endmodule module Top(output bit a,b);bit clk;bit enable=1;wire go;Child child(.clk(clk),.go(go));initial begin #1;clk=1;end initial begin @(posedge(go&enable));a=1;enable=0;end initial begin @(posedge(go&enable));b=1;end endmodule"#) + (top Top)(run_until 1)(assert_eq a 1)(assert_eq b 1)) + +(case direct_blocking_ff_woken_waiters_sample_before_continuations + (source "direct-blocking-ff-waiter-sampling.sv" #"module Top(output bit a,b);bit clk;bit enable=1;bit go;always_ff @(posedge clk)go=1;initial begin #1;clk=1;end initial begin @(posedge(go&enable));a=1;enable=0;end initial begin @(posedge(go&enable));b=1;end endmodule"#) + (top Top)(run_until 1)(assert_eq a 1)(assert_eq b 1)) + +(case variable_initializers_observe_staged_inputs_before_initial_blocks + (source "staged-variable-initializers.sv" #"module Top(input bit a,output wire seen);bit saved=a;assign seen=saved;initial begin #2;$finish;end endmodule"#) + (top Top)(set a 1)(run_until 0)(assert_eq seen 1)(run_to_finish)) + +(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 variable_initializer_dependencies_and_automatic_locals_preserve_order + (source "staged-variable-initializers.sv" #" + module Top(input bit[7:0]a,output wire[7:0]saved_value,next_value,copied_value,generated_value,output bit[7:0]initial_value,later_value); + bit[7:0] saved=a,next_saved=saved+1; + bit[7:0] copied=saved; + if(1)begin:g bit[7:0] generated=a;assign generated_value=generated;end + assign saved_value=saved,next_value=next_saved,copied_value=copied; + function automatic bit[7:0] echo(input bit[7:0] value); + bit[7:0] local_copy=value; + return local_copy; + endfunction + initial begin initial_value=saved;#1;later_value=echo(a);#1;$finish;end + endmodule + "#) + (top Top)(set a 1)(run_until 0)(assert_eq saved_value 1)(assert_eq next_value 2)(assert_eq copied_value 1)(assert_eq generated_value 1)(assert_eq initial_value 1) + (set a 2)(run_until 1)(assert_eq saved_value 1)(assert_eq next_value 2)(assert_eq copied_value 1)(assert_eq generated_value 1)(assert_eq later_value 2) + (run_to_finish)(expect_output "")) + +(case variable_initializer_finish_prevents_procedural_start + (source "initializer-finish.sv" #" + module Top(output wire seen); + function automatic bit stop_now();$finish;return 1;endfunction + function automatic bit finish_now();return stop_now();endfunction + bit saved=finish_now(); + assign seen=saved; + initial $fatal(1,"procedure ran after initializer finish"); + endmodule + "#) + (top Top)(run_to_finish)(assert_eq seen 0)(expect_output "")) + + +(case escaped_continuous_destinations_preserve_identifier_terminators + (source "escaped-continuous-function.sv" #" + module Top(input bit go,output wire y,z); + wire \out ; + wire \other = checked(go); + function automatic bit checked(input bit value); + if(!value)$fatal(1,"escaped function ran before setup"); + return value; + endfunction + assign \out =checked(go); + assign y=\out ; + assign z=\other ; + initial begin #2;$finish;end + endmodule + "#) + (top Top)(set go 1)(run_until 0)(assert_eq y 1)(assert_eq z 1) + (run_to_finish)(expect_output "")) + +(case repeated_active_edges_share_one_nba_batch + (source "repeated_active_edges_share_one_nba_batch.sv" #"module Top(output bit[7:0]q);bit d;initial begin #1;d=1;d=0;d=1;end always @(posedge d)q<=q+1;endmodule"#) + (top Top)(run_until 1)(assert_eq q 1)) + +(case false_wait_preserves_separate_hierarchical_write_times + (source "false_wait_preserves_separate_hierarchical_write_times.sv" #"module Child(output bit[1:0]v);initial begin #1;v[0]=1;wait(0);end initial begin #2;v[1]=1;end endmodule module Top(output bit[7:0]q);wire[1:0]v;Child c(.v(v));initial forever begin @(v[0]^v[1]);q++;end endmodule"#) + (top Top)(run_until 1)(assert_eq q 1)(run_until 2)(assert_eq q 2)) + +(case always_timed_task_without_inline_timing_executes + (source "always_timed_task_without_inline_timing_executes.sv" #"module Top(output bit q);task tick;#1;q=~q;endtask always tick();endmodule"#) + (top Top)(run_until 1)(assert_eq q 1)(run_until 2)(assert_eq q 0)(run_until 3)(assert_eq q 1)) + + +(case initializer_function_effects_are_scoped_to_each_module + (source "initializer-module-effects.sv" #" + module Effectful(output bit value); + function automatic bit high_value();$display("effectful");return 0;endfunction + initial begin #1;value=high_value();end + endmodule + module Pure(output bit seen); + function automatic bit high_value();return 1;endfunction + bit clk=high_value(); + always_ff @(posedge clk)seen=1; + endmodule + module Top(output wire seen,output wire value); + Effectful effectful(.value(value));Pure pure_unit(.seen(seen)); + initial begin #2;$finish;end + endmodule + "#) + (top Top)(run_until 0)(assert_eq seen 0)(run_to_finish)(expect_output "effectful\n")) + +(case initializer_default_argument_effects_run_during_initialization + (source "initializer-default-effects.sv" #" + module Top(output wire seen); + function automatic bit stop_now();$finish;return 1;endfunction + function automatic bit wrapper(input bit x=stop_now());return x;endfunction + bit saved=wrapper(); + assign seen=saved; + initial $fatal(1,"initial ran after default argument finish"); + endmodule + "#) + (top Top)(run_to_finish)(assert_eq seen 0)(expect_output "")) + +(case continuous_zero_argument_function_tracks_global_reads + (source "continuous-function-dependencies.sv" #" + module Top(input bit[7:0]go,output wire[7:0]y,z); + function automatic bit[7:0]checked();if(go==0)$fatal(1,"early zero-argument call");return go;endfunction + assign y=checked(); + wire[7:0]other=checked();assign z=other; + initial begin #2;$finish;end + endmodule + "#) + (top Top)(set go 1)(run_until 0)(assert_eq y 1)(assert_eq z 1) + (set go 2)(run_until 1)(assert_eq y 2)(assert_eq z 2)(run_to_finish)(expect_output "")) + + +(case initializer_explicit_arguments_skip_effectful_defaults + (source "initializer-explicit-default.sv" #" + module Top(output bit seen); + function automatic bit side_effect();$fatal(1,"unused default ran");return 0;endfunction + function automatic bit wrapper(input bit value=side_effect());return value;endfunction + bit clk=wrapper(1); + always_ff @(posedge clk)seen=1; + initial begin #2;$finish;end + endmodule + "#) + (top Top)(run_until 0)(assert_eq seen 0)(run_to_finish)(expect_output "")) + + +(case constant_continuous_function_edges_match_staged_startup + (source "constant-continuous-clocks.sv" #" + module Top(output bit net_seen,assign_seen); + function automatic bit high_value();return 1;endfunction + wire net_clock=high_value(); + wire assign_clock;assign assign_clock=high_value(); + always_ff @(posedge net_clock)net_seen=1; + always_ff @(posedge assign_clock)assign_seen=1; + initial begin #2;$finish;end + endmodule + "#) + (top Top)(run_until 0)(assert_eq net_seen 1)(assert_eq assign_seen 1)(run_to_finish)) + +(case escaped_initializer_function_effects_finish_during_initialization + (source "escaped-initializer-effect.sv" #" + module Top(output wire seen); + function automatic bit \stop_now ();$finish;return 1;endfunction + bit saved=\stop_now (); + assign seen=saved; + initial $fatal(1,"initial ran after escaped initializer finish"); + endmodule + "#) + (top Top)(run_to_finish)(assert_eq seen 0)(expect_output "")) + +(case constant_comb_if_discards_unreachable_pulse_branch + (source "constant-comb-if.sv" #"module Top(input bit go,output bit[7:0]q);bit v; + always_comb if(1'b1)v=go;else begin v=0;v=1;end + initial forever begin @(v);q++;end endmodule"#) + (top Top)(run_until 0)(assert_eq q 0)(set go 1)(run_until 1)(assert_eq q 1) + (set go 0)(run_until 2)(assert_eq q 2)) + +(case constant_child_ff_case_discards_unreachable_pulse_arm + (source "constant-child-ff-case.sv" #"module Child(input bit clk,output bit v); + always @(posedge clk) case(2'd1) 2'd1:v<=~v;default:begin v<=0;v<=1;end endcase endmodule + module Top(input bit clk,output bit[7:0]q);wire v;Child c(clk,v); + initial forever begin @(v);q++;end endmodule"#) + (top Top)(run_until 0)(assert_eq q 0)(set clk 1)(run_until 1)(assert_eq q 1) + (set clk 0)(run_until 2)(set clk 1)(run_until 3)(assert_eq q 2)) + +(case typed_continuous_enum_drivers_preserve_assignment_types + (source "typed-continuous-enum.sv" #"module Top(input bit[1:0]go,output wire a,b); + typedef enum logic {LOW,HIGH} level_t; + function automatic level_t checked(input bit[1:0]value); + if(!value)$fatal(1,"early enum driver");if(value[0])return HIGH;return LOW;endfunction + wire level_t first=checked(go); + wire level_t second;assign second=checked(go); + assign a=first;assign b=second;initial #2 $finish;endmodule"#) + (top Top)(set go 1)(run_until 0)(assert_eq a 1)(assert_eq b 1) + (set go 2)(run_until 1)(assert_eq a 0)(assert_eq b 0)) + +(case constant_child_loop_exit_keeps_one_write + (source "constant_child_loop_exit_keeps_one_write.sv" #"module Child(input bit clk,output bit v); + always @(posedge clk)begin repeat(2)begin v=~v;if(1'b1)break;end end endmodule + module Top(input bit clk,output bit[7:0]q);wire v;Child c(clk,v); + initial forever begin @(v);q++;end endmodule"#) + (top Top)(run_until 0)(assert_eq q 0)(set clk 1)(run_until 1)(assert_eq q 1) + (set clk 0)(run_until 2)(set clk 1)(run_until 3)(assert_eq q 2)) + +(case constant_child_case_exit_keeps_one_write + (source "constant_child_case_exit_keeps_one_write.sv" #"module Child(input bit clk,output bit v); + always @(posedge clk)begin repeat(2)begin v=~v;case(1)1:break;default:;endcase end end endmodule + module Top(input bit clk,output bit[7:0]q);wire v;Child c(clk,v); + initial forever begin @(v);q++;end endmodule"#) + (top Top)(run_until 0)(assert_eq q 0)(set clk 1)(run_until 1)(assert_eq q 1) + (set clk 0)(run_until 2)(set clk 1)(run_until 3)(assert_eq q 2)) + +(case four_state_child_if_keeps_one_write + (source "four_state_child_if_keeps_one_write.sv" #"module Child(input bit clk,output bit v); + always @(posedge clk)begin if(4'bx001)v=~v;else begin v=0;v=1;end end endmodule + module Top(input bit clk,output bit[7:0]q);wire v;Child c(clk,v); + initial forever begin @(v);q++;end endmodule"#) + (top Top)(run_until 0)(assert_eq q 0)(set clk 1)(run_until 1)(assert_eq q 1) + (set clk 0)(run_until 2)(set clk 1)(run_until 3)(assert_eq q 2)) + +(case selected_child_dependency_ignores_unreachable_reads(source "selected_child_dependency_ignores_unreachable_reads.sv" #"module Child(input bit a,output bit q);always_comb case(1)1:q=0;default:q=a;endcase endmodule +module Top(output bit[7:0]seen);bit a;wire q;Child c(a,q);initial begin #1;a=1;a=0;end initial forever begin @(q);seen++;end endmodule"#)(top Top)(run_until 0)(assert_eq seen 0)(run_until 1)(assert_eq seen 0)) + +(case selected_child_loop_exit_ignores_unreachable_suffix(source "selected_child_loop_exit_ignores_unreachable_suffix.sv" #"module Child(input bit clk,output bit q);always @(posedge clk)repeat(2)begin q=~q;if(1)break;q=~q;end endmodule +module Top(input bit clk,output bit[7:0]seen);wire q;Child c(clk,q);initial forever begin @(q);seen++;end endmodule"#)(top Top)(run_until 0)(assert_eq seen 0)(set clk 1)(run_until 1)(assert_eq seen 1)) + +(case finite_process_loop_preserves_continuation_values(source "finite_process_loop_preserves_continuation_values.sv" #"module Top(output bit[7:0]q,output bit done);initial begin repeat(4)q++;if(q!=4)$fatal(1,"finite loop state lost");#1;done=1;end endmodule"#)(top Top)(run_until 0)(assert_eq q 4)(assert_eq done 0)(run_until 1)(assert_eq done 1)) + +(case zero_trip_child_dependencies_ignore_body_and_step + (source "zero-trip-child.sv" #" + module Child(input bit a,output bit q); + function bit read_a();return a;endfunction + always_comb begin q=0;repeat(0)q=a;while(1'b0)q=read_a();for(int i=0;1'b0;i=read_a())q=a;end + endmodule + module Top(output bit[7:0]seen);bit a;wire q;Child c(a,q); + initial begin #1;a=1;a=0;end initial forever begin @(q);seen++;end endmodule + "#)(top Top)(run_until 0)(assert_eq seen 0)(run_until 2)(assert_eq seen 0)) + +(case cross_file_package_initializers_keep_static_clock_baseline + (source "base.sv" #"package Base;function automatic bit one();return 1;endfunction endpackage"#) + (source "values.sv" #"package P;function automatic bit high_value();return Base::one();endfunction endpackage"#) + (source "clocks.sv" #" + module Qualified(output bit[7:0]q);bit clk=P::high_value();always @(posedge clk)q++;endmodule + module Imported(output bit[7:0]q);import P::*;bit clk=high_value();always @(posedge clk)q++;endmodule + module Top(output wire[7:0]qualified,imported);Qualified a(qualified);Imported b(imported);initial #2 $finish;endmodule + "#)(top Top)(run_until 0)(assert_eq qualified 0)(assert_eq imported 0)(run_until 1)(assert_eq qualified 0)(assert_eq imported 0)(run_to_finish)) diff --git a/crates/celox-test-suite/src/sv/verification.rs b/crates/celox-test-suite/src/sv/verification.rs index bae5ce0ad28..6f197332d0e 100644 --- a/crates/celox-test-suite/src/sv/verification.rs +++ b/crates/celox-test-suite/src/sv/verification.rs @@ -156,7 +156,23 @@ impl Frontend for SvFrontend { } fn prepare(&self, design: &Design) -> Result { - let info = design_info(design); + self.prepare_with_defines(design, &[]) + } + + fn prepare_with_defines(&self, design: &Design, defines: &[&str]) -> Result { + let mut analyzed = design.clone(); + if design.timed { + let sources = design + .sources + .iter() + .map(|s| (s.text.as_str(), s.path.as_path())) + .collect::>(); + let expanded = crate::frontend::expanded_timed_sources(&sources, defines)?; + for (source, text) in analyzed.sources.iter_mut().zip(expanded) { + source.text = text; + } + } + let info = design_info(&analyzed); Ok(PreparedDesign { sources: design .sources diff --git a/crates/celox-test-suite/src/verification.rs b/crates/celox-test-suite/src/verification.rs index 18459ff42aa..1fbef4dbc30 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 @@ -606,7 +616,24 @@ 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) { + // The simulators' `$finish` notices name the staged source files. + let sources: Vec = std::fs::read_dir(directory) + .map(|entries| { + entries + .filter_map(|entry| entry.ok()) + .map(|entry| { + entry + .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(); + match crate::script::sv::check_output(&log, &sources) { Ok(()) => ("passed", "execute", String::new()), Err(detail) => ("mismatch", "execute", detail), } diff --git a/crates/celox-test-suite/src/verilator.rs b/crates/celox-test-suite/src/verilator.rs index 63023805f19..cf8daf421a5 100644 --- a/crates/celox-test-suite/src/verilator.rs +++ b/crates/celox-test-suite/src/verilator.rs @@ -41,7 +41,7 @@ impl Verilator { top, testbench, edges, - } = stage(frontend, design, directory, script)?; + } = stage(frontend, design, directory, script, &[])?; write_if_changed( &directory.join("vpi_bits.hpp"), include_bytes!("vpi_bits.hpp"), diff --git a/crates/celox-test-suite/tests/timed_protocol.rs b/crates/celox-test-suite/tests/timed_protocol.rs new file mode 100644 index 00000000000..544a20b311d --- /dev/null +++ b/crates/celox-test-suite/tests/timed_protocol.rs @@ -0,0 +1,383 @@ +#![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)", + ), + ( + "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(); + assert!(icarus.run_testbench().is_err(), "Icarus accepted {name}"); + let mut verilator = celox_test_suite::verilator::Verilator::build_script( + &frontend, + case, + &root.join(name).join("verilator"), + ) + .unwrap(); + let result = verilator.run_testbench(); + let log = std::fs::read(root.join(name).join("verilator/protocol.log")).unwrap(); + assert!( + result.is_err() || celox_test_suite::script::sv::check_output(&log, &[]).is_err(), + "Verilator accepted {name}" + ); + } + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +#[ignore = "requires Verilator and a C++ compiler; Icarus rejects unique-if syntax"] +fn qualified_ff_if_actions_are_not_truncated_during_staging() { + let text = r##"(group qualified (category sequential)) + (case startup (source "qualified.sv" #"module Top(input bit clk, en, output bit q, y); + always_ff @(posedge clk) unique if(en) q<=1; else q<=0; + initial y=q; + endmodule"#) (top Top) (set en 1) (set clk 1) (run_until 0) (assert_eq y 0) (assert_eq q 1))"##; + let case = load_group("qualified.vtest", text, no_std_library)[0]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../target/qualified-ff-protocol") + .join(std::process::id().to_string()); + let frontend = celox_test_suite::sv::verification::SvFrontend; + let mut backend = + celox_test_suite::verilator::Verilator::build_script(&frontend, case, &root).unwrap(); + backend.run_testbench().unwrap(); + let log = std::fs::read(root.join("protocol.log")).unwrap(); + celox_test_suite::script::sv::check_output(&log, &[]).unwrap(); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +#[ignore = "requires Icarus, Verilator and a C++ compiler"] +fn bare_continuous_function_calls_observe_staged_inputs() { + // Exercise the adapter directly: Celox currently rejects bare function + // values in continuous assignments, while the adapter normalizes them + // to explicit calls for the external simulators. + let text = r##"(group protocol (category sequential)) + (case bare (source "bare.sv" #" + package bare_shadow_pkg; function automatic bit constant_ready; return 0; endfunction endpackage + module Top(input bit[7:0] go,output wire[7:0] y,z,output wire ready); + import bare_shadow_pkg::*; + function automatic bit[7:0] checked; + if(!go)$fatal(1,"bare function ran before setup"); + return go; + endfunction + assign y=checked; + wire[7:0] other=checked; + assign z=other; + wire constant_ready=1; + assign ready=constant_ready; + initial begin #2;$finish;end + endmodule + "#) (top Top)(set go 1)(run_until 0)(assert_eq y 1)(assert_eq z 1)(assert_eq ready 1) + (set go 2)(run_until 1)(assert_eq y 2)(assert_eq z 2))"##; + let case = load_group("bare.vtest", text, no_std_library)[0]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../target/bare-continuous-protocol") + .join(std::process::id().to_string()); + let frontend = celox_test_suite::sv::verification::SvFrontend; + let mut icarus = + celox_test_suite::icarus::Icarus::build_script(&frontend, case, &root.join("icarus")) + .unwrap(); + icarus.run_testbench().unwrap(); + let mut verilator = celox_test_suite::verilator::Verilator::build_script( + &frontend, + case, + &root.join("verilator"), + ) + .unwrap(); + verilator.run_testbench().unwrap(); + let log = std::fs::read(root.join("verilator/protocol.log")).unwrap(); + celox_test_suite::script::sv::check_output(&log, &[]).unwrap(); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +#[ignore = "requires Icarus, Verilator and a C++ compiler"] +fn callable_instance_connections_wait_for_staged_inputs() { + let text = r##"(group protocol (category sequential)) + +(case callable_instance_inputs_wait_for_staged_values + (source "instance-connection-effects.sv" #" + module Child #(parameter W=8)(input bit[W-1:0]value,output wire[W-1:0]seen);assign seen=value;endmodule + module Top(input bit[7:0]go,output wire[7:0]a,b,output wire[15:0]broadcast,distributed,ordered_array,signed_array); + function automatic bit[1:0]checked(input bit[7:0]value);if(!value)$fatal(1,"early instance connection");return value;endfunction + Child #(.W(8)) named(.value(checked(go)+2'd3),.seen(a)); + Child #(8) ordered(checked(go)+2'd3,b); + function automatic bit[7:0]broadcast_value(input bit[7:0]value);if(!value)$fatal(1,"early array broadcast");return value+8'd3;endfunction + function automatic bit[15:0]distributed_value(input bit[7:0]value);if(!value)$fatal(1,"early array distribution");return {value+8'd1,value};endfunction + function automatic bit signed[7:0]negative_value(input bit[7:0]value);if(!value)$fatal(1,"early signed broadcast");return -value;endfunction + Child #(8) bn[1:0](.value(broadcast_value(go)),.seen(broadcast)); + Child #(8) dn[0:1](.value(distributed_value(go)),.seen(distributed)); + Child #(8) dp[1:0](distributed_value(go),ordered_array); + Child #(8) sn[1:0](negative_value(go),signed_array); + initial begin #2;$finish;end + endmodule + "#) + (top Top)(set go 1)(run_until 0)(assert_eq a 4)(assert_eq b 4)(assert_eq broadcast 1028)(assert_eq distributed 513)(assert_eq ordered_array 513)(assert_eq signed_array 65535) + (set go 2)(run_until 1)(assert_eq a 5)(assert_eq b 5)(assert_eq broadcast 1285)(assert_eq distributed 770)(assert_eq ordered_array 770)(assert_eq signed_array 65278)) + +"##; + let case = load_group("connections.vtest", text, no_std_library)[0]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../target/callable-connection-protocol") + .join(std::process::id().to_string()); + let frontend = celox_test_suite::sv::verification::SvFrontend; + let mut icarus = + celox_test_suite::icarus::Icarus::build_script(&frontend, case, &root.join("icarus")) + .unwrap(); + let icarus_result = icarus.run_testbench(); + let mut verilator = celox_test_suite::verilator::Verilator::build_script( + &frontend, + case, + &root.join("verilator"), + ) + .unwrap(); + let verilator_result = verilator.run_testbench(); + assert!( + icarus_result.is_ok() && verilator_result.is_ok(), + "Icarus: {icarus_result:?}; Verilator: {verilator_result:?}" + ); + let log = std::fs::read(root.join("verilator/protocol.log")).unwrap(); + celox_test_suite::script::sv::check_output(&log, &[]).unwrap(); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +#[ignore = "requires Icarus, Verilator and a C++ compiler"] +fn typed_continuous_drivers_preserve_enum_assignment_type() { + let text = r##"(group protocol (category sequential)) + (case typed_driver (source "typed-driver.sv" #" + module Top(input bit go,output wire a,b); + typedef enum logic {LOW,HIGH} level_t; + function automatic level_t checked(input bit value); if(!value)$fatal(1,"early enum driver");return HIGH;endfunction + wire level_t first=checked(go); + wire level_t second;assign second=checked(go); + assign a=first;assign b=second;initial #2 $finish; + endmodule"#)(top Top)(set go 1)(run_until 0)(assert_eq a 1)(assert_eq b 1))"##; + let case = load_group("typed.vtest", text, no_std_library)[0]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../target/typed-driver-protocol") + .join(std::process::id().to_string()); + let frontend = celox_test_suite::sv::verification::SvFrontend; + let mut icarus = + celox_test_suite::icarus::Icarus::build_script(&frontend, case, &root.join("icarus")) + .unwrap(); + let mut verilator = celox_test_suite::verilator::Verilator::build_script( + &frontend, + case, + &root.join("verilator"), + ) + .unwrap(); + assert!(icarus.run_testbench().is_ok()); + assert!(verilator.run_testbench().is_ok()); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn dynamic_const_initializers_are_rejected_before_tool_invocation() { + let text = r##"(group protocol (category sequential)) + (case dynamic_const (source "const.sv" #"module Top(input bit a,output wire seen);const bit saved=a;assign seen=saved;initial #2 $finish;endmodule"#) + (top Top)(set a 1)(run_until 0)(assert_eq seen 1))"##; + let case = load_group("const.vtest", text, no_std_library)[0]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../target/const-initializer-protocol") + .join(std::process::id().to_string()); + let frontend = celox_test_suite::sv::verification::SvFrontend; + let icarus = + celox_test_suite::icarus::Icarus::build_script(&frontend, case, &root.join("icarus")) + .err() + .expect("dynamic const reached Icarus compilation"); + assert!( + icarus.is::(), + "{icarus}" + ); + let verilator = celox_test_suite::verilator::Verilator::build_script( + &frontend, + case, + &root.join("verilator"), + ) + .err() + .expect("dynamic const reached Verilator compilation"); + assert!( + verilator.is::(), + "{verilator}" + ); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +#[ignore = "requires Verilator and a C++ compiler; Icarus lacks unpacked function returns"] +fn unpacked_continuous_drivers_preserve_destination_shape() { + let text = r##"(group protocol (category sequential)) + (case unpacked_driver (source "unpacked-driver.sv" #" + module Child(input bit[7:0]go,output wire[7:0]a,b); + typedef logic[7:0] pair_t[0:1]; + function automatic pair_t checked(input bit[7:0]value); if(!value)$fatal(1,"early array driver");return '{value,value+8'd1};endfunction + wire logic[7:0] first[0:1]=checked(go); + wire pair_t second;assign second=checked(go); + assign a=first[0]+first[1];assign b=second[0]+second[1];initial #2 $finish; + endmodule + module Top(input bit[7:0]go,output wire[7:0]a,b);Child c(go,a,b);endmodule"#)(top Top)(set go 1)(run_until 0)(assert_eq a 3)(assert_eq b 3) + (set go 2)(run_until 1)(assert_eq a 5)(assert_eq b 5))"##; + let case = load_group("unpacked.vtest", text, no_std_library)[0]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../target/unpacked-driver-protocol") + .join(std::process::id().to_string()); + let frontend = celox_test_suite::sv::verification::SvFrontend; + let mut verilator = + celox_test_suite::verilator::Verilator::build_script(&frontend, case, &root).unwrap(); + assert!(verilator.run_testbench().is_ok()); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +#[ignore = "requires Icarus, Verilator and a C++ compiler"] +fn timed_sources_share_ordered_macro_definitions() { + let text = r##"(group protocol (category sequential)) + (case ordered_macros + (source "defines.sv" #"`define ENABLE_WRITE +`define WIDTH 4 +`define STORE(v) q=(v) +module Definitions;endmodule"#) + (source "top.sv" #"module Top(input bit[`WIDTH-1:0]go,output bit[`WIDTH-1:0]q); +initial begin #1; +`ifdef ENABLE_WRITE +`STORE(go); +`else +q=0; +`endif +end endmodule"#) + (source "tail.sv" #"`undef ENABLE_WRITE +module Tail(output wire value); +`ifdef ENABLE_WRITE +assign value=0; +`else +assign value=1; +`endif +endmodule"#) + (top Top)(set go 3)(run_until 1)(assert_eq q 3))"##; + let case = load_group("macros.vtest", text, no_std_library)[0]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../target/ordered-macro-protocol") + .join(std::process::id().to_string()); + let frontend = celox_test_suite::sv::verification::SvFrontend; + let mut icarus = + celox_test_suite::icarus::Icarus::build_script(&frontend, case, &root.join("icarus")) + .unwrap(); + let mut verilator = celox_test_suite::verilator::Verilator::build_script( + &frontend, + case, + &root.join("verilator"), + ) + .unwrap(); + assert!(icarus.run_testbench().is_ok()); + assert!(verilator.run_testbench().is_ok()); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +#[ignore = "requires Icarus, Verilator and a C++ compiler"] +fn callable_input_connections_preserve_package_enum_type() { + let text = r##"(group protocol(category sequential)) + (case typed_port(source "typed_port.sv" #" + package P;typedef enum logic[1:0]{LOW=0,HIGH=2} level_t;endpackage + module Child(input P::level_t mode,output wire q);assign q=(mode==P::HIGH);endmodule + module Top(input bit go,output wire a,b); + function automatic P::level_t checked();if(!go)$fatal(1,"called before setup");return P::HIGH;endfunction + Child first(.mode(checked()),.q(a));Child second(checked(),b); + initial #2 $finish;endmodule"#)(top Top)(set go 1)(run_until 0)(assert_eq a 1)(assert_eq b 1))"##; + let case = load_group("typed_port.vtest", text, no_std_library)[0]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../target/typed-port-protocol") + .join(std::process::id().to_string()); + let frontend = celox_test_suite::sv::verification::SvFrontend; + let mut icarus = + celox_test_suite::icarus::Icarus::build_script(&frontend, case, &root.join("icarus")) + .unwrap(); + icarus.run_testbench().unwrap(); + let mut verilator = celox_test_suite::verilator::Verilator::build_script( + &frontend, + case, + &root.join("verilator"), + ) + .unwrap(); + verilator.run_testbench().unwrap(); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +#[ignore = "requires Verilator and a C++ compiler; Icarus rejects unpacked function return values"] +fn callable_input_connections_preserve_unpacked_typedef_shape() { + let text = r##"(group protocol(category sequential)) + (case typed_array_port(source "typed_array_port.sv" #" + package P;typedef logic[3:0] pair_t[2];endpackage + module Child(input P::pair_t mode,output wire[7:0]q);assign q={mode[0],mode[1]};endmodule + module Top(input bit[3:0]go,output wire[7:0]q); + function automatic P::pair_t checked();P::pair_t result;if(!go)$fatal(1,"called before setup");result[0]=go;result[1]=go+1;return result;endfunction + Child first(.mode(checked()),.q(q));initial #2 $finish;endmodule"#) + (top Top)(set go 2)(run_until 0)(assert_eq q 35)(set go 3)(run_until 1)(assert_eq q 52))"##; + let case = load_group("typed_array_port.vtest", text, no_std_library)[0]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../target/typed-array-port-protocol") + .join(std::process::id().to_string()); + let frontend = celox_test_suite::sv::verification::SvFrontend; + let mut verilator = + celox_test_suite::verilator::Verilator::build_script(&frontend, case, &root).unwrap(); + verilator.run_testbench().unwrap(); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +#[ignore = "requires Icarus, Verilator and a C++ compiler"] +fn cross_file_constant_initializers_do_not_create_startup_edges() { + let text = r##"(group protocol(category sequential)) + (case cross_file_initializer + (source "values.sv" #"package P;function automatic bit high_value();return 1;endfunction endpackage"#) + (source "top.sv" #"module Top(output bit[7:0]q);bit clk=P::high_value();always @(posedge clk)q++;initial #2 $finish;endmodule"#) + (top Top)(run_until 0)(assert_eq q 0)(run_until 1)(assert_eq q 0))"##; + let case = load_group("cross_file_initializer.vtest", text, no_std_library)[0]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../target/cross-file-initializer-protocol") + .join(std::process::id().to_string()); + let frontend = celox_test_suite::sv::verification::SvFrontend; + let mut icarus = + celox_test_suite::icarus::Icarus::build_script(&frontend, case, &root.join("icarus")) + .unwrap(); + icarus.run_testbench().unwrap(); + let mut verilator = celox_test_suite::verilator::Verilator::build_script( + &frontend, + case, + &root.join("verilator"), + ) + .unwrap(); + verilator.run_testbench().unwrap(); + std::fs::remove_dir_all(root).unwrap(); +} diff --git a/crates/celox-test-suite/verification/repros/sv_timed_unit_icarus.json b/crates/celox-test-suite/verification/repros/sv_timed_unit_icarus.json new file mode 100644 index 00000000000..48c33533071 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_timed_unit_icarus.json @@ -0,0 +1,33 @@ +{ + "suite": "sv", + "suite_version": "0.10.1", + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "include_ignored": false, + "schema_version": 3, + "cases": [ + { + "category": "Sequential", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Malformed statement\n", + "expectation": "Simulation", + "name": "timing::qualified_unit_tasks_keep_setup_edges", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ], + "counts": { + "passed": 0, + "rejected": 0, + "unexpected_accept": 0, + "mismatch": 0, + "emission_error": 0, + "compile_error": 1, + "runtime_error": 0, + "unsupported": 0, + "ignored": 0 + }, + "note": "Focused pre-exclusion result for the new qualified compilation-unit task case. IEEE 1800-2023 3.12.1 permits $unit:: qualification. Celox and Verilator pass the unchanged case; Icarus 13.0 rejects the qualified call." +} diff --git a/crates/celox-test-suite/verification/sv/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..3f34d276c91 --- /dev/null +++ b/crates/celox-test-suite/verification/sv/icarus/timing.json @@ -0,0 +1,246 @@ +{ + "cases": [ + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::always_with_a_delay_generates_a_clock", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::any_change_waits_wake_on_every_value_change", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::delays_resume_initial_blocks_at_later_times", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::edge_waits_resume_before_the_registers_of_that_edge_update", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::edge_waits_see_the_signals_the_script_drives", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::finish_in_an_always_process_ends_the_simulation", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::four_state_edges_count_transitions_through_unknown", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Icarus 13.0 rejects interface port declarations (syntax error in port declarations), modport function imports (\"sorry: modport task/function ports are not yet supported\") and multidimensional interface instance arrays (\"sorry: Multi-dimensional arrays of instances are not yet supported\"). Verilator passes these cases.", + "expectation": "Simulation", + "known_issue": { + "id": "sv_icarus_interfaces", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 rejects interface port declarations (syntax error in port declarations), modport function imports (\"sorry: modport task/function ports are not yet supported\") and multidimensional interface instance arrays (\"sorry: Multi-dimensional arrays of instances are not yet supported\"). Verilator passes these cases.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "name": "timing::generic_interface_methods_keep_setup_edges", + "phase": "compile", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Icarus 13.0 rejects interface port declarations (syntax error in port declarations), modport function imports (\"sorry: modport task/function ports are not yet supported\") and multidimensional interface instance arrays (\"sorry: Multi-dimensional arrays of instances are not yet supported\"). Verilator passes these cases.", + "expectation": "Simulation", + "known_issue": { + "id": "sv_icarus_interfaces", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 rejects interface port declarations (syntax error in port declarations), modport function imports (\"sorry: modport task/function ports are not yet supported\") and multidimensional interface instance arrays (\"sorry: Multi-dimensional arrays of instances are not yet supported\"). Verilator passes these cases.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "name": "timing::inherited_interface_methods_keep_setup_edges", + "phase": "compile", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Icarus 13.0 rejects interface port declarations (syntax error in port declarations), modport function imports (\"sorry: modport task/function ports are not yet supported\") and multidimensional interface instance arrays (\"sorry: Multi-dimensional arrays of instances are not yet supported\"). Verilator passes these cases.", + "expectation": "Simulation", + "known_issue": { + "id": "sv_icarus_interfaces", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 rejects interface port declarations (syntax error in port declarations), modport function imports (\"sorry: modport task/function ports are not yet supported\") and multidimensional interface instance arrays (\"sorry: Multi-dimensional arrays of instances are not yet supported\"). Verilator passes these cases.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "name": "timing::interface_modport_methods_keep_setup_edges", + "phase": "compile", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::level_sensitive_always_runs_as_a_process", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::processes_wake_each_other_at_the_same_time", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Icarus 13.0 rejects $unit::tick(q) as a malformed statement. IEEE 1800-2023 3.12.1 permits scope-qualified compilation-unit identifiers. Celox and Verilator pass the unchanged timed task case.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_timed_unit_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_qualified_unit_task", + "observed_version": "Icarus 13.0 / Verilator 5.052", + "phase": "compile", + "reason": "Icarus 13.0 rejects $unit::tick(q) as a malformed statement. IEEE 1800-2023 3.12.1 permits scope-qualified compilation-unit identifiers. Celox and Verilator pass the unchanged timed task case.", + "upstream": [] + }, + "name": "timing::qualified_unit_tasks_keep_setup_edges", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::tasks_with_timing_controls_run_in_processes", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::unknown_delays_and_conditions_count_as_zero_and_false", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::wait_statements_block_until_their_condition_holds", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::waiting_processes_do_not_keep_an_idle_simulation_running", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ], + "exclude_stronger_than_sv": false, + "include_ignored": false, + "schema_version": 3, + "suite": "sv", + "suite_version": "0.10.1", + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)" +} diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 632e6dace3e..4f18957498c 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -613,7 +613,10 @@ "interfaces::overrides_body_parameters_and_drives_members_from_imported_functions", "interfaces::reads_undriven_interface_members_as_unknown", "interfaces::rewrites_nested_references_and_keeps_declaration_functions", - "interfaces::runs_interface_processes_once_per_array_element" + "interfaces::runs_interface_processes_once_per_array_element", + "timing::generic_interface_methods_keep_setup_edges", + "timing::inherited_interface_methods_keep_setup_edges", + "timing::interface_modport_methods_keep_setup_edges" ] } }, @@ -1265,5 +1268,22 @@ "indexed_select::constant_parameter_initializers_preserve_unknown_indices" ] } + }, + { + "id": "sv_icarus_qualified_unit_task", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus 13.0 / Verilator 5.052", + "reason": "Icarus 13.0 rejects $unit::tick(q) as a malformed statement. IEEE 1800-2023 3.12.1 permits scope-qualified compilation-unit identifiers. Celox and Verilator pass the unchanged timed task case.", + "upstream": [], + "evidence": [ + "verification/repros/sv_timed_unit_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "timing::qualified_unit_tasks_keep_setup_edges" + ] + } } ] diff --git a/crates/celox-test-suite/verification/sv/limitations/icarus.json b/crates/celox-test-suite/verification/sv/limitations/icarus.json index 33a06fd54ef..45d032cb203 100644 --- a/crates/celox-test-suite/verification/sv/limitations/icarus.json +++ b/crates/celox-test-suite/verification/sv/limitations/icarus.json @@ -9,7 +9,7 @@ "unexpected_accept": 1, "mismatch": 14, "emission_error": 0, - "compile_error": 104, + "compile_error": 107, "runtime_error": 3, "unsupported": 0, "ignored": 0 @@ -1155,6 +1155,30 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Sequential", + "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:6: sorry: modport task/function ports are not yet supported.\n/source_0.sv:8: syntax error\n/source_0.sv:8: Errors in port declarations.\n", + "expectation": "Simulation", + "name": "timing::interface_modport_methods_keep_setup_edges", + "phase": "compile", + "status": "compile_error" + }, + { + "category": "Sequential", + "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:6: sorry: modport task/function ports are not yet supported.\n/source_0.sv:8: syntax error\n/source_0.sv:8: Errors in port declarations.\n", + "expectation": "Simulation", + "name": "timing::generic_interface_methods_keep_setup_edges", + "phase": "compile", + "status": "compile_error" + }, + { + "category": "Sequential", + "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:6: sorry: modport task/function ports are not yet supported.\n/source_0.sv:8: syntax error\n/source_0.sv:8: Errors in port declarations.\n", + "expectation": "Simulation", + "name": "timing::inherited_interface_methods_keep_setup_edges", + "phase": "compile", + "status": "compile_error" } ] } diff --git a/crates/celox-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..bc4d1741e08 --- /dev/null +++ b/crates/celox-test-suite/verification/sv/verilator/timing.json @@ -0,0 +1,154 @@ +{ + "cases": [ + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::always_with_a_delay_generates_a_clock", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::any_change_waits_wake_on_every_value_change", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::delays_resume_initial_blocks_at_later_times", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::edge_waits_resume_before_the_registers_of_that_edge_update", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::edge_waits_see_the_signals_the_script_drives", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::finish_in_an_always_process_ends_the_simulation", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "four-state expectations", + "expectation": "Simulation", + "name": "timing::four_state_edges_count_transitions_through_unknown", + "phase": "compile", + "status": "unsupported", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::level_sensitive_always_runs_as_a_process", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::processes_wake_each_other_at_the_same_time", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::tasks_with_timing_controls_run_in_processes", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "four-state expectations", + "expectation": "Simulation", + "name": "timing::unknown_delays_and_conditions_count_as_zero_and_false", + "phase": "compile", + "status": "unsupported", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::wait_statements_block_until_their_condition_holds", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::waiting_processes_do_not_keep_an_idle_simulation_running", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ], + "exclude_stronger_than_sv": false, + "include_ignored": false, + "schema_version": 3, + "suite": "sv", + "suite_version": "0.10.1", + "tool": "verilator", + "version": "Verilator 5.052 2026-09-05 rev v5.052" +} diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 6332e23ba81..aa13ac61ac7 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -356,6 +356,9 @@ impl Simulation { self.simulator.check_vcd_rewind(record.time)?; let parts = self.simulator.resolve_schedule(record)?; self.simulator.load_state(file)?; + // V1 recorded Boolean (known) baselines. Masks of the restored + // current values may belong to a still-pending write and cannot be + // substituted for those historical baselines. self.state.import_schedule(parts); self.pending_host_work = false; Ok(()) @@ -451,6 +454,39 @@ impl Simulation { value } + /// Returns the value and unknown-bit mask of a signal. + pub fn get_four_state( + &mut self, + signal: SignalRef, + ) -> (num_bigint::BigUint, num_bigint::BigUint) { + let was_dirty = self.simulator.dirty; + let value = if self.state.is_finished() { + self.simulator.backend.get_four_state(signal) + } else { + self.simulator.get_four_state(signal) + }; + self.synchronize_runtime_finish(was_dirty); + value + } + + /// Sets a signal to a known value. The write takes effect at the current + /// time: processes waiting for it resume when the simulation next runs. + pub fn set_wide(&mut self, signal: SignalRef, value: num_bigint::BigUint) { + self.simulator.set_wide(signal, value); + self.synchronize_host_write(); + } + + /// Sets a signal's value and unknown-bit mask, like [`Self::set_wide`]. + pub fn set_four_state( + &mut self, + signal: SignalRef, + value: num_bigint::BigUint, + mask: num_bigint::BigUint, + ) { + self.simulator.set_four_state(signal, value, mask); + self.synchronize_host_write(); + } + /// Modifies internal state via a callback and re-stabilizes combinational logic. pub fn modify(&mut self, f: F) -> Result<(), RuntimeErrorCode> where @@ -461,11 +497,29 @@ impl Simulation { result } + fn validate_event_time(&self, time: u64) -> Result<(), RuntimeErrorCode> { + if time < self.state.time() { + return Err(RuntimeErrorCode::Runtime { + message: format!( + "cannot schedule an event in the past: {time} before {}", + self.state.time() + ), + signals: Vec::new(), + }); + } + Ok(()) + } + /// Register a clock signal and its period, enqueuing the first edge. /// Odd periods alternate floor/ceil half periods. Periods below two /// time units use a two-unit period so both phases advance time. - /// `initial_delay` specifies when the first rising edge occurs. + /// `initial_delay` specifies when the first rising edge occurs. Past + /// timestamps are ignored by this compatibility API; use + /// [`Self::try_add_clock_by_id`] for an error result. pub fn add_clock(&mut self, port: &str, period: u64, initial_delay: u64) { + if self.validate_event_time(initial_delay).is_err() { + return; + } let signal = self.simulator.signal(port); let addr = self.simulator.program.get_addr(&[], &[port]).unwrap(); if let Some(ev) = self.simulator.backend.resolve_event_opt(&addr) { @@ -476,6 +530,7 @@ impl Simulation { /// Schedule a one-shot event at a specific time. /// The signal must be registered as an event (clock or async reset) in the backend. pub fn schedule(&mut self, port: &str, time: u64, value: u64) -> Result<(), RuntimeErrorCode> { + self.validate_event_time(time)?; let signal = self.simulator.signal(port); let addr = self.simulator.program.get_addr(&[], &[port]).unwrap(); let ev_opt = self.simulator.backend.resolve_event_opt(&addr); @@ -496,13 +551,81 @@ impl Simulation { /// instead: the call then returns the current time without advancing, /// so what the process did is observable at its own time. pub fn step(&mut self) -> Result, RuntimeErrorCode> { + if self.state.is_finished() { + return Ok(None); + } self.settle_host_writes()?; + if self.state.is_finished() { + return Ok(None); + } if self.state.poll_waiting(&mut self.simulator)? { - return Ok(Some(self.state.time())); + return Ok((!self.state.is_finished()).then_some(self.state.time())); + } + if self.state.has_unsettled_edges(&self.simulator.backend) { + let time = self.state.time(); + let active = self + .state + .has_unsettled_active_edges(&self.simulator.backend); + let queued = self.state.next_event_time() == Some(time); + if queued { + self.state.step(&mut self.simulator)?; + } else { + self.state.settle_at(&mut self.simulator, time)?; + } + if self.state.is_finished() { + return Ok(None); + } + if active || queued { + return Ok(Some(time)); + } } self.state.step(&mut self.simulator) } + /// Settle the combinational logic after host writes and resume the + /// processes they woke at the current time, with the rounds that + /// follow, as [`Self::step`] does before advancing. Time does not + /// advance. + pub fn settle(&mut self) -> Result<(), RuntimeErrorCode> { + // A lazy output read can settle the host write and leave only its + // finish event pending. Synchronize termination before the clean path. + if self.simulator.has_pending_runtime_finish() { + self.state.finish(); + } + if self.state.is_finished() { + return Ok(()); + } + let time = self.state.time(); + if self.simulator.dirty + || !self.simulator.backend.get_triggered_bits().is_empty() + || self.state.has_unsettled_edges(&self.simulator.backend) + || self + .state + .next_event_time() + .is_some_and(|next| next <= time) + { + self.settle_host_writes()?; + if self.state.is_finished() { + return Ok(()); + } + let mut drained = false; + while self + .state + .next_event_time() + .is_some_and(|next| next <= time) + { + self.state.step(&mut self.simulator)?; + drained = true; + } + if !drained { + self.state.settle_at(&mut self.simulator, time)?; + } + } else { + self.state.poll_waiting(&mut self.simulator)?; + } + Ok(()) + } + /// Settle the combinational logic a host write left dirty, so a process /// waiting for a derived value sees it. fn settle_host_writes(&mut self) -> Result<(), RuntimeErrorCode> { @@ -534,12 +657,36 @@ impl Simulation { /// Run one step at or before `limit`, including processes a host write /// woke at the current time. Leave a later event queued. pub fn step_until(&mut self, limit: u64) -> Result, RuntimeErrorCode> { + if self.state.is_finished() { + return Ok(None); + } if self.state.time() > limit { return Ok(None); } self.settle_host_writes()?; + if self.state.is_finished() { + return Ok(None); + } if self.state.poll_waiting(&mut self.simulator)? { - return Ok(Some(self.state.time())); + return Ok((!self.state.is_finished()).then_some(self.state.time())); + } + if self.state.has_unsettled_edges(&self.simulator.backend) { + let time = self.state.time(); + let active = self + .state + .has_unsettled_active_edges(&self.simulator.backend); + let queued = self.state.next_event_time() == Some(time); + if queued { + self.state.step(&mut self.simulator)?; + } else { + self.state.settle_at(&mut self.simulator, time)?; + } + if self.state.is_finished() { + return Ok(None); + } + if active || queued { + return Ok(Some(time)); + } } if self .state @@ -555,11 +702,25 @@ impl Simulation { /// Advance time and run until `end_time` (inclusive). As for /// [`Self::step`], processes that a host write woke resume first. pub fn run_until(&mut self, end_time: u64) -> Result<(), RuntimeErrorCode> { + if self.state.is_finished() { + return Ok(()); + } if self.state.time() > end_time { return Ok(()); } self.settle_host_writes()?; self.state.poll_waiting(&mut self.simulator)?; + if self.state.has_unsettled_edges(&self.simulator.backend) { + let time = self.state.time(); + if self.state.next_event_time() == Some(time) { + self.state.step(&mut self.simulator)?; + } else { + self.state.settle_at(&mut self.simulator, time)?; + } + } + if self.state.is_finished() { + return Ok(()); + } while let Some(next_time) = self.state.next_event_time() { if next_time > end_time { break; @@ -695,13 +856,15 @@ impl Simulation { /// # Errors /// /// Returns [`RuntimeErrorCode::NotAnEvent`] if `event_id` is unknown or - /// does not resolve to an event (clock or asynchronous reset). + /// does not resolve to an event (clock or asynchronous reset), or a runtime + /// error if the initial edge would precede the current time. pub fn try_add_clock_by_id( &mut self, event_id: u32, period: u64, initial_delay: u64, ) -> Result<(), RuntimeErrorCode> { + self.validate_event_time(initial_delay)?; let addr = self .simulator .backend @@ -730,6 +893,7 @@ impl Simulation { time: u64, value: u64, ) -> Result<(), RuntimeErrorCode> { + self.validate_event_time(time)?; let addr = self .simulator .backend @@ -1531,6 +1695,34 @@ mod finish_and_cotrigger_tests { } } +#[cfg(all(test, feature = "systemverilog"))] +mod idle_settle_tests { + use super::*; + #[test] + fn settled_reads_do_not_repeat_comb_side_effects() { + fn check(mut sim: Simulation) { + let a = sim.signal("a"); + sim.set_wide(a, 1u8.into()); + sim.run_until(0).unwrap(); + assert!(sim.drain_runtime_events().iter().any( + |e| matches!(e,crate::RuntimeEvent::Display { message } if message.as_slice()==b"x") + )); + sim.settle().unwrap(); + sim.settle().unwrap(); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + assert!(sim.drain_runtime_events().is_empty()); + } + let source = "module Top(input bit a,output bit q);always @* begin q=a;if(a)$display(\"x\");end endmodule"; + let builder = + || Simulator::from_sv_sources(vec![(source, std::path::Path::new("settle.sv"))], "Top"); + check(Simulation::new(builder().build_interpreter().unwrap())); + check(Simulation::new(builder().build_cranelift().unwrap())); + check(Simulation::new(builder().build_wasm().unwrap())); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(builder().build_native().unwrap())); + } +} + #[cfg(all(test, feature = "systemverilog"))] mod active_comb_nba_tests { use super::*; @@ -1633,6 +1825,33 @@ mod direct_finish_tests { } } +#[cfg(all(test, feature = "systemverilog"))] +mod current_time_settle_tests { + use super::*; + #[test] + fn settle_consumes_current_time_clock_events() { + fn check(mut sim: Simulation) { + sim.run_until(0).unwrap(); + sim.schedule("clk", 0, 1).unwrap(); + sim.settle().unwrap(); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + assert_eq!(sim.time(), 0); + assert_eq!(sim.next_event_time(), None); + sim.settle().unwrap(); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + } + let source = + "module Top(input bit clk,output bit[7:0]q);always @(posedge clk)q<=q+1;endmodule"; + let builder = + || Simulator::from_sv_sources(vec![(source, std::path::Path::new("settle.sv"))], "Top"); + check(Simulation::new(builder().build_interpreter().unwrap())); + check(Simulation::new(builder().build_cranelift().unwrap())); + check(Simulation::new(builder().build_wasm().unwrap())); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(builder().build_native().unwrap())); + } +} + #[cfg(all(test, feature = "systemverilog"))] mod drained_finish_tests { use super::*; @@ -1746,6 +1965,157 @@ mod scheduled_pulse_tests { } } +#[cfg(all(test, feature = "systemverilog"))] +mod lazy_host_clock_review_tests { + use super::*; + fn check(mut sim: Simulation, mask: u8) { + let clk = sim.signal("clk"); + let q = sim.signal("q"); + sim.set_four_state(clk, 1u8.into(), 0u8.into()); + sim.settle().unwrap(); + assert_eq!(sim.get(q), 1u8.into()); + sim.set_four_state(clk, 0u8.into(), mask.into()); + let _ = sim.get(q); + sim.settle().unwrap(); + sim.set_four_state(clk, 1u8.into(), 0u8.into()); + let _ = sim.get(q); + sim.settle().unwrap(); + assert_eq!(sim.get(q), 2u8.into(), "inactive mask {mask}"); + } + #[test] + fn lazy_reads_do_not_hide_inactive_clock_transitions() { + let source = + "module Top(input logic clk,output int q);always @(posedge clk)q<=q+1;endmodule"; + let build = || { + Simulator::from_sv_sources(vec![(source, std::path::Path::new("lazy-clock.sv"))], "Top") + .four_state(true) + }; + for mask in [0, 1] { + check(Simulation::new(build().build_interpreter().unwrap()), mask); + check(Simulation::new(build().build_cranelift().unwrap()), mask); + check(Simulation::new(build().build_wasm().unwrap()), mask); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap()), mask); + } + } +} + +#[cfg(all(test, feature = "systemverilog"))] +mod legacy_clock_state_review_tests { + use super::*; + fn check(mut source: Simulation, mut target: Simulation, known: u8) { + let clk = source.signal("clk"); + source.set_four_state(clk, 1u8.into(), 0u8.into()); + source.settle().unwrap(); + source.set_four_state(clk, known.into(), 1u8.into()); + source.settle().unwrap(); + let file = source.save_state().unwrap(); + let unknown_bytes = 4 + file + .schedule + .as_ref() + .unwrap() + .unknown_events + .iter() + .flatten() + .map(|name| 4 + name.len()) + .sum::(); + let mut bytes = Vec::new(); + file.write_to(&mut bytes).unwrap(); + bytes[8..10].copy_from_slice(&1u16.to_le_bytes()); + bytes.truncate(bytes.len() - unknown_bytes); + let legacy = celox_runtime::StateFile::read_from(bytes.as_slice()).unwrap(); + target.load_state(&legacy).unwrap(); + let q = target.signal("q"); + let before = target.get(q); + let clk = target.signal("clk"); + target.set_four_state(clk, known.into(), 0u8.into()); + target.settle().unwrap(); + assert_eq!(target.get(q), before); + } + #[test] + fn legacy_files_keep_known_boolean_clock_baselines() { + for (edge, known) in [("posedge", 1u8), ("negedge", 0u8)] { + let source = format!( + "module Top(input logic clk,output int q);always @({edge} clk)q<=q+1;endmodule" + ); + let build = || { + Simulator::from_sv_sources( + vec![(source.as_str(), std::path::Path::new("legacy-clock.sv"))], + "Top", + ) + .four_state(true) + }; + check( + Simulation::new(build().build_interpreter().unwrap()), + Simulation::new(build().build_interpreter().unwrap()), + known, + ); + check( + Simulation::new(build().build_cranelift().unwrap()), + Simulation::new(build().build_cranelift().unwrap()), + known, + ); + check( + Simulation::new(build().build_wasm().unwrap()), + Simulation::new(build().build_wasm().unwrap()), + known, + ); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check( + Simulation::new(build().build_native().unwrap()), + Simulation::new(build().build_native().unwrap()), + known, + ); + } + } +} + +#[cfg(all(test, feature = "systemverilog"))] +mod staged_edge_review_tests { + use super::*; + fn check(mut sim: Simulation, mut restored: Simulation) { + let a = sim.signal("a"); + let qa = sim.signal("qa"); + let qb = sim.signal("qb"); + sim.set_wide(a, 1u8.into()); + let mut file = sim.save_state().unwrap(); + file.schedule.as_mut().unwrap().unknown_events = None; + let mut bytes = Vec::new(); + file.write_to(&mut bytes).unwrap(); + let file = celox_runtime::StateFile::read_from(bytes.as_slice()).unwrap(); + restored.load_state(&file).unwrap(); + restored.settle().unwrap(); + assert_eq!(restored.get(qa), 1u8.into()); + sim.schedule("b", 0, 1).unwrap(); + sim.settle().unwrap(); + assert_eq!(sim.get(qa), 1u8.into()); + assert_eq!(sim.get(qb), 1u8.into()); + } + #[test] + fn host_edges_join_current_time_events_and_survive_legacy_state_files() { + let source = "module Top(input bit a,b,output bit[7:0]qa,qb);always @(posedge a)qa<=qb+1;always @(posedge b)qb<=qa+1;endmodule"; + let build = + || Simulator::from_sv_sources(vec![(source, std::path::Path::new("staged.sv"))], "Top"); + check( + Simulation::new(build().build_interpreter().unwrap()), + Simulation::new(build().build_interpreter().unwrap()), + ); + check( + Simulation::new(build().build_cranelift().unwrap()), + Simulation::new(build().build_cranelift().unwrap()), + ); + check( + Simulation::new(build().build_wasm().unwrap()), + Simulation::new(build().build_wasm().unwrap()), + ); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check( + Simulation::new(build().build_native().unwrap()), + Simulation::new(build().build_native().unwrap()), + ); + } +} + #[cfg(all(test, feature = "systemverilog"))] mod finished_host_write_review_tests { use super::*; @@ -1786,6 +2156,93 @@ mod finished_host_write_review_tests { } } +#[cfg(all(test, feature = "systemverilog"))] +mod public_host_edge_review_tests { + use super::*; + fn check(mut sim: Simulation, operation: &str) { + let clk = sim.signal("clk"); + let q = sim.signal("q"); + sim.set_wide(clk, 1u8.into()); + match operation { + "step" => { + sim.step().unwrap(); + } + "step_until" => { + sim.step_until(0).unwrap(); + } + _ => sim.run_until(0).unwrap(), + }; + assert_eq!(sim.get(q), 1u8.into()); + assert_eq!(sim.time(), 0); + sim.run_until(10).unwrap(); + assert!(sim.schedule("clk", 5, 0).is_err()); + sim.settle().unwrap(); + assert_eq!(sim.time(), 10); + } + #[test] + fn public_runs_settle_host_edges_and_reject_past_schedules() { + let source = "module Top(input bit clk,output bit q);always @(posedge clk)q<=1;endmodule"; + for operation in ["step", "step_until", "run_until"] { + let build = || { + Simulator::from_sv_sources( + vec![(source, std::path::Path::new("host-edge.sv"))], + "Top", + ) + }; + check( + Simulation::new(build().build_interpreter().unwrap()), + operation, + ); + check( + Simulation::new(build().build_cranelift().unwrap()), + operation, + ); + check(Simulation::new(build().build_wasm().unwrap()), operation); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap()), operation); + } + } + #[test] + fn legacy_pending_known_to_unknown_edges_keep_their_known_baseline() { + let source = "module Top(input logic clk,output bit q);always @(posedge clk)q<=1;endmodule"; + let build = || { + Simulator::from_sv_sources( + vec![(source, std::path::Path::new("legacy-pending.sv"))], + "Top", + ) + .four_state(true) + }; + fn check(mut source: Simulation, mut target: Simulation) { + source.set_four_state(source.signal("clk"), 0u8.into(), 1u8.into()); + let mut file = source.save_state().unwrap(); + file.schedule.as_mut().unwrap().unknown_events = None; + let mut bytes = Vec::new(); + file.write_to(&mut bytes).unwrap(); + let file = celox_runtime::StateFile::read_from(bytes.as_slice()).unwrap(); + target.load_state(&file).unwrap(); + target.settle().unwrap(); + assert_eq!(target.get(target.signal("q")), 1u8.into()); + } + check( + Simulation::new(build().build_interpreter().unwrap()), + Simulation::new(build().build_interpreter().unwrap()), + ); + check( + Simulation::new(build().build_cranelift().unwrap()), + Simulation::new(build().build_cranelift().unwrap()), + ); + check( + Simulation::new(build().build_wasm().unwrap()), + Simulation::new(build().build_wasm().unwrap()), + ); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check( + Simulation::new(build().build_native().unwrap()), + Simulation::new(build().build_native().unwrap()), + ); + } +} + #[cfg(all(test, feature = "systemverilog"))] mod scheduled_derived_concat_review_tests { use super::*; @@ -1847,6 +2304,45 @@ mod scheduled_derived_concat_review_tests { } } +#[cfg(all(test, feature = "systemverilog"))] +mod past_by_id_review_tests { + use super::*; + fn check(mut sim: Simulation) { + sim.run_until(10).unwrap(); + let clk = sim.signal("clk"); + let id = sim + .simulator + .backend + .id_to_addr_slice() + .iter() + .position(|addr| sim.simulator.backend.resolve_signal(addr) == clk) + .unwrap() as u32; + assert!(sim.schedule_by_id(id, 5, 1).is_err()); + assert!(sim.try_add_clock_by_id(id, 4, 5).is_err()); + sim.add_clock("clk", 4, 5); + sim.add_clock_by_id(id, 4, 5); + sim.settle().unwrap(); + assert_eq!(sim.time(), 10); + assert_eq!(sim.next_event_time(), None); + sim.schedule_by_id(id, 10, 1).unwrap(); + sim.settle().unwrap(); + assert_eq!(sim.time(), 10); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + } + #[test] + fn by_id_schedules_and_clock_registration_cannot_rewind_time() { + let source = "module Top(input bit clk,output bit q);always @(posedge clk)q<=1;endmodule"; + let build = || { + Simulator::from_sv_sources(vec![(source, std::path::Path::new("past-id.sv"))], "Top") + }; + check(Simulation::new(build().build_interpreter().unwrap())); + check(Simulation::new(build().build_cranelift().unwrap())); + check(Simulation::new(build().build_wasm().unwrap())); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap())); + } +} + #[cfg(all(test, feature = "systemverilog"))] mod finish_during_round_review_tests { use super::*; @@ -1886,17 +2382,74 @@ mod finish_during_round_review_tests { queued_finish(Simulation::new(build().build_native().unwrap())); } } - #[test] - fn nba_woken_finishes_stop_remaining_work() { - let source = "module Top(input bit clk,output bit a,y);bit q;assign y=a;always @(posedge clk)q<=1;initial begin @(posedge q);a=1;$finish;end endmodule"; - let build = - || Simulator::from_sv_sources(vec![(source, Path::new("nba-finish.sv"))], "Top"); - nba_finish(Simulation::new(build().build_interpreter().unwrap())); - nba_finish(Simulation::new(build().build_cranelift().unwrap())); - nba_finish(Simulation::new(build().build_wasm().unwrap())); - #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] - nba_finish(Simulation::new(build().build_native().unwrap())); - } + #[test] + fn nba_woken_finishes_stop_remaining_work() { + let source = "module Top(input bit clk,output bit a,y);bit q;assign y=a;always @(posedge clk)q<=1;initial begin @(posedge q);a=1;$finish;end endmodule"; + let build = + || Simulator::from_sv_sources(vec![(source, Path::new("nba-finish.sv"))], "Top"); + nba_finish(Simulation::new(build().build_interpreter().unwrap())); + nba_finish(Simulation::new(build().build_cranelift().unwrap())); + nba_finish(Simulation::new(build().build_wasm().unwrap())); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + nba_finish(Simulation::new(build().build_native().unwrap())); + } +} + +#[cfg(all(test, feature = "systemverilog"))] +mod inactive_host_transition_review_tests { + use super::*; + fn check(mut sim: Simulation, method: &str, future: bool) { + let clk = sim.signal("clk"); + sim.set_wide(clk, 1u8.into()); + sim.run_until(0).unwrap(); + sim.set_wide(clk, 0u8.into()); + if future { + sim.schedule("clk", 5, 1).unwrap(); + } + if method == "step" { + assert_eq!(sim.step().unwrap(), future.then_some(5)); + } else { + assert_eq!(sim.step_until(4).unwrap(), None); + if future { + assert_eq!(sim.step_until(5).unwrap(), Some(5)); + } + } + } + #[test] + fn inactive_host_edges_do_not_fabricate_steps() { + let source = "module Top(input bit clk,output bit q);always @(posedge clk)q<=1;endmodule"; + for method in ["step", "step_until"] { + for future in [false, true] { + let build = || { + Simulator::from_sv_sources( + vec![(source, std::path::Path::new("inactive-host.sv"))], + "Top", + ) + }; + check( + Simulation::new(build().build_interpreter().unwrap()), + method, + future, + ); + check( + Simulation::new(build().build_cranelift().unwrap()), + method, + future, + ); + check( + Simulation::new(build().build_wasm().unwrap()), + method, + future, + ); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check( + Simulation::new(build().build_native().unwrap()), + method, + future, + ); + } + } + } } #[cfg(all(test, feature = "systemverilog"))] @@ -1996,6 +2549,120 @@ mod queued_derived_ff_review_tests { } } +#[cfg(all(test, feature = "systemverilog"))] +mod host_finish_edge_review_tests { + use super::*; + #[test] + fn host_finish_and_edge_do_not_report_a_step() { + let source = "module Top(input bit a,output bit q);always_comb if(a)$finish;always @(posedge a)q<=1;endmodule"; + fn check(mut sim: Simulation, bounded: bool) { + sim.run_until(0).unwrap(); + assert!(!sim.is_finished()); + sim.set_wide(sim.signal("a"), 1u8.into()); + let result = if bounded { + sim.step_until(0) + } else { + sim.step() + }; + assert_eq!(result.unwrap(), None); + assert!(sim.is_finished()); + assert_eq!(sim.get(sim.signal("q")), 0u8.into()); + assert_eq!(sim.time(), 0); + } + for bounded in [false, true] { + let build = || { + Simulator::from_sv_sources( + vec![(source, std::path::Path::new("host-finish-edge.sv"))], + "Top", + ) + }; + check( + Simulation::new(build().build_interpreter().unwrap()), + bounded, + ); + check(Simulation::new(build().build_cranelift().unwrap()), bounded); + check(Simulation::new(build().build_wasm().unwrap()), bounded); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap()), bounded); + } + } +} + +#[cfg(all(test, feature = "systemverilog"))] +mod cross_mode_clock_baseline_review_tests { + use super::*; + #[test] + fn unknown_clock_baselines_coerce_with_loaded_state() { + let source = + "module Top(input logic clk,output bit[7:0]q);always @(negedge clk)q<=q+1;endmodule"; + fn check(mut source: Simulation, mut target: Simulation, payload: u8) { + let clk = source.signal("clk"); + source + .modify(|io| io.set_four_state(clk, payload.into(), 1u8.into())) + .unwrap(); + source.run_until(0).unwrap(); + assert_eq!(source.get(source.signal("q")), 0u8.into()); + let file = source.save_state().unwrap(); + target.load_state(&file).unwrap(); + target.settle().unwrap(); + assert_eq!(target.get(target.signal("q")), 0u8.into()); + let clk = target.signal("clk"); + target.set_wide(clk, 1u8.into()); + target.settle().unwrap(); + target.set_wide(clk, 0u8.into()); + target.settle().unwrap(); + assert_eq!(target.get(target.signal("q")), 1u8.into()); + } + let bit_source = source.replace("input logic clk", "input bit clk"); + for (payload, target_four_state, target_bit) in [ + (0, false, false), + (1, false, false), + (0, true, true), + (1, true, true), + (0, true, false), + (1, true, false), + ] { + let build = |four_state, bit| { + let code = if bit { bit_source.as_str() } else { source }; + Simulator::from_sv_sources( + vec![(code, std::path::Path::new("baseline-coercion.sv"))], + "Top", + ) + .four_state(four_state) + }; + check( + Simulation::new(build(true, false).build_interpreter().unwrap()), + Simulation::new( + build(target_four_state, target_bit) + .build_interpreter() + .unwrap(), + ), + payload, + ); + check( + Simulation::new(build(true, false).build_cranelift().unwrap()), + Simulation::new( + build(target_four_state, target_bit) + .build_cranelift() + .unwrap(), + ), + payload, + ); + check( + Simulation::new(build(true, false).build_wasm().unwrap()), + Simulation::new(build(target_four_state, target_bit).build_wasm().unwrap()), + payload, + ); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check( + Simulation::new(build(true, false).build_native().unwrap()), + Simulation::new(build(target_four_state, target_bit).build_native().unwrap()), + payload, + ); + } + } +} + #[cfg(all(test, feature = "systemverilog"))] mod zero_delay_review_tests { use super::*; @@ -2188,6 +2855,36 @@ mod active_feedback_review_tests { } } +#[cfg(all(test, feature = "systemverilog"))] +mod lazy_finish_settle_review { + use super::*; + #[test] + fn settle_recognizes_finish_after_lazy_reads() { + let source = "module Top(input bit go,output bit y);always_comb begin y=go;if(go)$finish;end endmodule"; + fn check(mut sim: Simulation) { + sim.run_until(0).unwrap(); + let go = sim.signal("go"); + let y = sim.signal("y"); + sim.modify(|io| io.set(go, 1u8)).unwrap(); + assert_eq!(sim.get(y), 1u8.into()); + sim.settle().unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.step().unwrap(), None); + } + let build = || { + Simulator::from_sv_sources( + vec![(source, std::path::Path::new("lazy-finish.sv"))], + "Top", + ) + }; + check(Simulation::new(build().build_interpreter().unwrap())); + check(Simulation::new(build().build_cranelift().unwrap())); + check(Simulation::new(build().build_wasm().unwrap())); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap())); + } +} + #[cfg(all(test, feature = "systemverilog"))] mod post_nba_retrigger_review_tests { use super::*; @@ -2212,6 +2909,77 @@ mod post_nba_retrigger_review_tests { } } +#[cfg(all(test, feature = "systemverilog"))] +mod other_domain_host_step_review { + use super::*; + #[test] + fn any_change_runtime_domains_report_host_falls_at_current_time() { + let source = "module Top(input bit clk,output bit[7:0]count);always @(posedge clk)count<=count+1;endmodule"; + fn check(simulator: Simulator, bounded: bool) { + // The compiled event entry is the FF operation. Its edge policy + // comes from runtime metadata; exercise an any-change domain here. + let signal = simulator.signal("clk"); + let address = simulator.program.get_addr(&[], &["clk"]).unwrap(); + let event = simulator.backend.resolve_event(&address); + let mut kinds = vec![None; simulator.backend.num_events()]; + kinds[event.id()] = Some(celox_design::DomainKind::Other); + let mut info = vec![ + EventInfo { + canonical_id: usize::MAX, + is_cascaded: false, + eval_ff_event: None, + eval_only_event: None, + apply_event: None + }; + simulator.backend.num_events() + ]; + info[event.id()] = EventInfo { + canonical_id: event.id(), + is_cascaded: false, + eval_ff_event: Some(event), + eval_only_event: simulator.backend.resolve_eval_only_event(&address), + apply_event: simulator.backend.resolve_apply_event(&address), + }; + let state = SimulationState::new( + &simulator.backend, + vec![(signal, event.id(), event.id())], + kinds, + info, + Vec::new(), + ); + let mut sim = Simulation { + simulator, + state, + pending_host_work: false, + }; + sim.set_wide(signal, 1u8.into()); + assert_eq!(sim.step().unwrap(), Some(0)); + assert_eq!(sim.get(sim.signal("count")), 1u8.into()); + sim.set_wide(signal, 0u8.into()); + let time = if bounded { + sim.step_until(0).unwrap() + } else { + sim.step().unwrap() + }; + assert_eq!(sim.get(sim.signal("count")), 2u8.into()); + assert_eq!(time, Some(0)); + } + for bounded in [false, true] { + let build = || { + Simulator::from_sv_sources( + vec![(source, std::path::Path::new("any-change-operation.sv"))], + "Top", + ) + }; + check(build().build_interpreter().unwrap(), bounded); + check(build().build_cranelift().unwrap(), bounded); + check(build().build_wasm().unwrap(), bounded); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap(), bounded); + } + } +} + #[cfg(all(test, feature = "systemverilog"))] mod additional_host_edge_reviews { use super::*; @@ -2274,6 +3042,9 @@ mod additional_host_edge_reviews { "get" => { assert_eq!(sim.get(y), 1u8.into()); } + "get_four_state" => { + assert_eq!(sim.get_four_state(y), (1u8.into(), 0u8.into())); + } "drain" => { assert!( sim.drain_runtime_events() @@ -2295,7 +3066,7 @@ mod additional_host_edge_reviews { sim.drain_runtime_events(); assert_eq!(sim.simulator.backend.get(y), 1u8.into()); } - for op in ["get", "drain", "modify"] { + for op in ["get", "get_four_state", "drain", "modify"] { let build = || { Simulator::from_sv_sources( vec![(source, std::path::Path::new("facade-finish.sv"))], @@ -2311,6 +3082,37 @@ mod additional_host_edge_reviews { } } +#[cfg(all(test, feature = "systemverilog"))] +mod host_finish_queued_settle_review { + use super::*; + #[test] + fn host_finish_prevents_a_queued_current_time_edge() { + let source = "module Top(input bit go,clk,output bit q);always @(posedge clk)q<=1;always_comb if(go)$finish;endmodule"; + fn check(mut sim: Simulation) { + sim.run_until(0).unwrap(); + let go = sim.signal("go"); + let q = sim.signal("q"); + sim.schedule("clk", 0, 1).unwrap(); + sim.set_wide(go, 1u8.into()); + sim.settle().unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.get(q), 0u8.into()); + assert_eq!(sim.get(sim.signal("clk")), 0u8.into()); + } + let build = || { + Simulator::from_sv_sources( + vec![(source, std::path::Path::new("queued-finish.sv"))], + "Top", + ) + }; + check(Simulation::new(build().build_interpreter().unwrap())); + check(Simulation::new(build().build_cranelift().unwrap())); + check(Simulation::new(build().build_wasm().unwrap())); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap())); + } +} + #[cfg(all(test, feature = "systemverilog"))] mod lazy_event_pulse_review { use super::*; @@ -2408,6 +3210,74 @@ mod lazy_read_and_ff_edges_review { } } +#[cfg(all(test, feature = "systemverilog"))] +mod loaded_schedule_and_finish_review { + use super::*; + #[test] + fn ff_finish_keeps_later_queued_event_unapplied() { + let source = "module Top(input bit clk,output bit q);always @(posedge clk)begin q=1;$finish;end endmodule"; + fn check(mut sim: Simulation) { + sim.run_until(0).unwrap(); + sim.schedule("clk", 1, 0).unwrap(); + let clk = sim.signal("clk"); + sim.modify(|io| io.set(clk, 1u8)).unwrap(); + sim.run_until(2).unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.time(), 0); + assert_eq!(sim.get(clk), 1u8.into()); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + } + let build = || { + Simulator::from_sv_sources( + vec![(source, std::path::Path::new("queued-after-finish.sv"))], + "Top", + ) + }; + check(Simulation::new(build().build_interpreter().unwrap())); + check(Simulation::new(build().build_cranelift().unwrap())); + check(Simulation::new(build().build_wasm().unwrap())); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap())); + } + #[test] + fn state_load_rejects_past_events_atomically() { + let source = "module Top(input bit clk,output bit q);always @(posedge clk)q<=!q;endmodule"; + fn check(mut sim: Simulation) { + sim.run_until(5).unwrap(); + sim.schedule("clk", 6, 1).unwrap(); + let file = sim.save_state().unwrap(); + for periodic in [false, true] { + let mut corrupt = file.clone(); + let record = corrupt.schedule.as_mut().unwrap(); + if periodic { + let mut e = record.events[0].clone(); + e.time = 4; + record.periodic.push((e, 1)); + } else { + record.events[0].time = 4; + } + let before = sim.save_state().unwrap(); + assert!(sim.load_state(&corrupt).is_err()); + assert_eq!(sim.save_state().unwrap(), before); + assert_eq!(sim.time(), 5); + } + sim.load_state(&file).unwrap(); + sim.run_until(6).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + } + let build = || { + Simulator::from_sv_sources( + vec![(source, std::path::Path::new("past-loaded-event.sv"))], + "Top", + ) + }; + check(Simulation::new(build().build_interpreter().unwrap())); + check(Simulation::new(build().build_cranelift().unwrap())); + check(Simulation::new(build().build_wasm().unwrap())); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap())); + } +} #[cfg(all(test, feature = "systemverilog"))] mod implicit_host_edge_review { use super::*; @@ -2693,6 +3563,93 @@ mod nba_waiter_sampling_review { } } +#[cfg(all(test, feature = "systemverilog"))] +mod mixed_other_domain_host_review { + use super::*; + #[test] + fn any_change_host_falls_join_current_time_batches() { + let source = "module Top(input bit clk,queued,output bit[7:0]count,queued_count);always @(posedge clk)count<=count+1;always @(posedge queued)queued_count<=queued_count+1;endmodule"; + fn check(simulator: Simulator, mode: u8) { + // The compiled event entry is the FF operation. Its edge policy + // comes from runtime metadata; exercise an any-change domain here. + let signal = simulator.signal("clk"); + let address = simulator.program.get_addr(&[], &["clk"]).unwrap(); + let event = simulator.backend.resolve_event(&address); + let mut kinds = vec![None; simulator.backend.num_events()]; + kinds[event.id()] = Some(celox_design::DomainKind::Other); + let queued_address = simulator.program.get_addr(&[], &["queued"]).unwrap(); + let queued_event = simulator.backend.resolve_event(&queued_address); + let queued_signal = simulator.signal("queued"); + kinds[queued_event.id()] = Some(celox_design::DomainKind::ClockPosedge); + let mut info = vec![ + EventInfo { + canonical_id: usize::MAX, + is_cascaded: false, + eval_ff_event: None, + eval_only_event: None, + apply_event: None + }; + simulator.backend.num_events() + ]; + info[event.id()] = EventInfo { + canonical_id: event.id(), + is_cascaded: false, + eval_ff_event: Some(event), + eval_only_event: simulator.backend.resolve_eval_only_event(&address), + apply_event: simulator.backend.resolve_apply_event(&address), + }; + info[queued_event.id()] = EventInfo { + canonical_id: queued_event.id(), + is_cascaded: false, + eval_ff_event: Some(queued_event), + eval_only_event: simulator.backend.resolve_eval_only_event(&queued_address), + apply_event: simulator.backend.resolve_apply_event(&queued_address), + }; + let state = SimulationState::new( + &simulator.backend, + vec![ + (signal, event.id(), event.id()), + (queued_signal, queued_event.id(), queued_event.id()), + ], + kinds, + info, + Vec::new(), + ); + let mut sim = Simulation { + simulator, + state, + pending_host_work: false, + }; + sim.set_wide(signal, 1u8.into()); + assert_eq!(sim.step().unwrap(), Some(0)); + assert_eq!(sim.get(sim.signal("count")), 1u8.into()); + sim.set_wide(signal, 0u8.into()); + sim.schedule("queued", 0, 1).unwrap(); + let time = match mode { + 0 => sim.step().unwrap(), + 1 => sim.step_until(0).unwrap(), + _ => sim.state.step(&mut sim.simulator).unwrap(), + }; + assert_eq!(sim.get(sim.signal("count")), 2u8.into()); + assert_eq!(time, Some(0)); + assert_eq!(sim.get(sim.signal("queued_count")), 1u8.into()); + } + for mode in [0, 1, 2] { + let build = || { + Simulator::from_sv_sources( + vec![(source, std::path::Path::new("any-change-operation.sv"))], + "Top", + ) + }; + check(build().build_interpreter().unwrap(), mode); + check(build().build_cranelift().unwrap(), mode); + check(build().build_wasm().unwrap(), mode); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap(), mode); + } + } +} + #[cfg(all(test, feature = "systemverilog"))] mod active_settle_review { use super::*; @@ -3756,6 +4713,56 @@ mod sampled_host_review { } } +#[cfg(all(test, feature = "systemverilog"))] +mod host_finish_step_review { + use super::*; + + #[test] + fn host_dispatch_reports_finished_without_returning_a_time() { + fn check(mut sim: Simulation) { + sim.run_until(0).unwrap(); + let initial = sim.checkpoint().unwrap(); + let clk = sim.signal("clk"); + for bounded in [false, true] { + sim.restore(&initial).unwrap(); + sim.modify(|io| io.set(clk, 1u8)).unwrap(); + let result = if bounded { + sim.step_until(10) + } else { + sim.step() + }; + assert_eq!(result.unwrap(), None); + assert!(sim.is_finished()); + assert_eq!(sim.time(), 0); + assert_eq!(sim.step().unwrap(), None); + } + } + for body in [ + "initial @(posedge clk)$finish;", + "always @(posedge clk)$finish;", + ] { + let source = format!("module Top(input bit clk);{body} endmodule"); + macro_rules! build { + ($method:ident) => { + check(Simulation::new( + Simulator::from_sv_sources( + vec![(source.as_str(), std::path::Path::new("host-finish.sv"))], + "Top", + ) + .$method() + .unwrap(), + )); + }; + } + build!(build_interpreter); + build!(build_cranelift); + build!(build_wasm); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + build!(build_native); + } + } +} + #[cfg(all(test, feature = "systemverilog"))] mod round57_review_tests { use super::*; @@ -4210,4 +5217,45 @@ mod round62_review_tests { backends!(&source, check); } } + #[test] + fn direct_host_setters_expose_pending_process_work() { + fn check(mut sim: Simulation) { + sim.run_until(0).unwrap(); + let clean = sim.checkpoint().unwrap(); + let go = sim.signal("go"); + for active_drain in [false, true] { + for four in [false, true] { + for observe in 0..3 { + sim.restore(&clean).unwrap(); + sim.eval_comb().unwrap(); + let _drain = active_drain + .then(|| sim.simulator.runtime_event_drain()) + .flatten(); + if four { + sim.set_four_state(go, 1u8.into(), 0u8.into()); + } else { + sim.set_wide(go, 1u8.into()); + } + match observe { + 1 => { + sim.get(go); + } + 2 => { + sim.eval_comb().unwrap(); + } + _ => {} + } + assert_eq!(sim.next_event_time(), Some(0)); + assert_eq!(sim.step().unwrap(), Some(0)); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + assert_eq!(sim.next_event_time(), None); + } + } + } + } + backends!( + "module Top(input bit go,output bit q);initial begin @(posedge go);q=1;end endmodule", + check + ); + } } diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index c8fdf179793..4220cd538cd 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -2927,6 +2927,74 @@ mod host { } } + /// The same configuration as a builder of an event-driven + /// [`Simulator`] that emits the triggers the timed scheduler needs. + fn into_simulator_builder(self) -> SimulatorBuilder<'a, Simulator> { + let mut builder = SimulatorBuilder { + sources: self.sources, + sv_sources: self.sv_sources, + top: self.top, + ignored_loops: self.ignored_loops, + true_loops: self.true_loops, + options: self.options, + vcd_path: self.vcd_path, + metadata: self.metadata, + clock_type: self.clock_type, + reset_type: self.reset_type, + param_overrides: self.param_overrides, + live_signals: self.live_signals, + injected_components: self.injected_components, + frontend_artifact: self.frontend_artifact, + _marker: std::marker::PhantomData, + }; + builder.options.emit_triggers = true; + builder + } + + /// Compiles with the Cranelift JIT backend and constructs the timed + /// simulation wrapper. + pub fn build_cranelift(self) -> Result, SimulatorError> { + Ok(crate::Simulation::new( + self.into_simulator_builder().build_cranelift()?, + )) + } + + /// Compiles with the interpreter backend and constructs the timed + /// simulation wrapper. + pub fn build_interpreter( + self, + ) -> Result, SimulatorError> { + Ok(crate::Simulation::new( + self.into_simulator_builder().build_interpreter()?, + )) + } + + /// Compiles with the WebAssembly backend and constructs the timed + /// simulation wrapper. + pub fn build_wasm( + self, + ) -> Result, SimulatorError> + { + Ok(crate::Simulation::new( + self.into_simulator_builder().build_wasm()?, + )) + } + + /// Compiles with the native backend of the host architecture and + /// constructs the timed simulation wrapper. + #[cfg(any( + all(target_arch = "x86_64", not(feature = "arm64-codegen")), + all(target_arch = "aarch64", not(feature = "x86_64-codegen")) + ))] + pub fn build_native( + self, + ) -> Result, SimulatorError> + { + Ok(crate::Simulation::new( + self.into_simulator_builder().build_native()?, + )) + } + /// Compiles the Veryl source and constructs the timed simulation wrapper. pub fn build(mut self) -> Result { self.options.emit_triggers = true; diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index a2180669b8f..1e93ab000fa 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -400,6 +400,20 @@ impl Simulator { &self, record: &ScheduleRecord, ) -> Result, StateError> { + if let Some(event) = record + .events + .iter() + .chain(record.periodic.iter().map(|(event, _)| event)) + .find(|event| event.time < record.time) + { + return Err(StateError::Runtime(RuntimeErrorCode::Runtime { + message: format!( + "cannot load an event in the past: {} before {}", + event.time, record.time + ), + signals: Vec::new(), + })); + } let events: HashMap = self .backend .id_to_event_slice() diff --git a/crates/celox/tests/frontends/systemverilog/processes.rs b/crates/celox/tests/frontends/systemverilog/processes.rs index f3e477a2e7a..9cdedcbe37f 100644 --- a/crates/celox/tests/frontends/systemverilog/processes.rs +++ b/crates/celox/tests/frontends/systemverilog/processes.rs @@ -1310,6 +1310,30 @@ fn rejects_nonblocking_assignments_in_tasks_a_process_calls() { ); } +/// `Simulation::settle` resumes the processes a host write woke at the +/// current time, as a simulator's settle step does, without advancing time. +#[test] +fn settle_resumes_the_processes_a_host_write_wakes() { + let source = r#" + module Top(input logic go, output logic [7:0] seen); + initial begin + seen = 8'd0; + wait (go); + seen = 8'd1; + #0 seen = 8'd2; + end + endmodule + "#; + let mut sim = simulation(source); + let (go, seen) = (sim.signal("go"), sim.signal("seen")); + assert_eq!(sim.step().unwrap(), Some(0)); + assert_eq!(sim.get(seen), 0u8.into()); + sim.set_wide(go, 1u8.into()); + sim.settle().unwrap(); + assert_eq!(sim.get(seen), 2u8.into()); + assert_eq!(sim.time(), 0); +} + #[test] fn review_rejects_impure_wait_conditions_and_static_event_locals() { let source = r#"module Top(input bit go); diff --git a/crates/celox/tests/frontends/systemverilog/suite.rs b/crates/celox/tests/frontends/systemverilog/suite.rs index 2e3578f14a4..24c289786a5 100644 --- a/crates/celox/tests/frontends/systemverilog/suite.rs +++ b/crates/celox/tests/frontends/systemverilog/suite.rs @@ -1,10 +1,160 @@ //! Runs SystemVerilog suite cases on the Celox backends. -use celox::{BigUint, SimBackend, Simulator}; +use celox::{BigUint, RuntimeEvent, SimBackend, Simulation, Simulator}; use celox_test_suite::{Backend, CompilationRejected, Design, Result, SignalPath}; struct CeloxBackend(Simulator); +/// A timed case: the design's own processes and clocks run. +struct TimedBackend(Simulation, Vec, bool); +impl TimedBackend { + fn new(sim: Simulation) -> Self { + Self(sim, Vec::new(), false) + } + fn capture_events(&mut self) -> Result<()> { + let events = self.0.drain_runtime_events(); + self.2 |= events + .iter() + .any(|event| matches!(event, RuntimeEvent::Finish)); + let error = events.iter().find_map(|event| match event { + RuntimeEvent::AssertFatal { message } => Some(format!( + "fatal assertion: {}", + String::from_utf8(message.clone()).unwrap_or_else(|_| format!("{message:?}")) + )), + RuntimeEvent::AssertContinue { message } => Some(format!( + "failed assertion: {}", + String::from_utf8(message.clone()).unwrap_or_else(|_| format!("{message:?}")) + )), + RuntimeEvent::Missed { count } => Some(format!("{count} runtime events were missed")), + _ => None, + }); + self.1.extend(events); + if let Some(error) = error { + Err(error.into()) + } else { + Ok(()) + } + } + fn settle_checked(&mut self) -> Result<()> { + let already_finished = self.finished(); + self.0.settle()?; + self.capture_events()?; + if !already_finished && self.finished() { + return Err("the design finished outside run_to_finish during settling".into()); + } + Ok(()) + } + fn finished(&self) -> bool { + self.0.is_finished() || self.2 + } +} + +fn signal_of(sim: &Simulation, path: &SignalPath) -> celox::SignalRef { + let instances: Vec<_> = path + .instances + .iter() + .map(|i| (i.name.as_str(), i.index.unwrap_or(0))) + .collect(); + sim.child_signal(&instances, &path.name) +} + +fn collect_output(events: Vec) -> Result> { + let mut output = 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 = signal_of(&self.0, path); + if mask == BigUint::default() { + self.0.set_wide(signal, payload); + } else { + self.0.set_four_state(signal, payload, mask); + } + Ok(()) + } + + fn read(&mut self, path: &SignalPath) -> Result<(BigUint, BigUint)> { + self.settle_checked()?; + let signal = signal_of(&self.0, path); + Ok(self.0.get_four_state(signal)) + } + + /// Settling also resumes the processes the writes woke, as the external + /// simulators' settle step does. + fn eval_comb(&mut self) -> Result<()> { + self.settle_checked()?; + Ok(()) + } + + 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.settle_checked()?; + collect_output(std::mem::take(&mut self.1)) + } + + fn run_until(&mut self, time: u64) -> Result<()> { + let now = self.0.time(); + if time < now { + return Err(format!("run_until {time}: the simulation is already at {now}").into()); + } + self.0.settle()?; + self.0.run_until(time)?; + self.capture_events()?; + if self.finished() { + return Err(format!( + "run_until {time}: the design finished the simulation at {}", + self.0.time() + ) + .into()); + } + Ok(()) + } + + fn run_to_finish(&mut self) -> Result<()> { + // Draining dirty state would evaluate staged writes before this + // operation begins. Check prior finish, then settle within the run. + if self.finished() { + return Err( + "run_to_finish: the design already finished before the operation began".into(), + ); + } + self.0.settle()?; + self.capture_events()?; + while !self.finished() { + let step = self.0.step()?; + self.capture_events()?; + if step.is_none() { + break; + } + } + if !self.finished() { + return Err( + "run_to_finish: the simulation ran out of events before a process finished it" + .into(), + ); + } + Ok(()) + } +} + impl CeloxBackend { fn signal(&self, path: &SignalPath) -> celox::SignalRef { let instances: Vec<_> = path @@ -40,31 +190,41 @@ 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 { + let builder = design.parameters.iter().fold( + Simulation::from_sv_sources(sources, &design.top).four_state(design.four_state), + |builder, (name, value)| builder.param(name, *value), + ); + return Ok(match backend { + "native" => Box::new(TimedBackend::new(builder.build_native()?)), + "cranelift" => Box::new(TimedBackend::new(builder.build_cranelift()?)), + "native-parallel" => Box::new(TimedBackend::new( + builder + .threads(4) + .parallel_partition(celox::ParallelPartition::Always) + .build_native()?, + )), + "cranelift-parallel" => Box::new(TimedBackend::new( + builder + .threads(4) + .parallel_partition(celox::ParallelPartition::Always) + .build_cranelift()?, + )), + "wasm" => Box::new(TimedBackend::new(builder.build_wasm()?)), + _ => return Err(format!("unknown backend: {backend}").into()), + }); + } let builder = design.parameters.iter().fold( Simulator::from_sv_sources(sources, &design.top).four_state(design.four_state), |builder, (name, value)| builder.param(name, *value), @@ -122,3 +282,164 @@ pub fn run_case(name: &'static str, backend: &'static str) { .unwrap_or_else(|panic| std::panic::resume_unwind(panic)); }); } + +#[test] +fn run_to_finish_reaches_the_last_scheduler_timestamp() { + let source = "module Top(output bit done); initial begin #(64'hffffffffffffffff); done = 1; $finish; end endmodule"; + let simulation = + celox::Simulation::from_sv_sources(vec![(source, std::path::Path::new("last.sv"))], "Top") + .build() + .unwrap(); + let mut backend = TimedBackend::new(simulation); + backend.run_to_finish().unwrap(); + assert_eq!(backend.0.time(), u64::MAX); + assert_eq!(backend.0.get(backend.0.signal("done")), 1u8.into()); +} + +#[test] +fn run_to_finish_rejects_a_finish_during_an_earlier_settle() { + for operation in 0..3 { + let source = "module Top(input bit go, output bit done); initial begin wait(go); done=1; $finish; end endmodule"; + let simulation = + Simulation::from_sv_sources(vec![(source, std::path::Path::new("early.sv"))], "Top") + .build() + .unwrap(); + let mut backend = TimedBackend::new(simulation); + backend.run_until(0).unwrap(); + let go = backend.0.signal("go"); + backend.0.set_wide(go, 1u8.into()); + match operation { + 0 => assert!( + backend + .eval_comb() + .unwrap_err() + .to_string() + .contains("finished outside") + ), + 1 => { + backend + .read(&SignalPath { + instances: Vec::new(), + name: "done".into(), + }) + .unwrap_err(); + } + _ => { + assert!( + backend + .take_output() + .unwrap_err() + .to_string() + .contains("finished outside") + ); + } + } + assert!( + backend + .run_to_finish() + .unwrap_err() + .to_string() + .contains("already finished") + ); + } +} + +#[test] +fn run_until_settles_a_host_edge_without_a_runtime_process() { + let source = "module Top(input bit clk);always_ff @(posedge clk)$finish;endmodule"; + for name in [ + "native", + "cranelift", + "native-parallel", + "cranelift-parallel", + "wasm", + ] { + let design = celox_test_suite::load_group( + "finish-edge.vtest", + &format!( + "(group protocol (category sequential))(case finish (source \"finish-edge.sv\" #\"{source}\"#)(top Top)(set clk 1)(run_until 0))" + ), + celox_test_suite::no_std_library, + )[0]; + let mut backend = build(&design.design(), name).unwrap(); + backend + .write( + &SignalPath { + instances: Vec::new(), + name: "clk".into(), + }, + 1u8.into(), + 0u8.into(), + ) + .unwrap(); + assert!( + backend + .run_until(0) + .unwrap_err() + .to_string() + .contains("finished"), + "{name}" + ); + } +} + +#[test] +fn buffered_host_fatal_cannot_be_hidden_by_a_later_finish() { + let source = "module Top(input bit go);always_comb if(go)$fatal(1,\"host fatal\");initial #1 $finish;endmodule"; + let text = format!( + "(group protocol (category sequential))(case fatal (source \"fatal.sv\" #\"{source}\"#)(top Top)(set go 1)(run_to_finish))" + ); + let case = + celox_test_suite::load_group("fatal.vtest", &text, celox_test_suite::no_std_library)[0]; + for name in [ + "native", + "cranelift", + "native-parallel", + "cranelift-parallel", + "wasm", + ] { + let mut backend = build(&case.design(), name).unwrap(); + backend + .write( + &SignalPath { + instances: Vec::new(), + name: "go".into(), + }, + 1u8.into(), + 0u8.into(), + ) + .unwrap(); + assert!( + backend + .run_to_finish() + .unwrap_err() + .to_string() + .contains("fatal"), + "{name}" + ); + } +} + +#[test] +fn continuing_assertions_cannot_pass_a_timed_finish() { + let source = "module Top;initial begin #1;$error(\"timed failure\");#1;$finish;end endmodule"; + let text = format!( + "(group protocol (category sequential))(case assertion (source \"assertion.sv\" #\"{source}\"#)(top Top)(run_to_finish))" + ); + let case = + celox_test_suite::load_group("assertion.vtest", &text, celox_test_suite::no_std_library)[0]; + for name in [ + "native", + "cranelift", + "native-parallel", + "cranelift-parallel", + "wasm", + ] { + let mut backend = build(&case.design(), name).unwrap(); + let result = backend.run_to_finish(); + assert!( + result.unwrap_err().to_string().contains("timed failure"), + "{name}" + ); + } +} diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs new file mode 100644 index 00000000000..c67f43c4330 --- /dev/null +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -0,0 +1,331 @@ +//! Shared timing-control cases: `#delay`, `@(event)` and `wait` in +//! processes, driven through the timed `Simulation` on every backend. + +sv_backends! { + fn delays_resume_initial_blocks_at_later_times(sim) { + @case "timing::delays_resume_initial_blocks_at_later_times"; + } + + fn always_with_a_delay_generates_a_clock(sim) { + @case "timing::always_with_a_delay_generates_a_clock"; + } + + fn edge_waits_resume_before_the_registers_of_that_edge_update(sim) { + @case "timing::edge_waits_resume_before_the_registers_of_that_edge_update"; + } + + fn any_change_waits_wake_on_every_value_change(sim) { + @case "timing::any_change_waits_wake_on_every_value_change"; + } + + fn wait_statements_block_until_their_condition_holds(sim) { + @case "timing::wait_statements_block_until_their_condition_holds"; + } + + fn level_sensitive_always_runs_as_a_process(sim) { + @case "timing::level_sensitive_always_runs_as_a_process"; + } + + fn processes_wake_each_other_at_the_same_time(sim) { + @case "timing::processes_wake_each_other_at_the_same_time"; + } + + fn tasks_with_timing_controls_run_in_processes(sim) { + @case "timing::tasks_with_timing_controls_run_in_processes"; + } + + fn edge_waits_see_the_signals_the_script_drives(sim) { + @case "timing::edge_waits_see_the_signals_the_script_drives"; + } + + fn finish_in_an_always_process_ends_the_simulation(sim) { + @case "timing::finish_in_an_always_process_ends_the_simulation"; + } + + fn waiting_processes_do_not_keep_an_idle_simulation_running(sim) { + @case "timing::waiting_processes_do_not_keep_an_idle_simulation_running"; + } + + fn four_state_edges_count_transitions_through_unknown(sim) { + @case "timing::four_state_edges_count_transitions_through_unknown"; + } + + fn unknown_delays_and_conditions_count_as_zero_and_false(sim) { + @case "timing::unknown_delays_and_conditions_count_as_zero_and_false"; + } + + fn host_inputs_are_staged_before_time_zero_initial_blocks(sim) { + @case "timing::host_inputs_are_staged_before_time_zero_initial_blocks"; + } + + fn eval_starts_due_time_zero_processes(sim) { + @case "timing::eval_starts_due_time_zero_processes"; + } + + fn direct_reads_settle_waiting_processes(sim) { + @case "timing::direct_reads_settle_waiting_processes"; + } + + fn output_reads_settle_waiting_processes(sim) { + @case "timing::output_reads_settle_waiting_processes"; + } + + fn run_until_drains_target_time_before_later_writes(sim) { + @case "timing::run_until_drains_target_time_before_later_writes"; + } + + fn repeated_settles_do_not_advance_design_time(sim) { + @case "timing::repeated_settles_do_not_advance_design_time"; + } + + fn run_to_finish_has_no_simulated_time_deadline(sim) { + @case "timing::run_to_finish_has_no_simulated_time_deadline"; + } +} + +sv_backends! { + fn plain_always_processes_start_after_host_inputs(sim) { + @case "timing::plain_always_processes_start_after_host_inputs"; + } + fn timed_control_names_do_not_collide_with_design_names(sim) { + @case "timing::timed_control_names_do_not_collide_with_design_names"; + } +} + +sv_backends! { + fn event_always_processes_start_after_host_inputs(sim) { + @case "timing::event_always_processes_start_after_host_inputs"; + } +} + +sv_backends! { + fn ff_actions_wait_for_staged_startup(sim) { + @case "timing::ff_actions_wait_for_staged_startup"; + } + fn ff_startup_does_not_invent_an_unstaged_edge(sim) { + @case "timing::ff_startup_does_not_invent_an_unstaged_edge"; + } +} + +sv_backends! { + fn ff_startup_preserves_nested_if_case_actions(sim) { + @case "timing::ff_startup_preserves_nested_if_case_actions"; + } +} + +sv_backends! { + fn qualified_ff_startup_actions(sim) { @case "timing::qualified_ff_startup_actions"; } + fn ordinary_edge_always_retains_staged_startup_edges(sim) { @case "timing::ordinary_edge_always_retains_staged_startup_edges"; } + fn macro_ff_startup_actions(sim) { @case "timing::macro_ff_startup_actions"; } + fn macro_argument_process_keywords_are_expanded_before_staging(sim) { @case "timing::macro_argument_process_keywords_are_expanded_before_staging"; } + fn do_while_ff_bodies_are_staged_in_full(sim) { @case "timing::do_while_ff_bodies_are_staged_in_full"; } + fn wildcard_always_blocks_settle_staged_inputs(sim) { @case "timing::wildcard_always_blocks_settle_staged_inputs"; } + fn timed_edge_always_bodies_do_not_replay_setup_edges(sim) { @case "timing::timed_edge_always_bodies_do_not_replay_setup_edges"; } + fn timed_edge_always_task_calls_do_not_replay_setup_edges(sim) { @case "timing::timed_edge_always_task_calls_do_not_replay_setup_edges"; } + fn imported_timed_tasks_do_not_replay_setup_edges(sim) { @case "timing::imported_timed_tasks_do_not_replay_setup_edges"; } + fn untimed_local_tasks_shadow_timed_tasks_in_other_scopes(sim) { @case "timing::untimed_local_tasks_shadow_timed_tasks_in_other_scopes"; } + fn automatic_module_ff_staging_keeps_its_state(sim) { @case "timing::automatic_module_ff_staging_keeps_its_state"; } + fn control_members_do_not_pollute_user_package_imports(sim) { @case "timing::control_members_do_not_pollute_user_package_imports"; } + fn blocking_ff_stores_are_visible_before_inactive_work(sim) { @case "timing::blocking_ff_stores_are_visible_before_inactive_work"; } + fn nonblocking_ff_stores_remain_pending_during_inactive_work(sim) { @case "timing::nonblocking_ff_stores_remain_pending_during_inactive_work"; } + fn mixed_ff_stores_keep_their_active_and_nba_values(sim) { @case "timing::mixed_ff_stores_keep_their_active_and_nba_values"; } + fn single_item_generate_ff_rewrites_keep_their_else(sim) { @case "timing::single_item_generate_ff_rewrites_keep_their_else"; } +} + +sv_backends! { + fn immediate_assertion_ff_keeps_both_actions(sim) { @case "timing::immediate_assertion_ff_keeps_both_actions"; } + fn printed_finish_notice_is_design_output(sim) { @case "timing::printed_finish_notice_is_design_output"; } + fn combinational_finish_ends_timed_execution(sim) { @case "timing::combinational_finish_ends_timed_execution"; } +} + +sv_backends! { + fn local_function_shadows_unrelated_timed_task(sim) { @case "timing::local_function_shadows_unrelated_timed_task"; } + fn explicit_timed_import_overrides_earlier_wildcard(sim) { @case "timing::explicit_timed_import_overrides_earlier_wildcard"; } +} + +sv_backends! { + fn else_prefixed_instance_is_not_an_else_action(sim) { @case "timing::else_prefixed_instance_is_not_an_else_action"; } + fn nested_imports_do_not_leak_into_module_edge_processes(sim) { @case "timing::nested_imports_do_not_leak_into_module_edge_processes"; } +} + +sv_backends! { + fn single_item_case_generate_ff_is_staged_together(sim){@case "timing::single_item_case_generate_ff_is_staged_together";} + fn timed_expansion_preserves_adapter_macros(sim){@case "timing::timed_expansion_preserves_adapter_macros";} +} + +sv_backends! { + fn comment_semicolons_in_function_headers_preserve_setup_edges(sim){@case "timing::comment_semicolons_in_function_headers_preserve_setup_edges";} +} + +sv_backends! { + fn import_comment_commas_do_not_change_visible_callables(sim){@case "timing::import_comment_commas_do_not_change_visible_callables";} +} + +sv_backends! { + fn escaped_import_commas_keep_explicit_callable_selection(sim){@case "timing::escaped_import_commas_keep_explicit_callable_selection";} +} + +sv_backends! { + fn parameterized_interface_methods_keep_setup_edges(sim){@case "timing::parameterized_interface_methods_keep_setup_edges";} +} + +sv_backends! { + fn blocking_concatenation_publishes_one_event_update(sim) { + @case "timing::blocking_concatenation_publishes_one_event_update"; + } + fn finite_active_feedback_preserves_convergence(sim) { + @case "timing::finite_active_feedback_preserves_convergence"; + } +} + +sv_backends! { fn interface_modport_methods_keep_setup_edges(sim) { @case "timing::interface_modport_methods_keep_setup_edges"; } } + +sv_backends! { fn generic_interface_methods_keep_setup_edges(sim) { @case "timing::generic_interface_methods_keep_setup_edges"; } } + +sv_backends! { fn inherited_interface_methods_keep_setup_edges(sim) { @case "timing::inherited_interface_methods_keep_setup_edges"; } } + +sv_backends! { fn pure_function_rhs_preserves_distinct_write_times(sim) { @case "timing::pure_function_rhs_preserves_distinct_write_times"; } } + +sv_backends! { fn conditional_writes_preserve_distinct_activation_times(sim) { @case "timing::conditional_writes_preserve_distinct_activation_times"; } } + +sv_backends! { fn case_writes_preserve_distinct_activation_times(sim) { @case "timing::case_writes_preserve_distinct_activation_times"; } } + +sv_backends! { fn staged_wildcard_finish_waits_for_startup(sim) { @case "timing::staged_wildcard_finish_waits_for_startup"; } } + +sv_backends! { fn constant_repeat_writes_preserve_distinct_activation_times(sim) { @case "timing::constant_repeat_writes_preserve_distinct_activation_times"; } } + +sv_backends! { fn separate_comb_assignments_preserve_selected_dependencies(sim) { @case "timing::separate_comb_assignments_preserve_selected_dependencies"; } } + +sv_backends! { fn staged_always_comb_finish_ignores_initial_inputs(sim) { @case "timing::staged_always_comb_finish_ignores_initial_inputs"; } } + +sv_backends! { fn constant_for_writes_preserve_distinct_activation_times(sim) { @case "timing::constant_for_writes_preserve_distinct_activation_times"; } } + +sv_backends! { fn untimed_tasks_preserve_distinct_activation_times(sim) { @case "timing::untimed_tasks_preserve_distinct_activation_times"; } } + +sv_backends! { fn untimed_task_copyback_preserves_distinct_activation_times(sim) { @case "timing::untimed_task_copyback_preserves_distinct_activation_times"; } } + +sv_backends! { fn statically_satisfied_waits_preserve_distinct_activation_times(sim) { @case "timing::statically_satisfied_waits_preserve_distinct_activation_times"; } } +sv_backends! { fn nba_woken_waiters_sample_before_continuations(sim) { @case "timing::nba_woken_waiters_sample_before_continuations"; } } +sv_backends! { fn staged_always_comb_side_effects_wait_for_setup(sim) { @case "timing::staged_always_comb_side_effects_wait_for_setup"; } } + +sv_backends! { + fn negative_repeat_counts_do_not_run_the_body(sim) { + @case "timing::negative_repeat_counts_do_not_run_the_body"; + } +} + +sv_backends! { + fn staged_wildcard_side_effects_wait_for_setup(sim) { + @case "timing::staged_wildcard_side_effects_wait_for_setup"; + } +} + +sv_backends! { + fn staged_continuous_side_effects_wait_for_setup(sim) { + @case "timing::staged_continuous_side_effects_wait_for_setup"; + } + +} + +sv_backends! { + fn continuous_call_drivers_preserve_assignment_context(sim) { + @case "timing::continuous_call_drivers_preserve_assignment_context"; + } +} + +sv_backends! { fn blocking_ff_woken_waiters_sample_before_continuations(sim) { + @case "timing::blocking_ff_woken_waiters_sample_before_continuations"; +} } + +sv_backends! { fn direct_blocking_ff_woken_waiters_sample_before_continuations(sim) { + @case "timing::direct_blocking_ff_woken_waiters_sample_before_continuations"; +} } + +sv_backends! { fn variable_initializers_observe_staged_inputs_before_initial_blocks(sim) { + @case "timing::variable_initializers_observe_staged_inputs_before_initial_blocks"; +} } + +sv_backends! { fn constant_variable_initializers_do_not_invent_clock_edges(sim) { + @case "timing::constant_variable_initializers_do_not_invent_clock_edges"; +} } + +sv_backends! { fn variable_initializer_dependencies_and_automatic_locals_preserve_order(sim) { + @case "timing::variable_initializer_dependencies_and_automatic_locals_preserve_order"; +} } +sv_backends! { fn variable_initializer_finish_prevents_procedural_start(sim) { + @case "timing::variable_initializer_finish_prevents_procedural_start"; +} } + +sv_backends! { fn escaped_continuous_destinations_preserve_identifier_terminators(sim) { + @case "timing::escaped_continuous_destinations_preserve_identifier_terminators"; +} } + +sv_backends! { fn repeated_active_edges_share_one_nba_batch(sim) { + @case "timing::repeated_active_edges_share_one_nba_batch"; +} } + +sv_backends! { fn false_wait_preserves_separate_hierarchical_write_times(sim) { + @case "timing::false_wait_preserves_separate_hierarchical_write_times"; +} } + +sv_backends! { fn always_timed_task_without_inline_timing_executes(sim) { + @case "timing::always_timed_task_without_inline_timing_executes"; +} } + +sv_backends! { fn initializer_function_effects_are_scoped_to_each_module(sim) { + @case "timing::initializer_function_effects_are_scoped_to_each_module"; +} } + +sv_backends! { fn initializer_default_argument_effects_run_during_initialization(sim) { + @case "timing::initializer_default_argument_effects_run_during_initialization"; +} } + +sv_backends! { fn continuous_zero_argument_function_tracks_global_reads(sim) { + @case "timing::continuous_zero_argument_function_tracks_global_reads"; +} } + +sv_backends! { fn initializer_explicit_arguments_skip_effectful_defaults(sim) { + @case "timing::initializer_explicit_arguments_skip_effectful_defaults"; +} } + +sv_backends! { fn constant_continuous_function_edges_match_staged_startup(sim) { + @case "timing::constant_continuous_function_edges_match_staged_startup"; +} } + +sv_backends! { fn escaped_initializer_function_effects_finish_during_initialization(sim) { + @case "timing::escaped_initializer_function_effects_finish_during_initialization"; +} } + +sv_backends! { fn constant_comb_if_discards_unreachable_pulse_branch(sim) { + @case "timing::constant_comb_if_discards_unreachable_pulse_branch"; +} } + +sv_backends! { fn constant_child_ff_case_discards_unreachable_pulse_arm(sim) { + @case "timing::constant_child_ff_case_discards_unreachable_pulse_arm"; +} } + +sv_backends! { fn typed_continuous_enum_drivers_preserve_assignment_types(sim) { + @case "timing::typed_continuous_enum_drivers_preserve_assignment_types"; +} } + +sv_backends! { fn constant_child_loop_exit_keeps_one_write(sim) { + @case "timing::constant_child_loop_exit_keeps_one_write"; +} } + +sv_backends! { fn constant_child_case_exit_keeps_one_write(sim) { + @case "timing::constant_child_case_exit_keeps_one_write"; +} } + +sv_backends! { fn four_state_child_if_keeps_one_write(sim) { + @case "timing::four_state_child_if_keeps_one_write"; +} } + +sv_backends! {fn selected_child_dependency_ignores_unreachable_reads(sim) { @case "timing::selected_child_dependency_ignores_unreachable_reads"; } } + +sv_backends! {fn selected_child_loop_exit_ignores_unreachable_suffix(sim) { @case "timing::selected_child_loop_exit_ignores_unreachable_suffix"; } } + +sv_backends! {fn finite_process_loop_preserves_continuation_values(sim) { @case "timing::finite_process_loop_preserves_continuation_values"; } } + +sv_backends! {fn zero_trip_child_dependencies_ignore_body_and_step(sim) { @case "timing::zero_trip_child_dependencies_ignore_body_and_step"; } } + +sv_backends! {fn cross_file_package_initializers_keep_static_clock_baseline(sim) { @case "timing::cross_file_package_initializers_keep_static_clock_baseline"; } } diff --git a/crates/celox/tests/systemverilog.rs b/crates/celox/tests/systemverilog.rs index d6c4e5cc91c..95fde02a7c1 100644 --- a/crates/celox/tests/systemverilog.rs +++ b/crates/celox/tests/systemverilog.rs @@ -128,6 +128,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; @@ -213,3 +215,56 @@ fn simulates_systemverilog_always_ff() { sim.tick(clk).unwrap(); assert_eq!(sim.get(q), 1u8.into()); } + +sv_backends! { + fn multiple_import_items_preserve_untimed_edges(sim) { @case "timing::multiple_import_items_preserve_untimed_edges"; } + fn escaped_timed_tasks_do_not_replay_setup_edges(sim) { @case "timing::escaped_timed_tasks_do_not_replay_setup_edges"; } + fn control_names_do_not_rewrite_the_dut_type(sim) { @case "timing::control_names_do_not_rewrite_the_dut_type"; } +} + +sv_backends! { + fn attributes_preserve_single_generate_arms(sim) { @case "timing::attributes_preserve_single_generate_arms"; } + fn adapter_defines_preserve_line_macros(sim) { @case "timing::adapter_defines_preserve_line_macros"; } + fn callable_timing_keeps_generate_scope(sim) { @case "timing::callable_timing_keeps_generate_scope"; } + fn single_item_generate_imports_do_not_leak(sim) { @case "timing::single_item_generate_imports_do_not_leak"; } + fn exported_untimed_tasks_keep_setup_edges(sim) { @case "timing::exported_untimed_tasks_keep_setup_edges"; } + fn qualified_unit_tasks_keep_setup_edges(sim) { @case "timing::qualified_unit_tasks_keep_setup_edges"; } +} + +sv_backends! { + fn timed_file_macros_keep_each_source_path(sim) { @case "timing::timed_file_macros_keep_each_source_path"; } + fn escaped_identifiers_do_not_collide_with_control_names(sim) { @case "timing::escaped_identifiers_do_not_collide_with_control_names"; } +} + +sv_backends! { + fn function_return_bounds_do_not_shadow_local_calls(sim) { @case "timing::function_return_bounds_do_not_shadow_local_calls"; } + fn control_shaped_display_is_design_output(sim) { @case "timing::control_shaped_display_is_design_output"; } +} + +sv_backends! { + fn staged_ff_edge_can_finish_without_scheduled_work(sim) { @case "timing::staged_ff_edge_can_finish_without_scheduled_work"; } + fn coalesced_setup_writes_do_not_invent_ff_edges(sim) { @case "timing::coalesced_setup_writes_do_not_invent_ff_edges"; } +} + +sv_backends! { + fn computed_edge_always_processes_arm_after_setup(sim) { @case "timing::computed_edge_always_processes_arm_after_setup"; } + fn non_ff_multiple_edge_always_processes_arm_after_setup(sim) { @case "timing::non_ff_multiple_edge_always_processes_arm_after_setup"; } +} + +sv_backends! { + fn timed_calls_after_forever_do_not_replay_setup_edges(sim) { @case "timing::timed_calls_after_forever_do_not_replay_setup_edges"; } + fn parenthesized_ff_event_leaves_preserve_setup_edges(sim) { @case "timing::parenthesized_ff_event_leaves_preserve_setup_edges"; } +} +sv_backends! { + fn named_arguments_do_not_invent_timed_calls(sim) { @case "timing::named_arguments_do_not_invent_timed_calls"; } +} +sv_backends! { + fn timed_calls_after_do_do_not_replay_setup_edges(sim) { @case "timing::timed_calls_after_do_do_not_replay_setup_edges"; } +} +sv_backends! { + fn timed_calls_after_named_blocks_do_not_replay_setup_edges(sim) { @case "timing::timed_calls_after_named_blocks_do_not_replay_setup_edges"; } +} +sv_backends! { + fn timed_calls_after_endcase_do_not_replay_setup_edges(sim) { @case "timing::timed_calls_after_endcase_do_not_replay_setup_edges"; } + fn inactive_time_directives_do_not_change_scheduler_units(sim) { @case "timing::inactive_time_directives_do_not_change_scheduler_units"; } +} diff --git a/crates/celox/tests/vcd.rs b/crates/celox/tests/vcd.rs index ef85a06d05a..eff566c2131 100644 --- a/crates/celox/tests/vcd.rs +++ b/crates/celox/tests/vcd.rs @@ -558,6 +558,14 @@ mod activity { if step == 2 { let rst = sim.signal("rst"); sim.modify(|io| io.set(rst, 1u8)).unwrap(); + // An inactive host transition settles at the current time + // without fabricating a scheduler event. Sample that boundary + // in both writers before step advances to the next event. + sim.dump(sim.time()); + let (ptr, size) = sim.memory_as_ptr(); + reference + .dump(sim.time(), unsafe { std::slice::from_raw_parts(ptr, size) }) + .unwrap(); } let time = sim.step().unwrap().unwrap(); sim.dump(time);