diff --git a/crates/celox-napi/src/lib.rs b/crates/celox-napi/src/lib.rs index af000d0e460..2f439a631e1 100644 --- a/crates/celox-napi/src/lib.rs +++ b/crates/celox-napi/src/lib.rs @@ -1780,6 +1780,140 @@ impl NativeSimulatorHandle { } } +/// A runtime event of a simulation: `$display`, `$write`, a report of a +/// severity task, `$finish`, `$stop`, or events the design's event buffer +/// overwrote before they were drained. +#[cfg(not(target_arch = "wasm32"))] +#[napi(object)] +pub struct NapiRuntimeEvent { + /// `"display"`, `"write"`, `"report"`, `"finish"`, `"stop"` or + /// `"missed"`. + pub kind: String, + pub message: Option, + /// `"info"`, `"warning"`, `"error"` or `"fatal"` for a report. + pub severity: Option, + pub time: Option, + pub scope: Option, + pub file: Option, + pub line: Option, + pub assertion: Option, + /// The number of missed events. + pub count: Option, +} + +/// The assertion whose action block issued a report. +#[cfg(not(target_arch = "wasm32"))] +#[napi(object)] +pub struct NapiAssertionSite { + pub label: Option, + /// `"assert"`, `"assume"` or `"cover"`. + pub directive: String, + /// `"none"`, `"observed"` (`#0`) or `"final"`. + pub deferral: String, + /// `"pass"` or `"fail"`. + pub outcome: String, +} + +#[cfg(not(target_arch = "wasm32"))] +fn severity_name(severity: celox::Severity) -> &'static str { + match severity { + celox::Severity::Info => "info", + celox::Severity::Warning => "warning", + celox::Severity::Error => "error", + celox::Severity::Fatal => "fatal", + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn parse_severity(name: &str) -> Result { + Ok(match name { + "info" => celox::Severity::Info, + "warning" => celox::Severity::Warning, + "error" => celox::Severity::Error, + "fatal" => celox::Severity::Fatal, + _ => { + return Err(Error::from_reason(format!( + "unknown severity `{name}`: expected info, warning, error or fatal" + ))); + } + }) +} + +#[cfg(not(target_arch = "wasm32"))] +fn napi_runtime_event(event: celox::RuntimeEvent) -> NapiRuntimeEvent { + let mut out = NapiRuntimeEvent { + kind: String::new(), + message: None, + severity: None, + time: None, + scope: None, + file: None, + line: None, + assertion: None, + count: None, + }; + match event { + celox::RuntimeEvent::Display { message } => { + out.kind = "display".into(); + out.message = Some(message.into()); + } + celox::RuntimeEvent::Write { message } => { + out.kind = "write".into(); + out.message = Some(message.into()); + } + celox::RuntimeEvent::Report(report) => { + out.kind = "report".into(); + out.severity = Some(severity_name(report.severity).into()); + out.message = Some(report.message.into()); + out.time = report.time.map(|time| time as f64); + out.scope = report.scope; + if let Some(location) = report.location { + out.file = Some(location.file); + out.line = Some(location.line as u32); + } + out.assertion = report.assertion.map(|assertion| NapiAssertionSite { + label: assertion.label, + directive: match assertion.directive { + celox::AssertionDirective::Assert => "assert", + celox::AssertionDirective::Assume => "assume", + celox::AssertionDirective::Cover => "cover", + } + .into(), + deferral: match assertion.deferral { + celox::AssertionDeferral::None => "none", + celox::AssertionDeferral::Observed => "observed", + celox::AssertionDeferral::Final => "final", + } + .into(), + outcome: match assertion.outcome { + celox::AssertionOutcome::Pass => "pass", + celox::AssertionOutcome::Fail => "fail", + } + .into(), + }); + } + celox::RuntimeEvent::Finish => out.kind = "finish".into(), + celox::RuntimeEvent::Stop => out.kind = "stop".into(), + celox::RuntimeEvent::Missed { count } => { + out.kind = "missed".into(); + out.count = Some(count as f64); + } + } + out +} + +/// The error of a run that stopped at a report of the `failOn` severity. +#[cfg(not(target_arch = "wasm32"))] +fn check_failure(sim: &celox::Simulation) -> Result<()> { + match sim.failure() { + Some(report) => Err(Error::from_reason(format!( + "failOn: {}", + String::from_utf8_lossy(&report.render()) + ))), + None => Ok(()), + } +} + /// Low-level handle wrapping a `celox::Simulation`. #[cfg(not(target_arch = "wasm32"))] #[napi] @@ -2082,7 +2216,8 @@ impl NativeSimulationHandle { .as_mut() .ok_or_else(|| Error::from_reason("Simulation has been disposed"))?; sim.run_until(end_time as u64) - .map_err(|e| Error::from_reason(format!("{}", e))) + .map_err(|e| Error::from_reason(format!("{}", e)))?; + check_failure(sim) } /// Advance until `end_time` taking at most `max_steps` steps. Returns @@ -2093,8 +2228,40 @@ impl NativeSimulationHandle { .sim .as_mut() .ok_or_else(|| Error::from_reason("Simulation has been disposed"))?; - sim.run_until_bounded(end_time as u64, max_steps as u64) - .map_err(|e| Error::from_reason(format!("{}", e))) + let reached = sim + .run_until_bounded(end_time as u64, max_steps as u64) + .map_err(|e| Error::from_reason(format!("{}", e)))?; + check_failure(sim)?; + Ok(reached) + } + + /// Take the runtime events the design emitted since the last call, in + /// emission order. + #[napi] + pub fn drain_runtime_events(&mut self) -> Result> { + let sim = self + .sim + .as_mut() + .ok_or_else(|| Error::from_reason("Simulation has been disposed"))?; + Ok(sim + .drain_runtime_events() + .into_iter() + .map(napi_runtime_event) + .collect()) + } + + /// Make runs and steps fail after the time step of a report of at least + /// `severity` (`"info"`, `"warning"`, `"error"` or `"fatal"`); `null` + /// fails only at `$fatal`. + #[napi] + pub fn set_fail_on(&mut self, severity: Option) -> Result<()> { + let severity = severity.as_deref().map(parse_severity).transpose()?; + let sim = self + .sim + .as_mut() + .ok_or_else(|| Error::from_reason("Simulation has been disposed"))?; + sim.set_fail_on(severity); + Ok(()) } /// Report that the host wrote the state through the shared memory: the @@ -2117,9 +2284,12 @@ impl NativeSimulationHandle { .sim .as_mut() .ok_or_else(|| Error::from_reason("Simulation has been disposed"))?; - sim.step() + let time = sim + .step() .map(|opt| opt.map(|t| t as f64)) - .map_err(|e| Error::from_reason(format!("{}", e))) + .map_err(|e| Error::from_reason(format!("{}", e)))?; + check_failure(sim)?; + Ok(time) } /// Returns the current simulation time. diff --git a/crates/celox-runtime/src/simulation/time.rs b/crates/celox-runtime/src/simulation/time.rs index 4bbd67c6922..32c77cebfb0 100644 --- a/crates/celox-runtime/src/simulation/time.rs +++ b/crates/celox-runtime/src/simulation/time.rs @@ -288,8 +288,9 @@ impl SimulationState { Ok(()) } - /// The next time with scheduled events or processes to run. - pub(super) fn next_work_time(&self) -> Option { + /// The next time with scheduled events or processes to run, apart + /// from host writes to settle. + pub fn next_work_time(&self) -> Option { if self.finished { return None; } diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 4023e326033..e380e44d959 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -99,6 +99,19 @@ pub struct Simulation { checked_steps: u64, /// Why [`crate::SchedulerMode::Differential`] has no shadow. unchecked: Option<&'static str>, + /// Boxed: only runs with `fail_on` use it. + reports: Box, +} + +/// Reports a simulation stops at, set by [`Simulation::set_fail_on`]. +#[derive(Debug, Default)] +struct ReportWatch { + fail_on: Option, + /// Events taken after each step while `fail_on` is set, with the time of + /// that step, for the next [`Simulation::drain_runtime_events`]. + events: Vec, + /// The first report of the last run at or above `fail_on`. + failure: Option, } impl std::fmt::Debug for Simulation { @@ -416,6 +429,7 @@ impl Simulation { shadow: None, checked_steps: 0, unchecked: None, + reports: Box::default(), }) } @@ -653,9 +667,40 @@ impl Simulation { /// Returns the new simulation time, the current time when only host /// writes were settled, or None if nothing was to do. pub fn step(&mut self) -> Result, RuntimeErrorCode> { + self.reports.failure = None; + if self.reports.fail_on.is_some() { + return self.watched_step(); + } self.step_until(u64::MAX) } + /// [`Self::step`] while [`Self::set_fail_on`] is set: a slot that only + /// settles host writes is watched before the step goes on to the next + /// time. + #[cold] + #[inline(never)] + fn watched_step(&mut self) -> Result, RuntimeErrorCode> { + let mut settled = None; + 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() { + return Ok(Some(self.state.time())); + } + } + let host_only = + self.state.host_pending() && self.state.next_work_time() != Some(next_time); + let time = self.step_until(next_time)?; + self.watch_reports(); + if !host_only || self.state.is_stopped() || self.reports.failure.is_some() { + return Ok(time); + } + settled = time; + } + self.watch_settle()?; + Ok(settled) + } + /// [`Self::step`] that, after settling host writes at the current time, /// does not advance past `end_time`. fn step_until(&mut self, end_time: u64) -> Result, RuntimeErrorCode> { @@ -671,12 +716,112 @@ impl Simulation { result } + /// The steps of a run while [`Self::set_fail_on`] is set, apart from + /// the run loop that has no reports to watch. Returns `false` when a + /// step stopped at `$stop` or at a failure, or `max_steps` ran out. + #[cold] + #[inline(never)] + fn watched_steps(&mut self, end_time: u64, max_steps: u64) -> Result { + let mut steps = 0; + while let Some(next_time) = self.state.next_event_time() { + if next_time > end_time { + break; + } + if steps >= max_steps { + return Ok(false); + } + if next_time > self.state.time() { + self.watch_settle()?; + if self.reports.failure.is_some() { + return Ok(false); + } + } + // One slot per step, so that a slot that only settles host + // writes is watched before the next runs. + self.step_until(next_time)?; + self.watch_reports(); + steps += 1; + if self.state.is_stopped() || self.reports.failure.is_some() { + return Ok(false); + } + } + self.watch_settle()?; + Ok(self.reports.failure.is_none()) + } + + /// Settle combinational logic that no step settled, as after host writes + /// that wake no process, at the current time, and watch its reports. A + /// watched run does this before it moves to a later time. + fn watch_settle(&mut self) -> Result<(), RuntimeErrorCode> { + if !self.simulator.dirty { + return Ok(()); + } + if let Err(error) = self.simulator.eval_comb_checked() { + self.flush_error_output(); + return Err(error); + } + self.simulator.dirty = false; + self.watch_reports(); + Ok(()) + } + + /// Stop [`Self::run_until`] and [`Self::run_until_bounded`] after the + /// time step of the first report of at least `severity`, which + /// [`Self::failure`] then returns. While it is set, the events of each + /// step are taken from the design's event buffer after the step and keep + /// the time of that step, so none are missed and their reports have an + /// exact time. They wait for [`Self::drain_runtime_events`]. `None` + /// stops only at `$fatal`, as before. + pub fn set_fail_on(&mut self, severity: Option) { + self.reports.fail_on = severity; + } + + /// The report the last run stopped at (see [`Self::set_fail_on`]). + /// The next run clears it. + pub fn failure(&self) -> Option<&crate::Report> { + self.reports.failure.as_ref() + } + + fn watch_reports(&mut self) { + let Some(fail_on) = self.reports.fail_on else { + return; + }; + // A step leaves combinational logic settled. + let events = + self.simulator + .drain_settled_runtime_events_with_context(crate::RuntimeFormatContext { + tb_time: Some(self.state.time()), + scope: None, + }); + if self.reports.failure.is_none() { + self.reports.failure = events.iter().find_map(|event| match event { + crate::RuntimeEvent::Report(report) if report.severity >= fail_on => { + Some(report.clone()) + } + // A lost event may have been a failure. + crate::RuntimeEvent::Missed { count } => Some(crate::Report::new( + fail_on, + format!("missed {count} runtime events").into_bytes(), + )), + _ => None, + }); + } + self.reports.events.extend(events); + } + /// Advance time and run until `end_time` (inclusive). /// Targets earlier than the current time leave time and state unchanged. /// A process that executes `$stop` returns control early, after the time /// slot of the stop, with [`Self::is_stopped`] set; calling this again - /// continues. + /// continues. A report of the severity of [`Self::set_fail_on`] returns + /// early in the same way, with [`Self::failure`] set. pub fn run_until(&mut self, end_time: u64) -> Result<(), RuntimeErrorCode> { + self.reports.failure = None; + // With reports to watch, step one slot at a time; the run below + // then only advances the time. + if self.reports.fail_on.is_some() && !self.watched_steps(end_time, u64::MAX)? { + return Ok(()); + } let reached = match self.shadow.take() { None => self.state.run_until(&mut self.simulator, end_time)?, Some(mut shadow) => { @@ -704,7 +849,7 @@ impl Simulation { /// Like [`Self::run_until`], but takes at most `max_steps` steps. /// Returns `false`, with the simulation at the time of its last step, /// when another step would be needed to reach `end_time`, including when - /// a step stopped at `$stop`. + /// a step stopped at `$stop` or at a [`Self::failure`]. pub fn run_until_bounded( &mut self, end_time: u64, @@ -713,6 +858,14 @@ impl Simulation { if end_time < self.state.time() { return Ok(true); } + self.reports.failure = None; + if self.reports.fail_on.is_some() { + if !self.watched_steps(end_time, max_steps)? { + return Ok(false); + } + self.run_until(end_time)?; + return Ok(!self.state.is_stopped()); + } let mut steps = 0; while let Some(next_time) = self.state.next_event_time() { if next_time > end_time { @@ -761,7 +914,9 @@ impl Simulation { /// Takes the runtime events (`$display`, messages, `$finish`, ...) the /// design emitted since the last call, in emission order. pub fn drain_runtime_events(&mut self) -> Vec { - self.simulator.drain_runtime_events() + let mut events = std::mem::take(&mut self.reports.events); + events.extend(self.simulator.drain_runtime_events()); + events } /// Returns the time of the next scheduled event, if any. diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index 0df0be8c0d4..dc7af3cc618 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -1188,6 +1188,19 @@ mod host { self.collect_formatted_runtime_events(ctx) } + /// Drain runtime events while combinational logic is settled, as + /// after a step of a timed simulation. + pub(crate) fn drain_settled_runtime_events_with_context( + &mut self, + ctx: RuntimeFormatContext<'_>, + ) -> Vec { + assert!( + !self.runtime_event_drain_active.load(Ordering::Acquire), + "cannot use Simulator::drain_runtime_events while a RuntimeEventDrain is active", + ); + self.collect_formatted_runtime_events(ctx) + } + fn eval_comb_for_runtime_event_drain(&mut self) -> Result<(), RuntimeErrorCode> { let (result, _) = self.eval_comb_capturing_events(); self.check_comb_backend_result(result)?; diff --git a/crates/celox/tests/sv_reports.rs b/crates/celox/tests/sv_reports.rs index d03a96c5735..cceecc58a08 100644 --- a/crates/celox/tests/sv_reports.rs +++ b/crates/celox/tests/sv_reports.rs @@ -148,6 +148,142 @@ macro_rules! reports { ); } + /// 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. + #[test] + fn fail_on_stops_runs_at_the_time_of_a_report() { + let source = "`timescale 1ns/1ns\nmodule Top;\n initial begin\n \ + #1 $warning(\"w\");\n \ + #1 $error(\"e\");\n \ + #1 $display(\"after\");\n \ + end\nendmodule"; + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("reports.sv"))], + "Top", + ) + .$backend() + .unwrap(); + sim.set_fail_on(Some(Severity::Error)); + sim.run_until(10).unwrap(); + assert_eq!(sim.time(), 2); + let failure = sim.failure().unwrap(); + assert_eq!(failure.message, b"e"); + assert_eq!(failure.time, Some(2)); + let times: Vec<_> = sim + .drain_runtime_events() + .into_iter() + .map(|event| match event { + celox::RuntimeEvent::Report(report) => (report.severity, report.time), + event => panic!("unexpected event {event:?}"), + }) + .collect(); + assert_eq!( + times, + vec![(Severity::Warning, Some(1)), (Severity::Error, Some(2))] + ); + sim.run_until(10).unwrap(); + assert!(sim.failure().is_none()); + assert_eq!(sim.time(), 10); + assert!(matches!( + sim.drain_runtime_events().as_slice(), + [celox::RuntimeEvent::Display { message }] if message == b"after" + )); + } + + /// A report caused by a host write stops the run in the slot + /// that settles the write, before later slots run. + #[test] + fn fail_on_stops_at_reports_of_host_writes() { + let source = "`timescale 1ns/1ns\nmodule Top(input logic a);\n \ + always @(posedge a) $error(\"e\");\n \ + initial #5 $display(\"later\");\nendmodule"; + for step in [false, true] { + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("reports.sv"))], + "Top", + ) + .$backend() + .unwrap(); + sim.set_fail_on(Some(Severity::Error)); + sim.run_until(2).unwrap(); + let a = sim.signal("a"); + sim.modify(|io| io.set(a, 1u8)).unwrap(); + if step { + assert_eq!(sim.step().unwrap(), Some(2)); + } else { + sim.run_until(10).unwrap(); + } + assert_eq!(sim.time(), 2); + assert_eq!(sim.failure().unwrap().time, Some(2)); + let events = sim.drain_runtime_events(); + assert!( + matches!( + events.as_slice(), + [celox::RuntimeEvent::Report(report)] if report.message == b"e" + ), + "{events:?}" + ); + } + } + + /// A report of combinational logic that a host write leaves to + /// settle, with no step at the current time, stops the run there, + /// by `run_until` or by `step`, also before later work. + #[test] + fn fail_on_stops_at_reports_of_settles_without_steps() { + for later in ["", "\n initial #5 $display(\"later\");"] { + let source = format!("`timescale 1ns/1ns\nmodule Top(input logic a);\n \ + always_comb if (a) $error(\"e\");{later}\nendmodule"); + for step in [false, true] { + let mut sim = celox::Simulation::from_sv_sources( + vec![(source.as_str(), Path::new("reports.sv"))], + "Top", + ) + .$backend() + .unwrap(); + sim.set_fail_on(Some(Severity::Error)); + sim.run_until(2).unwrap(); + let a = sim.signal("a"); + sim.modify(|io| io.set(a, 1u8)).unwrap(); + if step { + sim.step().unwrap(); + } else { + sim.run_until(10).unwrap(); + } + assert_eq!(sim.time(), 2, "step: {step}"); + let failure = sim.failure().expect("a failure"); + assert_eq!(failure.message, b"e"); + assert_eq!(failure.time, Some(2)); + sim.run_until(10).unwrap(); + assert!(sim.failure().is_none()); + assert_eq!(sim.time(), 10); + } + } + } + + /// Events lost to a full event buffer may have been failures. + #[test] + fn fail_on_stops_at_missed_events() { + let source = "`timescale 1ns/1ns\nmodule Top;\n initial begin\n \ + #1;\n \ + for (int i = 0; i < 2000; i++) $display(\"x\");\n \ + #1 $display(\"after\");\n \ + end\nendmodule"; + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("reports.sv"))], + "Top", + ) + .$backend() + .unwrap(); + sim.set_fail_on(Some(Severity::Error)); + sim.run_until(10).unwrap(); + assert_eq!(sim.time(), 1); + let failure = sim.failure().unwrap(); + assert_eq!(failure.severity, Severity::Error); + assert!(failure.message.starts_with(b"missed "), "{failure:?}"); + } + #[test] fn line_directives_set_the_reported_location() { let reports = reports("`line 40 \"other.sv\" 0\n initial $info(\"moved\");"); diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index aa944c98e4d..36efccb0a4c 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -596,7 +596,8 @@ 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. `Report::render` formats a report as the VPI host +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 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/guide/writing-tests.md b/docs/guide/writing-tests.md index 141bb6de910..95b96532fd1 100644 --- a/docs/guide/writing-tests.md +++ b/docs/guide/writing-tests.md @@ -197,6 +197,34 @@ sim.runUntil(10000); sim.runUntil(10000, { maxSteps: 500 }); ``` +### Runtime Events and Reports + +`drainRuntimeEvents()` returns what the design emitted since the last call, in +emission order: `$display` and `$write` output, `report` events of severity +tasks and failed assertions, `$finish` and `$stop`. A report has its +`severity` (`"info"`, `"warning"`, `"error"` or `"fatal"`), its `message` bytes, +and the `scope`, `file` and `line` that issued it. + +`setFailOn(severity)` makes `runUntil()`, `step()` and the waits throw after the +time step of the first report of at least that severity. While it is set, each +report keeps the `time` it was issued at. Events lost to a full event buffer +(a `missed` event) count as a failure, since they may have held one. A later +call continues the simulation. + +```typescript +sim.setFailOn("error"); +try { + sim.runUntil(10000); +} catch (error) { + // "failOn: Error: ..." at the time of the first $error +} +for (const event of sim.drainRuntimeEvents()) { + if (event.kind === "report") { + console.log(event.severity, event.time, new TextDecoder().decode(event.message)); + } +} +``` + ## Simulator Options Both `Simulator` and `Simulation` accept the following options: diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 22c756c2ce5..b4ed6ed42cf 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -389,7 +389,8 @@ static な output 引数も、代入しない経路では以前の値を保持 スコープを持ちます。即時アサーションのアクションブロックからの報告は、そのアサーションも示します。 文ラベル、`assert` / `assume` / `cover` の別、pass と fail のどちらのアクションから出たかです。 アクションブロックが呼ぶサブルーチン内の重大度タスクは、アサーションに結び付けません。`time` は -drain のコンテキストが与える時刻で、VPI ホストはコールバックごとに与えます。`Report::render` は、 +drain のコンテキストが与える時刻で、VPI ホストはコールバックごとに与えます。`Simulation::set_fail_on` +の設定中は、報告が出たタイムステップの時刻です。`Report::render` は、 VPI ホストと `celox` コマンドが表示する形に整形します。`celox` の実行を失敗にするのは `$error` と `$fatal` だけで、`$fatal` はさらにシミュレーションをエラーで終了します。 diff --git a/docs/ja/guide/writing-tests.md b/docs/ja/guide/writing-tests.md index 42b3607e8e1..f68ad81fe86 100644 --- a/docs/ja/guide/writing-tests.md +++ b/docs/ja/guide/writing-tests.md @@ -159,6 +159,32 @@ sim.runUntil(10000); sim.runUntil(10000, { maxSteps: 500 }); ``` +### 実行時イベントと報告 + +`drainRuntimeEvents()` は、前回の呼び出し以降に設計が出したものを出した順に返します。 +`$display` と `$write` の出力、重大度タスクと失敗したアサーションの `report` イベント、 +`$finish`、`$stop` です。報告は `severity`(`"info"`、`"warning"`、`"error"`、`"fatal"`)、 +`message` のバイト列、報告した `scope`、`file`、`line` を持ちます。 + +`setFailOn(severity)` を設定すると、その重大度以上の報告が最初に出たタイムステップの後で、 +`runUntil()`、`step()`、各種の待ちが例外を投げます。設定中は、各報告が出た時刻を `time` に +保持します。イベントバッファがあふれて失われたイベント(`missed` イベント)は、失敗を +含んでいた可能性があるため失敗として扱います。次の呼び出しはシミュレーションを続けます。 + +```typescript +sim.setFailOn("error"); +try { + sim.runUntil(10000); +} catch (error) { + // 最初の $error の時刻で "failOn: Error: ..." +} +for (const event of sim.drainRuntimeEvents()) { + if (event.kind === "report") { + console.log(event.severity, event.time, new TextDecoder().decode(event.message)); + } +} +``` + ## シミュレータオプション `Simulator` と `Simulation` の両方で以下のオプションが使えます: diff --git a/packages/celox/src/index.ts b/packages/celox/src/index.ts index 3130ff6815b..bf0892490af 100644 --- a/packages/celox/src/index.ts +++ b/packages/celox/src/index.ts @@ -59,9 +59,11 @@ export { runTestFromProject, runTestWithFrontendArtifact, } from "./testbench.js"; +// Runtime events // Core types /** @internal */ export type { + AssertionSite, ClockEdge, CreateResult, EventHandle, @@ -79,6 +81,9 @@ export type { OptimizeOptions, ParamOverride, PortInfo, + Report, + RuntimeEvent, + Severity, SignalLayout, SimulatorOptions, SourceFile, diff --git a/packages/celox/src/napi-helpers.ts b/packages/celox/src/napi-helpers.ts index 3ad0f006c11..5730a231ffc 100644 --- a/packages/celox/src/napi-helpers.ts +++ b/packages/celox/src/napi-helpers.ts @@ -13,6 +13,7 @@ import { withOwnedHandle } from "./handle-ownership.js"; import type { NativeCreateSimulationFn } from "./simulation.js"; import type { NativeCreateFn } from "./simulator.js"; import type { + AssertionSite, CreateResult, FrontendSimulatorHandle, LoopBreak, @@ -21,6 +22,9 @@ import type { NativeSimulationHandle, NativeSimulatorHandle, PortInfo, + Report, + RuntimeEvent, + Severity, SignalLayout, SimulatorOptions, SourceFile, @@ -63,9 +67,66 @@ export interface RawNapiSimulationHandle { loadState?(bytes: Uint8Array): void; clockPeriods?(): { eventId: number; period: number }[]; switchVcd?(path: string): void; + drainRuntimeEvents?(): RawRuntimeEvent[]; + setFailOn?(severity: string | null): void; dispose(): void; } +/** A runtime event as the addon returns it: absent fields are null. */ +export interface RawRuntimeEvent { + kind: string; + message?: Uint8Array | null; + severity?: string | null; + time?: number | null; + scope?: string | null; + file?: string | null; + line?: number | null; + assertion?: { + label?: string | null; + directive: string; + deferral: string; + outcome: string; + } | null; + count?: number | null; +} + +/** Convert an addon event to a `RuntimeEvent`, dropping absent fields. */ +export function runtimeEvent(raw: RawRuntimeEvent): RuntimeEvent { + switch (raw.kind) { + case "display": + case "write": + return { kind: raw.kind, message: raw.message ?? new Uint8Array() }; + case "finish": + case "stop": + return { kind: raw.kind }; + case "missed": + return { kind: "missed", count: raw.count ?? 0 }; + case "report": { + const report: Report = { + kind: "report", + severity: raw.severity as Severity, + message: raw.message ?? new Uint8Array(), + }; + if (raw.time != null) report.time = raw.time; + if (raw.scope != null) report.scope = raw.scope; + if (raw.file != null) report.file = raw.file; + if (raw.line != null) report.line = raw.line; + if (raw.assertion != null) { + const assertion: AssertionSite = { + directive: raw.assertion.directive as AssertionSite["directive"], + deferral: raw.assertion.deferral as AssertionSite["deferral"], + outcome: raw.assertion.outcome as AssertionSite["outcome"], + }; + if (raw.assertion.label != null) assertion.label = raw.assertion.label; + report.assertion = assertion; + } + return report; + } + default: + throw new Error(`unknown runtime event kind \`${raw.kind}\``); + } +} + export interface NapiFalseLoop { from: NapiSignalPath; to: NapiSignalPath; @@ -925,6 +986,14 @@ export function wrapDirectSimulationHandle( ...(raw.clockPeriods ? { clockPeriods: () => raw.clockPeriods!() } : {}), ...(raw.isFinished ? { isFinished: () => raw.isFinished!() } : {}), ...(raw.isStopped ? { isStopped: () => raw.isStopped!() } : {}), + ...(raw.drainRuntimeEvents + ? { + drainRuntimeEvents: () => raw.drainRuntimeEvents!().map(runtimeEvent), + } + : {}), + ...(raw.setFailOn + ? { setFailOn: (severity: Severity | null) => raw.setFailOn!(severity) } + : {}), }; } diff --git a/packages/celox/src/runtime-events-addon.test.ts b/packages/celox/src/runtime-events-addon.test.ts new file mode 100644 index 00000000000..05081f5807e --- /dev/null +++ b/packages/celox/src/runtime-events-addon.test.ts @@ -0,0 +1,87 @@ +/** Runtime events and `failOn` through the native addon. */ +import { afterEach, describe, expect, test } from "vitest"; +import { createSimulationBridge, loadNativeAddon } from "./napi-helpers.js"; +import { Simulation } from "./simulation.js"; +import type { ModuleDefinition, Report } from "./types.js"; + +const VERYL = ` +module Top ( + clk: input clock, + cnt: output logic<8>, +) { + var r: logic<8>; + always_ff (clk) { + $display("tick %0d", r); + $assert_continue(r != 8'd2, "r=%0d", r); + r = r + 1; + } + assign cnt = r; +} +`; + +type Ports = { readonly cnt: bigint }; + +const Top: ModuleDefinition = { + __celox_module: true, + name: "Top", + sources: [{ path: "Top.veryl", content: VERYL }], + ports: { + clk: { direction: "input", type: "clock", width: 1 }, + cnt: { direction: "output", type: "logic", width: 8 }, + }, + events: ["clk"], +}; + +let live: Simulation[] = []; + +function simulation(): Simulation { + const sim = Simulation.create(Top, { + __nativeCreate: createSimulationBridge(loadNativeAddon()), + }); + sim.addClock("clk", { period: 10 }); + live.push(sim); + return sim; +} + +afterEach(() => { + for (const sim of live) sim.dispose(); + live = []; +}); + +const text = (bytes: Uint8Array) => new TextDecoder().decode(bytes); + +describe("runtime events through the addon", () => { + test("drainRuntimeEvents returns displays and reports in order", () => { + const sim = simulation(); + sim.runUntil(100); + const events = sim.drainRuntimeEvents(); + const reports = events.filter((event) => event.kind === "report"); + expect(reports).toHaveLength(1); + expect(reports[0]).toMatchObject({ severity: "error" }); + expect(text((reports[0] as Report).message)).toBe("r=2"); + const before = events.slice(0, events.indexOf(reports[0]!)); + expect( + before.map((event) => event.kind === "display" && text(event.message)), + ).toContain("tick 2"); + expect(sim.drainRuntimeEvents()).toEqual([]); + }); + + test("failOn stops the run after the time step of the report", () => { + const sim = simulation(); + sim.setFailOn("error"); + expect(() => sim.runUntil(1000)).toThrow(/failOn: Error/); + const stopped = sim.time(); + expect(stopped).toBeLessThan(1000); + const report = sim + .drainRuntimeEvents() + .find((event): event is Report => event.kind === "report"); + expect(report?.time).toBe(stopped); + sim.runUntil(1000); + expect(sim.time()).toBe(1000); + }); + + test("failOn rejects an unknown severity", () => { + const sim = simulation(); + expect(() => sim.setFailOn("loud" as never)).toThrow(/unknown severity/); + }); +}); diff --git a/packages/celox/src/simulation.ts b/packages/celox/src/simulation.ts index 49fbeb41a32..7feb23e896a 100644 --- a/packages/celox/src/simulation.ts +++ b/packages/celox/src/simulation.ts @@ -22,6 +22,8 @@ import type { FourStateValue, ModuleDefinition, NativeSimulationHandle, + RuntimeEvent, + Severity, SignalLayout, SimulatorOptions, SourceFile, @@ -495,6 +497,35 @@ export class Simulation

