use core::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Pred {
True,
False,
Eq(u64),
Ne(u64),
Lt(u64),
Le(u64),
Gt(u64),
Ge(u64),
Not(&'static Pred),
And(&'static Pred, &'static Pred),
Or(&'static Pred, &'static Pred),
}
impl Pred {
pub const fn eval(&self, value: u64) -> bool {
match self {
Pred::True => true,
Pred::False => false,
Pred::Eq(k) => value == *k,
Pred::Ne(k) => value != *k,
Pred::Lt(k) => value < *k,
Pred::Le(k) => value <= *k,
Pred::Gt(k) => value > *k,
Pred::Ge(k) => value >= *k,
Pred::Not(p) => !p.eval(value),
Pred::And(a, b) => a.eval(value) && b.eval(value),
Pred::Or(a, b) => a.eval(value) || b.eval(value),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ContractError {
pub kind: Obligation,
pub value: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Obligation {
Precondition,
Postcondition,
Invariant,
Assertion,
}
impl fmt::Display for ContractError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let kind = match self.kind {
Obligation::Precondition => "precondition",
Obligation::Postcondition => "postcondition",
Obligation::Invariant => "invariant",
Obligation::Assertion => "assertion",
};
write!(f, "{} violated at value {}", kind, self.value)
}
}
#[derive(Debug, Clone, Copy)]
pub struct Contract {
pub pre: Pred,
pub post: Pred,
}
impl Contract {
pub const fn new(pre: Pred, post: Pred) -> Contract {
Contract { pre, post }
}
pub const fn check_pre(&self, input: u64) -> Result<(), ContractError> {
if self.pre.eval(input) {
Ok(())
} else {
Err(ContractError { kind: Obligation::Precondition, value: input })
}
}
pub const fn check_post(&self, output: u64) -> Result<(), ContractError> {
if self.post.eval(output) {
Ok(())
} else {
Err(ContractError { kind: Obligation::Postcondition, value: output })
}
}
}
pub fn assert_that(p: Pred, value: u64) -> Result<(), ContractError> {
if p.eval(value) {
Ok(())
} else {
Err(ContractError { kind: Obligation::Assertion, value })
}
}
pub fn check_invariant(p: Pred, value: u64) -> Result<(), ContractError> {
if p.eval(value) {
Ok(())
} else {
Err(ContractError { kind: Obligation::Invariant, value })
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn predicates_evaluate() {
assert!(Pred::Lt(10).eval(9));
assert!(!Pred::Lt(10).eval(10));
assert!(Pred::Ge(10).eval(10));
assert!(Pred::And(&Pred::Ge(5), &Pred::Lt(10)).eval(7));
assert!(Pred::Not(&Pred::Eq(1)).eval(2));
}
#[test]
fn contract_reports_the_failing_obligation() {
let c = Contract::new(Pred::Lt(100), Pred::Lt(200));
assert!(c.check_pre(50).is_ok());
let err = c.check_pre(150).unwrap_err();
assert_eq!(err.kind, Obligation::Precondition);
assert_eq!(err.value, 150);
}
}