use verif::mir::spec;
use verif::mir::verify::{self, FnOutcome};
#[path = "../examples/mir_targets/actuator.rs"]
mod actuator;
use actuator::*;
const TARGET: &str = "examples/mir_targets/actuator.rs";
fn rustc() -> Option<String> {
if let Some(p) = std::env::var("VERIF_RUSTC").ok().filter(|s| !s.is_empty()) {
return Some(p);
}
let out = std::process::Command::new("rustc").arg("--version").output().ok()?;
if !out.status.success() {
return None;
}
Some("rustc".to_string())
}
fn verify_all() -> Option<verify::FileReport> {
let rustc = rustc()?;
let only: Vec<String> = [
"clamp",
"rate_limit",
"sat_add",
"sat_sub",
"shift_const",
"shift_left",
"sat_shift",
"sat_mul",
"unchecked_add",
"unchecked_sub",
"unchecked_div",
"unchecked_mul",
"off_by_one_guard",
"clamp_signed",
"checked_div_signed",
"unchecked_div_signed",
"signed_add_misguarded",
"signed_add_guarded",
"signed_mul_guarded",
"signed_mul_negative",
"checked_neg",
"inline_saves_arg",
"inline_clobber_would_pass",
"bool_ret_false",
"bool_ret_true",
"nested_parens",
"vacuous_precondition",
"add_always_overflows",
"div_by_always_zero",
"clamp_bounds",
"first_of",
"slice_alias_tripwire",
"assert_guarded",
"assert_misguarded",
"panic_guarded",
]
.iter()
.map(|s| s.to_string())
.collect();
match verify::verify_file_with(&rustc, std::path::Path::new(TARGET), &only) {
Ok(r) => Some(r),
Err(e) => panic!("frontend failed: {e}"),
}
}
fn outcome<'a>(report: &'a verify::FileReport, name: &str) -> &'a FnOutcome {
report
.outcomes
.iter()
.find(|(n, _)| n == name)
.map(|(_, o)| o)
.unwrap_or_else(|| panic!("{name} missing from the report"))
}
fn assert_refuted(report: &verify::FileReport, name: &str) {
let o = outcome(report, name);
assert!(
matches!(o, FnOutcome::Failed { .. }),
"`{name}` must be refuted with a counterexample, got: {o}"
);
}
#[test]
fn scanner_reads_contracts_and_ignores_inner_docs() {
let src = r#"
//! requires: this is documentation, not a contract
//! ensures: and neither is this
/// requires: b != 0
/// ensures: ret <= a
pub fn div(a: u32, b: u32) -> u32 {
a / b
}
"#;
let specs = spec::extract(src);
let c = specs.get("div").expect("div should have a contract");
assert_eq!(c.requires, vec!["b != 0".to_string()]);
assert_eq!(c.ensures, vec!["ret <= a".to_string()]);
}
#[test]
fn scanner_does_not_leak_a_contract_onto_a_later_function() {
let src = r#"
/// requires: a > 0
const LIMIT: u32 = 10;
pub fn unrelated(a: u32) -> u32 { a }
"#;
let specs = spec::extract(src);
assert!(
specs.get("unrelated").is_none(),
"a contract before a non-fn item must not attach to the next fn"
);
}
#[test]
fn scanner_finds_a_pub_crate_fn() {
let src = "/// requires: a > 0\npub(crate) fn f(a: u32) -> u32 { a }\n";
let specs = spec::extract(src);
assert!(specs.get("f").is_some(), "`pub(crate) fn` must be recognized");
}
#[test]
fn contract_expressions_evaluate() {
use verif::smt;
smt::with_fresh(|| {
let mut args = std::collections::BTreeMap::new();
args.insert("b".to_string(), smt::var_named(2, 32));
let p = spec::eval_requires("b != 0", &args, &std::collections::BTreeSet::new(), &spec::FieldEnv::default()).expect("should parse");
assert!(!smt::prove(p).is_proved());
});
}
#[test]
fn a_contradictory_contract_is_refused_or_vacuous() {
use verif::smt;
smt::with_fresh(|| {
let mut args = std::collections::BTreeMap::new();
args.insert("b".to_string(), smt::var_named(2, 32));
let p = spec::eval_requires("b < 3 && b > 10", &args, &std::collections::BTreeSet::new(), &spec::FieldEnv::default()).expect("should parse");
assert_eq!(smt::find_model(p), smt::Verdict::Unsat);
});
}
#[test]
fn refuses_a_contract_it_cannot_read() {
use verif::smt;
smt::with_fresh(|| {
let args = std::collections::BTreeMap::new();
assert!(spec::eval_requires("foo(b) < 3", &args, &std::collections::BTreeSet::new(), &spec::FieldEnv::default()).is_err());
assert!(spec::eval_requires("b as u64 < 3", &args, &std::collections::BTreeSet::new(), &spec::FieldEnv::default()).is_err());
assert!(spec::eval_requires("zzz < 3", &args, &std::collections::BTreeSet::new(), &spec::FieldEnv::default()).is_err());
});
}
#[test]
fn a_literal_is_sized_from_the_operand_it_meets() {
use verif::smt;
smt::with_fresh(|| {
let mut args = std::collections::BTreeMap::new();
args.insert("xs__len".to_string(), smt::var(64));
let ret = smt::var(8);
let p = spec::eval_ensures(
"ret <= 255",
&args,
Some(ret),
spec::RET_IS_UNKNOWN,
&std::collections::BTreeSet::new(),
false,
&spec::FieldEnv::default(),
&std::collections::BTreeMap::new(),
)
.expect("a narrow literal against a wide name must still parse");
assert!(
!smt::is_ill_formed(),
"the literal must be resized to `ret`'s 8 bits, not left at 64"
);
assert!(smt::prove(p).is_proved(), "`ret <= 255` must hold for every u8");
});
}
#[test]
fn a_literal_that_does_not_fit_is_refused_not_truncated() {
use verif::smt;
smt::with_fresh(|| {
let mut args = std::collections::BTreeMap::new();
args.insert("a".to_string(), smt::var(8));
let err = spec::eval_requires(
"a <= 300",
&args,
&std::collections::BTreeSet::new(),
&spec::FieldEnv::default(),
)
.expect_err("300 does not fit a u8, so the contract must be refused");
assert!(
err.to_string().contains("300") && err.to_string().contains("8-bit"),
"the refusal must name the value and the width, got: {err}"
);
});
}
#[test]
fn a_bare_ret_on_an_aggregate_names_the_aggregate_reason() {
use verif::smt;
smt::with_fresh(|| {
let args = std::collections::BTreeMap::new();
let err = spec::eval_ensures(
"ret <= 5",
&args,
None,
spec::RET_IS_AGGREGATE,
&std::collections::BTreeSet::new(),
false,
&spec::FieldEnv::default(),
&std::collections::BTreeMap::new(),
)
.expect_err("a bare `ret` on an aggregate must be refused");
assert!(
err.to_string().contains(spec::RET_IS_AGGREGATE),
"the message must name the aggregate cause and the fix, got: {err}"
);
});
}
#[test]
fn a_bare_ret_with_an_unknown_value_names_the_unknown_reason() {
use verif::smt;
smt::with_fresh(|| {
let args = std::collections::BTreeMap::new();
let err = spec::eval_ensures(
"ret <= 5",
&args,
None,
spec::RET_IS_UNKNOWN,
&std::collections::BTreeSet::new(),
false,
&spec::FieldEnv::default(),
&std::collections::BTreeMap::new(),
)
.expect_err("a bare `ret` with no value must be refused");
assert!(
err.to_string().contains(spec::RET_IS_UNKNOWN),
"a scalar return must not be reported as an aggregate, got: {err}"
);
});
}
#[test]
fn a_literal_in_arithmetic_is_sized_to_its_operand() {
let Some(report) = verify_realistic(&["add_literal_wide_scope"]) else { return };
let o = outcome(&report, "add_literal_wide_scope");
assert!(o.is_verified(), "`add_literal_wide_scope` must verify, got: {o}");
}
#[test]
fn a_named_type_bound_keeps_its_own_width() {
use verif::smt;
smt::with_fresh(|| {
let mut args = std::collections::BTreeMap::new();
args.insert("a".to_string(), smt::var(8));
args.insert("xs__len".to_string(), smt::var(64));
let mut signed = std::collections::BTreeSet::new();
signed.insert("a".to_string());
let p = spec::eval_requires("a >= i8::MIN", &args, &signed, &spec::FieldEnv::default())
.expect("`a >= i8::MIN` must parse even with a wide name in scope");
assert!(!smt::is_ill_formed(), "the bound must be built at 8 bits");
assert!(smt::prove(p).is_proved(), "`a >= i8::MIN` must hold for every i8");
});
}
#[test]
fn a_negative_literal_is_sign_extended_to_the_operand() {
use verif::smt;
smt::with_fresh(|| {
let mut args = std::collections::BTreeMap::new();
args.insert("a".to_string(), smt::var(8));
let mut signed = std::collections::BTreeSet::new();
signed.insert("a".to_string());
let p = spec::eval_requires("a >= -10", &args, &signed, &spec::FieldEnv::default())
.expect("`a >= -10` must parse");
assert!(!smt::is_ill_formed(), "the literal must be resized to 8 bits");
let minus_ten = smt::word(0xF6, 8);
let bad = smt::and(p, smt::slt(args["a"], minus_ten));
assert_eq!(
smt::find_model(bad),
smt::Verdict::Unsat,
"`a >= -10` must exclude exactly `a < -10`"
);
});
smt::with_fresh(|| {
let mut args = std::collections::BTreeMap::new();
args.insert("a".to_string(), smt::var(8));
args.insert("xs__len".to_string(), smt::var(64));
let mut signed = std::collections::BTreeSet::new();
signed.insert("a".to_string());
let p = spec::eval_requires("a >= -10", &args, &signed, &spec::FieldEnv::default())
.expect("`a >= -10` must parse with a wide name in scope");
assert!(
!smt::is_ill_formed(),
"narrowing a negative literal must take the low bits, not rebuild a wide word"
);
assert!(
!matches!(smt::find_model(p), smt::Verdict::Unsat),
"`a >= -10` must be satisfiable"
);
assert!(!smt::prove(p).is_proved(), "`a >= -10` must not hold for every i8");
});
}
#[test]
fn guarded_functions_verify() {
let Some(report) = verify_all() else { return };
for name in [
"clamp",
"rate_limit",
"sat_add",
"sat_sub",
"shift_const",
"sat_shift",
"clamp_bounds",
] {
let o = outcome(&report, name);
assert!(
o.is_verified(),
"{name} should verify, got: {o}\n{}",
report_source_hint()
);
}
}
#[test]
fn unchecked_functions_are_refuted() {
let Some(report) = verify_all() else { return };
for name in [
"unchecked_add",
"unchecked_sub",
"unchecked_div",
"unchecked_mul",
"shift_left",
] {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Failed { .. }),
"{name} must be refuted, got: {o}"
);
}
}
#[test]
fn counterexamples_really_panic() {
let Some(report) = verify_all() else { return };
let prev = std::panic::take_hook();
std::panic::set_hook(Box::new(|_| {}));
let mut checked = 0;
let mut failures: Vec<String> = Vec::new();
for name in [
"unchecked_add",
"unchecked_sub",
"unchecked_div",
"unchecked_mul",
"shift_left",
"unchecked_div_signed",
"signed_add_misguarded",
"signed_mul_negative",
] {
let o = outcome(&report, name);
let FnOutcome::Failed { detail, .. } = o else {
continue;
};
let names = match name {
"unchecked_div" => ("n", "d"),
"shift_left" => ("x", "n"),
_ => ("a", "b"),
};
let (a, b) = parse_cex_args(detail, names);
let a = a.unwrap_or(0);
let b = b.unwrap_or(0);
let panicked = match name {
"unchecked_add" => std::panic::catch_unwind(|| unchecked_add(a as u16, b as u16)).is_err(),
"unchecked_sub" => std::panic::catch_unwind(|| unchecked_sub(a as u16, b as u16)).is_err(),
"unchecked_div" => std::panic::catch_unwind(|| unchecked_div(a as u32, b as u32)).is_err(),
"unchecked_mul" => std::panic::catch_unwind(|| unchecked_mul(a as u8, b as u8)).is_err(),
"shift_left" => std::panic::catch_unwind(|| shift_left(a as u16, b as u16)).is_err(),
"unchecked_div_signed" => {
std::panic::catch_unwind(|| unchecked_div_signed(a as i16, b as i16)).is_err()
}
"signed_add_misguarded" => {
std::panic::catch_unwind(|| signed_add_misguarded(a as i8, b as i8)).is_err()
}
"signed_mul_negative" => {
std::panic::catch_unwind(|| signed_mul_negative(a as i8, b as i8)).is_err()
}
_ => unreachable!(),
};
if !panicked {
failures.push(format!(
"{name}: counterexample a={a} b={b} did not actually panic, \
so the engine reported a defect that is not there"
));
}
checked += 1;
}
std::panic::set_hook(prev);
assert!(failures.is_empty(), "{}", failures.join("\n"));
assert!(checked >= 3, "expected several counterexamples, checked {checked}");
}
#[test]
fn a_wrong_postcondition_is_caught() {
let Some(report) = verify_all() else { return };
let o = outcome(&report, "off_by_one_guard");
match o {
FnOutcome::Failed { kind, detail } => {
assert!(
kind.contains("postcondition"),
"the failing obligation should be the postcondition, got kind `{kind}`"
);
assert!(
detail.contains("a =") && detail.contains("b ="),
"the witness should name both arguments by their source names, got: {detail}"
);
assert!(
!detail.contains("v1:"),
"the witness must not fall back to `v1:` for a named argument, got: {detail}"
);
}
other => panic!("a wrong postcondition must be refuted, got: {other}"),
}
}
#[test]
fn a_counterexample_is_rendered_with_source_names() {
let Some(report) = verify_all() else { return };
for (name, expected) in [
("unchecked_add", &["a = ", "b = "][..]),
("unchecked_div", &["d = "][..]),
("shift_left", &["n = "][..]),
("signed_mul_negative", &["a = ", "b = "][..]),
] {
let o = outcome(&report, name);
let FnOutcome::Failed { detail, .. } = o else {
panic!("{name} must be refuted, got: {o}");
};
for want in expected {
assert!(
detail.contains(want),
"{name}: the witness should name its argument `{want}`, got: {detail}"
);
}
assert!(
!detail.contains("v1:") && !detail.contains("v2:"),
"{name}: a named argument must not fall back to `vN:`, got: {detail}"
);
}
let o = outcome(&report, "off_by_one_guard");
let FnOutcome::Failed { detail, .. } = o else {
panic!("off_by_one_guard must be refuted, got: {o}");
};
assert!(
detail.contains("a = 32768") && detail.contains("b = 32768"),
"the guard's witness must name both arguments, got: {detail}"
);
let Some(report) = verify_realistic(&["a_field_array_write_is_not_the_seed"]) else {
return;
};
let o = outcome(&report, "a_field_array_write_is_not_the_seed");
let FnOutcome::Failed { detail, .. } = o else {
panic!("a_field_array_write_is_not_the_seed must be refuted, got: {o}");
};
assert!(
detail.contains("v") && detail.contains(":u8 = "),
"a variable with no source name must still render as `vN:uW = value`, got: {detail}"
);
}
#[test]
fn verified_functions_do_not_panic_concretely() {
let Some(report) = verify_all() else { return };
if !outcome(&report, "sat_add").is_verified() {
return;
}
let prev = std::panic::take_hook();
std::panic::set_hook(Box::new(|_| {}));
let mut violations = Vec::new();
let mut vals: Vec<u16> = vec![0, 1, 2, 100, 32767, 32768, 65534, 65535];
for i in 0..40u32 {
vals.push((i.wrapping_mul(1657)) as u16);
}
for &a in &vals {
for &b in &vals {
if std::panic::catch_unwind(|| sat_add(a, b)).is_err() {
violations.push((a, b));
}
}
}
std::panic::set_hook(prev);
assert!(
violations.is_empty(),
"sat_add was verified but panics on {violations:?}"
);
}
#[test]
fn sat_mul_is_verified_by_the_exact_division_overflow_test() {
let Some(report) = verify_all() else { return };
let o = outcome(&report, "sat_mul");
assert!(
o.is_verified(),
"sat_mul must be verified now that the multiply-overflow test is exact: {o}"
);
}
#[test]
fn signed_arithmetic_is_not_verified_as_unsigned() {
let Some(report) = verify_all() else { return };
let o = outcome(&report, "signed_add_misguarded");
assert!(
matches!(o, FnOutcome::Failed { .. }),
"a signed add that overflows on `127 + 1` must be refuted, got: {o}"
);
for name in ["signed_add_guarded", "signed_mul_guarded", "clamp_signed", "checked_neg"] {
let o = outcome(&report, name);
assert!(o.is_verified(), "{name} should verify, got: {o}");
}
let o = outcome(&report, "signed_mul_negative");
assert!(
matches!(o, FnOutcome::Failed { .. }),
"a signed multiply of two negatives must be refuted, got: {o}"
);
}
#[test]
fn the_min_constant_is_the_top_bit() {
let Some(report) = verify_all() else { return };
let o = outcome(&report, "checked_neg");
assert!(
o.is_verified(),
"checked_neg excludes i8::MIN and should verify, got: {o}"
);
let prev = std::panic::take_hook();
std::panic::set_hook(Box::new(|_| {}));
let panics = std::panic::catch_unwind(|| {
let a: i8 = std::hint::black_box(i8::MIN);
-a
})
.is_err();
std::panic::set_hook(prev);
assert!(panics, "`-i8::MIN` must panic, so the guard is load-bearing");
}
#[test]
fn verified_signed_functions_do_not_panic_concretely() {
let Some(report) = verify_all() else { return };
if !outcome(&report, "signed_add_guarded").is_verified() {
return;
}
let prev = std::panic::take_hook();
std::panic::set_hook(Box::new(|_| {}));
let mut violations = Vec::new();
for a in -60i16..=60 {
for b in -60i16..=60 {
if std::panic::catch_unwind(|| signed_add_guarded(a as i8, b as i8)).is_err() {
violations.push((a, b));
}
}
}
std::panic::set_hook(prev);
assert!(
violations.is_empty(),
"signed_add_guarded was verified but panics on {violations:?}"
);
}
#[test]
fn a_missing_contracted_function_is_reported() {
let Some(rustc) = rustc() else { return };
let only = vec!["no_such_function".to_string()];
let report = verify::verify_file_with(&rustc, std::path::Path::new(TARGET), &only)
.expect("the file itself should still parse");
assert!(
report.outcomes.is_empty(),
"nothing should have been verified for an absent function"
);
}
#[test]
fn a_report_with_an_unknown_path_is_never_clean() {
let mut report = verify::FileReport::default();
report.outcomes.push((
"f".to_string(),
FnOutcome::Incomplete {
report: Box::new(verify::MirReport::default()),
reasons: vec!["budget".to_string()],
},
));
assert!(!report.is_clean());
assert_eq!(report.incomplete(), 1);
assert_eq!(report.verified(), 0);
}
#[test]
fn a_missing_contract_is_not_clean() {
let mut report = verify::FileReport::default();
report.missing.push("ghost".to_string());
assert!(!report.is_clean());
}
fn report_source_hint() -> &'static str {
"hint: the frontend reads the MIR of examples/mir_targets/actuator.rs; \
run examples/mir_demo.rs to see the per-function report"
}
fn parse_cex_args(detail: &str, names: (&str, &str)) -> (Option<u64>, Option<u64>) {
let mut first = None;
let mut second = None;
for part in detail.split(',') {
let part = part.trim();
let Some((lhs, rhs)) = part.split_once('=') else {
continue;
};
let lhs = lhs.trim();
let val: u64 = rhs.trim().parse().unwrap_or(0);
if lhs == names.0 || lhs.starts_with("v1:") {
first = Some(val);
} else if lhs == names.1 || lhs.starts_with("v2:") {
second = Some(val);
}
}
(first, second)
}
#[test]
fn an_inlined_call_does_not_clobber_the_caller() {
let Some(report) = verify_all() else { return };
let good = outcome(&report, "inline_saves_arg");
assert!(
good.is_verified(),
"returning the caller's saved argument must verify, got: {good}"
);
let bad = outcome(&report, "inline_clobber_would_pass");
assert!(
matches!(bad, FnOutcome::Failed { .. }),
"`ret == b` is false for `inline_clobber_would_pass` and must be refuted, got: {bad}"
);
}
#[test]
fn a_boolean_return_is_checked_against_its_postcondition() {
let Some(report) = verify_all() else { return };
let bad = outcome(&report, "bool_ret_false");
assert!(
matches!(bad, FnOutcome::Failed { .. }),
"`ret == false` for a function returning `true` must be refuted, got: {bad}"
);
let good = outcome(&report, "bool_ret_true");
assert!(
good.is_verified(),
"`ret == true` for the same function must verify, got: {good}"
);
}
#[test]
fn nested_predicate_parentheses_parse() {
let Some(report) = verify_all() else { return };
let o = outcome(&report, "nested_parens");
assert!(
o.is_verified(),
"`requires: ((a == 0))` must parse and verify, got: {o}"
);
}
#[test]
fn a_scoped_debug_alias_does_not_rename_a_parameter() {
let Some(rustc) = rustc() else { return };
let mir = verify::emit_mir_with(&rustc, std::path::Path::new(TARGET))
.expect("emit MIR for the target file");
let report = verify::verify_file_with(&rustc, std::path::Path::new(TARGET), &[
"inline_saves_arg".to_string(),
])
.expect("verify");
let (_, o) = report.outcomes.first().expect("one outcome");
assert!(
!matches!(o, FnOutcome::Skipped { .. }),
"the contract names the parameter `a` and must be readable, got: {o}"
);
assert!(mir.contains("debug a => _1;"), "the parameter binding is expected in the dump");
}
#[test]
fn an_unreadable_ensures_is_reported_not_ignored() {
let Some(rustc) = rustc() else { return };
let dir = std::env::temp_dir().join("verif_unreadable_ensures");
let _ = std::fs::create_dir_all(&dir);
let src = dir.join("u.rs");
std::fs::write(
&src,
"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n requires: true,\n ensures: ret == nonsense_name,\n}\npub fn f(a: u8) -> u8 { a }\n",
)
.expect("write source");
let report =
verify::verify_file_with_opts(&rustc, &src, &["f".to_string()], &probe_opts()).expect("verify");
let (_, o) = report.outcomes.first().expect("one outcome");
assert!(
matches!(o, FnOutcome::Skipped { .. }),
"an unreadable `ensures` must be reported as skipped, got: {o}"
);
assert!(
!report.is_clean(),
"a report with a skipped function must not be clean"
);
}
#[test]
fn an_unsatisfiable_precondition_is_a_failure() {
let Some(report) = verify_all() else { return };
let o = outcome(&report, "vacuous_precondition");
assert!(
matches!(o, FnOutcome::Failed { .. }),
"`a < 3 && a > 10` admits no input and must be a failure, got: {o}"
);
let text = o.to_string();
assert!(
text.contains("vacuous precondition"),
"the failure must name the vacuous precondition, got: {text}"
);
}
#[test]
fn a_panic_obligation_that_is_valid_is_a_failure() {
let Some(report) = verify_all() else { return };
let o = outcome(&report, "div_by_always_zero");
assert!(
matches!(o, FnOutcome::Failed { .. }),
"a divide by an always-zero divisor must be a failure, got: {o}"
);
assert!(
o.to_string().contains("panic"),
"the failure must name the panic, got: {o}"
);
}
#[test]
fn a_panic_on_every_input_is_a_failure() {
let Some(report) = verify_all() else { return };
let o = outcome(&report, "add_always_overflows");
assert!(
matches!(o, FnOutcome::Failed { .. }),
"an add that always overflows must be a failure, got: {o}"
);
}
#[test]
fn an_impossible_postcondition_says_so_rather_than_the_opposite() {
let Some(report) = verify_all() else { return };
let o = outcome(&report, "bool_ret_false");
let FnOutcome::Failed { kind, detail } = o else {
panic!("`bool_ret_false` must fail, got: {o}");
};
assert_eq!(kind, "postcondition");
assert!(
detail.contains("no input"),
"an `Unsat` postcondition must be reported as holding for no input, got: {detail}"
);
assert!(
!detail.contains("holds for every input"),
"the diagnosis is reversed: an `Unsat` postcondition holds for none, got: {detail}"
);
}
#[test]
fn an_always_firing_panic_says_it_fires_on_every_input() {
let Some(report) = verify_all() else { return };
let o = outcome(&report, "div_by_always_zero");
let FnOutcome::Failed { kind, detail } = o else {
panic!("`div_by_always_zero` must fail, got: {o}");
};
assert!(kind.contains("panic"), "the kind must name the panic, got: {kind}");
assert!(
detail.contains("every input"),
"a `Valid` panic query fires on every input and must say so, got: {detail}"
);
}
const REALISTIC: &str = "examples/mir_targets/realistic.rs";
fn verify_realistic(only: &[&str]) -> Option<verify::FileReport> {
let rustc = rustc()?;
let only: Vec<String> = only.iter().map(|s| s.to_string()).collect();
match verify::verify_file_with(&rustc, std::path::Path::new(REALISTIC), &only) {
Ok(r) => Some(r),
Err(e) => panic!("frontend failed: {e}"),
}
}
#[test]
fn the_independent_corpus_does_not_regress() {
const EVERYDAY: &str = "examples/mir_targets/everyday.rs";
let Some(rustc) = rustc() else { return };
let report = match verify::verify_file_with(&rustc, std::path::Path::new(EVERYDAY), &[]) {
Ok(r) => r,
Err(e) => panic!("frontend failed: {e}"),
};
let refuted: Vec<&str> = report
.outcomes
.iter()
.filter(|(_, o)| match o {
FnOutcome::Failed { kind, .. } => {
!(kind.starts_with("panic:") || kind.starts_with("reachable"))
}
_ => false,
})
.map(|(n, _)| n.as_str())
.collect();
assert!(
refuted.is_empty(),
"everyday.rs is ordinary Rust whose *contracts* must hold, so a contract \
refutation is a bug: {refuted:?}. A corpus function that is genuinely false \
belongs in a tripwire fixture, not here. (A panic or unreachable failure is a \
legitimate finding and is allowed.)"
);
let verified = report
.outcomes
.iter()
.filter(|(_, o)| matches!(o, FnOutcome::Verified { .. }))
.count();
assert!(
verified >= 17,
"everyday.rs verified {verified} of {} functions, down from 17 (81%); a regression \
dropped coverage of ordinary Rust below Phase 1's 80% exit criterion. Run: cargo run \
--features std --example mir_coverage -- {EVERYDAY}",
report.outcomes.len()
);
}
#[test]
fn every_edition_compiles_the_corpus_to_the_same_verdicts() {
use verify::Edition;
let Some(rustc) = rustc() else { return };
let editions =
[Edition::Rust2015, Edition::Rust2018, Edition::Rust2021, Edition::Rust2024];
let mut baseline: Option<Vec<(String, String)>> = None;
for ed in editions {
let opts = verify::MirOptions { edition: Some(ed), ..Default::default() };
let report = verify::verify_file_with_opts(&rustc, std::path::Path::new(TARGET), &[], &opts)
.unwrap_or_else(|e| panic!("frontend failed under {}: {e}", ed.as_str()));
let shape: Vec<(String, String)> = report
.outcomes
.iter()
.map(|(n, o)| (n.clone(), format!("{o:?}")))
.collect();
match &baseline {
None => baseline = Some(shape),
Some(base) => assert_eq!(
base,
&shape,
"edition {} disagrees with 2015 on {}",
ed.as_str(),
TARGET
),
}
}
}
#[test]
fn a_2021_only_file_is_verified_under_its_own_edition() {
use verify::Edition;
let Some(rustc) = rustc() else { return };
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nextern \"C\" {\n fn abs(x: i32) -> i32;\n}\nspec! {\n ensures: ret == x,\n}\npub fn f(x: u8) -> u8 { x }\n";
static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!("verif-edition-{}-{seq}", std::process::id()));
let _ = std::fs::create_dir_all(&dir);
let file = dir.join("probe.rs");
std::fs::write(&file, src).expect("write probe");
let opts21 = verify::MirOptions { edition: Some(Edition::Rust2021), ..Default::default() };
let report = verify::verify_file_with_opts(&rustc, &file, &[], &opts21)
.expect("a 2021 file with `extern \"C\"` must compile under 2021");
let o = report.outcomes.iter().find(|(n, _)| n == "f").map(|(_, o)| o.clone());
assert!(
matches!(o, Some(FnOutcome::Verified { .. })),
"the 2021 fixture must verify under 2021, got: {o:?}"
);
let opts24 = verify::MirOptions { edition: Some(Edition::Rust2024), ..Default::default() };
assert!(
verify::verify_file_with_opts(&rustc, &file, &[], &opts24).is_err(),
"the 2021-only file must be refused under 2024, not silently compiled"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_package_that_omits_an_edition_is_verified_as_2015() {
let Some(rustc) = rustc() else { return };
if std::env::var("VERIF_EDITION").map(|v| !v.is_empty()).unwrap_or(false) {
return;
}
static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!("verif-pkg2015-{}-{seq}", std::process::id()));
let _ = std::fs::create_dir_all(&dir);
std::fs::write(
dir.join("Cargo.toml"),
"[package]\nname = \"demo\"\nversion = \"0.1.0\"\n",
)
.expect("write manifest");
let file = dir.join("probe.rs");
std::fs::write(&file, "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n ensures: ret == x,\n}\npub fn f(x: u8) -> u8 { x }\n")
.expect("write probe");
let opts = verify::MirOptions { edition: None, ..Default::default() };
let (text, edition) = verify::emit_mir_with_opts(&rustc, &file, &opts)
.expect("a package without an `edition` must resolve to Cargo's 2015 default");
assert_eq!(edition, verify::Edition::Rust2015, "the default edition is 2015");
assert!(!text.is_empty(), "MIR must be emitted for the package");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_non_panicking_diverging_call_is_not_labelled_a_panic() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\npub fn die() -> ! { loop {} }\nspec! {\n requires: true,\n ensures: ret == 1,\n}\npub fn f(x: u8) -> u8 { if x == 0 { die(); } 1 }\n";
let Some(o) = verify_src("f", src) else { return };
match o {
FnOutcome::Failed { kind, .. } => {
assert!(
kind.contains("diverges"),
"a user `!`-returning function must be labelled `diverges`, not `panic`: got `{kind}`"
);
assert!(
!kind.contains("panic"),
"a non-panicking diverging call must not be labelled a panic: got `{kind}`"
);
}
other => panic!("a reachable call to a `!` function must fail, got: {other}"),
}
}
#[test]
fn a_panicking_diverging_call_is_labelled_a_panic() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n ensures: ret == 1,\n}\npub fn f(x: u8) -> u8 { if x == 0 { panic!(\"boom\"); } 1 }\n";
let Some(o) = verify_src("f", src) else { return };
match o {
FnOutcome::Failed { kind, .. } => assert!(
kind.contains("panic"),
"a real panic must be labelled `panic`: got `{kind}`"
),
other => panic!("an unguarded panic must fail, got: {other}"),
}
}
#[test]
fn a_contract_can_name_a_struct_field() {
let Some(report) = verify_realistic(&["pick_from", "clamp_by_value"]) else { return };
for name in ["pick_from", "clamp_by_value"] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
}
#[test]
fn struct_fields_are_independent_inputs_not_one_aliased_variable() {
let Some(report) = verify_realistic(&["field_alias_tripwire"]) else { return };
let o = outcome(&report, "field_alias_tripwire");
let FnOutcome::Failed { kind, detail } = o else {
panic!(
"`field_alias_tripwire` must fail: a pass means `c.lo` and `c.hi` \
collapsed to one variable and the contract was vacuous. got: {o}"
);
};
assert_eq!(kind, "postcondition", "got: {o}");
let names: Vec<&str> = detail.split_whitespace().filter(|t| t.starts_with('v')).collect();
assert!(
names.len() >= 2,
"the counterexample must assign both fields to show they differ, got: {detail}"
);
assert!(
names.iter().collect::<std::collections::BTreeSet<_>>().len() >= 2,
"the two fields were assigned the same variable, so they are aliased: {detail}"
);
}
#[test]
fn slice_elements_are_independent_inputs_not_one_aliased_variable() {
let Some(report) = verify_realistic(&["slice_alias_tripwire"]) else { return };
let o = outcome(&report, "slice_alias_tripwire");
let FnOutcome::Failed { kind, detail } = o else {
panic!(
"`slice_alias_tripwire` must fail: a pass means `xs[0]` and `xs[1]` \
collapsed to one variable and the slice contract was vacuous. got: {o}"
);
};
assert_eq!(kind, "postcondition", "got: {o}");
let names: Vec<&str> = detail.split_whitespace().filter(|t| t.starts_with('v')).collect();
assert!(
names.iter().collect::<std::collections::BTreeSet<_>>().len() >= 2,
"the two elements were assigned the same variable, so they are aliased: {detail}"
);
}
#[test]
fn a_slice_length_is_a_symbolic_input_shared_with_the_body() {
let Some(report) = verify_realistic(&["first_of"]) else { return };
let o = outcome(&report, "first_of");
assert!(o.is_verified(), "`first_of` must verify, got: {o}");
}
#[test]
fn a_contract_can_name_a_fixed_size_array_element() {
let Some(report) = verify_realistic(&["max_of_pair", "array_third"]) else { return };
for name in ["max_of_pair", "array_third"] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
}
#[test]
fn an_array_literal_element_is_concrete() {
let Some(report) = verify_realistic(&["array_literal_elem"]) else { return };
let o = outcome(&report, "array_literal_elem");
assert!(o.is_verified(), "`array_literal_elem` must verify, got: {o}");
}
#[test]
fn array_elements_are_independent_inputs_not_one_aliased_variable() {
let Some(report) = verify_realistic(&["array_alias_tripwire"]) else { return };
let o = outcome(&report, "array_alias_tripwire");
let FnOutcome::Failed { kind, detail } = o else {
panic!(
"`array_alias_tripwire` must fail: a pass means `a[0]` and `a[1]` \
collapsed to one variable and the array contract was vacuous. got: {o}"
);
};
assert_eq!(kind, "postcondition", "got: {o}");
let names: Vec<&str> = detail.split_whitespace().filter(|t| t.starts_with('v')).collect();
assert!(
names.iter().collect::<std::collections::BTreeSet<_>>().len() >= 2,
"the two elements were assigned the same variable, so they are aliased: {detail}"
);
}
#[test]
fn a_write_cannot_prove_a_stale_contract() {
let names = [
"array_write_then_symbolic_read",
"mut_ref_array_write_then_symbolic_read",
"generated_name_shadows_argument",
];
let Some(report) = verify_realistic(&names) else { return };
for name in names {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Failed { .. }),
"`{name}` proves a false contract; got: {o}"
);
}
let Some(report) = verify_realistic(&["struct_reassign_then_field_read"]) else { return };
let o = outcome(&report, "struct_reassign_then_field_read");
assert!(
!o.is_verified(),
"`struct_reassign_then_field_read` proves a stale field; got: {o}"
);
}
#[test]
fn stage_two_rvalues_are_modelled_and_their_tripwires_refuted() {
let verified = [
"struct_literal_reads_its_field",
"struct_literal_order",
"reference_reads_through",
"reference_write_reaches_target",
"array_len_is_the_type_constant",
"struct_reassign_reads_new_field",
"enum_match_is_bounded",
"enum_match_selects_by_tag",
"enum_payload_reads_through",
"enum_constructed_locally",
"enum_constructed_payload_reads_through",
"enum_explicit_discriminant_selects_by_tag",
"enum_user_variant_not_option",
"enum_user_variant_not_option_constructed",
];
let refuted = [
"struct_literal_order_tripwire",
"reference_write_tripwire",
"enum_match_tripwire",
"enum_constructed_locally_tripwire",
"enum_explicit_discriminant_tripwire",
"enum_user_variant_not_option_tripwire",
"enum_user_variant_not_option_constructed_tripwire",
];
let Some(report) = verify_realistic(&verified) else { return };
for name in verified {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
let Some(report) = verify_realistic(&refuted) else { return };
for name in refuted {
let o = outcome(&report, name);
let FnOutcome::Failed { .. } = o else {
panic!("`{name}` is a false contract that must be refuted, got: {o}");
};
}
}
#[test]
fn a_u16_product_is_decided_end_to_end() {
let Some(report) = verify_realistic(&["u16_product_guarded"]) else { return };
let o = outcome(&report, "u16_product_guarded");
assert!(o.is_verified(), "`u16_product_guarded` must verify, got: {o}");
let Some(report) = verify_realistic(&["u16_product_unguarded_tripwire"]) else { return };
let o = outcome(&report, "u16_product_unguarded_tripwire");
let FnOutcome::Failed { .. } = o else {
panic!("`u16_product_unguarded_tripwire` is false and must be refuted, got: {o}");
};
}
#[test]
fn the_complement_bit_counts_agree_with_rust() {
let verified = [
"count_zeros_of_zero_is_the_width",
"leading_ones_of_a_top_bit_value",
"trailing_ones_of_a_small_value",
];
let refuted = [
"count_zeros_of_zero_is_the_width_tripwire",
"leading_ones_of_a_top_bit_value_tripwire",
"trailing_ones_of_a_small_value_tripwire",
];
let Some(report) = verify_realistic(&verified) else { return };
for name in verified {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
let Some(report) = verify_realistic(&refuted) else { return };
for name in refuted {
let o = outcome(&report, name);
let FnOutcome::Failed { .. } = o else {
panic!("`{name}` is a false contract that must be refuted, got: {o}");
};
}
}
#[test]
fn is_power_of_two_is_a_modelled_bool() {
let verified = ["is_power_of_two_of_the_top_bit", "is_power_of_two_of_three"];
let refuted = ["is_power_of_two_of_zero_tripwire"];
let Some(report) = verify_realistic(&verified) else { return };
for name in verified {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
let Some(report) = verify_realistic(&refuted) else { return };
for name in refuted {
let o = outcome(&report, name);
let FnOutcome::Failed { .. } = o else {
panic!("`{name}` is a false contract that must be refuted, got: {o}");
};
}
}
#[test]
fn is_power_of_two_branches_on_the_predicate() {
let verified = [
"is_power_of_two_branching_takes_the_true_arm",
"is_power_of_two_branching_takes_the_false_arm",
];
let refuted = ["is_power_of_two_branching_of_zero_tripwire"];
let Some(report) = verify_realistic(&verified) else { return };
for name in verified {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
let Some(report) = verify_realistic(&refuted) else { return };
for name in refuted {
let o = outcome(&report, name);
let FnOutcome::Failed { .. } = o else {
panic!("`{name}` is a false contract that must be refuted, got: {o}");
};
}
}
#[test]
fn the_new_num_methods_verify_and_their_tripwires_refute() {
let verified = [
"midpoint_self_is_the_identity",
"midpoint_of_an_overflowing_sum",
"midpoint_rounds_toward_zero",
"midpoint_signed_truncates",
"midpoint_is_between",
"next_multiple_of_rounds_up",
"next_multiple_of_an_exact_multiple_is_the_identity",
"next_multiple_of_is_panic_free_here",
"checked_next_multiple_of_rounds_up",
"checked_next_multiple_of_that_overflows_is_none",
"checked_next_multiple_of_by_zero_is_none",
"ilog2_of_100",
"ilog2_of_one_is_zero",
"ilog2_of_a_signed_100",
"ilog2_is_bounded",
"ilog10_of_100",
"ilog10_below_ten_is_zero",
"ilog10_of_a_u32_thousand",
"ilog10_is_bounded",
"checked_ilog2_in_range",
"checked_ilog2_of_zero_is_none",
"checked_ilog10_in_range",
"checked_ilog10_of_zero_is_none",
"checked_ilog2_of_a_negative_is_none",
"next_power_of_two_rounds_up",
"next_power_of_two_of_a_power_is_itself",
"next_power_of_two_of_zero_is_one",
"next_power_of_two_of_a_u32_thousand",
"next_power_of_two_is_panic_free_here",
"checked_next_power_of_two_in_range",
"checked_next_power_of_two_out_of_range_is_none",
];
let refuted = [
"midpoint_of_an_overflowing_sum_cannot_prove_this",
"midpoint_rounds_toward_zero_cannot_prove_this",
"midpoint_signed_truncates_cannot_prove_this",
"midpoint_is_between_cannot_prove_this",
"next_multiple_of_rounds_up_cannot_prove_this",
"checked_next_multiple_of_overflow_is_some_cannot_prove_this",
"ilog2_of_100_cannot_prove_this",
"ilog10_of_100_cannot_prove_this",
"checked_ilog2_overflow_is_some_cannot_prove_this",
"checked_ilog2_of_a_negative_cannot_prove_this",
"next_power_of_two_rounds_up_cannot_prove_this",
"checked_next_power_of_two_in_range_cannot_prove_this",
"checked_next_power_of_two_payload_cannot_prove_this",
];
let panics = [
"next_multiple_of_that_overflows_panics",
"ilog2_of_zero_panics",
"ilog10_of_zero_panics",
"next_power_of_two_that_overflows_panics",
];
let Some(report) = verify_realistic(&verified) else { return };
for name in verified {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
let Some(report) = verify_realistic(&refuted) else { return };
for name in refuted {
let o = outcome(&report, name);
let FnOutcome::Failed { .. } = o else {
panic!("`{name}` is a false contract that must be refuted, got: {o}");
};
}
let Some(report) = verify_realistic(&panics) else { return };
for name in panics {
let o = outcome(&report, name);
let FnOutcome::Failed { kind, .. } = o else {
panic!("`{name}` must fail on its panic obligation, got: {o}");
};
assert!(
kind.starts_with("panic"),
"`{name}` must fail on a panic obligation, got kind `{kind}`"
);
}
}
#[test]
fn the_sign_predicates_are_signed_comparisons() {
let verified = [
"is_negative_of_min",
"is_negative_of_max",
"is_positive_of_max",
"is_negative_branching_takes_the_true_arm",
];
let refuted = ["is_negative_of_zero_tripwire", "is_positive_of_minus_one_tripwire"];
let Some(report) = verify_realistic(&verified) else { return };
for name in verified {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
let Some(report) = verify_realistic(&refuted) else { return };
for name in refuted {
let o = outcome(&report, name);
let FnOutcome::Failed { .. } = o else {
panic!("`{name}` is a false contract that must be refuted, got: {o}");
};
}
}
#[test]
fn the_mixed_signedness_additions_verify_and_their_tripwires_refute() {
let verified = [
"wrapping_add_signed_of_a_negative",
"saturating_add_signed_clamps_to_zero",
"overflowing_add_signed_below_zero_is_overflow",
"overflowing_add_signed_within_range_is_not_overflow",
"overflowing_add_signed_past_the_top_tripwire",
"wrapping_add_unsigned_of_the_top_bit",
"saturating_add_unsigned_clamps_to_signed_max",
"saturating_add_unsigned_top_bit_tripwire",
"checked_add_signed_in_range_is_the_sum",
"checked_add_unsigned_in_range_is_the_sum",
"overflowing_add_unsigned_within_range_is_not_overflow",
"overflowing_add_unsigned_past_the_top_is_overflow",
];
let refuted = [
"wrapping_add_signed_wrong_value_tripwire",
"saturating_add_signed_wrong_value_tripwire",
"overflowing_add_signed_wrong_flag_tripwire",
"checked_add_signed_none_tripwire",
"wrapping_add_unsigned_wrong_value_tripwire",
"saturating_add_unsigned_wrong_value_tripwire",
"overflowing_add_unsigned_wrong_flag_tripwire",
"checked_add_unsigned_wrong_value_tripwire",
];
let Some(report) = verify_realistic(&verified) else { return };
for name in verified {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
let Some(report) = verify_realistic(&refuted) else { return };
for name in refuted {
let o = outcome(&report, name);
let FnOutcome::Failed { kind, .. } = o else {
panic!("`{name}` is a false mixed-add contract that must be refuted, got: {o}");
};
assert_eq!(kind, "postcondition", "`{name}` got: {o}");
}
}
#[test]
fn a_trait_method_sharing_an_intrinsic_name_is_answered_by_its_body() {
let verified = ["trait_is_power_of_two_disagrees_with_core"];
let refuted = ["trait_is_power_of_two_disagrees_with_core_tripwire"];
let Some(report) = verify_realistic(&verified) else { return };
for name in verified {
let o = outcome(&report, name);
assert!(
o.is_verified(),
"`{name}` must verify: the trait body returns `false` at `x == 1`, so a \
model that answered from `core`'s predicate would refute it; got: {o}"
);
}
let Some(report) = verify_realistic(&refuted) else { return };
for name in refuted {
let o = outcome(&report, name);
let FnOutcome::Failed { kind, .. } = o else {
panic!(
"`{name}` must be refuted: it claims `core`'s answer, which the trait \
body does not produce. A pass is the false proof this pins. got: {o}"
);
};
assert_eq!(kind, "postcondition", "`{name}` got: {o}");
}
}
#[test]
fn ord_min_and_max_are_modelled_and_a_local_trait_still_wins() {
let verified = [
"ord_min_is_at_most_both",
"ord_max_is_at_least_x",
"ord_min_of_min_and_one_is_min",
"explicit_ord_min_is_modelled",
"local_ord_min_is_answered_by_its_body",
];
let refuted = ["ord_min_is_x_tripwire", "local_ord_min_is_not_the_model_tripwire"];
let Some(report) = verify_realistic(&verified) else { return };
for name in verified {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
let Some(report) = verify_realistic(&refuted) else { return };
for name in refuted {
let o = outcome(&report, name);
let FnOutcome::Failed { kind, .. } = o else {
panic!("`{name}` is a false contract that must be refuted, got: {o}");
};
assert_eq!(kind, "postcondition", "`{name}` got: {o}");
}
}
#[test]
fn partial_cmp_methods_are_modelled_and_a_local_trait_still_wins() {
let verified = [
"partial_eq_method_is_the_operator",
"partial_ne_method_is_the_operator",
"partial_lt_method_is_the_operator",
"partial_ge_method_is_the_operator",
"partial_lt_signed_is_not_unsigned",
"local_partial_ord_lt_is_answered_by_its_body",
"partial_eq_const_is_the_operator",
"partial_lt_const_signed_is_not_unsigned",
];
let refuted = [
"partial_lt_is_not_le_tripwire",
"local_partial_ord_lt_is_not_the_model_tripwire",
"partial_lt_const_is_not_le_tripwire",
];
let Some(report) = verify_realistic(&verified) else { return };
for name in verified {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
let Some(report) = verify_realistic(&refuted) else { return };
for name in refuted {
let o = outcome(&report, name);
let FnOutcome::Failed { kind, .. } = o else {
panic!("`{name}` is a false contract that must be refuted, got: {o}");
};
assert_eq!(kind, "postcondition", "`{name}` got: {o}");
}
}
#[test]
fn ord_cmp_returns_the_ordering_enum() {
let verified = [
"ord_cmp_less_arm",
"ord_cmp_equal_arm",
"ord_cmp_greater_arm",
"ord_cmp_matches_less",
"ord_cmp_signed_is_not_unsigned",
];
let refuted = ["ord_cmp_is_not_le_tripwire"];
let Some(report) = verify_realistic(&verified) else { return };
for name in verified {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
let Some(report) = verify_realistic(&refuted) else { return };
for name in refuted {
let o = outcome(&report, name);
let FnOutcome::Failed { kind, .. } = o else {
panic!("`{name}` is a false contract that must be refuted, got: {o}");
};
assert_eq!(kind, "postcondition", "`{name}` got: {o}");
}
}
#[test]
fn widening_conversions_are_modelled_by_the_sources_signedness() {
let verified = [
"from_u8_is_modelled",
"into_u8_is_modelled",
"signed_widening_keeps_negative_values",
"unsigned_source_widens_to_signed_destination",
];
let Some(report) = verify_realistic(&verified) else { return };
for name in verified {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
let refuted = ["signed_widening_is_not_zero_fill_tripwire"];
let Some(report) = verify_realistic(&refuted) else { return };
for name in refuted {
let o = outcome(&report, name);
let FnOutcome::Failed { kind, .. } = o else {
panic!("`{name}` is a false contract that must be refuted, got: {o}");
};
assert_eq!(kind, "postcondition", "`{name}` got: {o}");
}
}
#[test]
fn a_local_trait_named_from_does_not_answer_the_std_trait() {
let verified = ["local_from_is_answered_by_its_own_body"];
let Some(report) = verify_realistic(&verified) else { return };
for name in verified {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify from the local body, got: {o}");
}
let refuted = ["local_from_does_not_answer_the_std_trait"];
let Some(report) = verify_realistic(&refuted) else { return };
for name in refuted {
let o = outcome(&report, name);
let FnOutcome::Failed { kind, .. } = o else {
panic!("`{name}` claims the local body's answer for a library call and must be refuted, got: {o}");
};
assert_eq!(kind, "postcondition", "`{name}` got: {o}");
}
}
#[test]
fn a_user_type_named_range_is_not_answered_by_the_range_model() {
let spoof = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
pub mod a {
pub trait Custom {
fn into_iter(self) -> Self
where
Self: Sized,
{
panic!("into_iter is not the identity here")
}
}
}
pub mod b {
pub trait Custom {
fn into_iter(self) -> Self
where
Self: Sized,
{
panic!("the other trait")
}
}
}
pub struct Range<T> {
pub start: T,
pub end: T,
}
impl a::Custom for Range<u8> {}
spec! {
requires: true,
ensures: ret == 1,
}
pub fn caller() -> u8 {
let r = Range { start: 1u8, end: 2u8 };
let x = <Range<u8> as a::Custom>::into_iter(r);
x.start
}
"#;
let Some(o) = verify_src("caller", spoof) else { return };
assert!(
!o.is_verified(),
"a user `Range`'s custom `into_iter` must not be answered by the range \
model (the model would prove `ret == 1` for a function that panics), got: {o}"
);
let real = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
spec! {
requires: true,
ensures: ret == 3,
}
pub fn sums() -> u32 {
let mut c = 0u32;
for i in 1u32..=2u32 {
c += i;
}
c
}
"#;
let Some(o) = verify_src("sums", real) else { return };
assert!(
o.is_verified(),
"the standard library's `for`-loop range must still be modelled, got: {o}"
);
let self_receiver = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
#[derive(Clone, Copy)]
pub struct P {
pub v: u8,
}
pub trait T: Copy {
fn go(mut self) -> Self
where
Self: Sized,
{
self.set(42);
self
}
fn set(&mut self, x: u8) {
let _ = x;
}
}
impl T for P {
fn set(&mut self, x: u8) {
self.v = x;
}
}
spec! {
requires: true,
ensures: ret == 1,
}
pub fn caller() -> u8 {
let p = P { v: 1 };
let q = <P as T>::go(p);
q.v
}
"#;
let Some(o) = verify_src("caller", self_receiver) else { return };
assert!(
!o.is_verified(),
"a `<Self as T>::m` call inside a trait default body must not be answered \
by the default method when an impl overrides it (that proved `ret == 1` for \
a body returning `42`), got: {o}"
);
}
#[test]
fn a_bare_crate_root_trait_call_is_not_answered_by_the_model() {
let verified = ["crate_root_ord_default_verifies_from_its_body"];
let Some(report) = verify_realistic(&verified) else { return };
for name in verified {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify from the default body, got: {o}");
}
let refuted = ["crate_root_ord_default_is_not_the_model_tripwire"];
let Some(report) = verify_realistic(&refuted) else { return };
for name in refuted {
let o = outcome(&report, name);
let FnOutcome::Failed { kind, .. } = o else {
panic!(
"`{name}` claims `core`'s ordering for a call the compiler resolved to \
the local trait and must be refuted, got: {o}"
);
};
assert_eq!(kind, "postcondition", "`{name}` got: {o}");
}
}
#[test]
fn an_unrelated_same_named_trait_does_not_answer_a_bare_call() {
let verified = ["suffix_collision_verifies_from_the_named_trait"];
let Some(report) = verify_realistic(&verified) else { return };
for name in verified {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify from the crate-root trait, got: {o}");
}
let refuted = ["suffix_collision_is_not_the_module_trait_tripwire"];
let Some(report) = verify_realistic(&refuted) else { return };
for name in refuted {
let o = outcome(&report, name);
let FnOutcome::Failed { kind, .. } = o else {
panic!(
"`{name}` claims the module trait's body for a call naming the crate-root \
trait and must be refuted, got: {o}"
);
};
assert_eq!(kind, "postcondition", "`{name}` got: {o}");
}
}
#[test]
fn a_local_impl_of_an_imported_trait_does_not_answer_the_model() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
pub struct Local;
impl From<Local> for u16 {
fn from(_x: Local) -> Self {
107
}
}
spec! {
requires: true,
ensures: ret == 107,
}
pub fn imported_from_verifies_from_the_local_body() -> u16 {
<u16 as From<Local>>::from(Local)
}
spec! {
requires: true,
ensures: ret == 7,
}
pub fn imported_from_is_not_the_model_tripwire() -> u16 {
<u16 as From<Local>>::from(Local)
}
"#;
let o = verify_src("imported_from_verifies_from_the_local_body", src);
let Some(o) = o else { return };
assert!(
o.is_verified(),
"`imported_from_verifies_from_the_local_body` must verify from the local body, got: {o}"
);
let o = verify_src("imported_from_is_not_the_model_tripwire", src);
let Some(o) = o else { return };
match &o {
FnOutcome::Failed { kind, .. } => {
assert_eq!(kind, "postcondition", "the tripwire got: {o}");
}
_ => panic!(
"`imported_from_is_not_the_model_tripwire` claims the modelled conversion for a \
call the compiler resolved to a local impl and must be refuted, got: {o}"
),
}
}
#[test]
fn an_override_wins_over_the_traits_default_body() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
pub trait T { fn value(&self) -> u8 { 1 } }
pub struct Foo(pub u8);
impl T for Foo { fn value(&self) -> u8 { 2 } }
pub struct Bar(pub u8);
impl T for Bar {}
spec! {
requires: true,
ensures: ret == 2,
}
pub fn override_verifies(f: &Foo) -> u8 { <Foo as T>::value(f) }
spec! {
requires: true,
ensures: ret == 1,
}
pub fn override_is_not_the_default_tripwire(f: &Foo) -> u8 { <Foo as T>::value(f) }
spec! {
requires: true,
ensures: ret == 1,
}
pub fn default_still_used_when_not_overridden(b: &Bar) -> u8 { <Bar as T>::value(b) }
"#;
let Some(o) = verify_src("override_verifies", src) else { return };
assert!(o.is_verified(), "the override's body must answer, got: {o}");
let Some(o) = verify_src("default_still_used_when_not_overridden", src) else { return };
assert!(o.is_verified(), "the default must still answer when nothing overrides it, got: {o}");
let Some(o) = verify_src("override_is_not_the_default_tripwire", src) else { return };
match &o {
FnOutcome::Failed { kind, .. } => assert_eq!(kind, "postcondition", "got: {o}"),
_ => panic!("the default body must not answer a call an impl overrides, got: {o}"),
}
}
#[test]
fn a_generic_traits_arguments_separate_its_impls() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
pub struct Local;
impl From<Local> for u16 { fn from(_: Local) -> Self { 107 } }
spec! {
requires: true,
ensures: ret == 7,
}
pub fn library_call_is_seven() -> u16 { <u16 as From<u8>>::from(7u8) }
spec! {
requires: true,
ensures: ret == 107,
}
pub fn library_call_is_not_the_local_body_tripwire() -> u16 { <u16 as From<u8>>::from(7u8) }
spec! {
requires: true,
ensures: ret == 107,
}
pub fn local_call_is_onehundredseven() -> u16 { <u16 as From<Local>>::from(Local) }
"#;
let Some(o) = verify_src("library_call_is_seven", src) else { return };
assert!(o.is_verified(), "the modelled widening must answer a library call, got: {o}");
let Some(o) = verify_src("local_call_is_onehundredseven", src) else { return };
assert!(o.is_verified(), "the local impl's own instantiation must answer, got: {o}");
let Some(o) = verify_src("library_call_is_not_the_local_body_tripwire", src) else { return };
match &o {
FnOutcome::Failed { kind, .. } => assert_eq!(kind, "postcondition", "got: {o}"),
_ => panic!("a different instantiation's body must not answer, got: {o}"),
}
}
#[test]
fn an_imported_trait_keeps_its_imported_path() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
pub struct Local;
pub mod m {
use std::convert::From;
pub mod nested {}
impl From<crate::Local> for u16 { fn from(_: crate::Local) -> Self { 107 } }
}
spec! {
requires: true,
ensures: ret == 107,
}
pub fn imported_trait_after_nested_module() -> u16 {
<u16 as std::convert::From<crate::Local>>::from(crate::Local)
}
"#;
let Some(o) = verify_src("imported_trait_after_nested_module", src) else { return };
assert!(o.is_verified(), "the impl must be reached through its imported trait, got: {o}");
}
#[test]
fn a_multiline_restricted_import_is_read() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
pub struct Local;
pub mod m {
pub(crate) use std::convert::{
From,
};
impl From<crate::Local> for u16 { fn from(_: crate::Local) -> Self { 107 } }
}
spec! {
requires: true,
ensures: ret == 107,
}
pub fn multiline_imported_trait() -> u16 {
<u16 as std::convert::From<crate::Local>>::from(crate::Local)
}
"#;
let Some(o) = verify_src("multiline_imported_trait", src) else { return };
assert!(o.is_verified(), "a folded restricted import must still qualify the trait, got: {o}");
}
#[test]
fn a_nested_trait_argument_keeps_its_balanced_spelling() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
pub trait Wrap<T> { fn get(&self) -> u8; }
pub struct W;
impl Wrap<Option<u8>> for W { fn get(&self) -> u8 { 9 } }
spec! {
requires: true,
ensures: ret == 9,
}
pub fn nested_arg(w: &W) -> u8 { <W as Wrap<Option<u8>>>::get(w) }
spec! {
requires: true,
ensures: ret == 4,
}
pub fn nested_arg_tripwire(w: &W) -> u8 { <W as Wrap<Option<u8>>>::get(w) }
"#;
let Some(o) = verify_src("nested_arg", src) else { return };
assert!(o.is_verified(), "a nested trait argument must still find the local body, got: {o}");
let Some(o) = verify_src("nested_arg_tripwire", src) else { return };
match &o {
FnOutcome::Failed { kind, .. } => assert_eq!(kind, "postcondition", "got: {o}"),
_ => panic!("the local body returns 9, so `ret == 4` must be refuted, got: {o}"),
}
}
#[test]
fn a_cfg_disabled_import_does_not_displace_a_live_alias() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
pub trait From { fn make() -> u8 { 0 } }
pub mod m {
use std::convert::From as Conv;
pub struct Local;
impl Conv<Local> for u16 { fn from(_: Local) -> Self { 107 } }
#[cfg(any())]
use crate::Other as Conv;
}
pub struct Other;
spec! {
requires: true,
ensures: ret == 107,
}
pub fn cfg_live() -> u16 { <u16 as std::convert::From<m::Local>>::from(m::Local) }
spec! {
requires: true,
ensures: ret == 5,
}
pub fn cfg_tripwire() -> u16 { <u16 as std::convert::From<m::Local>>::from(m::Local) }
"#;
let Some(o) = verify_src("cfg_live", src) else { return };
assert!(o.is_verified(), "a live alias must survive a later cfg-disabled import, got: {o}");
let Some(o) = verify_src("cfg_tripwire", src) else { return };
match &o {
FnOutcome::Failed { kind, .. } => assert_eq!(kind, "postcondition", "got: {o}"),
_ => panic!("the live local body returns 107, so `ret == 5` must be refuted, got: {o}"),
}
}
#[test]
fn a_same_line_cfg_import_is_read() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
pub mod m {
#[cfg(all())] use std::convert::From as Conv;
pub struct Local;
impl Conv<Local> for u16 { fn from(_: Local) -> Self { 107 } }
}
spec! {
requires: true,
ensures: ret == 107,
}
pub fn same_line_live_import() -> u16 {
<u16 as std::convert::From<m::Local>>::from(m::Local)
}
"#;
let Some(o) = verify_src("same_line_live_import", src) else { return };
assert!(o.is_verified(), "a same-line cfg import must still bind, got: {o}");
}
#[test]
fn a_multiline_cfg_import_does_not_displace_a_live_alias() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
pub trait From { fn make() -> u8 { 0 } }
pub mod m {
use std::convert::From as Conv;
pub struct Local;
impl Conv<Local> for u16 { fn from(_: Local) -> Self { 107 } }
#[cfg(all(
any(),
))]
use crate::Other as Conv;
}
pub struct Other;
spec! {
requires: true,
ensures: ret == 107,
}
pub fn multi_cfg_live() -> u16 { <u16 as std::convert::From<m::Local>>::from(m::Local) }
spec! {
requires: true,
ensures: ret == 5,
}
pub fn multi_cfg_tripwire() -> u16 { <u16 as std::convert::From<m::Local>>::from(m::Local) }
"#;
let Some(o) = verify_src("multi_cfg_live", src) else { return };
assert!(o.is_verified(), "a multi-line cfg import must not displace a live alias, got: {o}");
let Some(o) = verify_src("multi_cfg_tripwire", src) else { return };
match &o {
FnOutcome::Failed { kind, .. } => assert_eq!(kind, "postcondition", "got: {o}"),
_ => panic!("the live local body returns 107, so `ret == 5` must be refuted, got: {o}"),
}
}
#[test]
fn a_quoted_delimiter_does_not_hide_a_cfg_import() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
pub trait From { fn make() -> u8 { 0 } }
pub mod m {
use std::convert::From as Conv;
pub struct Local;
impl Conv<Local> for u16 { fn from(_: Local) -> Self { 107 } }
#[cfg(any())]
#[doc = "("]
use crate::Other as Conv;
}
pub struct Other;
spec! {
requires: true,
ensures: ret == 107,
}
pub fn quoted_cfg_live() -> u16 { <u16 as std::convert::From<m::Local>>::from(m::Local) }
spec! {
requires: true,
ensures: ret == 5,
}
pub fn quoted_cfg_tripwire() -> u16 { <u16 as std::convert::From<m::Local>>::from(m::Local) }
"#;
let Some(o) = verify_src("quoted_cfg_live", src) else { return };
assert!(o.is_verified(), "a quoted delimiter must not hide the cfg import, got: {o}");
let Some(o) = verify_src("quoted_cfg_tripwire", src) else { return };
match &o {
FnOutcome::Failed { kind, .. } => assert_eq!(kind, "postcondition", "got: {o}"),
_ => panic!("the live local body returns 107, so `ret == 5` must be refuted, got: {o}"),
}
}
#[test]
fn the_nested_argument_and_cfg_alias_fixtures_are_decided() {
let verified = [
"nested_trait_arg_finds_the_body",
"cfg_disabled_import_keeps_the_live_alias",
"cfg_multiline_import_keeps_the_live_alias",
"cfg_quoted_delimiter_keeps_the_live_alias",
];
let Some(report) = verify_realistic(&verified) else { return };
for name in verified {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify from its local body, got: {o}");
}
let refuted = [
"nested_trait_arg_is_not_a_guess_tripwire",
"cfg_disabled_import_is_not_the_wrong_alias_tripwire",
"cfg_multiline_import_is_not_the_wrong_alias_tripwire",
"cfg_quoted_delimiter_is_not_the_wrong_alias_tripwire",
];
let Some(report) = verify_realistic(&refuted) else { return };
for name in refuted {
let o = outcome(&report, name);
let FnOutcome::Failed { kind, .. } = o else {
panic!("`{name}` is a false contract that must be refuted, got: {o}");
};
assert_eq!(kind, "postcondition", "`{name}` got: {o}");
}
}
#[test]
fn the_bitwise_complement_reads_the_operands_width() {
let verified = [
"not_of_zero_is_all_ones",
"not_is_255_minus_x",
"not_of_zero_is_minus_one",
"not_of_zero_u32_is_all_ones",
];
let Some(report) = verify_realistic(&verified) else { return };
for name in verified {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
let Some(report) = verify_realistic(&["not_is_always_255_tripwire"]) else { return };
let o = outcome(&report, "not_is_always_255_tripwire");
let FnOutcome::Failed { .. } = o else {
panic!("`not_is_always_255_tripwire` is false and must be refuted, got: {o}");
};
}
#[test]
fn a_struct_literal_reads_fields_in_declaration_order() {
let Some(report) = verify_realistic(&["struct_literal_order_tripwire"]) else { return };
let o = outcome(&report, "struct_literal_order_tripwire");
let FnOutcome::Failed { detail, .. } = o else {
panic!("`struct_literal_order_tripwire` must be refuted, got: {o}");
};
assert!(
detail.contains("= 0"),
"the witness must be `a == 0`, the value that is not `lo` (7); got: {detail}"
);
}
#[test]
fn a_contract_can_name_a_tuple_struct_field() {
let Some(report) = verify_realistic(&[
"tuple_struct_reads_its_field",
"tuple_struct_by_value_reads_its_field",
"tuple_struct_signed_field_reads",
"tuple_struct_fields_are_independent",
]) else {
return;
};
for name in [
"tuple_struct_reads_its_field",
"tuple_struct_by_value_reads_its_field",
"tuple_struct_signed_field_reads",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must be read and verified; got: {o}");
}
let o = outcome(&report, "tuple_struct_fields_are_independent");
assert!(
!o.is_verified(),
"`tuple_struct_fields_are_independent` must be refuted -- a reader that aliased \
`p.0` and `p.1` to one variable would prove it; got: {o}"
);
}
#[test]
fn a_tuple_struct_field_that_does_not_exist_is_refused() {
let Some(report) = verify_realistic(&[
"tuple_struct_out_of_range_field_is_refused",
"nested_path_off_the_layout_is_refused",
]) else {
return;
};
for name in [
"tuple_struct_out_of_range_field_is_refused",
"nested_path_off_the_layout_is_refused",
] {
let o = outcome(&report, name);
assert!(
!o.is_verified(),
"`{name}` names a field the layout does not have and must be refused; got: {o}"
);
}
}
#[test]
fn a_nested_field_projection_is_read_and_agrees_with_the_body() {
let Some(report) = verify_realistic(&[
"nested_tuple_projection_reads",
"nested_tuple_projection_is_the_body_value",
"nested_named_field_reads_its_leaf",
"nested_named_field_is_the_body_value",
]) else {
return;
};
for name in [
"nested_tuple_projection_reads",
"nested_tuple_projection_is_the_body_value",
"nested_named_field_reads_its_leaf",
"nested_named_field_is_the_body_value",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
}
#[test]
fn nested_leaves_under_different_paths_are_independent() {
let Some(report) = verify_realistic(&[
"nested_tuple_projection_leaves_are_independent",
"nested_named_leaves_under_different_fields",
]) else {
return;
};
for name in [
"nested_tuple_projection_leaves_are_independent",
"nested_named_leaves_under_different_fields",
] {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Failed { .. }),
"`{name}` must be refuted: aliasing its leaves would make it a false proof; got: {o}"
);
}
}
#[test]
fn a_field_write_through_a_mutable_reference_is_applied() {
let Some(report) = verify_realistic(&[
"field_write_through_ref_mut_takes_effect",
"field_write_through_ref_mut_is_not_dropped",
]) else {
return;
};
let true_dir = outcome(&report, "field_write_through_ref_mut_takes_effect");
assert!(
true_dir.is_verified(),
"the write must land, so the read after it is 5; got: {true_dir}"
);
let false_dir = outcome(&report, "field_write_through_ref_mut_is_not_dropped");
assert!(
matches!(false_dir, FnOutcome::Failed { .. }),
"the postcondition must be checked against the written value, so `ret == 0` \
is refuted rather than proved; got: {false_dir}"
);
}
#[test]
fn a_nested_field_write_through_a_mutable_reference_is_applied() {
let Some(report) = verify_realistic(&[
"nested_field_write_through_ref_mut_takes_effect",
"nested_field_write_through_ref_mut_is_not_dropped",
]) else {
return;
};
let true_dir = outcome(&report, "nested_field_write_through_ref_mut_takes_effect");
assert!(true_dir.is_verified(), "the nested write must land; got: {true_dir}");
let false_dir = outcome(&report, "nested_field_write_through_ref_mut_is_not_dropped");
assert!(
matches!(false_dir, FnOutcome::Failed { .. }),
"the nested write must be seen by the read, so `ret == 0` is refuted; got: {false_dir}"
);
}
#[test]
fn a_nested_seed_is_invalidated_by_a_write_and_carried_by_a_copy() {
let Some(report) = verify_realistic(&[
"whole_inner_write_makes_nested_seed_stale",
"whole_inner_write_is_seen_by_the_leaf",
"whole_inner_write_through_a_mutable_reference_is_seen",
"whole_inner_move_carries_the_source_leaf",
"whole_inner_move_is_not_the_stale_destination",
"nested_swap_carries_the_other_side",
"nested_swap_is_not_the_stale_side",
"nested_aggregate_argument_reaches_the_helper",
"nested_aggregate_argument_is_not_the_stale_destination",
"nested_return_carries_the_field",
"nested_return_is_not_the_stale_field",
"whole_struct_copy_carries_nested_paths",
]) else {
return;
};
let stale = outcome(&report, "whole_inner_write_makes_nested_seed_stale");
assert!(
matches!(stale, FnOutcome::Failed { .. }),
"a stale nested seed must let the false contract be refuted, not refused; got: {stale}"
);
let landed = outcome(&report, "whole_inner_write_is_seen_by_the_leaf");
assert!(
landed.is_verified(),
"a nested aggregate write must land where the leaf reads it; got: {landed}"
);
let via_ref = outcome(&report, "whole_inner_write_through_a_mutable_reference_is_seen");
assert!(
via_ref.is_verified(),
"a nested aggregate write through a &mut must reach the target's field path; got: {via_ref}"
);
let copy = outcome(&report, "whole_struct_copy_carries_nested_paths");
assert!(copy.is_verified(), "a whole-struct copy must carry nested paths; got: {copy}");
let carried = outcome(&report, "whole_inner_move_carries_the_source_leaf");
assert!(
carried.is_verified(),
"a nested-to-nested move must carry the source's leaf; got: {carried}"
);
let stale_move = outcome(&report, "whole_inner_move_is_not_the_stale_destination");
assert!(
matches!(stale_move, FnOutcome::Failed { .. }),
"the destination's pre-move leaf must not survive the move; got: {stale_move}"
);
let swap = outcome(&report, "nested_swap_carries_the_other_side");
assert!(swap.is_verified(), "a nested swap must exchange the leaves; got: {swap}");
let swap_stale = outcome(&report, "nested_swap_is_not_the_stale_side");
assert!(
matches!(swap_stale, FnOutcome::Failed { .. }),
"a nested swap must not keep each side's own leaf; got: {swap_stale}"
);
let through = outcome(&report, "nested_aggregate_argument_reaches_the_helper");
assert!(
through.is_verified(),
"a returned nested aggregate must keep its fields; got: {through}"
);
let through_stale =
outcome(&report, "nested_aggregate_argument_is_not_the_stale_destination");
assert!(
matches!(through_stale, FnOutcome::Failed { .. }),
"a returned nested aggregate must not keep a stale field; got: {through_stale}"
);
let field = outcome(&report, "nested_return_carries_the_field");
assert!(
field.is_verified(),
"a returned struct's field must keep its parts; got: {field}"
);
let field_stale = outcome(&report, "nested_return_is_not_the_stale_field");
assert!(
matches!(field_stale, FnOutcome::Failed { .. }),
"a returned struct's field must not keep a stale leaf; got: {field_stale}"
);
}
#[test]
fn a_helpers_write_through_a_mutable_reference_reaches_the_caller() {
let Some(report) = verify_realistic(&[
"helper_field_write_reaches_the_caller",
"a_stale_caller_field_cannot_prove_this",
"helper_scalar_write_reaches_the_caller",
"a_stale_caller_scalar_cannot_prove_this",
]) else {
return;
};
for name in
["helper_field_write_reaches_the_caller", "helper_scalar_write_reaches_the_caller"]
{
let o = outcome(&report, name);
assert!(o.is_verified(), "the helper's write must reach the caller; got: {o}");
}
for name in ["a_stale_caller_field_cannot_prove_this", "a_stale_caller_scalar_cannot_prove_this"]
{
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Failed { .. }),
"a stale caller value must not prove this false contract; got: {o}"
);
}
}
#[test]
fn a_field_array_element_is_one_word_for_contract_and_body() {
let Some(report) = verify_realistic(&[
"a_field_array_write_is_read_back",
"a_field_array_write_is_not_the_seed",
"a_sibling_field_array_is_untouched",
]) else {
return;
};
let read_back = outcome(&report, "a_field_array_write_is_read_back");
assert!(
read_back.is_verified(),
"a write to `x.a[0]` must be seen by the read of `x.a[0]`; got: {read_back}"
);
let seed = outcome(&report, "a_field_array_write_is_not_the_seed");
assert!(
matches!(seed, FnOutcome::Failed { .. }),
"the pre-write seed must not prove a contract the body refutes; got: {seed}"
);
let sibling = outcome(&report, "a_sibling_field_array_is_untouched");
assert!(
sibling.is_verified(),
"writing `x.a[0]` must leave `x.b[0]` alone; got: {sibling}"
);
}
#[test]
fn a_nested_field_array_element_is_one_word_for_contract_and_body() {
let Some(report) = verify_realistic(&[
"a_nested_field_array_write_is_read_back",
"a_nested_field_array_write_is_not_the_seed",
]) else {
return;
};
let read_back = outcome(&report, "a_nested_field_array_write_is_read_back");
assert!(
read_back.is_verified(),
"a nested `o.i.a[0]` write must be seen by the read; got: {read_back}"
);
let seed = outcome(&report, "a_nested_field_array_write_is_not_the_seed");
assert!(
matches!(seed, FnOutcome::Failed { .. }),
"the nested pre-write seed must not prove a refuted contract; got: {seed}"
);
}
#[test]
fn a_field_array_element_crosses_a_reference_argument() {
let Some(report) = verify_realistic(&[
"a_helper_field_array_write_is_read_back",
"a_helper_field_array_write_is_not_the_seed",
"a_helper_nested_aggregate_element_write_is_read_back",
"a_helper_nested_aggregate_element_write_is_not_the_seed",
"a_helper_nested_aggregate_element_read",
]) else {
return;
};
for name in [
"a_helper_field_array_write_is_read_back",
"a_helper_nested_aggregate_element_write_is_read_back",
"a_helper_nested_aggregate_element_read",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must decide and verify; got: {o}");
}
for name in [
"a_helper_field_array_write_is_not_the_seed",
"a_helper_nested_aggregate_element_write_is_not_the_seed",
] {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Failed { .. }),
"`{name}` claims the caller's seed after the helper wrote; must be refuted, got: {o}"
);
}
}
#[test]
fn a_whole_array_target_decides_without_a_false_proof() {
let Some(report) = verify_realistic(&[
"a_whole_array_target_crosses_a_reference_argument",
"a_whole_array_target_cannot_prove_this",
"a_whole_array_target_sibling_cannot_prove_this",
"a_whole_array_target_read_crosses_a_reference_argument",
"a_whole_array_target_read_cannot_prove_this",
"a_whole_array_target_read_modify_write",
"a_whole_array_target_read_modify_write_cannot_prove_this",
"a_nested_whole_array_target_crosses_a_reference_argument",
"a_nested_whole_array_target_cannot_prove_this",
"a_whole_array_target_crosses_two_frames",
"a_whole_array_target_crosses_two_frames_cannot_prove_this",
]) else {
return;
};
let o = outcome(&report, "a_whole_array_target_crosses_a_reference_argument");
assert!(
o.is_verified(),
"a `&mut x.a` array target re-bases the callee's element onto the caller's \
field-path store, so the true contract `ret == 9` must verify; got: {o}"
);
let twin = outcome(&report, "a_whole_array_target_cannot_prove_this");
assert!(
matches!(twin, FnOutcome::Failed { .. }),
"the false twin of the whole-array target must be refuted -- a false proof is the \
only unacceptable outcome, and `Verified` here would be one; got: {twin}"
);
let sibling = outcome(&report, "a_whole_array_target_sibling_cannot_prove_this");
assert!(
!sibling.is_verified(),
"the write to `x.a` must not leak into the sibling `x.b`, so claiming `x.b[0]` \
changed must not verify; got: {sibling}"
);
let read = outcome(&report, "a_whole_array_target_read_crosses_a_reference_argument");
assert!(
read.is_verified(),
"the read-only direction (`peek_of(&x.a)`) must also decide -- the carry-in \
re-bases the caller's field-path element onto the callee's store, so `ret == 5` \
verifies; got: {read}"
);
let read_twin = outcome(&report, "a_whole_array_target_read_cannot_prove_this");
assert!(
!read_twin.is_verified(),
"the false read-only twin (`ret == 7` against a seed of 5) must not verify; \
got: {read_twin}"
);
for (name, want) in [
("a_whole_array_target_read_modify_write", true),
("a_whole_array_target_read_modify_write_cannot_prove_this", false),
("a_nested_whole_array_target_crosses_a_reference_argument", true),
("a_nested_whole_array_target_cannot_prove_this", false),
("a_whole_array_target_crosses_two_frames", true),
("a_whole_array_target_crosses_two_frames_cannot_prove_this", false),
] {
let got = outcome(&report, name);
if want {
assert!(got.is_verified(), "`{name}` must verify; got: {got}");
} else {
assert!(
!got.is_verified(),
"`{name}` is a false direction and must not verify; got: {got}"
);
}
}
}
#[test]
fn a_returned_reference_to_an_element_reaches_the_caller() {
let Some(report) = verify_realistic(&[
"returned_ref_to_an_element_crosses_the_frame",
"returned_ref_to_an_element_cannot_prove_this",
"returned_ref_to_a_sibling_element",
"returned_ref_to_a_sibling_element_cannot_prove_this",
"returned_ref_write_is_not_the_wrong_element_cannot_prove_this",
"returned_ref_to_a_whole_array_element",
"returned_ref_to_a_whole_array_element_cannot_prove_this",
"returned_ref_to_a_nested_whole_array_element",
"returned_ref_to_a_nested_whole_array_element_cannot_prove_this",
"returned_ref_to_a_guarded_symbolic_element",
"returned_ref_to_a_guarded_symbolic_element_cannot_prove_this",
"returned_ref_to_an_unpinned_symbolic_element_cannot_prove_this",
"a_shifted_symbolic_element_cannot_prove_this",
"a_shifted_symbolic_element_is_not_proved",
]) else {
return;
};
for name in [
"returned_ref_to_an_element_crosses_the_frame",
"returned_ref_to_a_sibling_element",
"returned_ref_to_a_whole_array_element",
"returned_ref_to_a_nested_whole_array_element",
"returned_ref_to_a_guarded_symbolic_element",
] {
let o = outcome(&report, name);
assert!(
o.is_verified(),
"the write through the returned element reference must reach the caller's \
element, so `{name}` must verify; got: {o}"
);
}
for name in [
"returned_ref_to_an_element_cannot_prove_this",
"returned_ref_to_a_sibling_element_cannot_prove_this",
"returned_ref_write_is_not_the_wrong_element_cannot_prove_this",
"returned_ref_to_a_whole_array_element_cannot_prove_this",
"returned_ref_to_a_nested_whole_array_element_cannot_prove_this",
"returned_ref_to_a_guarded_symbolic_element_cannot_prove_this",
"returned_ref_to_an_unpinned_symbolic_element_cannot_prove_this",
] {
let o = outcome(&report, name);
assert!(
!o.is_verified(),
"`{name}` is a false direction -- a write aimed at the wrong element would \
prove it; got: {o}"
);
}
for name in [
"a_shifted_symbolic_element_cannot_prove_this",
"a_shifted_symbolic_element_is_not_proved",
] {
let o = outcome(&report, name);
assert!(
!o.is_verified(),
"`{name}` must be a refusal -- a symbolic returned index names no single \
element, so neither direction decides; got: {o}"
);
}
}
#[test]
fn a_helpers_nested_and_read_modify_write_through_a_reference_are_modelled() {
let Some(report) = verify_realistic(&[
"helper_nested_write_reaches_the_caller",
"a_stale_caller_nested_cannot_prove_this",
"read_modify_write_through_helper",
]) else {
return;
};
let nested = outcome(&report, "helper_nested_write_reaches_the_caller");
assert!(nested.is_verified(), "a nested write through a `&mut` must reach the caller; got: {nested}");
let stale = outcome(&report, "a_stale_caller_nested_cannot_prove_this");
assert!(
matches!(stale, FnOutcome::Failed { .. }),
"a stale caller nested value must not prove this false contract; got: {stale}"
);
let rmw = outcome(&report, "read_modify_write_through_helper");
assert!(rmw.is_verified(), "a read-modify-write through a `&mut` must be modelled; got: {rmw}");
}
#[test]
fn a_helper_write_lands_on_the_targets_projection() {
let Some(report) = verify_realistic(&[
"helper_write_reaches_a_field_target",
"a_stale_field_target_cannot_prove_this",
"helper_write_reaches_a_nested_target",
"a_stale_nested_target_cannot_prove_this",
"conditional_helper_write_reaches_the_caller",
"a_conditional_helper_write_cannot_prove_this",
]) else {
return;
};
for name in [
"helper_write_reaches_a_field_target",
"helper_write_reaches_a_nested_target",
"conditional_helper_write_reaches_the_caller",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "a helper write must reach the caller; got: {o}");
}
for name in [
"a_stale_field_target_cannot_prove_this",
"a_stale_nested_target_cannot_prove_this",
"a_conditional_helper_write_cannot_prove_this",
] {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Failed { .. }),
"a stale caller value must not prove this false contract; got: {o}"
);
}
}
#[test]
fn an_element_target_is_written_and_a_by_value_copy_is_not() {
let Some(report) = verify_realistic(&[
"helper_write_reaches_an_element_target",
"a_stale_element_target_cannot_prove_this",
"an_element_write_leaves_its_sibling",
"a_stale_element_sibling_cannot_prove_this",
"a_by_value_callee_write_stays_in_the_callee",
"a_by_value_callee_write_cannot_prove_this",
]) else {
return;
};
for name in [
"helper_write_reaches_an_element_target",
"an_element_write_leaves_its_sibling",
"a_by_value_callee_write_stays_in_the_callee",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "this contract must verify; got: {o}");
}
for name in [
"a_stale_element_target_cannot_prove_this",
"a_stale_element_sibling_cannot_prove_this",
"a_by_value_callee_write_cannot_prove_this",
] {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Failed { .. }),
"a stale caller value must not prove this false contract; got: {o}"
);
}
}
#[test]
fn a_method_is_inlined_by_its_tail_and_a_shared_tail_resolves_by_type() {
let Some(report) = verify_realistic(&[
"a_method_write_reaches_the_caller",
"a_method_write_cannot_prove_this",
"a_method_read_modify_write",
"a_method_leaves_its_sibling",
"a_stale_sibling_cannot_prove_this",
"an_ambiguous_method_tail_cannot_prove_this",
"a_generic_method",
"an_associated_fn_and_builder_chain",
"a_trait_method",
"a_tuple_struct_read_method",
"a_method_with_an_argument",
"a_reborrow_target_reaches_the_caller",
"a_stale_reborrow_cannot_prove_this",
"a_tuple_component_target_reaches_the_caller",
"a_stale_tuple_component_cannot_prove_this",
]) else {
return;
};
for name in [
"a_method_write_reaches_the_caller",
"a_method_read_modify_write",
"a_method_leaves_its_sibling",
"a_generic_method",
"an_associated_fn_and_builder_chain",
"a_trait_method",
"a_tuple_struct_read_method",
"a_method_with_an_argument",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "a method write must reach its caller; got: {o}");
}
for name in ["a_method_write_cannot_prove_this", "a_stale_sibling_cannot_prove_this"] {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Failed { .. }),
"a stale caller value must not prove this false contract; got: {o}"
);
}
for name in [
"a_reborrow_target_reaches_the_caller",
"a_tuple_component_target_reaches_the_caller",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "a sub-place target must reach the caller; got: {o}");
}
for name in [
"a_stale_reborrow_cannot_prove_this",
"a_stale_tuple_component_cannot_prove_this",
] {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Failed { .. }),
"a stale caller value must not prove this false contract; got: {o}"
);
}
let o = outcome(&report, "an_ambiguous_method_tail_cannot_prove_this");
assert!(
matches!(o, FnOutcome::Failed { .. }),
"a shared method tail must resolve to the receiver's own body and refute \
the false contract, not prove it; got: {o}"
);
}
#[test]
fn a_reference_argument_is_read_and_written_through_its_target() {
let Some(report) = verify_realistic(&[
"a_read_through_a_helper",
"a_stale_read_through_a_helper_cannot_prove_this",
"a_bump_through_a_helper",
"a_stale_bump_cannot_prove_this",
"two_reference_arguments",
"two_reference_arguments_other",
"two_reference_arguments_swapped_cannot_prove_this",
"a_swap_through_two_references",
"a_swap_through_two_references_other",
"a_stale_swap_cannot_prove_this",
"a_nested_aggregate_target_reaches",
"a_stale_nested_aggregate_cannot_prove_this",
"a_nested_aggregate_read",
"a_stale_nested_aggregate_read_cannot_prove_this",
]) else {
return;
};
for name in [
"a_read_through_a_helper",
"a_bump_through_a_helper",
"two_reference_arguments",
"two_reference_arguments_other",
"a_swap_through_two_references",
"a_swap_through_two_references_other",
"a_nested_aggregate_target_reaches",
"a_nested_aggregate_read",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "a reference argument must reach its target; got: {o}");
}
for name in [
"a_stale_read_through_a_helper_cannot_prove_this",
"a_stale_bump_cannot_prove_this",
"two_reference_arguments_swapped_cannot_prove_this",
"a_stale_swap_cannot_prove_this",
"a_stale_nested_aggregate_cannot_prove_this",
"a_stale_nested_aggregate_read_cannot_prove_this",
] {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Failed { .. }),
"a stale or unread referent must not prove this false contract; got: {o}"
);
}
}
#[test]
fn a_method_receiver_is_a_sub_place_like_any_other_argument() {
let Some(report) = verify_realistic(&[
"a_method_on_a_nested_receiver",
"a_stale_nested_receiver_cannot_prove_this",
"two_methods_in_sequence",
"a_stale_first_method_cannot_prove_this",
"a_method_through_a_reborrow",
"a_stale_reborrow_receiver_cannot_prove_this",
"a_read_method_feeds_a_write",
"a_stale_read_method_cannot_prove_this",
"a_leaf_write_leaves_its_sibling",
"a_stale_leaf_sibling_cannot_prove_this",
]) else {
return;
};
for name in [
"a_method_on_a_nested_receiver",
"two_methods_in_sequence",
"a_method_through_a_reborrow",
"a_read_method_feeds_a_write",
"a_leaf_write_leaves_its_sibling",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "a method receiver must reach its target; got: {o}");
}
for name in [
"a_stale_nested_receiver_cannot_prove_this",
"a_stale_first_method_cannot_prove_this",
"a_stale_reborrow_receiver_cannot_prove_this",
"a_stale_read_method_cannot_prove_this",
"a_stale_leaf_sibling_cannot_prove_this",
] {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Failed { .. }),
"a stale receiver value must not prove this false contract; got: {o}"
);
}
}
#[test]
fn a_reference_crosses_a_call_in_both_directions() {
let Some(report) = verify_realistic(&[
"a_two_frame_chain",
"a_stale_two_frame_chain_cannot_prove_this",
"a_two_frame_constant",
"a_stale_two_frame_constant_cannot_prove_this",
"a_write_through_a_returned_reference",
"a_stale_returned_reference_cannot_prove_this",
]) else {
return;
};
for name in [
"a_two_frame_chain",
"a_two_frame_constant",
"a_write_through_a_returned_reference",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "a forwarded reference must reach its target; got: {o}");
}
for name in [
"a_stale_two_frame_chain_cannot_prove_this",
"a_stale_two_frame_constant_cannot_prove_this",
"a_stale_returned_reference_cannot_prove_this",
] {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Failed { .. }),
"a dropped write must not prove this false contract; got: {o}"
);
}
}
#[test]
fn a_method_may_return_a_reference_to_its_own_field() {
let Some(report) = verify_realistic(&[
"a_write_through_a_returned_field_reference",
"a_stale_returned_field_reference_cannot_prove_this",
"a_write_through_the_other_returned_reference",
"a_stale_other_returned_reference_cannot_prove_this",
"a_write_through_a_returned_builder",
"a_stale_returned_builder_cannot_prove_this",
]) else {
return;
};
for name in [
"a_write_through_a_returned_field_reference",
"a_write_through_the_other_returned_reference",
"a_write_through_a_returned_builder",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "a returned field reference must reach the field; got: {o}");
}
for name in [
"a_stale_returned_field_reference_cannot_prove_this",
"a_stale_other_returned_reference_cannot_prove_this",
"a_stale_returned_builder_cannot_prove_this",
] {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Failed { .. }),
"a dropped write through a returned reference must not prove this; got: {o}"
);
}
}
#[test]
fn a_returned_reference_carries_its_whole_projection() {
let Some(report) = verify_realistic(&[
"a_write_through_a_returned_nested_reference",
"a_stale_returned_nested_reference_cannot_prove_this",
"a_returned_nested_reference_leaves_its_sibling",
"a_write_through_a_method_nested_reference",
"a_stale_method_nested_reference_cannot_prove_this",
"a_write_through_a_second_argument_reference",
"a_stale_second_argument_reference_cannot_prove_this",
]) else {
return;
};
for name in [
"a_write_through_a_returned_nested_reference",
"a_returned_nested_reference_leaves_its_sibling",
"a_write_through_a_method_nested_reference",
"a_write_through_a_second_argument_reference",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "a returned reference must reach its place; got: {o}");
}
for name in [
"a_stale_returned_nested_reference_cannot_prove_this",
"a_stale_method_nested_reference_cannot_prove_this",
"a_stale_second_argument_reference_cannot_prove_this",
] {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Failed { .. }),
"a dropped write through a returned reference must not prove this; got: {o}"
);
}
}
#[test]
fn a_returned_reference_composes_with_the_next_use() {
let Some(report) = verify_realistic(&[
"a_reference_returned_into_another_call",
"a_stale_returned_into_another_call_cannot_prove_this",
"a_reborrow_of_a_returned_reference",
"a_stale_reborrow_of_a_returned_reference_cannot_prove_this",
"two_returned_field_references",
"a_stale_two_returned_fields_cannot_prove_this",
"a_returned_tuple_component_reference",
"a_stale_tuple_component_reference_cannot_prove_this",
]) else {
return;
};
for name in [
"a_reference_returned_into_another_call",
"a_reborrow_of_a_returned_reference",
"two_returned_field_references",
"a_returned_tuple_component_reference",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "a returned reference must compose with its next use; got: {o}");
}
for name in [
"a_stale_returned_into_another_call_cannot_prove_this",
"a_stale_reborrow_of_a_returned_reference_cannot_prove_this",
"a_stale_two_returned_fields_cannot_prove_this",
"a_stale_tuple_component_reference_cannot_prove_this",
] {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Failed { .. }),
"a dropped or misplaced write must not prove this false contract; got: {o}"
);
}
}
#[test]
fn two_reference_targets_in_one_call_stay_independent() {
let Some(report) = verify_realistic(&[
"two_aggregate_reference_targets",
"two_aggregate_reference_targets_other",
"a_stale_two_aggregate_targets_cannot_prove_this",
"a_swap_of_two_aggregate_targets",
"a_stale_swap_of_aggregate_targets_cannot_prove_this",
"two_elements_through_one_reference",
"two_elements_through_one_reference_other",
"a_stale_two_elements_cannot_prove_this",
"a_swap_of_two_elements",
"a_stale_swap_of_elements_cannot_prove_this",
]) else {
return;
};
for name in [
"two_aggregate_reference_targets",
"two_aggregate_reference_targets_other",
"a_swap_of_two_aggregate_targets",
"two_elements_through_one_reference",
"two_elements_through_one_reference_other",
"a_swap_of_two_elements",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "two reference targets must stay independent; got: {o}");
}
for name in [
"a_stale_two_aggregate_targets_cannot_prove_this",
"a_stale_swap_of_aggregate_targets_cannot_prove_this",
"a_stale_two_elements_cannot_prove_this",
"a_stale_swap_of_elements_cannot_prove_this",
] {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Failed { .. }),
"collapsed or stale targets must not prove this false contract; got: {o}"
);
}
}
#[test]
fn a_scalar_field_crosses_a_reference_argument() {
let Some(report) = verify_realistic(&[
"a_scalar_field_read_through_a_reference",
"a_stale_scalar_field_read_cannot_prove_this",
"a_scalar_field_write_through_a_reference",
"a_stale_scalar_field_write_cannot_prove_this",
]) else {
return;
};
for name in [
"a_scalar_field_read_through_a_reference",
"a_scalar_field_write_through_a_reference",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "a scalar field must cross a reference argument; got: {o}");
}
for name in [
"a_stale_scalar_field_read_cannot_prove_this",
"a_stale_scalar_field_write_cannot_prove_this",
] {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Failed { .. }),
"a stale scalar field must not prove this false contract; got: {o}"
);
}
}
#[test]
fn a_scalar_reference_argument_is_named_in_a_contract() {
let Some(report) = verify_realistic(&[
"bump_scalar_ref",
"a_stale_scalar_ref_cannot_prove_this",
"set_scalar_ref",
"a_scalar_ref_write_cannot_prove_this",
"signed_scalar_ref",
"a_scalar_ref_caller",
"bump_scalar_ref_star",
]) else {
return;
};
for name in [
"bump_scalar_ref",
"set_scalar_ref",
"signed_scalar_ref",
"a_scalar_ref_caller",
"bump_scalar_ref_star",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "a scalar reference argument must be nameable; got: {o}");
}
for name in ["a_stale_scalar_ref_cannot_prove_this", "a_scalar_ref_write_cannot_prove_this"] {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Failed { .. }),
"a scalar reference write must not prove the stale contract; got: {o}"
);
}
}
#[test]
fn a_scalar_reference_argument_reads_as_its_referent() {
use verif::smt;
smt::with_fresh(|| {
let mut args = std::collections::BTreeMap::new();
args.insert("c".to_string(), smt::var(16));
let mut old = std::collections::BTreeMap::new();
old.insert("c".to_string(), smt::var(16));
let p = spec::eval_ensures(
"c == old(c) + 1",
&args,
None,
spec::RET_IS_AGGREGATE,
&std::collections::BTreeSet::new(),
false,
&spec::FieldEnv::default(),
&old,
)
.expect("a scalar reference argument and `old` must parse");
assert!(!smt::is_ill_formed(), "the contract must be well-formed");
assert!(
matches!(smt::prove(p), smt::Verdict::Counterexample(_)),
"`c == old(c) + 1` must be refutable, not a tautology"
);
let star = spec::eval_ensures(
"*c == old(*c) + 1",
&args,
None,
spec::RET_IS_AGGREGATE,
&std::collections::BTreeSet::new(),
false,
&spec::FieldEnv::default(),
&old,
)
.expect("`*c` and `old(*c)` must parse");
assert!(
matches!(smt::prove(smt::iff(star, p)), smt::Verdict::Valid),
"`*c == old(*c) + 1` must mean the same as `c == old(c) + 1`"
);
assert!(
spec::eval_ensures(
"*d == 0",
&args,
None,
spec::RET_IS_AGGREGATE,
&std::collections::BTreeSet::new(),
false,
&spec::FieldEnv::default(),
&old,
)
.is_err(),
"`*d` on an unbound name must be refused"
);
let err = spec::eval_ensures(
"c == old(d)",
&args,
None,
spec::RET_IS_AGGREGATE,
&std::collections::BTreeSet::new(),
false,
&spec::FieldEnv::default(),
&old,
)
.expect_err("`old(d)` has no entry value and must be refused");
assert!(err.to_string().contains("old"), "the refusal must name `old`, got: {err}");
});
}
#[test]
fn a_reference_through_a_reference_is_not_dropped() {
let Some(report) = verify_realistic(&[
"a_write_through_two_levels_of_reference",
"a_stale_two_level_write_cannot_prove_this",
"a_read_through_two_levels_of_reference",
"a_stale_two_level_read_cannot_prove_this",
"a_write_to_a_copy_stays_in_the_copy",
"a_stale_copy_write_cannot_prove_this",
]) else {
return;
};
for name in [
"a_write_through_two_levels_of_reference",
"a_read_through_two_levels_of_reference",
"a_write_to_a_copy_stays_in_the_copy",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "a two-level reference must reach its place; got: {o}");
}
for name in [
"a_stale_two_level_write_cannot_prove_this",
"a_stale_two_level_read_cannot_prove_this",
"a_stale_copy_write_cannot_prove_this",
] {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Failed { .. }),
"a dropped two-level write, or an aliasing copy, must not prove this; got: {o}"
);
}
}
#[test]
fn a_reference_to_a_reference_crosses_a_frame_only_when_refused() {
let Some(report) = verify_realistic(&[
"a_copy_between_two_reference_targets",
"a_stale_copy_between_reference_targets_cannot_prove_this",
"a_write_through_a_double_reference_to_a_struct",
"a_stale_double_reference_struct_cannot_prove_this",
"a_call_through_a_reference_to_a_reference_is_refused",
]) else {
return;
};
for name in [
"a_copy_between_two_reference_targets",
"a_write_through_a_double_reference_to_a_struct",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "a local reference chain must be modelled; got: {o}");
}
for name in [
"a_stale_copy_between_reference_targets_cannot_prove_this",
"a_stale_double_reference_struct_cannot_prove_this",
] {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Failed { .. }),
"a stale or misdirected reference write must not prove this; got: {o}"
);
}
let refused = outcome(&report, "a_call_through_a_reference_to_a_reference_is_refused");
assert!(
matches!(refused, FnOutcome::Incomplete { .. }),
"a `&mut &mut T` call must be refused, not decided; got: {refused}"
);
}
#[test]
fn an_array_field_of_a_moved_aggregate_carries_its_elements() {
let Some(report) = verify_realistic(&[
"a_struct_literal_array_element_is_read_back",
"a_struct_literal_array_element_is_not_the_seed_cannot_prove_this",
"a_struct_literal_array_second_element_is_read_back",
"a_struct_literal_array_second_element_is_not_the_first_cannot_prove_this",
"a_nested_struct_literal_array_element_is_read_back",
"a_nested_struct_literal_array_element_is_not_the_seed_cannot_prove_this",
"a_whole_field_assignment_carries_its_array_elements",
"a_stale_whole_field_array_element_cannot_prove_this",
"a_whole_field_assignment_leaves_its_sibling",
"a_whole_field_assignment_leaves_its_sibling_cannot_prove_this",
"an_array_field_argument_is_read_by_element",
"an_array_field_argument_is_read_by_element_cannot_prove_this",
]) else {
return;
};
for name in [
"a_struct_literal_array_element_is_read_back",
"a_struct_literal_array_second_element_is_read_back",
"a_nested_struct_literal_array_element_is_read_back",
"a_whole_field_assignment_carries_its_array_elements",
"a_whole_field_assignment_leaves_its_sibling",
"an_array_field_argument_is_read_by_element",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "an array field's elements must reach the read; got: {o}");
}
for name in [
"a_struct_literal_array_element_is_not_the_seed_cannot_prove_this",
"a_struct_literal_array_second_element_is_not_the_first_cannot_prove_this",
"a_nested_struct_literal_array_element_is_not_the_seed_cannot_prove_this",
"a_stale_whole_field_array_element_cannot_prove_this",
"a_whole_field_assignment_leaves_its_sibling_cannot_prove_this",
"an_array_field_argument_is_read_by_element_cannot_prove_this",
] {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Failed { .. }),
"a stale or misdirected array-field element must not prove this; got: {o}"
);
}
}
#[test]
fn an_aggregate_literal_element_carries_its_own_leaves() {
let Some(report) = verify_realistic(&[
"an_array_literal_of_aggregates_is_read_back",
"an_array_literal_of_aggregates_is_not_the_other_element_cannot_prove_this",
"an_array_literal_of_aggregates_second_element_is_read_back",
"an_array_literal_of_aggregates_second_is_not_the_first_cannot_prove_this",
"an_array_literal_of_aggregate_fields_is_read_back",
"an_array_literal_of_aggregate_fields_is_not_the_other_cannot_prove_this",
"a_tuple_literal_of_aggregates_is_read_back",
"a_tuple_literal_of_aggregates_is_not_the_other_cannot_prove_this",
"an_element_write_of_an_aggregate_is_read_back",
"an_element_write_of_an_aggregate_is_not_the_old_leaf_cannot_prove_this",
]) else {
return;
};
for name in [
"an_array_literal_of_aggregates_is_read_back",
"an_array_literal_of_aggregates_second_element_is_read_back",
"an_array_literal_of_aggregate_fields_is_read_back",
"a_tuple_literal_of_aggregates_is_read_back",
"an_element_write_of_an_aggregate_is_read_back",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "an aggregate element's leaves must reach the read; got: {o}");
}
for name in [
"an_array_literal_of_aggregates_is_not_the_other_element_cannot_prove_this",
"an_array_literal_of_aggregates_second_is_not_the_first_cannot_prove_this",
"an_array_literal_of_aggregate_fields_is_not_the_other_cannot_prove_this",
"a_tuple_literal_of_aggregates_is_not_the_other_cannot_prove_this",
"an_element_write_of_an_aggregate_is_not_the_old_leaf_cannot_prove_this",
] {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Failed { .. }),
"a leaked or stale element leaf must not prove this; got: {o}"
);
}
}
#[test]
fn a_leaf_write_inside_an_element_is_read_back() {
let verified = [
"an_element_leaf_write_is_read_back",
"an_element_leaf_write_leaves_its_sibling",
"a_second_element_leaf_write_is_read_back",
"a_tuple_component_leaf_write_is_read_back",
];
let refuted = [
"an_element_leaf_write_is_not_the_old_leaf_cannot_prove_this",
"an_element_leaf_write_is_not_the_sibling_cannot_prove_this",
"a_second_element_leaf_write_is_not_the_old_leaf_cannot_prove_this",
"a_tuple_component_leaf_write_is_not_the_old_leaf_cannot_prove_this",
];
let mut names = verified.to_vec();
names.extend_from_slice(&refuted);
let Some(report) = verify_realistic(&names) else { return };
for name in verified {
let o = outcome(&report, name);
assert!(o.is_verified(), "a leaf write inside an element must reach the read; got: {o}");
}
for name in refuted {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Failed { .. }),
"a stale element leaf must not prove this; got: {o}"
);
}
}
#[test]
fn a_variant_measure_proves_loop_termination() {
let ok = verify_src(
"f",
"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n invariant: i <= n,\n variant: n - i,\n ensures: ret == n,\n}\npub fn f(n: u8) -> u8 { let mut i = 0u8; while i < n { i += 1; } i }\n",
);
let Some(o) = ok else { return };
assert!(o.is_verified(), "a decreasing measure must prove termination; got: {o}");
}
#[test]
fn a_loop_that_cannot_terminate_fails() {
let div = verify_src(
"f",
"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n invariant: i >= 0,\n variant: i,\n ensures: ret == 0,\n}\npub fn f(n: u32) -> u32 { let _ = n; let mut i = 0u32; while i < 5 { i += 0; } i }\n",
);
let Some(o) = div else { return };
assert!(!o.is_verified(), "a divergent loop must not verify; got: {o}");
match &o {
FnOutcome::Failed { kind, .. } => {
assert!(kind.contains("variant"), "the failure names termination; got: {kind}")
}
other => panic!("expected a termination failure, got: {other}"),
}
}
#[test]
fn a_measure_that_increases_fails() {
let wrong = verify_src(
"f",
"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n invariant: i <= n,\n variant: i,\n ensures: ret == n,\n}\npub fn f(n: u8) -> u8 { let mut i = 0u8; while i < n { i += 1; } i }\n",
);
let Some(o) = wrong else { return };
assert!(!o.is_verified(), "an increasing measure must fail; got: {o}");
}
#[test]
fn a_loop_without_a_measure_is_still_verified_for_partial_correctness() {
let partial = verify_src(
"f",
"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n invariant: i <= n,\n ensures: ret == n,\n}\npub fn f(n: u8) -> u8 { let mut i = 0u8; while i < n { i += 1; } i }\n",
);
let Some(o) = partial else { return };
assert!(o.is_verified(), "partial correctness must still be proved; got: {o}");
}
#[test]
fn a_measure_without_an_invariant_is_refused() {
let orphan = verify_src(
"f",
"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n variant: n,\n ensures: ret == 5,\n}\npub fn f(n: u32) -> u32 { let _ = n; 5 }\n",
);
let Some(o) = orphan else { return };
assert!(!o.is_verified(), "an orphan measure must not verify; got: {o}");
assert!(matches!(o, FnOutcome::Skipped { .. }), "expected a refusal; got: {o}");
}
#[test]
fn an_unwind_clause_raises_the_unwinding_bound() {
let default = verify_src(
"count_twelve_default",
"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n requires: true,\n ensures: ret == 12,\n}\npub fn count_twelve_default() -> u8 { let mut i = 0u8; while i < 12 { i += 1; } i }\n",
);
let Some(o) = default else { return };
assert!(
!o.is_verified(),
"twelve iterations exceed the default bound, so it must not verify; got: {o}"
);
match &o {
FnOutcome::Incomplete { reasons, .. } => assert!(
reasons.iter().any(|r| r.contains("unwound past")),
"the cutoff must name the unwinding bound; got: {reasons:?}"
),
other => panic!("expected an unwinding cutoff, got: {other}"),
}
let raised = verify_src(
"count_twelve_unwind",
"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n requires: true,\n unwind: 20,\n ensures: ret == 12,\n}\npub fn count_twelve_unwind() -> u8 { let mut i = 0u8; while i < 12 { i += 1; } i }\n",
);
let Some(o) = raised else { return };
assert!(o.is_verified(), "an explicit larger bound must decide the loop; got: {o}");
}
#[test]
fn an_unwind_bound_too_small_for_the_loop_is_refuted() {
let small = verify_src(
"count_five_unwind3",
"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n requires: true,\n unwind: 3,\n ensures: ret == 5,\n}\npub fn count_five_unwind3() -> u8 { let mut i = 0u8; while i < 5 { i += 1; } i }\n",
);
let Some(o) = small else { return };
assert!(!o.is_verified(), "a bound below the trip count must not verify; got: {o}");
match &o {
FnOutcome::Failed { kind, .. } => assert!(
kind.contains("unwind: 3"),
"the failure must name the declared bound; got: {kind}"
),
other => panic!("expected an unwinding-assertion failure, got: {other}"),
}
}
#[test]
fn an_unwind_clause_does_not_turn_a_false_postcondition_true() {
let bad = verify_src(
"count_twelve_bad",
"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n requires: true,\n unwind: 20,\n ensures: ret == 11,\n}\npub fn count_twelve_bad() -> u8 { let mut i = 0u8; while i < 12 { i += 1; } i }\n",
);
let Some(o) = bad else { return };
assert!(!o.is_verified(), "a false postcondition must not verify; got: {o}");
match &o {
FnOutcome::Failed { kind, .. } => {
assert!(kind.contains("postcondition"), "the failure is the postcondition; got: {kind}")
}
other => panic!("expected a postcondition failure, got: {other}"),
}
}
#[test]
fn max_of_verifies_with_a_sufficient_unwind_bound_and_fails_with_a_small_one() {
const BODY: &str = "pub fn max_of(a: [u8; 4]) -> u8 { let mut m = 0; let mut i = 0; \
while i < 4 { if a[i] > m { m = a[i]; } i += 1; } m }\n";
const ENSURES: &str = "/// ensures: ret >= a[0] && ret >= a[1] && ret >= a[2] && ret >= a[3]\n";
let ok = verify_src("max_of", &format!("/// requires: true\n/// unwind: 5\n{ENSURES}{BODY}"));
let Some(o) = ok else { return };
assert!(o.is_verified(), "`max_of` under `unwind: 5` must verify; got: {o}");
let small = verify_src(
"max_of_small",
&format!("/// requires: true\n/// unwind: 3\n{ENSURES}{BODY}")
.replace("max_of", "max_of_small"),
);
let Some(o) = small else { return };
assert!(!o.is_verified(), "`max_of` under `unwind: 3` must not verify; got: {o}");
match &o {
FnOutcome::Failed { kind, .. } => assert!(
kind.contains("unwind: 3"),
"the small-bound failure is the unwinding check; got: {kind}"
),
other => panic!("expected an unwinding-assertion failure, got: {other}"),
}
}
#[test]
fn a_clause_shaped_doc_comment_that_is_not_a_clause_is_refused() {
let typo = verify_src(
"f",
"/// requires: x == 0\n/// ensuers: ret == 99\npub fn f(x: u32) -> u32 { 5 }\n",
);
let Some(o) = typo else { return };
assert!(!o.is_verified(), "a typo must not verify the function without it; got: {o}");
assert!(
matches!(o, FnOutcome::Skipped { .. }),
"a dropped clause is a refusal, not a silent pass; got: {o}"
);
assert!(o.to_string().contains("ensuers"), "the refusal names the line; got: {o}");
assert!(o.to_string().contains("ensures"), "and suggests the keyword; got: {o}");
let orphan = verify_src("g", "/// variant: n\n/// ensures: ret == 5\npub fn g(n: u32) -> u32 { let _ = n; 5 }\n");
let Some(o) = orphan else { return };
assert!(!o.is_verified(), "an orphan measure must not pass silently; got: {o}");
assert!(o.to_string().contains("variant"), "the refusal names it; got: {o}");
let prose = verify_src(
"h",
"/// direction: a contract claiming the pre-write value would be proved.\n\
/// requires: x == 0\n/// ensures: ret == 5\npub fn h(x: u32) -> u32 { 5 }\n",
);
let Some(o) = prose else { return };
assert!(o.is_verified(), "prose with a colon is not a clause; got: {o}");
}
#[test]
fn a_pinned_rewrite_after_a_symbolic_write_is_read_back() {
let recovered = [
"a_pinned_leaf_rewrite_after_a_symbolic_write_is_read_back",
"a_pinned_element_rewrite_after_a_symbolic_write_is_read_back",
"a_pinned_leaf_rewrite_after_a_symbolic_element_write_is_read_back",
"a_helper_pinned_rewrite_after_a_symbolic_write_is_read_back",
];
let Some(report) = verify_realistic(&recovered) else { return };
for name in recovered {
let o = outcome(&report, name);
assert!(o.is_verified(), "a pinned rewrite is a known leaf; got: {o}");
}
let unknown = [
"a_pinned_rewrite_does_not_recover_its_sibling",
"a_pinned_rewrite_does_not_revive_the_old_leaf",
];
let Some(report) = verify_realistic(&unknown) else { return };
for name in unknown {
let o = outcome(&report, name);
assert!(!o.is_verified(), "a sibling stays unknown after a pinned rewrite; got: {o}");
}
}
#[test]
fn an_unpinned_write_poisons_the_whole_array() {
let names = [
"an_element_copy_after_an_unpinned_write_is_not_the_old_leaf",
"an_element_copy_after_an_unpinned_write_is_not_the_sibling",
"an_element_copy_after_an_unpinned_write_is_not_the_new_leaf",
"an_element_copy_after_an_unpinned_leaf_write_is_not_the_old_leaf",
"a_helper_unpinned_write_is_not_the_callers_old_leaf",
"a_helper_unpinned_write_is_not_the_callers_sibling",
];
let Some(report) = verify_realistic(&names) else { return };
for name in names {
let o = outcome(&report, name);
assert!(
!o.is_verified(),
"an unpinned write leaves no element known, so this must not be proved; got: {o}"
);
}
}
#[test]
fn a_whole_element_write_of_an_aggregate_crosses_a_call_boundary() {
let verified = [
"an_element_copy_from_another_element_is_read_back",
"a_helper_whole_element_write_is_read_back",
"a_helper_whole_element_write_leaves_its_sibling",
"a_helper_element_copy_is_read_back",
];
let refuted = [
"an_element_copy_is_not_the_old_leaf_cannot_prove_this",
"a_helper_whole_element_write_is_not_the_callers_leaf_cannot_prove_this",
"a_helper_whole_element_write_is_not_the_sibling_cannot_prove_this",
"a_helper_element_copy_is_not_the_old_leaf_cannot_prove_this",
];
let mut names = verified.to_vec();
names.extend_from_slice(&refuted);
let Some(report) = verify_realistic(&names) else { return };
for name in verified {
let o = outcome(&report, name);
assert!(o.is_verified(), "a whole-element write must reach the read; got: {o}");
}
for name in refuted {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Failed { .. }),
"a stale element leaf must not prove this; got: {o}"
);
}
}
#[test]
fn an_element_leaf_store_crosses_a_call_boundary() {
let verified = [
"a_helper_leaf_write_through_a_mutable_array_is_read_back",
"a_helper_leaf_read_through_an_array_argument_decides",
"a_returned_array_of_aggregates_keeps_its_leaves",
];
let refuted = [
"a_helper_leaf_write_is_not_the_callers_leaf_cannot_prove_this",
"a_helper_leaf_read_is_not_a_made_up_value_cannot_prove_this",
"a_returned_array_of_aggregates_is_not_a_made_up_value_cannot_prove_this",
];
let mut names = verified.to_vec();
names.extend_from_slice(&refuted);
let Some(report) = verify_realistic(&names) else { return };
for name in verified {
let o = outcome(&report, name);
assert!(o.is_verified(), "a leaf must cross the call boundary; got: {o}");
}
for name in refuted {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Failed { .. }),
"a dropped or stale leaf carry must not prove this; got: {o}"
);
}
}
#[test]
fn a_whole_aggregate_replacement_through_a_sub_place_decides() {
let Some(report) = verify_realistic(&[
"whole_replacement_through_sub_place",
"whole_replacement_through_sub_place_cannot_prove_this",
"whole_replacement_leaves_the_sibling",
"whole_replacement_leaves_the_sibling_cannot_prove_this",
"whole_replacement_from_a_local",
"whole_replacement_from_a_local_cannot_prove_this",
]) else {
return;
};
for name in [
"whole_replacement_through_sub_place",
"whole_replacement_leaves_the_sibling",
"whole_replacement_from_a_local",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "a whole replacement must reach the caller's leaf; got: {o}");
}
for name in [
"whole_replacement_through_sub_place_cannot_prove_this",
"whole_replacement_leaves_the_sibling_cannot_prove_this",
"whole_replacement_from_a_local_cannot_prove_this",
] {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Failed { .. }),
"a stale or misdirected whole replacement must not prove this; got: {o}"
);
}
}
#[test]
fn a_named_const_item_is_inlined_at_its_use_site() {
let Some(report) = verify_realistic(&[
"named_const_is_read",
"named_const_is_read_cannot_prove_this",
"named_const_keeps_its_width",
"named_const_keeps_its_width_cannot_prove_this",
"named_bool_const_selects",
"named_bool_const_selects_cannot_prove_this",
"named_const_bounds_a_comparison",
"named_const_bounds_a_comparison_cannot_prove_this",
"named_const_matches_an_equality",
"named_const_matches_an_equality_cannot_prove_this",
"named_negative_const_is_signed",
"named_negative_const_is_signed_cannot_prove_this",
"nested_module_const_is_read",
"nested_module_const_is_read_cannot_prove_this",
]) else {
return;
};
for name in [
"named_const_is_read",
"named_const_keeps_its_width",
"named_bool_const_selects",
"named_const_bounds_a_comparison",
"named_const_matches_an_equality",
"named_negative_const_is_signed",
"nested_module_const_is_read",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "a named const must fold at its use site; got: {o}");
}
for name in [
"named_const_is_read_cannot_prove_this",
"named_const_keeps_its_width_cannot_prove_this",
"named_bool_const_selects_cannot_prove_this",
"named_const_bounds_a_comparison_cannot_prove_this",
"named_const_matches_an_equality_cannot_prove_this",
"named_negative_const_is_signed_cannot_prove_this",
"nested_module_const_is_read_cannot_prove_this",
] {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Failed { .. }),
"a wrong inlined const value must not prove this; got: {o}"
);
}
}
#[test]
fn a_contract_may_name_a_const_item() {
let Some(report) = verify_realistic(&[
"a_contract_names_a_const",
"a_contract_names_a_const_cannot_prove_this",
"a_contract_names_a_negative_const",
"a_contract_names_a_bool_const",
"a_contract_names_a_qualified_const",
"a_contract_names_a_qualified_const_cannot_prove_this",
"a_contract_names_an_expression_const",
"a_misspelled_const_is_refused",
]) else {
return;
};
for name in [
"a_contract_names_a_const",
"a_contract_names_a_negative_const",
"a_contract_names_a_bool_const",
"a_contract_names_a_qualified_const",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "a contract must resolve a named const; got: {o}");
}
for name in [
"a_contract_names_a_const_cannot_prove_this",
"a_contract_names_a_qualified_const_cannot_prove_this",
] {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Failed { .. }),
"a wrong const value must not prove this; got: {o}"
);
}
let expr = outcome(&report, "a_contract_names_an_expression_const");
assert!(
expr.is_verified(),
"a contract must resolve an expression const now that it is folded; got: {expr}"
);
let misspelled = outcome(&report, "a_misspelled_const_is_refused");
assert!(
matches!(misspelled, FnOutcome::Skipped { .. }),
"an unresolvable const name must be refused, not guessed; got: {misspelled}"
);
}
#[test]
fn an_expression_const_is_inlined_in_both_directions() {
let Some(report) = verify_realistic(&[
"named_const_of_an_expression_is_inlined",
"named_const_of_an_expression_is_inlined_cannot_prove_this",
"an_expression_const_keeps_its_width",
]) else {
return;
};
let true_direction = outcome(&report, "named_const_of_an_expression_is_inlined");
assert!(
true_direction.is_verified(),
"an expression const must fold to its value; got: {true_direction}"
);
let false_direction =
outcome(&report, "named_const_of_an_expression_is_inlined_cannot_prove_this");
assert!(
matches!(false_direction, FnOutcome::Failed { .. }),
"`NEXT` is 11, so `ret == 10` must be refuted, not proved; got: {false_direction}"
);
let width = outcome(&report, "an_expression_const_keeps_its_width");
assert!(width.is_verified(), "an expression const keeps its width; got: {width}");
}
#[test]
fn a_signed_comparison_const_uses_the_operand_type() {
let Some(report) = verify_realistic(&[
"a_signed_comparison_const_is_read",
"a_signed_comparison_const_is_read_cannot_prove_this",
"an_unsigned_comparison_const_is_read",
]) else {
return;
};
let signed = outcome(&report, "a_signed_comparison_const_is_read");
assert!(
signed.is_verified(),
"`-1i8 < 0i8` is true and the contract must prove it; got: {signed}"
);
let false_direction = outcome(&report, "a_signed_comparison_const_is_read_cannot_prove_this");
assert!(
matches!(false_direction, FnOutcome::Failed { .. }),
"`LESS` is true, so `ret == false` must be refuted -- reading the operands \
as unsigned proves it from a wrong value; got: {false_direction}"
);
let unsigned = outcome(&report, "an_unsigned_comparison_const_is_read");
assert!(unsigned.is_verified(), "`200u8 > 100u8` is true; got: {unsigned}");
}
#[test]
fn a_forward_referenced_const_is_resolved() {
let Some(report) = verify_realistic(&[
"a_forward_referenced_const_is_read",
"a_forward_referenced_const_is_read_cannot_prove_this",
]) else {
return;
};
let resolved = outcome(&report, "a_forward_referenced_const_is_read");
assert!(
resolved.is_verified(),
"a constant may name a later one; the fold must reach a fixpoint; got: {resolved}"
);
let false_direction = outcome(&report, "a_forward_referenced_const_is_read_cannot_prove_this");
assert!(
matches!(false_direction, FnOutcome::Failed { .. }),
"`FWD_NEXT` is 11, so `ret == 12` must be refuted; got: {false_direction}"
);
}
#[test]
fn an_unused_i128_expression_const_does_not_abort_the_run() {
let Some(report) =
verify_realistic(&["a_file_with_an_unused_i128_const_still_verifies"])
else {
return;
};
let o = outcome(&report, "a_file_with_an_unused_i128_const_still_verifies");
assert!(
o.is_verified(),
"an unused i128 const must not abort the parse; got: {o}"
);
}
#[test]
fn a_local_const_is_not_in_scope_in_another_function() {
let Some(report) = verify_realistic(&[
"a_local_const_owner",
"a_local_const_is_not_in_scope_in_another_function",
]) else {
return;
};
let owner = outcome(&report, "a_local_const_owner");
assert!(owner.is_verified(), "the owner reads its own local const; got: {owner}");
let other = outcome(&report, "a_local_const_is_not_in_scope_in_another_function");
assert!(
!other.is_verified(),
"a contract must not resolve another function's local const -- that is a \
wrong proof; got: {other}"
);
}
#[test]
fn no_cannot_prove_entry_is_ever_verified() {
let Some(report) = verify_realistic(&[]) else { return };
let undecided_on_purpose: &[(&str, &str)] = &[
(
"a_shifted_symbolic_element_cannot_prove_this",
"a symbolic shift of an array element is not modelled, so the contract is \
unreadable -- the read never reaches the refutation",
),
(
"default_body_self_call_is_not_the_default_cannot_prove_this",
"the self-call to a trait default body is unmodelled, so the path is cut \
before the false claim is checked",
),
(
"generic_slice_element_cannot_prove_this",
"a generic `&[T]` has no element width, so `v[0]` is an unmodelled element \
read and `ret == d` is unreadable -- the length is modelled, the element \
is not, so the claim is a skip rather than a refutation",
),
];
let mut checked = 0usize;
let mut liars = Vec::new();
let mut wrongly_undecided = Vec::new();
for (name, o) in &report.outcomes {
let false_direction = name.ends_with("_cannot_prove_this");
if !false_direction {
continue;
}
checked += 1;
if o.is_verified() {
liars.push(name.clone());
} else if !matches!(o, FnOutcome::Failed { .. })
&& !undecided_on_purpose.iter().any(|(n, _)| n == name)
{
wrongly_undecided.push(format!("{name}: {o}"));
}
}
assert!(
liars.is_empty(),
"these entries claim a false contract and were `verified` -- a false proof: {liars:?}"
);
assert!(
wrongly_undecided.is_empty(),
"these tripwires were neither refuted nor on the documented undecided list -- a \
tripwire that was not pulled is not evidence: {wrongly_undecided:#?}"
);
assert!(
checked >= 40,
"expected the corpus to carry dozens of false-direction probes, found {checked}; \
has the naming convention changed?"
);
}
#[test]
fn a_loop_havocs_what_it_writes_through() {
let names = [
"for_loop_invariant_holds",
"for_loop_invariant_cannot_prove_this",
"while_writes_through_ref_holds",
"while_writes_through_ref_cannot_prove_this",
"ref_arg_written_in_a_loop_holds",
"ref_arg_written_in_a_loop_cannot_prove_this",
"call_writes_through_in_a_loop_holds",
"call_writes_through_in_a_loop_cannot_prove_this",
];
let Some(report) = verify_realistic(&names) else { return };
let outcome = |name: &str| {
report
.outcomes
.iter()
.find(|(n, _)| n == name)
.unwrap_or_else(|| panic!("`{name}` must be in the report"))
.1
.clone()
};
for holds in [
"for_loop_invariant_holds",
"while_writes_through_ref_holds",
"ref_arg_written_in_a_loop_holds",
"call_writes_through_in_a_loop_holds",
] {
assert!(
outcome(holds).is_verified(),
"`{holds}` establishes its postcondition and must verify, got: {}",
outcome(holds)
);
}
for twin in [
"for_loop_invariant_cannot_prove_this",
"while_writes_through_ref_cannot_prove_this",
"ref_arg_written_in_a_loop_cannot_prove_this",
"call_writes_through_in_a_loop_cannot_prove_this",
] {
match outcome(twin) {
FnOutcome::Failed { kind, .. } => assert!(
kind.contains("postcondition") || kind.contains("invariant"),
"`{twin}` must fail on its own claim, got `{kind}`"
),
other => panic!(
"`{twin}` claims a false postcondition and must be refuted; a header \
that is not havoced proves it, got: {other}"
),
}
}
}
#[test]
fn a_deep_term_walk_is_refused_not_allowed_to_overflow_the_stack() {
let Some(report) = verify_realistic(&[
"a_symbolic_division_by_a_non_power_of_two_at_i64",
"a_signed_division_by_a_non_power_of_two_at_i64",
"a_signed_constant_division_at_i64",
]) else {
return;
};
let deep = outcome(&report, "a_symbolic_division_by_a_non_power_of_two_at_i64");
assert!(
!deep.is_verified(),
"the general divider must not be reported verified: {deep}"
);
let pinned = outcome(&report, "a_signed_division_by_a_non_power_of_two_at_i64");
assert!(
pinned.is_verified(),
"the pinned divider must be decided by the fold, got: {pinned}"
);
let shallow = outcome(&report, "a_signed_constant_division_at_i64");
assert!(
shallow.is_verified(),
"the power-of-two fast path must still verify: {shallow}"
);
}
#[test]
fn a_pin_reaches_an_aggregate_part_not_only_a_whole_argument() {
let Some(report) = verify_realistic(&[
"a_field_pinned_division_at_i64",
"a_field_pinned_division_cannot_prove_this",
"a_nested_pinned_division_at_i64",
"a_nested_pinned_division_cannot_prove_this",
"an_element_pinned_division_at_i64",
"an_element_pinned_division_cannot_prove_this",
]) else {
return;
};
for name in [
"a_field_pinned_division_at_i64",
"a_nested_pinned_division_at_i64",
"an_element_pinned_division_at_i64",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "a pinned aggregate part must be decided; `{name}` got: {o}");
}
for name in [
"a_field_pinned_division_cannot_prove_this",
"a_nested_pinned_division_cannot_prove_this",
"an_element_pinned_division_cannot_prove_this",
] {
let o = outcome(&report, name);
assert!(
!o.is_verified(),
"a false claim about a pinned part must be refuted, not proved; `{name}` got: {o}"
);
}
}
#[test]
fn a_callee_contract_is_never_assumed() {
let Some(report) = verify_realistic(&[
"a_helper_whose_contract_is_false",
"a_caller_of_a_lying_helper_cannot_prove_this",
"a_caller_of_a_lying_helper_knows_the_truth",
"a_call_that_violates_a_precondition_is_not_checked",
"a_call_that_divides_by_zero_cannot_prove_this",
"a_vacuous_helper_whose_postcondition_is_false",
"a_caller_inheriting_a_vacuous_lie_cannot_prove_this",
"a_caller_of_a_vacuous_helper_knows_the_truth",
"a_recursive_contract_that_is_false_cannot_prove_this",
"a_mutual_lie_a_cannot_prove_this",
"a_mutual_lie_b_cannot_prove_this",
"an_invariant_false_on_entry_cannot_prove_this",
"an_invariant_not_preserved_cannot_prove_this",
]) else {
return;
};
for name in [
"a_caller_of_a_lying_helper_knows_the_truth",
"a_caller_of_a_vacuous_helper_knows_the_truth",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "the honest direction must verify; `{name}` got: {o}");
}
let unchecked = outcome(&report, "a_call_that_violates_a_precondition_is_not_checked");
assert!(
unchecked.is_verified(),
"a callee precondition is not a call-site obligation; expected verified, got: {unchecked}"
);
for name in [
"a_helper_whose_contract_is_false",
"a_caller_of_a_lying_helper_cannot_prove_this",
"a_call_that_divides_by_zero_cannot_prove_this",
"a_vacuous_helper_whose_postcondition_is_false",
"a_caller_inheriting_a_vacuous_lie_cannot_prove_this",
"a_recursive_contract_that_is_false_cannot_prove_this",
"a_mutual_lie_a_cannot_prove_this",
"a_mutual_lie_b_cannot_prove_this",
"an_invariant_false_on_entry_cannot_prove_this",
"an_invariant_not_preserved_cannot_prove_this",
] {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Failed { .. }),
"an assumed callee contract, an unchecked induction, or a vacuous \
precondition must not prove this; `{name}` got: {o}"
);
}
}
#[test]
fn a_counter_arithmetic_in_an_invariant_is_not_a_written_constant() {
let Some(report) = verify_realistic(&[
"an_invariant_subtracts_from_a_counter",
"an_invariant_subtracts_from_a_counter_cannot_prove_this",
"an_invariant_written_underflow_is_refused",
]) else {
return;
};
let o = outcome(&report, "an_invariant_subtracts_from_a_counter");
assert!(
o.is_verified(),
"a counter's `i - 1` is a variable's arithmetic and must be read; got: {o}"
);
let o = outcome(&report, "an_invariant_subtracts_from_a_counter_cannot_prove_this");
assert!(
matches!(o, FnOutcome::Failed { .. }),
"the false twin must be refuted, not proved; got: {o}"
);
let o = outcome(&report, "an_invariant_written_underflow_is_refused");
assert!(
matches!(o, FnOutcome::Skipped { .. } | FnOutcome::Incomplete { .. }),
"the written `0 - 1` must still be refused, not decided; got: {o}"
);
}
#[test]
fn a_slices_length_is_read_on_any_toolchain() {
let Some(report) = verify_realistic(&["slice_symbolic_index"]) else { return };
let o = outcome(&report, "slice_symbolic_index");
assert!(o.is_verified(), "the slice entry must decide on any toolchain; got: {o}");
}
#[test]
fn a_postcondition_can_name_a_tuple_component() {
let Some(report) = verify_realistic(&["split"]) else { return };
let o = outcome(&report, "split");
assert!(o.is_verified(), "`split` must verify, got: {o}");
}
#[test]
fn a_helper_that_indexes_its_parameter_reaches_the_caller_element() {
let names = ["head", "caller_of_head"];
let Some(report) = verify_realistic(&names) else { return };
for name in names {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
}
#[test]
fn a_write_through_a_reference_reaches_the_caller() {
let names = ["clear_head", "caller_of_clear_head"];
let Some(report) = verify_realistic(&names) else { return };
for name in names {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
}
#[test]
fn a_by_value_helper_cannot_write_the_callers_array() {
let Some(report) = verify_realistic(&["caller_of_written_copy"]) else { return };
let o = outcome(&report, "caller_of_written_copy");
assert!(
matches!(o, FnOutcome::Failed { .. }),
"a by-value helper's write leaked to the caller; got: {o}"
);
}
#[test]
fn a_constant_left_signed_compare_is_signed_not_unsigned() {
let names = ["signed_const_left_false", "signed_const_left_true"];
let Some(report) = verify_realistic(&names) else { return };
let bad = outcome(&report, "signed_const_left_false");
assert!(
matches!(bad, FnOutcome::Failed { .. }),
"`signed_const_left_false` proves a false contract; got: {bad}"
);
let good = outcome(&report, "signed_const_left_true");
assert!(good.is_verified(), "`signed_const_left_true` must verify, got: {good}");
}
#[test]
fn a_postcondition_can_name_a_bool_tuple_component() {
let Some(report) = verify_realistic(&["bool_component"]) else { return };
let o = outcome(&report, "bool_component");
assert!(o.is_verified(), "`bool_component` must verify, got: {o}");
}
#[test]
fn a_tuple_locals_component_can_be_read_back() {
let Some(report) = verify_realistic(&["tuple_local_component"]) else { return };
let o = outcome(&report, "tuple_local_component");
assert!(o.is_verified(), "`tuple_local_component` must verify, got: {o}");
}
#[test]
fn a_tuple_returning_calls_component_reaches_the_caller() {
let names = ["min2", "min_call"];
let Some(report) = verify_realistic(&names) else { return };
for name in names {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
}
#[test]
fn a_tuple_component_read_cannot_prove_the_wrong_component() {
let names = ["tuple_component_tripwire", "min_call_tripwire"];
let Some(report) = verify_realistic(&names) else { return };
for name in names {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Failed { .. }),
"`{name}` proves the wrong tuple component; got: {o}"
);
}
}
#[test]
fn a_widening_cast_respects_the_sources_signedness() {
let names = [
"widen_signed_true",
"widen_signed_false",
"widen_unsigned_true",
"widen_unsigned_false",
];
let Some(report) = verify_realistic(&names) else { return };
for name in ["widen_signed_true", "widen_unsigned_true"] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
for name in ["widen_signed_false", "widen_unsigned_false"] {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Failed { .. }),
"`{name}` proves a false widening; got: {o}"
);
}
}
#[test]
fn a_signed_element_comparison_keeps_the_elements_sign() {
let names = ["signed_slice_element_is_signed", "signed_slice_element_tripwire"];
let Some(report) = verify_realistic(&names) else { return };
let o = outcome(&report, "signed_slice_element_is_signed");
assert!(o.is_verified(), "`signed_slice_element_is_signed` must verify, got: {o}");
let o = outcome(&report, "signed_slice_element_tripwire");
assert!(
matches!(o, FnOutcome::Failed { .. }),
"`signed_slice_element_tripwire` proves `!(i8::MIN < 0)`; got: {o}"
);
}
#[test]
fn a_postcondition_can_name_a_component_a_modelled_call_wrote() {
let names = [
"overflowing_add_flag_or_exact_sum",
"overflowing_add_small_operands_never_flag",
"overflowing_add_value_is_exact_when_no_overflow",
"overflowing_add_flag_never_set_tripwire",
"overflowing_add_one_bound_only_tripwire",
"overflowing_add_wrapped_value_below_operand_tripwire",
];
let Some(report) = verify_realistic(&names) else { return };
for name in [
"overflowing_add_flag_or_exact_sum",
"overflowing_add_small_operands_never_flag",
"overflowing_add_value_is_exact_when_no_overflow",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
for name in [
"overflowing_add_flag_never_set_tripwire",
"overflowing_add_one_bound_only_tripwire",
"overflowing_add_wrapped_value_below_operand_tripwire",
] {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Failed { .. }),
"`{name}` states a false contract a dropped component would prove; got: {o}"
);
}
}
#[test]
fn a_reference_component_the_contract_does_not_name_does_not_skip_the_function() {
let Some(report) = verify_realistic(&["first_component_only"]) else { return };
let o = outcome(&report, "first_component_only");
assert!(o.is_verified(), "`first_component_only` must verify, got: {o}");
}
#[test]
fn a_contract_naming_an_unknown_field_is_refused() {
let mut args = std::collections::BTreeMap::new();
args.insert("c".to_string(), verif::smt::var(8));
let mut env = spec::FieldEnv::default();
env.declare_arg("c");
let err = spec::eval_requires("c.lo <= 3", &args, &std::collections::BTreeSet::new(), &env)
.expect_err("an unbound field must be refused");
assert!(
err.to_string().contains("unknown field `lo`"),
"the refusal must name the field, got: {err}"
);
}
#[test]
fn the_field_rewrite_does_not_fire_inside_a_longer_name() {
let mut fields = spec::FieldEnv::default();
let c = verif::smt::var(8);
fields.bind_bits(1, "c", "lo", 0, 8, false).unwrap();
let mut args = std::collections::BTreeMap::new();
args.insert("myc".to_string(), c);
let err = spec::eval_requires("myc.lo <= 3", &args, &std::collections::BTreeSet::new(), &fields)
.expect_err("`myc.lo` must not be rewritten to the binding for `c.lo`");
let msg = err.to_string();
assert!(
msg.contains("unknown name") || msg.contains("expected a comparison"),
"`myc.lo` must be refused, got: {msg}"
);
assert!(
!msg.contains("unknown field"),
"`myc` is not a known aggregate, so the message must not claim a bad field: {msg}"
);
let ok = spec::eval_requires("c.lo <= 3", &args, &std::collections::BTreeSet::new(), &fields);
assert!(ok.is_ok(), "the bound path must resolve, got: {ok:?}");
}
#[test]
fn a_symbolic_array_index_is_modelled_as_an_ite_chain() {
let Some(report) = verify_realistic(&["array_symbolic_index"]) else { return };
let o = outcome(&report, "array_symbolic_index");
assert!(o.is_verified(), "`array_symbolic_index` must verify, got: {o}");
}
#[test]
fn an_unbounded_symbolic_array_index_is_refused() {
let Some(report) = verify_realistic(&["array_unbounded_index_refused"]) else { return };
let o = outcome(&report, "array_unbounded_index_refused");
match o {
FnOutcome::Skipped { reason } => assert!(
reason.contains("not known to be in range"),
"the refusal must say the index is unbounded, got: {reason}"
),
other => panic!("`array_unbounded_index_refused` must be skipped, got: {other}"),
}
}
#[test]
fn a_contract_naming_a_different_symbolic_index_is_refused() {
let Some(report) = verify_realistic(&["array_wrong_index_refused"]) else { return };
let o = outcome(&report, "array_wrong_index_refused");
assert!(
matches!(o, FnOutcome::Skipped { .. }),
"`array_wrong_index_refused` must be skipped, got: {o}"
);
}
#[test]
fn a_contract_error_quotes_the_source_text() {
use verif::mir::spec;
use verif::smt;
let mut fields = spec::FieldEnv::default();
let mut args = std::collections::BTreeMap::new();
let i = smt::var(64);
args.insert("i".to_string(), i);
fields.bind_array_len(0, "a", 8, false, 4);
fields.bind_sym_index("a", 8, spec::IndexBound::Const(4), "i", i);
let src = "ret == a[i] && ret == a[j]";
let err = spec::eval_ensures(
src,
&args,
Some(smt::var(8)),
spec::RET_IS_UNKNOWN,
&std::collections::BTreeSet::new(),
false,
&fields,
&std::collections::BTreeMap::new(),
)
.expect_err("`a[j]` has no chain and must be refused");
assert_eq!(
err.text, src,
"the error must quote the source contract, not the rewritten one"
);
assert!(
!err.text.contains("__"),
"no mangled name may leak into the quoted text: {}",
err.text
);
}
#[test]
fn a_symbolic_index_through_a_local_alias_is_resolved() {
let Some(report) =
verify_realistic(&["array_local_index_through_alias", "array_local_index_tripwire"])
else {
return;
};
let o = outcome(&report, "array_local_index_through_alias");
assert!(o.is_verified(), "`array_local_index_through_alias` must verify, got: {o}");
let t = outcome(&report, "array_local_index_tripwire");
assert!(
!t.is_verified(),
"the alias tripwire must be refuted, got: {t}"
);
}
#[test]
fn a_subscript_through_a_reassigned_argument_is_refused() {
let Some(report) = verify_realistic(&["array_local_index_written_refused"]) else { return };
let o = outcome(&report, "array_local_index_written_refused");
match o {
FnOutcome::Skipped { reason } => assert!(
reason.contains("unknown name"),
"a subscript through a reassigned argument must be refused as an unknown name, \
got: {reason}"
),
other => panic!("`array_local_index_written_refused` must be skipped, got: {other}"),
}
}
#[test]
fn a_symbolic_index_resolves_under_every_spelling() {
let Some(report) =
verify_realistic(&["array_two_spellings_of_one_index", "array_two_spellings_tripwire"])
else {
return;
};
let o = outcome(&report, "array_two_spellings_of_one_index");
assert!(o.is_verified(), "`array_two_spellings_of_one_index` must verify, got: {o}");
let t = outcome(&report, "array_two_spellings_tripwire");
assert!(
!t.is_verified(),
"the two-spellings tripwire must be refuted, got: {t}"
);
}
#[test]
fn a_shadowed_alias_is_refused() {
let Some(report) = verify_realistic(&["array_shadowed_alias_refused"]) else { return };
let o = outcome(&report, "array_shadowed_alias_refused");
match o {
FnOutcome::Skipped { reason } => assert!(
reason.contains("unknown name"),
"a shadowed alias must be refused as an unknown name, got: {reason}"
),
other => panic!("`array_shadowed_alias_refused` must be skipped, got: {other}"),
}
}
#[test]
fn a_qualified_standard_construction_resolves() {
let Some(report) = verify_realistic(&[
"option_qualified_some_payload",
"option_qualified_some_payload_tripwire",
]) else {
return;
};
let o = outcome(&report, "option_qualified_some_payload");
assert!(o.is_verified(), "`option_qualified_some_payload` must verify, got: {o}");
let t = outcome(&report, "option_qualified_some_payload_tripwire");
assert!(!t.is_verified(), "the qualified-construction tripwire must be refuted, got: {t}");
}
#[test]
fn the_option_methods_read_the_receivers_tag_and_payload() {
let names = [
"option_unwrap_or_fallback",
"option_unwrap_or_fallback_tripwire",
"option_is_some_true_on_some",
"option_is_some_true_on_some_tripwire",
"option_is_some_false_on_none",
"option_is_some_false_on_none_tripwire",
"option_is_none_false_on_some",
"option_is_none_false_on_some_tripwire",
"option_is_none_true_on_none",
"option_is_none_true_on_none_tripwire",
"option_unwrap_guarded",
"option_unwrap_unguarded",
"option_expect_guarded",
"option_expect_unguarded",
"option_is_some_guards_unwrap",
"option_is_none_guards_unwrap",
"option_guard_tripwire",
"option_arg_unwrap_or",
"option_arg_unwrap_or_tripwire",
"option_arg_unwrap_unguarded",
"result_is_ok",
"result_is_ok_tripwire",
"result_is_err",
"result_is_err_tripwire",
"result_unwrap_or",
"result_unwrap_or_tripwire",
"result_unwrap_unguarded",
];
let Some(report) = verify_realistic(&names) else {
return;
};
for name in [
"option_unwrap_or_fallback",
"option_is_some_true_on_some",
"option_is_some_false_on_none",
"option_is_none_false_on_some",
"option_is_none_true_on_none",
"option_unwrap_guarded",
"option_expect_guarded",
"option_is_some_guards_unwrap",
"option_is_none_guards_unwrap",
"option_arg_unwrap_or",
"result_is_ok",
"result_is_err",
"result_unwrap_or",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
for name in [
"option_unwrap_or_fallback_tripwire",
"option_is_some_true_on_some_tripwire",
"option_is_some_false_on_none_tripwire",
"option_is_none_false_on_some_tripwire",
"option_is_none_true_on_none_tripwire",
"option_arg_unwrap_or_tripwire",
"result_is_ok_tripwire",
"result_is_err_tripwire",
"result_unwrap_or_tripwire",
] {
let o = outcome(&report, name);
assert!(!o.is_verified(), "`{name}` must be refuted, got: {o}");
}
for name in [
"option_unwrap_unguarded",
"option_expect_unguarded",
"option_guard_tripwire",
"option_arg_unwrap_unguarded",
"result_unwrap_unguarded",
] {
let o = outcome(&report, name);
match o {
FnOutcome::Failed { kind, .. } => {
assert!(
kind.contains("panic"),
"`{name}` must fail on a panic obligation, got kind: {kind}"
);
}
other => panic!("`{name}` must fail with a panic, got: {other}"),
}
}
let FnOutcome::Failed { kind, .. } = outcome(&report, "result_unwrap_unguarded") else {
panic!("`result_unwrap_unguarded` must fail on the `Err` panic");
};
assert!(
kind.contains("Err") && !kind.contains("None"),
"the `Result::unwrap` panic must name `Err`, got kind: {kind}"
);
}
#[test]
fn an_enum_return_contract_can_name_the_discriminant_methods() {
let names = [
"enum_ret_is_some",
"enum_ret_is_some_tripwire",
"enum_ret_is_none",
"enum_ret_is_none_tripwire",
"enum_ret_is_ok",
"enum_ret_is_ok_tripwire",
"enum_ret_is_err",
"enum_ret_is_err_tripwire",
"enum_ret_is_ok_or_err",
"enum_ret_is_ok_and_err_tripwire",
"enum_ret_passthrough",
"enum_ret_passthrough_tripwire",
"enum_ret_from_match",
"enum_ret_from_match_tripwire",
"enum_ret_method_on_non_enum",
"enum_arg_is_ok_guarded",
"enum_arg_is_ok_guarded_tripwire",
"enum_arg_is_ok_or_err",
"enum_arg_is_ok_and_err_tripwire",
];
let Some(report) = verify_realistic(&names) else {
return;
};
for name in [
"enum_ret_is_some",
"enum_ret_is_none",
"enum_ret_is_ok",
"enum_ret_is_err",
"enum_ret_is_ok_or_err",
"enum_ret_passthrough",
"enum_ret_from_match",
"enum_arg_is_ok_guarded",
"enum_arg_is_ok_or_err",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
for name in [
"enum_ret_is_some_tripwire",
"enum_ret_is_none_tripwire",
"enum_ret_is_ok_tripwire",
"enum_ret_is_err_tripwire",
"enum_ret_is_ok_and_err_tripwire",
"enum_ret_passthrough_tripwire",
"enum_ret_from_match_tripwire",
"enum_arg_is_ok_guarded_tripwire",
"enum_arg_is_ok_and_err_tripwire",
] {
let o = outcome(&report, name);
assert!(!o.is_verified(), "`{name}` must be refuted, got: {o}");
}
let o = outcome(&report, "enum_ret_method_on_non_enum");
assert!(
matches!(o, FnOutcome::Skipped { .. }),
"`ret.is_ok()` on a non-enum return must be refused, got: {o}"
);
}
#[test]
fn an_enum_return_contract_can_name_a_payload() {
let names = [
"ret_ok_payload",
"ret_ok_payload_tripwire",
"ret_some_payload",
"ret_some_payload_tripwire",
"ret_err_payload",
"ret_err_payload_tripwire",
"ret_payload_guarded_vacuous",
"ret_payload_guarded_vacuous_tripwire",
"ret_user_enum_payload",
"ret_user_enum_payload_tripwire",
"ret_payload_on_non_enum",
"ret_payload_on_unit_variant",
];
let Some(report) = verify_realistic(&names) else {
return;
};
for name in [
"ret_ok_payload",
"ret_some_payload",
"ret_err_payload",
"ret_payload_guarded_vacuous",
"ret_user_enum_payload",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
for name in [
"ret_ok_payload_tripwire",
"ret_some_payload_tripwire",
"ret_err_payload_tripwire",
"ret_payload_guarded_vacuous_tripwire",
"ret_user_enum_payload_tripwire",
] {
assert_refuted(&report, name);
}
for name in ["ret_payload_on_non_enum", "ret_payload_on_unit_variant"] {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Skipped { .. }),
"`{name}` must be refused (no such payload), got: {o}"
);
}
}
#[test]
fn a_parenthesized_comparison_is_a_bool_operand() {
let names = [
"bool_ret_is_comparison",
"bool_ret_is_comparison_tripwire",
"bool_ret_grouped_arithmetic",
"bool_ret_bare",
"bool_ret_bare_tripwire",
"bool_ret_negated",
];
let Some(report) = verify_realistic(&names) else {
return;
};
for name in [
"bool_ret_is_comparison",
"bool_ret_grouped_arithmetic",
"bool_ret_bare",
"bool_ret_negated",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
for name in ["bool_ret_is_comparison_tripwire", "bool_ret_bare_tripwire"] {
assert_refuted(&report, name);
}
}
#[test]
fn payload_summaries_cannot_prove_a_false_claim() {
let names = [
"grouped_payload_conjunction_cannot_prove_this",
"grouped_payload_conjunction_ok",
"ungrouped_payload_conjunction_cannot_prove_this",
"duo_pair_first_field",
"duo_pair_second_field_cannot_prove_this",
"payload_binding_shadow_tripwire",
"negated_payload_comparison",
"negated_payload_comparison_inequality",
"negated_payload_comparison_cannot_prove_this",
"negated_payload_mixed_variant_is_refused",
];
let Some(report) = verify_realistic(&names) else {
return;
};
let o = outcome(&report, "grouped_payload_conjunction_ok");
assert!(o.is_verified(), "`grouped_payload_conjunction_ok` must verify, got: {o}");
let o = outcome(&report, "duo_pair_first_field");
assert!(o.is_verified(), "`duo_pair_first_field` must verify, got: {o}");
for name in [
"grouped_payload_conjunction_cannot_prove_this",
"ungrouped_payload_conjunction_cannot_prove_this",
"duo_pair_second_field_cannot_prove_this",
] {
assert_refuted(&report, name);
}
let o = outcome(&report, "payload_binding_shadow_tripwire");
assert!(
matches!(o, FnOutcome::Skipped { .. }),
"`payload_binding_shadow_tripwire` must be refused, got: {o}"
);
for name in ["negated_payload_comparison", "negated_payload_comparison_inequality"] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
assert_refuted(&report, "negated_payload_comparison_cannot_prove_this");
let o = outcome(&report, "negated_payload_mixed_variant_is_refused");
assert!(
matches!(o, FnOutcome::Skipped { .. }),
"`negated_payload_mixed_variant_is_refused` must be refused, got: {o}"
);
}
#[test]
fn the_try_operator_decides_on_both_paths() {
let names = [
"result_try_ok_value",
"result_try_ok_value_cannot_prove_this",
"result_try_err_propagates",
"result_try_err_propagates_cannot_prove_this",
"result_try_value_used",
"result_try_value_used_cannot_prove_this",
"option_try_some_value",
"option_try_some_value_cannot_prove_this",
"option_try_none_propagates",
"option_try_none_propagates_cannot_prove_this",
"result_try_of_a_known_ok",
"result_try_of_a_known_err",
"result_try_of_a_known_err_cannot_prove_this",
"option_try_of_a_known_none",
"option_try_of_a_known_none_cannot_prove_this",
"result_try_chained",
"result_try_chained_cannot_prove_this",
"result_try_in_either_branch",
"result_try_in_either_branch_cannot_prove_this",
"result_try_widens_the_error",
"result_try_widens_the_error_cannot_prove_this",
];
let Some(report) = verify_realistic(&names) else {
return;
};
for name in [
"result_try_ok_value",
"result_try_err_propagates",
"result_try_value_used",
"option_try_some_value",
"option_try_none_propagates",
"result_try_of_a_known_ok",
"result_try_of_a_known_err",
"option_try_of_a_known_none",
"result_try_chained",
"result_try_in_either_branch",
"result_try_widens_the_error",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
for name in [
"result_try_ok_value_cannot_prove_this",
"result_try_err_propagates_cannot_prove_this",
"result_try_value_used_cannot_prove_this",
"option_try_some_value_cannot_prove_this",
"option_try_none_propagates_cannot_prove_this",
"result_try_of_a_known_err_cannot_prove_this",
"option_try_of_a_known_none_cannot_prove_this",
"result_try_chained_cannot_prove_this",
"result_try_in_either_branch_cannot_prove_this",
"result_try_widens_the_error_cannot_prove_this",
] {
assert_refuted(&report, name);
}
}
#[test]
fn the_option_result_conversions_decide_and_move_the_payload() {
let names = [
"ok_or_some_is_ok",
"ok_or_some_is_ok_tripwire",
"ok_or_none_is_err",
"ok_or_none_is_err_tripwire",
"ok_or_moves_the_payload",
"ok_or_moves_the_payload_tripwire",
"ok_ok_is_some",
"ok_ok_is_some_tripwire",
"ok_err_is_none",
"ok_err_is_none_tripwire",
"ok_moves_the_payload",
"ok_moves_the_payload_tripwire",
"err_err_is_some",
"err_err_is_some_tripwire",
"err_ok_is_none",
"err_ok_is_none_tripwire",
"err_moves_the_payload",
"err_moves_the_payload_tripwire",
];
let Some(report) = verify_realistic(&names) else {
return;
};
for name in [
"ok_or_some_is_ok",
"ok_or_none_is_err",
"ok_or_moves_the_payload",
"ok_ok_is_some",
"ok_err_is_none",
"ok_moves_the_payload",
"err_err_is_some",
"err_ok_is_none",
"err_moves_the_payload",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
for name in [
"ok_or_some_is_ok_tripwire",
"ok_or_none_is_err_tripwire",
"ok_or_moves_the_payload_tripwire",
"ok_ok_is_some_tripwire",
"ok_err_is_none_tripwire",
"ok_moves_the_payload_tripwire",
"err_err_is_some_tripwire",
"err_ok_is_none_tripwire",
"err_moves_the_payload_tripwire",
] {
assert_refuted(&report, name);
}
}
#[test]
fn the_option_result_conversions_handle_constructed_variants_and_grouping() {
let names = [
"constructed_none_ok_or_is_err",
"constructed_none_ok_or_is_err_tripwire",
"constructed_err_ok_is_none",
"constructed_err_ok_is_none_tripwire",
"constructed_ok_err_is_none",
"constructed_ok_err_is_none_tripwire",
"constructed_ok_ok_is_some",
"constructed_ok_ok_is_some_tripwire",
"grouped_enum_predicate",
"grouped_enum_predicate_tripwire",
"negated_enum_predicate",
"negated_enum_predicate_tripwire",
"grouped_enum_predicate_conjunction",
"grouped_enum_predicate_conjunction_tripwire",
"bare_negated_enum_predicate",
"bare_negated_enum_predicate_tripwire",
];
let Some(report) = verify_realistic(&names) else {
return;
};
for name in [
"constructed_none_ok_or_is_err",
"constructed_err_ok_is_none",
"constructed_ok_err_is_none",
"constructed_ok_ok_is_some",
"grouped_enum_predicate",
"negated_enum_predicate",
"grouped_enum_predicate_conjunction",
"bare_negated_enum_predicate",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
for name in [
"constructed_none_ok_or_is_err_tripwire",
"constructed_err_ok_is_none_tripwire",
"constructed_ok_err_is_none_tripwire",
"constructed_ok_ok_is_some_tripwire",
"grouped_enum_predicate_tripwire",
"negated_enum_predicate_tripwire",
"grouped_enum_predicate_conjunction_tripwire",
"bare_negated_enum_predicate_tripwire",
] {
assert_refuted(&report, name);
}
}
#[test]
fn option_or_and_are_total_and_select_the_right_operand() {
let names = [
"or_some_is_the_receiver",
"or_some_is_the_receiver_tripwire",
"or_none_is_the_argument",
"or_none_is_the_argument_tripwire",
"and_some_is_the_argument",
"and_some_is_the_argument_tripwire",
"and_none_is_the_receiver",
"and_none_is_the_receiver_tripwire",
"or_mixed_tag_widths_is_none",
"or_mixed_tag_widths_tripwire",
"or_mixed_tag_widths_none_is_argument",
"and_different_payload_widths",
"and_different_payload_widths_tripwire",
"and_none_receiver_decides",
"constructed_none_or_some",
"constructed_some_or_none",
"constructed_none_or_some_tripwire",
"or_slices_selects_the_receiver",
"or_slices_selects_the_receiver_tripwire",
"and_slices_selects_the_argument",
"and_slices_selects_the_argument_tripwire",
"and_different_width_deref",
"and_different_width_deref_tripwire",
"and_scalar_receiver_ref_argument",
"and_scalar_receiver_ref_argument_tripwire",
"chained_or_selects_the_first",
"chained_or_selects_the_first_cannot_prove_this",
"and_with_a_conditional_argument",
"and_with_a_conditional_argument_cannot_prove_this",
"signed_or_element_is_signed",
"signed_or_element_is_signed_cannot_prove_this",
"signed_or_element_divides_signed",
"signed_or_element_divides_signed_cannot_prove_this",
];
let Some(report) = verify_realistic(&names) else {
return;
};
for name in [
"or_some_is_the_receiver",
"or_none_is_the_argument",
"and_some_is_the_argument",
"and_none_is_the_receiver",
"or_mixed_tag_widths_is_none",
"or_mixed_tag_widths_none_is_argument",
"and_different_payload_widths",
"and_none_receiver_decides",
"constructed_none_or_some",
"constructed_some_or_none",
"or_slices_selects_the_receiver",
"and_slices_selects_the_argument",
"and_different_width_deref",
"and_scalar_receiver_ref_argument",
"chained_or_selects_the_first",
"and_with_a_conditional_argument",
"signed_or_element_is_signed",
"signed_or_element_divides_signed",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
for name in [
"or_some_is_the_receiver_tripwire",
"or_none_is_the_argument_tripwire",
"and_some_is_the_argument_tripwire",
"and_none_is_the_receiver_tripwire",
"or_mixed_tag_widths_tripwire",
"and_different_payload_widths_tripwire",
"constructed_none_or_some_tripwire",
"or_slices_selects_the_receiver_tripwire",
"and_slices_selects_the_argument_tripwire",
"and_different_width_deref_tripwire",
"and_scalar_receiver_ref_argument_tripwire",
"chained_or_selects_the_first_cannot_prove_this",
"and_with_a_conditional_argument_cannot_prove_this",
"signed_or_element_is_signed_cannot_prove_this",
"signed_or_element_divides_signed_cannot_prove_this",
] {
assert_refuted(&report, name);
}
}
#[test]
fn option_copied_and_cloned_copy_the_payload_with_the_tag() {
let names = [
"copied_first_is_the_element",
"copied_first_tripwire",
"copied_get_is_the_element",
"copied_get_tripwire",
"copied_empty_is_none",
"cloned_first_is_the_element",
];
let Some(report) = verify_realistic(&names) else {
return;
};
for name in [
"copied_first_is_the_element",
"copied_get_is_the_element",
"copied_empty_is_none",
"cloned_first_is_the_element",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
for name in ["copied_first_tripwire", "copied_get_tripwire"] {
assert_refuted(&report, name);
}
}
#[test]
fn char_literals_and_ascii_predicates_are_modelled() {
let names = [
"char_as_byte",
"char_ord_of_a",
"char_digit_is_true",
"char_digit_tripwire",
"char_high_digit_tripwire",
"char_high_is_not_digit",
"char_newline_is_whitespace",
"char_emoji_not_alphabetic",
"char_max_is_the_scalar_maximum",
"char_max_is_the_scalar_maximum_cannot_prove_this",
"char_min_is_nul",
];
let Some(report) = verify_realistic(&names) else {
return;
};
for name in [
"char_as_byte",
"char_ord_of_a",
"char_digit_is_true",
"char_high_is_not_digit",
"char_newline_is_whitespace",
"char_emoji_not_alphabetic",
"char_max_is_the_scalar_maximum",
"char_min_is_nul",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
assert_refuted(&report, "char_digit_tripwire");
assert_refuted(&report, "char_high_digit_tripwire");
assert_refuted(&report, "char_max_is_the_scalar_maximum_cannot_prove_this");
}
#[test]
fn slice_last_is_an_element_and_array_last_is_exact() {
let names = [
"slice_last_is_an_element",
"array_last_is_the_last_element",
"slice_last_is_an_element_cannot_prove_this",
"array_last_is_the_last_element_cannot_prove_this",
"slice_last_after_write_is_seen",
"slice_last_after_write_is_seen_cannot_prove_this",
"slice_last_is_kept_when_another_index_is_written",
"slice_last_read_before_a_write_is_not_kept_cannot_prove_this",
];
let Some(report) = verify_realistic(&names) else {
return;
};
for name in [
"slice_last_is_an_element",
"array_last_is_the_last_element",
"slice_last_after_write_is_seen",
"slice_last_is_kept_when_another_index_is_written",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
assert_refuted(&report, "slice_last_is_an_element_cannot_prove_this");
assert_refuted(&report, "array_last_is_the_last_element_cannot_prove_this");
assert_refuted(&report, "slice_last_after_write_is_seen_cannot_prove_this");
assert_refuted(&report, "slice_last_read_before_a_write_is_not_kept_cannot_prove_this");
}
#[test]
fn a_bool_conversion_is_the_zero_extended_bit() {
let names = [
"bool_to_u8_is_zero_or_one",
"bool_to_u8_of_true_is_one",
"bool_to_u8_of_true_is_one_cannot_prove_this",
"bool_to_u32_is_zero_or_one",
];
let Some(report) = verify_realistic(&names) else {
return;
};
for name in [
"bool_to_u8_is_zero_or_one",
"bool_to_u8_of_true_is_one",
"bool_to_u32_is_zero_or_one",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
assert_refuted(&report, "bool_to_u8_of_true_is_one_cannot_prove_this");
}
#[test]
fn a_mutable_bool_reference_postcondition_reads_its_final_value() {
let names = ["set_bool_ref", "a_bool_ref_write_cannot_prove_this", "keep_bool_ref"];
let Some(report) = verify_realistic(&names) else {
return;
};
for name in ["set_bool_ref", "keep_bool_ref"] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
assert_refuted(&report, "a_bool_ref_write_cannot_prove_this");
}
#[test]
fn a_trailing_comment_on_a_variant_keeps_the_layout() {
let Some(report) = verify_realistic(&[
"enum_trailing_comment_keeps_the_layout",
"enum_trailing_comment_tripwire",
]) else {
return;
};
let o = outcome(&report, "enum_trailing_comment_keeps_the_layout");
assert!(
o.is_verified(),
"`enum_trailing_comment_keeps_the_layout` must verify, got: {o}"
);
let t = outcome(&report, "enum_trailing_comment_tripwire");
assert!(!t.is_verified(), "the trailing-comment tripwire must be refuted, got: {t}");
}
#[test]
fn a_symbolic_slice_index_is_modelled_when_both_bounds_hold() {
let Some(report) = verify_realistic(&["slice_symbolic_index"]) else { return };
let o = outcome(&report, "slice_symbolic_index");
assert!(o.is_verified(), "`slice_symbolic_index` must verify, got: {o}");
}
#[test]
fn a_slice_chain_depends_on_the_index() {
let Some(report) = verify_realistic(&["slice_symbolic_index_tripwire"]) else { return };
let o = outcome(&report, "slice_symbolic_index_tripwire");
assert!(
matches!(o, FnOutcome::Failed { .. }),
"`slice_symbolic_index_tripwire` must be refuted (not skipped), got: {o}"
);
}
#[test]
fn a_slice_subscript_missing_either_bound_is_refused() {
let cases = [
("slice_unbounded_length_refused", "`xs.len() <= 64` does not hold"),
("slice_unbounded_index_refused", "`i < xs.len()` does not hold"),
];
for (name, want) in cases {
let Some(report) = verify_realistic(&[name]) else { return };
let o = outcome(&report, name);
match o {
FnOutcome::Skipped { reason } => assert!(
reason.contains(want),
"`{name}`'s refusal must name the missing bound `{want}`, got: {reason}"
),
other => panic!("`{name}` must be skipped, got: {other}"),
}
}
}
#[track_caller]
fn assert_not_dropped(name: &str, src: &str, present: bool, missing: &[String]) {
let has_contract = src.contains("///")
|| ["requires", "ensures", "invariant", "decreases", "variant", "unwind"]
.iter()
.any(|k| src.contains(&format!("{k}:")));
assert!(
present || !has_contract,
"`{name}` was dropped from the report: it has a contract but no outcome, so this test \
would have passed without checking anything (missing: {missing:?})"
);
}
fn verify_src(name: &str, src: &str) -> Option<FnOutcome> {
let rustc = rustc()?;
static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dir = std::env::temp_dir()
.join(format!("verif-{name}-{}-{seq}", std::process::id()));
let _ = std::fs::create_dir_all(&dir);
let file = dir.join("probe.rs");
std::fs::write(&file, src).expect("write probe");
let report = verify::verify_file_with_opts(&rustc, &file, &[], &probe_opts())
.expect("frontend");
let o = report
.outcomes
.into_iter()
.find(|(n, _)| n == name)
.map(|(_, o)| o);
let _ = std::fs::remove_dir_all(&dir);
assert_not_dropped(name, src, o.is_some(), &report.missing);
o
}
#[test]
fn an_in_code_contract_can_name_verif_through_an_extern() {
let rustc = std::env::var("RUSTC")
.ok()
.filter(|s| !s.is_empty())
.unwrap_or_else(|| "rustc".to_string());
if std::process::Command::new(&rustc)
.arg("--version")
.output()
.map(|o| !o.status.success())
.unwrap_or(true)
{
return;
}
let exe = std::env::current_exe().expect("current exe");
let profile = exe
.ancestors()
.find(|a| a.file_name().is_some_and(|n| n == "debug" || n == "release"))
.expect("a debug or release profile directory above the test binary");
fn walk(dir: &std::path::Path, depth: u32, out: &mut Vec<std::path::PathBuf>) {
if depth == 0 {
return;
}
let Ok(entries) = std::fs::read_dir(dir) else { return };
for e in entries.flatten() {
let p = e.path();
if p.is_dir() {
walk(&p, depth - 1, out);
} else if p
.file_name()
.and_then(|n| n.to_str())
.is_some_and(|n| n.starts_with("libverif") && n.ends_with(".rlib"))
{
out.push(p);
}
}
}
let mut rlibs = Vec::new();
walk(profile, 6, &mut rlibs);
let mut search: Vec<std::path::PathBuf> = rlibs
.iter()
.filter_map(|p| p.parent().map(|d| d.to_path_buf()))
.collect();
search.sort();
search.dedup();
let mut verif_rlibs: Vec<std::path::PathBuf> = rlibs
.into_iter()
.filter(|p| {
p.file_name()
.and_then(|n| n.to_str())
.is_some_and(|n| n.starts_with("libverif-"))
})
.collect();
verif_rlibs.sort();
verif_rlibs.dedup();
verif_rlibs.sort_by_key(|p| {
std::cmp::Reverse(std::fs::metadata(p).and_then(|m| m.modified()).ok())
});
assert!(
!verif_rlibs.is_empty(),
"an rlib of `verif` must exist under {}",
profile.display()
);
let src = "use verif::spec;\n\nspec! {\n requires: n <= 200,\n ensures: ret == n + 1,\n}\npub fn inc(n: u8) -> u8 { n + 1 }\n";
static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!("verif-extern-e2e-{}-{seq}", std::process::id()));
let _ = std::fs::create_dir_all(&dir);
let file = dir.join("probe.rs");
std::fs::write(&file, src).expect("write probe");
let bare = verify::verify_file_with_opts(&rustc, &file, &[], &probe_opts());
assert!(
bare.is_err(),
"an import of `verif` must fail without an extern, got: {:?}",
bare.map(|r| r.outcomes.len())
);
let mut verified = false;
let mut last_err = String::new();
for rlib in &verif_rlibs {
let mut opts = probe_opts();
opts.externs = vec![("verif".to_string(), rlib.clone())];
opts.search_paths = search.clone();
match verify::verify_file_with_opts(&rustc, &file, &[], &opts) {
Ok(report) => {
verified = report
.outcomes
.iter()
.find(|(n, _)| n == "inc")
.is_some_and(|(_, o)| o.is_verified());
if verified {
break;
}
last_err = format!("{:?}", report.outcomes);
}
Err(e) => last_err = e,
}
}
let _ = std::fs::remove_dir_all(&dir);
assert!(
verified,
"with a working extern the in-code contract must verify; last error: {last_err}"
);
}
fn probe_opts() -> verify::MirOptions {
verify::MirOptions { edition: Some(verify::Edition::Rust2024), ..Default::default() }
}
fn verify_all_outcomes(src: &str) -> (Vec<(String, FnOutcome)>, Vec<String>) {
let rustc = rustc().expect("a toolchain to dump MIR with");
static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!("verif-all-{}-{seq}", std::process::id()));
let _ = std::fs::create_dir_all(&dir);
let file = dir.join("probe.rs");
std::fs::write(&file, src).expect("write probe");
let report = verify::verify_file_with_opts(&rustc, &file, &[], &probe_opts()).expect("frontend");
let _ = std::fs::remove_dir_all(&dir);
(report.outcomes, report.missing)
}
#[test]
#[should_panic(expected = "was dropped")]
fn a_dropped_contracted_function_fails_even_when_missing_names_it() {
assert_not_dropped("ghost", "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n ensures: true,\n}\npub fn ghost() {}", false, &["ghost".to_string()]);
}
#[test]
fn a_present_function_passes_the_drop_guard() {
assert_not_dropped("f", "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n ensures: true,\n}\npub fn f() {}", true, &[]);
assert_not_dropped("f", "pub fn f() {}", false, &[]);
}
#[test]
fn an_element_write_reaches_the_symbolic_chain() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
spec! {
requires: i < 4 && i == 0,
ensures: ret == a[i],
}
pub fn written_then_symbolic(mut a: [u8; 4], i: usize) -> u8 {
a[0] = 0;
a[i]
}
"#;
let Some(o) = verify_src("written_then_symbolic", src) else { return };
assert!(
matches!(o, FnOutcome::Failed { .. }),
"a write must not leave a stale element readable by the chain; got: {o}"
);
}
#[test]
fn an_element_write_through_a_mutable_reference_reaches_the_chain() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
spec! {
requires: i < 4 && i == 0,
ensures: ret == a[i],
}
pub fn ref_written_then_symbolic(a: &mut [u8; 4], i: usize) -> u8 {
a[0] = 0;
a[i]
}
"#;
let Some(o) = verify_src("ref_written_then_symbolic", src) else { return };
assert!(
matches!(o, FnOutcome::Failed { .. }),
"a reborrowed element write must reach the chain too; got: {o}"
);
}
#[test]
fn a_vec_length_is_tracked_through_new_push_and_len() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
spec! {
requires: true,
ensures: ret == 1,
}
pub fn make_ok(n: u8) -> usize { let mut v = Vec::new(); v.push(n); v.len() }
spec! {
requires: true,
ensures: ret == 2,
}
pub fn make_bad(n: u8) -> usize { let mut v = Vec::new(); v.push(n); v.len() }
spec! {
requires: true,
ensures: ret == 2,
}
pub fn two_ok(n: u8) -> usize { let mut v = Vec::new(); v.push(n); v.push(n); v.len() }
spec! {
requires: true,
ensures: ret == 1,
}
pub fn two_bad(n: u8) -> usize { let mut v = Vec::new(); v.push(n); v.push(n); v.len() }
spec! {
requires: true,
ensures: ret == 0,
}
pub fn empty_ok() -> usize { Vec::<u8>::new().len() }
spec! {
requires: true,
ensures: ret == 3,
}
pub fn empty_bad() -> usize { Vec::<u8>::new().len() }
spec! {
requires: true,
ensures: ret == 1,
}
pub fn helper_ok(n: u8) -> usize { let mut v = Vec::new(); add(&mut v, n); v.len() }
spec! {
requires: true,
ensures: ret == 0,
}
pub fn helper_bad(n: u8) -> usize { let mut v = Vec::new(); add(&mut v, n); v.len() }
fn add(v: &mut Vec<u8>, x: u8) { v.push(x); }
spec! {
requires: true,
ensures: ret == 0,
}
pub fn arg_len_refused(v: &Vec<u8>) -> usize { v.len() }
spec! {
requires: true,
ensures: ret == 1,
}
pub fn is_empty_new_ok() -> u8 { Vec::<u8>::new().is_empty() as u8 }
spec! {
requires: true,
ensures: ret == 0,
}
pub fn is_empty_new_bad() -> u8 { Vec::<u8>::new().is_empty() as u8 }
spec! {
requires: true,
ensures: ret == 0,
}
pub fn not_empty_after_push_ok() -> u8 { let mut v = Vec::<u8>::new(); v.push(1); v.is_empty() as u8 }
spec! {
requires: true,
ensures: ret == 1,
}
pub fn not_empty_after_push_bad() -> u8 { let mut v = Vec::<u8>::new(); v.push(1); v.is_empty() as u8 }
spec! {
requires: true,
ensures: ret == 0,
}
pub fn pop_then_len_ok() -> usize { let mut v = Vec::<u8>::new(); v.push(1); v.pop(); v.len() }
spec! {
requires: true,
ensures: ret == 1,
}
pub fn pop_then_len_bad() -> usize { let mut v = Vec::<u8>::new(); v.push(1); v.pop(); v.len() }
spec! {
requires: true,
ensures: ret == 1,
}
pub fn pop_empty_is_none_ok() -> u8 { let mut v = Vec::<u8>::new(); v.pop().is_none() as u8 }
spec! {
requires: true,
ensures: ret == 0,
}
pub fn pop_empty_is_none_bad() -> u8 { let mut v = Vec::<u8>::new(); v.pop().is_none() as u8 }
spec! {
requires: true,
ensures: ret == 1,
}
pub fn pop_nonempty_is_some_ok() -> u8 { let mut v = Vec::<u8>::new(); v.push(9); v.pop().is_some() as u8 }
spec! {
requires: true,
ensures: ret == 0,
}
pub fn pop_nonempty_is_some_bad() -> u8 { let mut v = Vec::<u8>::new(); v.push(9); v.pop().is_some() as u8 }
"#;
for name in [
"make_ok",
"two_ok",
"empty_ok",
"helper_ok",
"is_empty_new_ok",
"not_empty_after_push_ok",
"pop_then_len_ok",
"pop_empty_is_none_ok",
"pop_nonempty_is_some_ok",
] {
let Some(o) = verify_src(name, src) else { return };
assert!(o.is_verified(), "`{name}` must verify; got: {o}");
}
for name in [
"make_bad",
"two_bad",
"empty_bad",
"helper_bad",
"is_empty_new_bad",
"not_empty_after_push_bad",
"pop_then_len_bad",
"pop_empty_is_none_bad",
"pop_nonempty_is_some_bad",
] {
let Some(o) = verify_src(name, src) else { return };
assert!(
matches!(o, FnOutcome::Failed { .. }),
"`{name}` claims a length the body never produces and must be refuted, \
not proved; got: {o}"
);
}
let Some(o) = verify_src("arg_len_refused", src) else { return };
assert!(
!o.is_verified(),
"a `Vec` argument's length is unmodelled and must not verify; got: {o}"
);
}
#[test]
fn a_vec_length_model_does_not_leak_across_a_drop_havoc_or_move() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
mod m {
pub struct Vec<T>(pub T);
impl<T> Drop for Vec<T> {
fn drop(&mut self) { panic!() }
}
}
spec! {
requires: true,
ensures: true,
}
/// A user `Vec` whose destructor always panics: `drop` runs it, so this must not
/// be `verified`. The bare-name model treated `m::Vec<u8>` as glue-free.
pub fn user_vec_drop_panics() { let _x = m::Vec(0u8); }
spec! {
requires: true,
invariant: i <= 3,
ensures: ret == 0,
}
/// The loop's entry length must be havoced at the header. A model that kept it
/// reads `0` at the exit and proves this; the body really returns `3`.
pub fn loop_push_cannot_prove_this() -> usize {
let mut v = Vec::<u8>::new();
let mut i = 0u8;
while i < 3 { v.push(1); i += 1; }
v.len()
}
spec! {
requires: true,
invariant: i <= 3,
ensures: ret == 3,
}
/// The control: the same loop, but the postcondition is about the *counter*,
/// which the invariant does relate (`i <= 3` and the exit guard `i >= 3` give
/// `i == 3`). Havocing the vector's length must not break this -- a model that
/// refused every `Vec`-carrying loop would pass the twin above while checking
/// nothing.
pub fn loop_counter_ok() -> u8 {
let mut v = Vec::<u8>::new();
let mut i = 0u8;
while i < 3 { v.push(1); i += 1; }
i
}
spec! {
requires: true,
ensures: ret == 1,
}
/// A move (`let w = v`) must carry the tracked length to the destination.
pub fn move_ok(n: u8) -> usize { let mut v = Vec::new(); v.push(n); let w = v; w.len() }
spec! {
requires: true,
ensures: ret == 0,
}
/// The false twin: a model that dropped the length on the move reads a receiver
/// with no length and refuses; one that kept the *source* length and read it
/// through the wrong local would prove this.
pub fn move_bad(n: u8) -> usize { let mut v = Vec::new(); v.push(n); let w = v; w.len() }
spec! {
requires: true,
ensures: ret == 0,
}
/// A returned vector must carry its length to the caller's destination.
pub fn mk() -> Vec<u8> { Vec::new() }
spec! {
requires: true,
ensures: ret == 0,
}
pub fn returned_ok() -> usize { let v = mk(); v.len() }
"#;
let Some(o) = verify_src("user_vec_drop_panics", src) else { return };
match o {
FnOutcome::Incomplete { .. } => {}
other => panic!(
"a user `Vec` whose `Drop` panics must be refused as `Incomplete` \
(the destructor's `panic!` is not modelled as a value), got: {other} -- \
a `verified` here is a false proof and a `Failed` would be a spurious \
refutation of `ensures: true`"
),
}
let Some(o) = verify_src("loop_push_cannot_prove_this", src) else { return };
match o {
FnOutcome::Failed { kind, .. } => assert!(
kind.contains("postcondition"),
"the loop twin must fail on its postcondition; got `{kind}`"
),
other => panic!(
"the loop entry length must be havoced, so `ret == 0` for a body \
returning 3 must be refuted; got: {other}"
),
}
let Some(o) = verify_src("loop_counter_ok", src) else { return };
assert!(
o.is_verified(),
"a `Vec`-carrying loop with a counter postcondition must still verify; got: {o}"
);
let Some(o) = verify_src("move_ok", src) else { return };
assert!(o.is_verified(), "a moved vector keeps its length; got: {o}");
let Some(o) = verify_src("move_bad", src) else { return };
assert!(
matches!(o, FnOutcome::Failed { .. }),
"the move twin claims `0` for a vector of length 1 and must be refuted; got: {o}"
);
let Some(o) = verify_src("returned_ok", src) else { return };
assert!(o.is_verified(), "a returned vector keeps its length; got: {o}");
}
#[test]
fn a_user_vec_method_is_answered_by_its_own_body() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
pub struct Vec<T>(pub T);
impl Vec<u8> {
pub fn new() -> Self { Vec(0) }
pub fn len(&self) -> usize { 7 }
}
spec! {
requires: true,
ensures: ret == 7,
}
/// The user body returns 7, so this verifies -- the model's `0` would refute it.
pub fn body_wins() -> usize { let v = Vec::new(); v.len() }
spec! {
requires: true,
ensures: ret == 0,
}
/// The twin: the container model would answer `0` and prove this, so a refutation
/// is the evidence the user body was used.
pub fn model_would_say_zero() -> usize { let v = Vec::new(); v.len() }
"#;
let Some(o) = verify_src("body_wins", src) else { return };
assert!(
o.is_verified(),
"a user `Vec` method must be answered by its own body; got: {o}"
);
let Some(o) = verify_src("model_would_say_zero", src) else { return };
assert!(
matches!(o, FnOutcome::Failed { .. }),
"the container model must not answer a user `Vec` call, so `ret == 0` must be \
refuted; got: {o}"
);
}
#[test]
fn a_str_length_is_a_symbolic_input() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
spec! {
requires: true,
ensures: ret <= s.len(),
}
pub fn len_bound(s: &str) -> usize { s.len() }
spec! {
requires: s.len() == 3,
ensures: ret == 3,
}
/// The length is pinned by the precondition, so the body's read is that value.
pub fn pinned_len(s: &str) -> usize { s.len() }
spec! {
requires: true,
ensures: ret == 4,
}
/// The false twin: an unbounded `&str` length is not 4.
pub fn wrong_len_cannot_prove_this(s: &str) -> usize { s.len() }
spec! {
requires: s.len() == 0,
ensures: ret,
}
/// `is_empty` reads the same variable, so it agrees with `len`.
pub fn empty_is_empty(s: &str) -> bool { s.is_empty() }
"#;
for name in ["len_bound", "pinned_len", "empty_is_empty"] {
let Some(o) = verify_src(name, src) else { return };
assert!(o.is_verified(), "`{name}` must verify; got: {o}");
}
let Some(o) = verify_src("wrong_len_cannot_prove_this", src) else { return };
assert!(
matches!(o, FnOutcome::Failed { .. }),
"an unbounded `&str` length must not be provable as `4`; got: {o}"
);
}
#[test]
fn option_unwrap_or_default_is_the_payload_or_zero() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
spec! {
requires: true,
ensures: ret <= 255,
}
pub fn or_zero(x: Option<u8>) -> u8 { x.unwrap_or_default() }
spec! {
requires: x.is_none(),
ensures: ret == 0,
}
pub fn none_is_zero(x: Option<u8>) -> u8 { x.unwrap_or_default() }
spec! {
requires: true,
ensures: ret == 7,
}
pub fn cannot_prove_this(x: Option<u8>) -> u8 { x.unwrap_or_default() }
"#;
for name in ["or_zero", "none_is_zero"] {
let Some(o) = verify_src(name, src) else { return };
assert!(o.is_verified(), "`{name}` must verify; got: {o}");
}
let Some(o) = verify_src("cannot_prove_this", src) else { return };
assert!(
matches!(o, FnOutcome::Failed { .. }),
"`unwrap_or_default` must not be provable as a fixed `7`; got: {o}"
);
}
#[test]
fn a_user_type_named_str_is_not_the_primitive_str() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
pub struct str { pub value: u8 }
spec! {
requires: s.value == 3,
ensures: ret == 3,
}
pub fn read(s: &str) -> u8 { s.value }
spec! {
requires: true,
ensures: ret == 3,
}
pub fn read_cannot_prove_this(s: &str) -> u8 { s.value }
"#;
let Some(o) = verify_src("read", src) else { return };
assert!(
o.is_verified(),
"a field of a user `str` must resolve; got: {o}"
);
let Some(o) = verify_src("read_cannot_prove_this", src) else { return };
assert!(
matches!(o, FnOutcome::Failed { .. }),
"the user `str`'s field is an input, so a fixed value must be refuted; got: {o}"
);
let prim = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
spec! {
requires: s.len() == 3,
ensures: ret == 3,
}
pub fn len_is_symbolic(s: &str) -> usize { s.len() }
spec! {
requires: true,
ensures: ret == 4,
}
pub fn wrong_len_cannot_prove_this(s: &str) -> usize { s.len() }
"#;
let Some(o) = verify_src("len_is_symbolic", prim) else { return };
assert!(o.is_verified(), "the primitive `str` length must resolve; got: {o}");
let Some(o) = verify_src("wrong_len_cannot_prove_this", prim) else { return };
assert!(
matches!(o, FnOutcome::Failed { .. }),
"an unpinned `str` length must not be provable as `4`; got: {o}"
);
}
#[test]
fn a_slice_element_write_reaches_the_store_the_read_consults() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
spec! {
requires: s.len() > 0,
ensures: ret == v,
}
pub fn slice_written_then_read(s: &mut [u8], v: u8) -> u8 {
s[0] = v;
s[0]
}
spec! {
requires: s.len() > 0,
ensures: ret == s[0],
}
pub fn slice_written_then_read_tripwire(s: &mut [u8], v: u8) -> u8 {
s[0] = v;
s[0]
}
"#;
let Some(o) = verify_src("slice_written_then_read", src) else { return };
assert!(
o.is_verified(),
"a write then a read of the same slice index returns what was written; got: {o}"
);
let Some(o) = verify_src("slice_written_then_read_tripwire", src) else { return };
assert!(
matches!(o, FnOutcome::Failed { .. }),
"the pre-write element must not stay readable after a slice write; got: {o}"
);
}
#[test]
fn a_slice_element_write_reaches_the_symbolic_chain() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
spec! {
requires: i < s.len() && s.len() <= 64 && i == 0,
ensures: ret == s[i],
}
pub fn slice_written_then_symbolic(s: &mut [u8], i: usize) -> u8 {
s[0] = 0;
s[i]
}
"#;
let Some(o) = verify_src("slice_written_then_symbolic", src) else { return };
assert!(
matches!(o, FnOutcome::Failed { .. }),
"a slice write must not leave a stale element readable by the chain; got: {o}"
);
}
#[test]
fn slice_first_and_get_reach_the_slices_own_element() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
spec! {
requires: xs.len() > 0 && xs[0] == 5,
ensures: ret == 5,
}
pub fn first_reads_the_element(xs: &[u8]) -> u8 {
*xs.first().unwrap()
}
spec! {
requires: xs.len() > 0 && xs[0] == 5,
ensures: ret == 6,
}
pub fn first_wrong_element_cannot_prove_this(xs: &[u8]) -> u8 {
*xs.first().unwrap()
}
spec! {
requires: xs.len() == 0,
ensures: ret,
}
pub fn first_is_none_when_empty(xs: &[u8]) -> bool {
xs.first().is_none()
}
spec! {
requires: xs.len() > 1 && xs[1] == 7,
ensures: ret == 7,
}
pub fn get_reads_the_indexed_element(xs: &[u8]) -> u8 {
*xs.get(1).unwrap()
}
spec! {
requires: xs.len() > 1 && xs[1] == 7,
ensures: ret == 8,
}
pub fn get_wrong_element_cannot_prove_this(xs: &[u8]) -> u8 {
*xs.get(1).unwrap()
}
spec! {
requires: xs.len() > 0,
ensures: ret == 7,
}
pub fn get_out_of_range_unwrap_panics(xs: &[u8]) -> u8 {
*xs.get(1).unwrap()
}
spec! {
requires: xs.len() > 0 && xs[0] == 5,
ensures: ret == 5,
}
pub fn first_match_reads_the_element(xs: &[u8]) -> u8 {
match xs.first() { Some(v) => *v, None => 0 }
}
spec! {
requires: xs.len() > 0 && xs[0] == 5,
ensures: ret == 6,
}
pub fn first_match_tripwire(xs: &[u8]) -> u8 {
match xs.first() { Some(v) => *v, None => 0 }
}
spec! {
requires: xs.len() == 0,
ensures: ret == 0,
}
pub fn first_match_empty_takes_none(xs: &[u8]) -> u8 {
match xs.first() { Some(v) => *v, None => 0 }
}
spec! {
requires: i < xs.len() && xs.len() <= 64,
ensures: true,
}
pub fn get_symbolic_index_is_refused(xs: &[u8], i: usize) -> u8 {
*xs.get(i).unwrap()
}
"#;
let Some(o) = verify_src("first_reads_the_element", src) else { return };
assert!(
o.is_verified(),
"`*xs.first().unwrap()` is `xs[0]`, so the true contract must verify; got: {o}"
);
let Some(o) = verify_src("first_wrong_element_cannot_prove_this", src) else { return };
assert!(
matches!(o, FnOutcome::Failed { .. }),
"the payload is the slice's own element, so a claim about a different value \
must be refuted, not proved; got: {o}"
);
let Some(o) = verify_src("first_is_none_when_empty", src) else { return };
assert!(
o.is_verified(),
"`first` is `None` exactly when the slice is empty; got: {o}"
);
let Some(o) = verify_src("get_reads_the_indexed_element", src) else { return };
assert!(
o.is_verified(),
"`*xs.get(1).unwrap()` is `xs[1]`, so the true contract must verify; got: {o}"
);
let Some(o) = verify_src("get_wrong_element_cannot_prove_this", src) else { return };
assert!(
matches!(o, FnOutcome::Failed { .. }),
"`get`'s payload is the indexed element, so a claim about another value must \
be refuted; got: {o}"
);
let Some(o) = verify_src("get_out_of_range_unwrap_panics", src) else { return };
assert!(
matches!(&o, FnOutcome::Failed { kind, .. } if kind.starts_with("panic")),
"`get(1)` past the end is `None`, so `unwrap` panics -- a real obligation, not \
an assumed `Some`; got: {o}"
);
let Some(o) = verify_src("first_match_reads_the_element", src) else { return };
assert!(
o.is_verified(),
"a `match` on `first()` names the same element `unwrap` does; got: {o}"
);
let Some(o) = verify_src("first_match_tripwire", src) else { return };
assert!(
matches!(o, FnOutcome::Failed { .. }),
"the `match` payload is the slice's element, so a claim about another value \
must be refuted; got: {o}"
);
let Some(o) = verify_src("first_match_empty_takes_none", src) else { return };
assert!(
o.is_verified(),
"an empty slice takes the `None` arm, which returns the constant; got: {o}"
);
let Some(o) = verify_src("get_symbolic_index_is_refused", src) else { return };
assert!(
!o.is_verified()
&& matches!(&o, FnOutcome::Incomplete { .. } | FnOutcome::Skipped { .. }),
"`xs.get(i)` for a symbolic `i` must be refused, not modelled; got: {o}"
);
}
#[test]
fn a_generic_slices_length_is_modelled_but_its_element_is_not() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
spec! {
requires: true,
ensures: ret == v.len(),
}
pub fn len_of<T: Copy>(v: &[T]) -> usize {
v.len()
}
spec! {
requires: true,
ensures: ret == (v.len() == 0),
}
pub fn empty_of<T: Copy>(v: &[T]) -> bool {
v.is_empty()
}
spec! {
requires: true,
ensures: true,
}
pub fn first_or_of<T: Copy>(v: &[T], d: T) -> T {
if v.is_empty() { d } else { v[0] }
}
spec! {
requires: true,
ensures: ret == 0,
}
pub fn len_is_zero_cannot_prove_this<T: Copy>(v: &[T]) -> usize {
v.len()
}
spec! {
requires: true,
ensures: ret == d,
}
pub fn element_cannot_prove_this<T: Copy>(v: &[T], d: T) -> T {
if v.is_empty() { d } else { v[0] }
}
"#;
let Some(o) = verify_src("len_of", src) else { return };
assert!(
o.is_verified(),
"`v.len()` on a `&[T]` reads only the length, which is modelled; got: {o}"
);
let Some(o) = verify_src("empty_of", src) else { return };
assert!(
o.is_verified(),
"`v.is_empty()` is `len == 0`, decided by the length alone; got: {o}"
);
let Some(o) = verify_src("first_or_of", src) else { return };
assert!(
o.is_verified(),
"`first_or` is guarded by `is_empty`, which the length decides, so the \
bounds check on `v[0]` is discharged; got: {o}"
);
let Some(o) = verify_src("len_is_zero_cannot_prove_this", src) else { return };
assert!(
matches!(o, FnOutcome::Failed { .. }),
"`v.len() == 0` is false for a non-empty slice, so this must be refuted \
(a verified verdict would mean the length was folded to the constant 0); \
got: {o}"
);
let Some(o) = verify_src("element_cannot_prove_this", src) else { return };
assert!(
!o.is_verified(),
"a generic slice's element has no width, so `ret == d` must never be \
reported verified; got: {o}"
);
}
#[test]
fn a_whole_struct_assignment_invalidates_its_fields() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
pub struct B { pub lo: u8 }
spec! {
requires: true,
ensures: ret == c.lo,
}
pub fn reassigned_then_field(mut c: B, d: B) -> u8 {
c = d;
c.lo
}
"#;
let Some(o) = verify_src("reassigned_then_field", src) else { return };
assert!(
!o.is_verified(),
"a reassigned struct's field binding is stale and must not prove a contract; got: {o}"
);
}
#[test]
fn a_one_line_struct_does_not_swallow_the_functions_after_it() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
pub struct B { pub lo: u8 }
spec! {
requires: true,
ensures: ret == 0,
}
pub fn after_inline_struct(x: u8) -> u8 {
0
}
"#;
let Some(o) = verify_src("after_inline_struct", src) else { return };
assert!(o.is_verified(), "the function must still be read and decided; got: {o}");
}
#[test]
fn a_generated_binding_cannot_shadow_an_argument() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
spec! {
requires: i < 4,
ensures: ret == a__chain,
}
pub fn shadow_probe(a: [u8; 4], i: usize, a__chain: u8) -> u8 {
a[i]
}
"#;
let Some(o) = verify_src("shadow_probe", src) else { return };
assert!(
!o.is_verified(),
"`a__chain` is a real argument and must not be replaced by the generated binding; got: {o}"
);
}
#[test]
fn a_generated_length_binding_cannot_shadow_an_argument() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
spec! {
requires: a.len() == 4,
ensures: ret == a__len,
}
pub fn shadow_len_probe(a: [u8; 4], a__len: usize) -> usize {
a.len()
}
"#;
let Some(o) = verify_src("shadow_len_probe", src) else { return };
assert!(
!o.is_verified(),
"`a__len` is a real argument and must not be replaced by the generated length; got: {o}"
);
}
#[test]
fn a_false_symbolic_index_postcondition_is_caught() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
spec! {
requires: i < 4,
ensures: ret <= 9,
}
pub fn chain_must_be_read(a: [u8; 4], i: usize) -> u8 {
a[i]
}
"#;
let Some(rustc) = rustc() else { return };
let dir = std::env::temp_dir().join(format!("verif-chain-{}", std::process::id()));
let _ = std::fs::create_dir_all(&dir);
let file = dir.join("chain.rs");
std::fs::write(&file, src).expect("write probe");
let report = verify::verify_file_with_opts(&rustc, &file, &[], &probe_opts()).expect("frontend");
let o = outcome(&report, "chain_must_be_read");
match o {
FnOutcome::Failed { detail, .. } => assert!(
!detail.is_empty(),
"a failed symbolic-index obligation must carry a counterexample"
),
other => panic!("`chain_must_be_read` must FAIL (ret <= 9 is false), got: {other}"),
}
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn an_enum_match_is_a_switch_on_a_symbolic_tag() {
let Some(report) = verify_realistic(&["enum_match_is_bounded"]) else { return };
let o = outcome(&report, "enum_match_is_bounded");
assert!(o.is_verified(), "`enum_match_is_bounded` must verify, got: {o}");
}
#[test]
fn an_enum_payload_is_read_through_the_downcast() {
let Some(report) = verify_realistic(&["enum_payload_reads_through"]) else { return };
let o = outcome(&report, "enum_payload_reads_through");
assert!(o.is_verified(), "`enum_payload_reads_through` must verify, got: {o}");
}
#[test]
fn a_match_guard_reads_its_payload_through_a_borrow() {
let Some(report) = verify_realistic(&["guarded_match_reads_its_payload"]) else { return };
let o = outcome(&report, "guarded_match_reads_its_payload");
assert!(o.is_verified(), "`guarded_match_reads_its_payload` must verify, got: {o}");
let Some(report) = verify_realistic(&["guarded_match_tripwire"]) else { return };
let t = outcome(&report, "guarded_match_tripwire");
match t {
FnOutcome::Failed { kind, .. } => assert_eq!(kind, "postcondition"),
other => panic!("`guarded_match_tripwire` must be refuted, got: {other}"),
}
}
#[test]
fn a_locally_constructed_variant_has_a_known_tag() {
let Some(report) = verify_realistic(&["enum_constructed_locally"]) else { return };
let o = outcome(&report, "enum_constructed_locally");
assert!(o.is_verified(), "`enum_constructed_locally` must verify, got: {o}");
}
#[test]
fn a_constructed_variants_payload_is_read_through_the_downcast() {
let Some(report) = verify_realistic(&["enum_constructed_payload_reads_through"]) else { return };
let o = outcome(&report, "enum_constructed_payload_reads_through");
assert!(o.is_verified(), "`enum_constructed_payload_reads_through` must verify, got: {o}");
}
#[test]
fn a_unit_variant_has_no_payload_to_name() {
let Some(report) = verify_realistic(&["enum_payload_tripwire"]) else { return };
let o = outcome(&report, "enum_payload_tripwire");
assert!(
!o.is_verified(),
"`enum_payload_tripwire` names a unit variant's payload and must be refused, got: {o}"
);
}
#[test]
fn count_ones_is_modelled_and_widens_its_result() {
let Some(report) = verify_realistic(&[
"popcount_of_nonzero",
"popcount_bounded_by_width",
]) else {
return;
};
for name in ["popcount_of_nonzero", "popcount_bounded_by_width"] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
}
#[test]
fn the_count_ones_tripwires_are_refuted_not_skipped() {
let Some(report) = verify_realistic(&[
"popcount_of_nonzero_tripwire",
"popcount_bounded_by_width_tripwire",
]) else {
return;
};
for name in ["popcount_of_nonzero_tripwire", "popcount_bounded_by_width_tripwire"] {
let o = outcome(&report, name);
let FnOutcome::Failed { kind, .. } = o else {
panic!("`{name}` must FAIL: a `Skipped` means `count_ones` is not modelled, got: {o}");
};
assert_eq!(kind, "postcondition", "`{name}` got: {o}");
}
}
#[test]
fn wrapping_abs_is_modelled_unary_and_signed() {
let Some(report) = verify_realistic(&["abs_never_below_operand"]) else { return };
let o = outcome(&report, "abs_never_below_operand");
assert!(o.is_verified(), "`abs_never_below_operand` must verify, got: {o}");
let Some(report) = verify_realistic(&["abs_never_below_operand_tripwire"]) else { return };
let o = outcome(&report, "abs_never_below_operand_tripwire");
let FnOutcome::Failed { kind, detail } = o else {
panic!("`abs_never_below_operand_tripwire` must FAIL, got: {o}");
};
assert_eq!(kind, "postcondition", "got: {o}");
assert!(
detail.contains("= 0"),
"the witness should be x == 0 (where abs is the identity), got: {detail}"
);
}
#[test]
fn the_zero_counts_are_modelled() {
let Some(report) = verify_realistic(&[
"leading_zeros_of_a_small_value",
"trailing_zeros_of_a_top_bit_value",
]) else {
return;
};
for name in ["leading_zeros_of_a_small_value", "trailing_zeros_of_a_top_bit_value"] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
let Some(report) = verify_realistic(&[
"leading_zeros_of_a_small_value_tripwire",
"trailing_zeros_of_a_top_bit_value_tripwire",
]) else {
return;
};
for name in [
"leading_zeros_of_a_small_value_tripwire",
"trailing_zeros_of_a_top_bit_value_tripwire",
] {
let o = outcome(&report, name);
let FnOutcome::Failed { kind, .. } = o else {
panic!("`{name}` must FAIL: a `Skipped` means the name is not modelled, got: {o}");
};
assert_eq!(kind, "postcondition", "`{name}` got: {o}");
}
let o = outcome(&report, "leading_zeros_of_a_small_value_tripwire");
let FnOutcome::Failed { detail, .. } = o else { panic!("got: {o}") };
assert!(
detail.contains("= 0"),
"the `leading_zeros` witness should be x == 0, got: {detail}"
);
}
#[test]
fn the_pow_families_are_modelled_with_a_wide_exponent() {
let Some(report) = verify_realistic(&[
"wrapping_pow_two_to_seven_is_128",
"checked_pow_two_to_seven_is_some_128",
"saturating_pow_three_to_five_is_243",
"overflowing_pow_two_to_seven_did_not_overflow",
"wrapping_pow_negative_two_to_seven_is_min",
"saturating_pow_negative_base_clamps_to_min",
"wrapping_pow_zero_exponent_is_one",
]) else {
return;
};
for name in [
"wrapping_pow_two_to_seven_is_128",
"checked_pow_two_to_seven_is_some_128",
"saturating_pow_three_to_five_is_243",
"overflowing_pow_two_to_seven_did_not_overflow",
"wrapping_pow_negative_two_to_seven_is_min",
"saturating_pow_negative_base_clamps_to_min",
"wrapping_pow_zero_exponent_is_one",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
let Some(report) = verify_realistic(&[
"wrapping_pow_two_to_eight_is_256_tripwire",
"checked_pow_two_to_eight_is_none_tripwire",
"saturating_pow_three_to_six_clamps_tripwire",
"overflowing_pow_two_to_eight_flag_tripwire",
"wrapping_pow_negative_two_to_eight_wraps_tripwire",
"saturating_pow_negative_base_to_max_tripwire",
"wrapping_pow_one_exponent_is_one_tripwire",
]) else {
return;
};
for name in [
"wrapping_pow_two_to_eight_is_256_tripwire",
"checked_pow_two_to_eight_is_none_tripwire",
"saturating_pow_three_to_six_clamps_tripwire",
"overflowing_pow_two_to_eight_flag_tripwire",
"wrapping_pow_negative_two_to_eight_wraps_tripwire",
"saturating_pow_negative_base_to_max_tripwire",
"wrapping_pow_one_exponent_is_one_tripwire",
] {
let o = outcome(&report, name);
let FnOutcome::Failed { kind, .. } = o else {
panic!("`{name}` must FAIL: a `Skipped` means the name is not modelled, got: {o}");
};
assert_eq!(kind, "postcondition", "`{name}` got: {o}");
}
}
#[test]
fn the_plain_pow_panics_where_it_overflows() {
let Some(report) = verify_realistic(&[
"plain_pow_three_to_five_is_243",
"plain_pow_two_to_seven_does_not_panic",
]) else {
return;
};
for name in ["plain_pow_three_to_five_is_243", "plain_pow_two_to_seven_does_not_panic"] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
let Some(report) = verify_realistic(&[
"plain_pow_panic_is_reachable",
"plain_pow_two_to_eight_would_panic_tripwire",
]) else {
return;
};
for name in ["plain_pow_panic_is_reachable", "plain_pow_two_to_eight_would_panic_tripwire"] {
let o = outcome(&report, name);
let FnOutcome::Failed { kind, .. } = o else {
panic!("`{name}` must FAIL on a panic, got: {o}");
};
assert!(
kind.starts_with("panic") && kind.contains("pow"),
"`{name}` must fail on the `pow` overflow panic, got: {o}"
);
}
}
#[test]
fn the_unary_neg_and_abs_families_disagree_at_min() {
let Some(report) = verify_realistic(&[
"saturating_neg_of_positive_is_negative",
"saturating_neg_of_non_positive_is_non_negative",
"saturating_abs_is_never_negative",
"saturating_abs_of_non_negative_is_identity",
]) else {
return;
};
for name in [
"saturating_neg_of_positive_is_negative",
"saturating_neg_of_non_positive_is_non_negative",
"saturating_abs_is_never_negative",
"saturating_abs_of_non_negative_is_identity",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
let Some(report) = verify_realistic(&[
"wrapping_neg_is_negative_tripwire",
"wrapping_neg_of_non_positive_is_non_negative_tripwire",
"wrapping_abs_is_never_negative_tripwire",
"saturating_abs_is_identity_tripwire",
]) else {
return;
};
for name in [
"wrapping_neg_is_negative_tripwire",
"wrapping_neg_of_non_positive_is_non_negative_tripwire",
"wrapping_abs_is_never_negative_tripwire",
"saturating_abs_is_identity_tripwire",
] {
let o = outcome(&report, name);
let FnOutcome::Failed { kind, .. } = o else {
panic!("`{name}` must FAIL: a `Skipped` means the shape is not modelled, got: {o}");
};
assert_eq!(kind, "postcondition", "`{name}` got: {o}");
}
let o = outcome(&report, "wrapping_abs_is_never_negative_tripwire");
let FnOutcome::Failed { detail, .. } = o else { panic!("got: {o}") };
assert!(
detail.contains("= 128"),
"the `wrapping_abs` witness should be x == i8::MIN (bits 128), got: {detail}"
);
}
#[test]
fn a_standard_enum_argument_is_a_switch_on_a_seeded_tag() {
let Some(report) = verify_realistic(&[
"option_arg_match",
"option_arg_match_tripwire",
"result_arg_match",
"result_arg_match_tripwire",
"option_arg_payload_passthrough",
"option_arg_payload_tripwire",
]) else {
return;
};
for name in ["option_arg_match", "result_arg_match", "option_arg_payload_passthrough"] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
for name in
["option_arg_match_tripwire", "result_arg_match_tripwire", "option_arg_payload_tripwire"]
{
let o = outcome(&report, name);
let FnOutcome::Failed { kind, .. } = o else {
panic!("`{name}` must FAIL: a `Skipped` means the shape is not modelled, got: {o}");
};
assert_eq!(kind, "postcondition", "`{name}` got: {o}");
}
}
#[test]
fn a_standard_enum_argument_payload_has_its_own_width() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
spec! {
requires: true,
ensures: ret <= 255,
}
pub fn opt_payload(x: Option<u8>) -> u8 {
match x { Some(v) => v, None => 0 }
}
spec! {
requires: true,
ensures: ret <= 1,
}
pub fn res_payload(r: Result<u8, u16>) -> u8 {
match r { Ok(_) => 0, Err(_) => 1 }
}
"#;
let Some(o) = verify_src("opt_payload", src) else { return };
assert!(o.is_verified(), "`opt_payload` must verify, got: {o}");
let Some(o) = verify_src("res_payload", src) else { return };
assert!(o.is_verified(), "`res_payload` must verify, got: {o}");
}
#[test]
fn a_cast_in_a_contract_extends_like_rust() {
let Some(report) = verify_realistic(&[
"contract_cast_widens_unsigned",
"contract_cast_widens_unsigned_tripwire",
"contract_cast_widens_signed",
"contract_cast_signed_to_unsigned",
"contract_cast_signed_to_unsigned_tripwire",
"contract_cast_narrows",
"contract_cast_narrows_tripwire",
"contract_cast_chain",
"contract_cast_chain_tripwire",
]) else {
return;
};
for name in [
"contract_cast_widens_unsigned",
"contract_cast_widens_signed",
"contract_cast_signed_to_unsigned",
"contract_cast_narrows",
"contract_cast_chain",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
for name in [
"contract_cast_widens_unsigned_tripwire",
"contract_cast_signed_to_unsigned_tripwire",
"contract_cast_narrows_tripwire",
"contract_cast_chain_tripwire",
] {
let o = outcome(&report, name);
let FnOutcome::Failed { kind, .. } = o else {
panic!("`{name}` must FAIL: a `Skipped` means the cast is not modelled, got: {o}");
};
assert_eq!(kind, "postcondition", "`{name}` got: {o}");
}
let o = outcome(&report, "contract_cast_signed_to_unsigned_tripwire");
let FnOutcome::Failed { detail, .. } = o else { panic!("got: {o}") };
assert!(
detail.contains("= 255"),
"the sign-extension witness should be x == -1 (bits 255), got: {detail}"
);
}
#[test]
fn a_contract_cast_is_read_and_proved() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
spec! {
requires: true,
ensures: ret == x as u32,
}
pub fn widen(x: u8) -> u32 {
x as u32
}
spec! {
requires: true,
ensures: ret == x as u8,
}
pub fn narrow(x: u16) -> u8 {
x as u8
}
"#;
let Some(o) = verify_src("widen", src) else { return };
assert!(o.is_verified(), "`widen` must verify, got: {o}");
let Some(o) = verify_src("narrow", src) else { return };
assert!(o.is_verified(), "`narrow` must verify, got: {o}");
}
#[test]
fn a_cast_in_a_contract_can_be_ordered() {
let names = [
"contract_cast_relational_nonneg",
"contract_cast_relational_lt_width",
"contract_cast_relational_signed_bound",
"contract_cast_relational_signed_nonneg_tripwire",
"contract_cast_relational_positive_tripwire",
];
let Some(report) = verify_realistic(&names) else { return };
for name in [
"contract_cast_relational_nonneg",
"contract_cast_relational_lt_width",
"contract_cast_relational_signed_bound",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
for name in [
"contract_cast_relational_signed_nonneg_tripwire",
"contract_cast_relational_positive_tripwire",
] {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Failed { .. }),
"`{name}` is false for every negative (resp. zero) input; got: {o}"
);
}
}
#[test]
fn a_wrapping_method_in_a_contract_is_read_as_the_operator_it_denotes() {
let names = [
"contract_wrapping_add_reads",
"contract_wrapping_add_is_a_value_tripwire",
"contract_wrapping_sub_mul_chain_reads",
"contract_wrapping_agrees_with_the_plain_operators",
"contract_wrapping_neg_on_unsigned_reads",
"contract_wrapping_neg_on_signed_reads",
"contract_wrapping_add_of_constants_wraps",
];
let Some(report) = verify_realistic(&names) else { return };
for name in [
"contract_wrapping_add_reads",
"contract_wrapping_sub_mul_chain_reads",
"contract_wrapping_agrees_with_the_plain_operators",
"contract_wrapping_neg_on_unsigned_reads",
"contract_wrapping_neg_on_signed_reads",
"contract_wrapping_add_of_constants_wraps",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
let o = outcome(&report, "contract_wrapping_add_is_a_value_tripwire");
assert!(
matches!(o, FnOutcome::Failed { .. }),
"the wrapping add is a value, so `+ 1` on it is false for every input; got: {o}"
);
for name in [
"contract_wrapping_add_of_an_out_of_range_literal_is_refused",
"contract_wrapping_add_on_an_untyped_receiver_is_refused",
] {
let Some(report) = verify_realistic(&[name]) else { return };
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Skipped { .. }),
"`{name}` is a rustc error and must be refused, never given a verdict, got: {o}"
);
}
}
#[test]
fn wrapping_shifts_are_modelled_with_the_amount_reduced_modulo_the_width() {
let Some(report) = verify_realistic(&[
"wrapping_shl_reduces_its_amount",
"wrapping_shl_amount_is_not_saturated_tripwire",
"wrapping_shr_signed_is_arithmetic",
"wrapping_shr_signed_is_not_logical_tripwire",
"wrapping_shr_unsigned_is_logical",
]) else {
return;
};
for name in [
"wrapping_shl_reduces_its_amount",
"wrapping_shr_signed_is_arithmetic",
"wrapping_shr_unsigned_is_logical",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
for name in [
"wrapping_shl_amount_is_not_saturated_tripwire",
"wrapping_shr_signed_is_not_logical_tripwire",
] {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Failed { .. }),
"`{name}` is false under the correct model and must be refuted, got: {o}"
);
}
}
#[test]
fn contract_operators_and_their_precedence() {
let Some(report) = verify_realistic(&[
"contract_shr_unsigned",
"contract_shr_unsigned_tripwire",
"contract_shl",
"contract_shr_signed_is_arithmetic",
"contract_shr_signed_is_arithmetic_tripwire",
"contract_udiv",
"contract_urem",
"contract_udiv_tripwire",
"contract_sdiv",
"contract_srem",
"contract_sdiv_tripwire",
"contract_precedence_and_over_add",
"contract_precedence_and_over_add_tripwire",
"contract_precedence_add_over_shl",
"contract_precedence_add_over_shl_tripwire",
"contract_precedence_and_over_or",
"contract_precedence_and_over_or_tripwire",
"contract_precedence_shift_over_eq",
"contract_precedence_shift_over_eq_tripwire",
"contract_precedence_cast_over_add",
"contract_precedence_neg_over_cast",
"contract_precedence_neg_over_rem",
"contract_precedence_mul_rem_left_assoc",
]) else {
return;
};
for name in [
"contract_shr_unsigned",
"contract_shl",
"contract_shr_signed_is_arithmetic",
"contract_udiv",
"contract_urem",
"contract_sdiv",
"contract_srem",
"contract_precedence_and_over_add",
"contract_precedence_add_over_shl",
"contract_precedence_and_over_or",
"contract_precedence_shift_over_eq",
"contract_precedence_cast_over_add",
"contract_precedence_neg_over_cast",
"contract_precedence_neg_over_rem",
"contract_precedence_mul_rem_left_assoc",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
for name in [
"contract_shr_unsigned_tripwire",
"contract_shr_signed_is_arithmetic_tripwire",
"contract_udiv_tripwire",
"contract_sdiv_tripwire",
"contract_precedence_and_over_add_tripwire",
"contract_precedence_add_over_shl_tripwire",
"contract_precedence_and_over_or_tripwire",
"contract_precedence_shift_over_eq_tripwire",
] {
let o = outcome(&report, name);
let FnOutcome::Failed { kind, .. } = o else {
panic!("`{name}` must FAIL: a `Skipped` means the operator is not modelled, got: {o}");
};
assert_eq!(kind, "postcondition", "`{name}` got: {o}");
}
let o = outcome(&report, "contract_shr_signed_is_arithmetic_tripwire");
let FnOutcome::Failed { detail, .. } = o else { panic!("got: {o}") };
assert!(detail.contains("= 248"), "the witness should be the `-8` pattern, got: {detail}");
let o = outcome(&report, "contract_precedence_and_over_add_tripwire");
let FnOutcome::Failed { detail, .. } = o else { panic!("got: {o}") };
assert!(detail.contains("= 1"), "the witness should be `x == 1`, got: {detail}");
}
#[test]
fn a_128_bit_function_is_refused_not_panicked() {
let Some(report) = verify_realistic(&[
"wide_arg",
"wide_return",
"wide_local_in_loop",
"wide_cast_in_contract",
"narrow_64_still_works",
]) else {
return;
};
for name in ["wide_arg", "wide_return", "wide_local_in_loop", "wide_cast_in_contract"] {
let o = outcome(&report, name);
let FnOutcome::Skipped { reason } = o else {
panic!("`{name}` must be refused, got: {o}");
};
assert!(
reason.contains("64-bit") || reason.contains("wider"),
"`{name}` should say why, got: {reason}"
);
}
let o = outcome(&report, "narrow_64_still_works");
assert!(o.is_verified(), "a 64-bit function must still verify, got: {o}");
}
#[test]
fn a_contract_cast_to_128_bits_is_refused() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n requires: true,\n ensures: ret == x as u128,\n}\npub fn f(x: u8) -> u64 { x as u64 }";
let Some(o) = verify_src("f", src) else { return };
let FnOutcome::Skipped { reason } = o else {
panic!("a cast to `u128` must be refused, got: {o}");
};
assert!(reason.contains("u128"), "the refusal should name the type, got: {reason}");
}
#[test]
fn contract_operators_parse_in_isolation() {
let cases: &[(&str, &str)] = &[
("shr", "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n requires: true,\n ensures: ret == x >> 1,\n}\npub fn shr(x: u8) -> u8 { x >> 1 }"),
("shl", "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n requires: true,\n ensures: ret == x << 2,\n}\npub fn shl(x: u8) -> u8 { x << 2 }"),
("udiv", "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n requires: true,\n ensures: ret == x / 3,\n}\npub fn udiv(x: u32) -> u32 { x / 3 }"),
("urem", "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n requires: true,\n ensures: ret == x % 10,\n}\npub fn urem(x: u32) -> u32 { x % 10 }"),
(
"prec",
"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n requires: true,\n ensures: ret == x & 1 + 1,\n}\npub fn prec(x: u8) -> u8 { x & 2 }",
),
];
for (name, src) in cases {
let Some(o) = verify_src(name, src) else { return };
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
}
#[test]
fn a_constant_signed_expression_uses_the_signed_engine() {
let srcs = [
(
"srem",
"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n requires: true,\n ensures: ret == -7 % 3,\n}\npub fn srem() -> i32 { -7i32 % 3i32 }",
"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n requires: true,\n ensures: ret == 2,\n}\npub fn srem() -> i32 { -7i32 % 3i32 }",
),
(
"sdiv",
"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n requires: true,\n ensures: ret == -7 / 2,\n}\npub fn sdiv() -> i32 { -7i32 / 2i32 }",
"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n requires: true,\n ensures: ret == 3,\n}\npub fn sdiv() -> i32 { -7i32 / 2i32 }",
),
(
"ashr",
"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n requires: true,\n ensures: ret == -8 >> 1,\n}\npub fn ashr() -> i32 { -8i32 >> 1 }",
"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n requires: true,\n ensures: ret == -1,\n}\npub fn ashr() -> i32 { -8i32 >> 1 }",
),
];
for (name, true_src, false_src) in srcs {
let Some(o) = verify_src(name, true_src) else { return };
assert!(o.is_verified(), "`{name}` (true) must verify, got: {o}");
let Some(o) = verify_src(name, false_src) else { return };
assert!(!o.is_verified(), "`{name}` (tripwire) must be refuted, got: {o}");
}
}
#[test]
fn a_negation_binds_tighter_than_a_cast() {
let cases = [
(
"neg_cast_gt",
"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n requires: -x as u8 > 127,\n ensures: ret == 1,\n}\npub fn neg_cast_gt(x: i8) -> u8 { 1 }",
true,
),
(
"neg_cast_lt_tripwire",
"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n requires: x == 1,\n ensures: (-x as u8) < 127,\n}\npub fn neg_cast_lt_tripwire(x: i8) -> u8 { 1 }",
false,
),
(
"neg_cast_value",
"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n requires: x == -5,\n ensures: ret == -x as u8,\n}\npub fn neg_cast_value(x: i8) -> u8 { -x as u8 }",
true,
),
];
for (name, src, want_verified) in cases {
let Some(o) = verify_src(name, src) else { return };
assert_eq!(
o.is_verified(),
want_verified,
"`{name}`: expected verified={want_verified}, got: {o}"
);
}
}
#[test]
fn the_contract_reader_agrees_with_rustc_on_a_grid() {
type Case = (&'static str, &'static str, &'static str, &'static [i64], Option<u8>);
let cases: &[Case] = &[
("x % 3", "i8", "i8", &[-128, -7, -1, 0, 1, 7, 127], None),
("x / 2", "i8", "i8", &[-128, -7, -1, 0, 1, 7, 127], None),
("x >> 1", "i8", "i8", &[-128, -7, -1, 0, 1, 7, 127], None),
("-7 % 3", "i8", "i8", &[0], None),
("-7 / 2", "i8", "i8", &[0], None),
("-8 >> 1", "i8", "i8", &[0], None),
("-x as u8", "i8", "u8", &[-7, -1, 0, 1, 127], None),
("-x as u8", "i8", "u8", &[-7, -1, 0, 1, 127], Some(127)),
("x as i16", "i8", "i16", &[-128, -1, 0, 1, 127], None),
("x as i8", "i16", "i8", &[-32768, -129, -1, 0, 1, 127, 128, 32767], None),
("x as i8 as i32", "i16", "i32", &[-32768, -129, -1, 0, 1, 127, 128, 32767], None),
("x as u16", "u8", "u16", &[0, 1, 128, 255], None),
("x & 1 + 1", "u8", "u8", &[0, 1, 2, 3, 255], None),
("x + 1 << 1", "u8", "u8", &[0, 1, 63, 126], None),
("x | 1 ^ 1", "u8", "u8", &[0, 1, 255], None),
("x & 3 | 4", "u8", "u8", &[0, 1, 3, 255], None),
("x ^ 1 & 3", "u8", "u8", &[0, 1, 3, 255], None),
("x | 1 ^ 2", "u8", "u8", &[0, 1, 2, 255], None),
("!!x", "u8", "u8", &[0, 1, 5, 250, 255], None),
("!x >> 1", "u8", "u8", &[0, 1, 250, 255], None),
("x << 1 | 1", "u8", "u8", &[0, 1, 2, 63], None),
("-x >> 1", "i8", "i8", &[-127, -1, 0, 1, 127], None),
("-x + 1", "i8", "i8", &[-126, -1, 0, 1, 126], None),
("x as u16 & 1", "i8", "u16", &[-128, -1, 0, 1, 127], None),
("x as u8 as u16", "i8", "u16", &[-128, -1, 0, 1, 127], None),
("1 + x * 2", "u8", "u8", &[0, 1, 5, 63], None),
("x >> 1 >> 1", "u8", "u8", &[0, 1, 255], None),
("x as i16 + 1", "i8", "i16", &[-1, 0, 5, 126], Some(6)),
("-x as i16", "i8", "i16", &[-1, 0, 1, 127], None),
("x << 2", "u8", "u8", &[0, 1, 63, 255], None),
("8 - 4 - 2", "i32", "i32", &[0], None),
("8 / 4 / 2", "u32", "u32", &[0], None),
("-x", "i8", "i8", &[-127, -1, 0, 1, 127], None),
("- -x", "i8", "i8", &[-127, -1, 0, 1, 127], None),
("0 - x", "i8", "i8", &[-127, -1, 0, 1, 127], None),
("x", "i8", "i8", &[-128, -7, -1, 0, 1, 7, 127], Some(0)),
("x % 3", "i8", "i8", &[-128, -7, -1, 0, 1, 7, 127], Some(0)),
("!x", "u8", "u8", &[0, 1, 128, 255], None),
("!!x", "u8", "u8", &[0, 1, 128, 255], None),
("!x + 1", "u8", "u8", &[1, 128, 255], None),
("x & !1", "u8", "u8", &[0, 1, 3, 255], None),
("!x", "u8", "u8", &[0, 1, 5, 250, 255], Some(5)),
("!x", "u8", "u8", &[0, 1, 5, 250, 255], Some(4)),
("!(x + 1)", "u8", "u8", &[0, 1, 5, 249, 254], None),
("x >> 1 + 1", "u8", "u8", &[0, 1, 2, 4, 8, 16, 128, 255], None),
("0xFF", "u8", "u8", &[0], None),
("0b1010", "u8", "u8", &[0], None),
("0o17", "u8", "u8", &[0], None),
("0xFFu8", "u8", "u8", &[0], None),
("0xFF_FF", "u16", "u16", &[0], None),
("0x10", "u8", "u8", &[0], None),
];
let mut checked = 0u32;
for (expr, arg_ty, ret_ty, grid, guard) in cases {
for &v in *grid {
let name = format!("oracle_{checked}");
let (src, want) = match guard {
None => (
format!(
"/// requires: x == {v}\n/// ensures: ret == {expr}\n\
pub fn {name}(x: {arg_ty}) -> {ret_ty} {{ {expr} }}\n"
),
true,
),
Some(t) => {
let probe = format!(
"/// requires: x == {v}\n/// ensures: ret == 1\n\
pub fn {name}(x: {arg_ty}) -> u8 {{ if {expr} > {t} {{ 1 }} else {{ 0 }} }}\n"
);
let o = verify_src(&name, &probe);
let Some(o) = o else { return };
let truth = o.is_verified();
let src = format!(
"/// requires: x == {v} && {expr} > {t}\n/// ensures: ret == 1\n\
pub fn {name}(x: {arg_ty}) -> u8 {{ 1 }}\n"
);
(src, truth)
}
};
let Some(o) = verify_src(&name, &src) else { return };
assert_eq!(
o.is_verified(),
want,
"the reader disagrees with rustc: `{expr}` at x == {v} ({arg_ty}), guard {guard:?} — expected verified={want}, got: {o}"
);
checked += 1;
}
}
assert!(checked >= 60, "the oracle checked only {checked} points");
}
#[test]
fn a_folded_constant_is_read_as_a_constant() {
let Some(o) = verify_src(
"folded_shift_amount",
"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n requires: x == 8,\n ensures: ret == x >> 1 + 1,\n}\npub fn folded_shift_amount(x: u8) -> u8 { x >> 2 }\n",
) else {
return;
};
assert!(o.is_verified(), "a folded shift amount must be read, got: {o}");
let Some(o) = verify_src(
"folded_zero_divisor",
"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n requires: x == 3,\n ensures: ret == x % (1 - 1),\n}\npub fn folded_zero_divisor(x: u8) -> u8 { x % 3 }\n",
) else {
return;
};
assert!(
matches!(o, FnOutcome::Skipped { .. }),
"a folded zero divisor must be refused, not decided, got: {o}"
);
let Some(o) = verify_src(
"folded_nonzero_divisor",
"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n requires: x == 4,\n ensures: ret == x / (1 + 1),\n}\npub fn folded_nonzero_divisor(x: u8) -> u8 { x / 2 }\n",
) else {
return;
};
assert!(
o.is_verified(),
"a folded non-zero divisor must be read and modelled, got: {o}"
);
let Some(o) = verify_src(
"folded_body_shift",
"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n requires: x == 8,\n ensures: ret == 2,\n}\npub fn folded_body_shift(x: u8) -> u8 { x >> 1 + 1 }\n",
) else {
return;
};
assert!(
o.is_verified(),
"a folded shift amount in the body must be lowered as a constant, got: {o}"
);
}
#[test]
fn a_radix_literal_is_read_at_its_radix() {
let verified = [
"contract_hex_literal_is_255",
"contract_binary_literal_is_ten",
"contract_octal_literal_is_fifteen",
"contract_hex_underscore_is_65535",
"contract_hex_with_suffix_is_255",
"contract_hex_arithmetic_is_folded",
"contract_hex_shift_amount",
"contract_hex_mask_keeps_low_nibble",
"contract_negative_hex_literal",
"contract_uppercase_hex_prefix",
];
let Some(report) = verify_realistic(&verified) else { return };
for name in verified {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
let Some(report) = verify_realistic(&["contract_hex_literal_is_not_zero_control"]) else {
return;
};
let o = outcome(&report, "contract_hex_literal_is_not_zero_control");
let FnOutcome::Failed { kind, detail, .. } = o else {
panic!("the control must be refuted -- verifying it is the false proof, got: {o}");
};
assert_eq!(kind, "postcondition", "the control got: {o}");
assert!(detail.contains("= 255"), "the witness should be `255`, got: {detail}");
}
#[test]
fn an_out_of_range_literal_is_refused_not_wrapped() {
let refused = [
"contract_out_of_range_literal_is_refused",
"contract_out_of_range_negation_is_refused",
"contract_constant_vs_constant_out_of_range",
"contract_constant_sum_overflow_is_refused",
"contract_constant_underflow_is_refused",
"contract_constant_div_overflow_is_refused",
"contract_constant_signed_sum_overflow_is_refused",
"contract_signed_literal_vs_unsigned_is_refused",
"contract_signed_constant_sum_vs_unsigned_is_refused",
"contract_signed_constant_mask_vs_unsigned_is_refused",
"contract_negation_of_min_is_refused",
"contract_negation_of_wrapping_shift_is_refused",
"contract_nested_shift_amount_overflow_is_refused",
"contract_nested_shift_amount_sum_overflow_is_refused",
"contract_nested_amount_suffix_does_not_fix_the_outer_width",
"contract_cast_amount_operand_fixes_the_width",
];
let Some(report) = verify_realistic(&refused) else { return };
for name in refused {
let o = outcome(&report, name);
assert!(
!o.is_verified(),
"`{name}` must be refused, not verified -- verifying it is the false proof, got: {o}"
);
assert!(
matches!(o, FnOutcome::Skipped { .. }),
"`{name}` must be skipped (unreadable contract), got: {o}"
);
}
let read = [
"contract_min_bound_still_reads",
"contract_negative_bound_reads_at_i16",
"contract_constant_vs_constant_in_range",
"contract_constant_sum_in_range_reads",
"contract_constant_sum_wider_operand_reads",
"contract_unsigned_literal_still_reads",
"contract_unsigned_constant_sum_still_reads",
"contract_unsigned_mask_still_reads",
"contract_negation_of_max_still_reads",
"contract_fitting_shift_amount_still_reads",
"contract_typed_amount_operand_fixes_the_width",
];
let Some(report) = verify_realistic(&read) else { return };
for name in read {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must still read and verify, got: {o}");
}
}
#[test]
fn a_signed_element_is_read_as_signed_in_the_contract() {
let refuted = [
"signed_slice_element_ensures_tripwire",
"signed_array_chain_ensures_tripwire",
];
let Some(report) = verify_realistic(&refuted) else { return };
for name in refuted {
let o = outcome(&report, name);
let FnOutcome::Failed { kind, detail, .. } = o else {
panic!(
"`{name}` is false at `i8::MIN` and must be refuted -- verifying it is \
the unsigned-reading false proof, got: {o}"
);
};
assert_eq!(kind, "postcondition", "`{name}` got: {o}");
assert!(
detail.contains("= 128"),
"the witness should be `128` (`i8::MIN`), got: {detail}"
);
}
}
#[test]
fn a_bang_binds_by_rusts_precedence_in_the_corpus() {
let verified = [
"contract_bang_binds_tighter_than_eq",
"contract_bang_is_bitwise_not",
"contract_bang_still_negates_a_predicate",
"contract_bang_binds_tighter_than_a_cast",
"contract_bang_binds_tighter_than_and",
"contract_bang_paren_arithmetic_is_a_value",
];
let Some(report) = verify_realistic(&verified) else { return };
for name in verified {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
let Some(report) = verify_realistic(&["contract_bang_binds_tighter_than_eq_control"]) else {
return;
};
let o = outcome(&report, "contract_bang_binds_tighter_than_eq_control");
let FnOutcome::Failed { .. } = o else {
panic!("`contract_bang_binds_tighter_than_eq_control` is false and must be refuted, got: {o}");
};
}
#[test]
fn a_contract_above_a_layout_does_not_leak_into_the_next_function() {
let names = ["leaked_requires_tripwire", "leaked_requires_is_dropped"];
let Some(report) = verify_realistic(&names) else { return };
for name in names {
let o = outcome(&report, name);
let FnOutcome::Failed { kind, .. } = o else {
panic!("`{name}` proves a false contract; got: {o}");
};
assert_eq!(kind, "postcondition", "`{name}` must fail on its postcondition, got: {o}");
}
}
#[test]
fn a_mixed_signedness_comparison_is_refused_and_the_same_signedness_pair_reads() {
let refused = [
"contract_mixed_signedness_compare_is_refused",
"contract_mixed_signedness_add_is_refused",
];
let Some(report) = verify_realistic(&refused) else { return };
for name in refused {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Skipped { .. }),
"`{name}` must be refused (skipped), not given a verdict, got: {o}"
);
}
let Some(report) = verify_realistic(&["contract_same_signedness_compare_still_reads"]) else {
return;
};
let o = outcome(&report, "contract_same_signedness_compare_still_reads");
assert!(o.is_verified(), "the same-signedness control must still verify, got: {o}");
}
#[test]
fn an_untyped_complement_equality_is_refused_and_a_typed_partner_reads() {
let Some(report) = verify_realistic(&["contract_untyped_complement_equality_is_refused"]) else {
return;
};
let o = outcome(&report, "contract_untyped_complement_equality_is_refused");
assert!(
matches!(o, FnOutcome::Skipped { .. }),
"`!0 == 255` is `false` in Rust; it must be refused, never given a verdict, got: {o}"
);
let Some(report) =
verify_realistic(&["contract_complement_of_literal_with_typed_partner_reads"])
else {
return;
};
let o = outcome(&report, "contract_complement_of_literal_with_typed_partner_reads");
assert!(o.is_verified(), "a typed partner fixes the reading and must verify, got: {o}");
}
#[test]
fn a_complement_of_an_out_of_range_literal_is_refused() {
let Some(report) = verify_realistic(&[
"contract_complement_of_out_of_range_literal_is_refused",
"contract_fitting_complement_still_reads",
"contract_complement_reads_at_a_wider_operand",
]) else {
return;
};
let o = outcome(&report, "contract_complement_of_out_of_range_literal_is_refused");
assert!(
matches!(o, FnOutcome::Skipped { .. }),
"`y <= !128` for an `i8` is a rustc range error; it must be refused, never given a \
verdict, got: {o}"
);
for name in [
"contract_fitting_complement_still_reads",
"contract_complement_reads_at_a_wider_operand",
] {
let o = outcome(&report, name);
assert!(
!matches!(o, FnOutcome::Skipped { .. }),
"{name} fits the operand type and must be decided, got: {o}"
);
}
}
#[test]
fn an_unsigned_negation_is_refused_and_a_signed_negation_reads() {
let Some(report) = verify_realistic(&["contract_unsigned_negation_is_refused"]) else { return };
let o = outcome(&report, "contract_unsigned_negation_is_refused");
assert!(
matches!(o, FnOutcome::Skipped { .. }),
"`-x` for a `u8` does not compile and must be refused, got: {o}"
);
let Some(report) = verify_realistic(&["contract_signed_negation_still_reads"]) else { return };
let o = outcome(&report, "contract_signed_negation_still_reads");
assert!(o.is_verified(), "a negation of a signed name must still verify, got: {o}");
}
#[test]
fn a_literal_widened_to_a_signed_operand_zero_fills() {
let Some(report) = verify_realistic(&["contract_literal_widened_to_signed_zero_fills"]) else {
return;
};
let o = outcome(&report, "contract_literal_widened_to_signed_zero_fills");
assert!(o.is_verified(), "`255` widened to i16 is `255` and must verify, got: {o}");
let Some(report) = verify_realistic(&["contract_literal_widened_to_signed_tripwire"]) else {
return;
};
let o = outcome(&report, "contract_literal_widened_to_signed_tripwire");
assert!(matches!(o, FnOutcome::Failed { .. }), "`254` is neither reading and must FAIL, got: {o}");
}
#[test]
fn a_literal_inside_a_constant_fold_is_range_checked_too() {
let refused = [
"contract_literal_in_fold_out_of_range_is_refused",
"contract_masked_literal_out_of_range_is_refused",
"contract_constant_sum_value_out_of_range_is_refused",
"contract_literal_in_difference_out_of_range_is_refused",
"contract_literal_in_negated_fold_is_refused",
"contract_complement_shift_amount_is_refused",
];
let Some(report) = verify_realistic(&refused) else { return };
for name in refused {
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Skipped { .. }),
"`{name}` is a rustc range error and must be refused, never given a verdict, got: {o}"
);
}
for name in [
"contract_fold_literals_in_range_still_read",
"contract_bare_negated_bound_still_reads",
] {
let Some(report) = verify_realistic(&[name]) else { return };
let o = outcome(&report, name);
assert!(o.is_verified(), "{name} fits the type it meets and must verify, got: {o}");
}
}
#[test]
fn a_sign_ambiguous_untyped_fold_is_refused() {
for name in [
"contract_sign_ambiguous_fold_is_refused",
"contract_sign_ambiguous_mul_is_refused",
"contract_complement_with_negated_literal_is_refused",
] {
let Some(report) = verify_realistic(&[name]) else { return };
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Skipped { .. }),
"`{name}` is sign-ambiguous and must be refused, never given a verdict, got: {o}"
);
}
for name in [
"contract_sign_ambiguous_fold_at_wider_width_reads",
"contract_agreeing_untyped_fold_still_reads",
] {
let Some(report) = verify_realistic(&[name]) else { return };
let o = outcome(&report, name);
assert!(o.is_verified(), "{name} agrees under both readings and must verify, got: {o}");
}
}
#[test]
fn an_opaque_folds_provisional_value_is_not_range_checked() {
let Some(report) =
verify_realistic(&["contract_opaque_fold_provisional_value_is_not_range_checked"])
else {
return;
};
let o = outcome(&report, "contract_opaque_fold_provisional_value_is_not_range_checked");
assert!(o.is_verified(), "`y == !(!1 + 1)` is `y == 0` and must verify, got: {o}");
let Some(report) =
verify_realistic(&["contract_literal_under_complement_is_still_range_checked"])
else {
return;
};
let o = outcome(&report, "contract_literal_under_complement_is_still_range_checked");
assert!(
matches!(o, FnOutcome::Skipped { .. }),
"`!128` is an `i8` range error and must be refused, got: {o}"
);
}
#[test]
fn a_suffixed_minimum_and_a_complement_operand_are_checked_where_they_are_written() {
for name in [
"contract_suffixed_positive_min_magnitude_is_refused",
"contract_double_negated_min_is_refused",
"contract_complement_operand_out_of_range_is_refused",
"contract_negated_complement_operand_is_refused",
"contract_nested_complement_fold_operand_is_refused",
] {
let Some(report) = verify_realistic(&[name]) else { return };
let o = outcome(&report, name);
assert!(
matches!(o, FnOutcome::Skipped { .. }),
"`{name}` is a rustc range error and must be refused, never given a verdict, got: {o}"
);
}
for name in [
"contract_suffixed_min_literal_still_reads",
"contract_suffixed_positive_literal_still_reads",
"contract_complement_does_not_pollute_a_bare_literal",
"contract_named_min_after_suffixed_min_reads",
"contract_suffixed_min_after_named_min_reads",
"contract_named_min_after_bare_128_reads",
] {
let Some(report) = verify_realistic(&[name]) else { return };
let o = outcome(&report, name);
assert!(o.is_verified(), "{name} is valid Rust and must verify, got: {o}");
}
}
#[test]
fn an_opaque_widening_is_refused_but_a_fold_widens() {
let Some(report) = verify_realistic(&[
"contract_opaque_widened_to_unsigned_is_refused",
"contract_opaque_widened_to_signed_is_refused",
"contract_fold_widens_to_unsigned_reads",
]) else {
return;
};
for name in [
"contract_opaque_widened_to_unsigned_is_refused",
"contract_opaque_widened_to_signed_is_refused",
] {
let o = outcome(&report, name);
assert!(
!o.is_verified(),
"{name} must not verify -- the reader cannot model the complement at the operand width, got: {o}"
);
}
let o = outcome(&report, "contract_fold_widens_to_unsigned_reads");
assert!(o.is_verified(), "a fold widens exactly and must verify, got: {o}");
}
#[test]
fn a_suffixed_literal_keeps_its_own_width() {
let Some(report) = verify_realistic(&[
"contract_suffixed_literal_keeps_its_width",
"contract_suffixed_literal_is_its_own_value",
]) else {
return;
};
let o = outcome(&report, "contract_suffixed_literal_keeps_its_width");
assert!(
!o.is_verified(),
"`128i16 as i32` is `128`, so `== -128` is false and must not verify, got: {o}"
);
let o = outcome(&report, "contract_suffixed_literal_is_its_own_value");
assert!(o.is_verified(), "`128i16 as i32 == 128` is true and must verify, got: {o}");
}
#[test]
fn a_complement_fold_widening_is_refused_but_masks_and_shifts_read() {
let Some(report) = verify_realistic(&[
"contract_complement_fold_widening_is_refused",
"contract_complement_mask_widens_exactly",
"contract_complement_shift_by_zero_reads",
"contract_complement_division_with_typed_operand_reads",
]) else {
return;
};
let o = outcome(&report, "contract_complement_fold_widening_is_refused");
assert!(!o.is_verified(), "`(x as i16 + 2) == !0 + 2` is false and must not verify, got: {o}");
for name in [
"contract_complement_mask_widens_exactly",
"contract_complement_shift_by_zero_reads",
"contract_complement_division_with_typed_operand_reads",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "{name} is a valid contract and must verify, got: {o}");
}
}
#[test]
fn an_untyped_fold_overflow_is_refused_but_a_fitting_fold_reads() {
let Some(report) = verify_realistic(&[
"contract_untyped_fold_overflow_is_refused",
"contract_untyped_fold_overflow_equality_is_refused",
"contract_fitting_fold_still_reads",
]) else {
return;
};
for name in [
"contract_untyped_fold_overflow_is_refused",
"contract_untyped_fold_overflow_equality_is_refused",
] {
let o = outcome(&report, name);
assert!(
!o.is_verified(),
"{name} folds an untyped constant into a value that overflows the operand width \
(`E0308`/overflow in Rust) and must be refused, got: {o}"
);
}
let o = outcome(&report, "contract_fitting_fold_still_reads");
assert!(
o.is_verified(),
"`200 + 100` is width-independent and must verify, got: {o}"
);
}
#[test]
fn an_untyped_shift_that_needs_a_wider_operand_is_refused_but_a_fitting_shift_reads() {
let Some(report) = verify_realistic(&[
"contract_untyped_shift_amount_over_narrow_width_is_refused",
"contract_untyped_left_shift_amount_over_narrow_width_is_refused",
"contract_untyped_shift_operand_out_of_narrow_range_is_refused",
"contract_fitting_untyped_shift_still_reads",
"contract_typed_shift_still_reads",
]) else {
return;
};
for name in [
"contract_untyped_shift_amount_over_narrow_width_is_refused",
"contract_untyped_left_shift_amount_over_narrow_width_is_refused",
"contract_untyped_shift_operand_out_of_narrow_range_is_refused",
] {
let o = outcome(&report, name);
assert!(
!o.is_verified(),
"{name} shifts an untyped constant by an amount (or with a value) that is only \
valid at the scope's width, not the width Rust infers from the partner, and must \
be refused, got: {o}"
);
}
for name in [
"contract_fitting_untyped_shift_still_reads",
"contract_typed_shift_still_reads",
] {
let o = outcome(&report, name);
assert!(
o.is_verified(),
"{name} is a shift whose width is known or whose value fits every width, and must \
verify, got: {o}"
);
}
}
#[test]
fn a_u128_suffix_literal_is_refused_not_panicked() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n requires: true,\n ensures: 0u128 == 0u128,\n}\npub fn f(x: u8) -> u8 { x }";
let Some(o) = verify_src("f", src) else { return };
let FnOutcome::Skipped { reason } = o else {
panic!("a `u128`-suffixed literal must be refused, got: {o}");
};
assert!(
reason.contains("128") && reason.contains("64-bit"),
"the refusal should name the width and the engine limit, got: {reason}"
);
}
#[test]
fn a_symbolic_mask_keeps_its_type_but_a_constant_mask_still_widens() {
let Some(report) = verify_realistic(&[
"contract_symbolic_mask_keeps_its_type",
"contract_complement_mask_widens_exactly",
]) else {
return;
};
let o = outcome(&report, "contract_symbolic_mask_keeps_its_type");
assert!(
!o.is_verified(),
"`(x & 128) == y` pairs a `u8` with an `i8` and must be refused, got: {o}"
);
let o = outcome(&report, "contract_complement_mask_widens_exactly");
assert!(
o.is_verified(),
"a constant width-independent mask still widens and must verify, got: {o}"
);
}
#[test]
fn a_fixed_width_constant_may_not_meet_a_partner_of_another_width() {
let Some(report) = verify_realistic(&[
"contract_fixed_width_constant_vs_wider_cast_is_refused",
"contract_two_fixed_width_constants_are_refused",
"contract_bare_negation_meets_a_wider_operand",
]) else {
return;
};
for name in [
"contract_fixed_width_constant_vs_wider_cast_is_refused",
"contract_two_fixed_width_constants_are_refused",
] {
let o = outcome(&report, name);
assert!(
!o.is_verified(),
"{name} compares a fixed-width constant with a differently-sized operand \
(`E0308`) and must be refused, got: {o}"
);
}
let o = outcome(&report, "contract_bare_negation_meets_a_wider_operand");
assert!(
o.is_verified(),
"a bare negation infers its width and is well-typed, so it must verify, got: {o}"
);
}
#[test]
fn a_typed_constant_mask_keeps_its_type() {
let Some(report) = verify_realistic(&[
"contract_signed_mask_vs_unsigned_is_refused",
"contract_signed_mask_with_signed_partner_reads",
"contract_unsigned_mask_vs_signed_is_refused",
"contract_unsigned_mask_with_unsigned_partner_reads",
]) else {
return;
};
for name in [
"contract_signed_mask_vs_unsigned_is_refused",
"contract_unsigned_mask_vs_signed_is_refused",
] {
let o = outcome(&report, name);
assert!(!o.is_verified(), "{name} pairs a typed mask with the other signedness \
(`E0308`) and must be refused, got: {o}");
}
for name in [
"contract_signed_mask_with_signed_partner_reads",
"contract_unsigned_mask_with_unsigned_partner_reads",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "{name} is well-typed and must verify, got: {o}");
}
}
#[test]
fn a_transitive_pin_chain_folds_the_body() {
let Some(report) = verify_realistic(&[
"a_transitive_pin_chain_folds_the_body",
"a_transitive_pin_chain_cannot_prove_this",
]) else {
return;
};
let good = outcome(&report, "a_transitive_pin_chain_folds_the_body");
assert!(good.is_verified(), "a transitive pin chain must fold the body; got: {good}");
let bad = outcome(&report, "a_transitive_pin_chain_cannot_prove_this");
assert!(
matches!(bad, FnOutcome::Failed { .. }),
"a false claim about a transitively pinned chain must be refuted, not refused; got: {bad}"
);
}
#[test]
fn an_unsigned_power_of_two_division_is_a_shift_not_a_divider() {
let Some(report) = verify_realistic(&[
"an_unsigned_power_of_two_division_is_decided",
"an_unsigned_power_of_two_division_cannot_prove_this",
"an_unsigned_power_of_two_remainder_is_decided",
]) else {
return;
};
for name in [
"an_unsigned_power_of_two_division_is_decided",
"an_unsigned_power_of_two_remainder_is_decided",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "an unsigned power-of-two op must be decided; `{name}` got: {o}");
}
let bad = outcome(&report, "an_unsigned_power_of_two_division_cannot_prove_this");
assert!(
!bad.is_verified(),
"a false claim about an unsigned division must be refuted; got: {bad}"
);
}
#[test]
fn a_recursive_function_is_proved_by_its_decreases_measure() {
let Some(report) = verify_realistic(&["a_recursive_identity"]) else { return };
let o = outcome(&report, "a_recursive_identity");
assert!(
o.is_verified(),
"a recursive function with a decreasing measure must be proved by induction, got: {o}"
);
}
#[test]
fn a_recursive_body_that_does_not_establish_its_postcondition_is_refuted() {
let Some(report) = verify_realistic(&["a_recursive_lie_cannot_prove_this"]) else { return };
let o = outcome(&report, "a_recursive_lie_cannot_prove_this");
let FnOutcome::Failed { kind, .. } = o else {
panic!("a recursive body that breaks its postcondition must fail, got: {o}");
};
assert_eq!(kind, "postcondition", "got: {o}");
}
#[test]
fn a_recursive_call_without_a_decreasing_measure_is_not_assumed() {
let Some(report) = verify_realistic(&["a_recursive_call_that_does_not_decrease_cannot_prove_this"])
else {
return;
};
let o = outcome(&report, "a_recursive_call_that_does_not_decrease_cannot_prove_this");
assert!(
!o.is_verified(),
"an induction without a decreasing measure must not be assumed, got: {o}"
);
}
#[test]
fn a_recursive_call_must_satisfy_its_own_precondition() {
let Some(report) =
verify_realistic(&["a_recursive_call_out_of_range_cannot_prove_this"])
else {
return;
};
let o = outcome(&report, "a_recursive_call_out_of_range_cannot_prove_this");
assert!(
!o.is_verified(),
"a recursive call that violates its own precondition must not be assumed, got: {o}"
);
}
#[test]
fn a_contract_on_an_inherent_method_is_resolved_and_checked() {
let Some(report) = verify_realistic(&["bump"]) else { return };
let o = outcome(&report, "bump");
let FnOutcome::Verified { obligations, .. } = o else {
panic!("a method whose contract holds must verify, got: {o}");
};
assert!(
*obligations > 0,
"the method's postcondition must be checked, not silently dropped; got {obligations} \
obligation(s)"
);
}
#[test]
fn a_contract_on_an_inherent_method_that_is_false_is_refuted() {
let Some(report) = verify_realistic(&["bump_cannot_prove_this"]) else { return };
let o = outcome(&report, "bump_cannot_prove_this");
let FnOutcome::Failed { kind, .. } = o else {
panic!("a method whose postcondition is false must fail, got: {o}");
};
assert_eq!(kind, "postcondition", "the failure must be the postcondition, got `{kind}`");
}
#[test]
fn an_intrinsic_call_is_not_a_self_recursive_call() {
let Some(report) = verify_realistic(&["wrapping_add"]) else { return };
let o = outcome(&report, "wrapping_add");
let FnOutcome::Failed { kind, .. } = o else {
panic!(
"a function named like an intrinsic that calls the intrinsic must be \
refuted, not proved from its own postcondition; got: {o}"
);
};
assert_eq!(kind, "postcondition", "the failure must be the postcondition, got `{kind}`");
}
#[test]
fn a_free_recursion_named_like_an_intrinsic_still_recurses() {
let Some(report) = verify_realistic(&["wrapping_add_still_recurses"]) else { return };
let o = outcome(&report, "wrapping_add_still_recurses");
assert!(
o.is_verified(),
"a free function named like an intrinsic that recurses must verify; got: {o}"
);
}
#[test]
fn a_method_named_like_an_intrinsic_still_recurses() {
let Some(report) = verify_realistic(&["wrapping_sub"]) else { return };
let o = outcome(&report, "wrapping_sub");
assert!(o.is_verified(), "a method named like an intrinsic that recurses must verify; got: {o}");
}
#[test]
fn a_recursive_contract_naming_a_const_is_resolved() {
let Some(report) = verify_realistic(&["a_recursive_contract_naming_a_const_is_resolved"])
else {
return;
};
let o = outcome(&report, "a_recursive_contract_naming_a_const_is_resolved");
assert!(
o.is_verified(),
"a recursive contract naming a crate-level const must resolve at the self-call; got: {o}"
);
}
#[test]
fn a_contract_only_const_is_resolved() {
let Some(report) = verify_realistic(&["a_contract_only_const_is_resolved"]) else { return };
let o = outcome(&report, "a_contract_only_const_is_resolved");
assert!(
o.is_verified(),
"a crate-level const named only by a contract must resolve; got: {o}"
);
}
#[test]
fn a_string_literal_does_not_leak_a_local_const() {
let Some(report) =
verify_realistic(&["a_string_literal_must_not_leak_a_unique_local_const"])
else {
return;
};
let o = outcome(&report, "a_string_literal_must_not_leak_a_unique_local_const");
assert!(
!o.is_verified(),
"a string literal must not leak a function-local const into a contract; got: {o}"
);
}
#[test]
fn a_local_trait_from_is_answered_by_its_body() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
pub mod conv_shim {
pub trait From<T> {
fn from(t: T) -> Self;
}
impl From<u8> for u16 {
fn from(_t: u8) -> u16 {
7
}
}
}
spec! {
requires: x == 0,
ensures: ret == x as u16,
}
pub fn local_from_is_not_the_model(x: u8) -> u16 {
conv_shim::From::from(x)
}
"#;
let Some(o) = verify_src("local_from_is_not_the_model", src) else { return };
let FnOutcome::Failed { ref kind, .. } = o else {
panic!("the local trait's body must refute the claim, got: {o}");
};
assert_eq!(kind, "postcondition", "got: {o}");
}
#[test]
fn a_conversion_agrees_with_a_cast_of_the_same_shape() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
spec! {
requires: true,
ensures: ret == x as u16,
}
pub fn from_matches_cast(x: u8) -> u16 {
u16::from(x)
}
spec! {
requires: true,
ensures: ret == x as i32,
}
pub fn into_signed_matches_cast(x: i8) -> i32 {
x.into()
}
"#;
let Some(o) = verify_src("from_matches_cast", src) else { return };
assert!(o.is_verified(), "`u16::from(x)` must agree with `x as u16`; got: {o}");
let Some(o) = verify_src("into_signed_matches_cast", src) else { return };
assert!(o.is_verified(), "`x.into()` must agree with `x as i32`; got: {o}");
}
#[test]
fn an_unmodelled_conversion_is_reported_unknown_not_guessed() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
spec! {
requires: true,
ensures: ret == 1,
}
pub fn from_char_is_unmodelled(c: char) -> u32 {
u32::from(c)
}
"#;
let Some(o) = verify_src("from_char_is_unmodelled", src) else { return };
assert!(
!o.is_verified(),
"a conversion the model does not hold must not verify; got: {o}"
);
let FnOutcome::Incomplete { .. } = o else {
panic!("an unmodelled conversion must be `Incomplete`, got: {o}");
};
}
#[test]
fn an_external_static_call_is_not_answered_by_a_local_method() {
let Some(report) = verify_realistic(&["a_static_call_resolves_to_its_own_impl_cannot_prove_this"])
else {
return;
};
let o = outcome(&report, "a_static_call_resolves_to_its_own_impl_cannot_prove_this");
assert!(
!o.is_verified(),
"a call to `u16::from` must not be answered by a local `from`; got: {o}"
);
let FnOutcome::Failed { kind, .. } = o else {
panic!("the modelled conversion must refute the fixture, got: {o}");
};
assert_eq!(kind, "postcondition", "got: {o}");
}
#[test]
fn a_local_static_call_resolves_to_its_impl() {
let Some(report) = verify_realistic(&["a_local_static_call_resolves_to_its_impl"]) else {
return;
};
let o = outcome(&report, "a_local_static_call_resolves_to_its_impl");
assert!(o.is_verified(), "a local static method call must resolve and verify; got: {o}");
}
#[test]
fn two_impls_with_a_shared_method_tail_keep_separate_contracts() {
let Some(report) = verify_realistic(&["tag"]) else { return };
for key in ["TaggedLeft::tag", "TaggedRight::tag"] {
let o = outcome(&report, key);
assert!(o.is_verified(), "{key} must be checked against its own contract; got: {o}");
}
}
#[test]
fn two_impls_with_a_shared_method_tail_do_not_conflate_contracts() {
let Some(report) = verify_realistic(&["tag_cannot_prove_this"]) else { return };
for key in ["TaggedLeft::tag_cannot_prove_this", "TaggedRight::tag_cannot_prove_this"] {
let o = outcome(&report, key);
let FnOutcome::Failed { kind, .. } = o else {
panic!("{key} must be refuted by its own postcondition, got: {o}");
};
assert_eq!(kind, "postcondition", "{key}: the failure must be the postcondition, got `{kind}`");
}
}
#[test]
fn a_trait_default_method_is_checked_against_its_contract() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\npub trait T {\n spec! {\n ensures: ret == 9,\n }\n fn value(&self) -> u8 { 7 }\n}\n";
let o = verify_src("T::value", src).expect("T::value must be verified, not dropped");
let FnOutcome::Failed { kind, .. } = o else {
panic!("a trait default with a false postcondition must be refuted, got: {o}");
};
assert_eq!(kind, "postcondition", "the failure must be the postcondition, got `{kind}`");
}
#[test]
fn a_module_nested_free_function_is_checked_against_its_contract() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\npub mod m {\n spec! {\n ensures: ret == 9,\n }\n pub fn f() -> u8 { 7 }\n}\n";
let o = verify_src("m::f", src).expect("m::f must be verified, not dropped");
let FnOutcome::Failed { kind, .. } = o else {
panic!("a module function with a false postcondition must be refuted, got: {o}");
};
assert_eq!(kind, "postcondition", "the failure must be the postcondition, got `{kind}`");
}
#[test]
fn two_sibling_modules_do_not_share_a_contract() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\npub mod a {\n spec! {\n ensures: ret == 9,\n }\n pub fn f() -> u8 { 1 }\n}\npub mod b {\n spec! {\n ensures: ret == 2,\n }\n pub fn f() -> u8 { 2 }\n}\n";
let left = verify_src("a::f", src).expect("a::f must be present");
let FnOutcome::Failed { kind, .. } = left else {
panic!("a::f has a false postcondition and must be refuted, got: {left}");
};
assert_eq!(kind, "postcondition", "a::f: the failure must be the postcondition, got `{kind}`");
let right = verify_src("b::f", src).expect("b::f must be present");
assert!(right.is_verified(), "b::f's own contract is true and must verify, got: {right}");
}
#[test]
fn a_cfg_excluded_contract_does_not_steal_a_compiled_body() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\npub mod a {\n spec! {\n ensures: ret == 1,\n }\n pub fn f() -> u8 { 1 }\n}\npub mod b {\n pub mod a {\n spec! {\n ensures: ret == 1,\n }\n #[cfg(any())]\n pub fn f() -> u8 { 2 }\n }\n}\n";
let rustc = rustc().expect("rustc");
let dir = std::env::temp_dir().join(format!("verif-cfg-steal-{}", std::process::id()));
let _ = std::fs::create_dir_all(&dir);
let file = dir.join("probe.rs");
std::fs::write(&file, src).expect("write probe");
let report = verify::verify_file_with_opts(&rustc, &file, &[], &probe_opts()).expect("frontend");
let _ = std::fs::remove_dir_all(&dir);
assert!(
report.outcomes.is_empty(),
"no body may be paired with the excluded `b::a::f`'s contract, got: {:?}",
report.outcomes
);
for name in ["a::f", "b::a::f"] {
assert!(
report.missing.contains(&name.to_string()),
"`{name}` must be reported missing rather than silently verified, got: {:?}",
report.missing
);
}
}
#[test]
fn a_nested_free_function_is_still_resolved_by_its_suffix() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\npub mod a {\n spec! {\n ensures: ret == 9,\n }\n pub fn f() -> u8 { 1 }\n}\n";
let o = verify_src("a::f", src).expect("a::f must be present");
let FnOutcome::Failed { kind, .. } = o else {
panic!("a::f has a false postcondition and must be refuted, got: {o}");
};
assert_eq!(kind, "postcondition", "a::f: the failure must be the postcondition, got `{kind}`");
}
#[test]
fn a_trait_default_and_a_free_function_do_not_share_a_contract() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n ensures: ret == 9,\n}\npub fn v() -> u8 { 1 }\npub trait A {\n spec! {\n ensures: ret == 2,\n }\n fn v(&self) -> u8 { 2 }\n}\n";
let free = verify_src("v", src).expect("v must be present");
let FnOutcome::Failed { kind, .. } = free else {
panic!("the free `v` has a false postcondition and must be refuted, got: {free}");
};
assert_eq!(kind, "postcondition", "v: the failure must be the postcondition, got `{kind}`");
let method = verify_src("A::v", src).expect("A::v must be present");
assert!(method.is_verified(), "the trait default's own contract is true, got: {method}");
}
#[test]
fn a_contract_on_a_trait_implementation_is_checked() {
let header = "pub trait Stow { fn value(&self) -> u8; }\npub struct Slot;\n";
let truth = format!(
"{header}impl Stow for Slot {{\n /// ensures: ret == 7\n fn value(&self) -> u8 {{ 7 }}\n}}\n"
);
let o = verify_src("value", &truth).expect("the trait impl's method must be present");
assert!(o.is_verified(), "`ret == 7` with a body of 7 must verify, got: {o}");
let falsehood = format!(
"{header}impl Stow for Slot {{\n /// ensures: ret == 9\n fn value(&self) -> u8 {{ 7 }}\n}}\n"
);
let o = verify_src("value", &falsehood).expect("the trait impl's method must be present");
let FnOutcome::Failed { kind, .. } = o else {
panic!("`ret == 9` with a body of 7 must be refuted, got: {o}");
};
assert_eq!(kind, "postcondition", "the failure must be the postcondition, got `{kind}`");
}
#[test]
fn a_multiline_impl_header_still_owns_its_methods() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\npub struct Foo;\nimpl Foo\n{\n spec! {\n ensures: ret == 9,\n }\n pub fn m(&self) -> u8 { 1 }\n}\n";
let o = verify_src("m", src).expect("m must be present");
let FnOutcome::Failed { kind, .. } = o else {
panic!("a method of a multiline impl with a false postcondition must be refuted, got: {o}");
};
assert_eq!(kind, "postcondition", "the failure must be the postcondition, got `{kind}`");
}
#[test]
fn an_implementation_that_breaks_its_traits_contract_is_refuted() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\npub trait Bump {\n spec! {\n ensures: ret == 9,\n }\n fn bump(&self) -> u8;\n}\npub struct S;\nimpl Bump for S { fn bump(&self) -> u8 { 7 } }\n";
let (outcomes, missing) = verify_all_outcomes(src);
assert!(missing.is_empty(), "the impl carries the promise, so nothing is missing: {missing:?}");
let o = pick(&outcomes, "bump");
let FnOutcome::Failed { kind, .. } = o else {
panic!("a body of 7 against `ret == 9` must be refuted, got: {o}");
};
assert_eq!(kind, "postcondition", "the failure must be the postcondition, got `{kind}`");
}
#[test]
fn an_implementation_that_keeps_its_traits_contract_verifies() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\npub trait Bump {\n spec! {\n ensures: ret == 9,\n }\n fn bump(&self) -> u8;\n}\npub struct S;\nimpl Bump for S { fn bump(&self) -> u8 { 9 } }\n";
let (outcomes, _) = verify_all_outcomes(src);
let o = pick(&outcomes, "bump");
assert!(o.is_verified(), "a body of 9 against `ret == 9` must verify, got: {o}");
}
#[test]
fn a_free_function_does_not_borrow_a_trait_declarations_contract() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\npub trait Bump {\n spec! {\n ensures: ret == 9,\n }\n fn bump(&self) -> u8;\n}\npub fn bump() -> u8 { 9 }\n";
let (outcomes, missing) = verify_all_outcomes(src);
for (key, _) in &outcomes {
assert_ne!(
key, "Bump::bump",
"the trait declaration has no body, so it can never be reported as a verified \
function: {outcomes:?}"
);
}
assert!(
missing.iter().any(|m| m.starts_with("Bump::bump")),
"the trait's promise has no implementation here, which must be visible rather than \
silently unenforced; missing was {missing:?}"
);
}
#[test]
fn a_trait_declaration_with_no_implementation_is_reported() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\npub trait Bump {\n spec! {\n ensures: ret == 9,\n }\n fn bump(&self) -> u8;\n}\n";
let (outcomes, missing) = verify_all_outcomes(src);
assert!(outcomes.is_empty(), "there is no body to verify, got: {outcomes:?}");
assert!(
missing.iter().any(|m| m.starts_with("Bump::bump")),
"an unenforced trait contract must be reported, got: {missing:?}"
);
}
#[test]
fn two_contracts_for_one_method_are_refused_not_silently_chosen() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\npub trait Bump {\n spec! {\n ensures: ret == 9,\n }\n fn bump(&self) -> u8;\n}\npub struct S;\nimpl Bump for S {\n spec! {\n ensures: ret == 7,\n }\n fn bump(&self) -> u8 { 7 }\n}\n";
let (outcomes, _) = verify_all_outcomes(src);
let o = pick(&outcomes, "bump");
let FnOutcome::Skipped { reason } = o else {
panic!("two contracts for one function must be refused, got: {o}");
};
assert!(
reason.contains("Bump") && reason.contains("contract"),
"the refusal must name the trait and say what conflicts, got: `{reason}`"
);
}
#[test]
fn two_implementations_of_a_contracted_trait_are_both_checked() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\npub trait Bump {\n spec! {\n ensures: ret == 9,\n }\n fn bump(&self) -> u8;\n}\npub struct A; pub struct B;\nimpl Bump for A { fn bump(&self) -> u8 { 7 } }\nimpl Bump for B { fn bump(&self) -> u8 { 9 } }\n";
let (outcomes, missing) = verify_all_outcomes(src);
assert!(missing.is_empty(), "both impls carry the promise: {missing:?}");
let a = pick(&outcomes, "A::bump");
let b = pick(&outcomes, "B::bump");
let FnOutcome::Failed { kind, .. } = a else {
panic!("`A::bump` returns 7 against `ret == 9` and must be refuted, got: {a}");
};
assert_eq!(kind, "postcondition", "the failure must be the postcondition, got `{kind}`");
assert!(b.is_verified(), "`B::bump` returns 9 and must verify, got: {b}");
}
#[test]
fn an_impl_of_an_uncontracted_trait_keeps_its_own_contract() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\npub trait Bump { fn bump(&self) -> u8; }\npub struct S;\nimpl Bump for S {\n spec! {\n ensures: ret == 7,\n }\n fn bump(&self) -> u8 { 7 }\n}\n";
let (outcomes, _) = verify_all_outcomes(src);
let o = pick(&outcomes, "bump");
assert!(o.is_verified(), "the impl's own `ret == 7` with a body of 7 must verify, got: {o}");
}
#[test]
fn a_trait_default_returning_an_array_is_still_checked() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\npub trait T {\n spec! {\n ensures: ret == 9,\n }\n fn v(&self, xs: [u8; 4]) -> u8 { 7 }\n}\n";
let (outcomes, missing) = verify_all_outcomes(src);
assert!(missing.is_empty(), "a default has a body, so nothing is missing: {missing:?}");
let o = pick(&outcomes, "T::v");
let FnOutcome::Failed { kind, .. } = o else {
panic!("a default whose `ret` is 7 against `ret == 9` must be refuted, got: {o}");
};
assert_eq!(kind, "postcondition", "the failure must be the postcondition, got `{kind}`");
}
#[test]
fn a_trait_default_method_is_not_treated_as_a_declaration() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\npub trait T {\n spec! {\n ensures: ret == 9,\n }\n fn value(&self) -> u8 { 7 }\n}\n";
let (outcomes, missing) = verify_all_outcomes(src);
assert!(missing.is_empty(), "a default has a body, so nothing is missing: {missing:?}");
let o = pick(&outcomes, "T::value");
let FnOutcome::Failed { kind, .. } = o else {
panic!("a default with a false postcondition must be refuted, got: {o}");
};
assert_eq!(kind, "postcondition", "the failure must be the postcondition, got `{kind}`");
}
#[test]
fn a_one_line_impl_body_does_not_leak_its_scope() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\npub struct Foo;\nimpl Foo { pub fn m(&self) -> u8 { 1 } }\nspec! {\n ensures: ret == 9,\n}\npub fn g() -> u8 { 1 }\n";
let o = verify_src("g", src).expect("g must be present");
let FnOutcome::Failed { kind, .. } = o else {
panic!("g has a false postcondition and must be refuted, got: {o}");
};
assert_eq!(kind, "postcondition", "the failure must be the postcondition, got `{kind}`");
}
#[test]
fn a_const_generic_does_not_leak_a_local_const() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\npub fn cg<const N: usize>() -> u8 { N as u8 }\npub fn owner() -> u8 { const N: u8 = 3; N }\nspec! {\n requires: N == 3,\n ensures: ret == N,\n}\npub fn reads() -> u8 { 3 }\n";
let o = verify_src("reads", src).expect("reads must be present");
assert!(
matches!(o, FnOutcome::Skipped { .. }),
"a contract naming the leaked local `N` must be refused, not decided, got: {o}"
);
}
#[test]
fn a_split_const_generic_does_not_leak_a_local_const() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\npub fn cg<\n const N: usize,\n>() -> u8 { N as u8 }\npub fn owner() -> u8 { const N: u8 = 3; N }\nspec! {\n requires: N == 3,\n ensures: ret == N,\n}\npub fn reads() -> u8 { 3 }\n";
let o = verify_src("reads", src).expect("reads must be present");
assert!(
matches!(o, FnOutcome::Skipped { .. }),
"a contract naming the leaked local `N` must be refused, not decided, got: {o}"
);
}
#[test]
fn a_const_generic_after_whitespace_or_a_comment_does_not_leak_a_local_const() {
for header in ["const\n N: usize", "const\tN: usize", "const/*c*/N: usize"] {
let src = format!(
"pub fn cg<{header}>() -> u8 {{ N as u8 }}\n\
pub fn owner() -> u8 {{ const N: u8 = 3; N }}\n\
/// requires: N == 3\n/// ensures: ret == N\npub fn reads() -> u8 {{ 3 }}\n"
);
let o = verify_src("reads", &src).expect("reads must be present");
assert!(
matches!(o, FnOutcome::Skipped { .. }),
"a contract naming the leaked local `N` must be refused, not decided, got: {o}"
);
}
}
#[test]
fn a_const_expression_in_an_impl_header_does_not_hide_its_method() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\npub struct Foo<const N: usize>;\nimpl Foo<{ 1 }>\n{\n spec! {\n ensures: ret == 9,\n }\n pub fn m(&self) -> u8 { 7 }\n}\n";
let o = verify_src("m", src).expect("m must be present");
let FnOutcome::Failed { kind, .. } = o else {
panic!("a method with a false postcondition must be refuted, got: {o}");
};
assert_eq!(kind, "postcondition", "the failure must be the postcondition, got `{kind}`");
}
#[test]
fn a_crate_level_const_is_still_read_beside_a_const_generic() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\npub const N: u8 = 5;\npub fn cg<const N: usize>() -> usize { N }\nspec! {\n ensures: ret == N,\n}\npub fn reads() -> u8 { 5 }\n";
let specs = spec::extract(src);
assert!(specs.crate_consts.contains("N"), "the crate-level `N` must still be read");
assert!(specs.const_generics.contains("N"), "the const-generic `N` must be recognized");
let o = verify_src("reads", src).expect("reads must be present");
assert!(o.is_verified(), "`ret == N` with crate `N == 5` must verify, got: {o}");
}
#[test]
fn a_local_const_does_not_shadow_a_crate_const_in_another_contract() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\npub const K: u8 = 7;\npub fn owner() -> u8 { const K: u8 = 3; K }\nspec! {\n ensures: ret == K,\n}\npub fn reads() -> u8 { 3 }\n";
let o = verify_src("reads", src).expect("reads must be present");
assert!(
!o.is_verified(),
"`K` is the crate's 7, so `ret == K` with ret 3 must not be proved against \
`owner`'s local 3, got: {o}"
);
if let FnOutcome::Failed { kind, .. } = o {
assert_eq!(kind, "postcondition", "the failure must be the postcondition, got `{kind}`");
}
}
#[test]
fn a_cfg_disabled_crate_const_does_not_let_a_local_shadow_it() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\n#[cfg(any())]\npub const K: u8 = 7;\npub fn owner() -> u8 { const K: u8 = 3; K }\nspec! {\n ensures: ret == K,\n}\npub fn reads() -> u8 { 3 }\n";
let o = verify_src("reads", src).expect("reads must be present");
assert!(
matches!(o, FnOutcome::Skipped { .. }),
"`K` is not a crate-level name here, so the contract must be refused, got: {o}"
);
}
#[test]
fn a_cfg_disabled_crate_const_alone_is_not_a_program_wide_name() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\n#[cfg(any())]\npub const K: u8 = 7;\nspec! {\n ensures: ret == K,\n}\npub fn reads() -> u8 { 3 }\n";
let o = verify_src("reads", src).expect("reads must be present");
assert!(
matches!(o, FnOutcome::Skipped { .. }),
"a disabled item is not a name the compiled crate has, got: {o}"
);
}
#[test]
fn a_local_const_alone_is_not_a_program_wide_name() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\npub fn owner() -> u8 { const K: u8 = 3; K }\nspec! {\n ensures: ret == K,\n}\npub fn reads() -> u8 { 3 }\n";
let o = verify_src("reads", src).expect("reads must be present");
assert!(
matches!(o, FnOutcome::Skipped { .. }),
"a name only a function-local `const` carries must be refused, not decided, got: {o}"
);
}
#[test]
fn an_associated_const_does_not_hide_a_crate_const() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nconst K: u8 = 7;\npub struct Foo;\nimpl Foo { pub const K: u8 = 3; }\npub fn uses_assoc() -> u8 { Foo::K }\nspec! {\n ensures: ret == K,\n}\npub fn reads() -> u8 { 7 }\n";
let o = verify_src("reads", src).expect("reads must be present");
assert!(
o.is_verified(),
"`K` is the compiled crate constant (7), so `ret == K` must be proved \
despite the associated `Foo::K`, got: {o}"
);
}
#[test]
fn a_nested_or_method_local_const_is_not_a_program_wide_name() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\npub const L: u8 = 40;\npub const M: u8 = 10;\npub struct Foo;\nimpl Foo { pub fn method(&self) -> u8 { const L: u8 = 4; L } }\npub fn outer() -> u8 { fn inner() -> u8 { const M: u8 = 1; M } inner() }\nspec! {\n ensures: ret == L,\n}\npub fn reads_l() -> u8 { 4 }\nspec! {\n ensures: ret == M,\n}\npub fn reads_m() -> u8 { 1 }\n";
for (name, local) in [("reads_l", "L"), ("reads_m", "M")] {
let o = verify_src(name, src).expect("contracted function must be present");
assert!(
matches!(o, FnOutcome::Skipped { .. }),
"`{local}` in `{name}` must resolve to the crate constant, not the \
method/nested local, so a body of the local's value must be refused, \
got: {o}"
);
}
}
#[test]
fn a_branching_const_does_not_fold_to_its_first_arm() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\npub const K: u8 = if false { 7 } else { 8 };\nspec! {\n ensures: ret == 8,\n}\npub fn true_claim() -> u8 { K }\nspec! {\n ensures: ret == 7,\n}\npub fn false_claim() -> u8 { K }\n";
let true_claim = verify_src("true_claim", src).expect("true_claim must be present");
let false_claim = verify_src("false_claim", src).expect("false_claim must be present");
assert!(
!false_claim.is_verified(),
"`K` is 8, so `ret == 7` must not be reported verified, got: {false_claim}"
);
assert!(
true_claim.is_verified(),
"a branching const body folds to the *taken* arm, so `ret == 8` decides; \
got: {true_claim}"
);
}
#[test]
fn an_unclosed_block_comment_after_const_is_not_a_panic() {
use verif::mir::spec;
for src in [
"fn f<const /*",
"fn f<const /*x",
"fn f<const /* ",
"fn f<const /*/",
"fn f<const /*x*",
"fn f<const /*x*/",
"fn f<const /*\n",
] {
let _ = spec::const_generic_params(src);
}
}
fn verify_all_src(src: &str) -> Option<Vec<(String, FnOutcome)>> {
let rustc = rustc()?;
static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dir = std::env::temp_dir()
.join(format!("verif-all-{}-{seq}", std::process::id()));
let _ = std::fs::create_dir_all(&dir);
let file = dir.join("probe.rs");
std::fs::write(&file, src).expect("write probe");
let report = verify::verify_file_with_opts(&rustc, &file, &[], &probe_opts()).expect("frontend");
let _ = std::fs::remove_dir_all(&dir);
Some(report.outcomes)
}
fn pick<'a>(outcomes: &'a [(String, FnOutcome)], name: &str) -> &'a FnOutcome {
outcomes
.iter()
.find(|(n, _)| n == name)
.map(|(_, o)| o)
.unwrap_or_else(|| {
let seen: Vec<&str> = outcomes.iter().map(|(n, _)| n.as_str()).collect();
panic!("`{name}` missing from {seen:?}")
})
}
#[test]
fn a_callee_contract_decides_a_call_with_no_body() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nunsafe extern \"C\" {\n spec! {\n requires: n <= 10,\n ensures: ret <= n + 1,\n }\n fn ext_bump(n: u32) -> u32;\n}\n\nspec! {\n requires: x <= 10,\n ensures: ret <= 11,\n}\npub fn caller_ok(x: u32) -> u32 { unsafe { ext_bump(x) } }\n";
let Some(all) = verify_all_src(src) else { return };
let o = pick(&all, "caller_ok");
assert!(o.is_verified(), "the contract should decide this call, got: {o}");
match o {
FnOutcome::Verified { obligations, .. } => assert!(
*obligations >= 2,
"the precondition obligation and the caller's postcondition must both \
be present, got {obligations}"
),
_ => unreachable!(),
}
}
#[test]
fn a_caller_that_does_not_establish_the_precondition_fails() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nunsafe extern \"C\" {\n spec! {\n requires: n <= 10,\n ensures: ret <= n + 1,\n }\n fn ext_bump(n: u32) -> u32;\n}\n\nspec! {\n requires: x <= 100,\n ensures: ret <= 101,\n}\npub fn caller_pre_fails(x: u32) -> u32 { unsafe { ext_bump(x) } }\n";
let Some(all) = verify_all_src(src) else { return };
let o = pick(&all, "caller_pre_fails");
match o {
FnOutcome::Failed { kind, .. } => assert!(
kind.contains("callee's precondition"),
"the failure must name the precondition, got: {kind}"
),
_ => panic!("a call outside the callee's precondition must FAIL, got: {o}"),
}
}
#[test]
fn a_call_to_a_callee_whose_postcondition_is_unsatisfiable_fails() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nunsafe extern \"C\" {\n spec! {\n requires: n <= 10,\n ensures: false,\n }\n fn ext_never_returns(n: u32) -> u32;\n}\n\nspec! {\n requires: x <= 10,\n ensures: ret == 0,\n}\npub fn caller_of_divergent(x: u32) -> u32 { unsafe { ext_never_returns(x) } }\n";
let Some(all) = verify_all_src(src) else { return };
let o = pick(&all, "caller_of_divergent");
match o {
FnOutcome::Failed { kind, .. } => assert!(
kind.contains("postcondition is unsatisfiable"),
"the failure must name the divergence, got: {kind}"
),
_ => panic!("a divergent callee must FAIL the caller, got: {o}"),
}
}
#[test]
fn a_callee_with_no_postcondition_is_not_assumed_to_promise_everything() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nunsafe extern \"C\" {\n spec! {\n requires: n <= 10,\n }\n fn ext_no_post(n: u32) -> u32;\n}\n\nspec! {\n requires: x <= 10,\n ensures: ret <= 11,\n}\npub fn caller_of_silent(x: u32) -> u32 { unsafe { ext_no_post(x) } }\n";
let Some(all) = verify_all_src(src) else { return };
let o = pick(&all, "caller_of_silent");
assert!(
!o.is_verified(),
"a callee with no `ensures` gives nothing to assume, got: {o}"
);
match o {
FnOutcome::Incomplete { reasons, .. } => assert!(
reasons.iter().any(|r| r.contains("no `ensures`")),
"the reason must say the callee has no postcondition, got: {reasons:?}"
),
_ => panic!("expected Incomplete, got: {o}"),
}
}
#[test]
fn a_signature_the_scanner_cannot_read_refuses_the_call() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nunsafe extern \"C\" {\n spec! {\n requires: n <= 10,\n ensures: ret <= n + 1,\n }\n fn ext_bump(_: u32) -> u32;\n}\n\nspec! {\n requires: x <= 10,\n ensures: ret <= 11,\n}\npub fn caller_unnamed(x: u32) -> u32 { unsafe { ext_bump(x) } }\n";
let Some(all) = verify_all_src(src) else { return };
let o = pick(&all, "caller_unnamed");
assert!(
!o.is_verified(),
"a parameter the scanner could not name must not be bound positionally, got: {o}"
);
match o {
FnOutcome::Incomplete { reasons, .. } => assert!(
reasons.iter().any(|r| r.contains("parameter(s)") || r.contains("signature")),
"the reason must name the arity or the unreadable signature, got: {reasons:?}"
),
_ => panic!("expected Incomplete, got: {o}"),
}
}
#[test]
fn a_call_passing_a_reference_to_a_bodyless_callee_is_refused() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nunsafe extern \"C\" {\n spec! {\n requires: *r <= 10,\n ensures: true,\n }\n fn ext_take(r: &mut u32);\n}\n\nspec! {\n requires: x <= 10,\n ensures: ret <= 10,\n}\npub fn caller_by_ref(x: u32) -> u32 {\n let mut y = x;\n unsafe { ext_take(&mut y) };\n y\n}\n";
let Some(all) = verify_all_src(src) else { return };
let o = pick(&all, "caller_by_ref");
assert!(
!o.is_verified(),
"a reference argument needs the aliasing model, got: {o}"
);
match o {
FnOutcome::Incomplete { reasons, .. } => assert!(
reasons.iter().any(|r| r.contains("passes a reference")),
"the reason must name the reference, got: {reasons:?}"
),
_ => panic!("expected Incomplete, got: {o}"),
}
}
#[test]
fn a_callee_with_a_body_is_inlined_rather_than_answered_from_its_contract() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n ensures: ret <= 100,\n}\npub fn callee(a: u32) -> u32 { a }\n\nspec! {\n requires: x <= 3,\n ensures: ret <= 3,\n}\npub fn caller(x: u32) -> u32 { callee(x) }\n";
let Some(all) = verify_all_src(src) else { return };
let o = pick(&all, "caller");
assert!(
o.is_verified(),
"the callee's body is in the dump, so inlining proves `ret <= 3`; a contract-only \
route would only give `ret <= 100`, got: {o}"
);
}
#[test]
fn an_inherited_contract_binds_parameters_by_position_not_by_name() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\npub trait T {\nspec! {\n ensures: ret == a,\n}\nfn f(&self, a: u8, b: u8) -> u8;\n}\npub struct S;\nimpl T for S { fn f(&self, b: u8, a: u8) -> u8 { a } }\n";
let (outcomes, missing) = verify_all_outcomes(src);
assert!(missing.is_empty(), "the impl carries the declaration's contract, so nothing is missing: {missing:?}");
let o = pick(&outcomes, "f");
assert!(
!o.is_verified(),
"the body returns the implementation's `a`, which is the trait's `b`, so \
`ret == a` (the trait's `a`) must be refuted, got: {o}"
);
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\npub trait T {\nspec! {\n ensures: ret == a,\n}\nfn f(&self, a: u8, b: u8) -> u8;\n}\npub struct S;\nimpl T for S { fn f(&self, b: u8, a: u8) -> u8 { b } }\n";
let (outcomes, _) = verify_all_outcomes(src);
let o = pick(&outcomes, "f");
assert!(
o.is_verified(),
"the body returns the implementation's `b`, which is the trait's `a`, so \
`ret == a` holds, got: {o}"
);
}
#[test]
fn an_inherited_contract_binds_a_field_to_the_declarations_parameter() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\npub struct Config { pub lo: u8, pub hi: u8 }\npub trait T {\nspec! {\n requires: c.lo <= c.hi,\n ensures: ret == c.hi,\n}\nfn hi_of(&self, c: Config) -> u8;\n}\npub struct S;\nimpl T for S { fn hi_of(&self, k: Config) -> u8 { k.hi } }\n";
let (outcomes, missing) = verify_all_outcomes(src);
assert!(missing.is_empty(), "nothing is missing here: {missing:?}");
let o = pick(&outcomes, "hi_of");
assert!(
o.is_verified(),
"the contract names the declaration's `c`, which is the implementation's \
`k` by position, so `c.hi` is `k.hi` and the body satisfies it, got: {o}"
);
}
#[test]
fn an_inherited_contract_that_cannot_be_aligned_is_refused() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\npub trait T {\nspec! {\n ensures: ret == 1,\n}\nfn f(&self, _: u8) -> u8;\n}\npub struct S;\nimpl T for S { fn f(&self, a: u8) -> u8 { let _ = a; 2 } }\n";
let (outcomes, missing) = verify_all_outcomes(src);
assert!(missing.is_empty(), "the impl is present, so nothing is missing: {missing:?}");
let o = pick(&outcomes, "f");
assert!(
!o.is_verified(),
"a contract whose declaration cannot be aligned must not be bound by guess, got: {o}"
);
match o {
FnOutcome::Skipped { reason } => assert!(
reason.contains("signature"),
"the refusal must name the unreadable declaration signature, got: {reason}"
),
_ => panic!("expected Skipped, got: {o}"),
}
}
#[test]
fn a_return_type_that_wraps_to_the_next_line_refuses_the_call() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nunsafe extern \"C\" {\nspec! {\n ensures: ret == i8::MIN,\n}\nfn ext() ->\ni8;\n}\nspec! {\n ensures: ret == 0,\n}\npub fn caller() -> u8 { if unsafe { ext() } < 0 { 1u8 } else { 0u8 } }\n";
let (outcomes, _) = verify_all_outcomes(src);
let o = pick(&outcomes, "caller");
assert!(
!o.is_verified(),
"the return type was not read whole, so the call must be refused rather than \
checked against an unsigned reading, got: {o}"
);
match o {
FnOutcome::Incomplete { reasons, .. } => assert!(
reasons.iter().any(|r| r.contains("signature")),
"the reason must name the unreadable signature, got: {reasons:?}"
),
_ => panic!("expected Incomplete, got: {o}"),
}
}
#[test]
fn a_return_type_on_one_line_is_read_and_refutes_the_false_claim() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nunsafe extern \"C\" {\nspec! {\n ensures: ret == i8::MIN,\n}\nfn ext() -> i8;\n}\nspec! {\n ensures: ret == 0,\n}\npub fn caller() -> u8 { if unsafe { ext() } < 0 { 1u8 } else { 0u8 } }\n";
let (outcomes, _) = verify_all_outcomes(src);
let o = pick(&outcomes, "caller");
assert!(
!o.is_verified(),
"a signed return of i8::MIN makes `ext() < 0` true, so `ret == 0` is false \
for that input, got: {o}"
);
match o {
FnOutcome::Failed { .. } => {}
_ => panic!("expected a definite counterexample, got: {o}"),
}
}
#[test]
fn a_trait_impl_written_with_a_relative_root_is_checked() {
for (label, path) in [("crate::T", "crate::T"), ("self::T", "self::T")] {
let src = format!(
"pub trait T {{\n\
/// ensures: ret == 9\n\
fn f(&self) -> u8;\n\
}}\n\
pub struct S;\n\
impl {path} for S {{ fn f(&self) -> u8 {{ 7 }} }}\n"
);
let (outcomes, missing) = verify_all_outcomes(&src);
assert!(
missing.is_empty(),
"`{label}` names the declared trait, so nothing is missing: {missing:?}"
);
let o = pick(&outcomes, "f");
assert!(
!o.is_verified(),
"the body returns 7 and the trait promises 9, so `{label}` must be \
refuted, got: {o}"
);
}
}
#[test]
fn a_bodyless_declaration_is_assumed_not_reported_missing() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nunsafe extern \"C\" {\nspec! {\n ensures: ret == 1,\n}\nfn ext() -> u8;\n}\nspec! {\n ensures: ret == 1,\n}\npub fn caller() -> u8 { unsafe { ext() } }\n";
let (outcomes, missing) = verify_all_outcomes(src);
assert!(
missing.is_empty(),
"an `extern` declaration is assumed at its calls, not missing: {missing:?}"
);
let o = pick(&outcomes, "caller");
assert!(o.is_verified(), "the call is decided by the callee's contract, got: {o}");
}
#[test]
fn an_assumed_bodyless_contract_is_still_refuted_when_unsatisfiable() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nunsafe extern \"C\" {\nspec! {\n ensures: ret == 1 && ret == 2,\n}\nfn ext() -> u8;\n}\nspec! {\n ensures: ret == 1,\n}\npub fn caller() -> u8 { unsafe { ext() } }\n";
let (outcomes, _) = verify_all_outcomes(src);
let o = pick(&outcomes, "caller");
assert!(
!o.is_verified(),
"a postcondition no input satisfies must not verify the caller, got: {o}"
);
}
#[test]
fn an_unreachable_call_is_not_a_divergence() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nunsafe extern \"C\" {\nspec! {\n ensures: true,\n}\nfn ext() -> u8;\n}\nspec! {\n ensures: ret == 0,\n}\npub fn caller(x: u8) -> u8 {\nif x == 0 { if x != 0 { unsafe { ext() }; } }\n0\n}\n";
let (outcomes, missing) = verify_all_outcomes(src);
assert!(missing.is_empty(), "the extern is assumed, so nothing is missing: {missing:?}");
let o = pick(&outcomes, "caller");
assert!(
o.is_verified(),
"the call sits under contradictory guards, so it cannot happen and is not a \
divergence, got: {o}"
);
}
#[test]
fn a_helper_call_in_a_measured_loop_keeps_the_termination_measure() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n requires: i < 255,\n ensures: ret == i + 1,\n}\npub fn step(i: u8) -> u8 { i + 1 }\n\nspec! {\n requires: n <= 200,\n invariant: i <= n,\n variant: n - i,\n ensures: ret == n,\n}\npub fn f(n: u8) -> u8 {\nlet mut i = 0u8;\nwhile i < n { i = step(i); }\ni\n}\n";
let (outcomes, missing) = verify_all_outcomes(src);
assert!(missing.is_empty(), "both bodies are present: {missing:?}");
let o = pick(&outcomes, "f");
assert!(
o.is_verified(),
"the helper call must not erase the loop's measure, got: {o}"
);
}
#[test]
fn an_assert_is_checked_and_discharged_under_its_precondition() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n requires: x <= 200,\n ensures: ret == 1,\n}\npub fn f(x: u8) -> u8 { assert!(x <= 200); 1 }\n";
let o = verify_src("f", src).expect("f must be in the report");
assert!(
o.is_verified(),
"the guard follows from the precondition, so the assert cannot fire: {o}"
);
}
#[test]
fn an_unproved_assert_is_refuted_with_a_counterexample() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n ensures: ret == 1,\n}\npub fn f(x: u8) -> u8 { assert!(x <= 200); 1 }\n";
let o = verify_src("f", src).expect("f must be in the report");
match o {
FnOutcome::Failed { kind, detail } => {
assert!(
kind.contains("assertion failed: x <= 200"),
"the report should name the failed assertion, got `{kind}`"
);
assert!(!detail.is_empty(), "a failure must carry a counterexample");
}
other => panic!("an assert with no guard must fail, got: {other}"),
}
}
#[test]
fn an_assert_guard_is_assumed_by_the_code_after_it() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n requires: x <= 200,\n ensures: ret == x + 1,\n}\npub fn f(x: u8) -> u8 { assert!(x <= 200); x + 1 }\n";
let o = verify_src("f", src).expect("f must be in the report");
assert!(o.is_verified(), "the assert must be assumed on the fall-through path: {o}");
}
#[test]
fn a_debug_assert_is_checked_like_an_assert() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n requires: x <= 200,\n ensures: ret == 1,\n}\npub fn f(x: u8) -> u8 { debug_assert!(x <= 200); 1 }\n";
let o = verify_src("f", src).expect("f must be in the report");
assert!(o.is_verified(), "a debug_assert is the same terminator as an assert: {o}");
}
#[test]
fn a_panic_is_refuted_unless_its_guard_excludes_it() {
let unguarded = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n ensures: ret == 1,\n}\npub fn f(x: u8) -> u8 { if x == 0 { panic!(\"zero\"); } 1 }\n";
let o = verify_src("f", unguarded).expect("f must be in the report");
match o {
FnOutcome::Failed { kind, .. } => {
assert!(kind.contains("zero"), "the report should name the panic, got `{kind}`");
}
other => panic!("an unguarded panic must fail, got: {other}"),
}
let guarded = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n requires: x != 0,\n ensures: ret == 1,\n}\npub fn f(x: u8) -> u8 { if x == 0 { panic!(\"zero\"); } 1 }\n";
let o = verify_src("f", guarded).expect("f must be in the report");
assert!(o.is_verified(), "the precondition excludes the panic: {o}");
}
#[test]
fn a_formatted_panic_message_is_recovered_from_the_fmt_chain() {
let unguarded = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n ensures: ret == 1,\n}\npub fn f(x: u8) -> u8 { if x == 0 { panic!(\"bad {}\", x); } 1 }\n";
let Some(o) = verify_src("f", unguarded) else { return };
match o {
FnOutcome::Failed { kind, .. } => {
assert!(
kind.contains("bad {}"),
"the report should name the panic's pieces, got `{kind}`"
);
}
other => panic!("a formatted panic with no guard must fail, got: {other}"),
}
let guarded = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n requires: x <= 100,\n ensures: ret == 1,\n}\npub fn f(x: u8) -> u8 { assert!(x <= 100, \"bad {}\", x); 1 }\n";
let o = verify_src("f", guarded).expect("f must be in the report");
assert!(o.is_verified(), "the precondition implies the formatted assert: {o}");
let misguarded = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n ensures: ret == 1,\n}\npub fn f(x: u8) -> u8 { assert!(x <= 100, \"bad {}\", x); 1 }\n";
let o = verify_src("f", misguarded).expect("f must be in the report");
match o {
FnOutcome::Failed { kind, .. } => assert!(
kind.contains("bad {}"),
"the formatted assert should be named by its pieces, got `{kind}`"
),
other => panic!("an unguarded formatted assert must fail, got: {other}"),
}
let no_pieces = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n ensures: ret == 1,\n}\npub fn f(x: u8) -> u8 { if x == 0 { panic!(\"{}\", x); } 1 }\n";
let o = verify_src("f", no_pieces).expect("f must be in the report");
match o {
FnOutcome::Failed { kind, .. } => assert!(
kind.contains("display") && !kind.contains('<'),
"the fallback should be the callee's name, not its generics, got `{kind}`"
),
other => panic!("an unguarded panic must fail, got: {other}"),
}
}
#[test]
fn a_literal_panic_macro_names_its_message() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n ensures: ret == 1,\n}\npub fn f(x: u8) -> u8 { if x == 0 { unreachable!(); } 1 }\n";
let Some(o) = verify_src("f", src) else { return };
match o {
FnOutcome::Failed { kind, .. } => assert!(
kind.contains("entered unreachable code"),
"the report should carry the macro's text, got `{kind}`"
),
other => panic!("an unguarded `unreachable!` must fail, got: {other}"),
}
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n ensures: ret == 1,\n}\npub fn f(x: u8) -> u8 { if x == 0 { todo!(); } 1 }\n";
let o = verify_src("f", src).expect("f must be in the report");
match o {
FnOutcome::Failed { kind, .. } => assert!(
kind.contains("not yet implemented"),
"the report should carry the macro's text, got `{kind}`"
),
other => panic!("an unguarded `todo!` must fail, got: {other}"),
}
}
#[test]
fn an_index_bounds_check_is_proved_unreachable() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\nspec! {\n requires: xs.len() >= 1,\n ensures: ret == 0,\n}\npub fn f(xs: &[u8]) -> u8 { xs[0] * 0 }\n";
let o = verify_src("f", src).expect("f must be in the report");
assert!(o.is_verified(), "the length precondition rules the bounds check out: {o}");
}
#[test]
fn a_diverging_call_in_a_function_with_a_drop_local_is_checked() {
let src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\npub struct Guard(pub u8);\nimpl Drop for Guard {\n fn drop(&mut self) {}\n}\nspec! {\n ensures: ret == 1,\n}\npub fn f(x: u8) -> u8 { let _g = Guard(0); assert!(x < 200); 1 }\n";
let o = verify_src("f", src).expect("f must be in the report");
match o {
FnOutcome::Failed { kind, detail } => {
assert!(
kind.contains("assertion failed: x < 200"),
"the cleanup-form assert must be named, got `{kind}`"
);
assert!(!detail.is_empty(), "a failure must carry a counterexample");
}
other => panic!(
"an unguarded assert with a live Drop local must be a failure, not a \
dropped path, got: {other}"
),
}
}
#[test]
fn abs_and_clamp_are_modelled_with_their_panics() {
let names = [
"abs_small_reads",
"abs_small_is_a_value_cannot_prove_this",
"abs_min_can_overflow",
"unsigned_abs_reads",
"unsigned_abs_of_min_is_the_magnitude",
"unsigned_abs_of_min_is_panic_free",
"unsigned_abs_is_a_value_cannot_prove_this",
"clamp_builtin_reads",
"clamp_builtin_can_panic",
"clamp_builtin_is_a_value_cannot_prove_this",
"clamp_builtin_signed_reads",
];
let Some(report) = verify_realistic(&names) else { return };
for name in [
"abs_small_reads",
"unsigned_abs_reads",
"unsigned_abs_of_min_is_the_magnitude",
"unsigned_abs_of_min_is_panic_free",
"clamp_builtin_reads",
"clamp_builtin_signed_reads",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
for name in [
"abs_small_is_a_value_cannot_prove_this",
"unsigned_abs_is_a_value_cannot_prove_this",
"clamp_builtin_is_a_value_cannot_prove_this",
] {
let o = outcome(&report, name);
match o {
FnOutcome::Failed { kind, .. } => assert!(
kind.starts_with("postcondition"),
"`{name}` must be refuted on the value (postcondition), got `{kind}`"
),
other => panic!("`{name}` claims a false value and must be refuted, got: {other}"),
}
}
for name in ["abs_min_can_overflow", "clamp_builtin_can_panic"] {
let o = outcome(&report, name);
match o {
FnOutcome::Failed { kind, .. } => {
assert!(kind.starts_with("panic"), "`{name}` must fail on the panic, got `{kind}`")
}
other => panic!("`{name}` must be a failing panic, got: {other}"),
}
}
}
#[test]
fn the_ascii_classes_are_modelled_with_their_boundaries() {
let names = [
"ascii_digit_value",
"ascii_digit_is_not_every_byte_cannot_prove_this",
"ascii_class_discriminates",
"ascii_class_hex_arm_is_not_every_byte_cannot_prove_this",
"ascii_is_ascii_boundary",
"ascii_is_ascii_is_not_every_byte_cannot_prove_this",
];
let Some(report) = verify_realistic(&names) else { return };
for name in ["ascii_digit_value", "ascii_class_discriminates", "ascii_is_ascii_boundary"] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
for (name, byte) in [
("ascii_digit_is_not_every_byte_cannot_prove_this", 48u64),
("ascii_class_hex_arm_is_not_every_byte_cannot_prove_this", 80),
("ascii_is_ascii_is_not_every_byte_cannot_prove_this", 128),
] {
let o = outcome(&report, name);
match o {
FnOutcome::Failed { kind, .. } => assert!(
kind.starts_with("postcondition"),
"`{name}` must be refuted on the postcondition, got `{kind}`"
),
other => panic!("`{name}` claims a false value and must be refuted, got: {other}"),
}
let detail = format!("{o}");
assert!(
detail.contains(&byte.to_string()),
"`{name}`'s witness should name the byte {byte}, got: {detail}"
);
}
}
#[test]
fn abs_diff_and_rotations_are_modelled_with_their_boundaries() {
let names = [
"abs_diff_ordered",
"abs_diff_is_symmetric_cannot_prove_this",
"rotate_left_wraps_the_top_bit",
"rotate_is_not_a_shift_cannot_prove_this",
"rotate_by_the_width_is_the_identity",
"rotate_by_more_than_the_width_wraps",
];
let Some(report) = verify_realistic(&names) else { return };
for name in [
"abs_diff_ordered",
"rotate_left_wraps_the_top_bit",
"rotate_by_the_width_is_the_identity",
"rotate_by_more_than_the_width_wraps",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
for name in ["abs_diff_is_symmetric_cannot_prove_this", "rotate_is_not_a_shift_cannot_prove_this"]
{
let o = outcome(&report, name);
match o {
FnOutcome::Failed { kind, .. } => assert!(
kind.starts_with("postcondition"),
"`{name}` must be refuted on the postcondition, got `{kind}`"
),
other => panic!("`{name}` claims a false value and must be refuted, got: {other}"),
}
}
}
#[test]
fn the_next_core_value_methods_are_modelled_with_their_tripwires() {
let names = [
"signum_of_min_is_minus_one",
"signum_of_a_negative_cannot_prove_this",
"cast_unsigned_reinterprets_negative_as_large",
"cast_unsigned_reinterprets_negative_cannot_prove_this",
"cast_signed_reinterprets_large_as_negative",
"cast_signed_reinterprets_large_cannot_prove_this",
"cast_unsigned_makes_a_comparison_unsigned",
"div_euclid_rounds_toward_negative_infinity",
"div_euclid_is_not_truncating_division_cannot_prove_this",
"rem_euclid_is_non_negative",
"rem_euclid_is_not_the_truncating_remainder_cannot_prove_this",
"unsigned_rem_euclid_is_the_plain_remainder",
"unsigned_rem_euclid_is_not_the_signed_adjustment_cannot_prove_this",
"unsigned_div_euclid_is_the_plain_quotient",
"unsigned_div_euclid_is_not_the_signed_adjustment_cannot_prove_this",
"div_ceil_rounds_toward_positive_infinity",
"div_ceil_is_not_truncating_division_cannot_prove_this",
"reverse_bits_of_the_top_bit",
"reverse_bits_is_not_the_identity_cannot_prove_this",
"swap_bytes_reverses_the_bytes",
"swap_bytes_is_not_the_identity_cannot_prove_this",
"to_be_on_a_little_endian_target_swaps",
"to_be_is_not_the_identity_here_cannot_prove_this",
"to_le_on_a_little_endian_target_is_the_identity",
"from_be_on_a_little_endian_target_swaps",
"from_be_is_not_the_identity_here_cannot_prove_this",
"from_le_on_a_little_endian_target_is_the_identity",
"to_be_then_from_be_is_the_identity",
"to_le_then_from_be_is_not_the_identity_cannot_prove_this",
"to_ascii_uppercase_of_a_lowercase_letter",
"to_ascii_uppercase_leaves_uppercase_cannot_prove_this",
"to_ascii_lowercase_of_an_uppercase_letter",
"is_multiple_of_six_by_three",
"is_multiple_of_seven_by_three_cannot_prove_this",
"is_multiple_of_zero_by_zero",
"is_multiple_of_five_by_zero",
];
let Some(report) = verify_realistic(&names) else { return };
for name in [
"signum_of_min_is_minus_one",
"cast_unsigned_reinterprets_negative_as_large",
"cast_signed_reinterprets_large_as_negative",
"cast_unsigned_makes_a_comparison_unsigned",
"div_euclid_rounds_toward_negative_infinity",
"rem_euclid_is_non_negative",
"unsigned_rem_euclid_is_the_plain_remainder",
"unsigned_div_euclid_is_the_plain_quotient",
"div_ceil_rounds_toward_positive_infinity",
"reverse_bits_of_the_top_bit",
"swap_bytes_reverses_the_bytes",
"to_be_on_a_little_endian_target_swaps",
"to_le_on_a_little_endian_target_is_the_identity",
"from_be_on_a_little_endian_target_swaps",
"from_le_on_a_little_endian_target_is_the_identity",
"to_be_then_from_be_is_the_identity",
"to_ascii_uppercase_of_a_lowercase_letter",
"to_ascii_lowercase_of_an_uppercase_letter",
"is_multiple_of_six_by_three",
"is_multiple_of_zero_by_zero",
"is_multiple_of_five_by_zero",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
for name in [
"signum_of_a_negative_cannot_prove_this",
"cast_unsigned_reinterprets_negative_cannot_prove_this",
"cast_signed_reinterprets_large_cannot_prove_this",
"div_euclid_is_not_truncating_division_cannot_prove_this",
"rem_euclid_is_not_the_truncating_remainder_cannot_prove_this",
"unsigned_rem_euclid_is_not_the_signed_adjustment_cannot_prove_this",
"unsigned_div_euclid_is_not_the_signed_adjustment_cannot_prove_this",
"div_ceil_is_not_truncating_division_cannot_prove_this",
"reverse_bits_is_not_the_identity_cannot_prove_this",
"swap_bytes_is_not_the_identity_cannot_prove_this",
"to_be_is_not_the_identity_here_cannot_prove_this",
"from_be_is_not_the_identity_here_cannot_prove_this",
"to_le_then_from_be_is_not_the_identity_cannot_prove_this",
"to_ascii_uppercase_leaves_uppercase_cannot_prove_this",
"is_multiple_of_seven_by_three_cannot_prove_this",
] {
let o = outcome(&report, name);
match o {
FnOutcome::Failed { kind, .. } => assert!(
kind.starts_with("postcondition"),
"`{name}` must be refuted on the postcondition, got `{kind}`"
),
other => panic!("`{name}` claims a false value and must be refuted, got: {other}"),
}
}
}
#[test]
fn the_u32_product_surface_is_modelled() {
let names = [
"u32_wrapping_product",
"u32_wrapping_product_tripwire",
"u32_saturating_product",
"u32_saturating_product_tripwire",
];
let Some(report) = verify_realistic(&names) else { return };
for name in ["u32_wrapping_product", "u32_saturating_product"] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
for name in ["u32_wrapping_product_tripwire", "u32_saturating_product_tripwire"] {
let o = outcome(&report, name);
match o {
FnOutcome::Failed { kind, .. } => assert!(
kind.starts_with("postcondition"),
"`{name}` must be refuted on the postcondition, got `{kind}`"
),
other => panic!("`{name}` claims a false value and must be refuted, got: {other}"),
}
}
}
#[test]
fn a_drop_terminator_is_modelled_and_its_destructor_runs() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
pub struct Guard(pub u8);
impl Drop for Guard {
fn drop(&mut self) {}
}
spec! {
requires: x < 200,
ensures: ret == 1,
}
pub fn guarded(x: u8) -> u8 {
let _g = Guard(0);
assert!(x < 200);
1
}
spec! {
requires: true,
ensures: ret == 1,
}
pub fn misguarded(x: u8) -> u8 {
let _g = Guard(0);
assert!(x < 200);
1
}
"#;
let Some(g) = verify_src("guarded", src) else { return };
assert!(
g.is_verified(),
"a function holding a live `Drop` local with a satisfied assert must verify, got: {g}"
);
let Some(m) = verify_src("misguarded", src) else { return };
match m {
FnOutcome::Failed { kind, .. } => assert!(
kind.starts_with("panic"),
"the misguarded assert must be refuted as a panic, got `{kind}`"
),
other => panic!("the misguarded assert is reachable and must be refuted, got: {other}"),
}
}
#[test]
fn a_destructor_body_is_executed_and_its_panic_is_an_obligation() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
pub struct PanicGuard { pub v: u8 }
impl Drop for PanicGuard {
fn drop(&mut self) {
assert!(self.v < 10);
}
}
spec! {
requires: true,
ensures: ret == 1,
}
pub fn unguarded(x: u8) -> u8 {
let _p = PanicGuard { v: x };
1
}
spec! {
requires: x < 10,
ensures: ret == 1,
}
pub fn guarded(x: u8) -> u8 {
let _p = PanicGuard { v: x };
1
}
"#;
let Some(u) = verify_src("unguarded", src) else { return };
match u {
FnOutcome::Failed { kind, detail } => {
assert!(
kind.starts_with("panic"),
"the destructor's assert must be a refuted panic, got `{kind}`"
);
assert!(
kind.contains("v < 10"),
"the refuted obligation must be the destructor's own assert, got: `{kind}` \
with witness {detail}"
);
}
other => panic!(
"a destructor that panics for `x >= 10` must be refuted, got: {other} -- \
treating the drop as a no-op would have proved it"
),
}
let Some(g) = verify_src("guarded", src) else { return };
assert!(g.is_verified(), "the guarded destructor cannot panic, got: {g}");
}
#[test]
fn an_unmodelled_drop_is_refused_not_assumed_away() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
spec! {
requires: true,
ensures: ret == 1,
}
pub fn owns_string(s: String) -> u8 {
let _owned = s;
1
}
"#;
let Some(o) = verify_src("owns_string", src) else { return };
match o {
FnOutcome::Incomplete { .. } | FnOutcome::Skipped { .. } => {}
other => panic!(
"a `String` drop is not representable and must be refused, got: {other} -- \
a verdict here would be a false proof"
),
}
}
#[test]
fn the_drop_fixtures_decide_and_the_false_ones_are_refuted() {
let names = [
"guard_is_dropped_cleanly",
"guard_guarded",
"destructor_panic_guarded",
"guard_misguarded_cannot_prove_this",
"destructor_panic_cannot_prove_this",
"string_drop_is_refused",
];
let Some(report) = verify_realistic(&names) else { return };
for name in [
"guard_is_dropped_cleanly",
"guard_guarded",
"destructor_panic_guarded",
] {
let o = outcome(&report, name);
assert!(o.is_verified(), "`{name}` must verify, got: {o}");
}
for name in [
"guard_misguarded_cannot_prove_this",
"destructor_panic_cannot_prove_this",
] {
let o = outcome(&report, name);
match o {
FnOutcome::Failed { kind, .. } => assert!(
kind.starts_with("panic"),
"`{name}` must be refuted as a reachable panic, got `{kind}`"
),
other => panic!(
"`{name}` has a reachable panic and must be refuted, got: {other} -- \
treating the `drop` as a no-op, or dropping the path at it, would hide it"
),
}
}
match outcome(&report, "string_drop_is_refused") {
FnOutcome::Incomplete { .. } | FnOutcome::Skipped { .. } => {}
other => panic!("a `String` drop must be refused, got: {other}"),
}
}
#[test]
fn a_combinator_that_destroys_a_value_respects_its_drop_glue() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
pub struct Boom;
impl Drop for Boom {
fn drop(&mut self) {
panic!("boom");
}
}
spec! {
requires: true,
ensures: ret <= 255,
}
pub fn boom_default(r: Result<u8, Boom>) -> u8 {
r.unwrap_or_default()
}
spec! {
requires: true,
ensures: ret <= 255,
}
pub fn boom_or(r: Result<u8, Boom>) -> u8 {
r.unwrap_or(7)
}
"#;
for name in ["boom_default", "boom_or"] {
let Some(o) = verify_src(name, src) else { return };
match o {
FnOutcome::Incomplete { .. } => {}
other => panic!(
"`{name}` destroys a `Boom` whose destructor panics and must be refused \
as `Incomplete`, got: {other} -- a `verified` here is a false proof"
),
}
}
}
mod review_round {
use super::*;
#[test]
fn a_field_with_its_own_destructor_is_refused_not_assumed_safe() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
pub struct Inner { pub v: u8 }
impl Drop for Inner {
fn drop(&mut self) { assert!(self.v < 10); }
}
pub struct Outer { pub inner: Inner }
impl Drop for Outer {
fn drop(&mut self) {}
}
spec! {
requires: true,
ensures: ret == 1,
}
pub fn outer_with_panicking_field(x: u8) -> u8 {
let _o = Outer { inner: Inner { v: x } };
1
}
spec! {
requires: x < 10,
ensures: ret == 1,
}
pub fn outer_guarded(x: u8) -> u8 {
let _o = Outer { inner: Inner { v: x } };
1
}
"#;
let Some(u) = verify_src("outer_with_panicking_field", src) else { return };
assert!(
!u.is_verified(),
"a struct whose field has a panicking destructor must not be `Verified`, got: {u}"
);
let Some(g) = verify_src("outer_guarded", src) else { return };
assert!(
!g.is_verified(),
"the guarded companion is the same unmodelled shape and must not verify, got: {g}"
);
}
#[test]
fn unwrap_or_refuses_an_error_type_whose_drop_is_unmodelled() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
pub struct Boom;
impl Drop for Boom {
fn drop(&mut self) { assert!(false); }
}
spec! {
requires: true,
ensures: ret <= 255,
}
pub fn unwrap_or_dropping_error(r: Result<u8, Boom>) -> u8 {
r.unwrap_or(0)
}
spec! {
requires: true,
ensures: ret <= 255,
}
pub fn unwrap_or_scalar_error(r: Result<u8, u8>) -> u8 {
r.unwrap_or(0)
}
"#;
let Some(d) = verify_src("unwrap_or_dropping_error", src) else { return };
assert!(
!d.is_verified(),
"`unwrap_or` on an error type with a panicking destructor must not verify, got: {d}"
);
let Some(s) = verify_src("unwrap_or_scalar_error", src) else { return };
assert!(
s.is_verified(),
"`unwrap_or` on a scalar error type must still verify (positive control), got: {s}"
);
}
#[test]
fn the_unwind_bound_counts_iterations_not_header_entries() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
spec! {
requires: true,
unwind: 3,
ensures: ret == 3,
}
pub fn while_exact() -> u32 {
let mut i = 0u32;
let mut s = 0u32;
while i < 3 { s += 1; i += 1; }
s
}
spec! {
requires: true,
unwind: 3,
ensures: ret == 3,
}
pub fn for_exact() -> u32 {
let mut s = 0u32;
for _i in 0..3u32 { s += 1; }
s
}
fn helper(x: u8) -> u8 { if x == 0 { 0 } else { 1 } }
spec! {
requires: x == 0,
unwind: 1,
ensures: ret == 0,
}
pub fn loop_free_helper_calls(x: u8) -> u8 {
let a = helper(x);
let b = helper(0);
a + b
}
"#;
for name in ["while_exact", "for_exact", "loop_free_helper_calls"] {
let Some(o) = verify_src(name, src) else { return };
assert!(
o.is_verified(),
"`{name}` must verify: the bound counts iterations, so `unwind: N` \
admits a loop that runs `N` times, and helper calls do not consume it; got: {o}"
);
}
}
#[test]
fn an_unwind_bound_below_the_iterations_still_fails() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
spec! {
requires: true,
unwind: 2,
ensures: ret == 3,
}
pub fn for_too_few() -> u32 {
let mut s = 0u32;
for _i in 0..3u32 { s += 1; }
s
}
"#;
let Some(o) = verify_src("for_too_few", src) else { return };
match o {
FnOutcome::Failed { kind, .. } => assert!(
kind.contains("unwind"),
"a too-small bound must fail on the unwind obligation, got `{kind}`"
),
other => panic!("`unwind: 2` on a 3-iteration loop must be refuted, got: {other}"),
}
}
#[test]
fn a_quoted_edition_key_and_an_explicit_workspace_path_are_resolved() {
let dir = std::env::temp_dir().join(format!("verif-edition-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("member")).unwrap();
std::fs::create_dir_all(dir.join("ws")).unwrap();
std::fs::write(dir.join("ws/Cargo.toml"), "[workspace]\n[workspace.package]\nedition = \"2021\"\n").unwrap();
std::fs::write(
dir.join("member/Cargo.toml"),
"[package]\nname = \"m\"\n\"edition\" = \"2024\"\n",
)
.unwrap();
std::fs::write(dir.join("member/src.rs"), "").unwrap();
let member = dir.join("member/src.rs");
assert_eq!(
verify::edition_from_manifest(&member),
Some(verify::Edition::Rust2024),
"a quoted `\"edition\"` key must be read, not defaulted to 2015"
);
std::fs::write(
dir.join("member/Cargo.toml"),
"[package]\nname = \"m\"\nworkspace = \"../ws\"\nedition.workspace = true\n",
)
.unwrap();
assert_eq!(
verify::edition_from_manifest(&member),
Some(verify::Edition::Rust2021),
"`package.workspace = \"../ws\"` must resolve to that root's edition"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_for_loop_range_desugaring_is_modelled() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
spec! {
requires: n <= 3,
unwind: 4,
ensures: ret <= 6,
}
pub fn for_inclusive_sum(n: u32) -> u32 {
let mut s = 0;
for i in 0..=n { s += i; }
s
}
spec! {
requires: n <= 3,
unwind: 4,
ensures: ret <= 5,
}
pub fn for_inclusive_sum_cannot_prove_this(n: u32) -> u32 {
let mut s = 0;
for i in 0..=n { s += i; }
s
}
spec! {
requires: true,
unwind: 3,
ensures: ret == 3,
}
pub fn for_exclusive_counts() -> u32 {
let mut s = 0;
for _i in 0..3u32 { s += 1; }
s
}
spec! {
requires: n <= 100,
invariant: s <= 5050,
ensures: ret <= 5050,
}
pub fn tri_invariant(n: u32) -> u32 {
let mut s = 0;
for i in 0..=n { s = i.min(5050); }
s
}
spec! {
requires: n <= 100,
invariant: s <= 5050,
ensures: ret <= 3,
}
pub fn tri_invariant_cannot_prove_this(n: u32) -> u32 {
let mut s = 0;
for i in 0..=n { s = i.min(5050); }
s
}
"#;
for name in ["for_inclusive_sum", "for_exclusive_counts", "tri_invariant"] {
let Some(o) = verify_src(name, src) else { return };
assert!(
o.is_verified(),
"`{name}` must verify: the range desugaring is modelled and the loop is \
decided by `unwind:` or by an invariant, got: {o}"
);
}
let Some(f) = verify_src("for_inclusive_sum_cannot_prove_this", src) else { return };
match f {
FnOutcome::Failed { kind, .. } => assert!(
kind.contains("postcondition"),
"the false twin must fail on its postcondition, got `{kind}`"
),
other => panic!(
"the false twin claims `ret <= 5` for a sum that reaches 6 and must be \
refuted; a model that ignored the range state would prove it, got: {other}"
),
}
let Some(g) = verify_src("tri_invariant_cannot_prove_this", src) else { return };
match g {
FnOutcome::Failed { kind, .. } => assert!(
kind.contains("postcondition"),
"the invariant tripwire must fail on its postcondition, got `{kind}`"
),
other => panic!(
"a `for` loop whose postcondition is false must be refuted, not merely \
undecided; a model that does not havoc the iterator state proves it, and \
one that refuses it checks nothing, got: {other}"
),
}
}
#[test]
fn a_loop_that_calls_a_recursive_function_terminates_and_is_sound() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
spec! {
requires: true,
decreases: n,
ensures: ret == n,
}
pub fn count_down(n: u8) -> u8 {
if n == 0 { 0 } else { count_down(n - 1) + 1 }
}
spec! {
requires: true,
decreases: n,
ensures: ret == 0,
}
pub fn walk(n: u8, c: &mut u8) -> u8 {
if n == 0 { 0 } else { *c = c.wrapping_add(1); walk(n - 1, c) }
}
spec! {
requires: n <= 3,
invariant: i <= 3,
ensures: ret <= 3,
}
pub fn loop_calls_recursive(n: u8) -> u8 {
let mut i = 0u8; let mut s = 0u8;
while i < 3 { s = count_down(n); i += 1; }
s
}
spec! {
requires: n <= 3,
invariant: i <= 3,
ensures: ret == 0,
}
pub fn loop_calls_recursive_cannot_prove_this(n: u8) -> u8 {
let mut i = 0u8; let mut s = 0u8;
while i < 3 { s = count_down(n); i += 1; }
s
}
spec! {
requires: x == 0,
invariant: i <= 3,
ensures: ret <= 255,
}
/// A loop calling a *reference-carrying* recursive callee: the call cycle is
/// refused rather than followed, and the call's reference argument is added
/// directly. `x` is written through `walk`, so the exit state cannot keep `0`.
pub fn loop_calls_ref_recursive(x: &mut u8) -> u8 {
let mut i = 0u8;
while i < 3 { walk(1, x); i += 1; }
*x
}
spec! {
requires: x == 0,
invariant: i <= 3,
ensures: ret == 0,
}
/// The false twin: `walk` writes `x`, so `ret == 0` is false. A model that
/// dropped the reference from the cycle's havoc would prove it.
pub fn loop_calls_ref_recursive_cannot_prove_this(x: &mut u8) -> u8 {
let mut i = 0u8;
while i < 3 { walk(1, x); i += 1; }
*x
}
spec! {
requires: n <= 8,
invariant: i <= 3,
ensures: ret <= 1,
}
/// A *mutual* recursion cycle reached from an invariant loop: `even_w` calls
/// `odd_w` calls `even_w`. The write-set walk must terminate on the cycle
/// (`visiting` holds the functions on the stack), and neither callee writes a
/// reference, so the loop's only write is its own counter. Before the cycle
/// guard this was an unbounded recursion between *invocations* and overflowed the
/// stack, aborting the whole run.
pub fn loop_calls_mutual_recursive(n: u8) -> u8 {
let mut i = 0u8;
let mut s = 0u8;
while i < 3 { s = even_w(n); i += 1; }
s
}
spec! {
requires: true,
decreases: n,
ensures: ret <= 1,
}
pub fn even_w(n: u8) -> u8 {
if n == 0 { 1 } else { odd_w(n - 1) }
}
spec! {
requires: true,
decreases: n,
ensures: ret <= 1,
}
pub fn odd_w(n: u8) -> u8 {
if n == 0 { 0 } else { even_w(n - 1) }
}
"#;
for name in [
"loop_calls_recursive",
"loop_calls_recursive_cannot_prove_this",
"loop_calls_ref_recursive",
"loop_calls_ref_recursive_cannot_prove_this",
] {
let Some(o) = verify_src(name, src) else { return };
assert!(
!matches!(o, FnOutcome::Skipped { .. } | FnOutcome::Incomplete { .. }),
"`{name}` must be decided, not refused: a cycle-aware write-set walk \
terminates; a refusal here means the walk gave up, got: {o}"
);
}
let Some(m) = verify_src("loop_calls_mutual_recursive", src) else { return };
assert!(
!m.is_verified(),
"a loop reaching a mutually recursive callee must not be *proved* (mutual \
recursion is not modelled), got: {m}"
);
let Some(f) = verify_src("loop_calls_recursive_cannot_prove_this", src) else {
return;
};
match f {
FnOutcome::Failed { kind, .. } => assert!(
kind.contains("postcondition"),
"the false twin must fail on its postcondition, got `{kind}`"
),
other => panic!(
"the false twin claims `ret == 0` for a loop returning `n` and must be \
refuted, got: {other}"
),
}
let Some(g) = verify_src("loop_calls_ref_recursive_cannot_prove_this", src) else {
return;
};
match g {
FnOutcome::Failed { kind, .. } => assert!(
kind.contains("postcondition"),
"the reference twin must fail on its postcondition, got `{kind}`"
),
other => panic!(
"`walk` writes `x` through its reference argument, so `ret == 0` must be \
refuted; a `verified` here means the reference write did not reach the \
loop's havoc set, got: {other}"
),
}
}
#[test]
fn a_loop_without_a_contract_names_the_missing_contract() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
spec! {
requires: true,
ensures: true,
}
pub fn tri(n: u32) -> u32 {
let mut s = 0;
for i in 0..=n { s += i; }
s
}
"#;
let Some(o) = verify_src("tri", src) else { return };
match o {
FnOutcome::Incomplete { reasons, .. } => {
let joined = reasons.join(" | ");
assert!(
joined.contains("missing loop contract")
&& joined.contains("invariant:")
&& joined.contains("unwind:"),
"the reason must name the missing loop contract and the two ways to \
supply it, got: {joined}"
);
}
other => panic!(
"`tri` declares no loop contract and must be an honest incompleteness, \
got: {other}"
),
}
}
}
mod range_and_layout_review {
use super::*;
#[test]
fn a_signed_inclusive_range_stops_at_its_boundary() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
spec! {
requires: true,
unwind: 8,
ensures: ret == 1,
}
pub fn single_signed_incl() -> u32 {
let mut c = 0u32;
for _ in 127i8..=127i8 { c += 1; }
c
}
spec! {
requires: true,
unwind: 8,
ensures: ret == 2,
}
pub fn two_signed_incl() -> u32 {
let mut c = 0u32;
for _ in 126i8..=127i8 { c += 1; }
c
}
spec! {
requires: true,
unwind: 8,
ensures: ret == 3,
}
pub fn three_signed_incl() -> u32 {
let mut c = 0u32;
for _ in (-128i8)..=(-126i8) { c += 1; }
c
}
spec! {
requires: true,
unwind: 4,
ensures: ret == 1,
}
pub fn single_unsigned_incl() -> u32 {
let mut c = 0u32;
for _ in 255u8..=255u8 { c += 1; }
c
}
"#;
for (name, want) in [
("single_signed_incl", 1u32),
("two_signed_incl", 2),
("three_signed_incl", 3),
("single_unsigned_incl", 1),
] {
let Some(o) = verify_src(name, src) else { return };
assert!(
o.is_verified(),
"`{name}` must verify with {want} iteration(s); a signed range whose \
overflow flag tests zero keeps yielding past its bound, got: {o}"
);
}
}
#[test]
fn an_empty_inclusive_range_stays_empty() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
spec! {
requires: true,
ensures: ret == 0,
}
pub fn empty_incl_twice() -> u8 {
let mut r = 255u8..=254u8;
let _a = r.next();
let b = r.next();
match b { Some(_) => 1, None => 0 }
}
spec! {
requires: true,
ensures: ret == 0,
}
pub fn empty_excl_twice() -> u8 {
let mut r = 255u8..255u8;
let _a = r.next();
let b = r.next();
match b { Some(_) => 1, None => 0 }
}
"#;
for name in ["empty_incl_twice", "empty_excl_twice"] {
let Some(o) = verify_src(name, src) else { return };
assert!(
o.is_verified(),
"`{name}` must verify: `next` leaves an empty range unchanged, so the \
second call is `None` too, got: {o}"
);
}
}
#[test]
fn the_unwind_bound_counts_the_whole_loop_not_one_latch() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
spec! {
requires: n == 2,
unwind: 1,
ensures: ret == 2,
}
pub fn two_latches(n: u8) -> u8 {
let mut i = 0u8;
while i < n {
if i == 0 { i += 1; } else { i += 1; }
}
i
}
spec! {
requires: n == 1,
unwind: 1,
ensures: ret == 1,
}
pub fn one_latch(n: u8) -> u8 {
let mut i = 0u8;
while i < n {
if i == 0 { i += 1; } else { i += 1; }
}
i
}
"#;
let Some(f) = verify_src("two_latches", src) else { return };
assert!(
!f.is_verified(),
"a two-iteration loop under `unwind: 1` must run off the bound, got: {f}"
);
let Some(o) = verify_src("one_latch", src) else { return };
assert!(
o.is_verified(),
"a one-iteration loop under `unwind: 1` must verify (positive control), got: {o}"
);
}
#[test]
fn two_same_named_structs_do_not_share_a_layout() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
pub mod m {
pub struct Outer { pub inner: Inner }
pub struct Inner(pub u8);
impl Drop for Inner {
fn drop(&mut self) { if self.0 == 0 { panic!("inner"); } }
}
impl Drop for Outer { fn drop(&mut self) {} }
}
pub mod n {
pub struct Outer { pub only: u8 }
}
spec! {
requires: true,
ensures: ret == 1,
}
pub fn same_name() -> u8 {
let _g = m::Outer { inner: m::Inner(0) };
1
}
"#;
let Some(o) = verify_src("same_name", src) else { return };
assert!(
!o.is_verified(),
"`m::Outer` has a field with a panicking destructor; sharing a layout with \
`n::Outer` would hide it and prove this, got: {o}"
);
}
#[test]
fn a_qualified_type_is_not_answered_by_a_bare_layout() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
pub struct Outer { pub lo: u8, pub hi: u8 }
pub mod m { pub struct Outer { pub hi: u8, pub lo: u8 } }
spec! {
requires: o.hi == 5,
ensures: ret == 5,
}
pub fn reads_the_other_field(o: &m::Outer) -> u8 { o.lo }
spec! {
requires: o.lo == 5,
ensures: ret == 5,
}
pub fn reads_the_other_field_mirror(o: &m::Outer) -> u8 { o.hi }
"#;
for name in ["reads_the_other_field", "reads_the_other_field_mirror"] {
let Some(o) = verify_src(name, src) else { return };
assert!(
!o.is_verified(),
"`m::Outer`'s layout is not in the source the scanner read, so a contract \
about its fields must be refused -- proving it means the crate-root \
`Outer`'s fields were read instead. Got: {o}"
);
}
}
#[test]
fn a_module_struct_on_its_own_lines_still_reads_its_fields() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
pub struct Outer { pub lo: u8, pub hi: u8 }
pub mod m {
pub struct Outer { pub hi: u8, pub lo: u8 }
}
spec! {
requires: o.hi == 5,
ensures: ret == 5,
}
pub fn reads_its_own_field(o: &m::Outer) -> u8 { o.hi }
"#;
let Some(o) = verify_src("reads_its_own_field", src) else { return };
assert!(
o.is_verified(),
"a module struct whose body is on its own lines has a real layout, so a true \
contract about it must verify. Got: {o}"
);
}
#[test]
fn a_unit_struct_runs_its_destructor() {
let src = r#"macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }
pub struct Guard;
impl Drop for Guard { fn drop(&mut self) {} }
spec! {
requires: true,
ensures: ret == 1,
}
pub fn unit_drop() -> u8 {
let _g = Guard;
1
}
pub struct Boom;
impl Drop for Boom { fn drop(&mut self) { panic!("boom"); } }
spec! {
requires: true,
ensures: ret == 1,
}
pub fn panics_on_drop() -> u8 {
let _g = Boom;
1
}
"#;
let Some(o) = verify_src("unit_drop", src) else { return };
assert!(
o.is_verified(),
"a unit struct with a no-op destructor must verify, got: {o}"
);
let Some(p) = verify_src("panics_on_drop", src) else { return };
assert!(
!p.is_verified(),
"a unit struct whose destructor panics must not verify, got: {p}"
);
}
}
#[test]
fn a_comment_before_a_clause_colon_is_whitespace_not_a_dropped_clause() {
let macros = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\n\n";
let true_src = format!("{macros}spec! {{\n requires/**/: n > 0,\n ensures/**/: ret == n,\n}}\npub fn f(n: u8) -> u8 {{ n }}\n");
let outcome = verify_src("f", &true_src).expect("the function must be reported");
assert!(
matches!(outcome, FnOutcome::Verified { .. }),
"a comment before the colon must not drop the clause, got: {outcome:?}"
);
let false_src = format!("{macros}spec! {{\n requires/**/: n > 0,\n ensures/**/: ret == n + 1,\n}}\npub fn g(n: u8) -> u8 {{ n }}\n");
let bad = verify_src("g", &false_src).expect("the function must be reported");
assert!(
matches!(bad, FnOutcome::Failed { .. }),
"a false postcondition behind a comment must still be refuted, got: {bad:?}"
);
}
#[test]
fn a_comment_and_a_non_ascii_name_cannot_smuggle_a_false_proof() {
let comment_src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\n\nspec! {\n requires: true,\n ensures: ret == n/**/as/**/u8,\n}\npub fn f(n: u8, nasu8: u8) -> u8 { let _ = n; nasu8 }\n";
let uni_src = "macro_rules! spec { ($($c:ident : $b:expr,)*) => {}; }\n\nspec! {\n requires: true,\n ensures: ret == \u{b5},\n}\npub fn g(\u{b5}: u8, \u{c2}\u{b5}: u8) -> u8 { let _ = \u{b5}; \u{c2}\u{b5} }\n";
for (name, src) in [("f", comment_src), ("g", uni_src)] {
let outcome = verify_src(name, src).expect("the function must be reported");
assert!(
matches!(outcome, FnOutcome::Failed { .. }),
"a clause naming a variable the body does not return must be refuted, got: {outcome:?}"
);
}
}