verif 0.1.1

In-code formal verification for Rust: an embedded bit-blasting SMT decision procedure, a symbolic DSL, contracts and a machine-checked proof kernel. SPARK-inspired, no_std, no external dependencies.
Documentation
// Differential oracle: the engine checked against Verus.
//
// The third backend, after `z3diff` (the exporter) and `kanidiff` (the engine, via Kani).
// Where Kani model-checks compiled MIR against CBMC, Verus translates Rust to Viper and
// discharges the proof obligations with SMT, using bit-vector reasoning for functions
// marked `#[verifier(bit_vector)]`. Two backends built on different foundations means a
// bug in one engine's blasting has to survive agreement with *both* -- a much narrower
// coincidence than either alone.
//
// The cases come from `examples/support/mod.rs`, shared with `kanidiff`, so this harness and
// the Kani harness are checking the same formulas rather than two drifting corpora.
//
// Verus is an oracle, not a dependency: the `verus` driver is invoked as a subprocess, and
// the crate still builds with zero dependencies. If Verus is absent the harness says so and
// exits non-zero; an oracle that did not run is not evidence.
//
// Verus is found via `$VERUS_BIN`, else `verus` on `PATH`. The official release ships a
// self-contained bundle (its own `z3` and a pinned rustc), so unpacking it and pointing
// `VERUS_BIN` at `verus-x86-linux/verus` is enough.

mod support;

use std::collections::BTreeSet;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use support::{Case, build_cases, tally_backend, tally_identities, verus_pred};

/// Where the Verus driver is.
fn verus_bin() -> String {
    std::env::var("VERUS_BIN").unwrap_or_else(|_| "verus".to_string())
}

