use std::collections::BTreeMap;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use dive_ir::{Arg, ExprId, StdOp};
use dive_value::{Ctx, Int, Value};
use crate::core::Core;
use crate::env::{Env, Ev, St, StateRef, control};
use crate::error::{Ec, EvalError, Result};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Counter {
Generated,
Distinct,
Queue,
Diameter,
Initial,
DurationSecs,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RunConfig {
pub deadlock: bool,
pub workers: i64,
pub seed: i64,
pub fingerprint: i64,
pub install: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HostError {
pub code: u32,
pub message: String,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Interrupted {
token: u64,
}
impl Interrupted {
#[must_use]
pub const fn new(token: u64) -> Self {
Self { token }
}
#[must_use]
pub const fn token(self) -> u64 {
self.token
}
}
pub trait HostControl: Send + Sync + std::fmt::Debug {
fn check(&self) -> Result<(), Interrupted>;
}
#[derive(Debug)]
pub struct HostControlScope {
pub(crate) core: Arc<Core>,
pub(crate) token: u64,
pub(crate) _thread: std::marker::PhantomData<std::rc::Rc<()>>,
}
impl Drop for HostControlScope {
fn drop(&mut self) {
self.core.host.remove_control(self.token);
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct HostControlConflict;
impl std::fmt::Display for HostControlConflict {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("another driver owns the evaluator host control")
}
}
impl std::error::Error for HostControlConflict {}
#[derive(Debug)]
struct ControlFrame {
token: u64,
owner: std::thread::ThreadId,
control: Option<Arc<dyn HostControl>>,
}
#[derive(Debug, Default)]
struct Controls {
next: u64,
frames: Vec<ControlFrame>,
}
pub trait Host: Send + Sync + std::fmt::Debug {
fn input(
&self,
_request: &crate::inputs::InputRequest,
) -> Option<Result<crate::inputs::InputResponse, HostError>> {
None
}
fn check_native_access(&self, _op: StdOp) -> Result<(), HostError> {
Ok(())
}
fn print_output(&self, _text: &str) -> Result<bool, HostError> {
Ok(true)
}
fn check_tlc_access(&self, _key: &str, _write: bool) -> Result<(), HostError> {
Ok(())
}
fn random(&self, _op: StdOp, _args: &[Value], _ctx: Ctx) -> Option<Result<Value, HostError>> {
None
}
fn check_random_in_enabled(&self) -> Result<(), HostError> {
Ok(())
}
fn check_register_access(&self) -> Result<(), HostError> {
Ok(())
}
fn check_action_composition(&self) -> Result<(), HostError> {
Ok(())
}
fn requires_bounded_action_composition(&self) -> bool {
false
}
fn check_bounded_action_composition(&self) -> Result<(), HostError> {
self.check_action_composition()
}
fn expression_cache_domain(&self) -> u64 {
0
}
fn level(&self) -> Option<i64> {
None
}
fn successor_level(&self) -> Result<i64, HostError> {
Err(HostError {
code: 0,
message: PRIMED_LEVEL_UNSUPPORTED.to_owned(),
})
}
fn counter(&self, _counter: Counter) -> Option<i64> {
None
}
fn config(&self) -> Option<RunConfig> {
None
}
fn request_exit(&self) -> bool {
false
}
}
pub const PRIMED_LEVEL_UNSUPPORTED: &str =
"TLCGet(\"level\") under a prime, which TLC evaluates at the successor's level";
pub const TLCGET_NAMES: &[&str] = &[
"exit",
"pause",
"config",
"spec",
"coverage",
"action",
"install",
"id",
"behavior",
"all",
"all:named",
"mode",
"deadlock",
"seed",
"fingerprint",
"worker",
"traces",
"depth",
"aril",
"sched",
"revision",
"timestamp",
"date",
"count",
"tag",
"calver",
"impliedinits",
"impliedactions",
"invariants",
"impliedtemporals",
"temporals",
"actions",
"inits",
"variables",
"actionconstraints",
"constraints",
"level",
"stats",
"duration",
"generated",
"diameter",
"distinct",
"initial",
"queue",
"retries",
"distinctvalues",
"levelmean",
"levelvariance",
];
#[derive(Debug, Default)]
pub(crate) struct Registers {
ints: BTreeMap<i64, Value>,
named: Vec<(String, Value)>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum NativeHooks {
#[default]
Callback,
Unrestricted,
}
#[derive(Debug)]
pub struct HostBinding {
host: Option<Arc<dyn Host>>,
hooks: NativeHooks,
cache_domain: Option<u64>,
}
impl HostBinding {
#[must_use]
pub fn callback(host: Option<Arc<dyn Host>>) -> Self {
Self {
host,
hooks: NativeHooks::Callback,
cache_domain: None,
}
}
#[must_use]
pub const fn native_hooks(&self) -> NativeHooks {
self.hooks
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct HostBindingStamp {
generation: u64,
hooks: NativeHooks,
}
impl HostBindingStamp {
#[must_use]
pub const fn generation(self) -> Option<u64> {
if self.generation == 0 {
None
} else {
Some(self.generation)
}
}
#[must_use]
pub const fn native_hooks(self) -> NativeHooks {
self.hooks
}
}
#[derive(Debug)]
pub struct HostBindingScope {
pub(crate) core: Arc<Core>,
pub(crate) previous: Option<HostBinding>,
pub(crate) _thread: std::marker::PhantomData<std::rc::Rc<()>>,
}
impl Drop for HostBindingScope {
fn drop(&mut self) {
if let Some(previous) = self.previous.take() {
drop(self.core.host.replace_binding(previous));
}
}
}
#[derive(Debug)]
struct BindingState {
binding: HostBinding,
generation: u64,
}
impl Default for BindingState {
fn default() -> Self {
Self {
binding: HostBinding {
host: None,
hooks: NativeHooks::Callback,
cache_domain: Some(0),
},
generation: 1,
}
}
}
#[derive(Debug, Default)]
pub(crate) struct HostSlot {
host: Mutex<BindingState>,
pub(crate) registers: Mutex<Registers>,
control: Mutex<Controls>,
pub(crate) cache_domain: AtomicU64,
unrestricted: AtomicBool,
}
impl HostSlot {
pub(crate) fn commit_subset_position(&self, position: dive_value::SubsetCommit<'_>) -> bool {
let slot = self.host.lock().unwrap_or_else(PoisonError::into_inner);
if slot.generation == 0
|| slot.binding.host.is_none()
|| slot.binding.hooks != NativeHooks::Unrestricted
|| slot.binding.cache_domain != Some(0)
{
return false;
}
position.commit();
true
}
pub(crate) fn replace(&self, host: Option<Arc<dyn Host>>) -> Option<Arc<dyn Host>> {
self.replace_binding(HostBinding::callback(host)).host
}
pub(crate) fn replace_binding(&self, binding: HostBinding) -> HostBinding {
let mut slot = self.host.lock().unwrap_or_else(PoisonError::into_inner);
self.install(&mut slot, binding)
}
fn install(&self, slot: &mut BindingState, mut binding: HostBinding) -> HostBinding {
let domain = binding.cache_domain.unwrap_or_else(|| {
binding
.host
.as_ref()
.map_or(0, |host| host.expression_cache_domain())
});
binding.cache_domain = Some(domain);
self.cache_domain.store(domain, Ordering::Release);
if slot.generation != 0 {
slot.generation = slot.generation.checked_add(1).unwrap_or(0);
}
if domain != 0 || slot.generation == 0 {
binding.hooks = NativeHooks::Callback;
}
self.unrestricted.store(
binding.hooks == NativeHooks::Unrestricted,
Ordering::Release,
);
std::mem::replace(&mut slot.binding, binding)
}
pub(crate) fn replace_hooks(&self, hooks: NativeHooks) -> Option<HostBinding> {
let mut slot = self.host.lock().unwrap_or_else(PoisonError::into_inner);
if hooks == NativeHooks::Unrestricted
&& (slot.generation == 0
|| slot.generation == u64::MAX
|| slot.binding.host.is_none()
|| slot.binding.cache_domain != Some(0))
{
return None;
}
let binding = HostBinding {
host: slot.binding.host.clone(),
hooks: if slot.binding.host.is_some() {
hooks
} else {
NativeHooks::Callback
},
cache_domain: slot.binding.cache_domain,
};
Some(self.install(&mut slot, binding))
}
pub(crate) fn stamp(&self) -> HostBindingStamp {
let slot = self.host.lock().unwrap_or_else(PoisonError::into_inner);
HostBindingStamp {
generation: slot.generation,
hooks: slot.binding.hooks,
}
}
pub(crate) fn check_native_access(&self, op: StdOp) -> Result<()> {
if self.unrestricted.load(Ordering::Acquire) {
return Ok(());
}
let host = {
let slot = self.host.lock().unwrap_or_else(PoisonError::into_inner);
match slot.binding.hooks {
NativeHooks::Unrestricted => None,
NativeHooks::Callback => slot.binding.host.clone(),
}
};
match host {
Some(host) => host.check_native_access(op).map_err(host_error),
None => Ok(()),
}
}
pub(crate) fn push_control(
&self,
control: Option<Arc<dyn HostControl>>,
) -> Result<u64, HostControlConflict> {
let owner = std::thread::current().id();
let mut controls = self.control.lock().unwrap_or_else(PoisonError::into_inner);
if controls
.frames
.last()
.is_some_and(|frame| frame.owner != owner)
{
return Err(HostControlConflict);
}
let token = controls.next.checked_add(1).ok_or(HostControlConflict)?;
controls.next = token;
controls.frames.push(ControlFrame {
token,
owner,
control,
});
Ok(token)
}
pub(crate) fn remove_control(&self, token: u64) {
let mut controls = self.control.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(index) = controls
.frames
.iter()
.position(|frame| frame.token == token)
{
controls.frames.remove(index);
}
}
pub(crate) fn check_control(&self) -> crate::Result<()> {
let controls = self.control.lock().unwrap_or_else(PoisonError::into_inner);
let control = match controls.frames.last() {
Some(frame) if frame.control.is_some() => frame.control.clone(),
Some(frame) if frame.owner != std::thread::current().id() => controls
.frames
.iter()
.rev()
.find_map(|frame| frame.control.clone()),
_ => None,
};
drop(controls);
match control {
Some(control) => control.check().map_err(EvalError::interrupted),
None => Ok(()),
}
}
pub(crate) fn cache_domain(&self) -> u64 {
self.cache_domain.load(Ordering::Acquire)
}
pub(crate) fn get(&self) -> Option<Arc<dyn Host>> {
self.host
.lock()
.unwrap_or_else(PoisonError::into_inner)
.binding
.host
.clone()
}
}
pub(crate) fn host_error(e: HostError) -> EvalError {
if e.code == 0 {
EvalError::unsupported(e.message)
} else {
EvalError::eval_exception(Ec::from_tlc_code(e.code), e.message)
}
}
impl Core {
fn check_register_access(&self) -> Result<()> {
match self.host.get() {
Some(host) => host.check_register_access().map_err(host_error),
None => Ok(()),
}
}
pub(crate) fn check_action_composition(&self) -> Result<()> {
match self.host.get() {
Some(host) => host.check_action_composition().map_err(host_error),
None => Ok(()),
}
}
pub(crate) fn expression_cache(&self) -> u64 {
self.host.cache_domain()
}
pub(crate) fn call_random(&self, op: StdOp, args: &[Value]) -> Result<Value> {
let Some(host) = self.host.get() else {
return Err(EvalError::unsupported(format!(
"{} without a random stream (the evaluator runs outside a model checker that seeds one)",
op.qualified_name()
)));
};
match host.random(op, args, self.ctx) {
Some(r) => r.map_err(host_error),
None => Err(EvalError::unsupported(format!(
"{} (this run provides no random stream)",
op.qualified_name()
))),
}
}
pub(crate) fn tlc_get(
self: &Arc<Self>,
env: &mut Env,
st: &St,
args: &[Arg],
e: ExprId,
) -> Result<Ev> {
let Some(Arg::Expr { expr, .. }) = args.first() else {
return Err(EvalError::bug("TLCGet arity"));
};
let vidx = self.eval_v(env, st, *expr)?;
let _g = self.enter(e)?;
self.tlc_get_value(&vidx, st).map(Ev::V)
}
pub(crate) fn tlc_get_value(&self, vidx: &Value, st: &St) -> Result<Value> {
match vidx {
Value::Int(_) | Value::BigInt(_) => {
let idx = self.register_index(vidx)?;
if idx >= 0 {
self.check_register_access()?;
let regs = self
.host
.registers
.lock()
.unwrap_or_else(PoisonError::into_inner);
return match regs.ints.get(&idx) {
Some(v) => Ok(v.clone()),
None => Err(undefined(&idx.to_string())),
};
}
}
Value::Str(s) => return self.tlc_get_string(s.as_str(), st),
_ => {}
}
Err(EvalError::eval_exception(
Ec::OneArgumentError,
format!(
"The argument of TLCGet should be a nonnegative integer, but instead it is:\n{}",
self.ppr(vidx)
),
))
}
fn register_index(&self, v: &Value) -> Result<i64> {
match v.as_int().and_then(|i| i.to_i64()) {
Some(i) if i32::try_from(i).is_ok() => Ok(i),
_ => Err(EvalError::unsupported(format!(
"a TLCGet/TLCSet register index outside TLC's 32-bit range: {}",
self.ppr(v)
))),
}
}
fn host_for(&self, key: &str) -> Result<Arc<dyn Host>> {
self.host.get().ok_or_else(|| {
EvalError::unsupported(format!(
"TLCGet(\"{key}\") without a model checker (the evaluator runs outside one)"
))
})
}
fn counter(&self, key: &str, c: Counter) -> Result<i64> {
self.host_for(key)?.counter(c).ok_or_else(|| {
EvalError::unsupported(format!("TLCGet(\"{key}\") (this run does not provide it)"))
})
}
fn narrow(n: i64) -> Result<Value> {
if i32::try_from(n).is_ok() {
Ok(Value::Int(n))
} else {
Err(EvalError::eval_exception(
Ec::Overflow,
format!("Overflow when computing {n}"),
))
}
}
fn record(&self, fields: Vec<(&str, Value)>) -> Result<Value> {
let fields = fields
.into_iter()
.map(|(n, v)| (self.names.intern(n), v))
.collect();
Ok(Value::record(fields, self.ctx)?)
}
#[allow(
clippy::too_many_lines,
reason = "one arm per key, as in TLCGetStringValue"
)]
fn tlc_get_string(&self, key: &str, st: &St) -> Result<Value> {
if let Some(host) = self.host.get() {
host.check_tlc_access(key, false).map_err(host_error)?;
}
match key {
"diameter" => Self::narrow(self.counter(key, Counter::Diameter)?),
"generated" => Self::narrow(self.counter(key, Counter::Generated)?),
"distinct" => Self::narrow(self.counter(key, Counter::Distinct)?),
"queue" => Self::narrow(self.counter(key, Counter::Queue)?),
"duration" => Self::narrow(self.counter(key, Counter::DurationSecs)?),
"stats" => {
let sat = |n: i64| Value::Int(n.clamp(i64::from(i32::MIN), i64::from(i32::MAX)));
let queue = self.counter(key, Counter::Queue)?;
let distinct = self.counter(key, Counter::Distinct)?;
let initial = self.counter(key, Counter::Initial)?;
let generated = self.counter(key, Counter::Generated)?;
let diameter = self.counter(key, Counter::Diameter)?;
let duration = self.counter(key, Counter::DurationSecs)?;
self.record(vec![
("queue", sat(queue)),
("distinct", sat(distinct)),
("initial", sat(initial)),
("generated", sat(generated)),
("diameter", sat(diameter)),
("duration", sat(duration)),
("worker", Value::Int(0)),
])
}
"config" => {
let c = self.host_for(key)?.config().ok_or_else(|| {
EvalError::unsupported("TLCGet(\"config\") (this run does not provide it)")
})?;
self.record(vec![
("mode", Value::string(&self.names, "bfs")),
("deadlock", Value::Bool(c.deadlock)),
("worker", Value::Int(c.workers)),
("seed", Value::string(&self.names, &c.seed.to_string())),
(
"fingerprint",
Value::string(&self.names, &c.fingerprint.to_string()),
),
("install", Value::string(&self.names, &c.install)),
])
}
"level" => {
if st.is(control::CONST) || st.is(control::INIT) {
return Ok(Value::Int(0));
}
if st.is(control::PRIMED) || matches!(st.s1, StateRef::Null) {
return self
.host_for(key)?
.successor_level()
.map(|level| Value::int(Int::Small(level)))
.map_err(host_error);
}
let level = self.host_for(key)?.level().ok_or_else(|| {
EvalError::unsupported(
"TLCGet(\"level\") (this run does not track the level of the state)",
)
})?;
Ok(Value::int(Int::Small(level)))
}
"all" => {
self.check_register_access()?;
let regs = self
.host
.registers
.lock()
.unwrap_or_else(PoisonError::into_inner);
let pairs = regs
.ints
.iter()
.map(|(i, v)| (Value::Int(*i), Value::tuple(vec![v.clone()])))
.collect();
Ok(Value::fcn(pairs, self.ctx)?)
}
"all:named" => {
self.check_register_access()?;
let regs = self
.host
.registers
.lock()
.unwrap_or_else(PoisonError::into_inner);
let pairs = regs
.named
.iter()
.map(|(k, v)| (Value::string(&self.names, k), Value::tuple(vec![v.clone()])))
.collect();
Ok(Value::fcn(pairs, self.ctx)?)
}
"spec" | "action" | "revision" => Err(EvalError::unsupported(format!(
"TLCGet(\"{key}\") (reads TLC's internal description of the run)"
))),
k if k.starts_with("s:") => {
self.check_register_access()?;
let regs = self
.host
.registers
.lock()
.unwrap_or_else(PoisonError::into_inner);
match regs.named.iter().find(|(n, _)| n == k) {
Some((_, v)) => Ok(v.clone()),
None => Err(undefined(k)),
}
}
"-Dtlc2.tool.impl.Tool.cdot" => Ok(Value::string(
&self.names,
if self.opts.action_composition == crate::options::ActionComposition::Off {
key
} else {
"true"
},
)),
k if k.starts_with("-D") => Err(EvalError::unsupported(format!(
"TLCGet(\"{k}\") (reads a Java system property of TLC's JVM)"
))),
k => Err(undefined(k)),
}
}
pub(crate) fn startup_register_write(&self, key: &Value, value: &Value) -> Result<()> {
match key {
Value::Int(_) | Value::BigInt(_) if self.register_index(key)? >= 0 => {
self.check_register_access()?;
Err(EvalError::general(
"integer TLCSet registers are unavailable during startup pre-evaluation",
))
}
Value::Str(name) if name.as_str().starts_with("s:") => {
if let Some(host) = self.host.get() {
host.check_tlc_access(name.as_str(), true)
.map_err(host_error)?;
}
self.check_register_access()
}
_ => self.tlc_set(key, value).map(|_| ()),
}
}
pub(crate) fn tlc_set(&self, vidx: &Value, val: &Value) -> Result<Value> {
match vidx {
Value::Int(_) | Value::BigInt(_) => {
let idx = self.register_index(vidx)?;
if idx >= 0 {
self.check_register_access()?;
self.host
.registers
.lock()
.unwrap_or_else(PoisonError::into_inner)
.ints
.insert(idx, val.clone());
return Ok(Value::TRUE);
}
}
Value::Str(s) => {
if let Some(host) = self.host.get() {
host.check_tlc_access(s.as_str(), true)
.map_err(host_error)?;
}
match s.as_str() {
"exit" => {
if matches!(val, Value::Bool(true)) {
let handled = self.host.get().is_some_and(|h| h.request_exit());
if !handled {
return Err(EvalError::unsupported(
"TLCSet(\"exit\", TRUE) without a model checker that stops on it",
));
}
}
return Ok(Value::TRUE);
}
"pause" => {
if matches!(val, Value::Bool(true)) {
return Err(EvalError::unsupported(
"TLCSet(\"pause\", TRUE) (waits for input on TLC's console)",
));
}
return Ok(Value::TRUE);
}
k if k.starts_with("s:") => {
self.check_register_access()?;
let mut regs = self
.host
.registers
.lock()
.unwrap_or_else(PoisonError::into_inner);
match regs.named.iter_mut().find(|(n, _)| n == k) {
Some(slot) => slot.1 = val.clone(),
None => regs.named.push((k.to_owned(), val.clone())),
}
return Ok(Value::TRUE);
}
k if k.starts_with("-D") => {
return Err(EvalError::unsupported(format!(
"TLCSet(\"{k}\", ...) (sets a Java system property of TLC's JVM)"
)));
}
_ => {}
}
}
_ => {}
}
Err(EvalError::eval_exception(
Ec::ArgumentError,
format!(
"The first argument of TLCSet should be a nonnegative integer, but instead it is:\n{}",
self.ppr(vidx)
),
))
}
}
fn undefined(key: &str) -> EvalError {
EvalError::eval_exception(Ec::TlcGetUndefined, format!("TLCGet({key}) was undefined."))
}
#[cfg(test)]
#[path = "host_binding_tests.rs"]
mod binding_tests;