From 3837df45d9e5b57551948db6e96bc9101b2417a8 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 24 Oct 2026 15:57:06 +0900 Subject: [PATCH] fix(sv)!: give reports the time they are issued at Store the issuing simulation time in severity report records, so draining several slots together preserves each report's original time. Keep timestamp arguments out of formatted messages and combinational sensitivity. RuntimeEventSite gains timestamp_arg; the native image container version is 44. Settle pending combinational reports before leaving their time, including when no event is scheduled. A $finish or $fatal during that settle runs final procedures and leaves the simulation at its termination time. Propagate terminal halts through the host boundary, preserve the original fatal diagnostic, and allow a $stop in a final procedure to suspend and resume without advancing time. Regression coverage exercises run_until, step, advance_to and bounded runs, with and without later clocks/report watching, across interpreter, native, Cranelift and WASM. The new regressions reproduced missing termination/finalization before the review fix. Validation: report, VCD, stop/resume and deferred-assertion integration tests (181 passed); celox/runtime unit tests (308 passed); formatting and affected-crate all-targets Clippy with -D warnings. Change-Id: I865a9dced4edb57838192ef0ed22fc22618d835a --- crates/celox-design/src/lib.rs | 6 + crates/celox-frontend-sv/src/lowering/comb.rs | 14 ++ crates/celox-frontend-sv/src/lowering/ff.rs | 14 ++ .../celox-frontend-veryl/src/lowering/ff.rs | 1 + .../src/lowering/logic_tree/effect.rs | 1 + crates/celox-frontend-veryl/src/testbench.rs | 1 + crates/celox-runtime/src/simulation/host.rs | 8 + crates/celox-runtime/src/simulation/mod.rs | 43 +++- crates/celox-runtime/src/simulation/time.rs | 3 + crates/celox/src/backend/native/image_file.rs | 2 +- crates/celox/src/simulation.rs | 43 +++- crates/celox/src/simulator.rs | 46 ++++ crates/celox/src/simulator/host/file_io.rs | 1 + crates/celox/tests/sv_reports.rs | 208 ++++++++++++++++-- docs/guide/systemverilog-reference.md | 8 +- docs/ja/guide/systemverilog-reference.md | 5 +- 16 files changed, 374 insertions(+), 30 deletions(-) diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 9ff485fbf42..cc67b04a278 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -211,6 +211,11 @@ pub struct RuntimeEventSite { /// deferred assertions. #[serde(default)] pub deferred: Option, + /// The last argument is the simulation time at which the site issued + /// the event, which a report carries (IEEE 1800-2023 20.10). It is not + /// formatted. + #[serde(default)] + pub timestamp_arg: bool, pub arg_widths: Vec, pub arg_signed: Vec, pub arg_is_string: Vec, @@ -2226,6 +2231,7 @@ mod tests { location: None, assertion: None, deferred: None, + timestamp_arg: false, arg_widths: Vec::new(), arg_signed: Vec::new(), arg_is_string: Vec::new(), diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index 06233d06023..246447ad5c8 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -3578,6 +3578,19 @@ impl<'p, 'a> Comb<'p, 'a> { arg_widths.push(self.width(node)); captured.push(self.capture(node)?); } + // A report carries the time it is issued at (IEEE 1800-2023 20.10). + // The time does not run the process. + let timestamp_arg = matches!(kind, SystemTaskKind::Message(_) | SystemTaskKind::Fatal); + if timestamp_arg { + let time = sv::ir::Expr::Ident(self.m.time_slot()); + let (node, _) = self.eval(store, frames, &time, None)?; + arg_signed.push(false); + arg_is_string.push(false); + arg_float_precision.push(None); + arg_is_handle.push(false); + arg_widths.push(self.width(node)); + captured.push(self.capture(node)?); + } let event_kind = kind.event_kind(); let condition = self.path_condition()?; let guard = if let Some(passed) = assertion { @@ -3649,6 +3662,7 @@ impl<'p, 'a> Comb<'p, 'a> { location: report_location(site), assertion: assertion_site.cloned(), deferred, + timestamp_arg, arg_widths, arg_signed, arg_is_string, diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 93ed22832e2..6f23db2d86c 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -570,6 +570,7 @@ impl<'p, 'a> Ff<'p, 'a> { location: None, assertion: None, deferred: Some(DeferredSite::FlushPoint), + timestamp_arg: false, arg_widths: Vec::new(), arg_signed: Vec::new(), arg_is_string: Vec::new(), @@ -3761,6 +3762,18 @@ impl<'p, 'a> Ff<'p, 'a> { } } } + // A report carries the time it is issued at (IEEE 1800-2023 20.10). + let timestamp_arg = matches!(kind, SystemTaskKind::Message(_) | SystemTaskKind::Fatal); + if timestamp_arg { + let time = sv::ir::Expr::Ident(self.m.time_slot()); + let reg = self.eval(&time, None)?; + arg_widths.push(self.b.register(®).width()); + arg_signed.push(false); + arg_is_string.push(false); + arg_float_precision.push(None); + arg_is_handle.push(false); + regs.push(reg); + } // Argument effects happen before branching, and the condition register // retains the value it had before those effects. let resume = match assertion { @@ -3794,6 +3807,7 @@ impl<'p, 'a> Ff<'p, 'a> { location: report_location(site), assertion: assertion_site.cloned(), deferred, + timestamp_arg, arg_widths, arg_signed, arg_is_string, diff --git a/crates/celox-frontend-veryl/src/lowering/ff.rs b/crates/celox-frontend-veryl/src/lowering/ff.rs index 474841588f8..09a556a434a 100644 --- a/crates/celox-frontend-veryl/src/lowering/ff.rs +++ b/crates/celox-frontend-veryl/src/lowering/ff.rs @@ -556,6 +556,7 @@ impl<'a> FfParser<'a> { location: None, assertion: None, deferred: None, + timestamp_arg: false, arg_widths: value_args .iter() .map(|arg| self.get_expression_width(&arg.0)) diff --git a/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs b/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs index f3c50003647..c6164737f68 100644 --- a/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs +++ b/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs @@ -104,6 +104,7 @@ fn register_comb_runtime_event_site<'a>( location: None, assertion: None, deferred: None, + timestamp_arg: false, arg_widths: value_args .iter() .map(|arg| arg.0.comptime().r#type.total_width().unwrap_or(1)) diff --git a/crates/celox-frontend-veryl/src/testbench.rs b/crates/celox-frontend-veryl/src/testbench.rs index e94a57e8747..25089bcc76e 100644 --- a/crates/celox-frontend-veryl/src/testbench.rs +++ b/crates/celox-frontend-veryl/src/testbench.rs @@ -112,6 +112,7 @@ fn runtime_event_site_for_assert( location: None, assertion: None, deferred: None, + timestamp_arg: false, arg_widths: value_args.iter().map(assert_arg_width).collect(), arg_signed: value_args .iter() diff --git a/crates/celox-runtime/src/simulation/host.rs b/crates/celox-runtime/src/simulation/host.rs index e2c753c4181..146bc75484b 100644 --- a/crates/celox-runtime/src/simulation/host.rs +++ b/crates/celox-runtime/src/simulation/host.rs @@ -146,6 +146,14 @@ pub trait HostBoundary: UnitExecutor { fn try_end_time_slot(&mut self, _timestamp: u64) -> Result<(), Halt> { Ok(()) } + + /// Called before a run or a step moves from `timestamp` to a later time: + /// before the step of a later slot, and at the end of a run to a time + /// without work. An error ends the run there, as an error of a step + /// does, and so does a `$finish` the host ran there. + fn try_leave_time(&mut self, _timestamp: u64) -> Result<(), Halt> { + Ok(()) + } } /// How many time slots a compiled scheduler may run at once (see diff --git a/crates/celox-runtime/src/simulation/mod.rs b/crates/celox-runtime/src/simulation/mod.rs index bc1af0b2da8..4d469da3cad 100644 --- a/crates/celox-runtime/src/simulation/mod.rs +++ b/crates/celox-runtime/src/simulation/mod.rs @@ -278,7 +278,10 @@ impl SimulationState { Ok(Some(self.scheduler.time)) } // The time slot goes on when the simulation continues. - Err(Halt::Stop) => Ok(Some(self.scheduler.time)), + Err(Halt::Stop) => { + self.stopped = true; + Ok(Some(self.scheduler.time)) + } Err(Halt::Error(error)) => { if matches!(&error, SimulatorErrorCode::Fatal { .. }) { let _ = self.finalize_terminal(executor); @@ -342,6 +345,12 @@ impl SimulationState { } else { None }; + if compiled.is_some() + && next_time > self.scheduler.time + && !self.leave_time(executor)? + { + return Ok(false); + } observer.before_step(self, executor); let result = match compiled { Some(limit) => self.run_compiled(executor, limit), @@ -356,10 +365,42 @@ impl SimulationState { if self.finished { return Ok(false); } + if end > self.scheduler.time && !self.leave_time(executor)? { + return Ok(false); + } self.advance_time(executor.backend_mut(), end); Ok(true) } + /// The host's work before a run leaves the current time + /// ([`HostBoundary::try_leave_time`]). Returns `false` when it stopped + /// or finished the simulation. + fn leave_time(&mut self, executor: &mut E) -> Result + where + E: SimulationExecutor, + { + match executor.try_leave_time(self.scheduler.time) { + Ok(()) => Ok(true), + Err(Halt::Stop) => { + self.stopped = true; + Ok(false) + } + Err(Halt::Finish) => { + self.finalize_terminal(executor)?; + Ok(false) + } + Err(Halt::Error(error)) => { + if matches!(&error, SimulatorErrorCode::Fatal { .. }) { + let _ = self.finalize_terminal(executor); + return Err(error); + } + let _ = self.finish_timed_boundary(executor, self.scheduler.time); + let _ = executor.flush_output(); + Err(error) + } + } + } + /// Select the loop that runs time slots. pub fn set_scheduler_mode(&mut self, mode: SchedulerMode) { self.stats.mode = mode; diff --git a/crates/celox-runtime/src/simulation/time.rs b/crates/celox-runtime/src/simulation/time.rs index cad499b6469..e48d6ce660d 100644 --- a/crates/celox-runtime/src/simulation/time.rs +++ b/crates/celox-runtime/src/simulation/time.rs @@ -128,6 +128,9 @@ impl SimulationState { if current_time > limit { return Ok(settled); } + if current_time > self.scheduler.time { + executor.try_leave_time(self.scheduler.time)?; + } // Host writes alone: settle them, then go on to the next time. let host_only = self.host_pending && self.next_work_time() != Some(current_time); self.run_time(executor, current_time)?; diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 03eac608b15..71fc64b00c4 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 43; +const CONTAINER_VERSION: u16 = 44; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index eed84eed802..f189a1c3170 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -314,6 +314,17 @@ impl HostBoundary for Simulator { self.dump_unless_rewound(timestamp); } + /// Combinational logic still to settle belongs to `timestamp`, so its + /// reports read that time: settle it before the run moves on. + fn try_leave_time(&mut self, _timestamp: u64) -> Result<(), Halt> { + if self.timestamped_reports && self.dirty { + self.eval_comb_checked().map_err(Halt::Error)?; + self.dirty = false; + self.runtime_finish()?; + } + Ok(()) + } + /// Deferred assertions mature in the Observed and Postponed regions of /// the slot (IEEE 1800-2023 16.4). fn try_end_time_slot(&mut self, _timestamp: u64) -> Result<(), Halt> { @@ -748,7 +759,11 @@ impl Simulation { return self.watched_step(); } // With nothing scheduled, the step ends the slot too. + let was_stopped = self.is_stopped(); self.end_idle_slot(self.state.next_event_time().unwrap_or(u64::MAX))?; + if !was_stopped && self.is_stopped() { + return Ok(Some(self.time())); + } self.step_until(u64::MAX) } @@ -759,7 +774,7 @@ impl Simulation { /// run at that time. #[inline] fn end_idle_slot(&mut self, end_time: u64) -> Result<(), RuntimeErrorCode> { - if !self.simulator.host_slot_work + if (!self.simulator.host_slot_work && !self.simulator.timestamped_reports) || end_time <= self.state.time() || self.state.next_event_time() == Some(self.state.time()) { @@ -774,7 +789,8 @@ impl Simulation { let result = if self.simulator.dirty { let result = self.simulator.eval_comb_checked(); self.simulator.dirty = false; - result + // A `$finish` of the settle finishes the simulation here. + result.and_then(|()| self.sync_finish_checked()) } else { Ok(()) }; @@ -796,7 +812,7 @@ impl Simulation { while let Some(next_time) = self.state.next_event_time() { if next_time > self.state.time() { self.watch_settle()?; - if self.reports.failure.is_some() { + if self.is_finished() || self.is_stopped() || self.reports.failure.is_some() { return Ok(Some(self.state.time())); } } @@ -844,7 +860,7 @@ impl Simulation { } if next_time > self.state.time() { self.watch_settle()?; - if self.reports.failure.is_some() { + if self.is_finished() || self.is_stopped() || self.reports.failure.is_some() { return Ok(false); } } @@ -858,7 +874,7 @@ impl Simulation { } } self.watch_settle()?; - Ok(self.reports.failure.is_none()) + Ok(!self.is_stopped() && self.reports.failure.is_none()) } /// Settle combinational logic that no step settled, as after host writes @@ -877,7 +893,11 @@ impl Simulation { return Ok(()); } if self.simulator.dirty { - if let Err(error) = self.simulator.eval_comb_checked() { + if let Err(error) = self + .simulator + .eval_comb_checked() + .and_then(|()| self.sync_finish_checked()) + { self.finalize_fatal(&error); self.flush_error_output(); return Err(error); @@ -959,7 +979,11 @@ impl Simulation { return Ok(()); } } else { + let was_stopped = self.is_stopped(); self.end_idle_slot(end_time)?; + if !was_stopped && self.is_stopped() { + return Ok(()); + } } let reached = match self.shadow.take() { None => self.state.run_until(&mut self.simulator, end_time)?, @@ -1008,6 +1032,9 @@ impl Simulation { } else { self.end_idle_slot(time)?; } + if self.is_finished() || self.is_stopped() { + return Ok(()); + } self.state.advance_time(&mut self.simulator.backend, time); if let Some(shadow) = &mut self.shadow { shadow @@ -1037,7 +1064,11 @@ impl Simulation { self.run_until(end_time)?; return Ok(!self.state.is_stopped()); } + let was_stopped = self.is_stopped(); self.end_idle_slot(end_time)?; + if !was_stopped && self.is_stopped() { + return Ok(false); + } let mut steps = 0; while let Some(next_time) = self.state.next_event_time() { if next_time > end_time { diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index 5eb290bfa55..15e9737d7ac 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -167,6 +167,8 @@ mod host { /// Deferred assertions or sampled copies have work when a host /// call's time slot is over. pub(crate) host_slot_work: bool, + /// Some report site reads the time it issues its report at. + pub(crate) timestamped_reports: bool, /// Identity of the state layout, computed on first checkpoint use. pub(super) checkpoint_fingerprint: std::sync::OnceLock, /// State objects as state files name them, built on first use. @@ -304,6 +306,7 @@ mod host { } pub struct RuntimeEventDrain { + timed: bool, buffer: Arc, layout: MemoryLayout, sites: Vec, @@ -334,6 +337,7 @@ mod host { events .into_iter() .filter_map(|raw| render_raw_runtime_event(raw, &self.sites, ctx)) + .map(|event| untimed_report(event, self.timed, ctx)) .collect() } } @@ -631,6 +635,7 @@ mod host { args: &[RuntimeEventArgValue], ctx: RuntimeFormatContext<'_>, ) -> Vec { + let args = formatted_args(site, args); let Some(template) = site.template.as_deref() else { let default_spec = match site.kind { // Veryl prints arguments without a format string in hexadecimal. @@ -751,11 +756,48 @@ mod host { } } + /// Without a scheduler the simulation has no time: a report has the + /// time the host gives, not the one its site read. + fn untimed_report( + event: RuntimeEvent, + timed: bool, + ctx: RuntimeFormatContext<'_>, + ) -> RuntimeEvent { + match event { + RuntimeEvent::Report(report) if !timed => RuntimeEvent::Report(Report { + time: ctx.tb_time, + ..report + }), + event => event, + } + } + + /// The arguments of an event that its message formats: all but the + /// time of a timestamped site. + fn formatted_args<'a>( + site: &RuntimeEventSite, + args: &'a [RuntimeEventArgValue], + ) -> &'a [RuntimeEventArgValue] { + match (site.timestamp_arg, args.split_last()) { + (true, Some((_, args))) => args, + _ => args, + } + } + fn render_runtime_event( site: &RuntimeEventSite, args: &[RuntimeEventArgValue], ctx: RuntimeFormatContext<'_>, ) -> RuntimeEvent { + // The time the site issued the event, unless the host gives one. + let issued = site + .timestamp_arg + .then(|| args.last().and_then(|time| time.values.first().copied())) + .flatten(); + let ctx = RuntimeFormatContext { + tb_time: ctx.tb_time.or(issued), + ..ctx + }; let message = render_runtime_event_message(site, args, ctx); match site.kind { RuntimeEventKind::Display => RuntimeEvent::Display { message }, @@ -1025,6 +1067,7 @@ mod host { &program.runtime_schema.comb_observers, ); let sites = &program.runtime_schema.runtime_event_sites; + let timestamped_reports = sites.iter().any(|site| site.timestamp_arg); let deferred_sites = if sites.iter().any(|site| site.deferred.is_some()) { sites .iter() @@ -1084,6 +1127,7 @@ mod host { comb_deferred_groups, timed: false, host_slot_work: !deferred_sites.is_empty() || !sample_shadows.is_empty(), + timestamped_reports, sample_shadows, components: Default::default(), component_simulation: None, @@ -1429,6 +1473,7 @@ mod host { ctx, ) }) + .map(|event| untimed_report(event, self.timed, ctx)) .collect() } @@ -1715,6 +1760,7 @@ mod host { .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) .ok()?; Some(RuntimeEventDrain { + timed: self.timed, buffer, layout: self.backend.layout().clone(), sites: self.program.runtime_schema.runtime_event_sites.clone(), diff --git a/crates/celox/src/simulator/host/file_io.rs b/crates/celox/src/simulator/host/file_io.rs index 1420c5d1975..90c2d98d1da 100644 --- a/crates/celox/src/simulator/host/file_io.rs +++ b/crates/celox/src/simulator/host/file_io.rs @@ -104,6 +104,7 @@ impl Simulator { location: None, assertion: None, deferred: None, + timestamp_arg: false, arg_widths: Vec::new(), arg_signed: Vec::new(), arg_is_string: Vec::new(), diff --git a/crates/celox/tests/sv_reports.rs b/crates/celox/tests/sv_reports.rs index cceecc58a08..d7554e6b140 100644 --- a/crates/celox/tests/sv_reports.rs +++ b/crates/celox/tests/sv_reports.rs @@ -33,12 +33,24 @@ fn report( } } +/// `reports`, issued at `time`. +fn at(time: u64, reports: Vec) -> Vec { + reports + .into_iter() + .map(|report| Report { + time: Some(time), + ..report + }) + .collect() +} + macro_rules! reports { ($module:ident, $backend:ident) => { mod $module { use super::*; - /// The reports of `body` in `module Top` until time 1. + /// The reports of `body` in `module Top` until time 10, drained + /// after the run. fn reports(body: &str) -> Vec { let source = format!("`timescale 1ns/1ns\nmodule Top;\n{body}\nendmodule"); let mut sim = celox::Simulation::from_sv_sources( @@ -47,7 +59,7 @@ macro_rules! reports { ) .$backend() .unwrap(); - sim.run_until(1).unwrap(); + sim.run_until(10).unwrap(); sim.drain_runtime_events() .into_iter() .filter_map(|event| match event { @@ -68,11 +80,14 @@ macro_rules! reports { $error(\"e\");\n \ end" ), - vec![ - report(Severity::Info, "i 1", 5, None), - report(Severity::Warning, "w", 6, None), - report(Severity::Error, "e", 7, None), - ] + at( + 1, + vec![ + report(Severity::Info, "i 1", 5, None), + report(Severity::Warning, "w", 6, None), + report(Severity::Error, "e", 7, None), + ] + ) ); } @@ -91,7 +106,7 @@ macro_rules! reports { assume (!a) $info(\"assumed\");\n \ end" ), - vec![ + at(1, vec![ report( Severity::Warning, "a low", @@ -111,7 +126,7 @@ macro_rules! reports { Some((Some("c1"), Cover, Pass)) ), report(Severity::Info, "assumed", 9, Some((None, Assume, Pass))), - ] + ]) ); } @@ -131,12 +146,15 @@ macro_rules! reports { end\n \ end" ), - vec![report( - Severity::Error, - "assert failed", - 7, - Some((Some("inner"), Assert, Fail)) - )] + at( + 1, + vec![report( + Severity::Error, + "assert failed", + 7, + Some((Some("inner"), Assert, Fail)) + )] + ) ); } @@ -144,10 +162,26 @@ macro_rules! reports { fn always_comb_reports_keep_their_location() { assert_eq!( reports(" bit a;\n always_comb if (!a) $warning(\"low\");"), - vec![report(Severity::Warning, "low", 4, None)] + at(0, vec![report(Severity::Warning, "low", 4, None)]) ); } + /// A report keeps the time of its step however late the host + /// drains it (IEEE 1800-2023 20.10). + #[test] + fn reports_keep_their_time_when_drained_late() { + let times: Vec<_> = reports( + " initial begin\n \ + #1 $warning(\"w\");\n \ + #3 $error(\"e\");\n \ + end", + ) + .into_iter() + .map(|report| report.time) + .collect(); + assert_eq!(times, vec![Some(1), Some(4)]); + } + /// With `failOn`, a run stops after the time step of the first /// report of at least that severity, the next run continues, /// and every report keeps the time it was issued at. @@ -284,6 +318,145 @@ macro_rules! reports { assert!(failure.message.starts_with(b"missed "), "{failure:?}"); } + /// The initial settle of combinational logic is at time zero, + /// also when the first work is a clock edge at a later time, + /// reached by `run_until` or by `step`. + #[test] + fn initial_reports_before_a_later_first_slot_are_at_time_zero() { + let source = "`timescale 1ns/1ns\nmodule Top(input bit clk);\n \ + bit q, a;\n \ + always_ff @(posedge clk) q <= !q;\n \ + always_comb if (!a) $warning(\"low\");\nendmodule"; + for (step, watch) in [(false, false), (true, false), (false, true), (true, true)] { + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("reports.sv"))], + "Top", + ) + .$backend() + .unwrap(); + sim.add_clock("clk", 2, 5); + // Watching reports keeps the issued time too. + if watch { + sim.set_fail_on(Some(Severity::Warning)); + } + if step { + sim.step().unwrap(); + } else { + sim.run_until(10).unwrap(); + } + let times: Vec<_> = sim + .drain_runtime_events() + .into_iter() + .map(|event| match event { + celox::RuntimeEvent::Report(report) => report.time, + event => panic!("unexpected event {event:?}"), + }) + .collect(); + assert_eq!(times, vec![Some(0)], "step: {step}, watch: {watch}"); + if watch { + assert_eq!(sim.failure().and_then(|report| report.time), Some(0)); + } + } + } + + /// A leave-time settle can terminate before any scheduled slot. + /// Exercise the host entry points, report watching, and final blocks. + #[test] + fn initial_report_finish_preserves_time_and_runs_final() { + for clock in [false, true] { + for watch in [false, true] { + for entry in 0..4 { + let source = r#"`timescale 1ns/1ns +module Top(input bit clk); + bit a; + int ticks, final_calls; + always_ff @(posedge clk) ticks <= ticks + 1; + always_comb if (!a) begin $warning("initial"); $finish; end + final final_calls++; +endmodule"#; + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("reports.sv"))], "Top", + ).$backend().unwrap(); + if clock { sim.add_clock("clk", 2, 5); } + if watch { sim.set_fail_on(Some(Severity::Error)); } + match entry { + 0 => sim.run_until(10).unwrap(), + 1 => { sim.step().unwrap(); } + 2 => sim.advance_to(10).unwrap(), + _ => { sim.run_until_bounded(10, 10).unwrap(); } + } + assert_eq!(sim.time(), 0, "clock={clock}, watch={watch}, entry={entry}"); + assert!(sim.is_finished(), "clock={clock}, watch={watch}, entry={entry}"); + let final_calls = sim.signal("final_calls"); + let ticks = sim.signal("ticks"); + assert_eq!(sim.get(final_calls), 1u32.into()); + assert_eq!(sim.get(ticks), 0u32.into()); + let times: Vec<_> = sim.drain_runtime_events().into_iter() + .filter_map(|event| match event { + celox::RuntimeEvent::Report(report) => Some(report.time), + _ => None, + }).collect(); + assert_eq!(times, vec![Some(0)]); + } + } + } + } + + #[test] + fn leave_time_final_can_stop_and_resume_at_the_same_time() { + for watch in [false, true] { + for entry in 0..4 { + let source = r#"`timescale 1ns/1ns +module Top; + bit a; + int final_calls; + always_comb if (!a) begin $warning("initial"); $finish; end + final begin final_calls++; $stop; final_calls++; end +endmodule"#; + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("reports.sv"))], "Top", + ).$backend().unwrap(); + if watch { sim.set_fail_on(Some(Severity::Error)); } + for resumed in [false, true] { + match entry { + 0 => sim.run_until(10).unwrap(), + 1 => { sim.step().unwrap(); } + 2 => sim.advance_to(10).unwrap(), + _ => { sim.run_until_bounded(10, 10).unwrap(); } + } + assert_eq!(sim.time(), 0); + assert_eq!(sim.is_stopped(), !resumed, "watch={watch}, entry={entry}"); + assert_eq!(sim.is_finished(), resumed); + let final_calls = sim.signal("final_calls"); + assert_eq!(sim.get(final_calls), (if resumed { 2u32 } else { 1u32 }).into()); + } + } + } + } + + #[test] + fn initial_fatal_runs_final_before_returning_the_error() { + for clock in [false, true] { + let source = r#"`timescale 1ns/1ns +module Top(input bit clk); + bit a, q; + int final_calls; + always_ff @(posedge clk) q <= !q; + always_comb if (!a) $fatal(1, "initial"); + final final_calls++; +endmodule"#; + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("reports.sv"))], "Top", + ).$backend().unwrap(); + if clock { sim.add_clock("clk", 2, 5); } + assert!(matches!(sim.run_until(10), Err(celox::RuntimeErrorCode::Fatal { .. }))); + assert_eq!(sim.time(), 0); + assert!(sim.is_finished()); + let final_calls = sim.signal("final_calls"); + assert_eq!(sim.get(final_calls), 1u32.into()); + } + } + #[test] fn line_directives_set_the_reported_location() { let reports = reports("`line 40 \"other.sv\" 0\n initial $info(\"moved\");"); @@ -300,7 +473,8 @@ macro_rules! reports { } reports!(interpreter, build_interpreter); -reports!(cranelift, build); +#[cfg(feature = "cranelift")] +reports!(cranelift, build_cranelift); #[cfg(target_arch = "x86_64")] reports!(native, build_native); reports!(wasm, build_wasm); diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 36732b073f3..46d41f1b895 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -704,9 +704,11 @@ severity, its message, the file and line of the call as `` `__FILE__ `` and action block of an immediate assertion also names that assertion: its statement label, `assert`, `assume` or `cover`, and whether the pass or the fail action issued it. Severity tasks in subroutines the action block calls -are not attributed. `time` is the time the drain's context gives, as the VPI -host does at each callback, or the time step of the report while -`Simulation::set_fail_on` is set. `Report::render` formats a report as the VPI host +are not attributed. `time` is the simulation time at which the report was +issued, however late the host drains it, unless the drain's context gives a +time, as the VPI host does at each callback; a `Simulator` has no time and +uses only the context's. +`Report::render` formats a report as the VPI host and the `celox` command print it. Only `$error` and `$fatal` fail a `celox` run; `$fatal` also ends the simulation with an error. diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index f904894e6f7..95b86fd8b90 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -404,8 +404,9 @@ static な output 引数も、代入しない経路では以前の値を保持 スコープを持ちます。即時アサーションのアクションブロックからの報告は、そのアサーションも示します。 文ラベル、`assert` / `assume` / `cover` の別、pass と fail のどちらのアクションから出たかです。 アクションブロックが呼ぶサブルーチン内の重大度タスクは、アサーションに結び付けません。`time` は -drain のコンテキストが与える時刻で、VPI ホストはコールバックごとに与えます。`Simulation::set_fail_on` -の設定中は、報告が出たタイムステップの時刻です。`Report::render` は、 +報告を出したシミュレーション時刻で、ホストがいつ drain しても変わりません。ただし drain の +コンテキストが時刻を与える場合はそれを使います。VPI ホストはコールバックごとに与えます。 +`Simulator` は時刻を持たないので、コンテキストの時刻だけを使います。`Report::render` は、 VPI ホストと `celox` コマンドが表示する形に整形します。`celox` の実行を失敗にするのは `$error` と `$fatal` だけで、`$fatal` はさらにシミュレーションをエラーで終了します。