fn verus_available() -> bool {
    Command::new(verus_bin())
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

/// Write the Verus source, returning the line number each case's `proof fn` starts on.
///
/// The line numbers are how a failure is mapped back to a case: Verus reports errors by
/// source location, and the enclosing case is the last one declared at or before the error
/// line. That is robust to the error pointing at the `ensures` clause, the body, or a
/// closing brace, all of which sit inside the same case.
fn write_source(path: &Path, cases: &[Case]) -> std::io::Result<Vec<usize>> {
    let mut src = String::from(
        "#![allow(unused)]\n\
         // Generated by examples/verusdiff.rs. Each proof fn is one predicate the engine\n\
         // proved; Verus must prove the same property.\n\
         use vstd::prelude::*;\n\n\
         verus! {\n\n\
         // The engine's shift rule: a shift by `k >= 8` is 0 (or the sign bit, for an\n\
         // arithmetic shift). Rust's `<<`/`>>` are not defined there, so spelling the\n\
         // engine's rule out is the only way to compare the same function.\n\
         spec fn shl_eng(x: u8, k: u32) -> u8 { if k >= 8 { 0 } else { x << k } }\n\
         spec fn lshr_eng(x: u8, k: u32) -> u8 { if k >= 8 { 0 } else { x >> k } }\n\
         spec fn ashr_eng(x: u8, k: u32) -> u8 { if k >= 8 { if x >= 0x80 { 0xff } else { 0 } } else { (((x as i8) >> k) as u8) } }\n\
         // Wrapping arithmetic. `bit_vector` rejects `wrapping_*` with a literal operand,\n\
         // and a constant like `255u8 * 255u8` is a rustc const-eval overflow error that\n\
         // aborts the run, so the wrap has to happen where the operands are already `int`.\n\
         spec fn add_eng(x: u8, y: u8) -> u8 { (x + y) as u8 }\n\
         spec fn sub_eng(x: u8, y: u8) -> u8 { (x - y) as u8 }\n\
         spec fn mul_eng(x: u8, y: u8) -> u8 { (x * y) as u8 }\n\n",
    );
    let mut lines = Vec::new();
    for (i, case) in cases.iter().enumerate() {
        let line_no = src.lines().count() + 1;
        lines.push(line_no);
        src.push_str(&format!(
            "#[verifier(bit_vector)]\nproof fn case_{i}(a: u8, b: u8, c: u8)\n    ensures {}\n{{\n}}\n\n",
            verus_pred(&case.ir)
        ));
    }
    src.push_str("fn main() {}\n\n}\n");
    fs::write(path, src)?;
    Ok(lines)
}

/// The outcome of one Verus run: the set of case indices it *refuted*, and whether the run
/// accounted for every case.
struct VerusRun {
    refuted: BTreeSet<usize>,
    error_lines: usize,
    unmapped_errors: usize,
    summary_verified: usize,
    summary_errors: usize,
    summary_present: bool,
}

/// Run Verus and map its error locations back to case indices.
fn run_verus(file: &Path, case_lines: &[usize]) -> std::io::Result<VerusRun> {
    let out = Command::new(verus_bin()).arg(file).output()?;
    let mut text = String::from_utf8_lossy(&out.stdout).into_owned();
    text.push('\n');
    text.push_str(&String::from_utf8_lossy(&out.stderr));

    let mut refuted = BTreeSet::new();
    let mut error_lines = 0usize;
    let mut unmapped_errors = 0usize;
    let mut summary_present = false;
    let mut summary_verified = 0usize;
    let mut summary_errors = 0usize;

    for line in text.lines() {
        let t = line.trim();
        if let Some(rest) = t.strip_prefix("verification results::") {
            // Shape: `verification results:: 35 verified, 23 errors`. The `verified` count
            // is *not* the number of proof fns that passed: it includes non-case items such
            // as `main`, which is why the accounting below does not compare it to the case
            // count directly.
            summary_present = true;
            for part in rest.split(',') {
                let words: Vec<&str> = part.split_whitespace().collect();
                if words.len() == 2 {
                    if let Ok(n) = words[0].parse::<usize>() {
                        if words[1].starts_with("verified") {
                            summary_verified += n;
                        } else if words[1].starts_with("error") {
                            summary_errors += n;
                        }
                    }
                }
            }
        }
        // Error locations look like `  --> cases.rs:214:7`. Take the last case declared at
        // or before that line: that is the case the error lives in.
        if let Some(rest) = t.strip_prefix("--> ") {
            error_lines += 1;
            let loc = rest.split_whitespace().next().unwrap_or("");
            let mut it = loc.rsplitn(3, ':');
            let _col = it.next();
            let mapped = it.next().and_then(|s| s.parse::<usize>().ok()).and_then(|line_no| {
                case_lines
                    .iter()
                    .enumerate()
                    .filter(|&(_, &l)| l <= line_no)
                    .map(|(i, _)| i)
                    .next_back()
            });
            match mapped {
                Some(i) => {
                    refuted.insert(i);
                }
                // An error before the first case declaration is a file-level problem
                // (a syntax error in the preamble, a rejected helper). It is not a case
                // being refuted, and treating it as one would silently drop a case.
                None => unmapped_errors += 1,
            }
        }
    }

    Ok(VerusRun {
        refuted,
        error_lines,
        unmapped_errors,
        summary_verified,
        summary_errors,
        summary_present,
    })
}

fn main() {
    if !verus_available() {
        eprintln!(
            "verusdiff: the `verus` driver is not available, so the oracle cannot run.\n\
             Set VERUS_BIN to the Verus release driver (e.g. verus-x86-linux/verus) and re-run.\n\
             An oracle that did not run is not evidence about the engine."
        );
        std::process::exit(2);
    }

    let cases_n: u32 = std::env::args().nth(1).and_then(|s| s.parse().ok()).unwrap_or(24);
    let cases = build_cases(cases_n);

    let tally = tally_identities(&cases, "verusdiff");
    let proved_by_engine = cases.iter().filter(|c| c.ours.is_proved()).count();

    let dir: PathBuf = std::env::temp_dir().join("verif_verusdiff");
    let _ = fs::remove_dir_all(&dir);
    if let Err(e) = fs::create_dir_all(&dir) {
        eprintln!("verusdiff: could not create {}: {e}", dir.display());
        std::process::exit(1);
    }
    let file = dir.join("cases.rs");
    let case_lines = match write_source(&file, &cases) {
        Ok(l) => l,
        Err(e) => {
            eprintln!("verusdiff: could not write {}: {e}", file.display());
            std::process::exit(1);
        }
    };

    let run = match run_verus(&file, &case_lines) {
        Ok(r) => r,
        Err(e) => {
            eprintln!("verusdiff: running verus failed: {e}");
            std::process::exit(1);
        }
    };

    // Verus must have accounted for every case. The check is on *error locations*, not on the
    // summary counts: `verification results:: 35 verified, 23 errors` counts non-case items
    // too (`main`, the helper functions), so `verified + errors == cases.len()` is simply
    // false and would fail every run. What must hold is that the number of error locations
    // matches the summary's error count and that every one of them maps to a case. An
    // unmapped error is a file-level problem (a rejected helper, a syntax error) that no
    // case verdict accounts for, and it must fail the sweep rather than vanish.
    let accounted = run.summary_present
        && run.unmapped_errors == 0
        && run.error_lines == run.summary_errors;
    if !accounted {
        eprintln!(
            "verusdiff: verus did not account for every case \
             (summary_present={} verified={} error_lines={} summary_errors={} unmapped_errors={} cases={}). \
             Treating all cases as missing.",
            run.summary_present,
            run.summary_verified,
            run.error_lines,
            run.summary_errors,
            run.unmapped_errors,
            cases.len()
        );
        println!(
            "cases={} proved_by_engine={} agree=0 mismatch=0 missing={} refuted_identity={} undecided_identity={} control_ok=false",
            cases.len(), proved_by_engine, cases.len(), tally.refuted, tally.undecided
        );
        std::process::exit(1);
    }

    let t = tally_backend(
        &cases,
        |case| {
            let i = cases.iter().position(|c| c.name == case.name).unwrap();
            Some(!run.refuted.contains(&i))
        },
        "verusdiff",
    );

    // The control: the engine must have refuted it and Verus must have failed it.
    let control_ok = {
        let i = cases.iter().position(|c| c.name == "NEGATIVE_CONTROL_sub_comm").unwrap();
        !cases[i].ours.is_proved() && run.refuted.contains(&i)
    };
    println!(
        "cases={} proved_by_engine={} agree={} mismatch={} missing={} refuted_identity={} undecided_identity={} control_ok={}",
        cases.len(), proved_by_engine, t.agree, t.mismatch, t.missing,
        tally.refuted, tally.undecided, control_ok
    );

    if t.mismatch > 0 || t.missing > 0 || tally.refuted > 0 || !control_ok {
        eprintln!(
            "verusdiff FAILED: mismatch={} missing={} refuted_identity={} control_ok={}",
            t.mismatch, t.missing, tally.refuted, control_ok
        );
        std::process::exit(1);
    }
}