# verif — formal verification that lives inside the Rust code
[](https://crates.io/crates/verif)
[](https://docs.rs/verif)
[](https://github.com/cipansor/verif/actions/workflows/ci.yml)
[](#license)
> An experiment: what if Rust could carry its own proof tooling the way
> SPARK/Ada carries `gnatprove`? Not a plugin, not an external solver, not a
> nightly feature — a **bit-blasting decision procedure compiled into your
> artifact**, next to a Curry–Howard proof kernel and a contract vocabulary.
> **Not affiliated with AdaCore or SPARK.** "SPARK" and "SPARK Pro" are
> AdaCore's; `gnatprove` is their tool. This crate is an independent experiment
> inspired by the *shape* of that workflow — contracts in the source, proofs
> discharged by a tool — and it embeds its own decision procedure rather than
> wrapping theirs. It is not a port, a wrapper, or a supported AdaCore product,
> and the name was chosen to describe what the crate *does*, not where it comes
> from.
`no_std`. Zero dependencies. Fixed-size, heap-free arena. `#![forbid(unsafe_op_in_unsafe_fn)]`.
```rust
use verif::prelude::*;
// ∀ x:u8. (x & 0x0f) < 16 — proved by the embedded SMT engine
let proved = verif::smt::with_fresh(|| {
let x = var(8);
(x & 0x0fu32).lt_val(16).prove().is_proved()
});
assert!(proved);
```
Run the flagship demo:
```console
$ cargo run --features std --example flight_control
[symbolic] map_reading output bound : valid (proved for all inputs)
[symbolic] rate_limit step bound : valid (proved for all inputs)
[exhaustive] clamp holds for all 65536 : true
[exhaustive] output in [PWM_MIN, PWM_MAX] : true
[exhaustive] rate limit for all u8 pairs : true
[exhaustive] mapping is monotone : true
[kernel] certificate accepted, value = 1500
[refuted] raw < ADC_MAX is false, witness raw = 4095
[honesty] (a*b)*c == a*(b*c) at 12 bits : unknown (no conclusion: budget exhausted, ill-formed query, or stale handle)
all obligations discharged
```
---
## Contents
**[Getting started](#installation)**
- [Installation](#installation)
- [The idea in one paragraph](#the-idea-in-one-paragraph)
- [The three ways this crate proves something](#the-three-ways-this-crate-proves-something)
- [What is in the box](#what-is-in-the-box)
- [Two ways to use the verifier: at build time, or on the target](#two-ways-to-use-the-verifier-at-build-time-or-on-the-target)
- [Building and testing](#building-and-testing)
- [Layout](#layout)
**[Proving a program](#verification-conditions-are-generated-not-hand-written)**
- [Verification conditions are generated, not hand-written](#verification-conditions-are-generated-not-hand-written)
- [Memory: `read`, `store`, and the frame condition](#memory-read-store-and-the-frame-condition)
- [Modular verification: procedures checked once, calls reasoned about through contracts](#modular-verification-procedures-checked-once-calls-reasoned-about-through-contracts)
- [Bounded quantification: the invariant a loop over memory needs](#bounded-quantification-the-invariant-a-loop-over-memory-needs)
- [Verifying real Rust: the MIR frontend](#verifying-real-rust-the-mir-frontend)
**[How the engine is held honest](#the-exported-query-must-mean-what-the-engine-proved)** — one section per claim, each naming the check that backs it
- [The exported query must mean what the engine proved](#the-exported-query-must-mean-what-the-engine-proved)
- [Substitution must not walk a shift amount](#substitution-must-not-walk-a-shift-amount)
- [A DSL's operator set is a claim too](#a-dsls-operator-set-is-a-claim-too)
- [Constant operands are folded, so a closed query is decided rather than refused](#constant-operands-are-folded-so-a-closed-query-is-decided-rather-than-refused)
- [A pin is transitive, and a closed goal is decided without its assumption](#a-pin-is-transitive-and-a-closed-goal-is-decided-without-its-assumption)
- [A division by a power of two is a shift, on both signs](#a-division-by-a-power-of-two-is-a-shift-on-both-signs)
- [Mixed-width operations are refused, not truncated](#mixed-width-operations-are-refused-not-truncated)
- [Differential fuzzing: the shapes I did not think to test](#differential-fuzzing-the-shapes-i-did-not-think-to-test)
- [The blasting is checked against Rust, not against itself](#the-blasting-is-checked-against-rust-not-against-itself)
- [Staleness is caught once, in the arena](#staleness-is-caught-once-in-the-arena)
- [A proof object must not change meaning underneath you](#a-proof-object-must-not-change-meaning-underneath-you)
- [A wrapper must not overclaim](#a-wrapper-must-not-overclaim)
- [A truncated witness has to say so](#a-truncated-witness-has-to-say-so)
- [A negative answer has to say what it swept](#a-negative-answer-has-to-say-what-it-swept)
- [An unreachable precondition is not a proof](#an-unreachable-precondition-is-not-a-proof)
- [A diverging call is a checked panic, not a dropped line](#a-diverging-call-is-a-checked-panic-not-a-dropped-line)
- [A `drop` is a terminator with a real successor](#a-drop-is-a-terminator-with-a-real-successor)
- [A bound must be wider than the address, or "all cells" is vacuous](#a-bound-must-be-wider-than-the-address-or-all-cells-is-vacuous)
- [The memory family, positive side](#the-memory-family-positive-side)
- [The differential harness now covers memory](#the-differential-harness-now-covers-memory)
- [A guard compares an index, it does not truncate it](#a-guard-compares-an-index-it-does-not-truncate-it)
- [A derived frame says whether it is complete](#a-derived-frame-says-whether-it-is-complete)
- [The obligation cap fails loudly, never silently](#the-obligation-cap-fails-loudly-never-silently)
- [Differential testing: a proof must not outrun reality](#differential-testing-a-proof-must-not-outrun-reality)
**[Design notes](#why-bdds-at-all)**
- [Why BDDs at all](#why-bdds-at-all)
**[Where this sits](#where-this-sits-in-the-rust-ecosystem)**
- [Where this sits in the Rust ecosystem](#where-this-sits-in-the-rust-ecosystem)
- [The SPARK comparison, stated plainly](#the-spark-comparison-stated-plainly)
- [What this is *not* — read this before trusting a green test](#what-this-is-not--read-this-before-trusting-a-green-test)
- [Documentation](#documentation)
- [License](#license)
**The open work** lives in [`ROADMAP.md`](ROADMAP.md) — one item per gap, each with
a priority, a measurable exit criterion, the competitor whose gap it closes, the
closing move (build / bridge / won't do), and a status. A PR that closes an item
updates its status there.
---
## Installation
Both crates are on crates.io. `verif` is the one you depend on; the proved
integer primitives it builds on are published separately as
[`verif-arithmetic`](https://crates.io/crates/verif-arithmetic) and pulled in for
you.
```toml
[dependencies]
verif = "0.1"
# The host-side tools (the MIR frontend, the file-backed helpers) need `std`.
# The engine itself does not: the default build is `no_std` and links `core`
# and nothing else, which is what a bare-metal safety build wants.
[dev-dependencies]
verif = { version = "0.1", features = ["std"] }
```
There is nothing else to add: `verif`'s only dependency is `verif-arithmetic`,
which is itself `no_std` and dependency-free, so the artifact's crates.io supply
chain is those two crates and no third party.
Building for a microcontroller:
```console
$ cargo build --target thumbv7em-none-eabihf
```
---
## The idea in one paragraph
SPARK's advantage is not that Ada is a better language. It is that **the prover
is part of the toolchain and the contracts are part of the source**. Rust has a
superb type system and no such prover, so verification is outsourced to external
tools (Kani, Creusot, Prusti, MIRAI) that you must install, configure, and trust.
This crate asks what happens if you instead *compile the prover in*: lower
bit-vector formulas to **Reduced Ordered Binary Decision Diagrams**, which are a
canonical form, so two formulas are equivalent exactly when their diagrams are
the *same node*. That one property yields, with no external process:
| `prove(p)` | `p` holds for every input (diagram is the `true` node) |
| `find_model(p)` | a concrete satisfying input, or `Unsat` |
| `prove_implies(pre, post)` | `pre => post` holds for every input |
| `prove_equiv(a, b)` | `a` and `b` are equivalent for every input |
## The three ways this crate proves something
They are deliberately different tools, and each has a different honesty profile.
| 1 | **Symbolic** — BDD, then CDCL SAT fallback | `smt::prove`, `sym::*::prove()` | no (scaling wall) | no — it returns `Unknown` |
| 2 | **Exhaustive** — every input of a real `fn` | `exhaustive::for_all_u8/u16` | yes, small domains | no |
| 3 | **Type-level** — Curry–Howard kernel | `proof::Certificate`, `assert_proof!` | yes, for composition | no — it will not compile |
A serious safety argument uses all three and says which one discharged each
obligation. That is what `examples/flight_control.rs` demonstrates.
## What is in the box
The engine is three modules (`smt`, `bitblast`, `sat`); the rest are the
specification surface, the complete-by-enumeration half, and interop.
| `smt` | Bit-vector terms, ROBDD engine, `Verdict`, counterexamples, `no_std` arena |
| `bitblast` | The bit-level term graph → CNF lowering, used by the SAT fallback |
| `sat` | The CDCL SAT solver used as the fallback past the BDD wall |
| `sym` | Operator overloading so specs read like code: `(x + y).eq(y + x).prove()` |
| `logic` | Checked/saturating arithmetic and a Q16.16 `Fixed` type, each with proofs |
| `proof` | Curry–Howard kernel (`Truth`, `And`, `Imp`, `Equals`) + composable `Certificate` |
| `contract` | Runtime `Pre`/`Post`/`Assert` over concrete values, structured errors |
| `vc` | `requires`/`ensures`/`invariant`, `verify_body`, `Verified<T>` |
| `wp` | Hoare logic: weakest preconditions, automatic VC generation, loop rules, termination by variant |
| `smtscript` | SMT-LIB2 export, so an external solver can check the same formula |
| `mem` | Bounded symbolic memory: `read`/`store`, frame condition, composes with `wp` |
| `quant` | Bounded `forall`/`exists`, expanded into finite conjunctions/disjunctions |
| `exhaustive` | Complete proofs by enumeration over `u8`/`u16` |
| `primitives` | The symbolic oracle for the `safe_*` ops and `Bounded` (the runtime half is `arith`) |
| `arith` (sibling crate) | `verif-arithmetic`, re-exported: total integer ops and a refinement-typed `Bounded<MIN, MAX>`, each proved by enumeration |
| `macros` | `verify!`, `verify_implies!`, `contract!`, `proof!`, `assert_proof!`, `check!`, `verify_exhaustive!` |
| `mir` (`std` only) | verify **real Rust**: read `rustc`'s own MIR, symbolically execute it, discharge rustc's overflow/underflow/div-by-zero asserts and doc-comment contracts |
The proved runtime primitives live in the sibling crate and are re-exported as
`verif::arith`, so a caller never has to name the workspace layout. `arith` is
`no_std`, `#![forbid(unsafe_code)]` and dependency-free on its own — that split
is what keeps the arithmetic a safety build ships down to `core` and nothing
else, while this crate keeps the symbolic engine that cross-checks those proofs.
## Verification conditions are generated, not hand-written
`vc` lets you write an obligation by hand. `wp` derives it from the program, which
is the part that actually feels like SPARK: you state `requires` and `ensures`,
describe the body, and read a verdict *per rule*.
```rust
use verif::prelude::*;
use verif::smt::{self, var};
use verif::wp::{self, Stmt};
let report = smt::with_fresh(|| {
let sum = var(4);
let i = var(4);
let n = var(4);
let step = var(4);
let pre = smt::and(n.le_val(3), step.le_val(3)); // requires
let init_sum = Stmt::Assign { var: sum, expr: smt::word(0, 4) };
let init_i = Stmt::Assign { var: i, expr: smt::word(0, 4) };
let bump_sum = Stmt::Assign { var: sum, expr: sum + step };
let bump_i = Stmt::Assign { var: i, expr: i + 1u32 };
let body = Stmt::Seq { first: &bump_sum, second: &bump_i };
// The invariant carries the arithmetic link; this is the human's job.
let inv = smt::and(i.le(n), sum.eq(smt::mul(i, step)));
let loop_ = Stmt::While { cond: i.lt(n), invariant: inv, body: &body };
let prog = Stmt::Seq {
first: &init_sum,
second: &Stmt::Seq { first: &init_i, second: &loop_ },
};
wp::verify(&prog, pre, sum.le(smt::mul(n, step))) // ensures
});
for ob in report.obligations.iter().flatten() {
println!("{:?}: {}", ob.rule, ob.discharge()); // LoopPreserve: valid
} // LoopExit: valid
assert!(report.is_verified());
```
Run it: `cargo run --features std --example pipeline`.
Three things about `wp` are worth knowing, because each is a place where a naive
implementation quietly proves the wrong thing:
1. **The walk starts at the postcondition.** Backward from `post`, through the
body, to a weakest precondition; the contract is `pre => wp(body, post)`.
Starting from `pre` instead yields a vacuous condition that "verifies" almost
anything.
2. **Loop obligations are universally quantified over the loop-head state.** They
are recorded in loop-head terms and *not* rewritten by the assignments that
dominate the loop. Rewriting them makes them trivially true whenever the
initialisation pins the variables, which turns a broken invariant green.
Assertions are the opposite: they are checked where control reaches them, so
the dominating assignments *do* apply.
3. **Termination is proved separately, by a variant.** Hoare logic alone says
"correct if it exits". Give the loop a `variant` and its progress is proved
too, which upgrades the result from partial to total correctness.
### Termination: give the loop a variant
A `variant` is an expression in loop-head terms that must strictly decrease each
iteration. For an unsigned measure, `I && c => V' < V` is the whole rule: a
strictly decreasing sequence in a well-founded order cannot be infinite.
```rust
let loop_ = Stmt::While {
cond: i.lt_val(10),
invariant: i.le_val(10),
variant: Some(smt::sub(smt::word(10, 8), i)), // 10 - i decreases by one
body: &step,
};
```
The value *after* one iteration is computed by symbolic evaluation of the body, so
you write the measure once, not twice. Through an `if` it becomes
`ite(cond, then_value, else_value)`; through a sequence it composes in execution
order. That is what makes a conditional body work without extra annotation:
```rust
// while i < 10 { if i < 5 { i := i + 2 } else { i := i + 1 } }
// V' is derived as ite(i < 5, 10 - (i + 2), 10 - (i + 1))
```
Because the measure is a bit-vector expression evaluated with wrapping, a measure
that wraps around is caught rather than silently accepted. Take the divergent loop
from `tests/wp.rs`, `while i != 0 { i := i + 2 }`: claim `variant: i` and the
obligation is refuted, because from `i == 253` the next value is `255`, which is
larger. The variant rule is what turns "this loop does not terminate" from a
comment into a failed proof obligation.
`Report::correctness()` tells you which claim you actually got:
```rust
assert_eq!(report.correctness(), Correctness::Total); // every loop has a variant
assert_eq!(report.correctness(), Correctness::Partial); // some loop does not
```
`Total` requires *every* loop to carry a variant. One unannotated loop makes the
whole report `Partial`, which is why the classification compares the number of
loops against the number of variants rather than checking that a variant exists
somewhere.
A report can be `Total` and still `!is_verified()`: the two questions — does it
terminate, and does it meet its contract — are answered independently.
### Why `variant_after` must havoc a nested loop
The variant obligation is `I && guard => V' < V`, where `V'` is the measure evaluated
after one iteration of the body. The whole proof rests on `V'` being the measure's *real*
value after that iteration, so `variant_after` must model the body's effect on the measure
faithfully. For an assignment, a sequence, or a conditional that is substitution and
`ite`. For a nested loop it is harder, because the loop runs an unknown number of times.
The first version read a nested `while` as a no-op — the measure "survives" it. That is
false whenever the inner body writes a variable the measure reads, and it is false in the
worst possible direction. Consider:
```text
while i < 100 {
i := i + 1;
while i != 0 { i := 0 } // resets i every outer iteration
}
```
This diverges. But with the inner loop read as a no-op, the outer obligation became
`100 - (i + 1) < 100 - i`, which is a tautology — so the engine returned `Valid` and the
report claimed `Total` for a program that never halts. A termination proof for a divergent
program is precisely the claim this crate exists to make honestly, so this is the worst
class of defect in it: not a missing proof, but a wrong one.
The fix is to havoc exactly the variables the inner body can write, since after the inner
loop each holds the result of applying the body some unknown number of times. A measure
that mentions one of them then reduces to a fresh variable and cannot be discharged, which
is the honest answer — the caller must supply a measure the inner loop cannot disturb, or
one that accounts for it. A measure that mentions none of them survives untouched, so the
common nested shape (an inner scan over `j` under an outer counter `i`) still proves.
`writes` supplies the write set; when it is incomplete, the effect is unknown outright
rather than under-approximated.
Two tests pin this: `a_nested_loop_cannot_make_the_outer_variant_look_healthy` (the
divergent program above must be refuted) and
`a_nested_loop_that_leaves_the_measure_alone_still_proves` (the sound nested shape must
still verify). Reverting the fix fails the first and leaves the second passing, which is
the signature of a soundness fix rather than a tightened heuristic.
### When the engine says `Unknown`, hand the formula to a solver
`smtscript` prints the *same* formula the engine reasoned about as SMT-LIB2, with
variables declared and the goal negated, so `unsat` from any compliant solver is a
proof:
```rust
let vars = [sum, i, n, step];
let q = Query::new(&vars, report.contract.goal);
println!("{}", q.to_smtlib2());
```
```text
(set-logic QF_BV)
(declare-fun x0_4 () (_ BitVec 4))
...
(assert (not (bvor ... )))
(check-sat)
(get-model)
```
Independence matters for a safety argument: a proof reproduced by a *different*
tool from a textual artifact is stronger evidence than one produced by the same
code that generated the obligation. The exporter needs no `std` — it writes into
any `core::fmt::Write`, including a fixed buffer on bare metal.
## Memory: `read`, `store`, and the frame condition
Bit-vector logic cannot say "this array element is unchanged". `mem` adds the one
theory that matters most for safety-critical code, without touching the decision
procedure: a memory of `2^addr_width` cells, each cell an ordinary symbolic word.
```rust
use verif::mem::{declare, Mem};
smt::with_fresh(|| {
let mut buf = [var(8); 4];
let n = declare(2, 8, &mut buf); // 4 cells, 8 bits each
let m = Mem::new(&buf[..n], 8);
let addr = var(2);
let val = var(8);
let at = var(2);
// The frame condition, proved for every address and value.
assert_eq!(smt::prove(m.frame_lemma(addr, val, at)), Verdict::Valid);
// A write, then a read back.
let readback = m.store_wp(addr, val, smt::eq(m.read(addr), val));
assert_eq!(smt::prove(readback), Verdict::Valid);
});
```
Run it: `cargo run --features std --example memory`.
Reading at a *concrete* address is a slice index. Reading at a *symbolic* address
is an ite chain, `ite(a == 0, m[0], ite(a == 1, m[1], ...))`. Because the address
has exactly `addr_width` bits, every value names exactly one cell: the encoding is
exact, with no default cell and no aliasing.
Writing is not mutation. `store(m, a, v)` is a *simultaneous* update of every
cell, `m'[k] = ite(a == k, v, m[k])`, produced by `Mem::store_binds`. That is the
same mechanism `wp` uses for assignment, which is why a memory write slots into
verification-condition generation with no new machinery — hand the bindings to
`Stmt::AssignMany` and the write becomes part of the program the engine reasons
about.
Two consequences are worth stating, because they are where people trip:
1. **The frame condition is a theorem, not a chore.** "A write to `a` leaves `b`
alone" follows from `frame_lemma` rather than needing to be re-stated at every
call site.
2. **Old values must be captured explicitly.** A postcondition is evaluated in the
final state, and substitution rewrites every cell variable in it, so
`m.read(i)` written directly in a postcondition means the *new* contents. To
talk about the old contents you assign them to fresh variables first — the same
discipline as SPARK's `m'Old`. `tests/mem.rs` verifies a swap this way.
### The memory limit, stated plainly
Bounds are *structural*: an address is `addr_width` bits, so it cannot name a cell
outside the memory. Out-of-range access is unrepresentable rather than proved
absent, which is a strong guarantee — but it means you must size the memory to the
largest address the real code can produce, and if that is not known, this is the
wrong tool.
A loop over addresses (`for k in 0..n { m[k] := 0 }`) *is* verifiable, because
its invariant needs a quantifier and bounded quantifiers can be expanded — see the
next section.
Cost: a symbolic read is `2^addr_width` ites and the BDD sees all of them, so
`MAX_CELLS` caps a memory at 64 cells (6 address bits).
The smallest memory is *two* cells, not one. A single cell is a power of two, so `new`
used to accept it — but then `addr_width()` is 0, and no `Var` can be zero bits wide, so
there was no address type with which to read or write it. `new` now refuses it, matching
`declare`, whose `addr_width` is already `1..=MAX_ADDR_WIDTH`. `a_single_cell_memory_is_refused`
pins it.
## The exported query must mean what the engine proved
The SMT-LIB export exists so an independent solver can reproduce a proof from a textual
artifact. That is only worth anything if the artifact says the same thing the engine said,
and twice it did not.
A boolean is a one-bit word here, so the printer has to coerce one to the other. The coercion
printed `(= w (_ bv0 1))` while its own comment said `w != 0` — the negation. A constant goal
came out inverted: `truth(false)` was written as `(assert false)`, which every solver reports
`unsat`, so an external checker would have called an impossible obligation *proved*. The
spelling of `!=` is `distinct`.
The operator choice was wrong too. `not`, `and`, `or` and `xor` exist in both readings, and
the printer always used the bit-vector one, so `not(x == y)` became `(bvnot (= x y))` —
ill-sorted, since `bvnot` wants a bit-vector and a comparison is a boolean. A solver rejects
that file, and a lenient one reads something else.
The first fix made the *node's own width* decide: at width 1 the boolean operator, above it the
bit-vector one. That is still wrong, because a one-bit connective's sort depends on **where it
sits**, not on how wide it is. As the goal, `x & y == 1` wants `and`; as an operand of `bvadd` it
wants `bvand`, and `Bool` is not `(_ BitVec 1)`. The width rule emitted `(bvule (_ bv1 1) (or …))`,
which z3 rejects as ill-sorted. The sort now decides: `Bool` prints comparisons natively and
one-bit connectives as `and`/`or`/`xor`/`not`; `Bits` prints comparisons as
`(ite <cmp> (_ bv1 1) (_ bv0 1))` and one-bit connectives as `bvand`/`bvor`/`bvxor`/`bvnot`.
`examples/z3diff.rs` is the harness that settles this rather than an argument. It generates random
predicates over 1-, 2-, 3-, 4-, 8- and 12-bit variables, with arithmetic, bitwise ops, shifts
(including over-shifts), `truncate` in both directions, and `ite`; asks the engine; exports the
same predicate; and asks z3. Measured with the current harness: 800 predicates — 0 parse errors,
0 disagreements, 25 refused, 0 undecided; 3000 predicates — 0 parse errors, 0 disagreements,
97 refused, 0 undecided.
The random sweep alone was not enough, and the way it fell short is the point. It compares only
sat/unsat, and a random predicate over free variables is essentially never a tautology, so a
well-sorted *semantic* printer bug is invisible to it: changing the exporter's `Op::Sub` to print
`bvadd` instead of `bvsub` left it at `mismatch=0`, even though `bvsub` appeared in 39 of the 800
exports and every one was decided. The operator was exercised on every run and never *checked*.
So the harness also carries a corpus of 42 *tautologies by construction* (`sub.self` is
`x - x == 0`, `mul.one` is `x * 1 == x`, `shl.nibble` is `0x0f << 4 == 0xf0`, and so on, one or
more per operator), each chosen so that at least one plausible mutation of the operator it names
breaks the identity. The export asserts `(not p)`, so z3 must answer `unsat`; a wrong operator
makes it `sat`. That is the dual of the random sweep and the only shape sensitive to a change that
preserves satisfiability. Measured: 42 identities, 0 mismatches. Teeth verified by mutating the
printer — `bvsub`→`bvadd`, `bvmul`→`bvadd`, `bvand`→`bvor`, `bvshl`→`bvlshr`, `bvxor`→`bvor`, and
widening `zero_extend`→`sign_extend` each make the harness exit 1 with the failing identity named.
"Refused" means the engine answered `Unknown` (typically a mixed-width term) and the exporter
declined to write a query for it, so there is nothing for z3 to contradict. "Undecided" is the
other way an `Unknown` can arise: the export *is* well formed, but the engine gave no verdict, so
z3 is never asked. It is counted separately rather than folded into the agreement count, because a
case z3 never saw is not a case z3 agreed with; it is 0 at both sizes. With the width-based
printing rule restored the same harness gets 21 of 800 rejected outright by z3 as ill-sorted. The
harness needs `z3-solver` installed; it is a development tool and the crate itself still has no
dependencies.
The harness also *fails* when it should. It exits 2 if the `z3` module is not importable, and
exits 1 on any disagreement or any file z3 refuses, printing the failing query. That matters
because the first version could not fail at all: it folded "the oracle is not installed" and "z3
rejected the file we printed" into the same `parse_err` tally and exited 0 either way, so a
broken exporter and a missing dependency produced the same green-looking line. A check that
cannot fail is not evidence.
The harness also has to be run against the *defect* to be worth anything: an oracle that passes
both with and without the fix proves nothing, and the classification has to be right. My first
version called `prove(p) == Unsat` a disagreement with z3's `sat`; it is not, since `prove`
answers `Unsat` when `p` is identically false, which is a tautology failure like any
counterexample. `Unknown` on our side is likewise never a disagreement — the engine is allowed to
be conservative, and z3 deciding is a stronger result, not a conflict.
This bug is worth the space because of how it hid. The engine was right the whole time — every
verdict it returned was correct. Only the *text* was wrong, so nothing in the crate's own tests
could see it, and the unit tests had been asserting the ill-sorted shape and passing. It took
handing the artifact to a different solver to notice that the artifact did not say what the
engine meant.
A third export bug sat in the same printer. `truncate` changes a width in either direction,
and the printer emitted `((_ extract w-1 0) x)` for both. That is only valid when the result is
no wider than the source; for a *widening* `truncate` it produced `((_ extract 15 0) x0_8)` —
extracting bit 15 from an 8-bit vector, which no solver accepts. Widening is `zero_extend`, and
the source width now decides which form is printed.
A fourth was not a printing bug at all, which is why it took longest to see. The engine
*refuses* a mixed-width operation — it returns `Unknown` and sets an internal flag — but the
term still exists, and the exporter printed its tree. So a query the engine had already
declined to decide was written out as `(bvadd x0_12 x1_8)`, which z3 rejects as ill-sorted.
The export is the artifact whose whole purpose is independent checking, and it was the one
thing that could not be checked: a reviewer would see a file that failed to load and read it
as a broken proof rather than a refused term.
The fix is that the export consults the same flag the engine does. `smt::is_ill_formed` is
public for exactly this reason, and a refused query writes a comment saying so and no
`(check-sat)` — there is no formula to hand to a solver, and pretending otherwise is worse
than saying nothing. `the_export_refuses_an_ill_formed_term_instead_of_printing_it` pins both
halves, and `a_well_formed_query_is_still_exported_in_full` is the control, so the refusal
cannot silently widen into refusing everything.
This is the general shape to watch for: a refusal that lives in the *engine* but not in the
*artifact*. The engine and the printer share a term representation, not a decision, so every
refusal has to be re-applied on the printing side, and only a test on the printed text can
show that it was.
## Substitution must not walk a shift amount
A shift node stores its amount in the same field every other binary node uses for a term id.
`subst` walked that field regardless, so substituting through `x << 3` recursed into whatever
term happened to have id 3. When that term contained the shift itself, the recursion never
bottomed out: `wp` on a two-line program blew the stack. When it did not, the walk still
touched an unrelated term, so a stale or oversized id there could flip the `stale` flag and
turn a provable goal into `Unknown`.
The differential test over the weakest-precondition transformer found it. It generates random
straight-line and branching programs, evaluates the generated `wp` at every one of the 256
inputs, and compares against running the same program concretely — exhaustive, and it does not
depend on the BDD engine at all. The fix skips the payload field for `Trunc` and the three
shifts, which the rebuild already carries across.
## A DSL's operator set is a claim too
The whole point of `sym` is that a specification reads like the expression it describes, so a
gap in it is not cosmetic. The literal-operator impls covered `x + 1u32`, `x * 2u32`,
`x & 0xffu32` and `x | 1u32` — but not `x - 1u32` or `x ^ 0xffu32`, which were compile errors.
Nothing about the four that worked tells you the other two are missing; a user has to discover
it by failing to compile, and a reader of the module cannot see the asymmetry at all.
Subtraction and XOR by a constant are as natural as addition and AND, so all six are now
provided, and `tests/sym.rs` pins each one against the `smt` primitive it is defined as. The
same file's teeth: it also asserts the six are *different* from one another, so a future edit
that wires every literal operator to `add` fails rather than passing six consistent
identities. (The DSL had no test file before this, which is how the gap survived.)
## Constant operands are folded, so a closed query is decided rather than refused
A verifier reading real code meets a literal on almost every operation: a scaled index
(`i * 4`), a masked flag (`x & 0xff`), a remainder by a literal (`n % 10`), and — the case
that found this — a *dividend pinned to a literal by a precondition*. The engine used to
build the full circuit for each of those and then refuse the query for the size of its own
diagram. The measurement that makes the point is a query with no symbolic input at all:
under `requires: a == -7`, `a / 3 == -2` at `i64` came back `Unknown` in ~1.1 s, because the
64-bit divider was blasted and walked before anyone looked at the constant.
Operations whose operands are both literals now fold to the literal they denote — the word
operations, the comparisons, and the divider itself. The same closed query is `Valid` in
0.000 s, and its term count falls from 660 to 5.
Two folds are deliberately withheld, and each is a way to get a *wrong verdict* rather than
a slow one, because the term arena is hash-consed and a fold that lands on an existing node
does not just shorten the term — it *merges* two nodes the frontend needs to tell apart:
- `0 - x` stays a `Sub` node. There is no unary negation in the term language, so a frontend
spells one that way, and it distinguishes `-128` (legal for an `i8`) from the bare literal
`128` (illegal) by the node's shape. Both are the same eight bits. Folding merged them and
refused valid `y == -128` contracts.
- `truncate` does not fold a literal. A *named* bound (`i8::MIN`) is spelled
`truncate(word(k, 64), w)` precisely so it does not hash-cons with `word(k, w)`. Folding
made the bound inherit `128i8`'s out-of-range envelope and refused `y == i8::MIN`.
The corpus caught both. That is the reason `examples/mir_targets/realistic.rs` exists: a fold
is not a neutral optimisation, and the coverage baseline is what says so.
## A pin is transitive, and a closed goal is decided without its assumption
A precondition that fixes a variable is what makes a query with a wide divider decidable at
all: `requires: a == 5` seeds `a` with the literal `5`, the body's operations fold, and the
obligation is a fact about numbers rather than a circuit. The pin extraction used to be one
pass, so it only saw a right-hand side that was closed on its own. `a == 5 && b == a + 1`
left `b` symbolic, because `a + 1` does not evaluate until `a`'s pin exists — and the chain
`a == 5 && b == a + 1 && c == b * 2` lost every link past the first.
The extraction now runs to a *fixpoint*: each round re-scans the conjuncts with the pins
found so far in scope, and a round that adds nothing ends it. Every pin is still a
consequence of the precondition by transitivity — `b == a + 1` *and* `a == 5` are both
conjuncts — so nothing is assumed beside `p`, and a value the conjuncts do not force stays
unpinned.
That closed the pin list but not the obligation. With `a`, `b`, `c` all pinned, the body
`c / 4` folds to the literal `3` and the goal becomes the closed fact `12 / 4 == 3`, which
the engine decides by evaluation in microseconds. `prove_implies` nevertheless built
`!pre || post` first, and `pre` still carried `c == b * 2` — a 64-bit multiply whose diagram
is refused for its own size. The query came back `Unknown` with a *trivial* goal.
So `prove_implies` now checks the goal on its own before it builds the implication: a closed
term that evaluates to true is a theorem unconditionally, whatever the assumption says, and
the check is a walk over the goal's own (small) DAG. The assumption is not weakened — the
path condition is untouched, so the ordinary route still sees it and nothing that used to be
decided by the diagram is lost. The corpus confirms the direction: `realistic.rs` stays at
264 of 490, with zero function changing verdict in either direction, and the
`a == 5 && b == a + 1 && c == b * 2` with body `c / 4` moves from `incomplete` to `verified`.
## A division by a power of two is a shift, on both signs
The restoring divider is exact, and exact is expensive: the term it builds is ~`2 * w` deep,
so an obligation that reads a *symbolic* dividend through it is refused for the size of its
own diagram rather than for anything about the property. The shapes that pay for this are
the ordinary ones — `n / 4`, `i / 8`, `x % 16` — where the divisor is a literal power of two
and the identity is elementary.
The signed case came first, because the *signed* divider is the worse of the two: its sign
fixup negates and selects on a 64-bit value whose bits are the divider's symbolic output,
and that is the shape that blows the diagram up. `sdiv(x, 2)` took 9.3 seconds against 47ms
for `udiv(x, 2)`, so `a / 2` on an `i64` was `incomplete`. Dividing by `2^k` needs no
divider at all: on the positive side it is a shift, and on the negative side it is a shift
after adding `2^k - 1`, which turns truncation toward zero into a floor. The bias is that
constant masked by the sign, and the sign mask is the sign bit replicated — one arithmetic
shift.
The unsigned case looked like the cheap one and was left alone, which was wrong in a way
the corpus could not show: the general unsigned divider is *not* the signed one's wall, but
it is still a `2 * w`-deep term, and a symbolic dividend through it is refused all the same.
`requires: n <= 1000; n / 4` at `u64` was `incomplete` in 0.9 s while the *signed* twin of
the same body was already decided. The unsigned identity is the simplest of the four: `x /
2^k` is `x >> k` and `x % 2^k` is `x & (2^k - 1)`, two operators and no fixup.
Both fast paths are guarded to `d >= 2` and a divisor that fits below the width. `d == 1`
is deliberately left to the general path — the guard then reads the same on both sides — and
`d == 0` never reaches either, so the general divider's *defined* zero case (all-ones
quotient, dividend remainder) is the one that still answers. Neither path can shadow it.
The tests are two-level, and the second level is the one that matters. A concrete sweep
walks every dividend at a width where the whole domain fits, against Rust's own `/` and `%`.
Then the engine is asked to prove the shift-and-mask expression *equal to the general
divider* with `x` free — that is the property a splice into a body depends on, and it is a
statement about all inputs rather than about the ones the sweep happened to try. The signed
sweep includes the negatives, since the bias and the negation exist for exactly those.
## Mixed-width operations are refused, not truncated
A bit-vector operation has no natural width when its operands disagree. The engine used to
take the *left* operand's width and truncate the right one silently. Fuzzing the predicate
layer found what that costs: `trunc2(b) + (a + 115)` was computed in two bits, so the
right-hand sum was masked to `y & 3`, the sum came out 2 instead of 142, and a predicate that
is false at `(a, b) = (27, 144)` read as `Valid`. That is a proof of a false statement, found
by a random predicate rather than by a test I would have written.
The crate has no widening operation, so the honest answer is to refuse the term. Every
binary operation — arithmetic, bitwise, comparison — and both branches of `ite` now check
that their operands agree in width. When they do not, the query returns `Unknown`, the same
way it does after an arena overflow or a stale handle. It never returns a wrong `Valid`.
This is a behavioural change, and a deliberate one: a term that used to be silently truncated
is now refused. The remedy at a call site is to write the intended width with `truncate`,
which makes the intent visible where the truncation happens rather than in the middle of an
arithmetic expression.
## Differential fuzzing: the shapes I did not think to test
The fixed harnesses check the cases I wrote down. A fuzzer checks the ones I did not: random
expression trees over two 8-bit variables, each proved symbolically and compared against
enumeration over all 65 536 inputs. `Valid` when enumeration finds a violation, a witness
that does not violate, or `Unsat` for a satisfiable equation are all failures. The seed is
fixed, so a failure is reproducible.
It found a bug in the *test*, not the engine. The oracle used Rust's `wrapping_shl`, which
masks the shift count by the width — `x << 8` on a `u8` is `x` — while this crate's
documented semantics is that a shift by at least the width yields zero. The engine was
right; the oracle was wrong. That is worth stating plainly: a differential test only says
what its oracle says, and the first oracle here was wrong.
The teeth are real. Making the BDD `Xor` arm behave like `And` makes the fuzzer report
`(!b) == b` as `Valid`, which it is not. That mutation was applied, observed, and reverted.
## The blasting is checked against Rust, not against itself
The differential harness compared whole predicates at eight bits. Above four bits `mul`
exhausts the BDD budget and `prove` returns `Unknown`, so the *blasting* of `mul` — the part
that decides proofs — had never been exercised by a passing test. Only its evaluation had.
A bug in that arm would be unsound, and nothing would have caught it.
Every operation is now checked at widths the BDD can finish, with Rust's own wrapping
arithmetic as the oracle: `add`, `sub`, `mul`, `and`, `or`, `xor`, all three shifts,
`ult`/`ule`/`eq`, and `truncate`. Each equation is routed through `prove`, so the blast arm
runs, and a deliberately wrong equation is asserted *not* to be proved, so an engine that
proved everything would fail.
Writing this found a hole in the test itself: the first version checked shifts through
`evaluate`, which exercises `eval_term` and not `blast`. A mutation to the BDD shift arm
passed. Routing through `prove` with a concrete constant catches it, and that is verified by
mutation rather than assumed.
## Staleness is caught once, in the arena
Stamping proof objects with an arena generation raised the obvious follow-up: what *else*
carries a term id? `Var`, `Pred`, `Mem`, `Query` — none of them stamped. Reusing one after a
reset did not fail cleanly. It overflowed the stack, exactly as the `with_fresh` comment had
always said it would:
```
use-after-free in the term arena ... typically shows up as unbounded recursion
rather than a clean panic
```
The comment was right, and had been right for several rounds while I read past it. It
described the *symptom* rather than the *invariant*, so it read like documentation of
intended behaviour instead of a bug report about a missing check.
Stamping each type would be whack-a-mole, and the next type would forget. Instead every term
id records the generation that created it, the term accessors note a mismatch, and the
traversals refuse to descend into a stale handle. One check covers every handle-carrying type
at once, and a query that touches a stale handle returns `Unknown`.
The subtlety that took two attempts: checking the *current* node is not enough. A constructor
can read a stale node and then build a *current* node that refers back to the stale id, so
the graph holds a cycle whose every node is current. Guarding the root is not guarding the
traversal — once any stale handle is touched, the whole walk stops.
## A proof object must not change meaning underneath you
The twelfth hole, and the most serious: a proof whose *meaning* silently changed. A
`Certificate` stores a `Pred`, which is a term **id**, and `with_fresh` resets the arena so
ids restart at 0. So a certificate from one scope named a *different formula* in the next:
```
scope A statement id : Pred(Term(2))
scope B predicate id : Pred(Term(2)) <- id recycled
same id? : true
prove(cert.statement()) in scope B : Counterexample
cert.weaken_to(y < 200) -> true <- a certificate for a falsehood
```
The engine knew `y < 200` was false, and the certificate claimed it was proved. The comment on
`with_fresh` had warned about exactly this — "use-after-free in the term arena" — but a warning
is not a check, and the failure was silent rather than a panic.
The arena now carries a `generation`, bumped by every reset, and `Certificate` and
`Implication` record it. Every rule re-checks it: `statement()` and `antecedent()` return
`None`, `weaken_to`/`and`/`apply`/`then` return `None`, and `Verified::from_certificate`
returns `None`. A stale proof object composes into nothing rather than into a falsehood.
A bare `Var` or `Pred` still carries no generation, so the "one `with_fresh` per proof" rule
still stands for those — the type cannot catch it. What the generation covers is the case that
outlives a scope *by construction*: the objects designed to be carried.
## A wrapper must not overclaim
The eleventh hole, and the one that undercut the crate's central promise: an overclaiming
abstraction. `Verified<T>` documented itself as evidence that "the associated contract was
proved", but it stored no contract, and `new(value, cert)` accepted *any* certificate. The
kernel test had been doing the wrong thing and passing:
```rust
let cert = Certificate::discharge(x.le_val(255)).unwrap(); // proves x <= 255
let v = Verified::new(42u32, cert); // value is 42u32
```
Nothing connected the two, and the type's name asserted a connection.
The wrapper now stores the statement, so the claim is checkable: `from_certificate` takes the
statement *from* the certificate (it cannot attest to anything else), `new` discharges the
statement itself and returns `None` if it is not a theorem, and `statement()` hands the claim
back.
Two honest boundaries, because this is exactly where a proof wrapper invites overclaiming.
First, the wrapper does not establish that `value` satisfies `statement` — the statement is
over symbolic variables and the value is concrete, so no constructor can check the link.
Second, and easier to miss: because the statement is a theorem it is equivalent to `true`, so
it carries no semantic content about the value. Its value is bookkeeping — which theorem was
discharged — and the type prevents mismatched bookkeeping, not an untrue claim.
## A truncated witness has to say so
The ninth hole, and the most consequential instance of the class: a *witness* presented as
complete while missing variables. A model is the evidence for a refutation, so a truncated one
is evidence with a hole in it.
`Cex` inlines `MAX_CEX` (16) assignments, and `model` stopped filling at the cap with no record
that it had. Worse, `value_of` returned `None` for a *dropped* variable exactly as it does for
one that was never mentioned, so an incomplete model was indistinguishable from a complete one.
The probe asks for a goal whose negation forces all twenty variables to be fixed:
```
assignments reported : 16
variables touched : 20
is_complete() : false
rendered : v0:u1 = 1, … v15:u1 = 1 … 16/20 shown (TRUNCATED)
```
`Cex` now carries `total`, the number of variables the model touched, and `is_complete()`
reports whether every one of them is present. The `Display` impl marks a truncated model too,
because a witness printed as if whole is the failure mode the flag exists to prevent.
## A negative answer has to say what it swept
The eighth hole, and the sharpest instance of the recurring class: a limit that silently means
something weaker than it looks, in the one function whose whole job is to *catch* the symbolic
engine being wrong.
`enumerate_counterexample` took a `limit` and returned `Option<u64>`, so `None` meant
two different things: "swept the whole domain and found nothing" and "stopped early and found
nothing". A caller reading `None` as "no counterexample exists" was wrong for the second. The
probe made it concrete — the claim `clamp(x, 20, 200) <= 100` is false, and the first witness is
`x = 101`:
```
limit=100 (a prefix) : None <- reads as "no counterexample"
limit=256 (the domain): Some(101)
```
The function now takes the **domain**, not a search budget — the domain *is* the search — and
returns `Search`, which separates `Witness(u64)` from `NoWitness`. `NoWitness` is explicitly a
statement about the domain that was searched, and `domain_of_bits(8)` derives `256` from the
input width so the domain cannot drift from the symbolic width or be mistyped.
`exhaustive.rs` was checked and is not affected: its domain is the whole type, derived from the
type itself, and termination uses `checked_add` so it cannot wrap. `None` there unambiguously
means "swept everything". The difference was the `limit` parameter, which let a caller pass a
prefix.
### A `verify_` name must not hand back a value the caller can drop
The library is honest — `for_all_u8` returns `false` for a refuted property — but the *macro*
built on it was not. `verify_exhaustive!` expanded to `for_all_u8(...)` and returned the
boolean, so the natural way to write it, as a statement:
```rust
verify_exhaustive!(a: u8 => a < 128); // false: 128..=255 violate it
println!("still here");
```
ran to completion and printed `still here`. Every sibling macro in the module (`verify!`,
`verify_implies!`, `contract!`, `proof!`) panics on a failed obligation, so the one macro whose
name also begins with `verify` was the one that could be ignored — and a reader who trusts the
name would not look for a returned boolean to check.
The fix makes it a statement: it finds the smallest violation and panics with it, naming the
witness (`counterexample a = 128`). Callers who want the boolean call `for_all_u8` directly. The
teeth are `exhaustive_macro_rejects_falsehoods`, a `#[should_panic]` test that pins both the
failure and the witness it reports.
The general question, and the third time this class has appeared: **which of a function's
results is a claim, and can the caller silently ignore it?** A returned `bool` is easy to drop; a
`panic` or a type is not. When a name promises verification, the failure has to be unmissable.
## An unreachable precondition is not a proof
The seventh hole, and the second of the vacuity kind. `verify(s, pre, post)` generates one
condition, `pre => wp(body, post)`. When `pre` is unsatisfiable that condition is a theorem
whatever the body and postcondition say — so every obligation discharges, `is_verified()`
returns true, and `establishes()` says `Total`, for a specification no run can ever reach:
```
pre satisfiable? : false
is_verified() : true
establishes() : Total
```
The body there was `x := 0` and the postcondition `x == 99`. The report called that `Total`.
This is the same failure as the bound hole seen from the other end: the first five holes let
a summary outrun its evidence, and these two give a proof with no evidence at all. Reachable
preconditions are a precondition *of* verification, not an assumption *about* it, and nothing
else in the tool was checking. The report now carries `Rule::VacuousPrecondition` as a
failure, so `establishes()` returns `Nothing`.
A note on where the check is needed. `verify_proc` uses a callee's `requires`, which is
normally reachable, and a `CallRequires` obligation still reports a real problem on an
unreachable path — so the gap is `verify` with a hand-written precondition, which is the case
the probe hit. The check is applied in `verify`, where every precondition arrives.
The teeth are two-sided: `an_unreachable_precondition_is_not_a_proof` pins the rejection, and
`a_reachable_precondition_is_still_proved` pins that a satisfiable precondition with a valid
contract still verifies, so the check cannot pass by rejecting everything.
### A call to a procedure that never returns is not a proof either
The third of the vacuity kind — reached through a `Call` rather than an
`Assume`. A callee whose postcondition is unsatisfiable never returns: `ensures false` says
there is no state in which the call completes. A `Call` is modelled as "assume `ensures`;
continue", so that assumption is `false`, the continuation becomes vacuous (`false => Q` is a
theorem), and every claim after the call discharges for free. With no loops in the program,
the report said:
```
is_verified() : true
establishes() : Total
```
for `boom(); x := 7` with postcondition `x == 7`, where `boom` is `requires true; ensures
false`. The program cannot get past the call, so the postcondition is never reached — and the
report called that progress.
This is the call-shaped twin of the unreachable-`Assume` hole, and it takes the same fix: the
walk records a `Rule::DivergentCall` finding at the call site, where the cut is, and reports
it as a failure. `Report::terminates` refuses it too, because a divergent call is a
termination finding and `correctness()` asks about termination on its own — otherwise
`loops == variants == 0` would read as progress on the strength of loops the program does not
have.
Two tests pin it, a matched pair again: `a_call_to_a_never_returning_proc_is_not_total` and,
as the control, `a_call_to_a_proc_that_merely_returns_nothing_is_still_total`. Reverting the
check fails the first and leaves the second green, so the fix refuses divergence, not calls.
The general shape, now seen three times: **a construct that cuts a path off makes everything
downstream vacuously true, and vacuous truth is indistinguishable from proof unless the cut is
recorded as a failure.** `Assume(false)`, an unsatisfiable precondition, and a never-returning
call are the three ways this fragment can cut a path, and each needed its own finding because
each is a different statement in the calculus.
## A bound must be wider than the address, or "all cells" is vacuous
The sixth hole, and the first of the *vacuity* kind. The previous five were summaries that
outran their evidence — a proof stronger than what was proved. This one is the dual: a proof
whose evidence is empty.
`Mem::check_addr_width` accepted a bound exactly as wide as the address, while its own
documentation told the caller to pass something wider. With a 4-cell memory the address is
2 bits, so a 2-bit bound cannot hold 4 — and "every cell is filled" is stated at
`bound == len`, i.e. `bound == 4`. The precondition was unsatisfiable, so the obligation was
vacuously true: `bound == 4 => P` *and* `bound == 4 => !P` both proved. A fill loop's
postcondition was "proved" without saying anything about the cells.
The tell was an impossible precondition reported as valid:
```
narrow(2-bit) bound == 4 satisfiable? : Valid
pre_narrow => post_narrow : Valid
pre_narrow => NOT post_narrow : Valid
```
The check now requires strictly more bits than the address, which is what every intended use
already passes — a loop counter must be wider than the address anyway, or `while k < len`
never terminates. `tests/mem.rs` pins the refusal, and also checks the *sensitivity* the old
behaviour lacked: at the intended width the property holds when the cells are zero and fails
when one is not.
## The memory family, positive side
The random memory family is 90% refutations, which tests strength but barely tests
soundness. A second family is therefore built the other way: templates that are *correct by
construction*, one per non-trivial rule (ite-chain read at a symbolic address, the frame
rule, `forall_below`, simultaneous bindings, read/write composition). Each must be proved by
the engine and must satisfy its own postcondition on every sampled array.
Each template also has a mutated twin — the same program with a false postcondition — which
must *not* be proved, so a template that verified for the wrong reason (a goal that collapsed
to `true`, say) cannot look like a success. 140 templates proved, 134 mutations refuted; the
six survivors are all the `n: 0` boundary, which is genuinely vacuous and is asserted to be
so explicitly rather than quietly skipped.
## The differential harness now covers memory
The harness in `tests/modular_differential.rs` compares the engine against concrete
execution, and until now it covered calls, loops containing calls, and obligation pressure.
The memory rules were the largest part of the crate with no such net, and they are the most
algebraic: an ite-chain read, a simultaneous binding list for a store, a frame lemma derived
by pushing one through the other, and a guarded quantifier for a prefix property. Each is a
place where the symbolic form could quietly disagree with an array.
The fourth family generates a program of stores — one of them at a *symbolic* address — plus
a postcondition, then checks both directions against an enumerated state space of four 8-bit
cells:
* `Valid` means no sampled `(initial array, address)` may violate the postcondition.
* anything else means some sampled input must violate it, and the search must find one.
The state space is small and closed, so unlike the call family this is an equivalence rather
than a one-way implication. Both directions are asserted, and the family fails if it is
vacuous in either — no case proved, or no case refuted. A companion test feeds a
deliberately wrong store rule (one that ignores the address and clobbers every cell) through
the same comparison to confirm the family can see a bad rule at all; with `store_binds`
actually broken, the family reports `VERIFIED but 4320 sampled (array, address) pairs
violate`.
## A guard compares an index, it does not truncate it
`quant::forall_guarded` and `quant::exists_guarded` quantify over a range while the upper
bound is a symbolic word — "every cell below the cursor". Their guard used to be built as
`ult(word(k, bits(bound)), bound)`, which truncates the concrete index `k` to the bound's
width. An index at or above `2^bits(bound)` then wrapped to a small value and satisfied the
guard, so an index provably *outside* the bound was treated as inside it. For
`exists_guarded` that is a soundness hole rather than a nuisance, because a satisfiable
guard weakens the disjunction: the formula becomes provable while the real obligation is
not. With `hi = 3` and a one-bit bound, `exists_guarded` came out `Valid` on an input whose
true form had a counterexample.
The guard now checks the index against the representable range first. An index that does
not fit is at least `2^bits(bound)`, hence provably `>= bound`, so the guard is `false` —
the truth rather than a wrap. The intended use, `Mem::forall_below` over a memory whose
cells match the bound's width, was never affected; the hole was reachable only through the
public `quant` API with a bound narrower than the range.
`tests/quant.rs` pins both directions: the guarded expansion must agree with the truth at a
narrow bound, and must be unchanged at a bound wide enough for every index.
## A derived frame says whether it is complete
The frame rule compares what a callee *claims* to write against what its body really
writes. That second set is derived from the syntax, and it is capped at `MAX_WRITES`.
Truncating it silently was a soundness hole that defeated the very check added to close
the first one: an under-complete "real" frame is exactly the condition the rule exists to
reject, so a callee writing more than `MAX_WRITES` variables looked like one writing
exactly `MAX_WRITES`, and a caller could prove that a clobbered variable survived.
So `writes` does not return `(array, count)` any more. It returns a `Frame`, whose
`complete()` is `false` when the body writes more than the cap, and every consumer treats
that as an unmodelled program rather than a partially modelled one:
```rust
let derived = wp::writes(callee.body);
if !derived.complete() { return false; } // `Stmt::frame` refuses the call
```
`unchanged_vars` returns nothing for such a call and `unchanged` answers `false` — no
caller variable is known to survive a body the engine cannot fully see. A count that stops
at the cap is indistinguishable from a body that writes exactly that many, which is why a
flag had to be part of the type rather than a separate return value.
`MAX_WRITES <= MAX_CALL_ARGS` is now a compile-time assertion, because `unchanged_vars`
maps a complete frame into a buffer sized by `MAX_CALL_ARGS`; the two constants being
independent was a latent version of the same bug.
## The obligation cap fails loudly, never silently
`verify` collects side obligations — loop preservation, variants, exits, assertions, call
contracts — into a fixed-size buffer, `MAX_OBLIGATIONS`. It used to drop them silently once
the buffer was full. That is unsound in the worst possible way: a program with more than
sixteen side obligations could have a *failing* `LoopExit` land in the part that did not
fit, and the report would still say `verified` — and `Total`. The probe that found it
printed:
```
verified : true
establishes : Total
--- ground truth: loop exits at i=10, so '100 <= i' is FALSE
```
A proof of a false statement is the one outcome a verifier must never produce. So the cap
now does two things:
* **Claim-carrying obligations report the drop.** A dropped loop rule or call rule raises
`Rule::ObligationOverflow`, whose goal is `false`, so `verified` becomes false and the
claim shrinks to what was actually checked. Assertions raise the same flag. They were
once exempt, on the argument that the backward walk still conjoins a dropped `assert c`
into the weakest precondition, so the contract obligation catches it. That is true of
`verify`, but it left `wp::obligations`' `complete` flag lying -- it returned `true`
while dropping obligations -- and a truncated obligation list is not a fully checked
claim, so the report has to shrink here too. See
`assertions_beyond_the_cap_are_reported_not_hidden` in `tests/wp.rs`.
* **The overflow notice itself cannot be dropped.** A `Report` carries one slot more than
`MAX_OBLIGATIONS`, reserved for a report-level finding. Without that reservation the
notice would be dropped by the same full buffer that caused it — which is exactly how
the first attempt at this fix failed.
`tests/modular_differential.rs` has an obligation-pressure family that pads a program with
assertions until the count crosses the cap and demands that nothing ever verifies; with the
fix reverted it fails at padding 15.
The low-level `wp::obligations` had the same shape of hole one level down. It returned a
count that saturates at `MAX_OBLIGATIONS`, so a caller could not tell a complete set of
that size from a truncated prefix — two different facts behind one number, exactly the
defect `writes` was fixed for. It now returns a third value, `complete`, which is `true`
only when every side obligation is in the buffer. `verify` already turned the flag into a
failure; this makes the same information available to a caller inspecting obligations
directly. `a_complete_obligation_set_reports_itself_complete` and
`too_many_obligations_is_reported_not_swallowed` pin both directions, and
`assertions_beyond_the_cap_are_reported_not_hidden` pins the assertion case, which was the
one still returning `true` while dropping.
## Differential testing: a proof must not outrun reality
The two soundness holes in the call rule were found by accident — by writing a test
that asserted the wrong thing and noticing the engine agreed. That is not a method, so
`tests/modular_differential.rs` is the method: it generates programs containing calls,
verifies them with the engine, and **interprets them concretely**, then demands:
> if the engine reports the caller verified, no concrete execution in a bounded
> enumeration violates the postcondition.
That is the direction that matters, because soundness is the property that, if broken,
lets a verifier certify a bug. The other direction — every reported failure has a real
counterexample — is checked where it is cheap, but it cannot be complete, since a
failure may come from a bound the enumeration does not reach.
Three things make the harness trustworthy rather than decorative:
1. **`smt::evaluate` is validated first.** The concrete evaluator is the oracle, so
`the_evaluator_agrees_with_the_engine_on_every_operator` pins it against the
bit-level engine for every operator and every input pair. An oracle that disagreed
would send you chasing bugs in the wrong place.
2. **The search space targets the known failure shapes.** The generator varies what the
callee writes (directly or through a nested call), which caller variables the rename
maps, and whether the declared frame is correct, generous, or a lie. It also *seeds*
the result variable before the call — without that seeding, a missing havoc rule is
invisible, because there is no pre-call value to be confused with the post-call one.
The loop family does the same for the loop rules: it varies the callee's contract
(exact or merely true), the frame, the invariant and the variant, and it includes
bodies that never advance the counter. That last shape is what makes termination
observable: a diverging loop claimed total is a contradiction the harness can see.
3. **The property has been observed to fail.** With the havoc rule disabled, the
harness fails at a specific case and input; with the frame-completeness check
disabled, two tests fail; with the termination check reduced to counting variants,
the loop family fails at case 4. `the_property_has_teeth` makes the same point inside
the suite, by running one case under a deliberately wrong semantics for calls and
requiring all 256 inputs to be caught. A check never seen to fail is not evidence.
Note what the loop defect teaches: a behavioural harness cannot see a *proof* defect
directly. A non-decreasing variant still terminates, so comparing against execution
is blind to it. It became visible only through the contradiction between a
termination claim and a divergence. When a rule's failure mode is "proves the wrong
thing" rather than "does the wrong thing", look for the contradiction it licenses.
## Bounded quantification: the invariant a loop over memory needs
A fill loop's invariant is "every cell below `k` is zero". That is a quantifier,
and a bit-vector decision procedure has none. But it is a *bounded* quantifier, and
a bounded quantifier is a finite conjunction, so it can simply be expanded:
```text
forall j < k { m[j] == 0 } => (0 < k => m[0] == 0) && (1 < k => m[1] == 0) && ...
```
`Mem::forall_below` and `Mem::exists_below` do that expansion, which is what makes
a loop over addresses verifiable at all rather than needing a hand unroll:
```rust
// for k := 0; k < 4; k += 1 { m[k] := 0 }
let inv = m.forall_below(k, |cell| smt::eq_const(cell, 0));
let post = m.forall_cells(|cell| smt::eq_const(cell, 0));
```
Run it: `cargo run --features std --example memory`. The invariant verifies with
`Total` correctness; weakening it to "only `m[k]` is zero" makes the proof fail,
which is the control that shows the quantifier is doing real work rather than being
decorative. `tests/quant.rs` verifies a fill and a scan this way, and executes both
on real arrays.
Two details matter:
1. **The loop counter must be wider than the address.** With 4 addresses, a 2-bit
counter cannot hold 4, so `while k < 4` would never exit. The counter is 3 bits
and `Mem::addr_of` truncates it back to an address at the point of use — a new
`truncate` primitive, since widths were previously immutable. Truncation wraps,
so it is only sound once you have proved the index is in range; a wrapped write
re-zeros an already-zero cell, which is why a fill survives it and a scan would
not.
2. **A bound larger than the memory is fine, not a gap.** The quantifier ranges
over the cells that exist, and those are the only addresses that can be named, so
`forall k < 8` over four cells constrains exactly cells 0..3. My first version of
this documentation claimed the opposite, and the test that caught it is
`a_bound_larger_than_the_memory_is_not_a_problem`.
`quant` also offers the plain `forall_range`/`exists_range` over a slice, which is
useful outside the memory layer. The expansion is exact: a proof of the conjunction
is a proof of the quantified formula, and a counterexample names the index that
broke it.
### The bound has to be a number the tool can count to
`forall k < 1000` is a thousand copies of the predicate, so the cost is linear in
the range. Unbounded quantification over an unknown domain would need a different
decision procedure — that is the line between this crate and a real SMT solver, and
it is not a small one.
## Modular verification: procedures checked once, calls reasoned about through contracts
Without contracts, verifying a call means inlining the callee's body — exponential in
the call graph, and impossible for recursion. With them, a procedure is proved once
against its own contract and every call site costs two implications.
A `Proc` carries its body *and* its contract together, so it is impossible to assume
a postcondition nobody ever proved:
```rust
let sat_inc = Proc {
name: "sat_inc",
requires: smt::ule_const(x, 20), // caller must establish
ensures: smt::and(smt::ule_const(r, 20), // caller may assume
smt::implies(x.lt_val(20), smt::eq(r, x + 1u32))),
body: &body,
};
assert!(wp::verify_proc(&sat_inc).is_verified()); // the "once" half
let call = Stmt::Call { proc_: &sat_inc, actuals: &[(x, a), (r, tmp)], writes: &[r] };
let report = wp::verify(&caller, smt::truth(true), post); // the "many" half
```
`actuals` is a *simultaneous rename* of the callee's variables to the caller's, the
same mechanism assignment and memory writes use. `writes` is the callee's frame, and
`Stmt::frame` derives the check from it rather than trusting a hand-written list.
Run it: `cargo run --features std --example contracts`.
### Where a postcondition stops being bookkeeping
Put a call in a loop and the callee's postcondition becomes load-bearing. With
`sat_inc` above, the invariant `a <= 20 && k <= 4` is preserved *only* because the
contract promises `r <= 20`. Weaken the contract to the equation alone and the loop
stops being provable — `LoopPreserve` fails. The caller never reads the body, so that
bound is the entire reason the proof goes through. Both directions are tests
(`a_call_inside_a_loop_body_verifies` and its control
`dropping_the_bound_from_the_postcondition_breaks_the_loop`), because a positive test
alone would not show the postcondition was being used.
### What a call is not allowed to do
`Stmt::frame` rejects five things, and each is a real hole rather than tidiness. The
declared frame is checked against the frame **derived from the body** by `wp::writes`,
so it cannot be under-stated:
0. **`writes` must be complete.** This one is the sharpest. A caller that declares an
empty frame for a callee that clobbers a variable is not making a bookkeeping
error — it is asking the engine to prove that the variable survived, and the
engine used to comply. I found this by probing rather than reasoning: the caller
"proved" `s == 7` after a call that had overwritten `s` with `6`. A proof about a
program that does not exist is worse than no proof, so the derived frame is now
computed from the body (recursing through branches, loops and nested calls, and
mapping a nested callee's writes through that call's actuals) and the declared
frame must cover it. Over-declaring is still fine: the rule is conservative.
1. **A write the caller does not name.** The caller's state after the call would be
unknown. Reported as `Rule::CallFrame`.
2. **A rename that is not a function** — a repeated callee variable.
3. **Two writes landing on one caller variable**, which is an order-dependent
simultaneous assignment.
4. **A write landing on a variable the call also reads.** This one is not obvious.
`ensures` is *assumed* after the call, so `x -> a, r -> a` would assume
`a == a + a`, silently forcing `a == 0` on the caller and letting the engine prove
anything about it. In-place update is not expressible by a rename; the caller must
capture the old value into a temporary first, exactly as it must for a memory swap.
I found this by writing a test that expected `frame` to accept the aliasing, and the
engine had already been accepting it.
An unmodelled call is reported as an obligation that can never hold, not asserted
away, so a whole program can be checked in one run.
### A call havocs what it writes
The other half of the frame rule, and a soundness fix rather than a refinement. The
caller-side target of every write is renamed to a **fresh variable** in both the
assumed postcondition and the continuation. Without that the two sides share a name,
and the value the variable held *before* the call is mistaken for the value it holds
after — so `c := 99; c := bump(a); assert c == 99` verified. It no longer does. The
fresh name is universally quantified by the prover, which is exactly the right
reading: the caller must be correct for every result the contract permits.
### Two-state specifications need a snapshot, not an `old` operator
"The result equals the argument that came in, plus one" is a two-state property, and
it needs no new machinery. A variable the callee cannot write has the same value
before and after, so `old(x)` *is* `x` — provided the frame is honest, which is now
enforced. The snapshot is an ordinary assignment:
```rust
a := 5; old_a := a; c := bump(a)
assert c == old_a + 1 && a == old_a
```
What was missing was not a way to *write* `old(v)` but a way to **ask** which
variables survive, because the engine was already assuming it silently:
```rust
wp::unchanged(&bump, &actuals, a) // true -- read-only, so it survives
wp::unchanged(&bump, &actuals, c) // false -- written, so its old value is gone
```
Both answer from the *derived* frame, so a caller cannot talk the query into a wrong
answer. For a written variable there is no query that helps: the caller must capture
the entry value into a temporary first, exactly as for a memory swap. That is a
discipline, not a convenience, and `the_snapshot_discipline_is_needed_for_written_variables`
is its control.
The havoc itself has a cap, and the cap has the same shape as the `writes` truncation it
shares a buffer size with: `havoc_writes` renames into a `MAX_CALL_ARGS` buffer and stops
at the end. That is sound only because `frame` refuses a declared frame with more than
`MAX_CALL_ARGS` distinct targets *before* the havoc runs, so a call that reaches the
rename can never overflow it. `a_declared_frame_longer_than_the_cap_is_refused` pins the
refusal, and its teeth are deliberate: it uses a body that writes a single variable, so
the derived-frame check passes and only the declared-frame cap can be what refuses the
call. (The first version of that test used a body at the `MAX_WRITES` cap and passed for
the wrong reason — check 0 refused it, not the cap — and did not fail when the cap was
removed. A test whose teeth are never pulled is a test that documents, not one that
guards.)
### The sharp edge, stated rather than hidden
`frame` checks the *shape* of the rename, not its meaning. A caller who wires the
result onto the wrong variable passes the check and gets a proof about a program it
did not write. And a caller that believes a contract whose body never established it
verifies anyway, because the caller does not read the body. Both are pinned by tests.
The discipline is therefore: verify every body against its contract with
`verify_proc`, and trust nothing else.
Recursion is supported for a *self-call* with a `decreases:` measure: the call is
answered by the function's own contract, the measure is proved to shrink, and the
postcondition is assumed for the result — well-founded induction, described in
the MIR frontend section below. A mutually recursive cycle has no such measure to
name here, so it is still refused rather than guessed.
## Verifying real Rust: the MIR frontend
Everything above has the same shape: you write a formula, or a `wp` program, and
the engine discharges it. The obligation is a *model* of the code, and a model can
drift from the code it describes. A human has to keep the two in step, and the
day they stop agreeing the proof is about the wrong program.
`verif::mir` removes that step. It reads the **actual MIR** that `rustc`
lowers a real Rust function to, symbolically executes it, and discharges the
obligations it finds — the overflow, underflow and divide-by-zero `assert`s that
`rustc` itself emits, plus the pre- and postconditions you wrote. Nothing is
re-modelled by hand, so there is nothing to keep in sync.
```console
$ cargo run --features std --example mir_demo
=== examples/mir_targets/actuator.rs ===
clamp verified (3 obligation(s), 0 panic(s) ruled out)
rate_limit verified (5 obligation(s), 2 panic(s) ruled out)
sat_add verified (4 obligation(s), 2 panic(s) ruled out)
sat_sub verified (1 obligation(s), 1 panic(s) ruled out)
shift_const verified (1 obligation(s), 1 panic(s) ruled out)
shift_left FAILED: panic: attempt to shift left by `{}`, which would overflow — n = 16
sat_shift verified (1 obligation(s), 1 panic(s) ruled out)
sat_mul verified (3 obligation(s), 3 panic(s) ruled out)
unchecked_add FAILED: panic: attempt to compute `{} + {}`, which would overflow — a = 32768, b = 32768
unchecked_sub FAILED: panic: attempt to compute `{} - {}`, which would overflow — a = 0, b = 32768
unchecked_div FAILED: panic: attempt to divide `{}` by zero — d = 0
unchecked_mul FAILED: panic: attempt to compute `{} * {}`, which would overflow — a = 128, b = 128
off_by_one_guard FAILED: postcondition — a = 32768, b = 32768
clamp_signed verified (3 obligation(s), 0 panic(s) ruled out)
checked_div_signed verified (3 obligation(s), 2 panic(s) ruled out)
unchecked_div_signed FAILED: panic: attempt to divide `{}` by zero — b = 0
signed_add_misguarded FAILED: panic: attempt to compute `{} + {}`, which would overflow — a = 128, b = 128
signed_add_guarded verified (2 obligation(s), 1 panic(s) ruled out)
signed_mul_guarded verified (2 obligation(s), 1 panic(s) ruled out)
signed_mul_negative FAILED: panic: attempt to compute `{} * {}`, which would overflow — a = 128, b = 128
checked_neg verified (2 obligation(s), 1 panic(s) ruled out)
assert_guarded verified (1 obligation(s), 0 panic(s) ruled out)
assert_misguarded FAILED: panic: assertion failed: n <= 100 — n = 128
panic_guarded verified (1 obligation(s), 0 panic(s) ruled out)
verified=14 failed=10 incomplete=0
All expectations met.
```
`unchecked_add` is `fn unchecked_add(a: u16, b: u16) -> u16 { a + b }` — ordinary
Rust with no annotations of any kind. The counterexample `32768 + 32768` is read
off the MIR, and `tests/mir.rs` feeds exactly that pair back into the compiled
function and requires the panic. That is the property worth having: the witness is
checked against `rustc`'s own code generator, not against another model.
The witness is rendered with the **source names** `rustc` recorded in its `debug`
bindings — `a = 32768`, `n = 16`, `d = 0` — rather than internal local indices. A
variable with no source name (a temporary, a promoted constant) keeps its
`v{index}:u{width}` spelling, so naming is a readability improvement and never a
loss.
### Contracts are doc comments, and that is forced
The obvious syntax is an attribute:
```rust,ignore
#[requires(lo <= hi)]
pub fn clamp(x: u32, lo: u32, hi: u32) -> u32 { … }
```
That cannot be done here. An unknown attribute on a function is not Rust; it needs
a proc-macro to consume it, and a proc-macro is a dependency, which would break the
zero-dependency gate that `scripts/gate.sh` enforces. So contracts live in doc
comments, which `rustc` accepts and the frontend reads out of the source:
```rust,ignore
/// requires: lo <= hi
/// ensures: lo <= ret
/// ensures: ret <= hi
pub fn clamp(x: u32, lo: u32, hi: u32) -> u32 {
if x < lo { lo } else if x > hi { hi } else { x }
}
```
A loop is proved by an `invariant:` line rather than by unwinding. It is the
induction hypothesis: true on entry to the loop head, and left true by one
iteration. Naming it is what makes a loop with a symbolic trip count decidable
instead of cut off at an unwind bound:
```rust,ignore
/// requires: n <= 8
/// invariant: i <= n && s == i
/// ensures: ret <= 8
pub fn sum_to(n: u8) -> u8 {
let mut s = 0u8;
let mut i = 0u8;
while i < n { s += 1; i += 1; }
s
}
```
An invariant may name any local, not just the parameters. It is checked twice —
once on entry to the head, once across an iteration — and at the head the locals
the loop can write are replaced by fresh values before the invariant is assumed,
so the state after the loop is *any* state satisfying the invariant and the exit
condition, not the state of the first pass. Omitting that step would prove false
postconditions; `AGENTS.md` records the measured case.
### Termination: a `variant:` measure
An invariant alone proves *partial* correctness: the loop is safe **if** it stops,
which a loop that never stops satisfies vacuously. A `variant:` line names the
quantity the loop counts down, and turns that into *total* correctness:
```rust,ignore
/// invariant: i <= n
/// variant: n - i
/// ensures: ret == n
pub fn count_to(n: u8) -> u8 {
let mut i = 0u8;
while i < n { i += 1; }
i
}
```
At the back edge the measure after one iteration is compared against the value at
the head, and the obligation is `I && guard => V' < V`. On a fixed bit width a
strictly decreasing sequence cannot be infinite, so no separate lower bound is
needed — and adding one would be wrong, because the measure is a machine word,
where "going negative" is just a smaller word, which is the descent that proves
termination. `while i < 5 { i += 0 }` is therefore reported as a failure on
`loop variant decreases` rather than as verified; before this clause existed it
came back `Verified`, which is the soundness hole the measure closes.
The measure is not inferred, for the same reason the invariant is not: a guessed
measure is a guessed proof. A loop with no `variant:` is still checked for partial
correctness, and no termination claim is made for it. A `variant:` with no
`invariant:` is refused, because the invariant is what locates the loop the measure
is about.
### Recursion: a `decreases:` measure
A recursive function is proved by *induction*, not by unrolling. Adding a
`decreases:` line names a measure — an expression in the arguments — that must be
non-negative at entry and strictly smaller at every self-call. The self-call is
then answered by the function's own contract instead of being inlined:
* the call's arguments must satisfy the `requires:`;
* the measure must strictly decrease (and stay non-negative, for a signed
measure);
* the `ensures:` is *assumed* for the call's result, which is the induction
hypothesis.
```rust,ignore
/// requires: true
/// decreases: n
/// ensures: ret == n
pub fn count_down(n: u8) -> u8 {
if n == 0 { 0 } else { count_down(n - 1) + 1 }
}
```
The measure is what makes the assumption an induction rather than a circular
argument: a strictly decreasing sequence in a well-founded order is finite, so
there is a base case, and nothing is assumed there — the body has to establish
the postcondition on its own. The base case is therefore still a proof
obligation, and a body that gets the base case wrong is refuted with a witness
(`a_recursive_lie_cannot_prove_this` in the corpus). A measure that does not
shrink, or a call that leaves its own precondition, is likewise a definite
failure rather than a silent pass. Without a `decreases:` line a self-call has no
induction principle, so it is inlined once and the result is reported
`Incomplete` at the depth bound — an honest "I could not decide", never a guess.
A contract may name a field of a struct argument, and a component of a tuple
return, by the same syntax the Rust body uses:
```rust,ignore
struct Bounds { lo: u8, hi: u8 }
/// requires: b.lo <= b.hi
/// ensures: ret >= b.lo && ret <= b.hi
pub fn clamp_bounds(b: &Bounds, v: u8) -> u8 {
if v < b.lo { b.lo } else if v > b.hi { b.hi } else { v }
}
/// requires: a <= b
/// ensures: ret.0 <= a
pub fn split(a: u8, b: u8) -> (u8, u8) {
if a <= b { (a, b) } else { (b, a) }
}
```
The MIR dump names the struct but never prints its layout — `_1: &Bounds` and
nothing more — so the field *indices and widths* are read from the source, the
same place the contract text comes from. That keeps the two consistent by
construction: a field the layout reader does not find cannot be named by a
contract that would otherwise be checked against it.
Each field is its own symbolic input. This is the honest model, not a
convenience: the frontend cannot see the caller's invariant relating two fields,
so assuming `lo <= hi` would be unsound. `examples/mir_targets/realistic.rs`
carries a `field_alias_tripwire` whose *failure* is the evidence that the two
fields are distinct variables rather than one aliased one; `tests/mir.rs`
requires that failure.
A projection that cannot be resolved is refused, never dropped. `c.lo` where `lo`
is not a field of `Bounds` is an error naming the field, and a projection on a
non-aggregate return is refused too — if the conjunct vanished instead, the
function would verify against a weaker contract than the source states.
A slice argument is named by its length and by its elements:
```rust,ignore
/// requires: xs.len() > 0
/// ensures: ret == xs[0]
pub fn first_of(xs: &[u8]) -> u8 {
xs[0]
}
```
A slice has no length in its type, so `xs.len()` is a *symbolic input* — whatever
the caller passed — not a constant. The same variable is what the body's
`PtrMetadata(_1)` reads and what the `assert` before `(*_1)[_2]` checks, so the
bounds check is discharged from the precondition rather than assumed. Each element
is its own input per index: `xs[0]` and `xs[1]` are two variables, and a
`slice_alias_tripwire` in `examples/mir_targets/realistic.rs` fails precisely
because of it. Only a literal index is modelled; `xs[i]` with `i` a parameter is
refused rather than resolved to an arbitrary element.
A fixed-size array is named the same way, but its length is not an input:
```rust,ignore
/// requires: a[0] <= a[1]
/// ensures: ret == a[1]
pub fn max_of_pair(a: [u8; 4]) -> u8 {
if a[0] > a[1] { a[0] } else { a[1] }
}
```
An array's length is part of its type, so `a.len()` is the *constant* `4` and not a
fresh variable — binding it to an input would admit lengths the type excludes, so a
contract proved at length 4 would claim to hold at any length. The body's bounds
check is against that same literal (`Lt(_2, const 4_usize)`), so it is discharged
from the index being a literal. Elements are inputs per index exactly as a slice's
are, and `array_alias_tripwire` fails to show it. An index past the length is
refused rather than bound, since the element does not exist.
A literal in a contract takes its width from the operand it meets, not from the
widest name in scope:
```rust,ignore
/// requires: true
/// ensures: ret <= 255
pub fn idx(a: [u8; 4]) -> u8 { a[0] }
```
Here `a` contributes a 64-bit length, but `ret` is 8 bits, so `255` has to be read
at 8 bits. Sizing it from the length instead made the comparison ill-formed, and an
ill-formed term makes *every* obligation in the run `Unknown` — so the function was
reported incomplete for a reason that had nothing to do with its body. A literal too
large for the operand's width is refused rather than truncated: `a <= 300` for a
`u8` must not become `a <= 44`.
The fit check is against the operand's *signed* range when the operand is signed,
not merely its bit width. `128` for an `i8` fits in eight bits, but those bits are
`0x80`, which is `-128` signed — so a check that only asked "does this fit in eight
unsigned bits?" accepted it and read `x <= 128` as `x <= -128`. rustc rejects
`x <= 128` for an `i8` ("literal out of range for `i8`"), and the wrong reading is a
false proof: `requires: x <= 128` with `ensures: ret != 127` *held*. The same holds
for a negation, where `-129` for an `i8` wraps to `127` at eight bits and `x >= -129`
became `x >= 127`. Both are refused now. The `i8::MIN` bound shares the bit pattern
`0x80` and still reads, which is why the fix distinguishes a non-negative literal
from a signed constant instead of refusing every `0x80`. The check runs even when
both operands are constants and no typed name is present: `128 <= i8::MAX` is a
`literal out of range` error, and reading `128` as `0x80` made it `-128 <= 127`,
always true — so it is refused, while `127 <= i8::MAX` and `i8::MIN <= i8::MAX` read.
A constant *arithmetic* expression is folded exactly, so one that overflows its
operand width is refused rather than wrapped. `200u8 + 100u8` is a rustc const-eval
error, but folding it mod 256 gave `44`, so `x <= 200 + 100` read as `x <= 44` — a
*stronger* precondition than the author wrote (`x <= 300`, which admits every `u8`)
— and `ensures: ret <= 44` was proved for a body that fails at `x == 100`: a false
proof. The same applies to `0 - 1` (underflow), `255 + 1`, `200 * 2`, and to a
constant `i8::MIN / -1` or `% -1`, which overflow the signed operand. The fold
widens past the operand width to keep the value exact, so the ordinary fit check
refuses the shape when the operand it meets is too narrow, while a sum whose overflow
is legal because a wider operand types it (`x as u16 <= 200 + 100` is `300`) still
reads. The widening is at the *expression's* signedness, so `i8::MAX + 1` is refused
too: `128` fits an unsigned byte but not a signed one, and an unsigned widening would
have left it at eight bits where it read as `-128` — a false proof in place of the one
being fixed.
A *signed* constant meeting an *unsigned* operand is refused, because Rust does not
type it either — at every level where two operands meet. A literal takes its type
from the operand it meets, so `x == -1` for a `u8` does not compile ("cannot apply
unary operator `-` to type `u8`"), and `x + -1`, `x - -1`, `x % -1`, `x * -1`,
`x & -1` and `x ^ -1` are the same shape. The reader carries the negation as a bit
pattern at the operand's width, so it read `x == -1` as `x == 255`, `x + -1 >= 0` as
`x + 255 >= 0`, and `x ^ -1 <= 255` as `x ^ 255 <= 255`. The first made
`ensures: ret == 255` *proved* for a body returning `x`; the second made
`requires: x + -1 >= 0` trivially true, so *any* postcondition was proved; the third
was always true. All false proofs, and the arithmetic and bitwise ones survive a
comparison-only check — the refusal has to sit at each operator, because that is
where the constant meets the name. Refusing the shape is the only sound answer: the
wrong reading is a proof, and a proof cannot be a warning. The refusal is narrow — a
bare literal is unsigned, so `0xFF` for a `u8` still reads as `255`, `x + 255 >= 0`
and `x & 255 == x` still read, and `x <= 127` for an `i8` is legal with the constant
on the unsigned side. Only a signed *constant* against an unsigned *name* (in either
order) triggers it, which is exactly the shape Rust rejects. The test that pins this
enumerates all sixteen operators (`== != < <= > >= + - * / % & | ^ << >>`) rather
than the levels a human remembered, because the hole was found one level at a time
and reasoning about the next level is what kept being wrong.
Two *names* of different signedness are refused for the same reason: `a > b` for an
`i8` and a `u8` is `E0308: mismatched types`, and the body reads each operand at its
own signedness, so a contract that picked one sign could disagree with the body about
what the operator means. Refusing keeps the answer "the tool could not run" rather
than a verdict on a program that does not compile. The refusal is narrow: two names of
the *same* signedness still compare, and a name against a literal of either value
still reads. A shift is exempt, because Rust lets the shift amount have its own type.
An *untyped* constant — the complement of a literal (`!0`), or a fold of untyped
operands — has no type of its own, and Rust types an untyped constant as `i32`, so
`!0` is `-1`. Where the signed and unsigned readings differ, the shape is refused
rather than guessed: at `>>`, `/`, `%`, an ordering comparison, a widening cast, and
at `==`/`!=` too. Equality is included because the two readings are different
*values*, not a different ordering of one — the reader built `255u8 == 255` from
`!0 == 255` and *verified* it, though Rust calls it false (a false proof). Any typed
operand fixes the reading, and two bare literals stay unambiguous.
Unary `-` on an unsigned operand is refused as well: `-x` for a `u8` is `E0600`, and
the reader's `0 - x` is a value Rust never produces. A signed name, and a bare literal
(Rust defaults it to a signed `i32`), still negate and read.
A constant widened to meet a wider operand fills from the value it **denotes**, not
blindly from the operand's sign. A bare literal is non-negative and zero-extends, so
`(x as i16) == 255` for a `u8` `x` is true — the same as Rust's `(255u8 as i16)`.
Filling from the signed operand instead sign-extended the `255` to `65535` and
*refuted* a postcondition Rust accepts (a false refutation). A typed signed constant
keeps sign-extending, so `-1 as i32` is still `-1`.
An *opaque* constant (`!0`, a fold of untyped operands) takes the operand's sign,
because that is the type Rust infers for it — but the reader holds a complement at the
*scope's* width, and no extension of that recovers the operand-width value (`!0` against
a `u16` is `65535`, not `255`). So an opaque widening is **refused** rather than guessed;
a *fold* is a value, not a bit pattern, and still widens exactly.
A numeric literal's **type suffix is kept**: `0u8` is unsigned, so `-1 <= 0u8` is an
error (a `u8` cannot be negated) and is refused rather than silently read as a signed
comparison. Dropping the suffix left `0u8` indistinguishable from a bare `0`, so a
mismatched constant pair was decided; the refusal now covers a signed constant meeting
an unsigned operand whether the other side is a name or another constant. Valid pairs
(`-1i8 <= 0i8`, `-1 <= 255`) still read.
A struct or enum whose body closes on its declaration line is read from that line,
not by opening a cursor. `pub struct B { pub lo: u8 }` used to leave a field cursor
open with no closing brace left to read, so every following line — the `///`
contracts and the `fn` items — was consumed as struct fields. Those functions then
had no contract at all and were neither verified nor reported as skipped: they
silently left the check set. A body that does not close on the line still opens a
cursor. The same distinction the enum reader already made for a refused one-line
body now applies to a readable one-line struct body.
A contract written above a struct or enum belongs to that item, not the next
function. The layout heads used to match and move on without clearing the pending
contract, so a doc comment above a struct carried over to the next `fn`. A leaked
`requires` is a false proof when it is satisfiable, because it narrows the inputs the
postcondition is checked for: `requires: x == 0` above a struct made
`ensures: ret == 0` for a body returning `x` verify. The contract now attaches only
to the item it was written above.
A slice or array element is read at the element type's signedness in the *contract*,
not only in the body. `bind_indexed_elem` recorded an `i8` element's sign for the
executor's seeds but not for the parser, so `xs[0] >= 0` over a `&[i8]` read as an
unsigned comparison — always true — and was *proved* for a body returning the element,
with `i8::MIN` as the counterexample. The symbolic-index chain (`a[i]` over `[i8; 4]`)
had the same hole. The existing `signed_slice_element_tripwire` did not catch it: its
body reads the element, and the body's own (correct) reading dominated the verdict, so
it was already FAILED for another reason. Both sign records are now made, and both
entries verify→refute when either is removed.
A literal is read at the radix it is written in. `0xFF` is `255`, `0b1010` is `10`
and `0o17` is `15`, in any width and with underscores or a type suffix (`0xFFu8`,
`0xFF_FF`). Reading every literal as decimal silently made `0xFF` equal `0` — the
digit run stopped at the `x` and the rest was skipped as a type suffix — and a wrong
value in a precondition is a *false proof*, not a refusal: `requires: x == 0xFF`
became `x == 0`, so `ensures: ret == 0` was proved for a function returning `255`. A
literal that is not an exact integer — a digit invalid for its radix (`0b12`, `0o9`),
no digits (`0xg`), an unknown suffix (`0xFFg`), or a value past `u64` — is refused,
so the fix does not trade one silent number for another.
The scanner is deliberately strict. A `requires:`, `ensures:` or `invariant:` that sits before a
`const`, a `struct` or a module comment is *not* attached to the next function, so
a misplaced contract is dropped rather than silently applied to the wrong item.
A contract expression outside the grammar — a function call, an unknown name, a
shift by a symbolic amount — is refused rather than approximated. An `invariant:`
clause carries no loop label, so a function may have at most one; a second is
refused rather than guessed at, since pairing the wrong text with the wrong loop
would check an obligation that does not mean what the source says.
The expression grammar is Rust's own subset, with Rust's precedence, so a contract
reads like the code it describes:
| bitwise or | `\|` |
| bitwise xor | `^` |
| bitwise and | `&` |
| shift | `<<` `>>` |
| additive | `+` `-` |
| multiplicative | `*` `/` `%` |
| unary | `-` (negation) `!` (bitwise NOT on a value, negation on a predicate) |
| comparison | `==` `!=` `<` `<=` `>` `>=` |
| logical | `&&` `\|\|` |
| cast | `as u8` … `as u64` (an atom followed by one or more `as <type>`) |
`>>` is arithmetic on a signed operand and logical on an unsigned one, and `/`/`%`
take the signed quotient or remainder when either operand is signed — the same
choices the body makes. A *negated literal* is signed, so `-7 % 3` is `-1` (the sign
follows the dividend), `-7 / 2` is `-3` (truncated toward zero) and `-7 < 3` is
true — Rust does not compile `let x: u32 = -1;`, so a negation is its own evidence
of a signed type. A unary `-` binds *tighter* than `as` (`-x as u8` is
`(-x) as u8`, type `u8`). A unary `!` on a *value* is bitwise NOT and binds tighter
than `==`, so `!x == 5` is `(!x) == 5` (`x == 250` for a `u8`), not `!(x == 5)`; on a
parenthesized *predicate* it negates, so `!(x == 5)` is `x != 5`. A cast *extends*:
`-1i8 as i16` is `-1`, and `-1i8 as u16`
is `65535`, not `255`. A shift amount must be a *constant expression* — `x >> 1 + 1` is
`x >> 2` — and a *symbolic* amount is a barrel shifter in the body and is refused in a
contract rather than guessed at. A divisor of constant zero is refused however it is
spelled (`0`, `1 - 1`, `2 - 2`), matching rustc's `unconditional_panic` lint.
The engine's words are 64 bits, so a `u128`/`i128` type is refused rather than
mis-modelled: a function with a 128-bit argument, local or return, and a contract
casting *to* one, both report the function as skipped. This is a refusal, not a
crash — a width the engine cannot hold is decided before any width-taking
constructor runs.
### A diverging call is a checked panic, not a dropped line
`assert!`, `debug_assert!`, `panic!`, `unreachable!`, `todo!`, `unwrap`, and the
bounds and slice checks `rustc` inserts all lower the same way: a call into
`core::panicking` (or a user function returning `!`) with **no `[return: bbN]`
arm**, because the call never returns.
```rust,ignore
/// requires: x <= 200
/// ensures: ret == 1
pub fn f(x: u8) -> u8 { assert!(x <= 200); 1 }
```
The parser recognised only the `[return:` shape, so this terminator came back
`Unknown("missing")`, the path was reported unmodelled, and the whole function was
`Incomplete`. The most ordinary safety guard in Rust was never checked at all —
`f` above was not proved, it was *skipped*, and a caller reading "incomplete" for
an `assert` would be right to distrust the tool.
The two call shapes are now read separately, and the diverging one becomes a
**panic obligation** rather than a silent drop:
* the obligation is `path`, "is this call reachable", discharged by `Unsat` — the
same polarity as the `assert` terminator, and for the same reason. The `switchInt`
that routes into the call already carries `!guard` in its path, so the query is
really about the guard;
* the fall-through of a *non*-diverging `assert` terminator still assumes the
guard, so code after an `assert!` may rely on it;
* the report names the failure from the string literal the dump passes, so an
unproved `assert!(x <= 200)` reads `panic: assertion failed: x <= 200` with the
counterexample that fires it, instead of a mangled callee path. Edition 2024 does
not pass a literal for a *formatted* message — `panic!("bad {}", x)` builds an
`Arguments` through `core::fmt` — so those pieces are recovered from that chain,
with the placeholder count taken from the call's own argument count
(`Arguments::new_v1::<P, A>`) rather than guessed from the pieces.
This is the sound direction, and it is the same shape as the `DivergentCall`
finding in `wp` — a construct that cuts a path off must be *recorded*, because
everything downstream of it is vacuously true. The teeth are a matched pair:
`an_assert_is_checked_and_discharged_under_its_precondition` pins the proof, and
`an_unproved_assert_is_refuted_with_a_counterexample` pins the refutation. A user
function returning `!` is treated the same way, so `if x == 0 { die(); }` is a
failure at `x == 0` and is proved unreachable under `requires: x != 0`.
`a_formatted_panic_message_is_recovered_from_the_fmt_chain` pins the message
recovery on whichever toolchain `VERIF_RUSTC` names — the `new_v1`/promoted-array
spelling on the MSRV and the `new::<LEN, A>` byte-template spelling on stable — and
`a_literal_panic_macro_names_its_message` pins that `unreachable!()` and `todo!()`,
which pass a literal, still name the text the programmer wrote. A name is never
reported as its type arguments: `panic!("{}", x)` has no literal piece at all, so it
falls back to the callee's name read through its generics (`panic_display`, not
`<u8>`).
### A `drop` is a terminator with a real successor
`drop(_x)` is the terminator `rustc` emits for a local whose type has drop glue, and
it prints with the same `-> [return: bbN, unwind continue]` shape as a call. So the
call arm claimed it, and because a `drop` line has no ` = ` destination,
`parse_call_head` returned `None` and the arm's fallback turned the whole line into
`Unknown` — reported as "unmodelled terminator", dropping the path. Every RAII local
lowers to a `drop`, so a function holding a `Vec`, a `String`, a lock guard or a user
`Drop` was `incomplete` for a reason that had nothing to do with its contract. It has
its own parser arm now, and `successors` knows the terminator has a normal successor,
so the path continues past it. (The old code had a `drop(` branch too, but it was
dead: the call arm above it matched first, because the line contains ` -> [return:`.)
Three cases, and the middle one is the soundness boundary:
* a type with **no drop glue** runs nothing, so the terminator is a no-op. rustc
emits no `drop` for such a type, so this arm is *defensive* — measured over
`realistic.rs`, 0 of 6 `drop` terms are glue-free — and its check lives in a unit
test rather than in a corpus fixture that could not exercise it;
* a **user `impl Drop`** has a body in the dump, so it is executed through the same
inliner a method call uses. The destructor's `self` is `&mut T`, so the dropped
place is the argument and the `by_ref` copy-back carries the destructor's writes
back to the caller. A destructor that panics is therefore a real obligation:
`destructor_panic_cannot_prove_this` is refuted with the witness that fires the
destructor's own `assert`, and its guarded twin verifies;
* **anything else** — a `Vec`, a `String`, a `Box`, a `MutexGuard`, or a generic `T`
whose glue the dump does not spell — is **refused**, never assumed to be a no-op.
This is the one place the review's first suggestion ("a std container is a no-op
that changes no scalar state") was unsound: the dump cannot tell a `Vec` from a
struct holding a user-`Drop` field, because both print the same `drop(_x)` line, so
treating the container as a no-op would prove a function panic-free whose destructor
panics. A refusal is a lost proof, never a false one.
The parser side is pinned by `parses_a_drop_terminator`; the executor's three cases by
the `tests/mir.rs` Drop tests and the `realistic.rs` fixtures; the no-op table by
`a_glue_free_type_has_a_noop_drop`, which needs no compiler. The `rustc_public` oracle
agrees on the parser's reading of the terminator's real shape.
### What is read from where, and why
| the body | `rustc --emit=mir` | the real lowering, including the checks `rustc` inserts |
| the contract | the source text | MIR carries no attributes or doc comments |
| the compiler | `VERIF_RUSTC`, else `rustc` | `--emit=mir` is stable, so the `rustc` on `PATH` is enough; the variable exists to point the frontend at a *different* compiler without disturbing cargo's own |
| the edition | `MirOptions::edition`, else `VERIF_EDITION`, else the nearest `Cargo.toml` | the edition changes the lowering, so a verdict is only meaningful under the edition the crate is built with |
The edition is resolved in that order, and it is never *guessed*: the first match
wins, and a value that is set but not one of `2015`/`2018`/`2021`/`2024` is an
error rather than a silent fallback. A file that lives in a crate takes the
edition from the nearest `Cargo.toml`'s `package.edition` (resolving
`edition.workspace = true` against the workspace root), and a `[package]` that
omits the key resolves to **2015**, which is Cargo's own default for a package
that does not state one. Only a *loose* file -- one with no manifest above it --
has no crate edition to infer, and it must be given one:
```bash
# A loose file has no Cargo.toml, so name the edition explicitly.
VERIF_EDITION=2021 VERIF_RUSTC="$(rustup which rustc)" \
cargo run --features std --example mir_coverage -- /tmp/probe.rs
```
A program calls the frontend directly through `MirOptions { edition: Some(..) }`,
which takes precedence over both; the environment variable is for the examples and
the tests, which have no options struct to fill in.
The five differential oracles (z3, Kani, Lean, Coq, Verus) all build their terms
with `smt::` calls, so they start *below* the contract reader. That left the reader
— the layer that turns contract text into terms — with no independent check, and
three parser bugs in a row (a negated literal read as unsigned, so `-7 % 3` was `0`;
a cast applied before a negation, so `-x as u8` had the wrong type) were found by
hand rather than by a gate. `the_contract_reader_agrees_with_rustc_on_a_grid` in
`tests/mir.rs` closes it against `rustc` itself: a *value* construction (the body is
the expression, so `ret == <expr>` is the agreement claim) and a *guard*
construction (`x == v && <expr> > t`, which is where a wrong *type* shows up, since
the value of `-x as u8` is the same under both readings but its type is not). The
oracle is itself checked by reverting each fix and confirming it fails.
### The edition and the minimum compiler
The crates are **edition 2024**, and `rust-version = "1.85"` in both manifests.
Edition 2024 is what the language is now: `gen` is reserved, `unsafe_op_in_unsafe_fn`
is on, and the pattern binding modes are the strict ones. Since 1.85 is exactly the
release that stabilised the edition, the floor and the edition are the same
decision — there is no version that takes one without the other.
The floor is a *lower* bound, not a pin. Everything here builds on current
stable (1.100 at the time of writing), and the MIR frontend runs on that same
stable `rustc`: `--emit=mir` is a stable flag, checked here down to 1.85, so no
part of the product needs a nightly. Only two *oracles* do — `tools/mir-oracle`
links `rustc_public` and the `rustc-dev` component, and Kani tracks a nightly —
and an oracle is a test tool that never enters the dependency tree. The
oracles' own toolchains move independently and are all newer: Verus pins the
compiler version its driver reports (CI installs exactly that toolchain), Kani
tracks a nightly, and Ferrocene — the qualified compiler, which is the one whose
ceiling could matter for a safety build — is currently downstream of Rust 1.96,
comfortably above 1.85. So no oracle forces the floor down, and none is held
back by it.
The MSRV is deliberately *not* raised to follow them. A `no_std` crate that ships
into a bare-metal safety build is the one place a high floor costs something real:
it locks out qualified and long-term-support toolchains that lag upstream. 1.85
buys the current edition at the oldest version that has it, and every later
compiler still works, so nothing is given up by staying there.
### The arithmetic, and one new primitive
MIR makes the checks explicit, so modelling them is most of the work. `a + b`
lowers to `AddWithOverflow` plus `assert(!(_3.1))`; the same for `SubWithOverflow`
and `MulWithOverflow`, and `/` comes with a `assert(!(_6))` for a zero divisor. The
`!` matters: rustc prints the failing polarity, and dropping it inverts every
check. `tests/mir.rs` and the parser's unit tests pin that.
Modelling overflow exactly needed a widened product for the *signed* case, which
exposed a fact worth writing down: **`smt::truncate` zero-extends when the target
is wider.** A signed `a * b` at `u16` is computed at 32 bits and compared with the
sign-extension of the wrapped result, so the predicate is exact rather than
approximate. The *unsigned* test is exact *without* widening, because
`x * y > MAX` iff `y != 0 && x > floor(MAX / y)`: the restoring divider decides it,
no `2w`-bit multiplier is built, and the form matches the guard a saturating
multiply is written with. That is what turned `sat_mul` from `incomplete` into
`verified` — the guard and the overflow test become structurally identical terms, so
the boolean fold collapses `guard && !guard` to `false` before the divider is ever
blasted (see the note on the multiply-overflow predicate below). Division needed
something the engine did not have, so `smt::divmod` builds a restoring divider out
of shifts, subtract, compare and select. It is exact — `tests/divmod.rs` checks it
against Rust's own `/` and `%` at every interesting boundary and proves
`(x / y) * y + x % y == x` and `x % y < y` symbolically. `y == 0` is given a
*defined* value (quotient all ones, remainder the dividend) rather than being left
as a hole, and rustc's own divide-by-zero assert is what turns that case into a
reported panic.
A *variable* shift amount needed two things that turned out to be one. The engine
gained `smt::shift_var`, a barrel shifter of `log2(w)` conditional stages, so
`x << n` is now in the vocabulary rather than refused. But the frontend also had to
start *assuming* an assert it had already checked: `Term::Assert` pushed the
fall-through block with the incoming path unchanged, so `assert(n < 16)` was proved
(a panic is reported when `n == 16`) and then discarded, and every obligation after
it was discharged as if `n` could still be 16. That is sound — the guard is checked
separately — but it is needlessly weak, and it is wrong for a guard the *caller*
wrote. The fall-through path now carries `satisfied`, which is what lets `sat_shift`
prove and what makes the modelled shift meaningful.
The shift is only half of it. rustc prints a cast constant as
`const 3_i32 as u32 (IntToInt)`, and `parse_rvalue` matched the `const ` prefix
*before* the ` as ` form, so the whole string went to `parse_const`, which read
`i32 as u32 (IntToInt)` as a type name and produced a constant with no width. Every
guard written against such a constant — `x << 3`, and the `assert(n < 16)` for a
`u16` shift — was then unmodelled, which is why a plain constant shift used to come
back `incomplete`. Checking the cast first fixes both. `tests/shift.rs` checks the
barrel shifter against Rust's own `<<` and `>>` at the interesting amounts, proves
it agrees with the constant path symbolically, and requires that a variable shift is
*not* the identity so a shifter that returned its input cannot pass.
### `core::num` is modelled rather than called
The `checked_*`, `saturating_*` and `wrapping_*` families are how real Rust writes
arithmetic that must not panic, and a call the frontend cannot model makes the
whole *path* unknown. So these are computed from their operands instead of being
refused. `src/mir/intrinsics.rs` holds the model:
- `wrapping_*` is the plain operator, because the plain operator already takes the
result modulo `2^w`. The term is the *same term* `a + b` produces, not a second
definition that could drift from it. A `wrapping_mul` needs no overflow test, so
it is admitted up to `MUL_MAX_WIDTH` (`32`) rather than stopping where the widened
product does; a `u32` `wrapping_mul` is a plain 32-bit multiply and settles in
milliseconds.
- `saturating_*` is `ite(fails, bound, plain)`, where `fails` is the very predicate
rustc's own `assert` reads and `bound` is the sign of the overflow. A function
written with `saturating_add` and one written with a hand-rolled guard are decided
by one rule.
- `checked_*` is an `Option<T>`: the tag is `1` where the operation is defined and
`0` where it is not, and the payload is the result. The tag is a *term*, not a
constant, so the `switchInt` on it takes the right arm on each path. rustc emits
the downcast payload read only inside the `Some` arm, which is what makes
recording the payload unconditionally sound.
- The unary `neg` and `abs` are `0 - x` and "negate if negative" in all four
families, and the six bit counts (`count_ones`, `count_zeros`,
`leading_zeros`, `leading_ones`, `trailing_zeros`, `trailing_ones`) are sums over
the operand's bits. The three *complement* counts are not a second summation:
each is `core`'s own definition, the corresponding positive count of `!x`, so
`count_zeros` is `count_ones(!x)` and a fix to one half cannot leave the other
behind. `!x` is spelled the way the executor spells it, so the model's `!x` and
the body's `!x` are the same term.
- `is_power_of_two` is a modelled shape whose *return type* is `bool`, so it
produces a predicate rather than a bit-vector. The executor writes it as a
`bool`, which is what the `if` that consumes it branches on; a one-bit word
there would leave the local readable only as a word. It is unsigned-only,
matching `core`.
- `is_negative`/`is_positive` are `bool` predicates too, and the model is
`core`'s own definition: `x < 0` and `x > 0` read *signed*. They exist only on
the signed types, and the signedness is the whole content — `i8::MIN` (`0x80`)
is the *largest* unsigned byte, so an unsigned reading of the top bit would call
it positive. Each is checked exhaustively against Rust's own method over `i8`
and `i16`, with `i8::MIN` named as the point an unsigned reading gets wrong.
- The ten `is_ascii_*` class tests (`is_ascii_digit`, `is_ascii_alphabetic`,
`is_ascii_alphanumeric`, `is_ascii_uppercase`, `is_ascii_lowercase`,
`is_ascii_hexdigit`, `is_ascii_whitespace`, `is_ascii_punctuation`,
`is_ascii_control`, `is_ascii`) are `bool` predicates too, and each is `core`'s
own range test on the byte (`is_ascii_digit` is `b'0'..=b'9'`, `is_ascii` is
`b < 128`, whitespace is the five `core` names — vertical tab excluded). They
are the first modelled methods whose receiver is `&self`, so the operand is the
*referent* of a reference the body materialises (`_3 = &_1`): the executor
follows the reference for these shapes and only these. Each is checked
exhaustively against Rust's own `u8` method, so the boundaries cannot drift from
the standard library's.
- `slice::len` and `slice::is_empty` are modelled from the slice's length
variable — the same symbolic input the frontend already binds for the bounds
checks — so a contract's `s.len()` and the body's `PtrMetadata(_1)` are one
number. They are matched on the *path* (`core::slice::<impl [T]>::len`), so a
`Vec::len` or `str::len` is not mistaken for a slice length; and the receiver's
length has to be one the frontend holds, so a receiver it did not bind is
refused rather than given an invented number.
- `slice::first` and `slice::get` are modelled for a *concrete* slice. They return
`Option<&T>`, so the payload is a *place*, not a value, and the model writes the
`Option`'s tag as a *predicate* — `len == 0` for `first`, `k >= len` for `get(k)`
— which is what makes the `unwrap` that usually follows carry a real panic
obligation rather than an assumed `Some`. The payload is the slice's *own*
element variable, the same one `xs[k]` names, so `*xs.first().unwrap()` and
`xs[0]` agree by construction; the returned reference's deref (`*_2`) reads
through a dedicated `Env::slice_elem_ref` store, and both `unwrap` and the
`match` desugaring (which reads the payload through a downcast temp) carry the
element to their destination, so the two spellings decide alike. `get`'s index
must be a *constant*: a slice's length is symbolic, so a symbolic index has no
finite domain and reading "some element" would be a wrong proof, not a missing
one. The *generic* `first_or<T>` is not this shape — it needs monomorphisation —
so it stays refused.
- `Ord::min` and `Ord::max` are the two modelled *trait* methods, so a dump spells
a call `<u8 as Ord>::min` (or `<i8 as std::cmp::Ord>::max` with `std` in scope)
rather than a `core::num::<impl …>` inherent path. The model is one `ite` over
the two operands, and the *sign* selects the ordering — `sle`/`sge` on a signed
type, `ule`/`uge` on an unsigned one — so both signednesses are exact. The sign
matters: `i8::MIN`'s bits (`0x80`) are the largest unsigned byte, so an unsigned
ordering would return the wrong operand for every pair with a negative side. Only
the standard library's `Ord` is accepted — the trait path must be exactly `Ord`,
`core::cmp::Ord` or `std::cmp::Ord`, which a user cannot define — so a local
trait's `min` is refused by name as well as by the same-dump lookup below.
- `From::from` and `Into::into` are the two *widening conversion* trait methods, so
a dump spells a call `<u16 as From<u8>>::from` (or `<u8 as Into<u16>>::into`).
They are the one modelled shape whose two operands have *different* types, so the
model reads both types from the call's name and extends the source by its *own*
signedness: `i8::MIN` widens to `i8::MIN` (a sign-extension), `255u8` to
`255u16` (a zero-fill). The source's sign decides the extension, not the
destination's, so `i16::from(255u8)` is `255` and not `-1`. A *strict widening*
between modelled integers is accepted, which is exactly every widening `From`
`core` implements, so a real call is never a guess. A *same-width* call is
`core`'s reflexive `impl<T> From<T> for T`, whose result is the source
unchanged, and is modelled as exactly that. Only a *narrowing*, or a source the
engine does not hold (a `bool`, say), is refused and the path is reported
unknown. The trait path must be exactly `From`/`Into`, `core::convert::…` or
`std::convert::…` — none of which a user can define — so a local `From` in a
module is refused by name.
- The inherent `iN::abs` and the trait `Ord::clamp` are the first modelled methods
whose failure is a **panic**, so the model carries *two* channels — the value and
a `fails` predicate — and the executor turns the predicate into a panic
obligation beside the value. The value is defined at every input (the wrapped
absolute value, the clamp expression), and the predicate is where `core`'s own
`assert` fires: `abs` fails exactly at `MIN`, and `clamp` fails exactly at
`lo > hi`. An out-of-range `x` is *not* a clamp panic — clamping it is the whole
point — and reading it as one made a true corpus function fail until the probe
corpus caught it. `abs` takes its sign from the operand (`Abs` joins the
sign-reading arms), and `clamp`'s comparisons are the type's own, so a signed
clamp reads `i8::MIN` as below `0`. Both are refused on a non-primitive self
type, and `clamp` is admitted only under the standard library's `Ord` path, the
same rule `min`/`max` follow.
- The inherent `iN::unsigned_abs` is the same magnitude as `abs` read as the
*unsigned* type (`i8::unsigned_abs(-128)` is `128u8`), so it reuses the same
`0 - x`/`x` `ite` — but it is *total* where `abs` panics: at `MIN` the
truncating subtraction is exactly the magnitude, which is the very bit pattern
the signed `abs` cannot represent. It is therefore a plain value with no
failure predicate, labelled unsigned on the way out so `128` is not read back as
`-128`. The pair is what makes `abs`'s panic meaningful: one call fails at `MIN`
and its sibling does not.
- `iN::abs_diff` and `iN::rotate_left`/`rotate_right` are total, so they are plain
values rather than a value-and-panic pair. `abs_diff`'s result is the *unsigned*
magnitude even on a signed type — `i8::abs_diff(-128, 127)` is `255u8` — so the
model widens both operands by their *own* sign to `w + 1` bits, subtracts there,
and takes the absolute value with a *signed* sign test: the `w + 1`-bit range is
exactly a signed one, so an unsigned difference `0 - 1` is read as `-1`, not as
`255`. The rotations reduce the amount modulo the width the way `core` does — a
rotation by the width is the identity and by `w + 1` is by `1` — and because a
modelled width is a power of two the reduction is one `and` and no divider. Both
are checked exhaustively over `u8`/`i8` against Rust's own methods, so the
rotation's wrap cannot drift from the standard library's.
- The remaining total `core` value methods are modelled as plain values, each
checked exhaustively against Rust's own method over the whole `u8`/`i8` domain:
`signum` (`-1`/`0`/`1`, signed-only, so `i8::MIN`'s top bit is read as a sign
rather than the largest unsigned byte); `cast_unsigned`/`cast_signed` (the
same-width signedness re-interpretation: the value is the operand *unchanged*,
and only the result *type* differs, so it is the one shape whose result sign is
the opposite of the operand's — read from the call's destination type, not
derived from the operand, which is what a later comparison or division then
consults); `reverse_bits` (a shift-OR fold, both
signednesses); `swap_bytes` (a rotation by `w/2` bits — the byte reversal, not a
rotation by `w/2 * 8`); `to_be`/`to_le` (a byte swap or the identity according to
the *target's* endianness, read from `cfg!(target_endian)` rather than guessed;
`core` has no `to_ne` value method, only `to_ne_bytes`); the ASCII case
conversions `to_ascii_uppercase`/`to_ascii_lowercase` (`u8`-only, a range test
over `b'a'..=b'z'`/`b'A'..=b'Z'`); and `is_multiple_of` (unsigned-only, `a % b ==
0` with `b == 0` defined as `a == 0`, so the `b != 0` guard and the `|| a == 0`
disjunct both carry). The `_bytes` forms of the byte orders return an array, not
an integer, so they are left unmodelled rather than written as a word.
- `iN::div_euclid`/`rem_euclid` and `uN::div_ceil` are the division shapes that are
*not* the truncating `/`/`%`. Each has a value *and* a panic predicate, because
each panics on a zero divisor (and `div_euclid`/`rem_euclid` also on `MIN / -1`,
the same predicate `checked_div` reports) — modelling them as total would hide a
panic. The Euclidean quotient is `a / b` adjusted *the other way* when the
truncating remainder is negative (`q - 1` for a positive divisor, `q + 1` for a
negative one; `-7.div_euclid(3)` is `-3`, not `-2`), the Euclidean remainder is
`a % b + |b|` when negative, and `div_ceil` is `a / b` rounded up. They are
signed-only (`div_euclid`/`rem_euclid`) or unsigned-only (`div_ceil`) and bounded
at `DIV_MAX_WIDTH`, like every divider-backed model. Each is checked against
Rust's own method at every input the call does not panic on, with the panic
predicate compared at *every* input.
- `iN::midpoint`, `iN::next_multiple_of` (and its `checked_` counterpart),
`iN::ilog2`/`ilog10` and the
`next_power_of_two` pair are the rounding and magnitude helpers. `midpoint` is
total and computed without a sum at the operand width — `(a & b) + ((a ^ b) >> 1)`,
plus a `+1` correction for the signed case when the result is negative and
`(a ^ b)` is odd, which is the truncation toward zero `core` documents (`-5` and
`-2` mid at `-3`, not the floor `-4`). `next_multiple_of` is unsigned-only and
value-and-panic (`a + (b - a % b) % b`, panicking on a zero divisor or an
overflow), and `checked_next_multiple_of` is the same value and condition as an
`Option` (`None` exactly where the plain call would panic, so its tag is a term
and no panic obligation is emitted). `ilog2`/`ilog10` exist on both signednesses,
are value-and-panic (a
non-positive argument panics), and return a `u32` whatever the operand's type;
`checked_ilog2`/`checked_ilog10` are the same value as an `Option`, `None` exactly
where the plain form panics, with the same `u32` payload.
`next_power_of_two` (unsigned-only) and its `checked_` counterpart are the
rounding sibling of `is_power_of_two`: the classic smear-and-add (`p = x - 1`,
forced to `0` for `x <= 1`; `p |= p >> 1; p |= p >> 2; …`; `p + 1`), which is
total at `w` bits — the plain form panics where the result does not fit
(`x > 2^(w-1)`) and the `checked_` form returns `None` there. Each is checked
exhaustively against Rust's own method (the `next_power_of_two` pair at 1/4/8/16
bits, with the oracle computed at the *model's* width).
- `Option`'s `unwrap`, `unwrap_or`, `expect`, `is_some` and `is_none`, and
`Result`'s `is_ok`, `is_err`, `unwrap` and `unwrap_or`, are the first modelled
calls that read an *enum* rather than a bit-vector operand: the receiver's tag
and payload, which the model's own `checked_*` family writes (`checked_add` on a
`u8` writes the tag and payload of an `Option<u8>`) and which a contract-bound
`Option`/`Result` argument also fills. `unwrap`/`expect` return the payload and
report a **panic** on the failure variant, the same reachable-failure obligation
`abs` and `clamp` carry, so the idiom `if x.is_some() { x.unwrap() }` verifies
with the panic ruled out; `unwrap_or(default)` is *total* — the payload on the
success variant, the default on the failure one — and the predicates are the tag
tested against the success/failure discriminant. The receiver is `self` for the
value methods and `&self` for the predicates, so the executor follows the
reference either way. The two families are one shape: `Option` puts the payload
on `Some` (tag `1`) and `is_some` tests that tag, `Result` puts it on `Ok` (tag
`0`) and `is_ok` tests *that* tag, so a single executor arm answers both with the
payload variant read off the method name. They are matched on the
`option::Option`/`result::Result` path rustc prints, so a user type spelled
`Option`/`Result` is refused, and a same-dump body wins the lookup first. This
closes the `checked_add(..).unwrap_or(u32::MAX)` and `checked_div(..).unwrap()`
idioms, whose `Option` handling was the gap — the remaining `div_unwrap`
incompleteness is the *divider* wall (`n / d <= n` at `u32`), not the `Option`,
and the same body decides at `u8`.
- A *local* method that shares an intrinsic's name is answered by its own body,
never by the model. rustc prints a trait impl's call as `<u8 as Trait>::m` but
its definition as `<impl at …>::m`, so the names never match; the model is only
consulted when no same-dump body exists and the call name carries the `<impl …>`
projection that every real `core` method call has. Without both halves, a trait
that disagrees with `core` would get a *false proof* from the model.
`Ord::min`/`Ord::max` and the widening `From::from`/`Into::into` are the two
exceptions to the projection rule — a trait call has no `<impl …>` — and each is
admitted only under the standard library's trait path (and, for `Ord`, only for a
*primitive* self type). A crate-root trait named `Ord` or `From` is the one
spelling that prints its own call with a bare trait path too, so the same
trait-path check separates it from the library trait — the local `From` is not a
suffix of `std::convert::From`, and the model answers only the library spelling.
- The same-dump lookup is *trait-aware*, so a local impl on a primitive cannot
answer a call the compiler resolved to a library trait. The hazard is concrete:
a local `impl From<u8> for u16` returning `7` shares the method tail (`from`)
*and* the owner (`u16`) with `core`'s `impl From<u8> for u16`, so matching on the
owner alone answered `<u16 as std::convert::From<u8>>::from` from the local body
— a false proof of a library call. A *trait* call (`<T as Trait<…>>::m`) is now
admitted only when the call's trait path is a `::`-aligned suffix of the candidate
impl's own trait path, which the source records (`impl_traits`): the local impl's
bare `conv_shim::From` is not a suffix of `std::convert::From`, so it is refused,
while the local trait's own call still reaches its body. A bare `Type::m` call
carries no ` as ` projection — rustc prints an inherent method and an in-scope
trait method that way — so it keeps the owner-type match alone, as before.
- A trait call's *instantiation* is part of its identity, not just its path and
owner. `impl From<Local> for u16` returning `107` and `core`'s `impl From<u8> for
u16` share the trait path, the owner and the method, so only the trait's
*argument* separates them; a local `impl From<Local> for u16` once answered
`<u16 as From<u8>>::from(7u8)` from its own body — a false proof. The argument is
now read on *both* sides, with the same balanced reader
(`spec::angle_inner`): `call_trait_args` from the call's name,
`Specs::impl_trait_args` from the impl header. A nested argument
(`impl Wrap<Option<u8>> for W`) is the case that keeps the reader honest — a
"strip trailing `>`" reading on the call side cut *every* closing bracket
(`Option<u8`), matched no impl, and turned a call with a real body into an
unmodelled one — a lost proof. An unreadable side is refused, not waved through.
- The import scan reads the source's `use` items, because rustc prints an imported
trait's call with the *imported* path (`use std::convert::From as Conv;` makes
`impl Conv<Local> for u16` print `<u16 as std::convert::From<Local>>::from`).
Imports are kept per module path, folded across the item's lines, and read
through any visibility (`pub(crate)`, `pub(in …)`), so a lost import — which
qualifies an impl with its own module and loses the call — is not the failure
mode. A `#[cfg]`-conditional `use` is the exception to order-independence: it
binds only when its condition holds, and rustc then binds nothing, so a
conditional binding never displaces an unconditional one (a disabled
`#[cfg(any())] use crate::Other as Conv;` once overwrote a live alias and lost
the call). An attribute on the `use`'s own line is peeled first, so a live
`#[cfg(all())] use …` is read rather than skipped, and the attribute block above
the `use` is read as whole bracket-balanced items, so a condition that *spans*
lines (`#[cfg(all(\n any(),\n))]`) is found too. A delimiter inside quoted
text is not a delimiter: `#[doc = "("]` carries an unmatched `(` in a string,
and counting it would run the reader past the attribute's real end, so string
and character literals are skipped (escapes honoured) while matching `#[…]`.
- `add_signed`/`add_unsigned` add a value to one of the *opposite* signedness
(`u8::wrapping_add_signed` adds an `i8` to a `u8`), so the two operands are read
at different signs. The value is the plain wrapped sum in both directions, since
rustc reinterprets the addend and adds. The overflow flag is the addition's own
overflow *adjusted by the addend's sign*, `carry XOR (addend < 0)` — not the
ordinary signed-addition rule, which is wrong on half the domain. `250u8 +
(-1i8)` carries but is in range, so the flag is `false`; `0i8 + 128u8` does not
carry but runs off the top, so it is `true`. The saturating clamp follows the
addend's end: `0` or `255` for an unsigned self, `127` for a signed one.
The refusals matter as much as the model, and each has a reason. Only `checked_div`
and `checked_rem` may model division: the `saturating_` and `wrapping_` forms *panic*
on a zero divisor, and modelling a panicking operation as total would hide a panic,
which is the one thing this frontend must never do. The shifts are refused because
the three families disagree about the amount — `wrapping_shl` reduces it modulo the
width, the engine's variable shift saturates to zero, and `checked_shl` returns
`None` past the width — and three behaviours under one name is not something to
guess at. `unchecked_*` is undefined behaviour, and a proof about UB is not a proof.
A name that is not in the table does not classify, and a name that classifies but
whose shape is past a width limit is refused by `eval`, which leaves the path
unknown rather than slow.
`src/mir/intrinsics.rs`'s unit tests are the oracle: every case is compared against
the real `core` call, over all of `u8` and all of `i8`, so the model is checked on
*every* input rather than on the ones that happened to be tried. That is what pins
the signed rules, which the unsigned tests cannot see — `-1 + 1` does not overflow,
but the unsigned carry test fires on it. The widths past the limits, the refused
names, and `i8::MIN / -1` are checked too.
### What it declines, and why that is the point
The frontend refuses far more than it accepts, and every refusal is reported:
- **MIR it cannot parse.** An unrecognized statement becomes `Unknown`, which
makes the path "not modelled", never "proved".
- **A signed multiply whose overflow test needs a `2w`-bit product.** This is no
longer a refusal. The predicate used to be written as a test on the sign-extended
`2w`-bit product, which is the BDD scaling wall, so past 16 bits there was no
predicate and the path was reported `incomplete`. The signed test is now the exact
division form, in the same shape as the unsigned one: `|x| > limit / |y|` with
`y != 0`, where `limit` is `2^(w-1) - 1` when the operands share a sign (the product
is positive) and `2^(w-1)` when they differ (the product is negative). It needs no
widening, so a predicate exists at `i64`, and it is exact for every combination of
the two signs — the claim that no such form exists was wrong, and brute force over
~93M cases at widths 2..=14 found no counterexample. Whether the query is then
*decided* still depends on the diagram budget, exactly as it does for the unsigned
form: a guard written as this predicate cancels against the obligation's assert at
every width, while a bare multiply the engine has to reason about from scratch can
run out of budget and report `incomplete`.
- **A `core::num` product whose overflow test needs a widened `2w`-bit multiply past
`u32`.** The `checked_*`/`saturating_*`/`overflowing_*` families need the exact
product to test overflow, which is built by widening the operands to `2w` — the
BDD scaling wall. `MUL_MAX_WIDTH` is `32`, so a `u32` product's predicate is built
(a 64-bit multiply) while a `u64` one is refused (`2w == 128` cannot be held) and
reported "past what the model covers". The *value* families (`wrapping_*`) need no
widened product at all — they are a plain `w`-bit multiply — so they are admitted
up to the same bound and a `u32` `wrapping_mul` (the shape `hash_step` uses) now
decides, while a `u64` one is past the wall regardless. The refusal is the honest
answer: the path stays unknown rather than being proved from a truncated product.
- **`core::num` operations other than the modelled families.** `checked_*`,
`saturating_*` and `wrapping_*` for `add`/`sub`/`mul`/`div`/`rem` and the
bitwise ops are computed from their operands (see below), as are the unary
`neg`/`abs` in all four families, the six bit counts (`count_ones`,
`count_zeros`, `leading_zeros`, `leading_ones`, `trailing_zeros`,
`trailing_ones`), the `bool` predicates `is_power_of_two`,
`is_negative`/`is_positive` and the ten
`is_ascii_*` class tests, the `slice::len`/`is_empty` length queries, the
`Ord::min`/`Ord::max`
trait methods, the `abs_diff` and `rotate_left`/`rotate_right` methods, the
widening `From::from`/`Into::into` conversions, the
mixed-signedness
additions (`wrapping_add_signed`, `saturating_add_signed`, `checked_add_signed`,
`overflowing_add_signed` and their `_unsigned` counterparts) and the `pow`
families. Every other intrinsic, and every other trait
method, is still a call the frontend cannot model.
- **A symbolic index into a *slice*, or a mutable reference write.** An array
subscripted by a parameter (`a[i]` on `[u8; 4]`) *is* modelled: the length is in
the type, so `a[i]` is the exact ite chain over `0..N`, admitted only when the
precondition establishes `i < N`. A slice has no such bound — its length is a
symbolic input — so `xs[i]` is refused rather than resolved to an arbitrary
element. `*r = v` is the aliasing model the crate does not claim. Fields and
elements of by-value aggregates, and elements and lengths of slices and
fixed-size arrays, *are* modelled — only the pointer arithmetic is not.
A subscript whose index is a *local* that aliases an argument is resolved to that
argument. `let k = i; a[k]` on a `Copy` index lowers to no local at all — the
body's `a[k]` really is `a[i]` — so the contract's `k` names the same index, and
`a[k]` builds the same ite chain `a[i]` would. The name resolves only when the
aliased local is an argument that the body never writes, so `let k = i; i = 2;`
does not alias `k` to the reassigned `i`; that subscript is refused instead.
### Signedness is a value question, not a display one
`i8`, `i16` and friends are bit patterns like any other, so every operation has one
bit-pattern answer — but signedness decides *which question a comparison asks*.
`-1 < 1` is `false` read unsigned and `true` read signed; `-7 / 2` is `-3` signed
and a huge positive number unsigned; and a signed add overflows where the unsigned
carry says nothing is wrong. The frontend reads the declared type and picks the
signed form (`slt`/`sle`/`sgt`/`sge`, `sdiv`/`srem`), and the contract evaluator
does the same, because a contract's `<` is the same comparison as the code's.
The overflow rules differ too. A signed add wraps exactly when the operands agree
in sign and the result disagrees; a signed multiply when the sign-extended product
is not the sign-extension of the wrapped result, which is `rustc`'s own test. This
matters in the direction that hides bugs: the unsigned carry test fires on
`127 + 1` but *also* on `-1 + 1`, which does not overflow, and `MIN` is the top bit
rather than zero. The demo's `signed_add_misguarded` is the case that pins it —
`requires: a <= 127 && b <= 1` reads like a safe guard and is not one.
`tests/signed.rs` checks the signed operators differentially against Rust's own on
the same two's-complement values, and `examples/z3diff.rs` carries signed
identities in its corpus. `MIN / -1` and a zero divisor are *defined* rather than
trapped, for the same reason the unsigned divider defines `y == 0`: a hole in the
model is a hole in the proof. `rustc`'s own `assert`s are what turn those inputs
into reported panics.
`FnOutcome::Incomplete` is not a pass. `FileReport::is_clean` is false whenever any
path was unmodelled or any contracted function is missing from the MIR, and a
missing contract is reported rather than quietly turning a function green. This is
the same discipline as `Verdict::Unknown` in the engine: a bounded checker that
says "I could not decide" is worth more than one that guesses.
### The known gaps, stated
1. **Calls are inlined one level, or answered by a contract.** A call to a
function in the same file is symbolically executed; a call to a function whose
body is *not* in the file but whose contract is -- an `extern` declaration, or
any item the dump does not carry a body for -- is answered from that contract:
its `requires:` is proved of the call's arguments, its `ensures:` is assumed of
the result, and an unsatisfiable postcondition refuses the call as divergent.
The precondition obligation is what makes the assumption sound; a call outside
the callee's precondition fails rather than being trusted. A callee with no
postcondition gives nothing to assume and stays incomplete. A *self-call* with
a `decreases:` measure is answered by the same contract route with well-founded
induction added, so a recursive function with a measure is decidable and one
without it is reported incomplete at the depth bound. A callee whose parameter
list the source scanner cannot read (a pattern parameter, a wrapped signature)
is refused rather than bound positionally, and a reference argument is refused
because there is no aliasing model to carry a write back to the caller.
2. **The dump is textual.** The frontend parses `--emit=mir` output rather than
linking `rustc-dev`. That keeps the dependency count at zero and makes the
input inspectable, but it means a rustc release that changes the pretty-printer
can break the parser. It fails closed when that happens, and the
`rustc_public` oracle in `tools/mir-oracle` (gate 10) catches one half of that
risk: it compares each function's **basic-block count and the panic guards
`rustc` inserted** (kind and polarity) between the text and typed MIR, so a
printer change that alters the *structure* of a body fails CI. It does **not**
compare places, types, locals or projections, so a change that only re-spells
a place is invisible to it — `Len((*_1))` becoming `PtrMetadata(copy _1)` in
1.99 was exactly that, and it was found by running the frontend's suite under a
second toolchain, not by this gate — gate 10 was silent across it. `src/mir/shape.rs`'s
`the_shape_sees_structure_and_guards_but_not_places` pins both directions of
that boundary, so this paragraph cannot drift into claiming more than the code
checks.
3. **Contracts are checked at entry and exit only.** A loop invariant written as a
contract is not an invariant; it is an assertion at two points.
4. **The verifier is not inside the artifact.** `gnatprove` and this crate's own
embedded engine are in-process; the MIR frontend shells out to `rustc` and lives
behind the `std` feature. The engine it uses is the embedded one, but the
frontend that feeds it is a development tool, not something that ships on a
microcontroller.
5. **A `for` loop over a *range* is modelled; a `for` over a *slice or array*, and an
iterator chain, are not.** `for i in 0..n` / `for i in 0..=n` desugars to
`Range`/`RangeInclusive` construction, `IntoIterator::into_iter` and
`Iterator::next(&mut range)`, and all of those *are* in the model (with `core`'s
`forward_overflowing` boundary reproduced exactly), so the loop decides through the
same machinery a `while` loop uses — `for i in 0..=n { s += i }` verifies under a
`requires:` that bounds `n` (or an `unwind:` bound), and a body decided by an
*inductive* `invariant:` verifies with one. What is *not* modelled is `for x in xs`
over a slice or array (it lowers to `<&[u8] as IntoIterator>::into_iter`, which is a
different impl) and any iterator chain (`fold`, `map`, `sum`, `.iter()`); those are
reported `incomplete` with the unmodelled call named, so the gap is visible rather
than silent. Two things are worth knowing about the range form: an `invariant:` that
*names* the loop element (`s <= i`) is refused as `unknown name i`, because the
element is a `debug` binding that is genuinely not live at the loop header — write
the invariant over the loop's *carried* state (`s <= 5050`) — and the invariant must
be *inductive* (`s <= 5050` over a body doing `s += i` is not; `s = i.min(5050)` is).
A `while` loop carrying an `invariant:` and a `variant:` remains the way to state an
iteration the `for` desugaring does not cover, and it is *more* precise, not less: the
measure gives total correctness, where an unwound `for` gives a bounded check.
## What this is *not* — read this before trusting a green test
Honesty matters more than a nice README, so:
1. **Pointers, aliasing and concurrency are still out of scope.** `mem` models a
bounded *array*, addressed by an integer. It does not model pointers, address
arithmetic across objects, or two threads touching the same cell. You cannot
state "this pointer is valid" or "these two threads do not race" in it.
Quantifiers are bounded and expanded, so `forall` over an unknown domain is not
available either — the range must be a number the tool can count to.
1b. **Termination needs a variant.** Without one, `wp` proves partial correctness
only: a divergent loop can verify. There is no inference of variants — you
supply the measure, the engine checks it decreases.
1c. **A nested loop's effect on an outer variant is handled by havocing, not by
tracking.** `variant_after` treats an inner `while` as writing every variable its
body can write, so a measure that mentions one of them becomes an obligation about a
fresh variable and cannot be discharged. That is sound but conservative: you must
supply an outer measure that does not depend on the inner loop's writes, or a measure
that accounts for them explicitly. The alternative — reading the inner loop as a no-op —
was a real soundness hole and is described under "Why `variant_after` must havoc a
nested loop" below.
1d. **`with_fresh` must not be nested.** The inner call wipes the term arena and
invalidates every `Var` the outer scope holds. One `with_fresh` per proof.
1e. **A call to a procedure whose postcondition is unsatisfiable is refused, not
trusted.** `ensures false` means the callee never returns, so a caller's claims after
the call are vacuous. The report carries a `Rule::DivergentCall` failure rather than
calling it `Total`. This is the call-shaped twin of the unreachable-`Assume` and
unreachable-precondition findings; see "A call to a procedure that never returns is not
a proof either".
2. **There is a scaling wall, and the engine says so.** Boolean *equality of two
wide multipliers* is the classic blow-up: `(a*b)*c == a*(b*c)` at 12 bits
returns `Unknown`, and the test suite asserts exactly that. This is why
`Unknown` is a first-class verdict: the engine refuses to guess. The wall is
not removed, only pushed out.
3. **Two engines, one term graph, two blasters.** BDDs are canonical and give
equivalence checking for free, but they blow up on multipliers. When the BDD
arena fills, the *same* term graph is handed to a CDCL SAT solver (`sat.rs`,
`bitblast.rs`) that has no canonical-form wall.
The two engines share **no** circuit: `smt::blast` writes BDD node ids and
`bitblast::blast` writes `Lit`s, and each writes its *own* ripple adder,
subtractor, multiplier and comparator loop. They cannot be one function
because both gate arenas are `&mut`. What they share is the term graph, so
each operation is *named* once — its operands and width are fixed when the
node is built — but the bit-level circuit for it is written twice, so the two
can diverge. That is why the agreement is treated as a property to *check*
rather than to assert away, and the check has to be aimed at the right
blaster: the differential corpus (`tests/differential.rs`) and the z3 oracle
run at widths the BDD engine finishes, so they exercise `smt::blast` and
never reach `bitblast::blast` at all. The oracle that pins *this* blaster is
the `tests` module in `bitblast.rs`, which drives `blast` directly, forces
every input pair at 1–4 bits, and asks the solver whether the circuit can
differ from Rust's own wrapping arithmetic. It is exhaustive, and it is
load-bearing: dropping the carry-generate term from the adder there (making
it compute `xor`) survives `tests/differential.rs`, the whole `cargo test`
run and the z3 oracle, and only that module fails.
The SAT engine is exact but not fast, so it runs under a conflict budget and
answers `Unknown` when it expires — a verifier that hangs is worse than one
that declines. The gain is real but specific: `add_comm` at 64 bits is
`Unknown` from the BDD engine alone and `Valid` with the fallback (the
measurement is recorded in `AGENTS.md`, "A fallback engine is only worth its
weight if the wall actually moves"). Multiplication equality stays out of
reach at both engines' budgets; that is the honest state.
The trade made here is still *no external process, no allocator,
deterministic memory*. The SAT arena is a `static` in BSS, sized at compile
time, and a capacity overrun yields `Unknown`, never a wrong verdict.
The arena being a `static` also means the `std` build **serializes** every
SAT query: both `Mutex` guards are held across the encoding *and* the solve,
so two threads whose hard proofs fall back to SAT run one after the other.
The BDD engine does not serialize, because its arena is a `thread_local!` on
`std`. This is a throughput cost, not a correctness one — the solver is
deterministic and the locks are always taken in the same order — and it is
the price of a compile-time-sized arena with no allocator.
4. **`no_std` uses a single static arena**, so the symbolic engine is not
re-entrant across interrupt contexts. Wrap queries in a critical section, or
use one context per core. This is documented at the definition site.
5. **Counterexamples are witnesses, not optima.** A model is derived from a BDD
path, so it is *a* violating input, not necessarily the smallest one.
Enumeration finds the smallest.
6. **This is a research-grade experiment**, not a certified tool. It has no
qualification evidence, no DO-178C tool qualification, and no independent
review. Treat it as a demonstration of an idea, not as something to put on an
aircraft without doing the certification work.
## Why BDDs at all
Because canonicity buys the properties that make "verification in the code"
practical:
- **Equivalence is node identity.** No proof search, no heuristics, no timeouts
on the easy cases.
- **A proof is a small object.** A `Certificate` is a couple of machine words,
so it can live in the artifact and be passed around, unlike a SAT proof trace.
- **No allocator.** A fixed arena gives a compile-time memory bound, which is
what a safety case wants to see.
The variable order interleaves bit-planes by significance
(`level_of` in `smt.rs`), which keeps ripple-carry adders and unsigned
comparators linear in diagram size — the reason a 32-bit `x & 0xff < 256` proof
is instantaneous while a 12-bit multiplier equality is not.
## Layout
```
.
├── Cargo.toml the crate manifest (`no_std`, zero dependencies)
├── Cargo.lock committed: two packages (this crate and its sibling), and no
│ external dependency at all
├── README.md this file
├── ROADMAP.md the open work: one item per gap, with exit criteria
├── SOUNDNESS.md the ledger of every false proof fixed, with its fixture
├── AGENTS.md notes for agents, including the traps that cost the most time
├── CONTRIBUTING.md how to build, test, and add a gate
├── SECURITY.md how to report a vulnerability (GitHub private advisories)
├── LICENSE Apache-2.0
├── NOTICE third-party attribution (oracles and comparisons only)
├── .github/
│ ├── FUNDING.yml
│ └── workflows/
│ ├── ci.yml the gates, plus Kani, Verus, Lean, Coq, the MIR oracle,
│ │ the comparison fixtures, packaging hygiene and the
│ │ publish dry-run as jobs
│ └── release.yml tag-driven release: one crate per tag, in dependency order
├── src/
│ ├── lib.rs crate root: module map, prelude, the three proof routes
│ ├── smt.rs the decision procedure (the heart of the crate)
│ ├── bitblast.rs bit-level term graph -> CNF, for the SAT fallback
│ ├── sat.rs CDCL SAT solver: the fallback when the BDD arena fills
│ ├── sym.rs symbolic DSL via operator overloading
│ ├── logic.rs verified arithmetic + Q16.16 fixed point
│ ├── proof.rs Curry–Howard kernel + certificates
│ ├── vc.rs requires/ensures/invariant, Verified<T>
│ ├── contract.rs runtime predicate checking
│ ├── exhaustive.rs complete proofs by enumeration
│ ├── primitives.rs total ops, Bounded<MIN,MAX>
│ ├── macros.rs verify!, contract!, proof!, ...
│ ├── wp.rs Hoare logic + automatic VC generation
│ │ (also carries Proc + Stmt::Call for modular verification)
│ ├── smtscript.rs SMT-LIB2 export for independent checking
│ ├── mem.rs bounded symbolic memory + frame condition
│ ├── quant.rs bounded forall/exists, expanded to finite form
│ └── mir/ the real-Rust frontend (`std` only)
│ ├── parse.rs rustc's textual MIR -> a small IR, failing closed
│ ├── exec.rs symbolic execution of that IR, with a frame stack for calls
│ ├── intrinsics.rs the `core` model: `checked_*`/`saturating_*`/`wrapping_*`,
│ │ the bit counts, `Range`/`Iterator::next`, `?`, ...
│ ├── shape.rs per-function summary the rustc_public oracle compares
│ ├── spec.rs contract scanner + the small contract-expression grammar
│ └── verify.rs driver: emit MIR, extract contracts, discharge, report
├── verif-arithmetic/ the sibling crate, re-exported as `verif::arith` (its own
│ │ `LICENSE`/`README`/`NOTICE`, because a `.crate` needs them)
│ ├── src/
│ │ ├── lib.rs the module map and the `no_std`/no-`unsafe` claim
│ │ ├── checked.rs checked/saturating/wrapping integer ops, proved by enumeration
│ │ ├── bounded.rs `Bounded<MIN, MAX>`, a refinement type whose invariant holds
│ │ ├── fixed.rs Q16.16 fixed point, with its truncate-toward-zero contract
│ │ └── prove.rs the enumeration prover (`ENUM_BUDGET`) the proofs run under
│ └── tests/
│ ├── proofs.rs the proofs, executed
│ └── readme.rs the sibling README's example, pinned
├── tests/
│ ├── smoke.rs the engine proves real identities
│ ├── kernel.rs the proof kernel, including a compile-fail case
│ ├── sym.rs the DSL operators, each against the primitive it wraps
│ ├── differential.rs symbolic prover vs brute-force execution
│ ├── sat_engine.rs the SAT solver vs brute force on raw CNFs
│ ├── wp.rs generated conditions checked against execution
│ ├── mem.rs memory proofs checked against real Rust arrays
│ ├── quant.rs fill and scan loops, both verified and executed
│ ├── call.rs modular verification, every positive with its control
│ ├── loopdiff.rs verifier vs exhaustive execution, loops and claims included
│ ├── modular_differential.rs generated callers, verified then executed
│ ├── divmod.rs the divider the MIR frontend needs, vs Rust's own `/` and `%`
│ ├── mul.rs the constant-multiply arm, through `prove` not `evaluate`
│ ├── shift.rs the barrel shifter, vs Rust's own `<<` and `>>`
│ ├── signed.rs signed arithmetic: `slt`, `sdiv`, sign-extend, overflow
│ ├── op_differential.rs `evaluate` vs `blast`, per operator, both operand shapes
│ ├── oracle.rs the reference oracle (enumeration), checked before it is used
│ ├── bang_literal_signedness.rs `!x` in a contract: value vs predicate reading
│ ├── mir.rs real-Rust verification, with counterexamples replayed
│ │ against the compiled functions
│ ├── readme.rs the README's examples, pinned so they cannot rot
│ └── soundness.rs every fixture the SOUNDNESS.md ledger names must exist
├── examples/
│ ├── flight_control.rs a realistic actuator path, all obligations discharged
│ ├── pipeline.rs program -> conditions -> proofs -> SMT-LIB2
│ ├── memory.rs read/store, the frame condition, and a fill loop
│ ├── contracts.rs procedures verified once, calls reasoned about by contract
│ ├── report_probe.rs a report's verdict must not depend on the arena it is read in
│ ├── z3diff.rs differential harness: engine vs z3 on the exported text
│ │ (needs z3-solver; a development tool, not a dependency)
│ ├── kanidiff.rs differential harness: engine vs Kani on compiled Rust
│ │ (needs `cargo kani`; a development tool, not a dependency)
│ ├── verusdiff.rs differential harness: engine vs Verus on a spec fn
│ │ (needs the Verus driver; a development tool, not a dependency)
│ ├── leandiff.rs differential harness: engine vs Lean 4's `bv_decide`
│ │ (needs Lean via elan; a development tool, not a dependency)
│ ├── coqdiff.rs differential harness: engine vs Coq's kernel, by enumeration
│ │ (needs `coqc`; a development tool, not a dependency)
│ ├── bare_metal.rs the prover as `#![no_std]` code, built for the target by
│ │ Ferrocene, the qualified toolchain (a `lib` example, no `main`)
│ ├── support/ the IR the engine harnesses share, so they check the
│ │ same formulas rather than two drifting corpora
│ ├── mir_demo.rs verifies real Rust read from MIR, end to end
│ ├── mir_coverage.rs the coverage scoreboard: how much real Rust is decided
│ │ (the number `ROADMAP.md` scores its corpora with)
│ ├── comparison_check.rs gate 13's driver: asserts each comparison fixture's
│ │ per-function outcome and obligation kind, not a count
│ ├── comparison/ the same three functions proved seven ways, plus
│ │ Ferrocene as the qualified compiler (see its README)
│ └── mir_targets/
│ ├── actuator.rs the Rust under verification; imports no `verif`
│ ├── realistic.rs the large regression corpus (adversarial fixtures included)
│ └── everyday.rs the independent corpus: ordinary Rust, not shaped for
│ the tool; Phase 1 in `ROADMAP.md` is scored on it
├── tools/
│ ├── mir-oracle/ the `rustc_public` oracle: checks the text-MIR frontend
│ │ against rustc's own typed MIR. Nightly + `rustc-dev`,
│ │ its own workspace, and never a dependency of `verif`.
│ ├── comparison/ gate 13: re-runs the comparison fixtures -- the contracts,
│ │ the teeth, and the degenerate-implementation check
│ ├── ferrocene/ gate 3: builds both crates with the qualified compiler for
│ │ `thumbv7em-none-eabihf` (skipped, reported, if absent)
│ ├── build-verify/ gate 18: the Kani/Verus shape -- verify from `build.rs`
│ │ and prove the artifact carries no prover (scratch crate)
│ ├── cost-bench/ the cross-tool cost table in "How the cost compares to
│ │ other verifiers": `run.sh` measures `verif`, Kani, Verus,
│ │ Coq and Lean on the same three functions (setup + per-
│ │ verification; the artifact axis is `shape-bench/`)
│ └── shape-bench/ the measured table in "Two ways to use the verifier":
│ `run.sh` builds four crates (build-time vs on-target
│ vs unused) on scratch copies, and `measurer.rs` is the
│ native launcher that reads each process's own `VmHWM`
│ rather than a `fork` harness's inflated `ru_maxrss`
└── scripts/
├── gate.sh every gate in one command, failing loudly
├── test-count.sh the exact passing-test count, only when all pass
├── check_package.sh packaging hygiene: manifests, LICENSE/README/NOTICE
├── check_doc_links.py every internal anchor and relative file link resolves
├── check_actions_pinned.py every GitHub Action `uses:` is pinned to a SHA
└── publish.py publish order, dry-run, tag/checkout checks, notes
```
## Building and testing
```console
# Everything, in one command that fails loudly on the first gate that does not hold
scripts/gate.sh
# Host, with the thread-local arena and the full test suite.
# The `--features std` is required: the default feature set is empty (`no_std`),
# and the tests need the thread-local arena, so a plain `cargo test` does not
# compile the test harness.
cargo test --features std
# Lint both halves -- `--features std` alone never compiles the `no_std` items
cargo clippy --features std --all-targets
cargo clippy --no-default-features --lib
# Bare metal: no std, no allocator, no dependencies
rustup target add thumbv7em-none-eabihf
cargo build --no-default-features --target thumbv7em-none-eabihf
```
`scripts/gate.sh` runs clippy (with `-D warnings`, over both the `std` and the `no_std` half
of the crate), the test suite, the bare-metal
`no_std` build, a zero-dependency check, and the z3 differential oracle. It exists because
the gates were previously five separate commands quoted in prose, which is how a gate
quietly stops being run. It also refuses to report success when the z3 oracle is not
installed: an oracle that did not run is not evidence about the exporter. Five further gates
run the Kani, Verus, Lean and Coq differential oracles and the `rustc_public` MIR oracle when those
tools are present and *skip them loudly* when they are not, because all three are large
downloads (Kani: a pinned nightly plus CBMC; Verus: a self-contained bundle with its own z3;
the MIR oracle: a nightly with the `rustc-dev` and `llvm-tools-preview` components) that a normal local run should not
pay for; CI installs them and runs them as hard gates. One more gate holds the comparison
fixtures themselves — `tools/comparison/run.sh` re-runs `verif` on the positive fixture
and all three bug fixtures through `examples/comparison_check.rs`, which asserts each
fixture's per-function `FnOutcome` and the *expected obligation kind* rather than scraping
`mir_coverage`'s `decided N of M` line (that line counts only `Verified`, so a `Failed`,
`Incomplete` or `Skipped` fixture all read `decided 0 of 1`, and a contract that had become
unreadable would have been reported as a caught defect — a lost proof read as a refutation);
the positive fixture's three names are pinned in the driver rather than read back from the
contracts, and so is each function's whole contract (`requires:`, `ensures:`, `invariant:`)
clause for clause — a name survives a deleted contract and a count survives a weakened one, so
neither alone holds the claim; the
expected obligation kind is compared for equality, not by a `panic` prefix that any panic would
satisfy; and each scratch fixture gets a path unique per call, so two concurrent gates cannot
delete each other's file;
the same gate checks that the contracts refuse the degenerate implementations the bounds-only
versions accepted, and runs Coq and Lean on the positive fixture and both teeth, including
the mutation that shows each rejection is of the defect rather than of the script's shape.
Coq and Lean are both *required*: an absent prover is a reported skip (exit 2), never a
success for a proof suite that did not run. The last four gates hold the *tree*
rather than the logic: rustdoc must build both crates with `-D warnings` (the crate is
`#![deny(missing_docs)]`, but that says nothing about whether a doc link still *resolves*),
no compiled output may be tracked (`git ls-files` must not list a `.rlib` or a `target/`
path — a `git add -A` re-committed six stray `.rlib`s once, and a `.gitignore` does not
untrack a file that is already in the index), the `unsafe` surface must stay at the two
blocks `SECURITY.md` names, each with a `// SAFETY:` justification (a count in prose is a
claim like any other, and this one is security-relevant), and the build-time path must
verify at compile time while leaving the prover out of the artifact (see
[Two ways to use the verifier](#two-ways-to-use-the-verifier-at-build-time-or-on-the-target) below).
### The third oracle: rustc's own MIR, against the parser
`z3diff` checks the exporter and `kanidiff`/`verusdiff` check the engine. The MIR frontend
has a third failure mode, and it is the one gap 2 below names: it reads rustc's *textual*
`--emit=mir` dump, so a rustc release that changes the pretty-printer can break the parser,
and the parser is the only thing that would notice. `tools/mir-oracle` closes part of that
loop. It asks `rustc_public` — the compiler's own public API, which needs a nightly with the
`rustc-dev` and `llvm-tools-preview` components — for the same programs' **typed** MIR, reduces each function to a
small comparable shape (how many basic blocks it lowered to, and which panic guards `rustc`
inserted and with what polarity, in block order), and fails if that disagrees with what the
frontend's parser read out of the text. The comparison is structural on purpose: the two
dumps are not byte-identical (the typed one omits `copy` qualifiers and nests `scope`
blocks), and comparing text would fail on cosmetics and prove nothing.
**What that shape can and cannot see is the honest limit of this gate**, and it is pinned in
both directions by `the_shape_sees_structure_and_guards_but_not_places` in
`src/mir/shape.rs`. It sees a change in *structure*: an extra basic block, a guard that moved
or was inserted, a guard whose polarity flipped. It does not see a change in *spelling*: a
place, a local index, a field projection, a type. Re-spelling `Len((*_1))` as
`PtrMetadata(copy _1)` — a real change in rustc 1.99 that cost four verdicts on the 1.85
floor — leaves the shape byte-identical, so gate 10 was silent across it; it was found by
running the suite under a second toolchain.
**Gate 14 is a sample of that coverage, not the whole of it.** It runs `tests/mir.rs` under
one older compiler (1.85) against the same suite on the current stable, and it *skipped
entirely* in a container without the 1.85 toolchain — reported, not passed, but a skip. Two
compilers catch a spelling change only where they differ; a printer change that lands in a
version *between* them, or after current stable, is not covered by either. The durable form of
the check is therefore a habit, not a gate: run the suite under a compiler you have not run
before when the toolchain moves. Measured for this paragraph, `tests/mir.rs` is 354/354 on
1.85.1, 1.100.0 and 1.102.0-nightly, and the two end spellings really do differ
(`Len((*_1))` on 1.85, `PtrMetadata(copy _1)` on stable). So gate 10 is evidence about the
parser's *reading of the control-flow skeleton*; gate 14 extends that evidence to one more
compiler's spellings; nothing here covers every token on every toolchain.
The oracle lives in
`tools/mir-oracle`, outside the workspace, so the nightly and the `rustc_private` feature
never touch a crate that must build on stable with zero dependencies; the dependency arrow
points one way, from the oracle to `verif`. Gate 10 of `scripts/gate.sh` runs it, and the
`mir-oracle` CI job makes it a hard gate.
### Four more oracles, for the engine instead of the exporter
`z3diff` checks the *exporter*: it prints a query and asks z3 to agree about that text.
`examples/kanidiff.rs`, `examples/verusdiff.rs`, `examples/leandiff.rs` and
`examples/coqdiff.rs` check the *engine*. Each takes predicates the engine proved, compiles
them into a real program or goal, and asks an independent verifier to establish the same
property:
* `kanidiff` compiles each case into a Rust function and asks **Kani** (AWS's model checker,
over CBMC) to verify it.
* `verusdiff` compiles each case into a Verus `spec fn` and asks **Verus** (Viper plus SMT,
with bit-vector reasoning) to verify it.
* `leandiff` compiles each case into a Lean 4 theorem and asks **`bv_decide`** to prove it.
This is the strongest of the four, and for a structural reason: `bv_decide` bit-blasts the
goal, runs a SAT solver, and then *replays the solver's refutation as a Lean proof term that
the kernel type-checks*. The verdict is not "a solver said so", it is a machine-checked
theorem about the same 8-bit words this crate blasts.
* `coqdiff` asks **Coq's kernel** to check a different thing from the other three: not "does
the engine decide this formula the same way" but "does the engine's arithmetic, transcribed
into `Z` with explicit masks, evaluate to the same truth value on every point of the 8-bit
domain". Coq has no machine word in its standard library, so the generator spells every
operator out over `Z` and the harness enumerates the domain with `vm_compute`. That makes it
the only oracle that checks the *transcription* rather than the verdict, and it is the
slowest by a wide margin (three variables is 16.7M evaluations), so it runs a selected
subset of the corpus — see `SELECTED` in `examples/coqdiff.rs`.
No backend ever sees a symbolic term or an SMT-LIB string, and the four are built on
different foundations, so agreement is agreement between five independently built decision
procedures. A blasting bug now has to survive agreement with all four, which is a much
narrower coincidence than surviving one.
The design detail that matters is that the predicate and the generated program are *not*
produced independently. They are interpretations of one shared IR tree (`WExpr`/`PExpr`, in
`examples/support/mod.rs`), so "the same property" is structural rather than hoped for; and
the two harnesses share that module, so they are checking the same formulas rather than two
corpora that drift apart. Generating predicate and program separately would compare unrelated
formulas and every disagreement would be noise.
The harnesses have been checked for teeth by mutation, which is the only way to know they ask
a real question. Dropping the `+1` from the `Sub` blast (`borrow = TRUE` → `FALSE`) makes the
engine reject three true identities (`sub_self`, `add_sub_cancel`, `sub_zero`); changing the
`Eq` blast from `and` to `or` over the per-bit equalities makes it prove false ones. The
first of those is caught by `kanidiff` and `verusdiff`; the second by both as `MISMATCH
rand_N` on the random sweep. `leandiff` and `coqdiff` were checked against a mutation of
their own — the `Sub` blast wired to `Op::Add` instead, a blasting bug the engine then
*blesses* rather than rejects — and both catch it: the negative control flips from refuted to
proved (`control_ok=false`), and each reports `refuted_identity=2` plus three `MISMATCH`
lines naming `sub_self`, `add_sub_cancel` and the control. So every harness here has been
observed to fail on a broken engine, which is the only evidence that a green run means
anything.
Each harness also carries a negative control — `a - b == b - a`, false by construction — and
fails if either side *proves* it, so a run where "everything agreed" because nothing was
really asked cannot pass.
Eight divergences surfaced while building these, and all are worth stating because they are
where a plausible harness would have quietly lied:
1. **Arena sharing.** One engine arena for all cases exhausted the node budget after about a
dozen queries, so later cases came back `Unknown` and the harness reported the engine as
weak when the *harness* had run the arena dry. Each case now gets its own arena.
2. **Shift semantics.** The engine defines a shift by `k >= width` to be 0 (or the sign bit),
the SMT-LIB rule, while Rust's `<<`/`>>` are an overflow error there. Emitting `x << k`
would have compared a different function, so the generated programs spell the engine's rule
out in `shl_eng`/`lshr_eng`/`ashr_eng`.
3. **The classification matrix.** The first version counted "engine refuted + backend proved"
as agreement. A mutated engine then produced `mismatch=0` and was caught only by the
curated corpus. Now only the engine's `Unknown` is "no claim"; every other engine verdict
is a definite claim the backend must not contradict.
4. **Verus's arithmetic and its summary counts.** `#[verifier(bit_vector)]` rejects
`wrapping_mul` when an operand is a literal, and a constant like `255u8 * 255u8` is a
rustc const-eval overflow error that aborts the whole run, so the generated file routes
arithmetic through spec helpers that wrap via `as u8`. And Verus's
`verification results:: N verified, M errors` counts non-case items such as `main`, so the
accounting check is on error *locations*, not on that sum.
5. **Lean's `setWidth` changes the type.** `setWidth 4` on a `BitVec 8` returns a `BitVec 4`,
and `==` is homogeneous, so a bare truncation cannot be compared against a `BitVec 8` at
all. The first `lean_word` emitted exactly that and every masked case came back as a
`Type mismatch` rather than a verdict — a harness bug that would have read as "the engine
and Lean disagree about masking" if the harness had counted non-verdicts as disagreement.
Widening back with `.setWidth 8` is the engine's `truncate`-then-widen `Mask`.
6. **Lean diagnostics are multi-line, and the line number is the second-to-last field.**
`bv_decide` and `native_decide` report a refutation in two different wordings
("The prover found a counterexample" vs "the proposition … is false"), and the second
only appears on a continuation line — so the classifier has to collect the whole
diagnostic block before it can judge it. Reading the first line alone called every
`native_decide` refutation "hard", i.e. unverifiable. The line number itself is the field
*before* the column, not the last one; taking the last one attributed every verdict to the
wrong case and produced 47 spurious mismatches against a correct engine.
7. **`first | bv_decide | decide` does not work, and the failure is silent.** `first` commits
to the first tactic that produces a proof *or an error*, and `bv_decide` reporting a
counterexample counts as an error — so `decide` then runs on every refuted goal, including
the wide arithmetic ones, where it exceeds the heartbeat limit. The case is then reported
as undecidable rather than refuted, which is a *lost* verdict rather than a wrong one, but
it makes the oracle look weaker than it is. `native_decide` compiles the decision instead
of reducing in the kernel and finishes those in under a second. The trade is real and
stated in the harness: `native_decide` is Lean's trusted-native escape hatch, so the
fallback verdicts are trusted rather than kernel-checked, which is why `bv_decide` is tried
first and applies to all but the out-of-fragment handful.
8. **Coq applies by juxtaposition, not by comma.** `add_eng(a, b)` is a type error —
`add_eng` has type `Z -> Z -> Z` but is applied to a single argument — and every case
failed to compile until the generator emitted `add_eng a b`. The harness refused to read
the failed compile as a set of verdicts, which is the behaviour that made it visible.
Two corpus entries were also wrong — a bare `Not(And(..))` is not De Morgan, and
`guard <=> ite(guard,a,b)==a` fails at `a==b` — and the engine correctly refuted both. The
lesson that keeps recurring: when a harness disagrees, suspect the harness first, but *check*.
The engine's `Unknown` on `mul_comm` (an 8×8 multiplier) is the documented size wall, not a
disagreement: both backends prove the identity, so the engine is incomplete there, which the
harnesses count separately (`undecided_identity=1`) and do not fail on. A *refuted* identity
is a soundness failure and does fail the run. Note that the SAT fallback also tries this
identity and also declines it, which is the intended outcome: the fallback moves the wall, it
does not remove it, and an incomplete-but-honest answer is what keeps the differential
harness meaningful.
The `differential` test is the one that makes the approach trustworthy: for a
family of predicates it checks that the symbolic prover and brute-force
execution give the *same* answer, and that any symbolic counterexample really
does violate the property.
## Where this sits in the Rust ecosystem
The other verification tools for Rust are a different *kind* of thing, and the
difference is worth stating before the comparison table, because it decides what
`verif` can and cannot be used for.
**The established tools verify Rust you already wrote, out of process.** Kani
(AWS) compiles to CBMC and model-checks; Verus and Creusot and Prusti translate
Rust (or its MIR) into a logic and hand it to an external SMT solver; `hax`
extracts Rust into F\*/Coq for other tools to consume; Flux adds refinement
types checked by a solver. All of them need a bespoke toolchain or a nightly
compiler, and all of them invoke a solver (usually Z3) as a separate binary.
**`verif` is a prover that compiles into your artifact.** The decision
procedure is bit-blasting BDDs in the crate, the proof is a value, and there is
no external solver, no plugin, no nightly feature. That is a narrower and more
awkward design point — it buys you a proof that can run where Z3 cannot — and it
costs you scale, as the limits below say.
The honest split:
| What is verified | the Rust function itself, from its MIR (plus a `Stmt` AST for the older frontend) | the Rust function itself (MIR/IR) | nothing — runtime `assert` |
| Needs external solver | no | yes (Z3 / CBMC) | no |
| Toolchain | stable, `no_std`, zero deps | nightly or bespoke driver | stable |
| Runs on the target | yes (compiled in) | no (host-side) | yes (but unchecked) |
| Scope | bit-vectors, booleans, bounded quantifiers | first-order + arithmetic + more | — |
| Maturity | a sketch | industrial | widely used |
That table is an argument. [`examples/comparison/`](examples/comparison/README.md)
is the evidence: three ordinary functions — a guarded `sat_add`, a `clamp`, and a
counted `sum_to` — written for `verif`, Kani, Verus, Prusti, SPARK, Coq and
Lean, each tool asked to prove the same properties and then asked to *refuse* the
same three injected bugs (a swapped-branch `sat_add`, a wrong-arm `clamp`, and a
wrong-body `sum_to`). Every tool proves all three and catches all three, so the
interesting result is not who wins but what each one is proving: Coq and Lean
prove theorems about a hand-written **model**, and that model can silently be
wrong (the first version of the Coq file proved the *buggy* `sat_add` correct,
because unbounded `Z` never wraps), while `verif` reads the MIR `rustc`
actually emitted, so there is no transcription to drift. The contracts state the
whole function, not a bound: `sat_add` says the result *is* the sum when it fits
and `u16::MAX` when it does not, so the degenerate `u16::MAX` for every input is
refused rather than accepted. The directory also puts Ferrocene beside the
verifiers, as the qualified *compiler* that answers the other half of a safety
case.
Two things follow. First, `verif` does compete with the big tools on the
question that matters — *is the proof about the code or about a model of it?* —
and the answer is the code: `src/mir/` reads the actual MIR that `rustc` lowers a
real function to, symbolically executes it, and discharges the overflow, shift and
divide-by-zero `assert`s `rustc` emits plus the pre- and postconditions you wrote
as doc comments. Nothing is re-modelled by hand, so nothing can drift. What it
does *not* match is **scale and scope**: it decides small, deterministic functions
(a few locals, bounded arithmetic, loops that carry an invariant) and declines the
rest rather than guessing, where Kani and Verus take on trait-heavy, generic,
iterator-driven code that this frontend reports as `incomplete`. The older
`Stmt` AST frontend (`wp::Stmt`) is still there and still useful for programs you
want to state directly, but it is no longer the only way in. Second, the niche it
does occupy — a checked contract that can be discharged *on the target*, with no
solver in the loop — is not one the big tools aim at, and it is the same niche a
`no_std` flight build actually needs.
They are not rivals here so much as a second opinion. The crate uses Kani and
Verus, Lean and Coq as *differential oracles* in its test suite (`examples/kanidiff.rs`,
`examples/verusdiff.rs`, `examples/leandiff.rs`, `examples/coqdiff.rs`): the engine's verdict
on a predicate is checked against each tool's verdict on the equivalent compiled program or
goal, so the five decision procedures have to agree. They are invoked as subprocesses and are never
dependencies — the shipped crate still has none — but "an independent verifier
agrees" is a much stronger claim than "the tests pass", and it is available
precisely because these tools exist.
### Rust is moving toward contracts
This is the part that makes the design timely rather than idiosyncratic. Rust is
adding contracts to the language itself: `#[contracts::requires(...)]` and
`#[contracts::ensures(...)]`, tracked in [rust-lang/rust#128044][track] (open,
`B-experimental`). The implementation landed in [PR #128045][pr], and its
description says the intrinsics for evaluating pre- and post-condition
predicates exist **"for third-party verifiers"**.
[track]: https://github.com/rust-lang/rust/issues/128044
[pr]: https://github.com/rust-lang/rust/pull/128045
So the language is growing the same contract vocabulary this crate has been
experimenting with, and it is deliberately leaving a door open for tools like
this one to sit on top. That cuts both ways, and both ways are worth naming: it
validates the direction, and it means a home-grown DSL will eventually be
competing with a blessed, in-tree syntax. The durable contribution here is the
*engine* — the embedded decision procedure and the proof kernel — not the
surface syntax, which is the layer most likely to be absorbed.
### Is it useful, and is it a big deal?
Useful, in a narrow band. For safety-critical or embedded Rust where you want
SPARK-style contracts and a machine-checked discharge with **no external
toolchain and no solver process** — an MCU, a flight build, a `no_std` target
where you cannot ship Z3 — this is a working sketch of how to get there, and it
is checked hard: differential testing of the exporter against Z3, differential
testing of the *engine* against both Kani and Verus, mutation testing of its own
guards, and a test suite that fails when a soundness guard is removed. The popular
`contracts` crate does runtime checking only; the gap between "assert at run
time" and "prove for all inputs" is exactly the gap this crate is about.
A big deal, no — not as a general-purpose verifier. That space belongs to
Kani and Verus, and this crate does not enter it. Its value is as a *reference
implementation* of the no-solver, no_std corner, and as evidence that the shape
works: a prover that is a library, a proof that is a value, a contract that
compiles into the artifact you ship.
## The SPARK comparison, stated plainly
| Contracts in source | `Pre`, `Post`, `Type_Invariant`, `Assert` | `requires`, `ensures`, `invariant`, `verify!` |
| Prover location | external tool in the toolchain | **inside the compiled artifact** |
| Logic | full first-order + linear arithmetic + arrays | bit-vectors and booleans |
| Memory model | pointer/aliasing analysis | none |
| Scaling | industrial, handles large systems | good on masks/bounds/shifts, weak on wide multipliers |
| Qualification | extensive certification evidence | none |
| Qualified compiler | AdaCore's qualified toolchain | **Ferrocene**, checked in CI |
The interesting part is not that `verif` beats `gnatprove` — it does not, and
cannot, on scope. The interesting part is the *shape*: a prover that is a
library, a proof that is a value, and a contract that compiles into the artifact
you ship. Rust can do that, and this crate is a working sketch of how.
### The qualified toolchain
Rust's answer to AdaCore's qualified toolchain is [Ferrocene], qualified to
ISO 26262 ASIL D, IEC 61508 SIL 3, EN 50128 and IEC 62304. This repository builds
its `no_std` crates with Ferrocene for `thumbv7em-none-eabihf` — a target
Ferrocene itself qualifies — so the qualified compiler is exercised against the
same sources this crate ships. That is gate 3 of `scripts/gate.sh` and the
`ferrocene` job in CI; `tools/ferrocene/` has the manifest and the script.
Be precise about what that does and does not buy, because the distinction is the
whole point of this section. It checks that the *qualified compiler accepts the
sources unchanged*. It does not qualify `verif` itself: a qualified compiler
is not a qualified verifier, and this crate's decision procedure is not in
Ferrocene's scope. The README's own statement still stands — no qualification
evidence, no DO-178C tool qualification — and building with Ferrocene does not
change it.
Ferrocene is commercial, and its archives require a customer-portal token that
does not allow programmatic access, so the gate reports and skips when the
toolchain is absent rather than passing in silence — the same convention Kani,
Verus, Lean and Coq follow here. A skipped oracle is not evidence, and the gate
says so.
The build that matters most is `examples/bare_metal.rs`. It is `#![no_std]`, it
has no `main`, and it *calls the decision procedure* — so compiling it for
`thumbv7em-none-eabihf` is what shows the prover itself, and not just the types
around it, is code the qualified compiler accepts for the target. The target has
no test harness, so its verdict tests run on the host instead, under
`cargo test --workspace --features std`.
[Ferrocene]: https://ferrocene.dev/
## Two ways to use the verifier: at build time, or on the target
The claim above — the prover is *in* the artifact — is one of **two shapes** this crate can
take, and the choice is real. The first is what Kani and Verus do and what a
size-constrained safety build usually wants; the second is the crate's own headline.
Both are reachable from the same dependency. What changes is *where* the obligation is
discharged and *what* the shipped artifact carries.
### Shape A — verify at build time (the Kani/Verus shape)
Put `verif` in `[build-dependencies]`, call the frontend from `build.rs`, and fail the
build when an outcome is not `Verified`. The `mir` frontend is already `std`-only host
tooling, so there is nothing else to wire up:
```rust,ignore
// build.rs
fn main() {
println!("cargo:rerun-if-changed=src/lib.rs");
let report = verif::mir::verify::verify_file_with("rustc", "src/lib.rs".as_ref(), &[])
.expect("the MIR frontend could not read the source");
for (name, outcome) in &report.outcomes {
println!("cargo:warning=verif {name}: {outcome}");
assert!(outcome.is_verified(), "verif: {name} is not verified: {outcome}");
}
}
```
A build script is a *separate compilation unit*: cargo compiles it for the host, runs it,
and throws it away. So the decision procedure — the whole BDD blasting and CDCL fallback —
is never linked into the crate's own artifact. That is not an optimisation, it is a
consequence of the build model, and it is what makes the two properties below both true at
once:
* **The verification happens at compile time.** A false contract is a build error naming
the broken obligation and its witness, exactly as it is under Kani or Verus. Nothing is
checked at runtime, so nothing can be skipped in a release build. (There is no separate
"build-time vs compile-time" mode: verifying from `build.rs` *is* verifying at compile
time. The real second mode is the one below.)
* **The artifact is zero-cost.** With `verif` as a build dependency the crate's own binary
carries **zero** `verif` symbols — see the measured table below.
This is gate 18 of `scripts/gate.sh`, run by `tools/build-verify/run.sh` on a scratch crate
it creates and removes. It is a gate rather than a paragraph because "zero cost" and
"verified at compile time" are both checkable claims, and both rot silently if only
asserted: the script requires a good contract to build *and* the verifier to report
`verified` (a build script that silently did nothing would otherwise pass), a broken
contract to fail the build on its named obligation, and the resulting rlib to carry no
prover symbols.
### Shape B — verify on the target (the prover in the artifact)
Add `verif` as an ordinary dependency and call the engine from your own code. Now the
decision procedure *is* in the binary and the obligation is discharged **at run time**, on
the machine that runs the program — which is the point: a proof that can run where Z3
cannot. `examples/bare_metal.rs` is the extreme case: `#![no_std]`, no `main`, the
decision procedure compiled for `thumbv7em-none-eabihf` and built by Ferrocene.
The `smt` engine needs no `std` and no allocator (the default build is `no_std`), so this
shape works on an MCU. It is **not** zero-cost: you ship the engine, and you pay for it in
binary size and in the time the proofs take when they run.
### The same function, two ways
One function, one contract; the difference is only *when* the obligation is discharged.
The contract is written once, as a doc comment, and read by the MIR frontend:
```rust
// The function under verification. The contract is a doc comment, because a MIR
// dump carries no attributes.
/// requires: n <= 1_000_000
/// ensures: ret <= 100
pub fn clamp100(n: u32) -> u32 {
if n > 100 { 100 } else { n }
}
```
The contract is a doc comment rather than an attribute for a reason the
[contracts-are-doc-comments](#contracts-are-doc-comments-and-that-is-forced) section
gives: rustc's MIR dump carries no attributes, so the frontend reads the contract
from the *source text* and the body from MIR.
**Verified at build time** — nothing about the function changes; the proof lives in
`build.rs` and runs while the crate is compiled. A false contract stops the build, and the
shipped binary contains none of the prover:
```rust,ignore
// build.rs — the verifier, as a build script
fn main() {
println!("cargo:rerun-if-changed=src/lib.rs");
let report = verif::mir::verify::verify_file_with("rustc", "src/lib.rs".as_ref(), &[])
.expect("the MIR frontend could not read the source");
for (name, outcome) in &report.outcomes {
assert!(outcome.is_verified(), "verif: {name} is not verified: {outcome}");
}
}
```
**Verified on the target** — the same bound is discharged by the engine compiled into the
binary, at the moment the function runs. The engine is `no_std`, so this compiles for bare
metal; it is the shape `examples/bare_metal.rs` demonstrates:
```rust
use verif::prelude::*;
/// The same function, with the same bound, checked at run time instead of at build time.
pub fn clamp100(n: u32) -> u32 {
let ok = verif::smt::with_fresh(|| {
let x = var(32);
// the clamped result is always <= 100, for every x
let clamped = verif::smt::ite(x.gt_val(100), verif::smt::word(100, 32), x);
clamped.le_val(100).prove().is_proved()
});
assert!(ok, "clamp100's bound did not discharge");
if n > 100 { 100 } else { n }
}
```
The two are not interchangeable. The build-time shape proves the contract *of the code you
shipped*, once, and costs nothing at run time; the on-target shape can prove a property of
*values the program has right now*, on hardware where no solver process can run, and pays
for the engine. A flight build might use the first to keep the artifact small and the
second for an on-target re-check of a critical invariant.
### What each shape costs
Four crates share one business function and one driver — the `clamp100` above, exercised
in a loop — so the only difference between the rows is how verification is attached.
`no_verif` is the baseline, `build_verif` puts `verif` in `[build-dependencies]`,
`runtime_verif` calls the engine from `main` and discharges the `clamp100` bound at run
time, and `unused_verif` links the engine but never calls it. Measured on `x86_64`,
`release`, rustc 1.100, four cores; regenerate with `sh tools/shape-bench/run.sh`:
| **compile** wall time | 0.16 s | 3.4 s | 12.9 s | 12.7 s |
| **compile** CPU time | 0.17 s | 5.1 s | 34.9 s | 35.1 s |
| **compile** peak RSS (build tree) | 96 MB | 433 MB | 502 MB | 508 MB |
| **binary size** | 438 312 B | 438 328 B | 5 775 256 B | 438 336 B |
| **run** wall time (median of 7) | 3.1 ms | 3.2 ms | 4.6 ms | 3.2 ms |
| **run** CPU time | 3.0 ms | 3.0 ms | 4.5 ms | 2.9 ms |
| **run** peak RSS | 2.1 MB | 2.1 MB | 5.6 MB | 2.1 MB |
| `verif` symbols in the binary | 0 | **0** | 42 | 0 |
| where verification happens | — | compile time | run time | nowhere |
Reading the table honestly:
* **Build-time verification is zero-cost in the artifact, not in the build.** The binary
is the baseline to within 16 bytes (438 312 → 438 328 B; the residue is the crate name in
the embedded metadata — `bench_build_verif` is longer than `bench_no_verif`, so the two
are not byte-identical, but the prover leaves no code) and carries zero `verif` symbols,
and the run-time figures are identical. The price is paid at compile time: a host-side
`rustc` runs the MIR frontend and the decision procedure, so the cold build goes from
0.16 s to 3.4 s and the build tree's peak RSS rises to ~433 MB (that peak is one `rustc`
compiling the `verif` crate, not the prover's own arena).
* **On-target verification costs size and a little run time.** The engine adds ~5.3 MB
(≈13×) to the binary and ~1.5 ms to the run. The ~1.5 ms is one obligation being
discharged by the embedded engine — the real `clamp100` bound
`ite(x > 100, 100, x) <= 100` at 32 bits, not a tautology. Measured in-process over
1000 repetitions, the engine's per-proof cost for that obligation is **~290 µs**; a wide
multiplier past the BDD wall is `Unknown` rather than slow, as the scaling notes
elsewhere say. (An earlier version of this table quoted ~14 µs, but that proof was
`x < 65536 || x >= 65536` on a 16-bit variable — a predicate that folds to `true` before
the solver sees it, so it measured the harness, not the engine.)
* **A dependency you never call is also zero-cost** — dead-code elimination leaves a
438 336-byte binary with zero `verif` symbols. But that is the linker dropping an unused
library, not a proof: nothing was verified.
* **The compile figures are not a like-for-like profile comparison.** Cargo compiles
build-dependencies with the `build-override` profile, which defaults to `opt-level = 0`,
while a normal dependency is compiled at the release profile's `opt-level = 3`. So the
3.4 s row is "what a user gets by default", not "build-dependencies are inherently
cheaper": set `[profile.release.build-override] opt-level = 3` and the build-time row's
wall time rises to ≈12.9 s, matching the run-time row. The engine is the same work
either way; only its optimisation level differs.
The RSS figures are read from `/proc/<pid>/status:VmHWM` by
`tools/shape-bench/measurer.rs`, the native launcher this table's numbers come from. A
`fork`-based harness (Python's `os.wait4`) reports `ru_maxrss`, which is the child's
resident high-water mark *since the fork* — so the launcher's own RSS becomes a floor
under every measurement. That floor is invisible on a build (a `rustc` peaks at ~500 MB)
and dominant on a run (a benchmark binary peaks at ~2 MB): the same `no_verif` run
reports 2.1 MB through the native launcher and 5.5 MB through a Python fork, because
5.5 MB is Python's own RSS. The launcher's header records the full reasoning.
The numbers are a measurement, not a guarantee; `tools/shape-bench/run.sh` prints them on
your machine. The *properties* — verification at build time, and no prover in the
artifact — are what gate 18 asserts, because a cost figure moves with the machine and a
property does not.
### When each shape is actually worth using
The two shapes are not equals, and the honest reading is that **one is the default and the
other is a narrow special case**. Saying so is more useful than presenting them as a
symmetric choice.
**Build time is the right default, for almost everyone.** Reach for it when:
- the claim is a property of the *code for all inputs* (`∀ n. clamp100(n) <= 100`) — that
is what a contract states, and it is a statement about the program, not about one run;
- you build on a normal host (a `rustc` that can `--emit=mir`, and `std`), and
- the artifact should stay small: the shipped binary carries zero `verif` symbols, and the
build-time row above is the same bytes as the baseline.
Its cost is a slower build (≈3.4 s here) and a host toolchain. Its limit is coverage: the
frontend models a subset of Rust, so a function that reaches an unmodelled shape comes back
`Incomplete` — which is *not* a proof, and must not be read as one.
**On the target is for a narrow case, and it is easy to reach for it wrongly.** The
on-target shape is worth its cost only when **all** of these hold:
- the property is a relation between *values the program has right now*, unknown at
compile time (a calibration constant, a sensor reading, a runtime config), **and**
- the property is non-trivial — several variables, or bit-vector structure that is awkward
to write as a direct check, **and**
- there is no solver that can be run there (bare metal, offline), **and**
- the check is *rare* — boot-time or config-time, not per control-loop iteration.
If any of those is missing, the engine is the wrong tool. The section's own example makes
the point: proving `ite(x>100,100,x) <= 100` costs ≈290 µs (measured, `shape-bench`),
while the *same* check as `assert!(n <= 100)` is one comparison — nanoseconds. For a single
concrete value, `assert!` or `checked_add` is always cheaper and clearer, and it needs no
engine. The on-target shape earns its ≈5.3 MB and its hundreds of microseconds only when
the property is genuinely *symbolic* at that point and cannot be checked by evaluating it.
So the practical rule is: **default to build time; reach for on-target only with an
explicit answer to "which dynamic property, why is it not a plain `assert`, and why can it
not be checked at build time".** If those three do not have answers, use `assert!`.
What the crate is *actually* unusual at is not "the prover can run on the target" — that is
an impressive demo and a narrow use — but that the prover is **a zero-dependency, `no_std`,
allocator-free library you can embed**. That is what makes it usable inside your own tooling
without pulling in Z3 or a solver process, and it is the property to weigh against the
mature, higher-coverage competitors.
### How the cost compares to other verifiers
The comparison in [`examples/comparison/`](examples/comparison/README.md) is about
*correctness* — every tool there verifies the same three functions, and the finding is what
each proves and what it catches. It is **not** a cost comparison, and the one cost sentence
it used to carry ("`verif` decided all three functions in about 0.01 s; Kani and Prusti take
seconds to minutes") was prose, not a measurement. `tools/cost-bench/run.sh` is the
measurement; run it and compare rather than trusting any figure here.
Cost has **three axes**, and folding them into one number is the usual way a comparison
misleads:
| **setup** | one-time install | below, and `tools/cost-bench/run.sh` |
| **per verification** | deciding the same three functions | below, and `tools/cost-bench/run.sh` |
| **artifact** | what the tool adds to the binary you ship | `tools/shape-bench/run.sh` |
Measured on one machine (x86_64, four cores; Kani 0.68.0, Verus 0.2026.11.02, Coq 8.20.1,
Lean 4.36.0, rustc 1.100.0), steady-state (each tool warmed once, then the median of three
runs — Kani is ≈3.2 s / ≈256 MB on a *cold* first run), the same three functions:
| `verif` | ≈0.07 s | ≈97 MB | ≈1.4 MB (a crate) |
| Kani | ≈0.7 s | ≈23 MB | ≈486 MB |
| Verus | ≈0.8 s | ≈316 MB | ≈133 MB |
| Coq | ≈0.5 s | ≈298 MB | ≈451 MB |
| Lean | ≈0.5 s | ≈472 MB | ≈3.1 GB |
Read the table with these caveats, each of which is the honest part:
- **`verif`'s row includes spawning `rustc --emit=mir`** to read the source — it is the
only row whose verification step also compiles the code it verifies. That is also why its
peak RSS is ≈97 MB, not the ≈10 MB the driver process alone peaks at: the *largest process
in the tree* is the peak, and for `verif` that is the `rustc` it spawns. The engine-only
cost of the same three functions is ≈0.05 s (the per-function `elapsed` column
`mir_coverage` prints), so "≈0.07 s" is not "the engine is 10× faster than Kani" — it is a
measurement that includes the frontend's compiler call. Peak RSS is a **tree** figure for
every row, so each number is the tool's real peak and not its launcher's.
- **Coq and Lean prove a hand-written *model*, not the Rust code.** Their rows are not "the
same thing, slower" — they are a different task, and the transcription is the risk the
comparison README is about. A like-for-like engine comparison would exclude them.
- **Prusti and SPARK are missing** because their installs are heavy (a pinned nightly and a
JDK; four bundled solvers). Their absence is named, not hidden — a table that shrank
silently reads as "the tool was fast".
- **The artifact axis is where `verif` on-target *loses*, and the others have no entry.**
Kani, Verus, Coq and Lean are host-side binaries that ship nothing; `verif` build-time
also ships nothing. `verif` on-target ships ≈5.3 MB and 42 symbols. That is the deliberate
trade for running where no solver can, and it is why the two shapes are not interchangeable.
- **These are steady-state figures, not a cold first run.** Kani and Verus warm their own
caches on the first run, so the harness warms each once and reports the median of three
warm runs. The gap is large — Kani is ≈3.2 s / ≈256 MB cold against ≈0.7 s / ≈23 MB warm —
so a "cold cache" label would be wrong by 4×. The number answers "what does a repeated
check cost", which is the useful one; a one-shot first run is larger.
- **These are one machine's figures.** They move with CPU, disk and cache. `verif` wins the
setup axis clearly and is competitive on the per-verification axis for this small fixture;
it does **not** claim to win on speed for large problems — the BDD scaling wall is real and
documented above, and the mature competitors have higher coverage (pointers, aliasing,
concurrency, unbounded induction). The reason to choose `verif` is *embeddability and no
external toolchain*, not raw speed.
## Documentation
- The crate's own docs are on [docs.rs/verif](https://docs.rs/verif). They are
built with `--all-features`, so the `std`-only surface is there too.
- The sibling crate has its own page: [docs.rs/verif-arithmetic](https://docs.rs/verif-arithmetic).
It is re-exported here as `verif::arith`, so its API is documented in both
places.
- This README is the long-form document: each section records a claim the crate
makes and the check that backs it. The [Contents](#contents) list at the top
groups those sections.
- [`CONTRIBUTING.md`](CONTRIBUTING.md) covers the ground rules and the gates.
- [`ROADMAP.md`](ROADMAP.md) is the single source for open work: each item carries
a priority, a measurable exit criterion, the competitor whose gap it closes, the
closing move (build / bridge / won't do), and a status.
- [`SECURITY.md`](SECURITY.md) covers reporting a **soundness bug** — a false
`Valid` — which is the vulnerability class that matters in a verifier.
- [`SOUNDNESS.md`](SOUNDNESS.md) is the ledger of every false proof and wrong
verdict the project has found, each with the fixture that fails if the fix is
undone; `tests/soundness.rs` checks the fixtures still exist.
- [`AGENTS.md`](AGENTS.md) is the engineering log: why each decision was made,
including the ones that were reversed.
The gates are one script:
```console
$ sh scripts/gate.sh
```
It runs clippy, the test suite, the `no_std` bare-metal build, the
zero-dependency check, the differential oracles (z3, Kani, Verus,
`rustc_public`, Lean 4, Coq), the comparison fixtures, the MSRV build, the
documentation build, the build-artifact check, the pinned-`unsafe` check and the
build-time zero-cost check, and prints `ALL GATES GREEN` only when all of them
hold.
## License
Apache-2.0. The full text is in [`LICENSE`](LICENSE).
Copyright 2026 Yayasan Pesantren Cipansor and contributors. Developed with
contributions from OpenHands agents; the copyright notice in `LICENSE` records
the foundation and the contributor base together, which is the arrangement the
project's authorship follows.
This project was previously offered under `MIT OR Apache-2.0`. It is now
Apache-2.0 only, which is the single license the `LICENSE` file has always
carried; the dual-license option in the manifest and this section is what was
removed. Recipients of a prior release keep the rights that release granted
them; Apache-2.0 is the license for this version and every version after it.