use verif::prelude::*;
use verif::smt::{self, var};
use verif::wp::{verify, Established, Stmt};
struct Lcg(u64);
impl Lcg {
fn next(&mut self) -> u64 {
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
self.0 >> 33
}
fn below(&mut self, n: u64) -> u64 {
if n == 0 { 0 } else { self.next() % n }
}
}
#[derive(Clone, Copy)]
enum Claim {
Le(u8),
Eq(u8),
Lt(u8),
}
impl Claim {
fn holds(self, acc: u8) -> bool {
match self {
Claim::Le(b) => acc <= b,
Claim::Eq(b) => acc == b,
Claim::Lt(b) => acc < b,
}
}
fn build(self, acc: Var) -> Pred {
match self {
Claim::Le(b) => acc.le_val(b as u64),
Claim::Eq(b) => acc.eq_val(b as u64),
Claim::Lt(b) => acc.lt_val(b as u64),
}
}
}
enum Step {
AddConst(u8),
AddVar,
Claim(Claim),
If { cond_lt: u8, then_: Vec<Step>, else_: Vec<Step> },
While { guard_lt: u8, body: Vec<Step> },
}
fn run_checked(steps: &[Step], mut acc: u8, x: u8) -> Option<u8> {
for s in steps {
match s {
Step::AddConst(k) => acc = acc.wrapping_add(*k),
Step::AddVar => acc = acc.wrapping_add(x),
Step::Claim(c) => {
if !c.holds(acc) {
return None;
}
}
Step::If { cond_lt, then_, else_ } => {
let branch = if acc < *cond_lt { then_ } else { else_ };
acc = run_checked(branch, acc, x)?;
}
Step::While { guard_lt, body } => {
let mut fuel = 300;
while acc < *guard_lt && fuel > 0 {
acc = run_checked(body, acc, x)?;
fuel -= 1;
}
}
}
}
Some(acc)
}
fn run(steps: &[Step], acc: u8, x: u8) -> u8 {
run_checked(steps, acc, x).unwrap_or(acc)
}
fn build(steps: &[Step], acc: Var, x: Var) -> &'static Stmt<'static> {
let mut seq: Stmt = Stmt::Skip;
for s in steps.iter().rev() {
let one: Stmt = match s {
Step::AddConst(k) => Stmt::Assign { var: acc, expr: acc + *k as u32 },
Step::AddVar => Stmt::Assign { var: acc, expr: acc + x },
Step::Claim(c) => Stmt::Assert(c.build(acc)),
Step::If { cond_lt, then_, else_ } => Stmt::If {
cond: acc.lt_val(*cond_lt as u64),
then_: Box::leak(Box::new(build(then_, acc, x))),
else_: Box::leak(Box::new(build(else_, acc, x))),
},
Step::While { guard_lt, body } => Stmt::While {
cond: acc.lt_val(*guard_lt as u64),
invariant: acc.le_val(255),
variant: Some(smt::sub(smt::word(*guard_lt as u64, 8), acc)),
body: Box::leak(Box::new(build(body, acc, x))),
},
};
seq = Stmt::Seq { first: Box::leak(Box::new(one)), second: Box::leak(Box::new(seq)) };
}
Box::leak(Box::new(seq))
}
fn make_steps(r: &mut Lcg, depth: u32, n: usize) -> Vec<Step> {
gen_with(r, depth, n, true)
}
fn gen_with(r: &mut Lcg, depth: u32, n: usize, claims: bool) -> Vec<Step> {
let top = if claims { 7 } else { 6 };
(0..n)
.map(|_| match r.below(top) {
0 if depth > 0 => {
let (nt, ne) = (r.below(3) as usize, r.below(3) as usize);
Step::If { cond_lt: 1 + r.below(250) as u8, then_: gen_with(r, depth - 1, nt, claims), else_: gen_with(r, depth - 1, ne, claims) }
}
1 if depth > 0 => {
let nb = r.below(3) as usize;
Step::While { guard_lt: 1 + r.below(250) as u8, body: gen_with(r, depth - 1, nb, claims) }
}
2 => Step::AddVar,
3 => {
let b = r.below(256) as u8;
match r.below(3) {
0 => Step::Claim(Claim::Le(b)),
1 => Step::Claim(Claim::Eq(b)),
_ => Step::Claim(Claim::Lt(b)),
}
}
k => Step::AddConst((k % 3) as u8 + 1),
})
.collect()
}
#[test]
fn a_verified_report_is_never_wrong_about_loops() {
let mut r = Lcg(0x7f3a_91b5_2c8d_0044);
let mut verified = 0u32;
let mut total = 0u32;
for _ in 0..600 {
let n = 1 + r.below(3) as usize;
let steps = gen_with(&mut r, 2, n, false);
let mut outputs = [0u8; 256];
for (v, o) in outputs.iter_mut().enumerate() {
*o = run(&steps, v as u8, v as u8);
}
let use_eq = r.below(2) == 0;
let bound = if use_eq {
outputs[r.below(256) as usize] as u64
} else {
let m = *outputs.iter().max().unwrap() as u64;
if r.below(2) == 0 { m } else { r.below(m + 1) }
};
smt::with_fresh(|| {
let x = var(8);
let acc = var(8);
let prog = build(&steps, acc, x);
let post = if use_eq { acc.eq_val(bound) } else { acc.le_val(bound) };
let report = verify(prog, smt::truth(true), post);
let mut first_bad = None;
for (v, out) in outputs.iter().enumerate() {
let ok = if use_eq { *out as u64 == bound } else { *out as u64 <= bound };
if !ok {
first_bad = Some((v as u8, *out));
break;
}
}
if report.establishes() == Established::Total {
total += 1;
}
if report.is_verified() {
verified += 1;
assert!(
first_bad.is_none(),
"the report says verified, but a concrete run falsifies the contract: \
bound={}, eq={}, first bad input x={:?}",
bound,
use_eq,
first_bad
);
}
});
}
assert!(verified > 30, "too few verified reports to be meaningful: {}", verified);
assert!(total > 20, "too few Total reports to be meaningful: {}", total);
}
#[test]
fn a_verified_report_never_misses_a_failed_claim() {
let mut r = Lcg(0x2b9c_4e17_a3f0_8811);
let mut verified = 0u32;
let mut with_failed_claim = 0u32;
for _ in 0..800 {
let n = 1 + r.below(4) as usize;
let steps = make_steps(&mut r, 2, n);
smt::with_fresh(|| {
let x = var(8);
let acc = var(8);
let prog = build(&steps, acc, x);
let report = verify(prog, smt::truth(true), smt::truth(true));
let mut first_bad = None;
for v in 0..=255u8 {
if run_checked(&steps, v, v).is_none() {
first_bad = Some(v);
break;
}
}
if first_bad.is_some() {
with_failed_claim += 1;
}
if report.is_verified() {
verified += 1;
assert!(
first_bad.is_none(),
"the report says verified, but a concrete run reaches a false claim: \
first bad input x={:?}",
first_bad
);
}
});
}
assert!(verified > 30, "too few verified reports to be meaningful: {}", verified);
assert!(
with_failed_claim > 30,
"too few programs with a genuinely false claim to be meaningful: {}",
with_failed_claim
);
}
#[derive(Clone, Copy)]
enum Act {
Add(u8),
Set(u8),
Skip,
}
impl Act {
fn apply(self, v: u8) -> u8 {
match self {
Act::Add(k) => v.wrapping_add(k),
Act::Set(k) => k,
Act::Skip => v,
}
}
fn build(self, v: Var) -> Stmt<'static> {
match self {
Act::Add(k) => Stmt::Assign { var: v, expr: v + k as u32 },
Act::Set(k) => Stmt::Assign { var: v, expr: smt::word(k as u64, 8) },
Act::Skip => Stmt::Skip,
}
}
fn name(self) -> &'static str {
match self {
Act::Add(k) => match k { 1 => "Add(1)", 2 => "Add(2)", _ => "Add(50)" },
Act::Set(k) => match k { 0 => "Set(0)", 10 => "Set(10)", 100 => "Set(100)", _ => "Set(255)" },
Act::Skip => "Skip",
}
}
}
struct Nested {
outer_guard: u8,
outer: Act,
inner_guard: u8,
inner: Act,
inner_on_i: Option<Act>,
start_i: u8,
start_j: u8,
}
fn run_nested(p: &Nested) -> Option<u8> {
let (mut i, mut j) = (p.start_i, p.start_j);
let mut fuel = 100_000u32;
while i < p.outer_guard {
if fuel == 0 {
return None;
}
fuel -= 1;
i = p.outer.apply(i);
while j < p.inner_guard {
if fuel == 0 {
return None;
}
fuel -= 1;
j = p.inner.apply(j);
if let Some(a) = p.inner_on_i {
i = a.apply(i);
}
}
j = p.start_j;
}
Some(i)
}
fn build_nested(p: &Nested) -> Stmt<'static> {
let i = var(8);
let j = var(8);
let mut inner_body: Stmt<'static> = Stmt::Skip;
if let Some(a) = p.inner_on_i {
inner_body = Stmt::Seq {
first: Box::leak(Box::new(inner_body)),
second: Box::leak(Box::new(a.build(i))),
};
}
let inner_body = Stmt::Seq {
first: Box::leak(Box::new(p.inner.build(j))),
second: Box::leak(Box::new(inner_body)),
};
let inner_loop = Stmt::While {
cond: j.lt_val(p.inner_guard as u64),
invariant: j.le_val(255),
variant: Some(smt::sub(smt::word(p.inner_guard as u64, 8), j)),
body: Box::leak(Box::new(inner_body)),
};
let reset_j = Stmt::Assign { var: j, expr: smt::word(p.start_j as u64, 8) };
let outer_body = Stmt::Seq {
first: Box::leak(Box::new(p.outer.build(i))),
second: Box::leak(Box::new(Stmt::Seq {
first: Box::leak(Box::new(inner_loop)),
second: Box::leak(Box::new(reset_j)),
})),
};
Stmt::While {
cond: i.lt_val(p.outer_guard as u64),
invariant: i.le_val(255),
variant: Some(smt::sub(smt::word(p.outer_guard as u64, 8), i)),
body: Box::leak(Box::new(outer_body)),
}
}
#[test]
fn a_total_report_means_the_nested_loop_terminates() {
let mut total = 0u32;
let mut divergent = 0u32;
let outer_acts = [Act::Add(1), Act::Add(2), Act::Add(50), Act::Set(0), Act::Skip];
let inner_acts = [Act::Add(1), Act::Add(2), Act::Set(10), Act::Set(100), Act::Set(0), Act::Skip];
let inner_on_i = [None, Some(Act::Set(0)), Some(Act::Add(1))];
for &outer_guard in &[10u8, 100] {
for &inner_guard in &[10u8, 100, 255] {
for &outer in &outer_acts {
for &inner in &inner_acts {
for &on_i in &inner_on_i {
for &(start_i, start_j) in &[(0u8, 0u8), (1, 0), (50, 5)] {
let p = Nested { outer_guard, outer, inner_guard, inner, inner_on_i: on_i, start_i, start_j };
let terminates = run_nested(&p);
if terminates.is_none() {
divergent += 1;
}
smt::with_fresh(|| {
let i = var(8);
let j = var(8);
let prog = build_nested(&p);
let pre = smt::and(i.eq_val(start_i as u64), j.eq_val(start_j as u64));
let report = verify(&prog, pre, smt::truth(true));
if report.establishes() == Established::Total {
total += 1;
assert!(
terminates.is_some(),
"the report says Total, but the program diverges: \
outer_guard={}, outer={}, inner_guard={}, inner={}, \
inner_on_i={:?}, start=({}, {})",
outer_guard, outer.name(), inner_guard, inner.name(),
on_i.map(Act::name), start_i, start_j
);
}
});
}
}
}
}
}
}
assert!(total > 20, "too few Total reports to be meaningful: {}", total);
assert!(
divergent > 0,
"the family must contain a divergent program, or it proves nothing"
);
}