#![forbid(unsafe_code)]
mod statistics;
pub use statistics::{ActionFlow, ActionGroup};
use dive_eval::next::StateVals;
mod host;
use dive_model::Model;
use dive_stdlib::random::RandomMode;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
#[derive(Clone, Debug)]
pub struct Options {
pub seed: i64,
pub aril: u64,
pub depth: usize,
pub traces: u64,
pub mode: RandomMode,
pub max_candidates: usize,
pub max_retained: usize,
pub max_generated: u64,
pub action_stats: bool,
pub generation: bool,
pub max_output_events: usize,
pub max_output_bytes: usize,
}
impl Options {
#[must_use]
pub const fn new(seed: i64, mode: RandomMode, depth: usize, traces: u64) -> Self {
Self {
seed,
aril: 0,
depth,
traces,
mode,
max_candidates: 1_000_000,
max_retained: 1_000_000,
max_generated: 10_000_000,
action_stats: false,
generation: false,
max_output_events: 100_000,
max_output_bytes: 16 * 1024 * 1024,
}
}
}
#[derive(Clone, Debug)]
pub struct Trace {
pub id: u64,
pub states: Vec<StateVals>,
}
#[derive(Clone, Debug)]
pub enum Outcome {
Sampled,
Violation {
kind: &'static str,
name: Option<String>,
code: u32,
trace: usize,
},
Error {
code: u32,
message: String,
},
Unsupported(String),
Limit(String),
Cancelled,
Internal(String),
}
#[derive(Clone, Debug)]
pub struct PendingViolation {
pub kind: &'static str,
pub name: Option<String>,
pub code: u32,
}
#[derive(Clone, Debug)]
pub struct Report {
pub stage: &'static str,
pub outcome: Outcome,
pub generated: u64,
pub initial_candidates: u64,
pub pending_violation: Option<PendingViolation>,
pub traces_started: u64,
pub traces: Vec<Trace>,
pub action_flow: Option<ActionFlow>,
pub runtime_output: Vec<dive_eval::capture::Captured>,
}
#[derive(Debug)]
pub struct Runtime {
options: Options,
host: Arc<host::SimulationHost>,
used: AtomicBool,
}
impl Runtime {
#[must_use]
pub fn new(options: Options) -> Self {
let host = host::SimulationHost::new(&options);
host.binding(true);
Self {
host,
options,
used: AtomicBool::new(false),
}
}
#[must_use]
pub fn host(&self) -> Arc<dyn dive_eval::Host> {
self.host.clone()
}
pub fn set_config(&self, config: Option<dive_eval::RunConfig>) {
self.host.set_config(config);
}
#[must_use]
pub fn simulate_with_backend(
&self,
model: &Model,
driver: impl FnOnce(&dyn Fn() -> (usize, usize)) -> Report,
) -> Report {
self.run(model, |host| driver(&|| host.remaining_output()))
}
fn run(&self, model: &Model, driver: impl FnOnce(&host::SimulationHost) -> Report) -> Report {
if self.used.swap(true, Ordering::AcqRel) {
return refused_runtime("simulation runtime was already used");
}
self.host.binding(false);
with_host(model, &self.options, &self.host, driver)
}
}
fn refused_runtime(reason: &str) -> Report {
Report {
stage: "preflight",
outcome: Outcome::Unsupported(reason.to_owned()),
generated: 0,
initial_candidates: 0,
pending_violation: None,
traces_started: 0,
traces: Vec::new(),
action_flow: None,
runtime_output: Vec::new(),
}
}
fn with_host(
model: &Model,
opts: &Options,
host: &Arc<host::SimulationHost>,
driver: impl FnOnce(&host::SimulationHost) -> Report,
) -> Report {
if let Some(outcome) = preflight(model, opts) {
return Report {
stage: "preflight",
outcome,
generated: 0,
initial_candidates: 0,
pending_violation: None,
traces_started: 0,
traces: Vec::new(),
action_flow: None,
runtime_output: Vec::new(),
};
}
let Some(_lease) = model.evaluator.try_simulation_lease() else {
return Report {
stage: "preflight",
outcome: Outcome::Unsupported(
"concurrent or reentrant simulation on the same evaluator".to_owned(),
),
generated: 0,
initial_candidates: 0,
pending_violation: None,
traces_started: 0,
traces: Vec::new(),
action_flow: None,
runtime_output: Vec::new(),
};
};
let _restore = host::HostRestore::install(&model.evaluator, host);
let capture = dive_eval::capture::PrintCapture::start();
let mut report = driver(host);
let mut output = model.evaluator.filter_captured_warnings(capture.take());
output.append(&mut report.runtime_output);
report.runtime_output = output;
if let Some(reason) = host.limit() {
report.outcome = Outcome::Limit(reason.to_owned());
} else if let Some(reason) = host.denied() {
report.outcome = Outcome::Unsupported(reason);
}
report
}
#[must_use]
pub fn preflight(model: &Model, opts: &Options) -> Option<Outcome> {
let refusal = |s: &str| Some(Outcome::Unsupported(s.to_owned()));
if opts.traces == 0 {
return refusal("simulation requires a positive finite trace count");
}
if opts.aril > 1_000_000 {
return Some(Outcome::Limit("simulation aril skip bound".to_owned()));
}
if opts.mode == RandomMode::Dive && opts.aril != 0 {
return refusal("nonzero aril outside TLC simulation mode");
}
if model.runtime_name_order {
return refusal(
"simulation runtime string encounter order requires independent namespace provenance",
);
}
if let Some(u) = model
.unsupported
.iter()
.find(|u| u.kind != dive_model::UnsupportedKind::TemporalProperty)
{
return refusal(&u.feature);
}
if !model.implied_temporals.is_empty() {
let names: Vec<&str> = model
.implied_temporals
.iter()
.map(|n| n.name.as_str())
.collect();
return refusal(&format!(
"simulation temporal properties: {}",
names.join(", ")
));
}
if !model.implied_inits.is_empty() {
return refusal(
"simulation implied initial properties require a separate validation contract",
);
}
if !model.implied_actions.is_empty()
&& (!model.constraints.is_empty() || !model.action_constraints.is_empty())
{
return refusal(
"simulation implied action properties with state/action constraints require a separate validation contract",
);
}
if model.symmetry.is_some() {
return refusal("simulation SYMMETRY declarations");
}
if model.view.is_some() {
return refusal("simulation VIEW declarations");
}
if matches!(model.alias, Some(Err(_))) {
return refusal("simulation ALIAS whose definition lookup fails");
}
if !matches!(&model.postconditions, Ok(p) if p.is_empty()) {
return refusal("simulation POSTCONDITION");
}
if model.actions.len() > i32::MAX as usize {
return Some(Outcome::Limit(
"simulation action count exceeds TLC integer indexing".to_owned(),
));
}
None
}