use crate::types::hash_of;
use std::error::Error;
use std::fmt;
use std::hash::Hash;
#[derive(Debug, Clone)]
pub struct Unknown {
pub code: i32,
}
impl Unknown {
pub fn new(code: i32) -> Self {
Self { code }
}
}
pub type Unknowns = Vec<Unknown>;
#[derive(Debug, Clone)]
pub enum RuleError {
Unknown(Unknown),
Model(Box<str>),
}
impl RuleError {
pub fn model(what: impl Into<String>) -> Self {
Self::Model(what.into().into_boxed_str())
}
}
impl From<Unknown> for RuleError {
fn from(u: Unknown) -> Self {
Self::Unknown(u)
}
}
pub fn error_if(cond: bool, what: impl Into<String>) -> Result<(), RuleError> {
if cond {
Err(RuleError::model(what))
} else {
Ok(())
}
}
#[derive(Debug, Clone)]
pub enum CheckerError {
PropertyViolation {
property: String,
detail: Option<String>,
},
Deadlock,
ModelError {
rule: String,
what: String,
},
}
impl fmt::Display for CheckerError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::PropertyViolation {
property,
detail: None,
} => {
write!(f, "property violation: {property}")
}
Self::PropertyViolation {
property,
detail: Some(d),
} => {
write!(f, "property violation: {property}: {d}")
}
Self::Deadlock => write!(f, "deadlock"),
Self::ModelError { rule, what } => {
write!(f, "model error in rule {rule}: {what}")
}
}
}
}
impl Error for CheckerError {}
pub trait State: Clone + Hash + Eq + fmt::Display + 'static {}
impl<S: Clone + Hash + Eq + fmt::Display + 'static> State for S {}
pub trait Rule<S: State> {
fn name(&self) -> &str;
fn precondition(&self, state: &S) -> bool;
fn apply(&self, state: &mut S) -> Result<bool, RuleError>;
}
pub struct RuleFn<S> {
name: String,
precondition: Box<dyn Fn(&S) -> bool>,
apply: Box<dyn Fn(&mut S) -> Result<bool, RuleError>>,
}
pub fn rule<S: State>(
name: impl Into<String>,
precondition: impl Fn(&S) -> bool + 'static,
apply: impl Fn(&mut S) -> bool + 'static,
) -> RuleFn<S> {
RuleFn {
name: name.into(),
precondition: Box::new(precondition),
apply: Box::new(move |s| Ok((apply)(s))),
}
}
pub fn rule_try<S: State>(
name: impl Into<String>,
precondition: impl Fn(&S) -> bool + 'static,
apply: impl Fn(&mut S) -> Result<bool, RuleError> + 'static,
) -> RuleFn<S> {
RuleFn {
name: name.into(),
precondition: Box::new(precondition),
apply: Box::new(apply),
}
}
impl<S: State> Rule<S> for RuleFn<S> {
fn name(&self) -> &str {
&self.name
}
fn precondition(&self, state: &S) -> bool {
(self.precondition)(state)
}
fn apply(&self, state: &mut S) -> Result<bool, RuleError> {
(self.apply)(state)
}
}
pub trait Property<S: State> {
fn name(&self) -> &str;
fn check_state(&self, _state: &S) -> bool {
true
}
fn on_successors(&mut self, _state: &S, _successors: &[(S, String)], _unknowns: &[Unknown]) {}
fn is_satisfied(&self) -> Option<String> {
None
}
}
pub struct InvariantFn<S> {
name: String,
check: Box<dyn Fn(&S) -> bool>,
}
pub fn invariant<S: State>(
name: impl Into<String>,
check: impl Fn(&S) -> bool + 'static,
) -> InvariantFn<S> {
InvariantFn {
name: name.into(),
check: Box::new(check),
}
}
impl<S: State> Property<S> for InvariantFn<S> {
fn name(&self) -> &str {
&self.name
}
fn check_state(&self, state: &S) -> bool {
(self.check)(state)
}
}
pub trait Stepping<S: State> {
fn step(&mut self, state: &S) -> Result<(Vec<(S, String)>, Unknowns), CheckerError>;
fn check_final(&self) -> Option<(String, String)>;
}
pub struct TransitionSystem<S: State> {
rules: Vec<Box<dyn Rule<S>>>,
properties: Vec<Box<dyn Property<S>>>,
deadlock_detection: bool,
}
impl<S: State> TransitionSystem<S> {
pub fn new() -> Self {
Self {
rules: Vec::new(),
properties: Vec::new(),
deadlock_detection: true,
}
}
pub fn add_rule(&mut self, rule: impl Rule<S> + 'static) -> &mut Self {
self.rules.push(Box::new(rule));
self
}
pub fn add_property(&mut self, prop: impl Property<S> + 'static) -> &mut Self {
self.properties.push(Box::new(prop));
self
}
pub fn with_deadlock_detection(mut self, enabled: bool) -> Self {
self.deadlock_detection = enabled;
self
}
pub(crate) fn step_candidates(
&self,
state: &S,
) -> Result<(Vec<(S, String)>, Unknowns), CheckerError> {
for prop in self.properties.iter() {
if !prop.check_state(state) {
return Err(CheckerError::PropertyViolation {
property: prop.name().to_owned(),
detail: None,
});
}
}
let mut successors: Vec<(S, String)> = Vec::new();
let mut successor_hashes: Vec<u64> = Vec::new();
let mut unknowns: Unknowns = Vec::new();
for rule in self.rules.iter() {
if rule.precondition(state) {
let mut next = state.clone();
match rule.apply(&mut next) {
Ok(true) => {
let hash = hash_of(&next);
let is_dup = successor_hashes
.iter()
.zip(successors.iter())
.any(|(&h, (s, _))| h == hash && *s == next);
if !is_dup {
successor_hashes.push(hash);
successors.push((next, rule.name().to_owned()));
}
}
Ok(false) => {}
Err(RuleError::Unknown(u)) => unknowns.push(u),
Err(RuleError::Model(what)) => {
return Err(CheckerError::ModelError {
rule: rule.name().to_owned(),
what: what.into(),
});
}
}
}
}
Ok((successors, unknowns))
}
pub(crate) fn step_finalize(
&mut self,
state: &S,
successors: Vec<(S, String)>,
unknowns: Unknowns,
) -> Result<(Vec<(S, String)>, Unknowns), CheckerError> {
if self.deadlock_detection && successors.is_empty() && unknowns.is_empty() {
return Err(CheckerError::Deadlock);
}
for prop in self.properties.iter_mut() {
prop.on_successors(state, &successors, &unknowns);
}
Ok((successors, unknowns))
}
}
impl<S: State> Stepping<S> for TransitionSystem<S> {
fn step(&mut self, state: &S) -> Result<(Vec<(S, String)>, Unknowns), CheckerError> {
let (succs, unknowns) = self.step_candidates(state)?;
self.step_finalize(state, succs, unknowns)
}
fn check_final(&self) -> Option<(String, String)> {
self.properties
.iter()
.find_map(|p| p.is_satisfied().map(|detail| (p.name().to_owned(), detail)))
}
}
impl<S: State> Default for TransitionSystem<S> {
fn default() -> Self {
Self::new()
}
}
pub struct TransitionSysSimulation<S: State, SimBy: State> {
inner: TransitionSystem<S>,
sim_by: TransitionSystem<SimBy>,
}
impl<S, SimBy> TransitionSysSimulation<S, SimBy>
where
S: State,
SimBy: State,
{
pub fn new(sim_by: TransitionSystem<SimBy>) -> Self {
Self {
inner: TransitionSystem::new(),
sim_by,
}
}
pub fn add_rule(&mut self, rule: impl Rule<S> + 'static) -> &mut Self {
self.inner.add_rule(rule);
self
}
pub fn add_property(&mut self, prop: impl Property<S> + 'static) -> &mut Self {
self.inner.add_property(prop);
self
}
pub fn with_deadlock_detection(mut self, enabled: bool) -> Self {
self.inner = self.inner.with_deadlock_detection(enabled);
self
}
}
impl<S, SimBy> Stepping<S> for TransitionSysSimulation<S, SimBy>
where
S: State + Into<SimBy> + PartialEq<SimBy>,
SimBy: State,
{
fn step(&mut self, state: &S) -> Result<(Vec<(S, String)>, Unknowns), CheckerError> {
let sim_by_state: SimBy = state.clone().into();
let (sim_by_succs, _) = self.sim_by.step(&sim_by_state)?;
let (candidates, unknowns) = self.inner.step_candidates(state)?;
let mut filtered = Vec::new();
for (s, rule_name) in candidates {
if sim_by_succs.iter().any(|(ss, _)| &s == ss) {
filtered.push((s, rule_name));
} else {
return Err(CheckerError::PropertyViolation {
property: "SIMULATION".to_owned(),
detail: None,
});
}
}
self.inner.step_finalize(state, filtered, unknowns)
}
fn check_final(&self) -> Option<(String, String)> {
self.inner.check_final()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Clone, Hash, PartialEq, Eq, Debug)]
struct Counter(u32);
impl fmt::Display for Counter {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Counter({})", self.0)
}
}
fn make_ts(limit: u32) -> TransitionSystem<Counter> {
let mut ts = TransitionSystem::new();
ts.add_rule(rule(
"increment",
move |s: &Counter| s.0 < limit,
|s: &mut Counter| {
s.0 += 1;
true
},
));
ts.add_property(invariant("non_negative", move |s: &Counter| s.0 <= limit));
ts
}
#[test]
fn step_produces_successors() {
let mut ts = make_ts(3);
let (succs, unknowns) = ts.step(&Counter(0)).unwrap();
assert_eq!(succs.len(), 1);
assert_eq!(succs[0].0, Counter(1));
assert_eq!(succs[0].1, "increment");
assert!(unknowns.is_empty());
}
#[test]
fn deadlock_at_limit() {
let mut ts = make_ts(2);
let err = ts.step(&Counter(2)).unwrap_err();
assert!(matches!(err, CheckerError::Deadlock));
}
#[test]
fn invariant_violation() {
let mut ts: TransitionSystem<Counter> = TransitionSystem::new();
ts.add_rule(rule(
"inc",
|_| true,
|s: &mut Counter| {
s.0 += 1;
true
},
));
ts.add_property(invariant("zero_only", |s: &Counter| s.0 == 0));
ts.step(&Counter(0)).unwrap();
let err = ts.step(&Counter(1)).unwrap_err();
assert!(matches!(err, CheckerError::PropertyViolation { .. }));
}
#[test]
fn no_deadlock_when_disabled() {
let mut ts = TransitionSystem::new().with_deadlock_detection(false);
ts.add_rule(rule(
"never_fires",
|_: &Counter| false,
|_: &mut Counter| true,
));
let (succs, unknowns) = ts.step(&Counter(0)).unwrap();
assert!(succs.is_empty());
assert!(unknowns.is_empty());
}
#[test]
fn unknown_collected_and_not_deadlock() {
let mut ts = TransitionSystem::new();
ts.add_rule(rule_try(
"maybe_unknown",
|_: &Counter| true,
|_: &mut Counter| Err(Unknown::new(42).into()),
));
let (succs, unknowns) = ts.step(&Counter(0)).unwrap();
assert!(succs.is_empty());
assert_eq!(unknowns.len(), 1);
assert_eq!(unknowns[0].code, 42);
}
#[test]
fn model_error_from_rule() {
let mut ts = TransitionSystem::new();
ts.add_rule(rule_try(
"guarded",
|_: &Counter| true,
|s: &mut Counter| {
s.0 += 1;
error_if(s.0 > 1, "counter exceeded 1")?;
Ok(true)
},
));
ts.step(&Counter(0)).unwrap();
let err = ts.step(&Counter(1)).unwrap_err();
assert!(matches!(
err,
CheckerError::ModelError { ref rule, ref what }
if rule == "guarded" && what == "counter exceeded 1"
));
}
#[test]
fn duplicate_successors_deduped() {
let mut ts = TransitionSystem::new();
for name in ["inc_a", "inc_b"] {
ts.add_rule(rule(
name,
|_: &Counter| true,
|s: &mut Counter| {
s.0 += 1;
true
},
));
}
let (succs, _) = ts.step(&Counter(0)).unwrap();
assert_eq!(succs.len(), 1);
assert_eq!(succs[0].1, "inc_a"); }
}