use std::path::{Path, PathBuf};
use verif::mir::spec;
use verif::mir::verify::{self, FnOutcome};
enum Want {
Verified(&'static [(&'static str, Contract)]),
Failed {
function: &'static str,
kind: &'static str,
},
}
#[derive(Debug)]
struct Contract {
requires: &'static [&'static str],
ensures: &'static [&'static str],
invariants: &'static [&'static str],
}
struct Fixture {
path: &'static str,
want: Want,
why: &'static str,
}
const ROOT: &str = "examples/comparison";
const OVERFLOW_ADD: &str = "panic: attempt to compute `{} + {}`, which would overflow";
const SAT_ADD_CONTRACT: Contract = Contract {
requires: &["true"],
ensures: &[
"ret >= a",
"ret >= b",
"a <= 65535u16 - b || ret == 65535u16",
"a > 65535u16 - b || ret == a + b",
],
invariants: &[],
};
const CLAMP_CONTRACT: Contract = Contract {
requires: &["lo <= hi"],
ensures: &[
"!(x < lo) || ret == lo",
"!(lo <= x && x > hi) || ret == hi",
"!(lo <= x && x <= hi) || ret == x",
],
invariants: &[],
};
const SUM_TO_CONTRACT: Contract = Contract {
requires: &["n <= 8"],
ensures: &["ret == n"],
invariants: &["i <= n && s == i"],
};
fn fixtures() -> Vec<Fixture> {
vec![
Fixture {
path: "target.rs",
want: Want::Verified(&[
("sat_add", SAT_ADD_CONTRACT),
("clamp", CLAMP_CONTRACT),
("sum_to", SUM_TO_CONTRACT),
]),
why: "the positive fixture: the same three functions every tool proves",
},
Fixture {
path: "bugs/target.rs",
want: Want::Failed {
function: "sat_add",
kind: OVERFLOW_ADD,
},
why: "swapped branches, so the guarded `+` is the one that can overflow",
},
Fixture {
path: "bugs/clamp.rs",
want: Want::Failed {
function: "clamp",
kind: "postcondition",
},
why: "returns `hi` below the range, so the contract's first disjunct is false",
},
Fixture {
path: "bugs/loop.rs",
want: Want::Failed {
function: "sum_to",
kind: "loop invariant preserved",
},
why: "the loop body adds two, so the invariant is not preserved",
},
]
}
fn main() {
let rustc = match std::env::var("VERIF_RUSTC") {
Ok(r) if !r.trim().is_empty() => r,
_ => {
eprintln!("comparison_check: set VERIF_RUSTC to a nightly `rustc`");
std::process::exit(2);
}
};
let mut failures: Vec<String> = Vec::new();
let mut checked = 0usize;
for f in fixtures() {
let path = PathBuf::from(ROOT).join(f.path);
checked += 1;
match check_one(&rustc, &path, &f) {
Ok(line) => println!("ok {:<20} {line}", f.path),
Err(why) => {
println!("FAIL {:<20} {why}", f.path);
failures.push(format!("{}: {why}", f.path));
}
}
}
for (name, src) in degenerate() {
checked += 1;
let tmp = write_scratch(&name, &src);
let why = "degenerate implementation the whole-function contract must refuse";
let r = check_failed(&rustc, &tmp, &name, "postcondition", why);
let _ = std::fs::remove_dir_all(tmp.parent().unwrap_or(&tmp));
match r {
Ok(line) => println!("ok {:<20} {line}", format!("degenerate/{name}")),
Err(why) => {
println!("FAIL {:<20} {why}", format!("degenerate/{name}"));
failures.push(format!("degenerate/{name}: {why}"));
}
}
}
println!("\nchecked {checked} fixture(s)");
if failures.is_empty() {
println!("every comparison claim held");
} else {
println!("\nUNEXPECTED:");
for f in &failures {
println!(" {f}");
}
std::process::exit(1);
}
}
fn check_one(rustc: &str, path: &Path, f: &Fixture) -> Result<String, String> {
match &f.want {
Want::Verified(expected) => check_verified(rustc, path, expected),
Want::Failed { function, kind } => check_failed(rustc, path, function, kind, f.why),
}
}
fn check_verified(
rustc: &str,
path: &Path,
expected: &[(&str, Contract)],
) -> Result<String, String> {
let text = std::fs::read_to_string(path)
.map_err(|e| format!("cannot read {}: {e}", path.display()))?;
let specs = spec::extract(&text);
let mir = verify::emit_mir_with(rustc, path).map_err(|e| format!("could not get MIR: {e}"))?;
for (name, want) in expected {
let Some(found) = resolve_contract(&specs, name) else {
return Err(format!(
"`{name}` carries no contract in the fixture, so the positive claim would go \
unchecked"
));
};
if found.ensures.is_empty() {
return Err(format!(
"`{name}` carries a contract but no `ensures:`, so only panic freedom would be \
checked -- the claimed result would go unchecked"
));
}
compare_clauses(name, "requires", want.requires, &found.requires)?;
compare_clauses(name, "ensures", want.ensures, &found.ensures)?;
compare_clauses(name, "invariant", want.invariants, &found.invariants)?;
}
let wanted: Vec<String> = expected.iter().map(|(n, _)| n.to_string()).collect();
let report =
verify::verify_mir_text(&mir, &specs, &wanted).map_err(|e| format!("driver error: {e}"))?;
if !report.missing.is_empty() {
return Err(format!(
"contracted but absent from the MIR: {:?}",
report.missing
));
}
if report.outcomes.len() != expected.len() {
return Err(format!(
"expected {} outcome(s) for {:?}, got {} ({:?})",
expected.len(),
expected.iter().map(|(n, _)| *n).collect::<Vec<_>>(),
report.outcomes.len(),
report
.outcomes
.iter()
.map(|(n, _)| n.as_str())
.collect::<Vec<_>>()
));
}
for (want, _) in expected {
let Some((name, outcome)) = report.outcomes.iter().find(|(n, _)| names_match(n, want))
else {
return Err(format!("`{want}` has no outcome in the report"));
};
match outcome {
FnOutcome::Verified { .. } => {}
FnOutcome::Failed { kind, detail } => {
return Err(format!(
"{name}: expected Verified, got FAILED ({kind} — {detail})"
));
}
FnOutcome::Incomplete { reasons, .. } => {
return Err(format!(
"{name}: incomplete, so not verified ({})",
reasons.join("; ")
));
}
FnOutcome::Skipped { reason } => {
return Err(format!("{name}: skipped, so never checked ({reason})"));
}
}
}
Ok(format!("{} function(s) verified", expected.len()))
}
fn check_failed(
rustc: &str,
path: &Path,
function: &str,
want_kind: &str,
why: &str,
) -> Result<String, String> {
let text = std::fs::read_to_string(path)
.map_err(|e| format!("cannot read {}: {e}", path.display()))?;
let specs = spec::extract(&text);
let mir = verify::emit_mir_with(rustc, path).map_err(|e| format!("could not get MIR: {e}"))?;
let only = vec![function.to_string()];
let report =
verify::verify_mir_text(&mir, &specs, &only).map_err(|e| format!("driver error: {e}"))?;
if !report.missing.is_empty() {
return Err(format!(
"contracted but absent from the MIR: {:?}",
report.missing
));
}
if report.outcomes.len() != 1 {
return Err(format!(
"expected exactly one outcome for `{function}`, got {} ({:?})",
report.outcomes.len(),
report
.outcomes
.iter()
.map(|(n, _)| n.as_str())
.collect::<Vec<_>>()
));
}
let (name, outcome) = &report.outcomes[0];
match outcome {
FnOutcome::Failed { kind, detail } => {
if kind == want_kind {
Ok(format!("{name}: FAILED — {kind} (witness: {detail})"))
} else {
Err(format!(
"{name}: failed on the WRONG obligation: expected `{want_kind}`, got `{kind}` \
-- the fixture is not testing what it claims ({why})"
))
}
}
FnOutcome::Skipped { reason } => Err(format!(
"{name}: SKIPPED, so the contract was never refuted -- the fixture is a lost proof, \
not a caught defect ({reason})"
)),
FnOutcome::Incomplete { reasons, .. } => Err(format!(
"{name}: INCOMPLETE, so no counterexample was found -- the fixture is a lost proof, \
not a caught defect ({})",
reasons.join("; ")
)),
FnOutcome::Verified { .. } => Err(format!(
"{name}: VERIFIED, so the defect was not caught at all"
)),
}
}
fn compare_clauses(name: &str, kind: &str, want: &[&str], found: &[String]) -> Result<(), String> {
if want == found {
return Ok(());
}
Err(format!(
"`{name}` states a different `{kind}:` than the one claimed:\n \
expected: {want:?}\n found: {found:?}"
))
}
fn resolve_contract<'a>(specs: &'a spec::Specs, name: &str) -> Option<&'a spec::FnContract> {
if let Some(c) = specs.by_fn.get(name) {
return Some(c);
}
specs
.by_fn
.iter()
.find(|(k, _)| names_match(k, name))
.map(|(_, c)| c)
}
fn names_match(key: &str, want: &str) -> bool {
key == want || key.rsplit("::").next() == Some(want)
}
fn degenerate() -> Vec<(String, String)> {
vec![
(
"sat_add".to_string(),
"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n requires: true,\n ensures: ret >= a,\n ensures: ret >= b,\n ensures: a <= 65535u16 - b || ret == 65535u16,\n ensures: a > 65535u16 - b || ret == a + b,\n}\npub fn sat_add(a: u16, b: u16) -> u16 { 65535u16 }\n"
.to_string(),
),
(
"clamp".to_string(),
"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n requires: lo <= hi,\n ensures: !(x < lo) || ret == lo,\n ensures: !(lo <= x && x > hi) || ret == hi,\n ensures: !(lo <= x && x <= hi) || ret == x,\n}\npub fn clamp(x: u16, lo: u16, hi: u16) -> u16 { lo }\n"
.to_string(),
),
]
}
fn write_scratch(name: &str, src: &str) -> PathBuf {
use std::sync::atomic::{AtomicU64, Ordering};
static SEQ: AtomicU64 = AtomicU64::new(0);
let seq = SEQ.fetch_add(1, Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!(
"verif-comparison-{}-{seq}-{name}",
std::process::id()
));
let _ = std::fs::create_dir_all(&dir);
std::fs::write(
dir.join("Cargo.toml"),
"[package]\nname = \"scratch\"\nversion = \"0.0.0\"\nedition = \"2021\"\n",
)
.expect("write scratch manifest");
let path = dir.join("probe.rs");
std::fs::write(&path, src).expect("write scratch fixture");
path
}