> { return t; } + /** + * Take the runtime events the design emitted since the last call, in + * emission order: `$display` and `$write` output, reports of severity + * tasks, `$finish` and `$stop`. + */ + drainRuntimeEvents(): RuntimeEvent[] { + this.ensureAlive(); + if (!this._handle.drainRuntimeEvents) { + throw new Error( + "This simulation does not support draining runtime events", + ); + } + return this._handle.drainRuntimeEvents(); + } + + /** + * Make `runUntil()`, `step()` and the waits throw after the time step of + * the first report of at least `severity`, such as `"error"` for + * `$error` and failed assertions. While it is set, each report keeps the + * exact time it was issued at. `null` throws only at `$fatal`. + */ + setFailOn(severity: Severity | null): void { + this.ensureAlive(); + if (!this._handle.setFailOn) { + throw new Error("This simulation does not support failOn"); + } + this._handle.setFailOn(severity); + } + /** Current simulation time. */ time(): number { this.ensureAlive(); diff --git a/packages/celox/src/types.ts b/packages/celox/src/types.ts index 7dfee70b78f..b358062dc33 100644 --- a/packages/celox/src/types.ts +++ b/packages/celox/src/types.ts @@ -227,6 +227,47 @@ export interface NativeSimulatorHandle { * Opaque handle returned by NAPI for time-based simulation. * @internal */ +/** The severity of a report (IEEE 1800-2023 20.10). */ +export type Severity = "info" | "warning" | "error" | "fatal"; + +/** The assertion whose action block issued a report. */ +export interface AssertionSite { + /** The statement label, which names the assertion within its scope. */ + label?: string; + directive: "assert" | "assume" | "cover"; + /** `"observed"` is `#0`. */ + deferral: "none" | "observed" | "final"; + /** Which action block issued the report. */ + outcome: "pass" | "fail"; +} + +/** + * What a severity task (`$info`, `$warning`, `$error`, `$fatal`) reports. + * `message` holds the formatted bytes; decode them explicitly when the + * design emits text. + */ +export interface Report { + kind: "report"; + severity: Severity; + message: Uint8Array; + /** The simulation time, when it is known (see `Simulation.setFailOn`). */ + time?: number; + /** The hierarchical name of the scope that issued the report. */ + scope?: string; + /** The file and line of the task call. */ + file?: string; + line?: number; + assertion?: AssertionSite; +} + +/** A runtime event a simulation drains with `drainRuntimeEvents()`. */ +export type RuntimeEvent = + | { kind: "display" | "write"; message: Uint8Array } + | Report + | { kind: "finish" | "stop" } + /** Events the design's event buffer overwrote before they were drained. */ + | { kind: "missed"; count: number }; + export interface NativeSimulationHandle { addClock(eventId: number, period: number, initialDelay: number): void; schedule(eventId: number, time: number, value: number): void; @@ -264,6 +305,10 @@ export interface NativeSimulationHandle { clockPeriods?(): { eventId: number; period: number }[]; /** Continue the waveform in a new VCD file. */ switchVcd?(path: string): void; + /** Take the runtime events emitted since the last call. */ + drainRuntimeEvents?(): RuntimeEvent[]; + /** Fail runs and steps at a report of at least `severity`. */ + setFailOn?(severity: Severity | null): void; } /**