# AGENTS.md
Repository-level notes for agents working in this workspace.
## Layout
- The repository root *is* the `verif` crate: a Rust crate that embeds a
formal-verification engine — a bit-blasting SMT decision procedure, a symbolic
DSL, a Curry–Howard proof kernel, contracts, and exhaustive verification.
`no_std`, zero dependencies, allocation-free. (`src/`, `tests/`, `examples/`,
`scripts/`, `Cargo.toml` all live at the root.)
- The proved runtime primitives live in the sibling crate `verif-arithmetic`
(`verif-arithmetic/`), re-exported at the crate root as `verif::arith` — so
callers write `verif::arith::prove::*`, not the `verif::verif_arithmetic`
stutter. Both crates are named after the *verb* the tool performs
(`verif` = verification, `verif-arithmetic` = verified arithmetic); the
earlier name `discharge` survives only as the English verb in prose ("the
proof is *discharged*") and as the `*::discharge()` method that performs the
discharge, never as a crate or module identifier.
- Governance files, so the tree is publishable and auditable: `LICENSE`
(Apache-2.0, in the root *and* in `verif-arithmetic/`, because a `.crate` must
carry its own), `NOTICE` (third-party attribution — SPARK, z3, Kani, Verus,
Lean, Coq, Ferrocene and the rest, each of which is an oracle or a comparison,
never a dependency), `SECURITY.md` (soundness bugs are the vulnerability class
that matters in a verifier), `CONTRIBUTING.md`, `ROADMAP.md` (the *single source
for open work* — one item per gap with a priority, a measurable exit criterion,
the competitor whose gap it closes, the closing move, and a status), `README.md`
(the long-form document, and the crate's page on crates.io), and `AGENTS.md`
(this file). This file records what was *learned*; `ROADMAP.md` records what is
*left*. When a "Stage N" or "Next stage" section below is finished, its remaining
work moves to `ROADMAP.md` rather than living here.
## Renaming the crate: `discharge` → `verif`
Done in one commit. The traps, so a future rename does not repeat them:
- **`discharge` is two things at once.** It is the crate name *and* the English
verb for what the prover does (`discharged`, `discharges`, `dischargeable`,
and the `discharge()` methods). A blind `sed s/discharge/verif/g` rewrites the
prose too — "the proof is *verifed*" — and renames `Certificate::discharge`,
the one name the whole crate is *about*. The mechanical pass must target only
the identifier forms: `discharge::`, `discharge-arithmetic`,
`discharge_arithmetic`, `DISCHARGE_*`, `cipansor/discharge`, `docs.rs/discharge`,
`-p discharge`, `name = "discharge"`. The verb forms are left alone on purpose.
- **`pub use verif_arithmetic;` does not rename the dependency.** `arith` is not
a dependency name, so `pub use arith;` is `E0433: cannot find crate`. The
sibling is aliased, not renamed: `pub use verif_arithmetic as arith;`. The
`Cargo.toml` key stays `verif-arithmetic` (it is the real crate), and only the
*import* path shortens.
- **`git checkout -- <file>` un-renames that file.** Four files were reverted
mid-run to undo a bad edit and came back holding the *old* crate name; the
build caught it only in `tests/oracle.rs`, because the lib re-export masked it.
After any revert during a rename, re-grep for the old name before trusting it.
- **The env var moves with the name.** `DISCHARGE_RUSTC`/`DISCHARGE_MSRV` →
`VERIF_RUSTC`/`VERIF_MSRV`, in `scripts/`, `.github/workflows/ci.yml`,
`tools/`, and every README/AGENTS mention. A stale `DISCHARGE_RUSTC` in one
script silently points the MIR frontend at the wrong compiler.
- **The GitHub repository rename is a manual step.** `repository`/`homepage` in
both `Cargo.toml`s now read `github.com/cipansor/verif`, but GitHub will keep
serving the old path only until the owner renames the repo; until then the
metadata URL and the real URL disagree. This is a human action, not a code one.
## Publishing to crates.io
Both crates are published: `verif-arithmetic` at `0.1.0` and `verif` at `0.2.0`.
They version independently, so those numbers are not required to agree — see the
`verif-arithmetic` requirement note in the root `Cargo.toml`. The repository is
arranged so they stay publishable, and the checks that make that true are separate
from the ones that make the *code* correct. A crate that builds and passes all
eighteen gates can still be unpublishable, and the failure only surfaces at
`cargo publish` — the worst moment, because an upload cannot be undone.
- **The crates version independently.** No `[workspace.package] version`, no
`version.workspace = true`. A shared version re-versions both crates at once,
which is how a release comes to publish a crate nobody asked for. Each
`Cargo.toml` states its own `version`.
- **A release tag names one crate**: `<crate>-v<version>`, e.g.
`verif-v0.1.0`. There is deliberately no bare `v<version>` tag — one tag
cannot say which of two crates it means. `.github/workflows/release.yml`
refuses one rather than interpreting it.
- **`verif` cannot be packaged until `verif-arithmetic` is on crates.io.**
`cargo publish` resolves a `path` dependency against the registry. Both crates
are published now, so the dry-run resolves the parent's dependency and reports
it *ready*; the rule still governs every later release, where a version bump of
the sibling has to land on the registry first. The two error shapes are
`no matching package named ...` (no version of the sibling at all) and
`failed to select a version for the requirement ...` (an older version exists,
the new one does not). Both mean "publish the sibling first".
`scripts/publish.py` derives the order from the manifests and reports the
second as *blocked*, not *broken*.
- **`verif`'s directory is the repository root**, so `dirty_by_crate` in
`publish.py` cannot attribute a root file to `verif` by path prefix (every
path is under the root). It relies on cargo's own `--allow-dirty` refusal
instead, which is scoped to the crate directory.
- **`verif-v0.1.0` starts with a `v`.** A bare-tag check written as
`tag.startswith("v")` rejects the parent's own valid tags, because the crate is
named `verif`. Match `^v[0-9]` instead — the digit is what distinguishes a
version from a crate name.
- **`[package.metadata.docs.rs] all-features = true` is load-bearing.** The
default feature set is empty (`no_std`), so without it docs.rs would publish
a crate smaller than the one that ships: no `mir` frontend, no proc-macro
surface. `scripts/check_package.sh` requires the table only for a crate that
actually has a non-default feature, so `verif-arithmetic` needs none.
- **A `.crate` must carry its own `LICENSE`.** `verif-arithmetic/` had none, so
its package shipped no licence text and no README at all. Each crate directory
now has `LICENSE`, `README.md` and `NOTICE`, and `check_package.sh` fails if
one goes missing. `verif-arithmetic/Cargo.toml` also gained `readme`.
- **Attribution is per crate, not global.** A project named in `verif`'s source
is `verif`'s to attribute; requiring the sibling to name it too is noise.
`verif-arithmetic/src/lib.rs` does mention `rustc_public`, so its `NOTICE`
names it — that was the one real finding of the first run.
- **`scripts/check_package.sh` is hermetic.** It reads manifests and the tracked
file list and runs no compiler, so it is cheap enough for every pull request.
It is a separate script rather than gate 19 because renumbering `gate.sh`'s
eighteen checks is churn that risks the checks themselves.
- **`.github/workflows/release.yml` authenticates by trusted publishing**, not by
a stored secret: `rust-lang/crates-io-auth-action` exchanges a GitHub OIDC
token for a short-lived crates.io token, which is why the workflow needs
`id-token: write` and why there is no `CARGO_REGISTRY_TOKEN` repository secret
to configure. The registration is keyed to this repository *and* to the
workflow's file name, so renaming `release.yml` breaks the exchange until the
crates.io setting is updated. It dry-runs first, then publishes, then waits for
the version to appear in the index. A version already on crates.io is skipped
rather than treated as a failure, so a re-run after a partial release finishes
the rest.
## Build and test commands
Rust is installed under `~/.cargo`; prepend it to `PATH` in every shell:
```bash
export PATH="$HOME/.cargo/bin:$PATH"
```
```bash
# Run from the repository root.
# Host build + full test suite (needs the `std` feature for the thread-local arena)
cargo test --features std
# Lint (must stay at zero warnings)
cargo clippy --features std --all-targets
cargo clippy --no-default-features --lib # the `no_std` half, which the line above never compiles
# Docs (must stay at zero warnings)
cargo doc --features std --no-deps
# Bare-metal: no std, no allocator, no dependencies
cargo build --no-default-features # host, exercises `static mut` path
cargo build --no-default-features --target thumbv7em-none-eabihf
# The flagship demo
cargo run --features std --example flight_control
# The MIR frontend: verify real Rust, reading the MIR rustc lowers it to.
# `--emit=mir` needs nightly, and the compiler is named separately from RUSTC
# so that pointing this at a nightly does not disturb the cargo building it.
VERIF_RUSTC="$(rustup which --toolchain nightly rustc)" \
cargo run --features std --example mir_demo
VERIF_RUSTC="$(rustup which --toolchain nightly rustc)" \
cargo test --features std --test mir
```
`clippy` was installed with `rustup component add clippy`; the bare-metal target
with `rustup target add thumbv7em-none-eabihf`.
```bash
# The qualified-toolchain gate, in isolation. Exits 0 on a build, 1 on a real
# failure, 2 when no Ferrocene toolchain is present (which `gate.sh` reports and
# skips). See `tools/ferrocene/README.md`.
FERROCENE_RUSTC=/path/to/ferrocene/bin/rustc sh tools/ferrocene/run.sh
```
## Verifying real Rust: the MIR frontend (`src/mir/`)
The rest of the crate proves things about *models*: a formula, or a `wp` program.
`src/mir/` proves things about the code itself, by reading the MIR that `rustc`
lowers it to. Five facts about it cost the most time to discover:
1. **A MIR dump carries no attributes and no doc comments.** So contracts cannot
come from MIR; they are scanned out of the *source* text, while bodies come
from MIR. That split is the design, not a limitation to work around.
2. **`rustc` prints the failing polarity of its arithmetic asserts:**
`assert(!move (_5.1: bool), "attempt to compute ...")`. Dropping the `!`
inverts every overflow, underflow and divide-by-zero check, and the tool then
reports safe code as broken. The flag is carried through the IR and pinned by
a parser unit test.
3. **A checked binary writes a tuple, and the tuple has no width.** `_3 =
AddWithOverflow(a, b)` makes `_3` a `(uN, bool)`. Reading the operand width
from `_3` gives 64 for every type, which silently mis-sizes the overflow test.
The width comes from `_3.0`.
4. **`smt::truncate` zero-extends when the target is wider.** That is what makes
the *signed* multiplication-overflow predicate exact: compute at `2w`, test the
top `w` bits. The unsigned case no longer widens at all -- see below.
5. **The output path matters.** `-o /dev/stdout` makes rustc try to create a temp
directory in `/dev` and fail; the MIR goes to a unique temp file. The name must
be unique per *call*, not per process, or parallel tests delete each other's
files.
Three engine consequences worth remembering:
- **Division is now in the engine** (`smt::divmod`, exact, restoring), because a
frontend reading real code meets `a / b` and must not guess. `y == 0` is a
*defined* value rather than a hole, and rustc's own divide-by-zero assert is
what reports the panic. The 1-bit fast path must honour the same `y == 0`
contract or it disagrees with the general path at exactly that input — a test
caught this.
- **A variable shift is a barrel shifter** (`smt::shift_var`), `log2(w)`
conditional stages. It is linear in the width, so it fits where a `w`-bit
multiplier does not. An out-of-range amount has a defined value (zero, or sign
fill for an arithmetic right shift), matching the shift-count-masking choice the
differential oracle already pins.
- **Widened products are gone from both overflow predicates.** A signed non-constant
multiply used to need a `2w`-bit product, which is the BDD wall, and a *weaker*
overflow predicate would be worse than declining, because it would make an overflowing
function look panic-free. So the code returned "no predicate" past 16 bits and the
path was reported `incomplete`.
The refusal rested on the belief that no division form is exact for every combination
of the signs. That is false, and it was replaced by the exact form
`y != 0 && |x| > limit / |y|`, with `limit = 2^(w-1) - 1` for same signs and
`2^(w-1)` for different ones. No widening, so it works at `i64`.
The old widening was measured rather than assumed: the engine has a SAT fallback for
when the arena fills, so the tempting fix was to raise the width and let the
fallback take it. Raising the threshold from 16 to 32 does not reach the
fallback: `mir_demo` on a widening multiply then runs past 300 s and has to be
killed, because the cost is in *building* the 32-bit diagram, before the arena
ever fills. That is why the fix is a division and not a bigger multiplier.
- **Signedness is part of the *value*, not a display detail.** The engine's
arithmetic is bit-vector arithmetic, so every operation has one bit-pattern
answer; 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's overflow is not the unsigned
carry. The frontend therefore reads signedness off the declared type and picks
`smt::slt`/`sle`/`sgt`/`sge` and `smt::sdiv`/`srem` rather than the unsigned
forms. The contract evaluator does the same, because a contract's `<` is the
same comparison as the code's. Two consequences worth remembering:
- `MIN` is *not* zero. `parse_const` used to return `0` for both `MIN` and
`MAX`, so `a != i8::MIN` meant `a != 0` and a signed negation guarded by it
was reported panic-free. `MIN` of a signed type is the top bit alone.
- The overflow rules are not the unsigned ones. For a signed add it is "the
operands agree in sign and the result disagrees"; for a subtract, "the
operands differ and the result takes the subtrahend's sign". The unsigned
carry test happens to fire on `127 + 1` but also fires on `-1 + 1`, which is
not an overflow. For a signed multiply the test is rustc's own: the
sign-extended product equals the sign-extension of the wrapped result.
`smt::sign_extend` exists for exactly this, because `truncate` zero-fills and
a zero-extended `-1` has the wrong magnitude.
- **A contract resolves a bare name against the arguments, then the `const`
table.** `verify_function` copies `MirProgram::consts` into `FieldEnv::consts`,
and `Parser::parse_primary` looks a name up there after the argument table and
after the associated-constant forms (`i8::MIN`). The table is the *same* one the
executor folds a body's `const LIMIT` from, so a contract's `LIMIT` and the
body's `LIMIT` are one value -- taken once from rustc's const-evaluated dump,
they cannot disagree. Four things to keep right if you touch this:
- The value is built at the *item's* own width and sign (`const 10_u8`,
`const -1_i8` prints as `0xff`), not at the operand's, because a constant has
a type of its own -- unlike a bare literal. It goes through `unshared_const`
so it does not hash-cons with a literal of the same bit pattern, whose
recorded envelope would otherwise be read back as the constant's.
- Arguments are checked *first*. Rust rejects a parameter that shadows a
constant (`E0005`), but reading the constant there would bind the wrong value
-- a false proof, not a refusal.
- A name whose printed body is not a literal (`const NEXT: u8 = LIMIT + 1`
prints as a `const NEXT: u8 = { ... }` block) is *refused*, not guessed: its
value lives in its own body, which the contract reader does not fold. Same for
a misspelled name. Both are skips, so nothing is proved either way.
- A module-nested item is keyed by its full path (`low::K`), which is how the
dump prints both the definition and the use, so it resolves only when the
contract spells the path -- a bare `K` does not silently pick one module.
- A `const` item is collected *before* the function loop, in two stages: every
literal (and every CTFE block that folds to one) first, then the
expression-bodied ones to a fixpoint. A single in-order pass folded
`const FWD_NEXT: u8 = FWD_LIMIT + 1` while the later `const FWD_LIMIT: u8 =
10` was still unresolved, because rustc prints source declaration order and
Rust lets a constant name a later one. The fixpoint sees each round's
resolved constants; a cycle resolves nothing and stops, leaving those items
unmodelled as before. `parse_const_item`/`const_key` are the item reader, so
the same keying rules apply to the prepass and the fixpoint.
- A comparison's width and sign come from its *operands*, never from its
destination. `const LESS: bool = -1i8 < 0i8` folds as `_0 = Lt(const -1_i8,
const 0_i8)`: a `bool` return place assigned from `i8` operands. Reading the
shape off the `bool` destination compared the `-1i8` pattern, 255, as unsigned
and folded the comparison to `false` -- and a contract claiming `ret == false`
was *proved* from a wrong value. `is_comparison` routes the comparison arms
through `c_operand_shape`, which takes the common operand shape and refuses a
mismatch rather than guessing.
- **The const folder's word is 64 bits.** `CVal::Word` holds a `u64`, so a width
past 64 (`i128`/`u128`) is refused by `c_width_ok` rather than carried. An
expression-bodied `i128` (`const HUGE: i128 = 1 + 2`) reaches `c_checked` as an
`AddWithOverflow` at width 128, whose exact overflow test negates
`1i128 << 127` -- `i128::MIN` -- which panics in a debug build, at *parse* time,
for an item no target named. Every width-taking folder (`cval_of_const`,
`c_binop`, `c_unop`, `c_checked`, `c_cast`) checks it, and `fold_const_block`
refuses such a `ret_ty` up front; the item stays unmodelled and a contract that
named it is a skip. `Ty::width` still reports 128 because the *constant reader*
needs it to compute `u128::MAX` and a negative literal's two's-complement
pattern -- only the folder refuses it. See `Ty::has_unrepresentable_leaf`.
## The unsigned multiply-overflow test is exact *division*, not a widened product
`sat_mul` (`if b != 0 && a > u16::MAX / b { u16::MAX } else { a * b }`) used to be the
corpus's one `incomplete`. It is now `verified`, and the two changes that got it there
are worth keeping apart because they fix different halves of the same query.
**1. The predicate is `y != 0 && x > MAX / y`, not a `2w`-bit product.** For unsigned
operands this is *exact*, not a sufficient condition: for `y != 0`, `x * y > MAX` iff
`x > floor(MAX / y)`, and `y == 0` can never wrap. It costs the restoring divider
(`smt::divmod`) the engine already has, and no `2w`-bit multiplier -- so the BDD wall
the old comment describes is never built. It also works at `w == 64`, where there is no
width left to widen to and the old path could not produce a predicate at all. The signed
case now uses the same idea rather than widening: `|x| > limit / |y|`, with `limit`
`2^(w-1) - 1` for same signs and `2^(w-1)` for different ones. The claim that no such
form is exact for every combination of the signs was wrong.
The form is deliberately the one the guard in the saturation idiom is written in
(`if b != 0 && a > MAX / b`), in the same operand order, so the two terms are
*structurally identical*. That is what the second change exploits.
**2. The boolean fold cancels through the `&&`/`||` spine.** `smt::bin_bool` folds the
boolean identities at construction (`p && !p == false`, `p && true == p`, `!!p == p`, and
the `Or`/`Xor` duals), and `Ctx::cancel_through_spine` extends the cancellation to a
`p`/`!p` pair that sits anywhere in the operands' `&&` spines rather than at their roots.
That second part is what the query actually needed, and the measurement is unambiguous.
The path into the multiply is the conjunction `b == 0 && a <= MAX / b`; the overflow
obligation is `b != 0 && a > MAX / b`. The conjuncts cancel pairwise, but *across* the two
spines, so a root-only identity check does not see it. Without the fold the bit-blaster
expands the 16-bit divider inside both terms before any solver sees the contradiction:
- `find_model(path && over)` at `u16`, spine fold absent: `Unknown` in ~0.49 s.
- the same query with the fold: `Unsat` in ~25 µs.
The time is the point: the verdict is not just faster, it *exists*, because the divider
is never blasted. A standalone `find_model(over)` at `u16` is still `Unknown` (the divider
alone is the wall), so this is not "the divider got cheap" -- it is "the contradiction is
found before the divider is reached".
Guards on the fold, because each one is a way to be wrong rather than slow:
- **Both widths of `!!p == p` must be 1.** A comparison node carries the *operand* width
(`Op::Eq` on two `u32` has width 32) even though it denotes one bit, so returning its
child where a predicate belongs hands back a wide term. A later `require_same_width`
then marks the arena ill-formed and turns a decidable query into `Unknown` -- which is
exactly what happened, and it is why `the_contract_reader_agrees_with_rustc_on_a_grid`
caught it (`8 / 4 / 2` at `u32`).
- **`op_leaves` is iterative and capped** (`MAX_CONJ`). A path condition is as deep as the
path is long, so a recursive walk would be the same stack risk `MAX_WALK_DEPTH` exists
to bound. Truncating at the cap only *misses* cancellations, never invents one: a leaf
left undecomposed is still entailed by the tree it came from.
- **The cancellation is soundness-neutral.** Every fold here rewrites a predicate to one
*equivalent* to it (`p && !p` really is false), so it can turn `Unknown` into a verdict
but never a `Valid` into a `Counterexample` or the reverse. That is why the width guard
above is a *correctness* fix and not a soundness one, and why the fold needs no new
oracle: the differential oracles already pin the semantics it must preserve.
Three traps that cost time here, all in the frontend rather than the engine:
- **`Term::Assert` must assume the guard it just checked on the fall-through
path.** It used to push the success block with the incoming path unchanged, so
`assert(n < 16)` was proved and then *discarded*: later obligations were
discharged as if `n` could still be 16. That is sound — the guard is checked
separately, so no panic is hidden — but it is needlessly weak, and wrong for a
guard the *caller* wrote. Carrying `satisfied` is what lets `sat_shift` verify.
If a function that clearly cannot panic comes back `failed` or `incomplete`,
check whether an assert guard was assumed before blaming the engine.
- **The parser must check ` as ` before `const `.** rustc prints a cast constant
as `const 3_i32 as u32 (IntToInt)`; matching the `const ` prefix first hands the
whole string to `parse_const`, which reads `i32 as u32 (IntToInt)` as a type
name and yields a constant with *no width*. Every guard written against such a
constant then goes unmodelled. This is why even `x << 3` used to be `incomplete`.
- **The cast's target width is the destination's, not the source's.** `Rvalue::Cast`
takes the width from the `as T` type; the operand keeps its own width. A shift
amount is a `u32` even for a `u16` shift, and rustc keeps it distinct, so the
width used to build the shift is the *left* operand's.
`tests/mir.rs` is the oracle that matters: it feeds each reported counterexample
back into the *compiled* function and requires the panic. That checks the engine
against rustc's code generator rather than against another model. `tests/divmod.rs`
does the same for the divider, against Rust's own `/` and `%`; `tests/shift.rs`
does it for the barrel shifter, against Rust's own `<<` and `>>`.
## Constant operands are folded, so a closed query is decided rather than refused
A frontend 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*. `Ctx::bin_word` and `Ctx::cmp` now fold an operation whose operands
are both literals, and `divmod`/`sdivmod` fold when both are literals, so the term
that reaches the solver is a single constant instead of the circuit that computes
it.
The motivating measurement is the cleanest possible demonstration that the engine
was refusing queries for their *size* rather than for anything unknown. A query
whose operands are *all* literals -- `-7 / 3 == -2` at `i64` -- has **no symbolic
input at all**, and it came back `Unknown` in ~1.1 s: the divider was blasted,
walked, and refused before the constant was ever looked at. With the fold the same
query is `Valid` in 0.000 s, and the term count drops from 660 to 5 -- the divider's
whole circuit replaced by the two literals it computes.
That is the fold's half of the story. The other half is getting the literals *into*
the body at all: a frontend builds `a / 3` from the symbolic value of `a`, so under
`requires: a == -7` the operands were a variable and a literal, not two literals,
and the fold had nothing to fold. Seeding a pinned argument with its literal is what
closes that gap; see the next section.
Where the fold must *not* go, because each one silently breaks the frontend's
literal-range bookkeeping -- these were regressions, caught by the corpus, not
theory:
- **`0 - x` must stay a `Sub` node.** The term language has no unary negation, so a
frontend spells one `0 - x`, and it tells `-128` (legal for an `i8`) from the bare
literal `128` (illegal) by the node being a `Sub` rather than a `Const`. Both are
the same eight bits, so the node *is* the only evidence. Folding the negation
merged them and refused valid `y == -128` contracts. Every other subtraction
still folds, including the `x - y` the restoring divider is built from.
- **`truncate` must not fold a literal.** The frontend spells a *named* bound
(`i8::MIN`) as `truncate(word(k, 64), w)` precisely so it does not hash-cons with
the literal `word(k, w)`. Folding a literal through `Trunc` merged the two and
made the bound inherit `128i8`'s out-of-range envelope, refusing
`y == i8::MIN`. Nothing is lost: the folds that carry the divider's constant path
are in `cmp` and `bin_word`, not in `trunc`.
- **A folded comparison is a *one-bit* constant.** A comparison node stores its
operands' width even though it denotes one bit, so a folded comparison left wide
would hand a later `require_same_width` a term of the wrong shape -- the same
trap the `!!p == p` width guard exists for.
The general lesson is worth stating because it recurs: **the term arena is
hash-consed, so a fold that produces a value which some other node already denotes
is not a neutral optimisation -- it *merges* the two nodes.** When the frontend
distinguishes two things by node identity rather than by value, a fold that erases
the distinction is a wrong verdict. Fold where the frontend does not depend on the
shape, and say why in the comment when you decline.
## A pinned argument is seeded with its literal, so a body over it folds
Folding (previous section) only reaches a query whose operands are literals, and a
frontend builds an operation from the *symbolic* values of its operands. So a
precondition that pins an argument -- `requires: a == -7` with the body `a / 3` --
left the body building `sdiv(a, 3)` over a fresh variable, and the fold had nothing
to fold: the `sdivmod` general path spells its magnitudes `0 - x`, the one
subtraction the fold deliberately declines, so a symbolic `sdiv` never collapses.
The pin was in `pre` and the fold was in the body, and nothing carried one to the
other.
`verify_fn` now seeds a pinned argument with the literal instead of a fresh
variable, and `smt::pinned_vars` extracts the pins from `pre`. The rule is
*closed* right-hand sides only: `v == k` (either operand order) under any nesting
of `&&` pins `v := k`; `v == w` between two variables pins neither, because it is a
relation and fixing either side would discard it. A disjunction of values (`a == 1
`pre` is assumed as the path condition, and `pre => goal` is unchanged when `goal`
is specialised to a value every model of `pre` already fixes. The extraction is
therefore *not* an extra assumption, and it cannot turn a false contract true --
`a == 3` with the body `a * 2` and the claim `ret == 7` is still refuted (the corpus
carries that false direction, `a_signed_constant_multiply_at_i64_cannot_prove_this`).
Two things this exposed, both worth remembering:
- **A latent hole in `overflow_pred` for `Mul`.** That predicate had an arm for one
constant operand (`x * c`), derived from the monotone bounds, but none for *both*
constant -- which rustc never produces itself, so the arm was unreachable until a
pin made the second operand a literal. The pair then fell through to the general
signed path, which has no sound predicate at `w == 64` and returns `None`, so the
`assert(!overflow)` was unmodelled and `a_signed_constant_multiply_at_i64` came
back `incomplete`. The fix is a both-constant arm that computes the exact product
and compares it against the range; it is checked exhaustively at 2..5 bits and at
`i64`'s boundary. **A new capability reaches code that was correct-by-vacuity: the
arm was sound but never asked, and only the pin asked it.**
- **The deep-walk guard needs a symbolic dividend.** `MAX_WALK_DEPTH` exists because
`i64 / 3` builds a ~262-deep divider that aborts on a 2 MiB stack, and
`a_deep_term_walk_is_refused_not_allowed_to_overflow_the_stack` held it with the
pinned shape. Pinning folds that divider away, so the guard lost its vehicle: the
test now drives a *symbolic* companion
(`a_symbolic_division_by_a_non_power_of_two_at_i64`) and asserts the pinned shape
is `verified` -- the positive evidence that the fold, not a tighter budget, closed
it. **When a fix makes a query decidable, check what else used that query as a
stress vehicle.**
## A pin is keyed by the variable's index, not the argument's local
The pin above worked for a whole argument because an argument's symbolic variable
*is* its local (`var_named(l, w)`), so `pins` could be a list of `(local, k)` and the
seed loop could look up by local. That is a coincidence of the argument case, not a
property of the pin. An aggregate part's variable is allocated from a different index
space (`spec.rs` gives a field `base + next_slot`, past `max_local + 1`), so the same
lookup never matched: `requires: w.v == -7` with the body `w.v / 3` was extracted as a
pin and then *discarded*, and the field stayed symbolic.
The cost is not small. The field is `i64`, so `w.v / 3` builds the full 64-bit
restoring divider -- the same ~262-deep term the symbolic-division vehicle uses -- and
the query is refused for the size of its own diagram even though the precondition
leaves exactly one value. Measured: `incomplete` in 1.18 s before, `verified` in 0.00 s
after.
`pins` is now `(variable index, k)` and the seed loop keys by `smt::index(v)`, so one
pin reaches wherever that variable is seeded: an argument, a struct field, a nested
path, an array element. `lit_of` masks to the *variable's own* width rather than the
argument's, because the pin value is written signed (`-7`) and each part needs its own
two's-complement pattern (`249` at eight bits, `-7` as `u64` at 64).
The general lesson: **an identity that holds for one seeding site is not an identity of
the pin.** The pin is about a *variable*; anything keyed to a local, an argument name,
or a MIR place is keyed to the wrong thing and will silently drop the pins it does not
recognise. The corpus is what catches it: the aggregate-part targets are the only ones
that distinguish the two keys, and before they existed a mutation that deleted the
field/nested/element arms passed every test.
## The imperative layer (`wp.rs`) has three traps
If you touch verification-condition generation, these are the mistakes that make
it *silently* prove nothing useful:
1. **Walk backwards from the postcondition.** The contract is
`pre => wp(body, post)`. Starting the walk from `pre` produces a vacuous
condition.
2. **Do not rewrite loop obligations with the dominating assignments.** Loop
preservation and exit are quantified over every loop-head state, so they are
recorded in loop-head terms. Rewriting them makes them trivially true once the
initialisation pins the variables — a broken invariant passes. Assertions are
the opposite and *are* rewritten, then wrapped in `pre =>` at the end of
`verify`.
3. **Termination is a separate obligation.** `While.variant` is optional; with it
the engine derives the measure after one iteration by *symbolic evaluation*
(`variant_after`, which builds expressions, not predicates) and emits
`I && c => V' < V`. Without it, only partial correctness holds and
`Report::correctness()` says `Partial`. `terminates()` compares the
loop count against the variant count: one unannotated loop makes the whole
report partial.
A known gap: `variant_after` treats a nested `while` as a no-op, so an outer
measure must already account for the inner loop.
## The memory layer (`mem.rs`) is a bounded array, not a heap
`Mem` is `2^addr_width` cells, one symbolic word each. `read` at a symbolic address
is an ite chain; `store` is a *simultaneous* update produced by `store_binds` and
applied through `smt::substitute` (or `Stmt::AssignMany`). Two things to keep in
mind when editing:
1. **Address width must match the cell count exactly.** A wider address could name
a value that is not a cell and would silently alias onto the last one, so
`check_addr` rejects it. `declare`/`Mem::new` enforce the power-of-two length
and the `MAX_CELLS` cap.
2. **Old values need capturing.** A postcondition lives in the final state, so
substitution rewrites every cell variable in it. Writing `m.read(i)` in a
postcondition means the *new* contents; assign old contents to fresh variables
first. `tests/mem.rs` shows the swap done correctly.
3. **Prefix predicates come from `quant`, not from the engine.** "All cells below
k" is a bounded quantifier, and `Mem::forall_below` expands it into one guarded
conjunct per cell. That is what makes a fill or scan loop verifiable. Two traps:
the loop counter must be *wider* than the address (a 2-bit counter cannot hold 4),
so `Mem::addr_of` truncates at the point of use; and the expansion cost is linear
in the range, so the bound must be a number the tool can count to. Do not add real
quantifiers to the bit-vector logic — that is a different decision procedure.
4. **`truncate` is the only width-changing operation.** `Op::Trunc` carries its
source width in the node's `b` field, which means the substitution walker must
treat it like a shift (carry `b` verbatim) rather than substituting it, and the
SMT-LIB exporter must render it as `((_ extract w-1 0) x)`. Adding a width-changing
op without updating those three places will produce silently wrong widths.
## A call is reasoned about through a contract, never through a body
`Stmt::Call` assumes the callee's `ensures` and discharges an obligation to establish
its `requires`. The body is never looked at, which is what makes verification modular
and also what makes the frame check load-bearing:
1. **`ensures` is an assumption, so it must imply the continuation** — `ensures => Q`,
not `ensures && Q`. Conjoining demands the callee's result satisfy the caller's
postcondition unaided, which makes every interesting call unprovable. I had this
wrong first; `a_call_is_reasoned_about_through_the_contract_alone` catches it.
2. **`requires` is an obligation, so it is recorded like an assertion**: dominating
assignments rewrite it and `verify` wraps it with the precondition. That is why
`Rule::CallRequires` appears alongside `Rule::Assertion` in both substitution
sites in `collect` and in `verify`.
3. **A write landing on a variable the call also reads is a soundness hole, not
tidiness.** With `x -> a, r -> a`, the assumed `ensures` becomes `a == a + a`,
which forces `a == 0` and lets the engine prove anything. `Stmt::frame` rejects it;
the caller must capture old values into a temporary, as for a memory swap.
4. **An unmodelled call is reported (`Rule::CallFrame`), never asserted away.** A
verifier that aborts on bad input cannot be run on a program you do not yet trust.
5. **`frame` checks shape, not meaning.** Renaming a write onto the wrong variable
passes. Do not try to "fix" this with a smarter check; the fix is `verify_proc` on
every body, and the limitation is documented where a user will meet it.
6. **The declared frame must be *complete*, checked against `wp::writes(&body)`.**
`writes` derives the real frame from the syntax and recurses through branches,
loops and nested calls (mapping a nested callee's writes through that call's
actuals). Without this a caller could declare an empty frame for a callee that
clobbers a variable, and the engine would prove the variable survived. That is a
proof about a program that does not exist, and it is the worst class of bug in a
verifier. Over-declaring is allowed: the rule is conservative.
7. **A call havocs its written targets: rename each to a fresh variable in both the
assumed `ensures` and the continuation.** Skipping this makes the pre-call value
masquerade as the post-call result (`c := 99; c := bump(a)` "proved" `c == 99`).
The fresh variable is universally quantified, which is the correct reading: the
caller must hold for every result the contract permits. `variant_after` havocs too,
so a call that writes the loop measure honestly makes termination unprovable.
8. **Two-state specs use a caller snapshot, not an `old` operator.** For a variable
the callee cannot write, `old(v)` and `v` coincide, so no operator is needed; the
missing piece was a *query*, `wp::unchanged`, which answers from the derived frame.
For a written variable there is no shortcut -- snapshot into a temporary first.
Do not add an `old` operator to the symbolic layer to "fix" this: it would give a
name to a value the state no longer contains.
Recursion is supported for a *self-call* that names a `decreases:` measure: the
call is answered by the function's own contract under well-founded induction
rather than inlined. A *mutually* recursive cycle still has no measure to name
here, so it remains unsupported. The full rule, its soundness argument, and the
four ways it is pinned are recorded in "Recursion by contract" near the end of
this file.
### The MIR frontend's version: a callee with no body is answered from its contract
The MIR executor had the same gap for a long time and it was the README's first
stated limitation: a call to a function in the same file was symbolically
executed, and a call to anything else was `Unknown`. Only a self-call with a
`decreases:` measure had a verdict, by induction. `try_callee_contract` in
`src/mir/exec.rs` closes the rest: a callee whose *body* the dump does not
contain, but whose *contract* the source does, is answered from that contract.
An `extern` declaration is the smallest shape that produces it, but the path is
not special-cased -- any item the dump carries no body for goes through it.
The order of the three checks is the whole soundness argument:
1. **`CalleePrecondition`** proves the callee's `requires:` of the call's
arguments. This is what makes the assumption sound. Proving a caller's
postcondition from an assumed postcondition whose precondition was never
established is assuming the conclusion, and this obligation is what stops a
contract from being a free pass.
2. **`CalleeDiverges`** refutes the postcondition *before* assuming it. `ensures
false` describes a callee that never returns, so every claim after the call
would be vacuously true, and a report that counted them would call a function
that does not run "verified". The query is `find_model(path && post)`, so its
discharge is `Unsat` rather than `Valid` -- the MIR twin of
`wp::Rule::DivergentCall`, and a kind whose polarity is the opposite of every
other `Callee*` obligation.
3. The postcondition is **assumed** of a fresh return variable, whose width comes
from the *caller's* destination (the one place the return type exists without
the callee's MIR).
Four refusals are deliberate, and each is the safe direction:
* A callee with **no `ensures`** gives nothing to assume. "No postcondition" is
not "postcondition `true`": the first promises nothing, the second promises
everything. Reading the absence as `true` would let a caller's postcondition be
proved from nothing at all.
* A **parameter list the source scanner cannot read** leaves the names unbound
and the call is refused. There is no second signal -- a bodyless callee has no
`debug` bindings -- so positional binding is the only tie between
`requires: n <= 10` and the first argument, and a list short by one would prove
a precondition nobody stated. `spec::fn_signature` therefore returns an *empty*
list on any shape it cannot read whole (a destructuring pattern, a wrapped
parameter list, a return type with no terminator on its line), never a partial
one. A *receiver* is not such a shape: it is read as a slot and dropped from the
call route's `params` because a call's argument list has none, which leaves a
method's list short by the receiver and refuses the call on the arity check
below. The body route needs the opposite view -- see "An inherited contract
binds by position".
* A **reference argument** is refused. `Ty::Ref` is modelled as its referent, so a
`&mut` write would land on the caller's value and not reach the local it names;
there is no aliasing model to carry it back. rustc does **not** elide the
receiver: `s.stash(x, 2)` dumps as `Slot::stash(copy _1, copy _2, const 2_u32)`
and a trait call as `<T as Bump>::bump(copy _1, copy _2)`, receiver first, so the
argument count already includes it. The real limitation is on the *source* side:
`spec::fn_signature` reads `name: Type` pairs, and a receiver has no such form
(`self`, `&self`, `&mut self`), so a method signature comes back short by the
receiver and `try_callee_contract` refuses on the arity mismatch. Even a
receiver the scanner *did* read would then hit the reference refusal above, since
`&self` is a `Ty::Ref`. So a bodyless method call is refused, deliberately and by
two independent checks, not by a missing arity check.
* **Inlining wins when it can.** The contract route runs *after* `resolve_callee`,
never before. When the body is in the dump, inlining executes the callee rather
than trusting what it promised, so it is strictly more precise; a contract route
that shadowed it would trade a proof for a promise. The test that pins this
deliberately gives the callee a contract *weaker* than its body, so a pass can
only mean the body was executed.
`CalleeEnv` resolves through `Specs::resolve`, so an `impl`-keyed contract and a
path-keyed one are both found by the rule the frontend already uses to attach a
contract to its function, rather than by a second lookup rule that could drift.
## A trait declaration's contract belongs to its implementations
A trait method declaration has no body, so rustc emits no MIR for it and it can
never be a verification target. Its contract is a promise every implementation
inherits, and the implementation is where it is kept or broken. Filing it with the
free functions was a **false proof**, not a cosmetic mis-filing: `by_fn` keys match
by unique path suffix, so a key `Bump::bump` answered a lookup for a free
`fn bump() -> u8 { 9 }`, that body was checked against the trait's
`ensures: ret == 9`, passed, and was reported `Bump::bump: Verified` -- naming the
trait method as verified when no implementation existed in the file at all.
Four rules follow, and the first two are the ones that make it sound:
* A **bodyless `fn` inside a `trait`** goes to `Specs::by_trait`, keyed
`Trait::method` with the trait's module-qualified path. A trait *default* has a
body, is real MIR, and stays in `by_fn` under the `T::value` key rustc prints for
it -- `spec::fn_has_body` is what tells the two apart.
* **Each implementation is a target**, discovered by inverting the inheritance:
for every `impl` and every contract its trait declares, the impl's method is
checked against that contract. Without this the promise was inherited by
`resolve` (so a *call* to it was answered correctly) but never checked on any
body, and the declaration was not in `by_fn` to be reported missing either -- a
silently unenforced claim, the one outcome this frontend treats as worse than a
refusal.
* A **declaration with no implementation in the file** is reported, with the
reason spelled out so it is not mistaken for a missing body. It can never be a
target, and leaving it unmentioned would make the run clean while the claim went
unchecked.
* **Two contracts for one method are refused, naming both.** When the impl and its
trait each declare a contract, `resolve` can return only one, so whichever it
dropped would vanish without a word; preferring either is indefensible. The
refusal is what loses nothing.
Tail counts are taken over *distinct functions*, not table entries: a method that
declares its own contract and also inherits its trait's appears in both tables, and
counting it twice would spell its report key `Owner::method` even when it is the
only one. Two implementations of one contracted trait are genuinely ambiguous and
do get `Owner::method`, which is what keeps one `outcomes` entry from hiding the
other.
## A verifier needs a differential harness, not just unit tests
Both soundness holes in the call rule were found by accident. `tests/modular_differential.rs`
is the deliberate version: generate callers, verify, then *interpret concretely* and
require that a proof never outruns reality. Three rules for keeping it honest:
1. **Validate the oracle before trusting it.** `smt::evaluate` is the concrete semantics
and the harness's oracle; `the_evaluator_agrees_with_the_engine_on_every_operator`
pins it against the engine. If you add an `Op` variant, add it to `eval_term` *and*
to that test, or the oracle silently becomes a second guess.
2. **Seed what the call writes.** A missing havoc rule is invisible unless a written
variable holds a distinguishable value before the call. The generator assigns `t`
before calling, precisely so that "the call left `t` alone" is a falsifiable claim.
Any new soundness rule needs the same treatment: construct the state where breaking
it is observable.
3. **Show the check can fail.** `the_property_has_teeth` runs one case under a
deliberately wrong semantics for calls and requires the detection. When adding a
rule, disable it once and confirm the harness goes red; a green check that has never
been red is not evidence of anything.
The interpreter is honest about the *declared* frame, so it reproduces the unsoundness
of an under-declared frame rather than hiding it. Do not "fix" that by having the
interpreter consult the body: the point is to model the declared contract, which is what
a real machine executes against.
## A total function can still be wrong
Two bugs in `Fixed` (Q16.16) were invisible to the proof layer, because both operations are
total and the engine proves things about them happily.
1. **`to_int` floored instead of truncating.** The doc said "truncated toward zero"; `>> 16`
is an arithmetic shift, which floors, so `-0.5` gave `-1`. Every negative fractional
input was off by one. This is the mirror of the shift-amount bug: the operator is total,
so nothing complains, and the comment described the *intent* rather than the code.
2. **`from_int` wrapped.** Q16.16 in `i32` spans `[-32768, 32767]` integers, and `v << 16`
silently wraps outside that, so `from_int(32768)` produced `-32768`. Saturating is the fix,
and it matches what `saturating_add`/`saturating_mul_int` already promise.
The lesson generalises: "this operation cannot panic" is not "this operation is correct". A
primitive that is total by construction (a shift, a cast, a bitwise op) is exactly where a
wrong result hides, because there is no trap to notice. Test the *value*, against the
language's own operator where one exists (`bits / 65536` is the definition of toward-zero).
## Fuzz the layers, not just the top
The differential harness started at the decision procedure and had to be pushed down twice,
each time finding a bug that the layer above could not see.
1. **The word layer.** `random_expressions_agree_with_enumeration` builds random expression
trees over two 8-bit variables and compares `prove` against enumeration over all 65 536
inputs. Mutation-validated: an Xor bug was caught (it claimed `(!b) == b` valid).
2. **The predicate layer.** `random_predicates_agree_with_enumeration` builds random
comparisons over random word expressions combined with and/or/not/implies. This found
DEFECT 15: a mixed-width operation silently truncated, so `trunc2(b) + (a + 115)` was
computed in two bits and a refutable predicate read as `Valid`. Both `evaluate_pred` and
the BDD agreed with each other because they share the constructor that was wrong; only
enumeration disagreed.
3. **The weakest-precondition layer.** `wp_matches_concrete_execution` builds random
straight-line and branching programs, evaluates the generated `wp` at all 256 inputs, and
compares against a concrete interpreter. It is exhaustive and does not touch the BDD
engine, so it tests the substitution machinery on its own. This found DEFECT 19: `subst`
walked a shift amount as if it were a term id, which on a two-line program recursed
forever and blew the stack.
Each layer needs its own oracle. When a bug is found, the oracle is usually the only thing
that disagrees -- which is the point.
## A field is not a term id just because its neighbours are
`Node.b` is a term id for most operations, but it is a *payload* for `Trunc` (source width)
and `Shl`/`LShr`/`Shr` (shift amount). Every traversal that reads `n.b` as a term has to
carve out those four ops. `blast` and `eval_term` do; `subst` did not, and that was DEFECT 19.
The symptom was not a wrong answer but unbounded recursion: term id 3 named a term that
contained the shift, so the walk never bottomed out.
When you add a traversal over `Node`, list the ops whose fields are payloads and handle them
explicitly. The compiler cannot help, because a shift amount and a term id have the same
type. Grep for `Term(n.b)` and check each site.
## A printer is part of the proof
`smtscript.rs` turns the engine's formula into SMT-LIB2 so an independent solver can
reproduce the proof. That makes the printer soundness-critical: if it prints a different
formula, the external evidence does not apply. Three bugs, all found by reading the output:
1. **Polarity.** A one-bit word used as a proposition printed as `(= w 0)` while the comment
said `w != 0`. `truth(false)` came out as `(assert false)`, which every solver reports
`unsat` -- so an external checker would call an impossible obligation proved. `distinct`
is the spelling of `!=`.
2. **Sort.** `not`, `and`, `or`, `xor` exist in both readings, and the printer always used the
bit-vector operator, so `not(x == y)` became `(bvnot (= x y))` -- ill-sorted, since `bvnot`
wants a bit-vector and a comparison is a boolean. The width decides which spelling is valid.
3. **Direction.** `truncate` widens as well as narrows, and the printer used `extract` for both,
so a widening `truncate` produced `((_ extract 15 0) x0_8)` -- extracting bit 15 from an
8-bit vector. Widening is `zero_extend`.
The lesson is that a comment stating the intended semantics is not a check. Two of the three
bugs were under a comment that described the correct behaviour.
## A hazard you can detect beats a hazard you document
The twelfth hole stamped `Certificate` and `Implication` with an arena generation. The
thirteenth did the same for `Report`. The fourteenth asked the obvious follow-up -- what
*else* carries a term id? -- and found `Var`, `Pred`, `Mem`, `Query`, none of them stamped.
A stale `Var` through `prove` overflowed the stack, which is exactly what the `with_fresh`
comment had always said would happen:
use-after-free in the term arena ... typically shows up as unbounded recursion rather
than a clean panic
The comment was right. It had been right for many rounds while I read past it, and the
reason is worth writing down: it described the *symptom* rather than the *invariant*, so it
read like documentation of intended behaviour instead of a bug report about missing checks.
Two lessons.
1. Stamping types one at a time is whack-a-mole; the next type forgets. The fix is a check
where the data lives -- term ids record their creating generation, and the arena's term
accessors note a mismatch -- so every handle-carrying type is covered by construction.
2. The first version of the check still overflowed. It tested the current node, and a
constructor can read a stale node then build a *current* node referring back to the stale
id, giving a cycle whose every node is current. Guarding the root is not guarding the
traversal: once anything stale is touched, the whole walk has to stop. I only found this
because I ran the probe and watched the stack blow, after having convinced myself the fix
was complete.
## A proof object has a lifetime the type does not encode
The twelfth hole, and the most serious one: `Certificate` stored a `Pred`, which is a term
*id*, and `with_fresh` resets the arena so ids restart at 0. A certificate from one scope named
a different formula in the next, and `weaken_to` returned a certificate for a statement the
engine itself refuted:
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 the statement was false and the certificate claimed it proved. The comment on
`with_fresh` warned about this in so many words — "use-after-free in the term arena" — and the
warning did not help, because a warning is not a check and the failure is silent rather than a
panic. A proof object whose meaning changes underneath it is worse than one that panics.
Fixed with an arena `generation` bumped by every reset; `Certificate` and `Implication` record
it, and every rule re-checks it and returns `None` on a mismatch.
Two general lessons, both about handles.
1. An id into a reusable arena is a *pointer*, and a pointer with no generation is dangling
after a reset. If a type is designed to outlive the scope that created it, it must carry
whatever makes it valid, and the rules that use it must re-check. "One `with_fresh` per
proof" is a convention; the generation is a check, and only the check survives a caller who
did not read the comment.
2. A documented hazard is not a handled hazard. This project treats an unbacked claim as a
defect; a comment warning that a thing will corrupt the arena is an unbacked claim about
*safety* unless something enforces it. When a comment says "do not do X or Y happens", ask
whether Y is caught or merely described.
## A stamp that the reset rewrites cannot detect a reset
The generation check above was itself defeated by the table it lived in. `term_gen[slot]`
recorded the generation that created the term in `slot`, and staleness was
`term_gen[slot] != generation`. But `reset()` is exactly the event that both recycles slot
numbering *and* leaves `term_gen` in place, so the next `mk_term` writes a *current* stamp
onto whatever term lands on a stale handle's slot. A `Pred` saved from one arena was then
discharged against a term it had never seen:
`x == 1 && x == 2` (false for every `x`), saved in arena A
arena B: build enough terms to reach A's slot
`saved.prove()` in arena B : `Valid` <- a proof of a false statement
The check compared the *slot's* stamp, which the recycling event rewrites; it had to compare
something the recycling event cannot touch. The generation is now packed into the id itself
(`Term::pack(slot, generation)`), so `is_stale` compares the handle's own bits. The lesson
generalises: an id that can be recycled needs its generation *inside the id*, because a side
table indexed by the recycled key is written by the same event that invalidates the handle.
`reset()` also keeps the generation non-zero and inside the bits a handle can hold, so the
sentinel's generation never matches a live arena.
The general auditing question, alongside "is the conclusion true" and "is the premise
reachable": **does the thing that invalidates the handle also rewrite the evidence used to
detect the invalidation?** If so, the check cannot fire.
## A refusal has to outrank the verdict it produced
Guarding a malformed term at the point of construction is not enough when a second entry
point can reach the same term. `word(1, 65)` built a term the bit-blaster's `[u32; 64]`
buffers could not hold; the blaster indexed `out[64]` and *panicked inside the solver*, so a
malformed specification became an unwind rather than an `Unknown`. Two fixes, both needed:
the width is refused where the term is built (`word`), and refused again at the blaster's
entry (`smt::Ctx::blast` and `bitblast::blast` mark the query ill-formed). The second matters
because a term can arrive by a path that skipped the first — a future constructor, or a
deserialised term — and the buffer bound is the invariant, not any single constructor.
The subtlety is that the SAT blaster marks the query and *returns*, and the caller had already
computed a verdict from the (now-meaningless) CNF. So the query layer had to check
`ill_formed` (and `stale`, and `var_overflow`) *before* reading the verdict: a refusal is only
a refusal if it wins. When adding a "mark and continue" path anywhere, check that every reader
of the result consults the mark.
## A report is valid only in the arena that produced it
`wp::Report` holds `Obligation`s, and an `Obligation` is a term id plus the generation that
created it. `Obligation::discharge` answers `Unknown` once the arena has moved on, so a report
that outlives its `with_fresh` scope *fails safe* — but it fails, and the example
`examples/pipeline.rs` was reading a report built in one scope after a second `with_fresh` had
already reset the arena. It happened to work only because no reset intervened before the read;
one more statement would have flipped every verdict to `Unknown`. The example now discharges
each report inside the scope that built it and lets only the self-contained SMT-LIB2 text
escape. The rule for callers: if a value holds a term id (`Report`, `Certificate`,
`Implication`, `Query`), consume it before the next `with_fresh`, or carry the generation and
re-check — never assume the arena is still the one you built in.
## The abstraction is where the claim lives
The eleventh hole was `Verified<T>`: it documented itself as "a machine-checked claim that the
associated contract was proved" while storing no contract and accepting any certificate. A
kernel test proved `x <= 255` and wrapped `42u32`, and it passed. The type name asserted a
connection that did not exist.
Two lessons, and the second is the sharp one.
First, an abstraction's doc comment is a claim like any other, and it can outrun the code the
same way a summary can. When the type is *named* for a guarantee, the name is the claim, and it
needs the same suspicion as a printed verdict.
Second: I tested the fix with `prove_equiv(v.statement(), x.le_val(255))` and it passed against
a deliberately broken wrapper. Of course it did — every certificate is a theorem, and every
theorem is equivalent to `true`. A semantic comparison cannot distinguish theorems, so it has
no teeth for checking *which* theorem was recorded. Structural equality does. The general
point: when testing that an object records the right thing, compare structure, not semantics;
if the object is constrained to be provable, semantics is constant and the test is vacuous.
## The exporter emitted formulas no solver would accept
The SMT-LIB2 exporter's doc said the boolean and one-bit-vector readings of `and`/`or`/
`xor`/`not` "coincide, so treating them as boolean is safe". They coincide *semantically*
and not *syntactically*: SMT-LIB is strongly sort-checked, and `Bool` is not `(_ BitVec 1)`.
Printing a one-bit connective in a bit-vector position produced
(bvule (_ bv1 1) (or (distinct ...) (distinct ...)))
which every compliant solver rejects. The failure mode is the worst kind for this module:
the export exists so an *independent* solver can check the proof, and an ill-sorted file is
not a failed check but no check at all -- the independence claim is quietly void.
It was found only by handing the text to a real solver. Unit tests asserted the *shape* of
the output and passed; a z3 differential over random predicates failed on 77 of 800 cases,
all of them width 1 or a comparison in a word position. Hand-wavy "the truth tables agree"
reasoning is not a substitute for running the artifact through the consumer.
The fix renders from the expected *sort*, not the node's own width: `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`. A comparison's spelling lives in its own `Cmp` printer
because both contexts need it -- and because `Bool` delegating to `Bits` which delegates
back to `Bool` for the same node recursed until the stack overflowed, which the first
attempt at the fix did.
## Third time: the call arm
After `if` and `while` came the call, the third construct whose right-hand claims were
checked in the wrong state. `a := 5; c := double(a); assert c == 10` was refuted with `c`
free, even though the callee's contract says `c == a + a == 10` and the `CallRequires`
obligation was discharged.
The fix differs from the other two in a way that matters, and getting it wrong would have
looked like success. `if` and `while` describe their entry state in the *same* variables,
so wrapping the claim with `guard_range` suffices. A call *renames* every written target
(that is the havoc that keeps pre- and post-call values apart), so the goal must be
substituted too. Wrapping alone would leave `implies(v == a + a, c == 10)` with the old `c`
still free -- still refuted, the change inert. The arm therefore substitutes the goal by the
havoc list *and* wraps it, which `guard_range` cannot express.
The pattern to carry forward: after a `while` or a call, a claim to the right is checked
under that construct's exit assumption, and the transformation must touch both the
assumption and the goal. `Assume` is the fourth instance of the same family and already does
this via `guard_range` plus `*cursor = implies(*c, *cursor)`.
## The same defect, one construct over
An assertion after an `if` was checked as if the `if` were absent (a false refusal, fixed
by rewriting the claim to `wp(if, g)`). The loop arm had exactly the same hole and was not
touched by that fix: an assertion after a `while` was checked in the *pre-loop* state.
`while x < 3 inv x <= 3 { x := x + 1 }; assert x >= 3` came back refuted with counterexample
`x = 0` -- the entry state, which the loop body never leaves untouched -- while the loop's
own `LoopExit` obligation, `inv && !guard => q`, proved the very same claim.
The tell is that the loop *already computes* the context the claim needs. `LoopExit` is
`inv && !guard => q` for the continuation `q`; a claim to the right of the loop is the same
`q`, so it wants the same context, `inv && !guard`. Fixing one construct does not fix its
sibling, and the sibling is found by asking where else the same expression is built: search
for the *shape*, not for the bug.
`LoopExit` itself must not be wrapped again -- it already carries its context, and
`guard_range`-ing it would only weaken a correct obligation. The rewrite is applied to
slots strictly to the right of the loop (`start..entry_n`), which is why `entry_n` is
captured before the loop's own obligations are pushed.
## A kernel rule with no bounds proves anything
The `Theorem` impl for `Imp` was
```rust
impl<P, Q> Theorem for Imp<P, Q> {
type Proof = ImpProof<P, Q>; // the *propositions*, not their proofs
}
```
There is no bound on `P` or `Q`, and the associated type names `P` and `Q` rather than
`P::Proof` and `Q::Proof`. So `assert_proof!(Imp<Truth, Falsity>)` compiled: the kernel
accepted `Truth => Falsity`, a falsehood, while correctly rejecting `And<Truth, Falsity>` and
`Equals<u8, u16>`. The module's doc says "if the reasoning is wrong, the program does not
compile", and it was false for the one connective that carries reasoning. The fix is both
bounds and the proof types:
```rust
impl<P: Theorem, Q: Theorem> Theorem for Imp<P, Q> {
type Proof = ImpProof<P::Proof, Q::Proof>;
}
```
Two things had to be true for this to survive, and both are worth checking for elsewhere.
1. **A missing bound is invisible until something requires it.** `And` and `Equals` carry
bounds (`P: Theorem, Q: Theorem`; `impl<A> Theorem for Equals<A, A>`), so a false `And` or a
false `Equals` fails to compile. `Imp` did not, and nothing noticed, because the only way to
notice is to ask for the proof of a false implication -- which no test did.
2. **A constructor that does not type-check against the associated type is a warning nobody
reads.** `imp_intro` and `modus_ponens` already used `P::Proof`/`Q::Proof`, so they returned
`ImpProof<TruthProof, TruthProof>` while the associated type was `ImpProof<Truth, Truth>`.
That mismatch is a compile error the moment a test *names* the associated type, and no test
did. The regression test now names it, and the `compile_fail` doctest
`assert_proof!(Imp<Truth, Falsity>)` is the teeth: reverting the impl turns it red.
The general rule for a proof kernel: every connective needs a `compile_fail` example for a
*false* instance of it. A kernel is only as strong as its weakest rule, and the untested rule
is the one that is wrong.
## A guard can be correct and still be untested
While sweeping for the ninth hole I checked `MAX_VARS`. `var_term` refuses an index past the
cap by setting `overflow` and returning `Term(0)` — and `Term(0)` is a *valid* node, so the
guard is what keeps a query from answering about the wrong term. `query_valid` and `query_model`
both check it and return `Unknown`. No test touched it.
I predicted the unguarded failure would be a false `Valid` (a proof of a false statement).
Measured, it is a bogus **witness**: `prove(v300 == 0)` comes back `Counterexample(v0 = 1)`,
because the fallback made v300 alias v0, so the engine names a variable the query never
mentioned. Wrong prediction, and the measured version is the more useful fact.
Two lessons. First, a guard that is correct is not the same as a guard that is tested — the
whole overflow path was dead to the suite. Second, and this is the recurring one: I predicted a
failure mode and it was wrong, which is why the test comment now records what was measured
rather than what was expected. Prediction is cheap; the probe is what counts.
Both directions are pinned: `exceeding_max_vars_reports_unknown_not_a_proof` and
`a_query_within_max_vars_is_decided_normally`, so the guard cannot pass by answering `Unknown`
to everything.
## An oracle that sweeps the poles does not test the boundary
`a_signed_constant_multiply_overflow_is_exact` checks the `i64` multiply-overflow
predicate, whose whole reason to exist is the `w == 64` arithmetic that the small-width
sweep cannot reach (`1i128 << 63`, the width mask). The `i64` sweep derived its probe
points as `lo = mn / |c|` and `hi = mx / c` for *both* signs of `c`. That is right for
`c > 0` and wrong for `c < 0`, where the product is decreasing and the safe interval
runs from the negative bound to the *positive* transition at `2^63 / |c|`. Deriving both
ends from `mn` put every negative-`c` probe near `-4.6e18` and never reached `+4.6e18`.
The tell was not a failure -- it was a **pass**. The small-width sweep covers the same
formula, so the test was green; what was untested was the 64-bit path specifically. To
show the hole is real, mutate the implementation in a way that only `w == 64` can
observe (`+ 1` guarded by `w >= 64` on the high bound) and run the test with the old
probes: it **passes**. With the probes bracketing the true interval it fails on
`4611686018427387905 * -2`, which is exactly the boundary. Two lessons:
- **A width-specific test must fail on a width-specific mutation.** If a bug that only
`w == 64` can exhibit does not turn the `i64` sweep red, the sweep is decoration -- the
small-width loop is doing the work. Mutate, then confirm the red.
- **Derive a probe bound from the true interval, never from the implementation.** The old
derivation was "the same way the implementation derives it", which is exactly backwards:
a bound copied from the code under test moves when the code moves, so it can never
straddle a fencepost the code got wrong. Here the two ends *swap* for `c < 0`, and the
honest derivation (`ceil_div(mx, c)` low, `floor_div(mn, c)` high) is what makes the
boundary visible.
## The evidence for a refutation is also a claim
The ninth hole was in `Cex`: the model returned with a `Counterexample` verdict. It inlines 16
assignments, `model` stopped at the cap silently, and `value_of` returned `None` for a dropped
variable exactly as for an untouched one. So a caller could not tell an incomplete witness from
a complete one, and a witness is the *evidence* for a refutation.
That is the same class from a third angle. The first five holes let a **summary** outrun its
evidence; the sixth and seventh gave a **proof** with no evidence; the eighth gave an ambiguous
**negative**; this one gives a **witness** with a hole. In every case the object claims more
coverage than it has. So the sweep question generalises:
6. When something is reported as a *result* — a verdict, a summary, a witness, a count — does
the type say what it covers? The negative and the positive both need the answer, and the
fixed-size buffer is where the coverage quietly shrinks.
`Cex` now carries `total` alongside `n`, `is_complete()` compares them, and `Display` prints
`TRUNCATED`. Nothing else in the crate consumed `Cex` fields, so the fix is contained.
## An ambiguous negative is the same bug as a silent truncation
The eighth hole lived in `enumerate_counterexample`, the function the tests use to
check the engine. It took a `limit` and returned `Option<u64>`, so `None` meant either "swept
the whole domain, nothing violated" or "stopped early, nothing violated". Searching a prefix of
the domain reported no counterexample for a property that is false.
That is the recurring class one level up: not a limit that truncates a *result*, but a limit
that truncates the *search* and then reports the same value as a complete sweep. The tell is a
negative answer whose type does not say what was covered. So:
6. When a function returns "nothing found", `false`, or `None`, does the type say whether the
whole space was covered? If a caller can pass a smaller space and get the same answer, the
negative is ambiguous, and it will eventually be read as a proof.
The fix removes the choice rather than documenting it: the parameter is now the domain size,
derived by `domain_of_bits(bits)` from the input width, and the return is `Search::Witness` or
`Search::NoWitness`. Checked while sweeping: `exhaustive.rs` is safe because its domain is the
type itself and its loop uses `checked_add`.
## Quote the count, do not remember it
Three commits in a row said "161 tests pass", "163 tests pass", "165 tests pass" while the
real numbers were 149, 151, 153. Every other figure in those messages was measured -- the
differential case counts, the mutation counts, the coverage counters. The test total was the
one number I recalled, and it drifted by a constant twelve, which is the signature of counting
something else once (test functions plus doc examples, probably) and then incrementing from
memory.
The failure is the same class as the seven holes, in the reporting rather than the code: a
number stated with more confidence than the evidence behind it. The fix is the same shape too
-- do not argue it, measure it. `scripts/test-count.sh` runs the suite and prints the exact
count, so the figure is a command rather than a memory. Run it before writing the number.
If a claim is worth putting in a commit message, it is worth the command that produces it.
## A literal is a claim about a width
`word(v, w)` truncated `v` to `w` bits. `word(300, 8)` was the same term as `word(44, 8)`, so
the DSL expression `x + 300u32` on a `u8` silently meant `x + 44`, and the engine would
happily return a counterexample or a proof about a constant nobody wrote. `eq_const` already
refused an out-of-range constant, so the two spellings of the same intent disagreed -- a
sure sign that one of them was wrong.
`word` now marks the term, and the query answers `Unknown`. The one legitimate use of the
truncation was the "all ones" idiom, `word(u64::MAX, w)`, used for a mask or a maximum; that
is now `all_ones(w)`, which says what it means and does not read as a 64-bit constant.
Two lessons.
1. A helper that takes a value and a width has a contract, and "it fits" is part of it. When
the type system cannot express the constraint (a runtime `u64` and a runtime width), the
check has to be explicit and the failure has to be *visible* -- here, a refusal rather
than a wrapped value.
2. When two entry points express the same idea (`eq_val` and `x + k`), test that they agree.
The disagreement was the bug, and it would have been caught by a one-line differential
test between the honest spelling and the convenient one.
## Vacuity is not only about widths
The sixth hole was vacuity caused by a width: a bound too narrow to name `len`. The seventh is
the same failure with no width involved at all -- `verify(s, pre, post)` with an unsatisfiable
`pre`. The condition `pre => wp(body, post)` is a theorem for *any* body and postcondition
when `pre` is unsatisfiable, so the report said `Total` about `x := 0` proving `x == 99`.
The lesson is that vacuity is a property of the *premise*, not of any particular construct.
Every entry point that takes a predicate and proves something under it has to ask whether the
predicate can hold:
* a top-level precondition (`verify`, `verify_proc`);
* a guard or a range that could be empty (`forall_guarded(lo, hi, ..)` with `hi <= lo`);
* a width, mask, or cap that makes a named value unreachable (the sixth hole).
Swept so far: `mem` (width), `verify` (unsatisfiable precondition). `quant::forall_guarded`
and `exists_guarded` are *not* affected: an empty range yields `true`/`false` respectively,
which is correct for an empty range, and `inside` already treats an unrepresentable index as
outside the bound rather than truncating it.
## A differential test that fails on a correct program is a bug in the test
The soundness families in `tests/modular_differential.rs` check one direction: if the engine
reports verified, no concrete execution violates the postcondition. That direction cannot see
over-refusal, and over-refusal is exactly what the two defects above were -- so the new
assertion family checks both directions:
> verified if and only if no concrete execution reaches a failed assertion.
Both defects 36 and 37 are caught by it. The teeth were confirmed by reverting each fix in
turn: without the branch guard the family reports "every concrete run is fine but the engine
refused the program", and dropping the assertion obligation outright makes it report "the
engine verified a program whose assertion fails on a real input".
The family also cost an afternoon to a phantom soundness hole, and that is worth recording.
The concrete interpreter threaded the state *by value* into the recursive branch call, so every
assignment made inside an `if` was lost. The engine was right and the interpreter was wrong, but
the failure message said the engine had verified a program with a real violation -- the most
alarming message a verifier's test suite can produce. The lesson is the ordering of suspicion: a
differential test that disagrees with the engine on a *correct* program is almost always the
test's bug, and the interpreter is the less-trusted component, because it is the newer and less
carefully reviewed one. Thread the state by `&mut` through branches.
## A claim after a statement is made in a state that statement can produce
An assertion recorded to the *right* of an `if` is dominated by it, so its claim is
`wp(if, g)`, not `g`. The walk already rewrote dominated claims through `Assign` and
`AssignMany`, but not through `If`, so `if x == 1 { x := 1 } else { x := 2 }; assert x == 1 ||
x == 2` was reported as a failure while the contract obligation proved it -- the assertion was
checked as if the `if` were not there. The `If` arm now rewrites the slots recorded before it
with `ite(cond, wp(then, g), wp(else, g))`.
This is the mirror image of the previous defect and it is worth seeing the pair together:
* a claim *inside* a branch is checked under the branch's guard (`guard_range`), because the
branch is what reaches it;
* a claim *after* the branch is checked through the branch's effect (`wp_of`), because the
branch is what the state came from.
Both are "the claim is about the states that can reach it", read in the two directions. A
statement that changes the state has to reach every claim it dominates, and an `If` was the
one statement that did not. Loops are deliberately excluded: a loop's effect on a claim after
it is only the invariant, and the cursor already carries that, but a dominated assertion is
not re-derived through a loop for the same reason loop obligations are not rewritten with a
dominating guard -- the invariant is universally quantified and rewriting through it would
hide a real failure behind a vacuous one.
## A claim is made in the state that reaches it, not in the state after it
An assertion recorded as `implies(cursor, c)` is the wrong claim. The cursor is what the
*continuation* needs, so `implies(cursor, c)` says "if whatever comes after this assertion is
satisfiable, then `c`". That is not what `assert c` means, and it has two consequences.
The visible one is that correct programs were refused. `if x == 1 { assert x == 1 }` was
reported as a failure, because the assertion was checked against every `x` rather than the `x`
the guard admits -- so an assertion inside a branch could never be used. `wp.rs` documented the
opposite ("checked in the context of the state that reaches it"), and no test exercised an
assertion inside a branch, so the documentation and the code disagreed and nothing noticed.
The assertion's goal is now just `c`. The state that reaches it is fixed by two mechanisms,
and keeping them separate is what makes the guard correct:
* assignments that dominate the assertion are applied as *substitutions*, in the backward
walk, so `x := 5; assert x == 1` becomes `assert 5 == 1`;
* guards, loop invariants and dominating `assume`s are attached as *context*, by
`guard_range`, after the branch or body has been walked. Wrapping `c` in `g => c` at the
enclosing construct keeps `g` about the entry state. Substituting `g` in instead would let a
write inside the branch rewrite the guard, which turns `if x == 1 { x := 5; assert x == 1 }`
into a green check.
`guard_range` applies to `Assertion` and `CallRequires` obligations only. Loop obligations are
universally quantified over the loop-head state and already carry their own context; rewriting
them with a dominating guard is the vacuity bug they exist to avoid.
## One variable index is one variable, at one width
The blaster keys its BDD variables by `(index, bit)`, and a variable's index is what
`var_named` sets. Declaring the same index at two widths therefore aliases the low bits:
`var_named(0, 8)` and `var_named(0, 16)` share bits 0..7, so `a == 3 => truncate(b, 8) == 3`
came back `Valid` -- a theorem about one variable silently constraining another. The engine
even handed back a counterexample naming one `(0, 16)` assignment while the model also touched
`(0, 8)`, because the model builder reports one entry per index.
`var_named(idx, w)` called twice at the same `w` is the intended "name a variable for a
readable model" case and stays allowed; calling it at a *different* width is a modelling
mistake, and the query is now refused. The general rule: if a name carries an index, the
index has to determine the variable completely, or the name is not a name.
## A missing conjunct hides in the ranges the tests do not use
`verify_bounded_sub_is_total` states the refinement of `Bounded::sub`. Its doc named three
conjuncts -- no underflow, result at or above `min`, and (free) at or below `max` -- and the
goal carried only two, as `iff(in_range(diff), want)`. The underflow gate `b <= a` was on the
right side but not on the left, so the left side asked whether the *wrapping* difference is in
range.
For the ranges the tests used that is the same question. A narrow range makes an underflow wrap
to a value above `max`, so `in_range(diff)` is false and the two sides agree. Every test used
`min`/`max` inside `[0, 1000]`, and all of them passed. At `min == 0`, `max == u32::MAX`, an
underflow wraps to a value that is still `<= max`, so the left side is true while `checked_sub`
returned `None`: the goal became `true <=> false` and the obligation was refuted. It was never
proved for a wide range at all.
The fix is to gate the left side exactly as `checked_sub` does -- `result_ok = no_underflow &&
in_range(diff)` -- and the new tests pin both the full range (it must now be proved) and the
ungated statement (it must still be refuted there, so the gate cannot be dropped again).
The general lesson is about the *test inputs*, not the formula: a proof obligation parameterised
by `min`/`max` is only as strong as the ranges the tests exercise. A boundary that the tests
never approach is a boundary the formula is free to get wrong, and a parameter that is always
zero or small in the tests is nearly a parameter the proof does not use.
## A proof that never mentions the thing it is named after
`verify_scale_identity` was documented as proving `k * SCALE / SCALE == k`, but its formula
was the `verify_fixed_roundtrip` proof with the local variable names changed: `shl(k, 4)` then
`lshr(..., 4)`. No scale factor appeared anywhere. The identity therefore held for *any* scale
value, because the scale was never an input -- a multiplication by 10 instead of 16 would have
"satisfied" it just the same. The function had a name, a doc comment and a passing test, and it
proved the roundtrip lemma a second time.
The fix is to actually multiply by the scale before dividing. The tell is general and cheap to
apply: read the formula and check that every noun in the doc comment appears in it. A verifier
whose name mentions a constant, a mode, a bound or a factor must have that thing as a term in
its goal, or the parameter is decorative.
## A proof about the wrong quantity
`verify_saturating_add_bounds` was documented as "the saturating result is always `>= a` and
`>= b`", but the formula never built the saturating result. It proved a *conditional* statement
about the *wrapping* sum, `a <= sum => (a <= sum && b <= sum)`. The hypothesis it carried is the
complement of the case that matters: saturation is interesting exactly when the sum overflows,
which is when `a <= sum` is false. So the one scenario the function is named for was excluded by
its own precondition.
The goal is now unconditional and about the saturating value. The test also asserts that the
wrapping sum violates the bound for some input, so the `ite` cannot be dropped.
The tell, shared with the earlier vacuity defects: the comment and the formula are about
different objects. Read the formula and ask which term in it is the one the comment names.
## Prove the property the comment claims, at the boundary
Two verifier functions in `logic.rs` proved a true statement that was one step weaker than the
claim their comments made, and the gap was exactly at the boundary:
* `verify_fixed_add_no_overflow` concluded `sum <= 2^15` while the comment said the sign bit
stays clear. `2^15` *is* the sign bit. At the stated inclusive bound `2^14` the sum
`2^14 + 2^14 = 2^15` reads as `-32768` in a signed 16-bit add. The bound is now `2^14 - 1`
and the goal is `sum <= 2^15 - 1`.
* The tenth "algebraic identity" was `ult(x, 0) <=> false` with the comment "x < 2^w". That is
a tautology of the encoding -- an unsigned value is never below zero -- and it is unchanged
by substituting *any* term for `x`, including a constant, so it proved nothing about `x`.
It is now `x <= all_ones(w)`, the range law the comment described.
Both are the same mistake: the comment and the formula describe different propositions, and
the formula is the weaker one. A verifier function is read by its comment; if the comment names
a bound, the formula has to prove *that* bound, at *that* boundary, including the endpoints.
## A parameter the proof never mentions is a parameter the proof cannot use
`verify_bounded_sub_is_total(min, max)` proved the refinement invariant of `Bounded::sub`, but
the formula dropped `min` outright (`let _ = min;`) and the doc claimed "in range exactly when
`a >= b`". That claim is false for any non-zero `min`: at `min == 10`, `a == 11` and `b == 10`
are in range and `a >= b`, but `a - b == 1` is below `min`, so `sub` rejects it. The proof
succeeded because it no longer mentioned the parameter it had been given.
The corrected obligation is `in_range(diff) <=> (b <= a && diff >= min)`, with the `min`
conjunct doing real work, and the test now states the claim *without* that conjunct and shows
it is refuted. The pattern to watch for: a verifier function that takes a parameter and
discards it. `let _ = min;` is a confession that the formula and the signature have drifted
apart, and the honest response is to either use the parameter or remove it.
## A sufficient condition that goes vacuous is not a proof
`verify_accumulator_no_overflow` proved "the sum cannot wrap" as `sum <= 2 * max`. That is a
sufficient condition only while `2 * max` fits the width. When it does not, `ule_const` reads
the bound as "every value is below it" and answers `true`, so the obligation was *vacuously*
proved for exactly the `max` values whose sums overflow. `verify_accumulator_no_overflow(8, 200)`
returned `Valid`, though 200 + 200 = 400 wraps to 144 in 8 bits. This is the whole safety
argument for an accumulator, so the vacuity sat on the most load-bearing proof in the module.
The fix is to test the property itself rather than a bound on it: a sum wraps exactly when
`sum < a`, which is width-independent and needs no side condition. The lesson is that any
"check `x <= bound`" goal has a `bound` large enough to make the check vacuous, and a proof
obligation must be phrased so that no value of its parameters can make it trivial. When the
goal mentions a constant, ask what happens when that constant is at the edge of its range.
The test now asserts the positive case *and* the four refutations, checking they come back as
counterexamples rather than merely "not proved", so a future fix that returns `Unknown` for
everything cannot pass it.
## Refuse an ambiguous assignment, do not pick one
`substitute` applied its bindings in order and kept the last for a repeated target, so a
simultaneous assignment written `x := 1, x := 2` proved `x == 2` -- a claim about a value that
appeared once in the list and lost. Reordering the same bindings proved `x == 1`. Both are
silent choices of one meaning among several, which is the failure this crate exists to prevent;
the honest answer is `Unknown`.
The refusal reuses the query-level ill-formed flag, which already covered a width clash and an
out-of-range constant, and is now named `ill_formed` rather than `width_clash` because it no
longer means only widths. Two different targets still substitute normally, which the test
asserts so the check cannot pass by refusing everything.
The general rule: when a list admits two readings, refuse. "Last one wins" is a convention, not
a specification, and it is invisible at the call site.
## A binding target must be a variable
`substitute` read a binding's left-hand side as `node_of(from).a`, with no check that `from`
was a variable. But `a` means different things per operation: for a `Var` it is the index, for
a `Const` it is the *value*, and for `Trunc`/`Ite` it is a *term id*. So binding the constant
`word(7, 8)` -- whose `a` is 7 -- silently substituted variable index 7, and a program that
"assigns" to a constant proved `v7 == 0`. A binding to a `Trunc` read a term id as an index,
which either fell outside `MAX_VARS` and was dropped, or named an unrelated variable.
None of these are refusals; they are silent rewrites of the wrong variable. The fix is that
the target must be `Op::Var`, asserted. The general pattern: `a` is an overloaded field, so
every consumer has to know which operation it is reading before it can interpret `a`, and the
only safe default is to check the operation first.
## The shift amount is a literal too
The out-of-range constant bug (`word`) had a twin in the exporter. A shift amount is printed
as a literal of the shift's width: `(bvshl x (_ bv300 8))`. `300` does not fit 8 bits, so that
is not a legal 8-bit literal -- a solver rejects the file or reads 44. And for `k >= 2^width`
the *wrap* changes the meaning: `shl(x, 256)` printed `(_ bv0 8)`, the identity, while the
engine's rule is that a shift of at least the width yields 0. So the exported file disagreed
with the engine on a legal program.
The engine's rule makes every amount `>= width` equivalent, so the exporter clamps the printed
amount to `width`: a legal literal with the same meaning. It is the same "a literal is a claim
about a width" mistake as `word`, in a different place, which is why it is worth stating as a
pattern rather than as a one-off.
The first export fuzzer could not have found it: its shift amounts were always `<= 8`, and the
bug lives at `>= 2^width`. A generator that only emits well-behaved inputs checks only the
well-behaved paths. The amounts now span `0..=11` (including `k == width` and just past it),
and a dedicated test drives `k` in `{8, 9, 255, 256, 300, u32::MAX}` and compares the parsed
meaning against the engine's rule for every input.
## A subexpression is read at its own type, not the surrounding operand's
Two reader bugs were the same mistake: a subexpression sized to the surrounding operand's
width instead of the width Rust gives it. Both let the reader *decide* a program rustc
rejects.
A shift *amount* is a value of its own type. Rust leaves an unsuffixed amount's type
unconstrained, so it defaults to `i32` and is folded at 32 bits, but the reader sized a bare
literal to the widest name in scope. At an eight-bit scope `x >> (2 << 7)` wrapped the amount
to `0` and read as `x >> 0`, and `x >> (2 << 7) == 0` was decided -- false at `x == 0` --
where rustc computes `256` and rejects the shift. The first fix floored an amount's bare
literals at a flat `i32`, which over-refused: a *typed* operand in the amount fixes the
amount's type, so `x >> (1u8 + (2 << 7))` for a `u8` `x` is a `u8` amount (`2 << 7` is `0u8`,
the amount is `1u8`) and rustc accepts it, while the flat floor built the inner `2 << 7` as
`256` and refused. `Parser::amount_width` now scans the amount's own add-level for a typed
operand and floors its bare literals at that width, or `i32` when none fixes the type.
The scan mirrors the grammar rather than flattening it, because only an operand at the amount's
*own* level fixes its type. In `2 << 7u8` the suffix is in the nested shift's amount, so the
outer amount stays the `i32` `256` (still a rustc overflow); a cast fixes the type and
overrides what it casts (`(1u8) as u16` is a `u16`, so the amount is `257u16`). `amount_floor`
is *inherited*, not recomputed, when a shift is itself inside an amount, so the enclosing type
unifies inward through the parentheses.
A negation of a constant is checked against the *value* the constant denotes, not the written
magnitude. `i8::MIN` is the bit pattern `128` and the value `-128`, and the legal literal
`128i8` has the same pattern, so the magnitude check passed `-(i8::MIN)` and recorded the
in-range `-128` -- deciding a program rustc rejects ("attempt to negate `i8::MIN`, which would
overflow"). `3 << 7` at eight bits wraps to the same pattern, so `-(3 << 7)` was decided too.
A pristine literal stays exempt, because there the negation is what makes the magnitude legal
(`-128i8` reads). The pattern to reach for: when a constant's *spelling* and its *value* can
differ (a bound, an inner negation, a wrapped fold), a check written against the spelling is a
check against the wrong thing.
The parser recurses once per nesting level, and it calls `smt::evaluate` (via `const_value`) at
every operator level. `evaluate` owns a 12 KiB `EvalMemo` as a stack local, so when the optimiser
inlines it into the recursive parser, *every* nesting level pays 12 KiB of stack: a debug frame
measured ~12.7 KiB, and `x >> ((2 << 7) + 1)` reached past the 2 MiB a test thread gets and
aborted. An abort is a crash in the caller's process, not a refusal -- the one thing the front end
is not allowed to do -- so this is a real defect, not a stack budget to be raised.
The fix is `#[inline(never)]` on `evaluate`, which keeps the memo in its own frame and alive only
for the walk; the parse depth falls from 254 KiB to 15 KiB. The memo cannot move to the heap
because `no_std` without an allocator has no heap, so keeping it off the recursion is the fix.
`verify_realistic` in `tests/mir.rs` deliberately runs on the *default* stack, and it is the gate:
reverting the attribute re-inflates the frames and the test aborts. The lesson generalises -- a
large stack local in a function the optimiser can inline into a recursion is a stack cost per
level, and the frame-address probe that found it (print `&local` at each parser level and diff the
addresses) is the way to see it, because the parse is shallow and looks innocent.
## Two rules, one program: `verify` and `wp` must agree
`verify` runs `collect`, which checks `Stmt::frame` at every call and reports a bad frame as
an obligation. `wp::wp` is *also* public -- it is the rule a caller uses to build a weakest
precondition by hand -- and it applied the same call rule *without* the frame check. So the
two entry points disagreed about the same program.
The consequence was a false proof, not a missing one. A callee whose body zeroes `g`, called
with an empty declared frame, havocs nothing under the old `wp`, so `wp(call, g == 7)` was
just `g == 7`, and `g == 7 => wp` came back `Valid`: a proof that the callee's write did not
happen. `verify` rejected the same call.
The fix is that `wp_of` checks the frame too, and returns `false` when it fails -- there is no
report to carry the failure, and the honest weakest precondition of an unmodelled call is
`false`. The general lesson: a second entry point into one rule is a second chance to forget
a precondition, and the tests have to drive *both*. `tests/call.rs` now has
`wp_refuses_to_reason_about_a_call_with_a_bad_frame` (the bad frame) and
`wp_still_reasons_about_a_call_with_a_good_frame` (a framed call still works), because a fix
that returned `false` for every call would pass the first test alone.
## A test that passes by failing to parse
The first version of the independent SMT-LIB reader could not parse `((_ extract 7 0) x)` --
a standard *indexed application*, whose head is itself a parenthesised `(_ ...)`. It handled
only the self-contained literal `(_ bvN w)`, which has one `(`.
That bug made a "teeth" test lie. `the_export_checker_rejects_what_the_old_exporter_printed`
asserted that `extract` past the end of a vector is rejected, and it was -- but by a *parser
error* at byte 10, not by the sort check the test is named for. Worse, every well-formed
export containing an `extract` or a `zero_extend` was rejected too, so the new
mixed-operator fuzzer failed on correct output.
Two things follow. First, a rejection test needs a positive control: the same test now asserts
that a well-formed `extract` and `zero_extend` *parse*, so it cannot pass by refusing
everything. Second, "the checker rejects X" is only evidence of a sort check if the checker can
parse X's valid neighbours. When the checker is the oracle, its own parser is part of the
thing under test.
## Read the printer with a parser, not with your eyes
Three defects in the SMT-LIB2 exporter were found by *reading* the output: an inverted
polarity, `bvnot` applied to a boolean, and `extract` for a widening truncate. Each was
invisible in the source -- `write!(f, "(bvnot {})", ...)` looks fine -- and each made the
external evidence not apply, because an ill-sorted file is rejected or misread.
The fix for "reading is not a check" is a second implementation. `tests/differential.rs` now
carries an independent SMT-LIB reader: it parses the export, rejects any ill-sorted operator
application (the three shapes above are its regression cases), and *evaluates* the parsed
term over all 65 536 inputs to compare against the predicate it came from. The exporter and
the engine are no longer the only two things that agree with each other.
The general lesson, and the reason it took three rounds: a printer's contract is
well-sortedness *and* meaning, and the two fail differently. Meaning you can only check by
evaluating; sort you can only check by knowing the operand types, which means the checker has
to be a type checker, not a text diff.
## Vacuity is a property of the *path*, not just the premise
The seventh hole was an unsatisfiable precondition. The next one is the same failure one
level down: an unsatisfiable `Assume` *inside* the body. `Assume(false); y := 0` with
postcondition `y == 99` came back `verified` / `Total`, because `false => wp(y := 0, y == 99)`
is a theorem. The contract was about code no run can reach.
The precondition check could not see it: the precondition was `true`, perfectly reachable.
Vacuity is not about the *entry* predicate, it is about whether any execution reaches the
code the proof is supposed to cover. Every construct that can cut a path has to ask whether
it did:
* a precondition (`verify`, `verify_proc`);
* an `Assume` inside the body -- this hole;
* a guard that is unsatisfiable, which the loop rules inherit from `Assume`-like reasoning;
* a branch condition that is a contradiction, which makes the branch vacuous.
`Assume` cannot simply be refused: a reachable `Assume` is how a callee guard or a
case-analysis split is written, and it must still verify. The check is "this `Assume` cannot
hold", not "there is an `Assume`", and the reachable case is pinned by a test so the fix
cannot degrade into refusing all of them.
## The dual class: vacuity, a proof with no evidence
Six holes now, and the sixth is the mirror of the first five. Those were *unsound*: a
summary (`verified`, `Total`, `Valid`, `unchanged`) stronger than the evidence behind it. The
sixth is *vacuous*: a proof whose evidence is empty.
`Mem::check_addr_width` accepted a bound exactly as wide as the address. A 2-bit bound on a
4-cell memory cannot hold `len`, so the standard postcondition `bound == len` was
unsatisfiable, and `bound == len => P` and `bound == len => !P` both proved. The tell is
unmistakable once seen: **an impossible precondition reported as valid.** Ask of any proof
not only "is the conclusion true" but "is the premise reachable". A verifier that cannot
distinguish `Valid` from `vacuously Valid` will certify a specification that constrains
nothing.
The fix is one bit: the bound must be strictly wider than the address. Every intended use
already passed a wider bound, so the check costs nothing and closes the trap.
Two auditing questions to add to the three above:
4. Can a precondition or guard be unsatisfiable, making the obligation vacuous? In
particular, can a width, mask, or cap make a value that the specification names
unreachable?
5. Is a proved obligation *sensitive* to the thing it claims to constrain? A mutation test —
change the postcondition to something false and demand the proof fails — is the cheapest
way to tell a real proof from a vacuous one.
That is what the memory positive family does: templates correct by construction, each with a
mutated twin that must be refuted. 140 proved, 134 mutations refuted, and the six survivors
are the `n: 0` boundary, asserted to be vacuous on purpose.
The trap also hides in the *width a claim is stated at*, not just in a bound. The
`flight_control` example proved `clamped <= 4095 => clamped * 1000 <= 4 095 000` at 16 bits,
where the product wraps to 16 bits: `scaled <= 4 095 000` is then true for every value (the
maximum is 65 535), so the implication holds for *any* antecedent and constrains nothing. The
example now models it at 22 bits — the first width that holds 4 095 000 — and asserts the
bound is refutable there before proving the implication, so a future narrowing of the model
fails loudly instead of passing vacuously. When a proof states a claim about an operation that
can overflow, check the modelled width can represent the result the claim names.
The *guard* that establishes this is itself a place to be vacuous, and was. It first read
`!prove(scaled.gt_val(4_095_000)).is_proved()`, but `scaled` is the **clamped** product, which
is at most 4 095 000 at every width: the predicate is `Unsat` at 22 bits *and* at 16, so the
negated `is_proved()` was true in both cases and the guard could not detect the narrowing it
existed to detect. The guard has to be stated over the **unclamped** product —
`find_model((raw * 1000u32).gt_val(4_095_000))`, requiring a `Counterexample` — which is
satisfiable at 22 bits (`raw = 4096`) and unsatisfiable at 16. Two lessons: a guard's predicate
must be over the quantity whose range the guard is about, not over a value already constrained
to be in that range; and `!is_proved()` is the wrong way to say "refutable", because it also
accepts `Unsat` and `Unknown`. The tests `the_vacuity_guard_{accepts,rejects}_...` pin both
widths, and `a_clamped_product_is_never_above_the_bound_at_any_width` records the fact that
made the old form vacuous.
## The harness must cover every module, or it certifies only the covered ones
The differential harness had three families -- calls, loops-with-calls, obligation pressure
-- and memory had none. Memory is the most algebraic module in the crate (ite-chain read,
simultaneous store bindings, a derived frame lemma, a guarded quantifier), so that gap was
not a coverage statistic; it was the module most likely to hold a silent disagreement with
concrete execution, and the least checked.
The fourth family compares the engine against a concrete array over an enumerated state
space of four 8-bit cells, in *both* directions, because the state space is small and
closed. Two lessons from writing it:
* **A teeth test must break in the dangerous direction.** My first attempt at a deliberately
wrong store rule made a copy keep the destination's own value, which is the identity: the
engine honestly said "not proved", so nothing was caught, and the teeth test failed for
the right reason. Proving *too little* is not a soundness bug. The rule has to prove *too
much* -- the working version writes `val` to every cell and ignores the address, which
makes `m[1] == 5` provable after `m[0] := 5`.
* **Assert non-vacuity explicitly.** A generated family can pass by producing no interesting
cases. Both counts are asserted: at least one case proved, at least one refuted.
The teeth check that matters is against the *real* rule: break `store_binds` so it ignores
the address, and the family reports `VERIFIED but 4320 sampled (array, address) pairs
violate`. That is the harness doing its job on the code it exists to guard.
The same "cover every module" rule caught `sym`, which had *no* test file at all. A DSL with
no test is a module whose surface is only ever exercised by the doc example, and the doc
example used one operator. Walking it turned up the missing literal `-` and `^` (see the
README). A module that only wraps other modules still needs its own tests, because the
*wrapping* is the code under test — an operator mapped to the wrong primitive is invisible to
every test of the primitive.
Also, twice now a heredoc-written patch has corrupted a file (a stray leading byte spliced
into the first line). Prefer the editor tool for multi-line Rust; keep heredocs for shell.
## The recurring class: a limit that truncates instead of reporting
Five soundness holes in a row, all the same shape — a bounded buffer or a width that
silently truncates a value, so a summary outruns the evidence behind it:
| `verified` | callee body | under-declared frame |
| `Total` | variant verdict | counted instead of discharged |
| `verified` + `Total` | obligations | dropped at `MAX_OBLIGATIONS` |
| `verified` + queries | real frame | truncated at `MAX_WRITES` |
| `Valid` from `exists_guarded` | index range | index truncated to the bound's width |
Two of these were *not* buffer caps but width truncations of a value, which is the same
failure in different clothing: `word(k, w)` silently keeps only the low bits of `k`. When a
value is narrowed for a comparison, ask whether the comparison is still the one intended.
When auditing, the questions that found all five:
1. Where does a count stop early, and does anything downstream know it stopped?
2. Where is a value narrowed, and can narrowing change a comparison's answer?
3. Which summaries (`verified`, `Total`, `Valid`, `unchanged`) are computed from partial
evidence, and what happens when the evidence is incomplete?
Report, never truncate. If a function can return partial data, the partiality belongs in
its type.
## A truncated set must not look like a small set
Fourth instance of the same class, and the one that defeated the fix for the first.
`writes` derived a procedure's real frame into a `MAX_WRITES` buffer and returned
`(array, count)`, truncating silently. The frame-completeness check added for the
under-declared-frame hole then compared the declared frame against a *prefix* of the truth,
so a callee writing more than `MAX_WRITES` variables was indistinguishable from one writing
exactly that many — and a caller could prove a clobbered variable survived the call.
The fix is a type change, not a flag: `writes` returns `Frame`, whose `complete()` is
`false` past the cap, and `Stmt::frame`, `unchanged_vars` and `unchanged` all treat an
incomplete frame as an unmodelled program. A separate boolean return value would have been
easy to ignore, which is exactly what happened for three rounds.
Two lessons worth keeping:
* **A count that saturates is not a count.** `(buf, n)` where `n` stops at the cap carries
no information about whether it stopped. If a function can return partial data, the
partiality has to be part of its type or it will be lost at some call site.
* **Independent constants that must stay in a relation are a bug waiting.** `MAX_WRITES`
and `MAX_CALL_ARGS` had to satisfy `MAX_WRITES <= MAX_CALL_ARGS` for `unchanged_vars` to
be total, and nothing said so. It is now a `const _: () = assert!(..)`.
Fifth instance, found in the same session as the surface pass: the *public* `wp::obligations`
also returned a saturating count, so a caller inspecting obligations directly could not tell
a complete set of `MAX_OBLIGATIONS` from a truncated prefix. `verify` was never fooled — it
reads the internal flag and raises `Rule::ObligationOverflow` — but the public accessor was,
which is the point: **fixing a defect in one path does not fix the same defect in a sibling
path that re-exposes the same data.** When a fix adds a completeness flag to an internal
helper, walk every public function that wraps that helper and check it does not re-hide the
partiality behind the old return shape.
Also: when a heredoc-written Python patch garbles itself, the failure mode is duplicated
definitions, not a clean error — `git checkout` the file and use a precise edit instead.
## A capped summary must fail loudly
`MAX_OBLIGATIONS` is a fixed-size buffer, and `push` used to drop obligations silently when
it filled. A program with more side obligations than the cap could therefore report
`verified` — and `Total` — while a failing `LoopExit` sat in the part that did not fit. Two
rules follow, and both bit me:
1. **Claim-carrying obligations must report the drop.** Loop rules and call rules go
through `push_checked`, which raises an `ObligationOverflow` obligation with goal
`false`. Assertions may still be dropped quietly, because a dropped assertion poisons
the weakest precondition and the contract obligation catches it.
2. **The notice needs a slot the program cannot occupy.** `Report::obligations` is one
longer than `MAX_OBLIGATIONS`, and `push` stops at `program_limit` (one below the end)
while `push_notice` may use the last slot. My first fix appended the overflow obligation
with `push`, so a full buffer dropped the notice too and the report still said
`verified`. When adding a report-level finding, reserve its space explicitly.
The general lesson, which is the third instance of the same class: **a summary claim is
only as good as the checks behind it.** `verified`, `Total` and `Partial` are summaries.
Whenever one is computed, ask what happens when the underlying evidence is incomplete —
missing, dropped, or merely assumed — and make that case a failure rather than a silence.
## Termination claims must be discharged, not counted
`Report::terminates` counts only variant obligations whose verdict is
*proved*. Counting the obligations instead of discharging them was a real defect: a
loop whose measure does not decrease reported `Total` while the report was unverified.
When adding a rule that contributes to a summary claim, discharge the obligation before
letting it count. `Report::establishes` answers "verified?" and "termination proved?"
together, so a caller cannot read the optimistic half alone.
## A behavioural harness cannot see a proof defect
Worth knowing before trusting the differential harness too far. The termination defect
above is invisible to concrete execution: a loop with a non-decreasing variant still
*terminates*, so `verified => no violating execution` says nothing about it. What made
it visible was a loop that diverges *and* is claimed total — the divergence is behaviour,
the claim is proof, and the two only meet when the proof is wrong in the direction that
lets a divergence through.
Two consequences for the harness:
1. Check a summary claim **outside** the `verified` branch. A claim like `Total` matters
most when the report failed, and that is exactly when an assertion nested inside
`if verified` never runs. My first version of the loop check had this bug and so
missed the defect entirely.
2. Read the claim the way a careless caller would. The harness deliberately reads
`correctness()` rather than `establishes()`, because `establishes()` folds a failure
into `Nothing` and would hide the defect. Test the sharp edge, not the safe wrapper.
## Two paths for one obligation mean neither path's teeth are real
`wp` carries an `assert` two ways: as its own recorded obligation *and* in the backward
cursor that the enclosing rule consumes. Three defects lived in this area, and each was
found by a hand-built example rather than by a test, for a reason worth internalising:
breaking *either* path alone changes nothing observable, because the other still discharges
the claim. Only a mutation that breaks both at once — or that breaks the composition rule
they share — shows the harness is load-bearing.
The consequence for testing: when a mutation does not make a test fail, do not conclude the
test is weak. First ask whether the property is enforced twice. If it is, either break both
paths in one mutation, or aim the mutation at the shared rule. `LoopExit` dropped alone is
caught by `tests/loopdiff.rs`; the cursor's claim propagation dropped alone is not, and that
is a property of the design rather than a gap in the test.
## Teeth have to isolate the guard they claim to test
The mirror of the lesson above, and the opposite failure: a test whose teeth are never
pulled, because a *different* check refuses the input first. The test
`a_declared_frame_longer_than_the_cap_is_refused` was written to pin that `Stmt::frame`
refuses a declared frame with more than `MAX_CALL_ARGS` writes — the guard that keeps
`havoc_writes` from truncating. Its first version built a body writing `MAX_CALL_ARGS + 1`
variables, which the *derived-frame* check (check 0, `!derived.complete()`) refuses long
before the declared-frame cap is reached. So the test passed, and kept passing when the cap
check was deleted: it was asserting the wrong guard, and the mutation could not tell.
The fix is to make every earlier check pass, so only the guard under test can be what
refuses: a body writing a *single* variable (derived frame small and complete), distinct
globals, distinct images. Then removing the cap makes the test fail, which is the only
proof that the teeth are real. The rule: before trusting a rejection test, run the mutation
that removes the guard it names, and confirm it fails. If a nearer check could also reject
the input, the test is ambiguous and you cannot tell which check fired.
**Follow-up: the same rule applies to proof scripts, and it caught two more defects.** The
comparison's negative Coq and Lean fixtures (`examples/comparison/bugs/coq/`, `bugs/lean/`)
were false theorems about buggy definitions, and their proof *scripts* were tailored to the
buggy shape. Correcting the definition therefore broke the *script* rather than the
*proof*, so the non-zero exit was an artifact of the script and not evidence about the bug —
the mutation said so, and the fixtures were rewritten so one script runs against both the
correct and the buggy definition (correcting the definition now makes the file compile).
Splitting the two Coq theorems into separate compilation units is what exposed a second
defect: a failed `Qed` stops `coqc`, so with both theorems in one file the second was never
reached and the exit code proved only that the first failed. The isolation check then found
a third: the loop theorem was stated `forall n, n <= 8 -> ...` under `Open Scope Z_scope`,
where `n <= 8` for `n : nat` is a *type error*, not a proof failure — it had been failing
for the wrong reason and was reported as a caught bug. The general lesson is that a proof
script is a test, and a test that fails while the defect is present has proved nothing until
the defect is removed and it passes.
**Follow-up: the gate that enforced the rule broke it, by reading a count.** The comparison
gate first asserted `verif`'s coverage summary — the `decided 0 of 1` line — for each
injected bug. That line counts only `FnOutcome::Verified`, so `Failed`, `Incomplete` *and*
`Skipped` all leave it at zero. A fixture whose contract had become unreadable (a typo in an
`ensures` name) therefore still printed `decided 0 of 1` and the gate reported a caught
defect while holding no counterexample: a lost proof read as a refutation. The summary is a
*coverage* number and the claim was about a *verdict*, and the two only agreed while every
fixture happened to be well-formed. The fix is `examples/comparison_check.rs`, which asserts
the per-function `FnOutcome` and the expected obligation kind (`panic` for the swapped
`sat_add`, `postcondition` for the wrong-arm `clamp`, `loop invariant` for the wrong-body
`sum_to`), and treats `Skipped`, `Incomplete`, a missing function and a failure on the wrong
obligation as failures. The general rule: assert the *outcome* you mean, never a number that
several outcomes share, because a shared number cannot tell them apart and the difference is
exactly what the test exists to detect. A second instance in the same file: the gate skipped
whichever of Coq and Lean was absent and still exited 0, so "every claim held" could be
printed having run one of the two proof suites; both are now required, and a missing prover
is exit 2 (a reported skip), never success.
**Follow-up: the same gate had three more holes, each a different flavour of "the test does
not test what it claims".** All three were reproduced before being fixed. (1) *The positive
fixture read its own claim from the thing it was checking.* The driver built its request list
from `spec::extract`, so the names came from the contracts; deleting one function's contract
deleted its name, the list shrank, the other two still passed, and the gate printed "2
function(s) verified" and exited 0 with the deleted claim never checked. A claim list derived
from the input shrinks with the input — pin the expected names independently. (2) *A `panic`
prefix accepted any panic.* The swapped-add fixture asserted `kind.starts_with("panic")`, so a
divide-by-zero planted before the addition passed a test about an overflow; the kind is now
compared for equality against the exact rustc text. A prefix is a range, and the claim was
about one point in it. (3) *Scratch fixtures shared a path.* `write_temp` named the degenerate
fixtures by function only, so two concurrent gates wrote the same file and the first to finish
removed it under the second's `rustc`; the path is now unique per call (`pid` + a process-wide
sequence), mirroring `verify::emit_mir_with`, which had already been fixed for exactly this
reason. A test that fails only when two of them run at once is a test that will fail in CI and
pass on the laptop, which is the worst order. The unifying rule: every one of these let the
test pass while checking less than it claimed, and none of them was visible from the happy
path — each needed the failure to be *induced* (delete the contract, plant the wrong panic,
run two at once) before it could be seen.
**Follow-up: pinning the name was still not enough, because a `requires`-only contract is still
a contract.** The check for (1) above tested that *a* contract existed, and existence is not
content: with every `ensures:` deleted but `requires:` left in place, the name survived, the
function shrank to panic freedom (`clamp` went from 3 obligations to 0), and it came back
`Verified` with the claimed result never checked. The fix pins the whole contract — `requires:`,
`ensures:` and `invariant:`, clause for clause and in order — and compares each kind exactly.
Pinning the *text* rather than a count matters for the same reason the fixtures exist: a count
cannot tell a whole-function contract from a weakened one. Swapping `sat_add`'s `ret == a + b`
for `ret >= a` keeps the clause count and drops the part that says what the function computes,
and loosening `sum_to`'s `n <= 8` to `n <= 2` proves a strictly smaller statement — and that
second one was still passing after the `ensures` fix, because each clause kind can be weakened
independently, so each has to be pinned independently. The general rule this pair teaches:
when a test asserts that something *exists*, ask what the weakest thing that satisfies
"exists" is, and pin that instead. "A contract is present" is satisfied by a contract that
claims nothing; "the clause count is 3" is satisfied by three clauses that claim less.
## A SAFETY comment is a claim, and it needs the same treatment as any other
The `no_std` `with_ctx` takes `&mut` to a `static mut`, and justified it with "the arena is
not `Send`/`Sync`". It was: every field of `Ctx` is a plain array or integer, so `Ctx` was
auto-`Send` and auto-`Sync`, and a `Sync` type can be shared across threads. The comment was
false, which is worse than absent — a reviewer checks the unsafe block against it.
The fix was not to reword it but to make it true: `Ctx` now carries
`PhantomData<*mut ()>`, the one pointer type with no `Send`/`Sync` impl. Verify this kind of
claim by asserting the trait bound in a scratch test and watching it fail. A comment that
names a mechanism the type system enforces will survive refactoring; one that names an
intention will not.
**Follow-up: the scratch test was not enough, so it is now a gate.** A scratch test that
was run once and deleted leaves the marker exactly as unprotected as the comment was — the
next refactor that drops `_not_shared` builds clean and the safety argument is false again,
with nothing to notice. `smt.rs` now carries a permanent `const _: fn() = || { ... }` that
fails the *build* if `Ctx` ever becomes `Send` or `Sync`. The mechanism is inference
ambiguity: `AmbiguousIfImpl<()>` is implemented for every type, and
`AmbiguousIfImpl<InvalidSend>` again for every `Send` type, so a `let _ = <Ctx as
AmbiguousIfImpl<_>>::some_item;` compiles only while `Ctx` is `!Send` (one applicable impl)
and is an `E0283` inference error the moment it is `Send` (two). `Sync` is checked the same
way. Teeth confirmed the only way that counts: removing `_not_shared` fails the build with
`multiple impls satisfying Ctx: AmbiguousIfImpl<_>`, and restoring it builds. The general
rule this is an instance of: a one-off verification of an invariant is not the same as a
gate, and only the gate survives the next change.
## The front end is total, and "it has never panicked" is not the same as "it cannot"
The MIR reader parses text the crate did not write — rustc's `-Zunpretty=mir` output, or
anything a caller hands `parse_program` directly. A panic on a shape it did not expect is a
crash in the caller's process, not a refusal, and the crate's whole posture is that an
unmodelled input is a refusal. So "the reader is total" is a property the safety story leans
on, and it was, until now, only an observation: nobody had seen it panic.
It is now a test, `mir::parse::tests::no_input_panics_the_reader`. The interesting choice is
the *input distribution*. A random token soup is cheap and reaches almost no parser state —
it fails at the first unexpected token, which is the easy path. What reaches the boundary
between states is a **valid dump with a few characters mutated**, so the corpus is two real
dumps with 1-12 single-character insertions, deletions and substitutions from a pool of
characters the reader actually reacts to. 20,000 such inputs, deterministic and seeded.
The test asserts three things, not one, because "did not panic" alone can pass for the wrong
reason:
* it does not panic (the property);
* the same text parses to the same structure twice (so the reader is a function, not a
side-effecting accumulator — this is what makes the survival evidence rather than luck);
* at least one mutation still produced a parsed function (a positive control, so the test
cannot pass by the reader refusing everything — the same trap as the export-checker test
above).
The contract reader (`spec::extract`) reads the same text and is checked for the panic
property too. It survived 300,000 token-soup inputs and 700,000 mutation inputs across the
two entry points while this was being written, so the property appears to hold rather than
merely to be untested. Nothing was found, which is the honest result: a robustness test that
finds nothing has still converted an assumption into a check.
## A number in a document is a claim that must reproduce
The README said "77 of 800 random predicates" were ill-sorted by the old exporter. The
number came from a generator that no longer exists, so no reader could check it. The fix is
`examples/z3diff.rs`, a committed harness whose output the README quotes: 800 and 3000
predicates, 0 parse errors, 0 mismatches with the current printer; 21 of 800 rejected with
the old one. Prefer a number a reader can regenerate to a number that sounds precise.
The harness also had to be checked against itself. Its first version called
`prove(p) == Unsat` a disagreement with z3's `sat`; it is not, because `prove` answers
`Unsat` when `p` is identically false, which is a tautology failure like any counterexample.
111 apparent mismatches were the harness's comparison being wrong. A differential test needs
its own oracle stated explicitly, in a comment, before its output means anything.
## Documentation drifts to describe code that no longer exists
Three README defects in one session, all the same shape: the exporter paragraph described
the *first* fix for the sort bug (the width rule) after the *second* fix replaced it; the
demo output quoted the old `Verdict::Unknown` wording; the layout tree listed `wp.rs` twice
and omitted a test file. Code changes get a test; doc changes get nothing, so docs are where
the previous revision survives.
Two habits help. Quote demo output by *running the example* rather than by remembering it.
And when a fix supersedes a documented behaviour, search the prose for the superseded rule —
`grep` for the phrase the old fix introduced, not for the new one.
## Architecture (read this before editing `smt.rs`)
`src/smt.rs` is the heart: bit-vector terms are bit-blasted into a Reduced
Ordered BDD. Invariants that are easy to break and hard to debug:
1. **Terminal nodes must have `var == u32::MAX`.** `top_var`/`cofactors` use that
to mean "no variable here". `ensure_ready()` sets this. If it is wrong you get
a non-canonical diagram and exponential blow-up, *not* an error.
2. **Every recursive cache must be cleared by `reset()`.** `reset()` clears
`and_*`, `or_*`, `xor_*`, `not_*`, `uniq_*` and `term_*` in place (it must not
use `*self = Ctx::new()`, which materialises a large stack temporary). Forgetting
a cache leaves stale node ids pointing at recycled nodes, which produces a
cycle and an infinite recursion (stack overflow).
3. **`neg()` must stay memoised.** Without the cache it walks shared subgraphs
once per path, which is exponential; a few thousand nodes then takes minutes.
4. **Comparison ops (`Eq`/`Ult`/`Ule`) store the *operand* width**, not width 1.
`blast` walks all operand bits and writes `out[0]`. Storing width 1 makes every
comparison look at bit 0 only.
5. **BDD variable order** is `level_of` = interleaved bit-planes. This keeps
adders/comparators linear. Changing it will silently make proofs slow or
return `Unknown`.
6. **The substitution epoch must be bumped, never reset.** `reset()` and
`clear_subst()` call `bump_epoch()`. Restoring an earlier epoch makes stale
`subst_memo` stamps look current, and the memo then returns node ids that
`reset` has already recycled: a cycle in the term graph and unbounded
recursion. This was a real bug, not a hypothetical.
7. **`with_fresh` must not be nested.** The inner call wipes the arena while the
outer scope still holds live `Var`s. The symptom is unbounded recursion, not a
clean panic.
8. **`blast` must stop on `overflow`, not walk to completion.** Once the node
table is full every `mk_node` returns `FALSE` without setting `overflow` again,
so nothing downstream notices. A fold-built term (`pow`, `udiv`) is a fan-out
DAG whose *unrolled* size is exponential in its step count, and `blast` visits
a shared subterm once per path to it -- so the walk runs for minutes on a query
that should have fallen back to SAT. The `overflow` check in `Ctx::blast` turns
"arena full" into "stop now"; the caller's `overflow` test then routes the query
to the SAT engine. `overflow` is checked *separately* from `stale`: marking the
query stale on overflow would refuse it (`Unknown`) instead of falling back.
9. **A fold over a constant must not build the steps that cannot run.** The
general `pow_fold` gates every step with an `ite`, which is correct and also
exponential in the unrolled DAG; a literal exponent is known up front, so the
`smt::const_of` fast path skips the dead steps entirely. The two paths are the
same recurrence and `a_constant_exponent_agrees_with_a_symbolic_one` pins that
they agree, because "same recurrence" is an argument and not a measurement.
Note the symbolic path is still intractable at the BDD wall, so a corpus entry
with a *symbolic* exponent and a wide base cannot be posed; pin constant
exponents there.
## Conventions
- `Verdict::Unknown` is a first-class, correct answer when the node budget is
exhausted. Never "fix" a proof by making the engine guess; either raise `CAP`
or state a smaller-width obligation.
- Proofs that fail are usually mis-stated, not engine bugs. Verify a surprising
result by hand (or with `exhaustive`) before touching the engine.
- The differential test (`tests/differential.rs`) is the trust anchor: symbolic
proof and brute-force execution must agree, and symbolic counterexamples must
be real.
- Keep the README honest about limits. Do not claim memory/aliasing/concurrency
coverage; the logic is bit-vectors and booleans only.
## A construct that cuts a path off is a claim, and vacuous truth is not proof
The recurring shape, now met four times, and worth stating as a rule rather than a story.
Three ways this fragment cuts a path off, each of which makes everything downstream
*vacuously* true — `false => Q` is a theorem for any `Q` — and each of which was, at some
point, reported as a proof:
| `Assume(false)` | the assumption is unsatisfiable | hand-built example |
| unreachable `pre` | `pre => wp(body, post)` is a theorem | hand-built example |
| a call to `ensures false` | the callee never returns, so the post-call state is empty | probing the `Call` rule |
All three are now recorded as *failures* (`VacuousAssume`, `VacuousPrecondition`,
`DivergentCall`), because the honest reading is "nothing was proved", not "the contract
holds". The questions to ask, generalising the three above:
* Which statements can cut a path off, and does the report say so when one does?
* When a summary (`verified`, `Total`) is computed, does it distinguish "proved" from
"proved only because the path was cut"?
* A cut makes the *continuation* vacuous. Does any summary read the continuation without
noticing the cut? `terminates` did: `loops == variants == 0` on a program
whose only divergence was a call.
## A type's invariant must hold for every constructor, including the degenerate input
`Bounded<MIN, MAX>` advertises `LOW <= get() <= HIGH` as an invariant that "cannot be broken
by construction". `new` upheld it; `clamp` returned `MIN` when `MIN > MAX`, so
`Bounded<100, 10>::clamp(50)` gave `100` — outside the type's own range, in the one type the
crate offers as the example of an invariant that holds by construction. Nothing tested the
degenerate range, because every test used a real one.
The question generalises: for a type that claims an invariant, walk every constructor and
every public entry point and ask what the degenerate input does — empty range, zero width,
empty slice, `MIN > MAX`. A refinement type is only as strong as its weakest constructor,
and the degenerate case is where the invariant is usually not even well-defined.
Also: the fix was a signature change (`clamp -> Option<Self>`), not a `debug_assert`. A
`panic` would turn a specification mistake into a runtime abort in the deployed build,
which is the opposite of what this crate is for. When a constructor cannot honour its
invariant, the partiality belongs in its type.
## Probing a rule means probing what it *models*, not what it computes
Both termination findings this session (DEFECT 44's nested-loop havoc, and the
never-returning call) came from the same move: take a rule, ask what program construct it
stands for, and check the model against the construct's real meaning.
* `variant_after` modelled an inner loop as a no-op. Its *computation* was fine; the
*model* was wrong, and a divergent program was proved `Total`.
* The `Call` rule models "assume `ensures`; continue". That is right for a returning call
and wrong for one that never returns, and the difference is invisible in the computation.
Neither is reachable by reading the code for arithmetic mistakes. They are reachable by
writing down what each rule claims about the program and asking for a counterexample to the
claim. `examples/` probes are the cheap way to do this; delete them once the finding is
pinned by a test.
## An API surface is a set of claims, and each one has to be walked
The four path-cut findings were all *semantic* — a rule that modelled a construct wrongly.
The findings on the surface are quieter and come from walking each public name and asking
two questions:
* **What does this return, and can the caller silently drop it?** `verify_exhaustive!`
returned a `bool` while every sibling `verify!` macro panicked, so a false property written
as a statement ran to completion. A returned `bool` is easy to ignore; a panic is not. When
a name promises verification, the failure must be unmissable.
* **Does the doc name *every* way the function can fail?** `Fixed::checked_div_int` said
`None` means `k == 0`, but `i32::MIN / -1` also yields `None`. The function was right; the
doc named half its failure modes, which is enough for a reader to write the wrong guard.
The same shape applies to a *type's* constructors: walk every constructor and every entry
point for the degenerate input (empty range, zero width, `MIN > MAX`).
Both are found by reading the signatures and the doc comments against the behaviour, not by
probing the decision procedure. Worth doing as its own pass once the semantic audit settles,
because the failures are silent by construction — nothing in the test suite is asking the
question.
## A harness that cannot fail is not a harness
Two findings this session, both on *tooling* rather than the engine, and both the same
shape: a check that reports a number while being structurally unable to signal failure.
* `examples/z3diff.rs` collapsed every non-answer from the oracle into one tally. When the
`z3` Python module was absent from the environment, the harness printed `parse_err=771`
and exited `0`. So "the exporter printed a file z3 rejects" — the exact bug the harness
exists to catch — and "the oracle was not installed" were the same output, and neither
failed the run. Fixing the environment restored the README's `agree=771`, but the harness
would have reported the same green-looking line had the exporter been broken. The fix
separates the outcomes (`Verdict` / `ParseFail` / `Error` / `Unavailable`), refuses to run
without the oracle (exit 2), and fails the run on any mismatch or parse error (exit 1).
* `scripts/test-count.sh` summed lines matching `test result: ok`, so a suite with a failing
test printed a *smaller* number and exited `0`. A failed run and a smaller passing run were
indistinguishable, and the number was one this project quotes. The fix makes a failure,
a compile error, or an empty run a hard error, and prints the count only when the whole run
is green.
The question to ask of any script or harness in this repo: **can it exit 0 while the thing it
checks is wrong?** If yes, it is not evidence, and quoting its output is a claim, not a
measurement. Teeth for both fixes were run: shadowing the `z3` module (`PYTHONPATH` with a
stub that raises `ImportError`) makes `z3diff` exit 2 with a message; mutating the exporter
(`bvult` -> `bvule`) makes it exit 1 with `mismatch=50`; a deliberately failing test makes
`test-count.sh` exit 1 and name the failure.
## Reading a tool's output is part of the audit
The `parse_err=771` was in the resumed task's own notes as a *passing* figure
(`agree=771`), because the run that produced it had the oracle installed. Re-running the
same command in the resumed environment produced a different, wrong-looking line that was
easy to skim past as "still fine". The lesson: re-run the commands a summary quotes, and
read the *whole* output line — a tally that shifted from `agree` to `parse_err` with the
same total is a silent failure, not a stable result.
## Gates quoted in prose stop being run; make them one command
The gates this crate depends on (clippy `-D warnings`, the test suite, the bare-metal
`no_std` build, the zero-dependency check, the z3, Kani, MIR and Verus oracles) were
separate commands,
written in the README and copied into summaries by hand. That is exactly how a gate quietly
stops being run: the summary says "all gates green" because the four that were re-run were
green, and the fifth was recalled rather than executed. `scripts/gate.sh` is now the single
entry point, it fails on the first gate that does not hold, and it treats an unavailable z3
oracle as a failure rather than a pass.
This is the same lesson as the two tooling defects above, one level up: **a gate you did
not run is not a gate you passed**, and the only way to keep that honest is to make "run
all the gates" a single command whose exit code is the claim. A summary that says "gates
green" should quote that command's output, not a memory of running the pieces.
A practical consequence in a container that is rebuilt between sessions: the `z3-solver`
Python module does not survive it, so gate 6 fails with "the `z3` Python module is not
importable" on a fresh container even though the last run was green. That is the gate
working -- it refuses to pass without its oracle -- not a regression, and the fix is
`python3 -m pip install z3-solver` before re-running. Read the failure line before
suspecting the change under test; twice now the gate "failure" was a missing module and
the code was fine.
## A skipped oracle is not a passed oracle: the Ferrocene gate
The crate's whole pitch is the safety-critical corner -- a `no_std`, no-solver prover you
can ship on an MCU. The one piece of that pitch that cannot be self-certified is the
*compiler*: SPARK's story rests on a qualified toolchain, and Rust's is Ferrocene (ISO
26262 ASIL D, IEC 61508 SIL 3, EN 50128, IEC 62304). So `scripts/gate.sh` builds both
crates with Ferrocene for `thumbv7em-none-eabihf` -- a target Ferrocene itself qualifies --
in gate 3, and CI has a matching `ferrocene` job.
Three things had to be true for that gate to be honest, and each is a rule worth keeping:
- **It must not become a dependency.** Ferrocene is invoked as a subprocess through
`RUSTC=...`, exactly like Kani, Verus, Lean and Coq, so gate 5's zero-external-dependency
check still passes when it runs. A qualified *toolchain* that leaked into `Cargo.toml`
would defeat the point of a zero-dependency crate.
- **"Absent" and "failed" must be different exit codes.** `tools/ferrocene/run.sh` exits
`2` when no toolchain is found and `1` on a real build failure; `gate.sh` skips on `2` and
fails on anything else. The mirror-image trap is the one gate 10's comment already names:
conflate them and a broken install reads as "skipped", which reads as green.
- **A skip must be *visible*.** Ferrocene is commercial -- a subscription plus a
customer-portal token whose archives "don't allow programmatic access" (User Manual
3.2.1) -- so a public CI job genuinely cannot install it. The gate prints the skip and the
CI job raises a warning annotation, so "Ferrocene did not run" is on the run summary
rather than being an absence nobody notices.
The build that carries the weight is `examples/bare_metal.rs`: `#![no_std]`, no `main`, and
it *calls the decision procedure*, so compiling it for the target is what shows the prover
itself is code the qualified compiler accepts. It is a `crate-type = ["lib"]` example with
`test = true`, because the target has no test harness but the verdicts still need checking
somewhere -- the `lib` shape lets the bare-metal build exist, and `test = true` makes
`cargo test --workspace` run the host-side verdict tests rather than building and ignoring
them, which is the "gate that silently did not run" trap again.
What the gate buys is narrow and worth stating plainly: it checks the *qualified compiler
accepts the sources unchanged*. It does not qualify `verif`. A qualified compiler is not
a qualified verifier, and this crate's decision procedure is outside Ferrocene's scope. The
README's "no qualification evidence" line is still true after this gate runs, and the gate's
comment says so at the definition site.
## An untyped generator is a second program, and it needs its own type discipline
The fuzz generator built random *word* expressions, so every comparison it formed was
8-bit against 8-bit and the query was always well-typed. Adding `truncate` to the grammar
made it able to build `(b < (trunc3(b) << 2))` -- an 8-bit value compared with a 3-bit one --
which the engine *correctly* refuses as ill-formed (`Unknown`). Two existing tests then
failed, and neither failure was an engine bug: the generator had started producing
ill-typed programs that the tests' concrete oracles (`eval`, `evaluate_pred`) cannot be
asked about, because those only have a meaning for a well-sorted term.
The lesson is that a random generator is a second implementation of the language, and it
needs the same type discipline the language does. The fix is two entry points:
`fuzz_expr` (the full grammar, including `truncate`, used only by the word fuzz, which
asserts the weaker "never a wrong `Valid`") and `fuzz_expr_w8` (width-preserving, used
wherever the test compares the term against a concrete value). The refusal path keeps its
own dedicated test. A single generator for both jobs silently moves the well-typedness
burden onto every oracle.
## Mutual recursion between two grammars must decrement on every round trip
Making `ite` reach into the predicate grammar created a cycle: `pfuzz_pred`'s base case
called `fuzz_expr_w8(r, 2)` at a *fixed* depth, while `fuzz_expr_w8(d)` reaches
`pfuzz_pred(d - 1)`. So `pfuzz_pred(1) -> fuzz_expr_w8(2) -> pfuzz_pred(1)` never
terminated and overflowed the stack (found with `RUST_MIN_STACK=33554432`: the test then
passes). The fix threads the incoming depth through the base case, so each round trip loses
one level. When two grammars call each other, the depth has to decrease along the *cycle*,
not just along each grammar's own edges -- a base case that hardcodes a depth is the trap.
## A file tree in the docs is a claim about the filesystem, and now a check
The README's "Layout" section drew `verif/` as a tree. It had drifted from the
filesystem in three ways at once: `src/lib.rs` was missing, `tests/sym.rs` was missing,
`examples/report_probe.rs` was missing, and the `examples/` and `scripts/` blocks were
*drawn* as if each were the last child of the root (two `└──` siblings), so the tree was
also malformed as a tree. Nothing in the build read the block, so it stayed wrong across
several commits that each added or renamed a file.
A prose tree is a hand-maintained mirror of `ls`, which is exactly the kind of second copy
that goes stale silently -- the same defect class as a stale test count. The first fix was
manual; it drifted again, and a later audit found the tree naming an `examples/probe.rs`
that no longer existed (so the documented `cargo run --example probe` failed), a `src/mir/`
module list missing four entries, and the whole `verif-arithmetic/` crate absent. The
lesson had been written down and the drift happened anyway, which is what "fix it by hand
and assume it stays fixed" costs.
The durable check is now mechanical: `scripts/check_doc_links.py` (gate 15) also runs
`check_tree`, which parses the tree block, tracks the directory each line sits under by its
indentation, and fails when the tree *names* an entry that is not on disk. It checks
existence only -- a file the tree omits is not an error, because the tree is a curated map,
not an exhaustive listing -- but a file the tree names and that is absent is exactly the
defect that misleads, and it is now a gate failure rather than a thing someone has to
notice. Teeth were confirmed the only way that counts: pointing a line at a missing file
fails the gate with the file named.
## `ignore` on a doc example is an example that was never compiled
Two examples in `macros.rs` were marked ```` ```ignore ````: the `contract!` example was
not even valid Rust (it used `x` with no declaration) and the `verify_exhaustive!` example
was a claim about a macro whose whole recent fix was that it must *panic* on a false
property -- the exact property its own unit test checks, written in the docs and never
run. `ignore` is not "this is illustrative"; to `rustdoc` it means "do not check me", so a
doc example marked `ignore` is a sentence that no tool will ever contradict.
Both were made real doctests (the count went 8 passed + 2 ignored -> 10 passed + 0 ignored,
and the gate's test count 247 -> 249). When you write ```` ```ignore ````, ask which
mechanism would notice if the code stopped being true. If the answer is "none", it is not a
doc example, it is prose in a code block.
A third instance is the mirror of the first two, and the label is the whole point. The
`ArgRename` doc in `src/mir/spec.rs` shows a trait/impl pair whose `///` contract lines are
*inside* the snippet, so the block is not valid Rust and cannot be a doctest no matter how
it is written. It was marked ```` ```ignore ````, which reads as "a test, deliberately
skipped" and leaves a reader to wonder what is broken. It is now ```` ```text ````, which
says what it is -- an illustration, not a compiled example -- so a reader is not invited to
look for the failure that made someone add `ignore`. Choose the label that states the
intent: `rust` to compile it, `ignore` never, `text` when it is prose in a code block.
## A bucket named "agreement" that z3 was never asked to fill
`examples/z3diff.rs` counted three things as agreement: z3 said the same thing, our engine
declined to decide (`Unknown`) on a *well-formed* export, and both sides declined on an
ill-formed one. The first is real agreement. The third has its own counter already and is
different in kind: the export carries no `(check-sat)`, so there is no query to send. The
second is the one that was mislabelled: the export was well formed and z3 was never
invoked, so the case reached one party, not two. Folding it into `agree` means the summary
reports agreement for cases the oracle never saw.
Measured before changing anything: the bucket was 0 at both 800 and 3000 predicates, so the
quoted numbers were not wrong -- they were only *accidentally* right, on the strength of the
generator happening never to emit a well-formed-but-undecided case. The defect is that
nothing distinguished "z3 agreed" from "z3 was not asked"; the correct count depended on a
property of the input distribution rather than on the code.
Split into a separate `undecided` counter, reported in the summary line, with the reasoning
in the comment. The README's measured line now carries it too. This is the same class as the
rest of the crate's findings: a summary that can outrun the run it summarizes. When you
write `agree += 1`, name the two things that agreed; if one of them was never asked, it is
not agreement.
## A documented direction the generator never generated
The README said `examples/z3diff.rs` covers "`truncate` in both directions". The generator's
`truncate` arm was `truncate(x, 1 + r.below(w))`, and `below(w)` is in `0..w-1`, so the result
width was always `1..=w` -- always *narrowing*. `truncate` accepts a width above the source
(it is a zero-extend), and the exporter's `zero_extend` branch is the one that used to be a bug
(`((_ extract 15 0) x0_8)` on an 8-bit vector, ill-sorted and rejected by z3). So the harness
advertised the direction that exercises the fragile printer path and never generated it. The
printer branch was covered by a unit test asserting the text, but never by the oracle that exists
to catch exactly this: a claim about what was tested that the test did not test.
Fix: a widening arm that pairs `truncate(x, wide)` with a narrowing `truncate(.., w)`. The pair
matters -- a bare widening leaves the result wider than `w`, and every other operation in the
generator is width-preserving, so the predicates would compare mismatched widths, the term would be
refused, and the case would never reach z3. Pairing keeps the width at `w` while putting both
printer branches in one tree.
Verified by instrumentation, not by inference: a temporary counter for `zero_extend` in the
exported text reported 35 of 800 files, all accepted by z3 (0 parse errors). Without that check
"agree went up" would only have meant the generator produced *something* different; it would not
have shown the intended branch was reached. The counter was removed before committing; the
generator change is the only diff.
Numbers moved (both re-measured): 800 predicates refused 29 -> 25, agree 771 -> 775; 3000 refused
108 -> 97, agree 2892 -> 2903; mismatch 0 throughout. The README's measured line was updated.
Lesson: when a comment or README enumerates what a generator covers, check the generator against
the enumeration one item at a time. "Covers X in both directions" is a claim about a distribution,
and a distribution can be narrower than its description without any single run looking wrong.
## An assertion that compared a term with itself
`truncate` is the crate's only width-changing operation, so the tests around it matter. Three of
them contained the same defect: an `assert!(prove(eq(t, <the call that defines t>)))`.
- `tests/differential.rs`, `widening_through_truncate_agrees_with_the_original_value`:
`t = truncate(x, dst)` then `prove(eq(t, truncate(x, dst)))`. Both sides are the same term
id, so the equality is a tautology and the assert can never fail -- under a comment that said
it checked the widened value "matches the original".
- `tests/quant.rs`, `truncate_keeps_the_low_bits_and_zero_fills`: `low = truncate(x, 2)` then
`prove(eq(low, truncate(x, 2)))`, and `wide = truncate(x, 8)` then
`prove(eq(wide, truncate(x, 8)))`. Same shape, twice.
Because the terms are hash-consed, the two sides are literally the same node, so the obligation is
`eq(v, v)`, which the engine returns `Valid` for without ever touching the bit-blaster. The tests
were green and proved nothing about truncation. Note the third case in that same test,
`truncation_through_an_assignment_survives_substitution`, is *not* this defect: it compares
`after = substitute_word(narrowed, [(x, y)])` against `truncate(y, 2)`, and `after` and that call
are different nodes, so the check is real. The shape "compare `t` with a call that mentions `x`" is
fine; the shape "compare `t` with the call `t` is bound to" is vacuous.
Fix: pin the input with `prove_implies(eq_const(x, 0b1011), eq_const(t, <expected>))`, which makes
the claim falsifiable. For the widening round trip, `prove(eq(truncate(t, src), x))` -- narrow the
widened value back to `src` and require the original, which is well sorted (both sides `src` bits)
and is the non-trivial form of "widening preserves the value".
Verified by mutation, not by reading: flipping the bit-blaster's widening zero-fill from `FALSE`
to `TRUE` (`src/smt.rs`, `Op::Trunc`) makes both fixed tests fail, reporting counterexample
`x = 11`. Before the fix the same mutation left them green -- which is the whole point: an
assertion that cannot fail also cannot detect the bug it was written for. Source restored after.
Lesson: a test of an operation must compare the result against something *other than the
expression that produced it*. When the operands are hash-consed, `eq(t, f(x))` where `t == f(x)` is
not a weak test, it is no test. Pin an input, or compare against an independently computed value.
## A sentinel that was the first real variable
`wp.rs` had a comment on `writes` that read: "Slot 0 is never a real variable: `var()` starts
indices at 0, but a sentinel is all the initialisation needs". The buffer it describes is
`[Var::SENTINEL; MAX_WRITES]`, and `Var::SENTINEL` was `Var(Term(0))`. The term arena allocated ids
from 0, so `Term(0)` was the *first real term*, and `Var::SENTINEL == var(8)` was true. The
comment said the opposite of what the code did.
It was latent: every reader of those buffers is `[..n]`-counted, and no code compares a handle
against `SENTINEL` by value, so nothing was wrong at runtime. But the frame rule's whole design
leans on the sentinel being distinguishable from a live handle -- `MAX_WRITES` fixed buffers,
`out[..n]`-counted reads, no allocator -- and the one line a reviewer would check to confirm that
assumption was false. An invariant that is false and untested is a landmine for the next change
that does compare, or for anyone who trusts the comment.
Found by reading `SENTINEL`'s definition against `mk_term`, then confirmed by probe: a temporary
example printed `var(8) == SENTINEL ? true`. The fix is to make the claim true rather than delete
it: reserve term id 0 (`smt::TERM_SENTINEL`), start `n_terms` at 1 in both `Ctx::new` and `reset`,
and point `SENTINEL` at it. Cost is one term out of `CAP`. A regression test,
`the_sentinel_is_not_a_real_variable`, asserts `var(8) != Var::SENTINEL` -- it failed before the
fix and passes after, so it is not a comment about the fix.
Note the same `Term(0)` also appears as the *overflow* return in `mk_term`, `var_term`, and
`subst`. Those are deliberate: they poison the handle and set `overflow`/`stale`, and `prove`
checks the flag before answering, so a bogus `Term(0)` never reaches a verdict -- `smoke.rs`
documents measuring exactly that. Reserving id 0 leaves those paths alone; they return the reserved
id, which is still not a valid node, and the flag is still what refuses the query.
Lesson: when a comment asserts an invariant ("slot 0 is never a real variable"), it is a claim
like any other and deserves a test. If the invariant is load-bearing, make it true and pin it;
deleting the comment would have hidden a real coupling between `wp`'s buffers and the arena's id
allocation.
## A differential oracle that could not see a wrong operator
`examples/z3diff.rs` generates random predicates, exports them, and asks z3. It was passing at
`mismatch=0`, so it looked like the exporter was checked. It was not, in the way that mattered.
The harness compares only sat/unsat. A random predicate over free variables is essentially never a
tautology, so a *semantic* printing bug that keeps the formula well sorted is invisible: I changed
the exporter's `Op::Sub` to print `bvadd` instead of `bvsub`, and the random sweep still reported
`mismatch=0`. A probe showed `bvsub` in 39 of the 800 exports, every one decided -- so the operator
was exercised on every run and never *checked*. An instrument that is present in the sample but not
load-bearing in the assertion is the same defect class as the `Var::SENTINEL` comment: it looks
like coverage and is not.
Why it is invisible: the export asserts `(not p)`, so z3 answers `unsat` exactly when the printed
`p` is a tautology. For a random `p` z3 answers `sat` both before and after any semantic change that
preserves satisfiability, and swapping `bvsub` for `bvadd` does. The only predicate shape that
distinguishes the two is a *tautology*, and the generator makes almost none.
The fix is the dual of the random sweep: a corpus of tautologies by construction, one or more per
operator, each chosen so that a plausible mutation of the operator it names breaks the identity.
`sub.self` (`x - x == 0`) is sensitive to `bvsub`→`bvadd`; `mul.one` (`x * 1 == x`) to
`bvmul`→`bvadd` (note `add.comm` would not be -- commutativity survives the swap, so the identity
has to be picked against the mutation, not just to mention the operator); `shl.nibble`
(`0x0f << 4 == 0xf0`) to a shift-direction swap; `trunc.widen` to `zero_extend`→`sign_extend`.
42 identities across 8- and 12-bit widths, printed with the same `Query` path the random sweep uses.
Teeth, measured by mutating the printer and requiring the harness to fail: `bvsub`→`bvadd`,
`bvmul`→`bvadd`, `bvand`→`bvor`, `bvshl`→`bvlshr`, `bvxor`→`bvor`, and widening
`zero_extend`→`sign_extend` each now exit 1 with the failing identity named. Before the corpus, the
first of those passed silently.
Lesson: a differential test's *generator* determines what it can catch, and "the operator appears
in the output" is not "the operator was checked". When a decision is sat/unsat, the discriminating
inputs are the degenerate ones -- tautologies and contradictions -- not the generic ones. If you
want to know whether a check has teeth, mutate the thing it is supposed to check and confirm it
fails; if it does not, the sample was decorative.
## Completeness guards that nothing exercised
`wp::writes` derives a statement's write set into a fixed `Frame` of `MAX_WRITES = 16`
variables and sets `complete = false` when a body writes more. Five places consult that flag,
and the crate's own comments assert each is load-bearing -- the one in `variant_after` even
documents the divergence it prevents. Mutation testing said otherwise: blanking two of the five
guards to `if false` left the whole suite green.
1. `Stmt::frame` returns `false` for an incomplete *derived* frame. Its doc says
`under_declaring_the_frame_is_rejected` covers this. It does not: that test builds a
2-write body, so the frame is complete and the guard never runs; the test exercises the
*declared-covers-derived* check, a different guard two lines down. A body writing 17
variables is where the completeness guard is the only thing standing -- without it,
"declared covers derived" is checked against a 16-entry prefix and a caller who declares
those 16 passes while the callee overwrites the 17th.
2. `collect_written`'s `Call` arm propagates the callee's incompleteness upward. A caller that
merely *calls* an over-cap callee directly writes one variable, so its own frame looks
complete without the propagation, and the enclosing check accepts a prefix again -- the same
hole one level up.
Both are now pinned by tests that fail when the guard is removed: build a 17-write body, check
the derived frame is `len() == 16 && !complete()`, and assert `frame` refuses / the caller's
frame is incomplete. The verdict the *program* gets is refuted either way, so the test has to
assert on the guard's own observable -- `complete()`, or the refusal -- not on a proof failing.
That is the same lesson as the z3 identity corpus: a guard is only tested if the test observes
the thing the guard controls, and "this program does not verify" can be true for several
reasons at once. When a comment claims a named test covers a branch, read the test and check it
reaches the branch; here the comment was aspirational.
Method note: I found these by mutating each `if !…complete()` to `if false` and running the
suite, not by reading. Reading confirms a guard is *present*; only mutation shows it is
*load-bearing*. Both surviving mutants sat behind comments claiming coverage, which is exactly
where reading is least reliable.
## The assertion arm was the last silent `push`
The obligation cap was fixed once before (commit c786848): claim-carrying obligations went
through `push_checked` and raised `ObligationOverflow`, but the `Stmt::Assert` arm was left on
the old silent `push`, deliberately, with the argument that a dropped assertion is harmless
because the backward walk still conjoins it into the weakest precondition. That argument is
correct about `verify`'s soundness and wrong about `wp::obligations`: the latter documents its
third return value as `true` only when every side obligation is in the buffer, and it returned
`true` for 17..=20 assertions when the buffer holds 16. Two answers to one question, which is
the exact defect the earlier fix existed to remove.
The gap survived the earlier fix because every existing overflow test used *loops*, not
assertions -- the pressure family pads with assertions but asserts only on `verify`, never on
`obligations`' completeness flag, so the flag's assertion case was never observed. Found by
probe, not by reading: `obligations()` with N assertions for N in {15,16,17,20}.
Fix: `Stmt::Assert` now goes through `push_checked`; `push` is deleted (no callers left).
`verify` on a truncated assertion set now reports `ObligationOverflow`, and the completeness
flag goes false. Pinned by `assertions_beyond_the_cap_are_reported_not_hidden` in `tests/wp.rs`,
which fails when the arm is reverted to a silent drop. Lesson, same as the frame guards: when a
comment justifies leaving one site different from its siblings, test that site's own observable
-- here the completeness flag -- not the end-to-end verdict, which stays correct for the wrong
reason.
## The Kani oracle: a second verifier, and the bugs building it exposed
`examples/kanidiff.rs` checks the engine against Kani (model checking over CBMC), the same
way `z3diff` checks the exporter against z3: Kani is a subprocess oracle, never a
dependency. The predicate and the Rust text it compiles are two interpretations of one
shared IR tree, not independently generated -- otherwise "the same property" is a hope.
Building it found three bugs, all in the harness, each of which would have made a green run
mean less than it looked:
1. **Arena sharing.** One `with_fresh` for all cases exhausted the node budget after ~a
dozen queries, so later cases came back `Unknown` and the harness reported the engine as
weak (`not_proved=27`). The engine was fine; 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 / sign bit
(SMT-LIB rule); Rust `<<`/`>>` are an arithmetic-overflow error there. Emitting `x << k`
would have compared a different function. The generated crate now spells the engine's
rule out in `shl_eng`/`lshr_eng`/`ashr_eng`.
3. **The classification matrix.** The first version counted "engine refuted + Kani proved"
as agreement. A mutated `Sub` blast then produced `mismatch=0` on the random sweep and
was caught only by the curated corpus. Now only `Unknown` is "no claim"; any other
engine verdict is a definite claim Kani must not contradict. Found by mutating the
engine, not by reading.
Two corpus entries were also wrong (a bare `Not(And(..))` is not De Morgan; `guard <=>
ite(guard,a,b)==a` fails at `a==b`), which the engine correctly refuted. Lesson that keeps
recurring: when the harness disagrees, suspect the harness first, but *check* -- here the
engine was right both times.
Mutation evidence the harness has teeth: `Sub`'s `borrow = TRUE` -> `FALSE` makes the engine
refuse `sub_self`/`add_sub_cancel`/`sub_zero`; `Eq`'s per-bit `and` -> `or` makes it prove
false formulas, caught by the random sweep. Negative control `a - b == b - a` fails the run
if either side proves it.
## Verus as a third oracle
`examples/verusdiff.rs` checks the engine against Verus the way `kanidiff` checks it against
Kani. Both harnesses now take their cases and IR from `examples/support/mod.rs`, so they
check the *same* formulas; giving each its own corpus would make the two agreement claims
disjoint. Three backends (the engine, Kani, Verus) on different foundations means a blasting
bug has to survive agreement with both verifiers.
Verus facts that cost time to find, all in the generated-file path:
* `#[verifier(bit_vector)]` is required or Verus uses non-linear arithmetic and fails on
bitwise facts. With it, `+ - *` on `u8` wrap.
* `wrapping_mul(x, 1u8)` is *rejected* in `bit_vector` mode: "expected finite-width integer
in `bit_vector` proof, got Int(Nat)". Route arithmetic through spec helpers
(`(x * y) as u8`) instead.
* A constant expression that overflows, e.g. `255u8 * 255u8`, is a rustc const-eval *error*
that aborts the whole run -- `#![allow(arithmetic_overflow)]` does not help. The spec-helper
form avoids it because operands are already `int`.
* `verification results:: N verified, M errors` counts non-case items (`main`, helpers), so
`verified + errors == cases.len()` is false. Account on error *locations* mapping to cases,
and fail on any error that maps to none.
* Install: download the `x86-linux` release zip (self-contained, own `z3`), extract, chmod +x
`verus`/`rust_verify`/`z3`, then `rustup install <the pinned toolchain verus --version
prints>`. Point `VERUS_BIN` at the driver.
## GitHub Actions
`.github/workflows/ci.yml` has three jobs. The first runs `scripts/gate.sh` verbatim, so CI and
a local run mean the same thing. The other two install Kani (cached) and Verus (latest
release) and run `kanidiff` and `verusdiff` as hard gates. `gate.sh`'s Kani and Verus steps
skip when those tools are absent -- reported, not silent -- because both are large downloads;
CI is where they become mandatory. Gate count is now 8 (the MIR frontend is the eighth).
Three things about this file are easy to get wrong:
1. **Pin every `uses:` to a full commit SHA, with the tag in a trailing comment.** A tag is
movable, so `@v4` lets a retagged or compromised release change what CI runs without any
commit in this repository changing. The comment matters too: a bare SHA does not tell a
reviewer which version it is, and a pin they cannot identify is a pin they cannot check.
Resolve a tag to its commit with
`curl -s https://api.github.com/repos/OWNER/REPO/git/ref/tags/TAG` -- for these actions the
tag is lightweight, so `object.sha` is the commit directly. Verify it before trusting it.
2. **A workflow added by a pull request does not run on that pull request.** GitHub only
starts `pull_request` runs when the workflow file already exists on the *base* branch, so a
PR that introduces `.github/workflows/ci.yml` shows "no checks reported" until it is merged.
That is expected, not a broken pipeline: it is why the local `gate.sh` run is the evidence
for such a PR, and why the workflow says so rather than looking untested.
3. **`gh` needs `read:org` for some queries, a classic token may not have it.** `gh pr edit`
fails with "The 'login' field requires one of the following scopes: ['read:org']" on a token
scoped to `repo` only. The REST API does not need that scope, so update the PR body with
`curl -X PATCH .../pulls/N -d @payload.json` instead of reaching for a broader token.
## A fallback engine is only worth its weight if the wall actually moves
`smt.rs` is a BDD engine; when its arena fills, `query_valid`/`query_model` hand the *same*
term graph to `sat.rs`, a CDCL SAT solver, via `bitblast.rs`.
Two engines, one term graph, **two blasters** -- and the distinction matters, because the
first write-up of this said "one netlist" and that was wrong. `smt::blast` writes BDD node
ids; `bitblast::blast` writes `Lit`s. They cannot be one function: the term arena and the
gate arena are both `&mut`, so a shared blaster would have to split an arena or hide a
pointer behind a trait. What the two share is the *term graph*, so each operation is named
once -- operands and width are decided when the node is built -- but each blaster writes its
own adder, subtractor, multiplier and comparator circuit. So "the arithmetic is defined once"
is itself too strong: the *operations* are defined once, the *circuits* are not, and the two
circuits could diverge. That is a real risk, so it is treated as a property to check rather
than hope away. "One bit-slicer" and "one netlist" are both the stronger, false version of
this; the code and `src/sat.rs`'s header say the true one.
### The check has to be aimed at the blaster it is about
The first fix for the wording above kept the sentence "if the two adders ever disagree, one
of those fails", naming `tests/differential.rs` and the z3 oracle. That was measured and it
is **false**. Both run at widths where the BDD engine finishes (the z3 corpus sweeps 8 and 12
bits; the differential corpus pins every op at 1--4 bits *precisely so the BDD can finish*),
so every query they make is decided by `smt::blast`. `bitblast::blast` only runs once the BDD
arena has already filled, which is 64 bits for an adder and 8 for a multiplier -- nothing in
the suite reaches it.
The measurement: delete the carry-generate term (`a & b`) from `bitblast.rs`'s adder so it
computes `xor`, and drop a carry term from its multiplier. Then run the lot. `cargo test`
passes, `tests/differential.rs` passes, the z3 oracle reports `mismatch=0`, and the probe
still prints `add_comm 64b valid`. A query that *does* force the SAT path and is sensitive to
the bug (`add(x, y) == xor(x, y)`, or `(x+y)-x == y` at 64 bits) comes back `Valid` and
`Counterexample` -- that is, an unsound proof and a spurious witness, from a suite that is
green.
The fix is the `tests` module in `bitblast.rs`: drive `blast` directly, force both inputs,
and ask the solver whether the circuit can differ from Rust's wrapping arithmetic, exhaustive
over every input pair at 1--4 bits. It catches both mutants, and its own teeth are checked
(the helper is made to answer "no divergence" unconditionally and the teeth test fails). The
lesson is not "add a differential test"; it is that a differential test *between two engines*
proves nothing about the engine that never runs. The oracle has to reach the code under test,
and the way to know it does is to break that code and watch the test fail.
The point of recording this here is the measurement discipline, because the first version
of this feature *claimed* to have broken the wall and had not.
1. **An unsound solver reports a "better" result than the truth.** The first SAT engine
answered `Valid` on queries the BDD engine could not decide. That looked like the wall
breaking. It was a bug: the watch-list arena was one shared array with per-literal
*counts* but no per-literal *offsets*, so two literals' watch lists overlapped, unit
propagation was missed, and the solver called unsatisfiable formulas satisfiable. The
"success" and the unsoundness were the same event. Differential tests against
brute-force enumeration (`tests/sat_engine.rs`) are what separated them.
2. **The wall is where `Unknown` appears, and it is measured, not remembered.** After the
solver was made sound the wall came back. The honest result, from the scaling probe that
was run for it (a throwaway example, since deleted): adder equivalence now settles at 64
bits (`Unknown` with the fallback disabled, `Valid` with it); wide *multiplier*
equivalence is out of reach at both engines' budgets.
3. **Tombstoning is not deletion.** `reduce_db` marked dead learnt clauses with `c_len = 0`
but left their ids in the occurrence lists, whose spans were sized for the pre-deletion
clause set. `propagate` then walked a stale span and could report a conflict that did not
exist. If a clause is removed from a list, remove it from every list that indexes it, or
rebuild them.
4. **Learnt clauses that are never freed are a memory leak with a proof-theoretic cost.**
The literal arena filled with worthless learnt clauses, so a query the solver could still
decide came back `Unknown` for lack of space. `reduce_db` now keeps a set (originals,
current reasons, the more active half of the rest) and `compact` re-lays the arena,
remapping `reason` and rebuilding the occurrence lists. `SOLVER_BYTES` is
`size_of::<Solver>()` for this reason -- the hand-summed version went stale the moment
the new fields landed.
5. **An incomplete engine needs a budget, not patience.** `MAX_CONFLICTS` bounds the search;
past it the solver returns `Sat::Unknown`. A verifier that hangs is worse than one that
declines. The budget is also the honest knob: 20 000 conflicts cannot decide 64-bit
adder equivalence, 50 000 can, and `MAX_CONFLICTS` records which side of that line the
crate commits to.
The pattern is the one the rest of this file keeps finding: a claim about the engine is
worth only the command that measures it, and a *better-looking* claim is the first thing to
suspect.
## A verdict is a fact about a query; whether it is *good* depends on the query
The frontend turns each source obligation into an SMT query, and the two commonest
obligations ask *opposite* questions:
* A postcondition asks "does `path => post` hold for every input". `Valid` is the proof;
`Unsat` means the postcondition is false on **every** input, which is the strongest
possible failure.
* A panic (and an `unreachable`) asks "can this happen". `Unsat` is the proof;
`Counterexample` is the failing input; `Valid` means it happens on **every** input,
which is the worst case and has no witness to show.
The first version tested `verdict.is_proved()` — that is, `Valid` — for every obligation
regardless of kind. That reads the panic polarity backwards: a panic that fires on every
input is reported as *ruled out*. It also silently accepted the `Unsat` postcondition,
because `Unsat` is not `Valid` but the outcome classifier only looked for a
`Counterexample` and let everything else fall through to `Verified`. Both are the same
mistake — treating "the engine decided" as "the engine approved" — and both make the
crate's core claim (a `Verified` line means the obligations hold) false.
The fix is [`Obligation::is_discharged`], which is per-kind on purpose, and a
[`MirReport::first_failure`] that carries a witness *or* the "holds for every input" case
so an obligation with no counterexample is still a failure. The regression targets are
`bool_ret_false` (postcondition `Unsat`), `vacuous_precondition` (unsatisfiable `requires`),
and `div_by_always_zero` (panic query `Valid`). Each was checked by reverting the fix and
watching it fail — a test for a polarity bug that passes on the buggy polarity is not a
test.
### The same mistake in a boolean, and in a failure string
Two follow-on findings were the same error in different clothes, and both are worth naming
because they are easy to reintroduce.
1. **A satisfiability query has three outcomes, and a `bool` cannot hold three.**
`find_model` returns a model, `Unsat`, or `Unknown`. The first
`Contract::precondition_is_satisfiable` was `find_model(pre) != Verdict::Unsat`, which
folds `Unknown` in with "found a model" and answers `true`. An ill-formed precondition
(an equality between an 8-bit and a 16-bit variable, say) then reads as *satisfiable*,
so a caller checking `verif` and the boolean together claims a non-vacuous proof
with no evidence the precondition is reachable. The fix adds
`Contract::precondition_satisfiability`, returning the verdict, and makes the boolean
`true` only for `Valid` or a `Counterexample` -- the two outcomes that *are* a satisfying
input. `false` now means "not established", covering both `Unsat` and `Unknown`, and the
docs say so. The rule from above applies: three outcomes need a three-valued type, not a
boolean with a silent fold.
2. **Two failures with no witness are not the same failure.** `first_failure` returned a
kind and an optional witness, and the caller rendered "no witness" as the string "holds
for every input". That string is right for a `Valid` panic query (the panic fires on all
inputs) and exactly *backwards* for an `Unsat` postcondition (the postcondition holds
for **no** input). The detail is now built per kind and per verdict by
`Obligation::failure_detail`, and `first_failure` returns the obligation itself so the
kind, the witness, and the diagnosis come from one place instead of being re-derived.
The regression test asserts the `Unsat` postcondition's detail says "no input" and does
*not* contain "holds for every input".
The through-line with the polarity bug: a value that can mean two opposite things, rendered
or tested without its direction, will eventually be read the wrong way.
## A guard can be load-bearing and still invisible to a verdict
The second oracle of the same shape as "a harness covers only what it reaches", and the
sharper one, because the code *is* reached. `Solver::reduce_db` runs at every 2000
conflicts, and a 64-bit adder equivalence crosses that interval 15 times, so nothing here is
dead code. Yet deleting the loop that marks every clause currently justifying a trail
literal as `keep` left the entire suite green -- `cargo test`, `tests/sat_engine.rs`,
`tests/differential.rs`, the z3 corpus, and the Kani oracle.
The reason a verdict-level test cannot see it is the point. Dropping a reason does not
usually change the answer: `compact` remaps `reason[v]` to `NO_CLAUSE`, the literal becomes
indistinguishable from a decision, and `analyze` stops early and learns a *weaker* clause.
The solver still finds the right verdict, just more slowly. Instrumenting the guard showed
it rescuing 650 clause-reasons across those 15 calls, and with the guard removed 426 trail
assignments lost their justification while the verdict stayed `Unsat`. Correct verdict,
corrupt proof state.
So the oracle has to assert the invariant, not the outcome: each decision level holds
exactly one reason-free literal, at the front. That check fails on the mutant at level 4,
which is the only evidence the teeth are real. And it drives `reduce_db` on a hand-built
trail rather than searching for a hard instance, because a test that needs a 2000-conflict
search is a test that runs in minutes and whose teeth depend on the search happening to
reach the guard. Build the state the guard protects, then remove the guard and watch the
assertion fire.
Two mechanical notes worth keeping. A `Solver` is 2.2 MB, so a fixture that owns one
overflows the 2 MB test-thread stack -- use the shared static, and take the lock's
`MutexGuard`. And with every clause at the same activity, `reduce_db`'s stable sort keeps
the low ids, so the guard looks unnecessary by accident; set the activities explicitly so
the removable clauses really are the ones that get removed.
## A test that skips itself still reports `ok`
The sharpest instance of the "a harness covers only what it reaches" rule, because nothing
here was dead or wrong. `Obligation::is_discharged` in `src/mir/exec.rs` decides whether an
obligation is discharged, and the answer is *per kind*: an `Unsat` verdict **discharges** a
panic query ("it cannot happen") and **refutes** a postcondition ("it holds for no input").
Collapsing that match into `self.verdict.is_proved()` is the natural single-polarity reading,
and it is a soundness hole in both directions at once.
That mutant survives `cargo test` completely. The reason is not that the logic is unreached;
it is that the only tests for it live in `tests/mir.rs`, which needs `VERIF_RUSTC`
pointing at a nightly, and **skips itself when it is absent** with a bare
`let Some(report) = verify_all() else { return };`. A skipped test reports `ok`. So the suite
count is *identical* whether the MIR frontend ran or not: 325 with the nightly, 325 without.
CI never set `VERIF_RUSTC`, so in the one place that gates a merge, the polarity had no
teeth at all. A green suite said nothing about it.
Two fixes, and both are needed. First, an in-module oracle in `src/mir/exec.rs` that runs
*ungated*: it enumerates the whole truth table over the four kinds and four verdicts, so it
does not need a compiler or a model -- `Valid`, `Unsat` and `Unknown` are unit variants, and
a real `Cex` comes from `find_model` on a satisfiable-but-not-valid query. Verified by
mutation: collapsing the match, treating a `Valid` panic as ruled out, and discharging every
vacuity check each fail the oracle on a stable-only machine. Second, CI now installs the
nightly and points `VERIF_RUSTC` at it, so the end-to-end tests actually run. That
variable must be a *path*, not a toolchain name: the frontend runs it with `Command::new`.
The lesson to carry: a test that can silently become a no-op is not a test. When a harness
skips on a missing tool, the count that "proves" the suite is green has to be checked
against the count with the tool present. If the two are equal, the tool is not being used.
## Pin a remap by what it points at, not by where it points
A related trap in the same style, from the `reduce_db` oracle. `compact` renumbers clauses,
so it remaps `reason[v]` from the old id to the new one. The first version of the oracle
asserted only `reason[v] < n_clauses` -- "the reason names a live clause". That check passes
for *any* surviving clause, including one that has nothing to do with the literal it is
supposed to justify, so a remap that pointed every reason at clause 0 would have slipped
through. The oracle now compares the clause's literal *set* against the expected one, and a
mutant that remaps reasons to an unrelated live clause fails it.
The same fixture had a second hole worth naming. It left each reason clause's other literal
unassigned, so `clause_justifies` was never really exercised: the clause could not be shown
to be unit. The fixture now decides the other literal, so the reason clause is genuinely unit
on the propagated literal -- `(x2 | ¬x6)` with `x6` true -- which is what makes it a real
propagation justification rather than a clause that merely mentions the variable.
## An arena budget is not a time budget
The MIR frontend hung. `count_evens` -- `while i < n { if i % 2 == 0 { c += 1; } i += 1; }`
with `requires: n <= 8` -- ran for minutes and printed nothing, so the tool reported *no
verdict at all*, which is worse than any verdict. The first three explanations were wrong,
and each one was falsified by measurement rather than by reading:
1. **"The open-addressing tables filled up."** Plausible: `mk_node`, `mk_term`, and the
three `apply2` caches probe with `i = (i + 1) & mask` and no termination test, and the
capacity check sits *inside* the `k == u64::MAX` branch -- so a table with no empty slot
left can never reach it. That is a real latent bug and it is fixed, but it was not this
hang: instrumentation showed `overflow == false` and `nodes == 53` at 24 million
`apply2` calls.
2. **"The BDD blew up."** Also plausible, and also wrong: 24M calls producing 53 nodes is
the signature of recomputation, not of a growing diagram.
3. **"It is in `apply2`."** Wrong: instrumenting `apply2`, `blast_bool`, and `model` showed
`model()` completing in 7 iterations, then silence.
What found it was printing the frontend's own state. The worklist was visiting `bb1`..`bb7`
in a cycle forever, with `visits` growing by one per round. So it was not an infinite loop
and not a deadlock: it was a **path explosion**, slow enough to look like a hang. Every
branch inside an unwound loop multiplies the path count, and each path's BDD is larger than
the last, so the cost is super-linear in the path count. Measured: 200 paths took 16s, 2000
paths were still running after 90s.
The fix is `DEFAULT_PATH_BUDGET` in `src/mir/exec.rs`. `DEFAULT_UNWIND` bounds each loop;
nothing bounded the *number of paths*, and that is the missing guard. It is set to 64
because the measurement says a larger value buys no coverage -- the corpus scoreboard is
4 of 14 at 64 paths and 4 of 14 with no bound at all -- only latency.
Two lessons. First, **a bound on one resource is not a bound on the others**: this engine
had an arena budget and a loop budget, and still had no termination guarantee. When a tool
promises "never loop forever", that promise needs a guard on *time* or *steps*, not just on
memory. Second, **instrument before you theorise**. Three plausible root causes were wrong
here; the one that was right came from printing the loop's own counters, not from reasoning
about which data structure "must" be the problem.
The regression test is `a_branching_loop_reports_a_path_budget_rather_than_running_forever`
in `src/mir/exec.rs`. It embeds the real `rustc -O` MIR for `count_evens` so it runs on
stable, and it is *verified to hang without the fix* -- which is the only thing that makes
it a regression test rather than a test that happens to pass. Two details matter: it must go
through `verify_function` with a postcondition, because the postcondition is what makes each
path cost more than the last; and it runs on a 64 MB thread, because the harness's default
stack is smaller than the main thread's and the workload overflows it.
## A step budget is not a depth budget
The engine promised "refuse, never crash" and then aborted the process. `i64 / 3` -- a
division by a constant that is not a power of two -- overflowed the stack on the default
2 MiB test-thread stack (SIGABRT), in release as well as debug. Every budget the engine had
counted *steps*: `MAX_BLAST_STEPS`, `MAX_APPLY_STEPS`, the arena capacity, the path budget.
A stack overflow is not made of steps. The walk that overflows is ~262 levels deep and
costs only a few hundred steps, so it passed every budget and died on the recursion.
The root cause took four wrong guesses to find, and the way each was falsified is the
useful part:
1. **"It is the BDD, so `bitblast::blast`."** Depth there is 267 -- deepest candidate, and
wrong. Measured release frames put 267 of them well under the stack that failed, so
depth alone there was not the explanation.
2. **"It is `subst`."** Plausible, since substitution rebuilds terms. Instrumented: depth 0.
It never ran on this query.
3. **"It is the frame size."** Also wrong, and this one nearly ended the search. `objdump`
on the *rlib* showed `bitblast::blast` with `sub 0x1000,%rsp`, which looks fatal at depth
267. It is not the function's frame: the symbol's prologue is a stack-probe for a large
`[Lit; 64]` local, and the real frame is 840 bytes. Reading a disassembly is not the same
as knowing which code runs.
4. **"It is the step budget, so raise it."** No budget was involved at all.
What settled it was measuring depth per recursion site, not guessing from shape. `smt::blast`
is depth 262 with a 2.3 KiB release frame, so 262 x 2.3 KiB ~ 600 KiB -- the number that
matches a 2 MiB stack failing and 3 MiB succeeding. The deepest legitimate walk in the whole
corpus is 138, so the fix is a fourth bound, `MAX_WALK_DEPTH = 192`, charged by every
recursive walker: `smt::blast`, `smt::apply2`, `bitblast::blast`, and `eval_term`. A trip
sets the existing `overflow` flag, so the query routes to the SAT fallback and from there to
`Unknown` -- the same sound path the step budgets use.
Two lessons. First, **a budget on one resource is not a budget on the others** -- this is the
second time (the first was the path budget above) and the resource is now *stack depth*.
When a tool promises never to crash, each unbounded recursion needs its own guard; a step
counter will not see it, because the failing shape is deep and narrow. Second, **measure the
resource the failure is made of**. Every step-based measurement here was green while the
process aborted; only a depth measurement found it.
The regression test is `a_deep_term_walk_is_refused_not_allowed_to_overflow_the_stack` in
`tests/mir.rs`. It runs on the test thread's own stack, so removing the guard aborts the test
binary rather than failing an assertion -- verified by disabling the guard and watching it
SIGABRT. The split of each walker into a thin guarded wrapper and a `*_bounded` body is what
keeps the counter correct on the early returns inside the body.
## Cutting a loop at its invariant: the header must havoc what the loop writes
Loop invariants landed in the MIR frontend, and the first version was **unsound**. It
verified a postcondition that is false. This is worth recording in full, because the
mistake is the natural one and the symptom is a *success*.
The shape was the obvious one for a CFG. On every edge into the loop header, assert the
invariant; on an edge from a back edge, assert it and stop rather than re-enter. That
closes the induction with no unwinding: the assertion at the back edge is the step, the
assertion on the entry edge is the base case. Measured, it worked -- `count_evens` went
from *path budget exhausted* in 2.8 s to *verified* in 0.06 s, and the realistic corpus
went from 4 of 14 decided to 7 of 14.
It was wrong. `sum_to` with the deliberately weakened invariant `i <= n` -- which is true
on entry and preserved, but says nothing relating the accumulator to the counter -- came
back **verified**, while the loop plainly returns a value that violates `ret <= 8` for
`n = 8`. The tool had proved a false statement.
The cause is what the exit edge carries. `advance` asserted the invariant and then
continued into the header with the path the path *arrived* with. For the entry edge that
is the pre-loop state, so the guard is evaluated there: `0 < n` gives `n >= 1`, and
`!(0 < n)` gives `n == 0` with the counter still `0`. The exit edge is therefore only
ever walked from the state of the *first* iteration. Everything the loop does on its
second pass and later -- including writing the return value -- was never seen. A proof
that only inspects the first iteration is not a proof of the loop.
The fix is the standard rule, and it is a rule precisely because this is the trap. At the
header, **havoc** the locals the loop can write -- replace each with a fresh variable --
and only then assume the invariant. What the exit edge carries is then `I && !guard` over
*arbitrary* values satisfying `I`, which is what the invariant is a claim about. The
`havoc` set is an over-approximation (reachability from the header over the whole
function), which is the safe direction: havocing a local the loop never writes loses
information and can turn a proof into an open obligation, never the reverse. `_0`, the
return place, must be in the set; leaving it out is the specific way the hole reappeared,
since `s` in `sum_to` *is* `_0`.
Two things made this findable rather than a silent false positive:
* **A mutation test, not a reading.** The weakened invariant was checked by hand against
the corpus before being trusted. Reading the `advance` code did not reveal the bug; the
two-word diff that changed `s == i` to `s == 0`-equivalent did.
* **A regression test that fails without the fix.** `an_invariant_too_weak_for_the_
postcondition_is_not_a_proof` asserts only "not verified" -- a counterexample or an open
obligation both satisfy it -- and it was confirmed to *pass* on the unsound version and
fail once havoc was disabled with `if true { continue; }`. A test written after the fix
that only pins the happy path would have missed this entirely.
A smaller trap sits next to it. Classifying the edges needs care: the block *before* the
header also jumps into it, and that edge is the entry, not the latch. The test that gets
this right is `to <= from` -- strictly earlier targets are the entry, equal-or-later ones
are the latch, and a header that loops to itself is a latch. A "cleaner" two-pass version
that collected every block edging into the header from later in the layout classified the
entry edge as a latch, cut the loop before it was entered, and reported a proof of a false
postcondition again. The mutation tests caught it in seconds; a green suite after the
change would not have, which is why they assert the *negative*.
The general lesson: for a loop, an invariant is not a predicate to *check at the edges*,
it is a predicate to *assume over the whole state space it describes*. Asserting it at the
back edge is necessary and not sufficient; the header has to forget what it cannot know.
## A clause that is not a clause must be refused, not dropped
The contract reader takes four clause keywords: `requires:`, `ensures:`, `invariant:`,
`decreases:`. Anything else on a `///` line used to be ignored, and that is a **false
proof**, not a lost one. Measured at the time of the fix:
/// requires: x == 0
/// ensuers: ret == 99 <- one transposition from `ensures`
pub fn f(x: u32) -> u32 { 5 }
came back `Verified` with **zero obligations**. The typo meant the function had no
postcondition at all, so the body was checked against `true`, and the report was green
for a claim nobody had read. The `ensuers` case is the sharp one because it is the
*false* direction: had the claim been true, the green report would have been earned by
luck, and had it been false -- as here -- the tool would have certified it. `variant:`
was the same shape from the other side: a reader who writes a loop termination measure
reasonably expects it honoured, and the tool ignored it, so a total-correctness claim
rested on nothing.
The fix records any clause-shaped line the frontend does not take and **skips** the
function, naming the line and the keyword it looks like. The hard part is not the
refusal, it is *deciding what counts as clause-shaped*: a naive "any `/// word:`" rule
would refuse ordinary documentation, and the corpus is full of it (`/// direction: ...`,
`/// type: ...`, `/// width: ...`). The rule is a bounded edit distance of two on the
word before the first colon, so `ensuers` (one transposition) and `requiers` (one
transposition) are caught while `direction` (three edits from `decreases`) is left as
prose. Measured over `examples/`, `tests/` and `src/`: the only near misses anywhere are
inside the tests for this rule itself, so the corpus does not trip it.
`variant:` gets a distinct message rather than a "did you mean" suggestion, because it is
not a typo -- it is a feature this frontend does not have yet, and correcting the reader
into an invariant would hide that. That message is the honest statement of the gap, and
it is the reason this section exists in a document about *soundness* rather than one
about ergonomics.
The regression test `a_clause_shaped_doc_comment_that_is_not_a_clause_is_refused` was run
against the pre-fix code first and fails there with
`verified (0 obligation(s), 0 panic(s) ruled out)`.
## A loop invariant alone proves only partial correctness; the measure is separate
The invariant path cut a loop at its head and proved `I` on entry and across an
iteration. That is *partial* correctness: it says the loop is safe if it stops,
which a loop that never stops satisfies vacuously. Measured before the fix,
`while i < 5 { i += 0 }` -- a loop that never leaves -- came back `Verified`. The
tool certified a function that does not return.
The missing piece was the measure, and the shape of the fix is where the care is.
`variant: <expr>` is a clause of its own, not a second meaning for `invariant:`.
The measure is evaluated **twice in different states**:
* At the head, over the *havoced* state -- the same fresh locals the invariant was
assumed on. This is the value `V` the body's iteration starts from.
* At the back edge, over the state the body's own symbolic execution produced.
This is `V'`, derived rather than restated.
The obligation is then `path => V' < V`. Reading `V` from the *arriving* state
instead of the havoced one would compare an iteration against the first pass's
value, which proves the decrease for one iteration rather than for the loop --
the same mistake the invariant's havoc step exists to prevent, in the measure.
No lower-bound obligation is emitted, and this is deliberate. On a fixed bit width
a strictly decreasing sequence cannot be infinite, so strictness alone is the
well-founded basis. A `V >= 0` check would be *wrong* here: the measure is a
machine word, so a measure that "goes negative" is just a smaller word, which is
exactly the descent that proves termination. This is the opposite of the recursion
case, where the measure is over the mathematical integers and non-negativity is
load-bearing -- so the two `decreases:` checks are not the same check, even though
both are called "decrease".
The width wall shows up honestly. A `u32` measure bit-blasts to a query larger
than the engine's diagram budget, so it comes back `Incomplete` rather than
`Verified`; `u8`/`u16` decide. That is a refusal, not a failure, and it is the same
budget every other wide query meets.
`variant:` is only taken with an `invariant:`, because the invariant is what
locates the loop head the measure is evaluated at. An orphan measure is refused
rather than ignored -- ignoring it would report partial correctness as if it were
total.
## A call to `core` made the whole path unknown, and modelling it needed a tag that is a term
The MIR frontend's biggest coverage gap was not a parser shape or a width wall: it was that
any call into `core` was unmodelled, so `a.checked_add(b)` — the idiomatic way to write
arithmetic that must not panic — made every obligation downstream of it `incomplete`. The
corpus scoreboard said so in one line, `is_nonzero_after incomplete call to unmodelled
function ...checked_add`, and that line is why the scoreboard exists.
The fix is `src/mir/intrinsics.rs`: `checked_*`, `saturating_*` and `wrapping_*` are computed
from their operands rather than refused. Three things about it are worth carrying forward.
**The refusals are the design, not a limitation.** Only `checked_div`/`checked_rem` may model
division. `saturating_div` and `wrapping_div` *panic* on a zero divisor, and modelling a
panicking operation as total would hide a panic — the one thing this frontend must never do.
The shifts are refused because the families genuinely disagree: `wrapping_shl` reduces the
amount modulo the width, the engine's variable shift saturates to zero, and `checked_shl`
returns `None` past the width. Three behaviours under one name is not something to guess at,
and a wrong guess is not a weaker proof, it is a false one. So refusal happens at two layers
and a test pins both: a name whose operator is unknown does not `classify` at all, while a
name that classifies (`saturating_div`) is refused by `is_modelled`/`eval`. The first draft of
that test asserted `saturating_div` does not classify, and the failure was the useful kind — it
showed the two layers were real and the test was naming the wrong one.
**A `checked_*` result is an `Option`, and its tag is a *term*.** This is the part that made
the plumbing non-trivial. `checked_add` on a `u8` is `Option<u8>`: rustc lowers the consuming
`match` to a `switchInt` on `discriminant(_2)`, and reads the payload through a
`Proj::Downcast(Some)` place. A tag modelled as a constant would take one arm always. It has
to be `ite(fails, 0, 1)`, where `fails` is the same overflow predicate the `assert` reads, so
the `switchInt` goes the right way on each path. The payload is recorded *unconditionally*
under the `Some` projection, and that is sound precisely because rustc emits the downcast read
only inside the arm where the tag is `1` — the path condition is the gate, so no extra gate is
needed. The width is the *operand* width, not the destination's: sizing the payload from the
`Option<u8>` local would ask the engine for a 64-bit overflow test.
Three smaller traps fell out of the same work, each a place where a plausible reading is wrong:
* `Rvalue::Discriminant` was sizing the tag from the dump's `isize` rather than from the
payload width, and returning `Unknown` when no tag was recorded instead of `Val::Unknown`
for an unknown *tag*. A modelled `Option` local has no `locals` entry — its value *is* its
tag — so `Env::get` needed a fallback to the `discriminants` map, or `discriminant(_2)` and
`move _2` both came back unknown.
* The downcast payload read `((_2 as Some).0)` is *one* step, not two: the projection loop
consumed the `Downcast` and then processed the trailing `Field(0)`, which looked the payload
up in the tuple map and overwrote a good value with `Unknown`. The loop now consumes both.
* `parse_rvalue` matched the ` as ` cast form before trying a `copy`/`move` of a place, so a
downcast place did not parse. Checking the place form first fixes it — the same shape of
ordering bug as the earlier `const ... as ...` case, in the opposite direction.
**A `match` arm guard reads its payload through a borrow of a downcast place — a third
instance of the same ordering bug.** `Msg::Data(n) if n < 10` lowers to
`_4 = &((_1 as Data).0: u8); _6 = copy (*_4); _5 = Lt(move _6, const 10_u8)`. The rvalue
contains the word ` as ` *inside its parentheses*, and `parse_rvalue` checked for a cast
before a reference, so it split the borrow at that ` as `, read it as a cast of the
unparseable string `&((_1`, and produced a cast of `Unknown`. `_4` therefore got no
address, `copy (*_4)` read `Unknown`, and the `switchInt` on the guard's `bool` was
reported "unmodelled switch discriminant" — the *guard's* payload read was the thing that
failed, not the switch, which is what made the message point at the wrong construct. The
reference arm now runs before the cast arm; a real cast cannot be mis-taken for a
reference, because `&…` is not a place, so the reorder is safe in the direction that
matters. Pinned by `mir::parse::tests::a_borrow_of_an_enum_payload_is_a_ref_not_a_cast`
(unit, no toolchain needed) and `tests/mir.rs::a_match_guard_reads_its_payload_through_a_borrow`
(the corpus pair `guarded_match_reads_its_payload` / `guarded_match_tripwire`). Coverage:
`everyday.rs` 9/21 → **10/21** (`next_mode`, C5's own evidence function, now decides),
`realistic.rs` 398/737 → **399/739**; `scripts/test-count.sh` 874 → **876** passed, 0 failed.
The recurring shape, worth stating once: **`parse_rvalue`'s arms are ordered, and an
arm's pattern can appear inside another arm's string.** ` as ` lives inside a downcast
*place* (both the `copy ((_2 as Some).0)` form and the `&((_1 as Data).0: u8)` form), and
`const ` lives inside a cast constant. Each ordering fix so far has been found by a shape
whose rvalue contained another arm's keyword; when a new rvalue form is added, check it
against the arms above it, not only against the arms below.
**The oracle is Rust itself, enumerated.** The model claims to implement `core`'s definition,
so the unit tests in `src/mir/intrinsics.rs` compare against the real `u8::checked_add` and
its family over *all* of `u8` and all of `i8` — 65536 pairs per case, cheap because the term is
built once and walked per pair rather than reset per pair. That is what pins the signed rules,
which no unsigned test can see: `-1 + 1` does not overflow, but the unsigned carry test fires
on it, so an unsigned-only model would report a panic that is not there. `i8::MIN / -1` and the
width limits are checked the same way. The terms are read back with `smt::evaluate`, which is
the concrete semantics of the symbolic language, so the test compares *values* and not just
`Some`/`None`.
The scoreboard moved from 4 of 14 decided to 10 of 14, and the remaining four each name
themselves in the `detail` column — an unreadable `requires` (`c.lo <= c.hi`, `xs.len() > 0`)
and a tuple-returning `ensures` (`ret.0 <= a`). Those are the next gaps, and they are parser
gaps rather than engine ones, which the scoreboard says without being asked.
## A product is widened to `2w == 64`, and `pow`'s fold keeps its own tighter bound
The `Mul` arm of `intrinsics::failure` widens the operands to `2w` and multiplies there, because
overflow needs the *exact* product and `2w` bits hold it. The cap was `2w == 16` first, so a
`u16` `saturating_mul`/`checked_mul` was refused outright — every contract over one reported
"past what the model covers" and none could be settled. Raising `MUL_MAX_WIDTH` to `16` made the
`2w == 32` cap, and that width decided. The bound is `32` now (`2w == 64`), which decides the
whole `u32` product surface; `64` is where it stops, because `2w == 128` cannot be held at all.
**The two halves of a product cost very different things, and the bound is set where the cheap
half reaches.** The *value* families (`wrapping_*`) build no predicate — a `wrapping_mul` is a
plain `w`-bit multiply, which the BDD holds at `u32` in milliseconds — so raising the bound from
16 to 32 admitted `u32::wrapping_mul` and `hash_step` (the flagship `u32` example,
`h.wrapping_mul(31).wrapping_add(b as u32)`) went from `incomplete` to `verified` in 0.00s. The
*widened* `2w == 64` product is built only where a family needs the failure predicate: a constant
multiplier folds the obligation without blasting the multiply (`x.saturating_mul(3)` verifies in
0.01s), and a fully symbolic one answers `Unknown` after ~5s rather than hanging. The bound is
`32` and not `64` because a `u64` product's predicate is refused (`wide == w`, since `2w == 128`
clamps to 64) and a `u64` `wrapping_mul` is past the BDD wall regardless — measured `incomplete`
in 0.01s.
**The division form was tried here first and is worse.** The plain-`*` path uses
`y != 0 && x > MAX / y` (see the section above), and it is the *right* predicate there because
the corpus's guard is written in that shape and the boolean fold cancels the two against each
other. The intrinsics idioms are not that shape: `saturating_mul` asks about the *value* of a
`core` call and carries no hand-written division guard to cancel against, so the divider is
built and blasted instead of folding away. Measured: a `u16` idiom the widened test settles
`Valid` in ~180ms came back `Unknown` after ~3.2s under the division form, and the `pow` fold —
which composes up to 64 `mul_failure` queries — hung past the 900s test timeout, because 64
nested dividers are far past what the blaster holds. So the two paths share the overflow *rule*
but not its cheapest spelling, and the shared helper stays the widened one.
**`pow` gets `POW_MAX_WIDTH = 8`, below the product bound, on purpose.** Its fold is a `mul` and
a squaring per exponent bit, so it costs a large multiple of one product rather than the product
itself. Raising its bound to 16 bought nothing and cost seconds: a `u16` `saturating_pow` with a
symbolic exponent was still `Unknown`, but only after ~12s of diagram work, where the same
refusal at 8 bits is immediate. An answer that cannot be reached is not worth paying for. The
test `pow_is_modelled_only_where_a_product_is` pins the separation so a later change cannot
collapse the two constants quietly.
The teeth are unit tests and corpus pairs. `a_u16_product_is_modelled_and_exact` and
`a_u32_product_is_modelled_and_exact` sweep the boundary neighbourhood of a product against
`core`'s own `checked_mul`/`saturating_mul`, so the widened test is pinned as *exact* at each
width and not merely reachable; the `u32` sweep includes `65536 * 65536` (exactly `2^32`, one
past `MAX`) so an off-by-one fencepost fails. In the corpus, `u16_product_guarded` and
`u32_wrapping_product`/`u32_saturating_product` must verify while their `*_tripwire` twins — the
same body under a guard that does not rule out the claim — must be refuted; a bound raised
without the refutation would be a model that proves the wrong thing, which is worse than one
that declines.
**What is still open, and it is the *speed* half rather than the coverage half.** A `u32`
multiply-overflow guard at full width — the saturation idiom
`if b != 0 && a > u32::MAX / b { u32::MAX } else { a * b }`, and a plain `a * b` under a guard —
reports `incomplete` after ~4s. The plain-`*` path's exact-division form at `u32` is past the
diagram budget, so the query is *bounded* rather than decided; a per-function time budget would
report it promptly instead of waiting the ~4s out. `clamp_std` (`x.max(lo).min(hi)`) verifies in
9.8s, likewise the latency half of C7 rather than a coverage gap.
## An inlined call must restore the caller's loop cut, or the caller unwinds a loop it had cut
Cutting a loop at its invariant is a property of a *function*: the `Cut` names the header and
back edges of one loop in one function's CFG. Entering an inlined callee therefore clears
`cut`, correctly — the caller's invariant says nothing about the callee's locals. The return
path then copied the callee's `cut` into the resumed caller, which is the bug: a callee that
returns from a function with no loop leaves `cut` as `None`, so the caller resumed *inside its
own loop* with no cut. The next edge into the header was unwound rather than checked against
the invariant, and once the loop passed `DEFAULT_UNWIND` the function was reported
`Incomplete` — a valid proof discarded, not a false one, but a defect all the same.
The frame already had the fix's shape: `saved_env` is set aside at call entry and restored on
return, for the same reason. `saved_cut` follows it exactly. Restoring the cut is the whole
change; the callee's own cut is dropped because the callee has returned.
What made this reachable *now* is the exact-name lookup. Before it, a user function named
`wrapping_add` was answered by `intrinsics` as `a + b`, a leaf that never entered a frame, so
the caller's cut was never disturbed. Sending such a function through the inliner — the right
fix for the false proof it caused — exposed the return path's missing restore. A change that
fixes one defect can activate another that was latent behind it.
The teeth are two tests, and the second matters as much as the first:
`an_invariant_survives_an_inlined_call_on_the_loop_edge` requires the loop to verify across
the call (it fails on the pre-fix code), and `an_inlined_call_does_not_rescue_a_weak_invariant`
requires the same loop with `ensures: ret == 0` to still be refuted. Restoring the cut must
restore the proof the invariant actually carries, not resurrect one that was never there.
## The `rustc_public` oracle: what the text parser is checked against, and why it is a separate crate
The MIR frontend reads the **textual** `--emit=mir` dump. That is the crate's stated gap 2:
a rustc release that reprints the dump can break the parser, and the parser is the only thing
that reads the dump, so nothing else notices. `tools/mir-oracle` closes part of that loop by asking
`rustc_public` — the compiler's own public API — for the same programs' **typed** MIR and
comparing a per-function *shape*: block count plus the panic guards `rustc` inserted, in block
order. Structural, not textual, because the two dumps are not byte-identical (the typed one
omits `copy` qualifiers, prints `let _4` with different spacing, and nests `scope` blocks),
so a text diff fails on cosmetics and proves nothing.
**The half it does not close is a place re-spelled with the same control flow**, and that is
measured rather than assumed: see "The shape is two facts, and its blindness is a documented
boundary" near the end of this file for the five-row table and the test that pins it. In
short — a change to block count, a guard's presence, order or polarity is caught; a change to
how a place, local, projection or type is *spelled* is not, and `Len((*_1))` ->
`PtrMetadata(copy _1)` in 1.99 slipped past this gate; it was found by running the suite
under a second toolchain, which gate 14 now does on every run.
Traps that cost time, in the order they cost it:
* **`rustc_private` needs four `extern crate`s, not one.** `extern crate rustc_public;` alone
fails to link; `rustc_driver`, `rustc_interface` and `rustc_middle` must be declared too,
because the `run!` macro expands to code naming all three. The error is `cannot find module
or crate rustc_middle in this scope` pointing at the macro invocation, which reads as a
missing dependency rather than a missing `extern crate`.
* **`run!` wants `&args`, and argv[0] is the program name.** `run!(&args, …)`, not
`run!(args, …)`. Passing a `Vec<String>` is a type error against `&[String]`; passing a
slice with the file first (no program name) makes rustc read the file as the program name.
* **`--out-dir` is mandatory.** `rustc_public` runs a real rustc; without `--out-dir` it drops
`lib<stem>.rlib` next to the source file, so every oracle run litters the repository. The
oracle points it at a temp directory. This is easy to miss because the run still *succeeds*.
* **The binary needs the sysroot on its runtime path.** A `rustc_private` binary links
`librustc_driver-*.so` but cargo does not add the sysroot to its rpath, so it builds and then
dies with `cannot open shared object file`. `build.rs` bakes `-Wl,-rpath,$(rustc --print
sysroot)/lib` in, using the `RUSTC` cargo is building with. `run.sh` sets both `RUSTC` (what
cargo builds *with*) and `VERIF_RUSTC` (what the frontend *runs*) to the same nightly.
* **`rustc-dev` alone is not enough: `llvm-tools-preview` is required too, and the error
misreports the cause.** `rustc` links `libLLVM`, and cargo puts
`<sysroot>/lib/rustlib/<target>/lib` on the build script's `LD_LIBRARY_PATH`. A bare
toolchain keeps `libLLVM` in `<sysroot>/lib`; it reaches `rustlib/<target>/lib` only via
`llvm-tools-preview`. That directory *takes precedence* over the `$ORIGIN/../lib` RUNPATH in
the `rustc` binary, so with only `rustc-dev` the `build.rs` cannot even start
`rustc --print sysroot` — and the visible symptom is the *linker* failing with `unable to
find library -lLLVM-...`, two steps later. A `-L <sysroot>/lib` flag cannot fix it (the
failure is `rustc` failing to start, not `ld`), so `build.rs` now panics naming the
component instead of returning quietly. Install
`rustup component add rustc-dev llvm-tools-preview --toolchain nightly`.
* **`cargo clippy` ignores `RUSTC` when choosing its driver.** `RUSTC=<nightly> cargo clippy`
still runs the *default* toolchain's `clippy-driver`, so it checks a `rustc_private` crate
with the stable driver and reports `can't find crate for rustc_driver` — which reads like a
missing component and is not. Use `cargo +nightly clippy`, and install `clippy` onto the
nightly (a `--profile minimal` toolchain does not ship it). `cargo build` and `cargo test`
*do* honor `RUSTC`, so only the lint step needs this.
* **`cargo install` is not idempotent, which makes a warm cache a trap.** The Kani job cached
`~/.cargo/bin/cargo-kani` and then ran `cargo install` unconditionally; `cargo install`
refuses to overwrite (`binary cargo-kani already exists in destination`), so the job could
only pass on a cold cache. Guard the install on the binary being absent, and version the
cache key so a cache left in the broken state is dropped.
* **The crate is `exclude`d from the workspace, not a member.** A member would make
`cargo build --workspace` require a nightly, which breaks the stable zero-dependency build
that is the whole point of the crate. `exclude = ["tools/mir-oracle"]` plus `cargo build`
from inside `tools/mir-oracle`. `cargo metadata` lists exactly `verif` and
`verif-arithmetic`, so gate 4 still sees a two-line tree.
* **`rustc_public::mir::body` is private but glob-re-exported.** Import from
`rustc_public::mir::{…}`, not `rustc_public::mir::body::{…}`. `Local` is `pub type Local =
usize`, not a tuple struct, so `Local(0)` does not compile — use `Place::from(0usize)`.
The oracle has teeth and it was checked: flipping one arm of `PanicKind::from_text_message`
(Add -> Mul) makes the run exit 1 with 7 actuator functions and 4 realistic functions named
and their two panic lists printed. A tool that can only say "agree" is not evidence.
### Two things the first version of the shape could not see
Both were gaps in the *checker*, which is the worst place for one, and both are the same
mistake: reducing a function to a summary that is not injective, then comparing summaries.
* **The shape recorded a guard's kind but not its polarity.** `assert(!move _3, "…overflow")`
and `assert(move _3, "…overflow")` shaped identically, though they describe opposite
programs. A printer change that flipped a leading `!` therefore passed. The parser had
always carried `negated`; the shape — the thing compared — did not. `FnShape.panics` is now
`Vec<AssertShape>` with `AssertShape { kind, polarity }`. On the typed side the source is the
`Assert` terminator's `expected` flag, which is the value for which control *continues*, so
it is the **inverse** of the text side's `!` — `polarity_of` is a one-line function and
getting it backwards makes 21 actuator and 6 realistic functions disagree, which is how it
was checked. A useful side effect: the real asymmetry shows up, that `Bounds` is `True` while
every arithmetic guard is `Negated`.
* **The gate's cost was the test profile, not the algorithm.** `prove::ENUM_BUDGET`
is documented as "about two seconds of tight loop", but that figure is a *release*
calibration. Cargo's default test profile is unoptimised, and the enumerations are
tight integer loops, so the same `2^32` walk cost ~21 s in the gate against ~2.6 s
optimised — and three sibling tests did it. The fix is `[profile.test] opt-level = 2`
in the workspace root, which took `scripts/test-count.sh` from 1m50s to 15.5 s
without touching a single proof. Two things to keep in mind: `[profile.test]` only
takes effect in the workspace root manifest (a profile in a member is ignored, and
cargo does not warn), and it applies to the *library* the integration tests link,
which is where the hot loop actually lives. Do not buy the speed with
`debug-assertions = false` — this is an arithmetic crate, and the `checked_*` tests
are where a silent wrap would hide; `the_test_profile_is_optimised_without_losing_its_checks`
fails if someone tries.
* **A budget in cases is not a budget in seconds.** `ENUM_BUDGET` bounds the *count*
of cases, not the wall-clock cost. An obligation that does more work per case, or a
build without optimisation, is slower for the same count. Calibrating a case budget
in release and enforcing it in debug is exactly how a "2 second" bound became a
20 second gate.
* **A coverage check that compared first counterexamples.** `fixed_add_no_overflow`
skips the points its precondition rejects, which is only sound if the rectangle it
walks is *exactly* the precondition's set. The first version of the check ran both
walks on one goal and compared their verdicts — but a walk stops at its **first**
counterexample, and two different rectangles can share one. At width 8, bounds 200
and 199 both fail first at `(1, 198)`, so the check passed while the 199 rectangle
omitted every pair containing 200 that the precondition admits. Coverage is a
property of the *domains*, so it has to be checked on the domains, with no goal in
sight. The replacement compares the two bounds directly and is O(1): for a square
precondition (`a <= k && b <= k`) the two sets are equal exactly when the bounds
are equal, since neither can be a proper subset of the other. The general lesson is
the same one the shape gaps taught: a check whose verdict depends on the thing it
is checking is not a check. A brute-force sweep of the domain was written first,
agreed with the O(1) version everywhere, and was thrown away — it cost 11 s and
added no evidence.
* **Bare names were treated as unique keys.** `impl A { fn check }` and `impl B { fn check }`
in one file both reduce to `check`, and both sides used a single-slot map, so the first was
silently replaced by the second. Dropping it from the text parser produced *zero*
differences. Both sides now keep a `Vec<FnShape>` per name and compare it sorted, as a
multiset: the enumeration order differs between the two sources and is not worth asserting,
but the set of shapes under a name is exactly what a lost method changes.
Exit codes are four-way on purpose: `0` agree, `1` a shape disagreed, `2` the oracle could
not run (no nightly, or a missing `rustc-dev` / `llvm-tools-preview` component), `3` the
oracle could not be *built* though the components are present. Gate 9 skips only on `2` and
fails on everything else, so "the toolchain is missing" is never reported as a parser failure
nor as a pass — and, the mirror-image bug, a compile error in the oracle is never reported as
a missing toolchain and quietly skipped. `run.sh` decides between 2 and 3 by probing for
`librustc_driver-*.so` and `libLLVM-*` in `$sysroot/lib/rustlib/$host/lib` directly, rather
than by asking `rustup component list` (which answers for a toolchain *named* `nightly`, and
`VERIF_RUSTC` may point elsewhere).
## A projection is a binding decision, not a grammar rule
Contracts could name arguments and `ret`, and nothing else. `requires: b.lo <= b.hi` on a
`&Bounds` argument was `skipped` with "unknown name", because the expression language had no
dot operator and no notion of a field. Two of the fourteen functions in
`examples/mir_targets/realistic.rs` were lost to that — `pick_from` and `clamp_by_value` — and
a tuple return (`split`, `ensures: ret.0 <= a`) was lost to the same gap one level down.
The first idea was to add a projection operator to the parser. That is the wrong shape: it
puts the same decision (which field is this, how wide is it) at every operator that can
appear next to a place. Instead each readable field is *rewritten* to a mangled identifier
(`c.lo` → `c__f0`) before parsing, and bound to a variable of the field's own width and
signedness. The grammar stays "arithmetic over names"; the projection is one binding decision,
made in one place.
What makes this work, and the parts that would have been silent bugs:
* **The layout is not in the MIR.** The dump prints `_1: &Bounds` and never the fields, so
both the field *index* (declaration order) and the *width* have to come from the source.
That is consistent with how contracts are already read (doc comments, since attributes need
a proc-macro and a proc-macro is a dependency), and it means a contract and the layout it
names come from the same bytes. A struct the layout reader does not find yields no bindings,
and a contract naming one of its fields is refused — not checked against a guessed width.
* **Two fields must not alias, and a hash is how they would.** The first version derived the
field's variable slot from an FNV-1a hash of `arg.field`. A collision there is not a missing
proof but a *wrong* one: `c.lo <= c.hi` becomes `x <= x` and verifies vacuously. A sequential
counter cannot collide, so there is nothing left to argue about. The tripwire is
`field_alias_tripwire` in `realistic.rs` — same shape as `clamp_bounds` but claiming
`ret >= c.hi`, which is false whenever `v < c.lo <= c.hi`. It must FAIL, and its
counterexample names two distinct variable indices; `tests/mir.rs` requires both the failure
and the two distinct names.
* **The contract's field and the body's field must be the same variable.** The contract binds
`c.lo` to a variable; the body reads `((*_1).0)`. If those were two fresh variables the proof
would be vacuous in the direction that matters. `FieldEnv.seeds` carries `(local, field,
var)` to the executor, which seeds its `fields` map with exactly those variables, so the two
are made to agree by construction rather than by convention.
* **A deref is transparent only as a whole place.** `*_1` for a `&T` argument names the same
value `_1` does, because `Ty::Ref` is modelled as its referent. The gate has to be `i == 0`
as well as "the local is a reference": `*(_1.0)`, a field that is itself a reference, is a
*different* pointee and `deref_ok` says nothing about it. Reading the field as though it were
the argument's referent is a wrong value, not a missing one.
* **A projection that cannot be resolved is refused, never dropped.** `c.lo` where `lo` is not
a field is an error naming the field (not the parser's "expected a comparison operator",
which is what the `.` produced before the diagnostic was added), and `ret.0` on a
non-aggregate return is refused. A dropped conjunct would verify the function against a
weaker contract than the source states — the same class of bug as a skipped function
reporting `ok`.
* **`ret` for an aggregate is `None`, not a fabricated word.** A tuple return has no single
word, so `post` receives `Option<Var>` and the parser refuses a bare `ret` while still
resolving `ret.0`. Passing a fresh unconstrained word would have let `ensures: ret == k`
pass on a tuple return by luck.
Coverage on `realistic.rs` went from 10 of 14 decided to 13 of 14 when field and tuple support
landed. `clamp_bounds` was added to `actuator.rs`, the regression corpus where *every* function
must be decided, so a regression in field support is a failing test rather than a quietly lower
number. The `rustc_public` oracle (gate 9) agrees on 31 actuator and 15 realistic functions with
the new shapes.
## A slice length is an input, and its elements are indexed by value
The last `realistic.rs` skip was `first_of(xs: &[u8]) -> u8 { xs[0] }` with
`requires: xs.len() > 0` / `ensures: ret == xs[0]`. It is the same class of gap as a field —
a contract naming something the expression language had no way to name — but the *shape* of
the fix is different, and the difference is the interesting part.
A slice has no length in its type. `&[u8]` is the whole type; the length is whatever the caller
passed, so `xs.len()` cannot be a constant the frontend computes. It is a *symbolic input*, on
the same footing as an argument. The body agrees: rustc lowers `xs[0]` to `_3 =
PtrMetadata(copy _1)` (the length), `assert(Lt(_2, _3))` (the bounds check), then `(*_1)[_2]`.
The contract's `xs.len()` and the body's `PtrMetadata(_1)` have to be one variable or the
bounds check cannot be discharged from the precondition, so the length is bound once in
`FieldEnv` and handed to the executor as a `len_seed` — the slice analogue of the field seeds.
The parts that would have been silent bugs:
* **Elements are indexed by value, not one variable per slice.** The tempting model gives a
slice a single "element" variable. Then `xs[0] == xs[1]`, and `slice_alias_tripwire`
(`ensures: ret == xs[1]` on a body returning `xs[0]`) would verify. Elements are keyed by
`(local, index)` instead, so two indices are two inputs. The tripwire must FAIL, and its
counterexample assigns the two elements different values; `tests/mir.rs` requires both.
* **A symbolic subscript is refused on a slice, and modelled on an array.** `xs[i]` with `i` a
parameter has no single element to name on a slice, and reading "some element" would make
`xs[i]` a different value per read — a wrong proof, not a missing one. An *array* is
different: its length is in its type, so `a[i]` is the exact ite chain over `0..N` and is
modelled (see the symbolic-index section below). The distinction is the domain being finite,
not the subscript being symbolic.
* **The element width is the referent's, not the length's.** `&[u8]` has `u8` elements and a
`usize` length. Taking the element width from the length variable sizes every read at 64 bits
and mis-models the bounds check.
* **The element is created on first read, which `get` cannot do.** `Env::get` takes `&self`, and
the first read of `xs[0]` has no variable yet. A `read_slice_index(&mut self, …)` on the
operand path creates it; the second read of the same index finds the same variable. Binding
the *contract's* element references up front (`bind_slice_refs`) keeps the postcondition
closure — which cannot hold a `&mut` — evaluating against the same bindings.
Coverage on `realistic.rs` is now complete: every function is decided, and the three
tripwires (`field_`, `slice_`, `array_alias_tripwire`) are decided *and must fail*, which is
what makes them evidence rather than decoration. `first_of` was added to `tests/mir.rs` as a
must-verify case, so a regression in slice support fails a test.
### An array's length is a constant, not an input
`[u8; 4]` and `&[u8]` look alike at the use site and are not alike at all. A slice's length is
whatever the caller passed, so it is a fresh input. An array's length is *in the type*: `4` is
the only length the value can have. Binding it to a fresh variable would be the unsound
direction — the contract would be proved for some length the caller chose, when there was
nothing to choose, and a contract proved at length 4 would appear to hold at any length. So
`bind_array_len` binds `a.len()` to the constant word `4`, and the body's bounds check
(`assert(Lt(_2, const 4_usize))`) is discharged from the index being a literal below 4.
The rest of the machinery is shared with slices, deliberately: `FieldEnv::indexed` maps a name
to `(local, elem_w, Option<fixed_len>)`, where the length is `Some(n)` for an array and `None`
for a slice. One map, one element model, one scanner (`bind_index_refs`) — an array is not a
second feature bolted on, it is the same feature with the length known. `bind_indexed_elem`
refuses an index `>= n` for an array rather than binding a fresh variable, because the element
does not exist and a fresh variable there would make a meaningless contract look meaningful.
### A literal's width comes from the operand, not from the scope
This is the bug array support exposed, and it is worth recording because the symptom pointed
nowhere near the cause. `arr_pre(a: [u8; 4]) -> u8` with `ensures: ret <= 255` came back
`incomplete`. The body was trivially fine. The cause: a contract literal was built at the width
of the *widest name in scope*, and an array or slice length is a `usize`. So `255` was a 64-bit
constant compared against an 8-bit `ret`. `smt::cmp` refuses mismatched widths by setting the
engine's `ill_formed` flag, and **an ill-formed term makes every obligation in the run
`Unknown`** — so the function was undecided for a reason that had nothing to do with it. The
same bug had been silently present for slices: `slice_le` was `incomplete` at HEAD.
The fix is a per-use width decision, in three parts, and each part is a separate way to be
wrong:
* **Build the literal wide enough to hold its own value.** Sizing it at the scope's width
instead masks it: `a <= 300` for a `u8` becomes `a <= 44`, which is a weaker claim that could
pass. So the constant keeps its exact value and the width is chosen later.
* **Resize the constant to the other operand's width (`align_widths`).** Zero-extend for an
unsigned operand, sign-extend for a signed one. A value that does not fit is *refused*, not
truncated: `a <= 300` for a `u8` is an error naming the value and the width, because the
alternative is a proof of the wrong proposition.
* **Narrow by truncation, not by rebuilding from the value.** A negative literal is the bit
pattern `2^w - 10` at its source width. Rebuilding `word(val, wide)` from that value hands
`wide` a number that does not fit and sets `ill_formed` again — the very flag being avoided.
Taking the low `wide` bits is the same bit pattern, and the `fits` check is what keeps it
from being silent.
`i8::MIN` and friends are the same lesson from the other side: the bound must carry the width of
the type it *names*. `i8::MIN` is `0x80`, exactly 8 bits. Building it at a wide scope width and
narrowing back tested a 64-bit `128` against the signed 8-bit range and refused a bound that is
in range by construction.
Each of these has a test in `tests/mir.rs` written against the *evaluator*, so it does not
depend on a corpus function happening to be skipped for an unrelated reason. Two of them failed
when first written and found the masking and truncation bugs above.
The rule is not a comparison rule, it is a *meet* rule, and it applies wherever two operands meet:
the arithmetic levels (`parse_add`, `parse_mul`, …) call the same `align_widths` the comparison
does. `ret == a + 5` with a slice length in scope had the identical failure — an 8-bit `a` added
to a 64-bit `5` — and was `incomplete` for the same reason. That the first fix was written only in
`parse_cmp` is what made the arithmetic case a separate bug rather than the same one.
### A symbolic subscript is modelled on an array and refused on a slice
`a[i]` and `xs[i]` are the same source shape and are not the same problem. The difference is
not that one is symbolic and one is not — both are — but that one has a *finite domain*. An
array's length is in its type, so `a[i]` ranges over a set the frontend can enumerate:
`ite(i == 0, a0, ite(i == 1, a1, … ite(i == N-1, a_{N-1}, 0)))`. That is not an approximation of
`a[i]`, it is a *definition* of it. A slice's length is a symbolic input, so there is no domain
to enumerate and `xs[i]` stays the refusal it always was. The feature is drawn at the domain,
and `MAX_INDEX_CHAIN` bounds it so a large array is refused rather than turned into a term the
solver cannot hold.
Three things had to be true for the chain to be sound, and each is a separate trap:
* **The chain is only `a[i]` where `i < N`, so the precondition must establish that.** The chain
has to return *something* for `i >= N` (it falls through to the last element). Checking a
contract there would check it against a value that is not `a[i]`. So `index_guards` reports
`(index var, N)` for every symbolic subscript, and `verify_function` *proves* `pre ⇒ i < N`.
If it does not hold, the function is `Skipped` with a reason naming the bound. The tempting
alternative — conjoin `i < N` into the precondition — is unsound in the direction that
matters: it strengthens what the source asked to be verified, so a contract proved under
`i < 4` would be claimed to hold without it.
* **The chain must be built from the *same* element variables the body reads.** The parser
rewrites `a[i]` to the chain, and the chain is built from `elem_seeds` — the very variables
the executor is seeded with. If the contract's `a[i]` were built from fresh variables, the
postcondition would be about one array and the body about another, and every proof would be
vacuous in the direction that matters. `bind_sym_index` therefore binds *every* element of
the array up front, not on demand: an element the contract did not bind would be created
fresh by the body's first read.
* **Only the index that was bound has a chain.** `a[j]` where only `a[i]` was bound must not be
rewritten to the `a[i]` chain — that would prove `a[j] == a[i]`, false for every `i != j`. The
rewrite checks `sym_index_name` for the exact index argument before replacing, so a name that
merely looks like the bound one is left for the parser to refuse.
The index is a *name the contract may use* — an argument — and it is bound to that argument's
own variable, so `requires: i < 4` and the chain's guard are the same `i`. A compound index
(`a[i + 1]`) has no name to bind and is refused rather than mis-modelled.
`tests/mir.rs` pins all four sides: the chain verifies, an unbounded index is refused, a
different index is refused, a slice subscript is still refused, and a *false* postcondition
about `a[i]` fails with a counterexample (so "verified" cannot be the chain being a constant
the postcondition happened to accept). The corpus entries are
`array_symbolic_index`, `array_unbounded_index_refused`, `array_wrong_index_refused` and
`slice_symbolic_index_refused`.
### A write has to land where the read looks
The three soundness holes below were all the same shape: the environment held a
value for a place in *two* places, and a write updated one of them. Each produced
a *false proof* — a contract that does not hold, reported `verified` — which is
worse than a refusal, because it is the answer that gets trusted. They were found
by a review that read `Env::set` and `index_elem` side by side, not by a test; the
tests that now pin them were written after.
* **An element write went to the wrong store.** `Env` kept slice and array
*arguments*' elements in `indexed[local].elems` (seeded from `elem_seeds`, and
what the ite chain is built from) but stored a write with `elems.insert((local,
index), v)` — the map for array *literals*. The read consulted the first, the
write updated the second, so `a[0] = 0; a[i]` read the pre-write `a[0]` and
`ensures: ret == a[i]` under `i == 0` was *proved*. `set` now routes an element
write through `write_elem`, which picks the same store the read picks, and the
`(*_1)[0] = v` and `_1[_2] = v` forms are handled too. The general rule: the
write path and the read path must key on the same distinction, and when there
are two stores the code that writes has to know which one the reader will use.
* **A write the store cannot represent has to poison, not be dropped.** An element
write of an aggregate, or through a *symbolic* index (`_1[_2] = v`), has no
per-index slot: the first has no word to store and the second would have to
update every element the chain could select. Dropping it leaves the seeded value
readable — the same stale read, one level down. `Indexed::poisoned` marks every
element unknown instead, keeping the *length* (a write does not change a type's
length). `index_elem`, `read_indexed` and both `get` arms check it. An unknown
element fails a postcondition as an unreadable contract; it does not silently
become the old value.
* **A whole-place assignment left the parts behind.** `c = d` wrote `locals[c]`
and left `fields[(c, 0)]` holding the *argument's* field, so `c = d; c.lo` read
the stale `c.lo` and `ensures: ret == c.lo` was proved against the wrong struct.
`set` now calls `forget_parts` on a whole-place write, dropping the field,
element, payload and tag maps for that local (and poisoning its elements).
`Val::Agg` is the deliberate exception: an aggregate rvalue (`_0 = (a, b)`, the
`(result, overflowed)` of a `checked_*`) writes its own parts inside
`eval_rvalue` and then returns `Val::Agg`, so clearing there would delete the
parts that were just written and turn a modelled tuple back into an unknown one.
Clearing the derived state on a whole-value write is the conservative direction;
the exception is the one case where the derived state *is* the value.
* **A generated name must not be able to shadow a real one.** Bindings are named
by mangling (`a__len`, `c__f0`, `a__chain`) and handed to the parser *after* the
arguments, so an argument that happens to be called `a__chain` would be shadowed
by the chain and a contract naming it would be checked against the array. The
fix is not a less guessable separator — any scheme is guessable — but to record
every source name in `FieldEnv::declared` and refuse a generated name that
collides (`name_is_free`), so the binding is dropped rather than allowed to
shadow. The collision is a refusal, which is the honest answer: the source
chose a name the mangling wanted.
The `&mut [u8]` *slice* argument used to be a separate gap: a write lowers
through `&raw const (fake) (*_1)`, whose `PtrMetadata` the frontend did not model,
so the function was `incomplete` before any write was reached. That is now closed
(see the section below): the parser reads `&raw const (fake) (place)` as the place
it names, so the slice shape is modelled like the `&mut [u8; 4]` one — which goes
through a plain reborrow and was modelled all along.
`tests/mir.rs` pins each hole by name: `an_element_write_reaches_the_symbolic_chain`
(requires `Failed`, so a counterexample is the evidence the chain saw the write),
`an_element_write_through_a_mutable_reference_reaches_the_chain`,
`a_slice_element_write_reaches_the_store_the_read_consults` (the true half must
verify and its tripwire must fail), `a_slice_element_write_reaches_the_symbolic_chain`,
`a_whole_struct_assignment_invalidates_its_fields` (requires *not* `Verified` — the
write poisons the field, so the postcondition is unreadable),
`a_generated_binding_cannot_shadow_an_argument` and
`a_generated_length_binding_cannot_shadow_an_argument`, plus
`a_write_cannot_prove_a_stale_contract` over the corpus entries
`array_write_then_symbolic_read`, `mut_ref_array_write_then_symbolic_read`,
`generated_name_shadows_argument` and `struct_reassign_then_field_read`.
### `slice::first`/`get` return a *place*, so the payload is a reference, not a value
Modelling `slice::first` and `slice::get` (C6) turned on one shape the earlier
`core` models never met: their result is `Option<&T>`, so the payload is a
*reference* to a slice element, and the code that consumes it dereferences —
`*xs.first().unwrap()` lowers to `_3 = first(_1); _2 = unwrap(_3); _0 = copy (*_2)`.
Two things follow, and both are the honest direction rather than a convenience:
- **The payload is the slice's own element variable.** The model records
`(slice local, index)` in `Env::slice_elem_ref` and writes the `Option`'s payload
as the same `xs[k]` variable a subscript read names, so `*xs.first().unwrap()`
and `xs[0]` are *one* term by construction. Writing a fresh variable there would
make the two disagree, and `ensures: ret == xs[0]` would fail for a body that
clearly returns it.
- **The deref reads through the store, before the `deref_ok` gate.** `Env::get`'s
`Proj::Deref` arm refuses a deref of a local that is not a recorded reference
argument, which is what keeps a field-that-is-a-reference from being read as its
owner's referent. A `first`/`get` reference is a local a *call* produced, not an
argument, so the store is consulted first and the `deref_ok` gate is left for the
argument case it was written for. `unwrap` carries the element to its
destination, so the read works whether the caller dereferences the `Option`'s
payload directly or through an intermediate `let`.
- **The `match` desugaring is a *second* read path, and it had to be taught the
same thing.** `match xs.first() { Some(v) => *v, None => 0 }` does not call
`unwrap`; it reads the payload through a downcast temp (`_4 = copy ((_2 as
Some).0: &u8)`) and dereferences *that*. The `unwrap` arm alone left every
`match` form `incomplete` in both directions, which is a coverage gap and not a
soundness one -- but a `match` on the `Option` is at least as common as an
`unwrap`, so the `Rvalue::Use` arm now propagates the entry onto the downcast
destination. One rule, two spellings, and the fixtures pin both.
**The tag is a predicate, and that is the point.** `first` is `Some` exactly when
the slice is non-empty (`len != 0`), and `get(k)` exactly when `k < len`
(`len > k`, not `len >= k` — the predicate is the other way round, and getting it
backwards made every `get(0)` on a non-empty slice report a `None`-unwrap panic
until the fixtures caught it). Because the tag is an `ite` over that predicate and
not a constant, the `unwrap`'s panic obligation is real: `get(1)` past the end
*is* refuted with a panic witness, which a model that wrote `Some` unconditionally
would have missed. `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 make `xs[i]` a different value per read, which is a wrong proof rather than a
missing one. The *generic* `first_or<T>` is not this shape at all: its element type
has no width and its length is never seeded, so it stays refused until generics
(C10) land — which is why the ROADMAP note that `first`/`get` were "blocked on
monomorphisation" was wrong for a concrete `&[u8]`.
Seven fixtures are in `realistic.rs` (four true, two tripwires, one panic) and
`tests/mir.rs::slice_first_and_get_reach_the_slices_own_element` pins all six
directions; the test was confirmed to have teeth by neutralising the
`slice_elem_ref` lookup, which turns the true direction `incomplete`.
## A call boundary is a real boundary: what crosses it and what must not
Four soundness holes and two completeness holes lived at the same place — the
inlined call — and in the same shape of mistake: a value or a type was carried
across the boundary when it should have died with the frame, or dropped when it
should have crossed.
**A by-value aggregate is the callee's copy; a reference is the caller's storage.**
The frontend models `&T` as its referent (the single-owner reading, not an aliasing
model), so a `&mut [T; N]` argument and the caller's local denote the same store:
the callee's post-state *is* the caller's post-state and is copied back on return
(`Frame::by_ref_indexed`). A by-value `[T; N]` is the opposite: the callee got its
own copy, its writes must die with the frame, and nothing is copied back
(`Frame::by_value_indexed` records the pair only so the return-merge can tell the
two apart). Sharing the copy — the tempting way to make a callee's element read
agree with the caller's — makes `let b = f(a)` mutate `a`, so a caller contract
about `a` is checked against a value that never existed. The corpus tripwires are
`caller_of_written_copy` (by-value write must **not** leak; `ret == 0` is false, so
it must fail) against `caller_of_clear_head` (a `&mut` write **must** be visible).
**A constant operand carries its own signedness.** `0 < a` lowers to
`Lt(const 0_i8, copy _1)` — the constant is the *left* operand, and `Const::UInt`'s
type suffix is the only place the signedness appears. Reading a constant as
unsigned made `0 < a` unsigned, under which `i8::MIN` (`0x80`) is the *largest*
value, so `requires: a == i8::MIN; ensures: ret == 1` on `if 0 < a { 1 } else { 0 }`
was **proved** — a reachable false proof, since `i8::MIN` is negative and the
branch is never taken. The fix is `operand_signedness`, which returns `Option<bool>`
and *refuses* (`None`) when the type cannot be resolved rather than defaulting to
unsigned; every caller (`eval_binary`, the checked intrinsics, `try_intrinsic`)
propagates the refusal as `Val::Unknown`. A wrong signedness is not a missed proof
but a wrong branch, which is a wrong answer. The unit test
`a_constants_signedness_comes_from_its_suffix` pins all three answers, because the
bug was a *default* and a test that only checked the signed case would pass the
moment the default came back.
**A tuple component and a struct field are two spellings of "component N".**
`_3 = (a, b)` stores the components under an *index* projection (`elems`), but rustc
prints the read back as `_3.0` — a *field* projection (`fields`). The two have to
meet in one store (`Env::get`'s `Proj::Field` arm falls back to `elems`), or
`let t = (a, b); t.0` reads `Unknown`. A local is a struct or a tuple and never
both, so the fallback can only hit for the tuple case; a struct field that is
genuinely unwritten finds nothing in either store and stays `Unknown`.
**A tuple return's components cross the call boundary with the aggregate.** The
callee stores its result in its *own* return place (`_0.0`, `_0.1`); the caller's
`min2(a, b).0` reads `_2.0`. Carrying only the aggregate loses the components and a
contract about them is unreadable rather than checked. They are copied under the
*destination's* local, and only the ones the callee wrote — a path that left `_0.1`
unwritten leaves the caller's `dest.1` unknown rather than inventing a value. The
tripwires `tuple_component_tripwire` and `min_call_tripwire` claim the *wrong*
component and must fail.
**A tuple-return postcondition is checked on the components a contract names.**
`ret.0` of a `(bool, u8)` is a `bool` in the type but a one-bit word in the
postcondition, so the component is widened on read-out (`Val::Bool` →
`ite(p, 1, 0)`) — without it the name is unbound and the contract is refused. And
the up-front parse probe (`verify::verify_fn`) binds only the components the
contract *names* (`spec::named_ret_components`): binding every declared component
made a `(u8, &u8)` return unprobeable (component 1 is a reference with no bit
width), so a contract about `ret.0` alone skipped the whole function. A component
the contract names and that has no width is still refused — then the name really
cannot be resolved.
`tests/mir.rs` pins each by name:
`a_helper_that_indexes_its_parameter_reaches_the_caller_element`,
`a_write_through_a_reference_reaches_the_caller`,
`a_by_value_helper_cannot_write_the_callers_array`,
`a_constant_left_signed_compare_is_signed_not_unsigned`,
`a_postcondition_can_name_a_bool_tuple_component`,
`a_reference_component_the_contract_does_not_name_does_not_skip_the_function`,
`a_tuple_locals_component_can_be_read_back`,
`a_tuple_returning_calls_component_reaches_the_caller` and
`a_tuple_component_read_cannot_prove_the_wrong_component`, over the corpus entries
`head`/`caller_of_head`, `clear_head`/`caller_of_clear_head`,
`caller_of_written_copy`/`clear_copy`, `signed_const_left_false`/`_true`,
`bool_component`, `first_component_only`, `tuple_local_component`, `min2`/`min_call`
and the two tuple tripwires.
## A widening cast needs the *source's* signedness, and `truncate` is not it
`Rvalue::Cast` used `smt::truncate` for every target width. `truncate` zero-fills,
so `-1i8 as i16` was modelled as the bit pattern `255` — and
`requires: a == -1; ensures: ret == 255` on `a as i16` was **proved**, a second
reachable false proof of the same family as the constant-left comparison: a value
operation that silently lost its sign.
The two widening directions need *opposite* rules, so no single rule is right:
`i8 as i16` sign-extends (`-1` stays `-1`), `u8 as u16` zero-fills (`255` stays
`255`). The source operand's signedness decides, via the same `operand_signedness`
the comparison and shift paths use — `Some(true)` → `smt::sign_extend`,
`Some(false)` → `smt::truncate`, and `None` (the source type could not be read) →
refuse, because zero-filling a signed value is the false proof above and
sign-extending an unsigned one turns `255u8 as u16` into `65535`. `sign_extend`
truncates first when the target is no wider, so a *narrowing* cast (`300i16 as u8`
→ `44`) is unaffected and `truncate`'s behaviour is unchanged for it.
`tests/mir.rs::a_widening_cast_respects_the_sources_signedness` pins all four
directions — the two true contracts must verify and the two false ones must fail —
over `widen_signed_true`/`_false` and `widen_unsigned_true`/`_false`, because a
test that only checked the signed case would pass again the moment the rule went
back to a single default.
## Next stage: the signedness work is a *rule*, so let the engine state it
> The open work from every "Next stage" / "Stage N" section in this file is now
> tracked in [`ROADMAP.md`](ROADMAP.md), which is the single source for what is
> left. This section is kept as the *record* of the reasoning; check `ROADMAP.md`
> for the current status of each item.
Both false proofs fixed in this round were the same bug wearing different
clothes. A value operation silently dropped the signedness of its operand:
`0 < a` compared `const 0_i8` as unsigned, and `a as i16` zero-filled a signed
source. The repair went in at each *call site* of `operand_signedness`. That is
the shape of fix that leaves a third case behind, so the next stage is to make
the rule structural rather than per-site.
**Stage 1 — make the width-and-signedness rule a type, not a habit.** DONE.
`Val::Sym` is now `Val::Sym(Var, Sign)`, and `Sign` has *three* cases:
`Signed`, `Unsigned`, and `Unknown` for a value whose dump printed no type. The
third case is the whole point. With only two cases, a site that could not read
the sign had somewhere to fall back to, and both false proofs were exactly that
fallback: a suffix-less `const 0_i8` read as unsigned, and a cast source whose
sign was dropped. With three cases, every signedness-sensitive site has to say
what it does when the sign is missing, and the compiler names the ones that do
not -- which is how the four sites below were found rather than remembered:
* `eval_binary` -- a relational comparison (`<`, `<=`, `>`, `>=`) and the signed
divider/`srem` refuse an `Unknown` sign. `==`/`!=`, `+`, `&` and the rest do
not read the sign, so they still compute.
* `overflow_pred` -- an `Unknown` sign has no sound predicate, so it returns
`None` and the path is reported unmodelled rather than proved.
* `try_intrinsic` -- `sdiv`/`srem` on an `Unknown` sign are refused.
* `Rvalue::Cast` -- an `Unknown` *source* sign refuses the cast. This is the
`-1i8 as i16` bug's home; zero-filling a signed source and sign-extending an
unsigned one are both wrong, so neither may be guessed.
The sign travels with the seed too: `FieldEnv::seeds`, `len_seeds`, `elem_seeds`
and the `Indexed` element store all carry it, so an array element read out of the
store is a signed value on an `&[i8]` without any site having to look the type up
again. `operand_signedness` is *deleted* -- the lookup it performed no longer has
a caller to get wrong, because the sign is a field of the value it describes.
The regression net is the corpus (`signed_const_left_false`, `widen_signed_false`,
`signed_mul_negative`, `ashr_signed_false`) plus the two new entries
`signed_slice_element_is_signed` / `signed_slice_element_tripwire`, which pin the
element-side case: `i8::MIN` is the most negative `i8` and the largest `u8`, so
`xs[0] < 0` proves the opposite branch under the unsigned reading. A unit test
(`a_comparison_on_an_unprinted_sign_is_refused`) pins the refusal directly.
**Stage 2 — close the remaining `Rvalue` gaps, one at a time, each with a
tripwire.** The list below was written from reading the `Rvalue` enum, before
measuring which variants real rustc actually *prints*. Measuring first changed it:
two of the six items were not gaps at all, and the real ones were smaller and
differently shaped than the enum suggested. The lesson is the same one the
signedness round taught -- a gap list inferred from a type is a hypothesis, and
the corpus is the experiment that tests it. (`examples/mir_coverage` takes an
optional file argument, which is what made the measurement cheap.)
* **`Rvalue::Cast` to `bool` — not a gap.** `a as bool` does not compile
(`E0054`: `cannot cast u8 as bool`); the idiom is `a != 0`, which lowers to
`Ne`, already modelled. Nothing to do, and the item was removed rather than
implemented.
* **`Rvalue::Len` — not a gap.** Modern rustc does not print `Len(` at all: a
`.len()` lowers to `PtrMetadata`, and `grep -c 'Len('` over a full dump is `0`.
The real work was in `PtrMetadata`, below, not in the variant the enum names.
* **`Rvalue::Struct` for a struct literal — DONE.** `Config { lo, hi }` is a
*struct-literal* rvalue, not an array/tuple `Aggregate`. The two write different
stores: an aggregate writes `Proj::Index` (tuple components, which a contract
cannot name) and a struct literal writes `Proj::Field` (which a contract *does*
name, as `c.lo`). The fields are printed in **declaration** order, which is the
order the `Field(N)` projections count in, so a positional store is sound -- and
the tripwire pins exactly that: `struct_literal_order_tripwire` writes `hi`
first and must be refuted with a witness that is the `hi` operand, not `lo`.
* **`Rvalue::Ref` and dereference — DONE.** `&place` records the place it
addresses, and `Env::resolve` rewrites a `*_2` whose `_2` is addressed into that
place. This is a *substitution*, so a write through the reference and a read of
the target meet in one store: `reference_write_reaches_target` verifies because
the write is seen, and `reference_write_tripwire` fails because a snapshot model
would have proved it. The same store fixed a parser bug: `strip_annot` stripped
the parentheses off a bare `(*_2)`, leaving `*_2`, which no place parser reads.
* **`PtrMetadata` of an unsized array — DONE.** `a.len()` on `a: [u8; 4]` lowers
to `_3 = &_1; _2 = _3 as &[u8]; PtrMetadata(_2)`. The reference-to-reference
cast carries the address across, and `PtrMetadata` follows it to the array,
whose length is the *type's constant* -- not a fresh variable, so `a.len() == 4`
has something to agree with. `Env::pointee` is the one-level value step that
`resolve` deliberately does not take, because metadata belongs to the pointee,
not the pointer.
* **A whole-struct reassignment — DONE.** `c = d` copies a value the frontend
models as its *parts*, so `Env::copy_parts` moves the field/element/payload/tag
maps. It reports whether anything moved, which is what lets `set` keep the parts
(the same `Val::Agg` convention an aggregate literal uses) instead of clearing
them. `struct_reassign_then_field_read` moved from *incomplete* to **refuted**:
the false contract is now a counterexample, not a shrug.
* **A *nested* aggregate assignment — DONE.** `o.i = Inner { v: 9 }` lowers to a
struct literal into a temp followed by `(_1.0) = move _2`, so the parts being
moved are keyed under the temp and the destination is the nested place `_1.0`.
`copy_parts` is reached only for a whole-place destination, so the temp's `v`
never landed under `_1.0` and the later read `(_1.0).0` -- the *nested* store,
keyed by the whole chain -- found nothing. The body's value was then unknown,
and a contract that is false of the body was reported unreadable instead of
refuted. `Env::rebase_parts` moves the source's parts to the destination,
re-rooting both when either place is nested, called *after* `set` (whose field
arm forgets the stale nested paths first, and the helper is what puts the
source's parts back). It generalises `copy_parts`, which is the
whole-to-whole case and carries the element/payload/tag/index stores too; the
re-rooting one moves the two field-shaped stores and is reached when *either*
side is nested -- a struct literal into a nested field (`o.i = Inner { v: 9 }`),
and a nested-to-nested move (`o.i = o.j` lowers to `_2 = move (_1.1); (_1.0) =
move _2`, so a *nested source* into a whole temp, then a whole source into a
nested destination). `copy_parts` refuses a nested source, which is why the
nested-to-nested move was `incomplete` before. A part is re-keyed *relative* to
the source's own path: the entry at `(src, sp)` -- or the single-field entry
whose key *is* `sp` -- is the value at `src`, and it lands at the destination's
path. A whole destination drops all its parts first; a nested destination keeps
its siblings, because only the paths under it are written. Only an all-field
path is re-keyed: a deref, index or downcast names a store the helper does not
re-root, and writing a part where no read consults it would be a lost proof at
best, so those are refused.
`whole_inner_write_makes_nested_seed_stale` moved from *incomplete* to
**refuted**, and its positive companion `whole_inner_write_is_seen_by_the_leaf`
verifies -- the pair rules out a blanket refusal, which is what an
"`!is_verified()`" assertion on the false entry alone would have let through.
The nested-to-nested pair `whole_inner_move_carries_the_source_leaf` (true
`ret == 3`, verified) and `whole_inner_move_is_not_the_stale_destination` (the
destination's pre-move `7` claimed to survive; refuted, witness `o.i.v = 7`)
pins both directions: a model that kept the stale leaf would *prove* the twin.
The swap pair `nested_swap_carries_the_other_side` (seeds `3`/`4`, true `ret == 4`)
and `nested_swap_is_not_the_stale_side` (the pre-swap `3` claimed to survive;
refuted) is what makes the *either-side* guard load-bearing: with the guard
narrowed to "destination nested" both entries go `incomplete`, which is exactly
the mistake the pair catches.
A *returned* nested aggregate is the mirror image of the argument side. `id_inner(o.i).v`
lowers to `_3 = move (_1.0); _2 = id_inner(move _3); _0 = copy (_2.0)`, so the argument
is a sub-place (whose parts the re-based copy-in already carries) and the callee's
`_0 = _1` return builds `_0`'s fields field-by-field. The return merge only copied
`elems` (the tuple components), so a struct return lost its `fields`/`nested` and the
caller's read was `Unknown` while the contract was true. The merge now copies the
callee's `_0` fields and nested paths into the destination too, clearing the
destination's old parts first (a returned whole value must not keep a stale field the
callee did not write -- that would be a *wrong* value, not a missing one). The pair
`nested_aggregate_argument_reaches_the_helper` (true `ret == 9`, verified) and
`nested_aggregate_argument_is_not_the_stale_destination` (claims `7`; refuted, witness
`v4 = 9`) pins it: with the new branch disabled both go `incomplete`.
Three holes remain next to it, all *coverage* rather than soundness (nothing false can be
proved: each is an unreadable contract or an `Unknown` read, never a pass). A *two-level*
nested return path (`mk_outer(o.i).i.v`) is now closed: `_0 = OuterBox { i: copy _1, .. }`
stores the field value but not the operand aggregate's own parts, so `Rvalue::Struct`
re-roots an aggregate operand's parts onto the field (`rebase_parts`, gated on the operand's
type, because a by-value struct argument reads `Unknown` as a whole). Pinned by
`nested_return_carries_the_field` / `nested_return_is_not_the_stale_field`. An *array literal
of aggregates* (`[o.i, o.j]`) is now closed: the literal path stores the element under `elems`
by index, and the element's *leaves* are re-rooted onto that element in a store keyed
index-first (`elem_parts`, mirrored in `nested` for the tuple spelling), because the read
`a[0].v` lowers to `_2[_5].0` -- an index then a field, the opposite order from `o.a[0]`, so
`rebase_parts` (field chains only) could not carry it. The read arm consumes the trailing field
steps; without that the loop re-reads `Field(0)` against the local and replaces the leaf with
the whole element. A whole-aggregate *element write* (`b[0] = Inner { v: 7 }`) re-roots the same
way, and `copy_parts` carries `elem_parts` across a whole-value copy. Pinned by
`an_array_literal_of_aggregates_is_read_back` / `..._second_element_...` /
`..._aggregate_fields_...` / `a_tuple_literal_of_aggregates_...` /
`an_element_write_of_an_aggregate_...` and their `_cannot_prove_this` twins, asserted in
`an_aggregate_literal_element_carries_its_own_leaves`.
A *write* to a leaf inside such an element (`a[0].v = 7`, which lowers to
`(_1[_3].0: u8) = 7` -- an index then a field, `set`'s arms covered neither) is
`write_elem_part`: it drops the leaves the write replaces, writes both keys, and
poisons a subscript the run cannot pin. `write_elem` clears the element's old leaves
first, so a whole-element write whose source cannot be re-rooted (`a[0] = other[1]`,
which `rebase_elem_parts` now also carries) leaves them unknown rather than stale.
The store then crosses both call boundaries: the argument transfer and the reference
copy-back carry it (whole-local targets only -- a sub-place target's array is reached
through a field path this store has no key for, so its caller leaves are dropped, not
prefixed), and the return merge re-keys the callee's `_0` leaves onto the caller's
destination. Each of those was a *false proof*: the stale leaf decided a contract about
the pre-write value. Pinned by
`an_element_leaf_write_is_read_back` / `..._leaves_its_sibling` /
`a_second_element_leaf_write_...` / `a_tuple_component_leaf_write_...` and
`a_helper_leaf_write_through_a_mutable_array_...` / `a_helper_leaf_read_...` /
`a_returned_array_of_aggregates_...` with their `_cannot_prove_this` twins, asserted in
`a_leaf_write_inside_an_element_is_read_back` and
`an_element_leaf_store_crosses_a_call_boundary`.
A *whole-element* write of an aggregate (`a[0] = E { v: 7 }`) is the other half,
and through a `&mut` argument it lowers to `(*_1)[_3] = move _2` -- the leading
`Deref` is what the re-root gate used to miss, because it read `dest.proj`
directly; `elem_index_of` reads past it now (and past the `Deref` on a source
element too, so `rebase_elem_parts` takes the element-source arm for rustc's usual
`IndexVar` spelling, not only a constant `Proj::Index`). An element *copy*
(`a[0] = b[0]`) goes through a temp, and reading an element hands over its leaf
*scalar* rather than its parts, so `carry_elem_leaf_onto_local` moves them onto
that temp; that pair was `incomplete` in both directions, not a false proof. The
copy-back drops the caller's own leaves for a whole-local target *before* copying
the callee's in, because a callee that wrote through an index it could not pin
poisoned its array and holds none -- keeping the caller's would leave a stale
pre-call leaf readable. Pinned by
`an_element_copy_from_another_element_is_read_back` /
`a_helper_whole_element_write_is_read_back` /
`..._leaves_its_sibling` / `a_helper_element_copy_is_read_back` and their
`_cannot_prove_this` twins, asserted in
`a_whole_element_write_of_an_aggregate_crosses_a_call_boundary`.
An *unpinned* element write (`a[i] = x`) poisons the whole array, and the poison
has to reach *both* leaf representations: `poison_elems` cleared `elem_parts` and
left its `nested` mirror, so a later element *copy* (`let x = a[0]`) collected the
mirror and **proved** `x.v` was the pre-write leaf. The poison also has to cross
the call boundary, which it did not: a helper's symbolic write left the callee with
no leaves, the copy-back inserted none, and the caller's own leaves survived. A
literal array's elements live in `elems`, which has no `poisoned` flag of its own,
so `Env::poisoned_elems` records the local; the argument transfer carries it in,
and the copy-back drops the caller's `elems`/`nested`/`elem_parts` for that local
before copying anything. Pinned by
`an_element_copy_after_an_unpinned_write_is_not_the_old_leaf` /
`..._is_not_the_sibling` / `..._is_not_the_new_leaf` /
`..._after_an_unpinned_leaf_write_...` and
`a_helper_unpinned_write_is_not_the_callers_old_leaf` / `..._sibling`, asserted
`!is_verified()` in `an_unpinned_write_poisons_the_whole_array` -- `incomplete` is
the honest answer for a write the run cannot pin, and the one outcome that must
never appear is `verified`.
The poison is array-wide, but the leaf maps *are* the record of which indices have
been re-established, so an array-wide veto must not sit in front of them: a pinned
write after a symbolic one (`a[i].v = 7; a[0].v = 9`) re-populates exactly its
index, and `poisoned_elems` must not hide it -- that made
`let x = a[0]; x.v` `incomplete` though the copy is always `9`. The marker is for
the *call boundary* only, where it means "this array is not wholly known"; it is
no longer consulted by `carry_elem_leaf_onto_local` or by the `elem_parts` reader.
Pinned by `a_pinned_leaf_rewrite_after_a_symbolic_write_is_read_back` /
`a_pinned_element_rewrite_after_a_symbolic_write_is_read_back` /
`a_pinned_leaf_rewrite_after_a_symbolic_element_write_is_read_back` /
`a_helper_pinned_rewrite_after_a_symbolic_write_is_read_back` (verified) against
the twins `a_pinned_rewrite_does_not_recover_its_sibling` /
`a_pinned_rewrite_does_not_revive_the_old_leaf` (`!is_verified`), so the recovery
is per-element and never a blanket un-poisoning.
And an *array whose type is
a field* (`o.a[0]`) is skipped, since the `indexed` store is keyed by local only (see the note
below).
Two notes on what this did *not* need. The nested literal always reaches the
store through a temp, so `Rvalue::Struct`/`Aggregate` do **not** need to write
under `dest.proj`; and making `Aggregate` do so *drops* a nested tuple write
(`(_1.0) = (5, 6)` writes `(_1.0.0)`, a `Field(0) + Index(0)` chain the `set`
catch-all does not re-root), so the tempting "consistency" edit is a
regression. The minimal, evidence-backed change is the assignment hook alone.
Both projections are *resolved* before the path is read, and one leading
`Deref` is stripped as `field_steps` strips one (it now backs `field_chain`):
`o.i = Inner { v: 9 }` through an `&mut Outer` lowers to `((*_1).0) = move _2`,
and an `&mut T` argument is modelled as its referent, so `resolve` leaves the
lone deref in place. Without the strip the write is refused for the wrong
reason and the leaf reads `Unknown` --
`whole_inner_write_through_a_mutable_reference_is_seen` verifies after it and
is `incomplete` before, the tripwire for the deref case.
The deep `i64 / 3` wall is *not* part of this: that entry is the deliberate
`MAX_WALK_DEPTH` refusal vehicle (`a_symbolic_division_by_a_non_power_of_two_at_i64`,
whose contract is false in general), so its `incomplete` is intended, not a bug.
* **`Rvalue::Discriminant` and `Downcast` for a real enum match — DONE.**
A `match` on an enum lowers to `_2 = discriminant(_1); switchInt(move _2)`,
so the tag is a symbolic input whose *domain is the set of variant
discriminants*. That bound is a fact about the type, not an assumption about
the caller, so the run may assume it -- and it is what makes the `otherwise`
arm (lowered to `unreachable` for an exhaustive `match`) genuinely unreachable
instead of a spurious panic. Three pieces make it work:
- `spec::EnumDef` / `EnumLayout` carry each variant's **discriminant** from the
same source pass as the contracts, so a `(base as Variant)` downcast's tag
and a contract's `Mode::Run` constant agree by construction rather than by
convention. The discriminant is rustc's value, not the vector position: an
explicit `B = 3` renumbers `C` to `4`, and numbering by position would put a
contract naming `Gap::C` on the wrong tag. A one-line body
(`pub enum E { A, B }`) and a multi-line one are read by the same
top-level-comma split, so the numbering cannot drift between them.
- `FieldEnv::bind_enum` binds the argument's own name to the tag, so a
contract writes `m == Mode::Run`; each variant's first payload is bound
separately (keyed by discriminant), so `m.Data` names the same variable the
body's `((_1 as Data).0)` downcast reads.
- `Seeds::tag_seeds` seeds the tag with its discriminants and
`Seeds::payload_seeds` the payloads, and the run conjoins the *disjunction of
the discriminants* onto the initial path -- `tag < count` is only the same
domain when the numbering is `0..count`, which an explicit discriminant
breaks.
The tripwires pin the model rather than its presence: `enum_match_tripwire`
claims every arm returns `2` and must be refuted with the tag in the witness
(a constant tag would prove it), `enum_explicit_discriminant_tripwire` claims
the `B` arm ran for `Gap::C` and must be refuted (a positional reader proves
it), and `enum_payload_tripwire` names a *unit* variant's payload, which is
refused rather than bound to a fabricated value. A variant with no payload is
refused with a message naming the variant.
* **A locally constructed variant has a *known* tag — DONE.** `let m = Mode::Idle;`
lowers to `_1 = Mode::Idle;`, a bare path constant with **no `const ` prefix**,
which the rvalue parser did not recognise: it fell through to `Rvalue::Unknown`
and the tag was never written, so `let m = Mode::Idle; match m` stayed
`incomplete` even once a tag read from an *argument* worked. Two changes close
it. `parse_rvalue` recognises a bare `Enum::Variant` path as a constant, and
`eval_rvalue::Use` resolves it against the program's enum layouts -- the same
table a `match`'s downcast reads -- writing a *constant* tag rather than
seeding a symbolic one. The tag's width is the enum's *discriminants'*, taken
from the destination's type, not the dump's `isize`: `Env::tag_widths` records
it so `discriminant` reads the tag back at the width the contract's comparison
was checked at. A payload construction (`Msg::Data(9)`) is `Rvalue::Variant`:
the tag is the variant's discriminant and the operands are written as the
variant's fields, so the match's `((_1 as Data).0)` downcast reads what the
construction wrote. `enum_constructed_locally` verifies and
`enum_constructed_locally_tripwire` is refuted; the payload case
(`enum_constructed_payload_reads_through`) verifies.
* **A variant's tag is rustc's *discriminant*, not its position — DONE.** The
reader used to number variants by their position in the declaration
(`EnumDef::index_of` returned the vector index, the tag's width was the
variant *count*'s, and payloads were keyed by position). An explicit
discriminant breaks all three: `pub enum Gap { A, B = 3, C }` gives `C` the
discriminant `4`, so a positional reader calls it `1`, puts a contract naming
`Gap::C` on the wrong tag, and -- because the `match` arm constants come from
rustc -- lets the contract and the arm disagree, which is a **false proof**
(`enum_explicit_discriminant_tripwire` was *verified* before the fix). The
data model now carries `(name, payload, discriminant)` per variant,
`parse_discriminant_literal` reads a decimal/hex/binary/octal literal (an
unreadable one refuses the *whole* layout rather than guessing), `tag_width`
is the largest discriminant's width, the tag's assumed domain is the
*disjunction of the discriminants* rather than `tag < count`, and payloads are
keyed by discriminant. Two related built-in hazards were closed at the same
time: a *declared* layout now wins over the built-in `Option`/`Result`
numbering for a qualified name (`Shadow::Some` is tag `0` for a user
`enum Shadow { Some, None }`, not `Option`'s `1` --
`enum_user_variant_not_option_constructed_tripwire` was verified before this
fix), and a qualified name whose enum is unknown is refused rather than
answered by another layout that happens to share the variant name.
* **`// MIR FOR CTFE` is a copy, not a second function — DONE.** Building a
tuple-variant constructor in a `let` (`Msg::Data(9)`) makes rustc print a
*second*, `// MIR FOR CTFE`-marked body for the constructor. It is a copy of an
item already printed above it, and the typed MIR has one body per item, so
parsing it made the text side count 69 functions where `rustc_public` counted
68 -- a `rustc_public` MIR-oracle failure (gate 9) over a function that is
really there once. The parser now skips a `// MIR FOR CTFE` marker and the body
that follows it. This is exactly the class of printer change gate 9 exists to
catch: the frontend's own verdicts were unaffected, and only the oracle
noticed.
* **`Rvalue::Unary(Not)` on a word operand — DONE.** The mask now comes from
the *operand's* width (`smt::bits`), with `dest_w` kept as a cross-check that
refuses a disagreement. Measured first: rustc lowers `!x` at `u8`/`i8`/`u32`
to `_0 = Not(copy _1)` with `dest_w` equal to the operand's width, so the
reachable behaviour is unchanged -- this removes a way to be wrong, it does not
change an answer. The real gap was coverage: `!x` had *no* corpus entry. Five
now carry it (`not_of_zero_is_all_ones`, `not_of_zero_u32_is_all_ones`,
`not_of_zero_is_minus_one`, `not_is_255_minus_x` and
`not_is_always_255_tripwire`, refuted with witness `v1 = 1`), taking coverage
from 71/123 to **75/128**. See the section below.
Corpus coverage went from 33/51 to 44/67 decided across this round; the new
entries are `struct_literal_reads_its_field`, `struct_literal_order` (+ its
tripwire), `reference_reads_through`, `reference_write_reaches_target` (+ its
tripwire), `array_len_is_the_type_constant`, `struct_reassign_reads_new_field`,
the five enum entries (`enum_match_is_bounded`, `enum_match_selects_by_tag`,
`enum_payload_reads_through` and their tripwires) and the two construction
entries (`enum_constructed_locally` + tripwire,
`enum_constructed_payload_reads_through`).
**Stage 3 — the contract language's two deliberate refusals.** `xs[i]` with a
symbolic `i` on a *slice*, and `a[k]` where `k` is a local rather than an
argument. Both halves are DONE.
*The local half is DONE.* `let k = i; a[k]` was refused because the contract's
`k` resolved to nothing. The refusal was misdiagnosed as "there is no local":
`rustc` prints no local for `k` at all. A `Copy` argument copied into a `let`
lowers to the argument's *own* local, and `k` survives only as a scoped
`debug k => _2;` — the body's `a[k]` really is `_1[_2]`. So the fix is to resolve
the name, not to bind a new variable.
The parser keeps every `debug` binding in `MirFn::debug_aliases` (the existing
`local_names` map cannot: it keeps the *first* binding per local, so that a scoped
alias does not rename the parameter, and it therefore drops `k`). `MirFn::
alias_locals` then decides which of those names may resolve, and it resolves a
name only when the aliased local is an argument, is never written by the body, is
not already an argument's own name, and does not alias two different arguments.
The `written` set is collected from the parsed blocks, so a `mut i` that the body
reassigns makes `k` unresolvable — the conservative direction, which loses a
proof rather than inventing one.
The names flow through `arg_vars` and `signed_args`, so `a[k]` builds the same
ite chain `a[i]` would *and* a signed `i` makes `k` signed in a comparison. Two
corpus entries carry it — `array_local_index_through_alias` (verifies) and
`array_local_index_tripwire` (must fail, and its witness pins `k` to a real index)
— and `array_local_index_written_refused` pins the `written` gate. Coverage went
from 44/67 to 45/69.
*The slice half is DONE.* The design note below had a soundness hole and it is worth
recording, because the hole is the interesting part.
A slice's length is a symbolic input, so `xs[i]` cannot be enumerated over a type
length the way an array can. The note proposed enumerating `0..MAX_INDEX_CHAIN` and
guarding each step with `k == n && k < len_var`, with the obligation that the
precondition imply `i < xs.len()`. That obligation is *not enough*. The chain has to
return something for `i >= MAX_INDEX_CHAIN`, and an index in `[64, len)` is in range
and past the enumeration, so it would fall through to a wrong element. The obligation
that closes it is on the *length*: `xs.len() <= MAX_INDEX_CHAIN`, which makes the
enumeration cover every index the slice can hold, not just the one the contract named.
Bounding the index alone leaves the body's read at some other index unmodelled.
So a slice's subscript has two obligations, not one, and they are checked separately so
the refusal names the missing one:
* `i < xs.len()` — the named index is in range.
* `xs.len() <= MAX_INDEX_CHAIN` — the enumeration covers the whole slice.
The machinery: `IndexBound` (`Const(n)` for an array, `Len(v)` for a slice) replaces the
`u64` that `index_guards` used to yield, so the bound travels as one shape whether it is
a constant or a term. `FieldEnv::sym_bound` records it; `bind_sym_index` enumerates
`steps` accordingly. On the executor side a slice's chain length cannot come from
`fixed_len` (there is none), so `Seeds::slice_steps` carries it — and it is populated
*only* when the contract established `len <= MAX_INDEX_CHAIN`, which is what keeps a
slice subscript a refusal when it is not bounded. `Indexed` gained `slice_steps` and
`index_chain` now takes `fixed_len.or(slice_steps)`.
Three corpus entries carry it and each pins a different half: `slice_symbolic_index`
(verifies, both bounds present), `slice_symbolic_index_tripwire` (must FAIL on the
postcondition, with `i` pinned non-zero — the evidence the chain depends on the index),
and `slice_unbounded_length_refused` / `slice_unbounded_index_refused` (each supplies one
bound and withholds the other, so a rule checking only one would model what it must
refuse). The tripwire names `xs[i]` *and* `xs[0]`: naming only the literal leaves the
body's symbolic read unmodelled and the entry comes back a refusal rather than a
refutation, which a `!is_verified` assertion would accept for the wrong reason — so the
test asserts `Failed`, not `!is_verified()`.
One shape is left out on purpose. A body reading a *different* symbolic index than the
contract bounded (`xs[j]` under a contract about `xs[i]`) is modelled, but with two
64-deep chains the engine returns `Unknown` rather than a refutation, so it is a
completeness cliff and not a corpus entry: an entry that neither verifies nor refutes is
not evidence. Coverage went from **51/82 to 52/85** and the test count from 488 to
**490**.
A second boundary is a consequence of the design and worth stating: a slice's chain
exists only when the *contract* bounded the length, because `sym_bound` is what the
executor's `slice_steps` is derived from. So a function whose body reads `xs[i]`
symbolically but whose contract never names a slice subscript gets no chain and that read
stays a refusal. An array does not have this coupling — `array_lens` comes from the type,
not the contract — so a body-only symbolic array read is modelled where the slice one is
not. The asymmetry loses a proof rather than inventing one, and closing it would mean
walking the body for slice reads and then proving `len <= 64` for functions that never
needed slice modelling, so it is left as the honest boundary.
**Stage 4 — the missing intrinsics.** `wrapping_neg`, `wrapping_div`,
`wrapping_rem`, `leading_zeros`, `trailing_zeros`, `count_ones`, `pow`,
`is_power_of_two`, `add_signed`/`add_unsigned`. The `wrapping_*` family is the same
arithmetic the `checked_*` arms already do, minus the overflow obligation, so it is
mostly plumbing.
`count_ones` and the zero-counts are small bit-vector loops and belong in
`verif-arithmetic` beside the other proved primitives, not in the frontend.
All of these are now modelled except the division families that cannot express a
zero divisor as a value (see below); the
bit-count family is complete, `count_ones`/`count_zeros`, `leading_zeros`/`leading_ones`
and `trailing_zeros`/`trailing_ones` each being one expression applied to `x` and `!x`.
**Stage 4 progress: the two-operand families and the whole unary surface are
modelled.** `checked_*`, `saturating_*`, `wrapping_*` and `overflowing_*` are all
computed in the frontend from their operands: the two-operand `overflowing_*`
shapes share the `failure` predicate the other families read, and were checked
against `core` over the whole `u8`/`i8` domain. `count_ones`, `leading_zeros` and
`trailing_zeros` are the bit counts; `neg` and `abs` are modelled in all four
families. The `Intrinsic` enum was restructured to say so: `Bits(BitKind)` for the
counts, `Unary(Family, UnOp)` for the operators, and `Overflowing(BinOp)` for the
`(T, bool)` family. The three *complement* counts `count_zeros`, `leading_ones` and
`trailing_ones` are modelled too, and are defined as `core` defines them — the
corresponding positive count of `!x` — so there is one expression per pair rather
than two that could drift. `!x` is `bxor(x, all_ones(w))`, the same term the
executor builds for a `Not` rvalue, so a bit count of a written `!x` and a bit count
of the complement cannot disagree. `is_power_of_two` is modelled too, and it is the
one shape whose *return type* is `bool`: the model produces a `Pred` and the executor
writes a `Val::Bool`, which is what the `if` that consumes it branches on. It is
unsigned-only, because `core` has no such method on the signed types. The sign
predicates `is_negative`/`is_positive` are modelled the same way and are `core`'s
own definition read *signed* (`x < 0`, `x > 0`); they exist only on the signed
types, and the signedness is the whole content, because `i8::MIN` (`0x80`) is the
largest unsigned byte, so an unsigned reading of the top bit would call it positive.
Each is checked exhaustively over `i8`/`i16` against Rust's own methods
(`the_sign_predicates_agree_with_rust`), with `i8::MIN` named as the point an
unsigned reading gets wrong. The
mixed-signedness additions — `wrapping_add_signed`, `saturating_add_signed`,
`checked_add_signed`, `overflowing_add_signed` and their `_unsigned` counterparts —
are modelled too, as `Intrinsic::MixedAdd(Family)`: their two operands have
*opposite* signedness (`u8::wrapping_add_signed` adds an `i8` to a `u8`), so they
are their own shape rather than a `BinOp`, and the direction is read from the
operands rather than stored in the variant. Findings worth more than the coverage:
* **The mixed-add overflow flag is *not* the ordinary signed-addition rule, and a
model that reached for that rule would be wrong on half the domain.** The flag
rustc inlines is `carry XOR (addend < 0)`, where `carry` is the addition's
overflow read at the *method's own type* (the unsigned carry for `u8`, the signed
overflow for `i8`) — which is exactly the `failure(Add, …)` predicate the other
families already use, so the mixed shapes reuse it rather than stating a second
carry rule. The adjustment is load-bearing in both directions and the naive
reading fails both ways: for `u8::add_signed`, `250u8 + (-1i8)` is `249`, in
range, but the addition *carries* (`250 + 255` wraps), so the bare carry reports
an overflow that is not there; for `i8::add_unsigned`, `0i8 + 128u8` is `-128`,
which has run off the top, but the addition does *not* carry, so the bare carry
misses it. The addend's top bit is its sign in either reading, so one term serves
both. Both directions were walked over the whole `u8`/`i8` domain (65536 pairs
each) against `core`'s own methods; the carry alone missed 32768 of them. The
first cut of this model used the *self* operand's sign instead of the addend's and
was caught by the differential test at `i8::add_unsigned` (`0i8 + 128u8`), which is
why the test walks both directions rather than one.
* **The saturating clamp differs by direction, and the two clamps are not the same
bound.** `u8::saturating_add_signed` clamps to the *addend's* end — `0` for a
negative addend, `255` for a non-negative one — while `i8::saturating_add_unsigned`
adds a non-negative count and can only run off the top, so it clamps to `127`. A
model that took the unsigned maximum for a signed self would return `255`, which
reads back as `-1`; the exhaustive walk caught exactly that (`0i8 + 128u8`).
* **The value is one term in both directions.** rustc reinterprets the operand of the
opposite signedness and adds, so `mixed_add_result` is a plain `smt::add` and the
same expression serves `u8::wrapping_add_signed` and `i8::wrapping_add_unsigned`.
Only the failure predicate and the clamp read the direction.
* **A `u8`/`i8` corpus pin is not enough for the `_unsigned` direction.** `0i8 +
128u8` is `-128` under *both* readings of the addend (`128u8` as `u8` gives `-128`;
`128u8` as `i8` is `-128`, and `0 + -128` also gives `-128`), so it does not
separate them. The separating pin is `1i8 + 128u8`: the right reading clamps to
`127`, the wrong one computes `1 + -128` = `-127` in range. The corpus carries both.
* **`count_ones`, `leading_zeros` and `trailing_zeros` are the modelled calls whose
result width differs from their operand's** (`u8::count_ones` returns `u32`). The
model builds the count at the operand's width and zero-extends it to the
destination's; the executor reads the destination's width for exactly this reason,
and the `eval` signature takes the operand width and the result width separately.
Every other shape passes the same value for both, so the change is inert outside
these three. The three complement counts widen the same way.
* **`saturating_neg` and every `abs` do not exist on the unsigned types**, while
`wrapping_neg`, `checked_neg` and `overflowing_neg` do -- where negation is modular
and the failure case is `x != 0`. So `is_modelled` reads the sign for the unary
operators rather than assuming one, and the unsigned `neg` families are modelled
rather than refused. This is the one place the four families have different
*membership*, not just different definitions.
* **`MIN` is where the four families separate, and the model has no `MIN` special
case anywhere.** `neg` and `abs` share the `0 - x` core; `wrapping_*` return `MIN`
there because `0 - MIN` wraps, `saturating_*` clamp to `MAX` through the same
overflow predicate, `checked_*` return `None` through it, and `overflowing_*`
report it as the flag. One expression plus one predicate, four answers -- so the
four cannot drift apart.
* **An off-by-one in `leading_zeros` was caught by the exhaustive walk.** Counting
`x < 2^k` from `k == 1` reports `w - 1` for `x == 0`, where `core` reports `w`.
That is one wrong input out of `2^w`, and it is exactly the input the corpus
tripwire names -- a sample-based test would have missed it.
* **The `overflowing_*` return is a `(T, bool)` whose components a modelled call
writes *field by field*, and the `ret.N` reader had to learn that.** A literal
`_0 = (a, b)` stores components under `Proj::Index`; a modelled call writes
`_0.0`/`_0.1` under `Proj::Field`. `Env::get` already met both spellings, but two
other readers did not: the return-component collector read `elems` only, and
`Env::get` itself returned `Unknown` early for a local with no whole value before
ever consulting the projected store. The symptom was a `ret.1` contract refused as
"the return type is an aggregate, so `ret` has no single value" -- a message about
the wrong problem, since the answer was to read the component, not to give up on
it. Both readers now go through `get`.
* **`overflowing_div`/`overflowing_rem` panic on a zero divisor and are refused.**
The flag reports `MIN / -1`, which makes the family look like a total form of
division -- and the previous session modelled it as one. A differential test
against `core` is what exposed it: `7u8.overflowing_div(0)` *unwinds*, it does not
return `(_, true)`. So the flag is not the whole failure predicate, and treating
the call as total would have let a function that divides by zero be *proved
panic-free*. `is_modelled` now admits only `checked_div`/`checked_rem`, and the
corpus records why.
**Evidence for the mixed-signedness additions.** `scripts/test-count.sh` **755 ->
760** passed, 0 failed; `scripts/gate.sh` **ALL GATES GREEN**; clippy (`--all-targets`
and the `no_std` half) and rustdoc clean; zero dependencies and `no_std` untouched.
Five new unit tests walk both directions over the whole `u8`/`i8` domain against
`core`'s own methods — the differential test is the oracle, not a copy of the model —
and the corpus gains eight fixtures (six verify, two are the `overflowing` flag pinned
in both directions). The model was wrong twice on the first cut and both were caught
by the exhaustive walk rather than by a sample: the flag used the self operand's sign
instead of the addend's (caught at `i8::add_unsigned`), and the saturating clamp used
the unsigned maximum for a signed self (caught at `0i8 + 128u8`). Each corpus pin was
checked for teeth by flipping its expected value: `overflowing_add_signed_within_range_is_not_overflow`
is the one the bare-carry model refutes, and `saturating_add_unsigned_top_bit_tripwire`
is the one an addend-signedness swap refutes.
`wrapping_div`/`wrapping_rem`/`saturating_div`/`saturating_rem` are *not* reachable
by design, because they panic on a zero divisor and modelling them as total would
hide that panic; `overflowing_div`/`overflowing_rem` join them for the same reason.
`pow` and the mixed-signedness additions are now modelled, so neither is a reachable
gap. `rotate_*` and `abs_diff` were gaps when this was written and are modelled now
(see C6 in `ROADMAP.md`), and so are the remaining total value methods -- `signum`,
`reverse_bits`, `swap_bytes`, `to_be`/`to_le`, the ASCII case conversions and
`is_multiple_of` -- plus the Euclidean pair (`div_euclid`/`rem_euclid`) and
`div_ceil`, which are value-and-panic pairs because each panics on a zero divisor.
Three facts cost time here and are worth keeping: `swap_bytes` is a rotation by
`w/2` *bits*, not `w/2 * 8` (the differential test caught the first cut);
`div_euclid` adjusts the truncating quotient *away* from zero when the remainder is
negative, which is the opposite of the natural reading (also caught by the test);
and `core` has no `to_ne` *value* method, only `to_ne_bytes`, so the byte-order
model has two variants and not three. The `next_multiple_of`/`div_*` helpers and
the `_bytes` byte-order forms (which return an array, not an integer) remain
reachable and unmodelled. The bit-count proofs do **not** go in `verif-arithmetic`: their oracle here is Rust's own method, checked
exhaustively over the whole operand domain, which is a stronger oracle than a
small-domain enumeration would be. A third engine with less coverage is not a proof,
so the split the roadmap proposed is not made.
**Ordering rationale.** Stage 1 first because it is the *class* of bug, not one
bug; doing Stages 2–4 first multiplies the call sites that can forget the sign.
Stage 2's enum item before Stage 3 because an enum match appears in almost every
real function and the slice-index case appears in almost none. Stage 4 last
because it is additive coverage with no soundness content.
**Standing tripwire rule for every stage.** A new shape is not "supported" until
there is a corpus entry that *verifies* and a tripwire that *fails*. The tripwire
is the evidence: a shape that only ever verifies is a shape whose model has never
been contradicted.
## Ferrocene gate: what was verified end to end
The Ferrocene work landed as three commits on `license-arith-mir-oracle` (PR #3):
- `af8818e` — the gate itself: `tools/ferrocene/run.sh` (exit 0 built / 1 real failure /
2 no toolchain), `criticalup.toml`, `tools/ferrocene/README.md`, gate 3 in
`scripts/gate.sh`, and the `ferrocene` job in `.github/workflows/ci.yml`.
- `18681e1` — `examples/bare_metal.rs`, the `#![no_std]` `lib` example that *calls the
decision procedure*, so the qualified compiler builds the prover itself and not just the
types around it. Wired into gate 4 and `run.sh`; `test = true` so the host verdict tests
actually run. Test count 463 -> 466.
- `5bed9d4` — the token goes to CriticalUp on stdin, not as an argument, so it never
reaches the process table.
Verified, not assumed:
- Full `scripts/gate.sh`: **12/12 green** on the final head.
- `run.sh` exercised in all three modes: no toolchain (exit 2, reports and skips), stable
rustc named via `FERROCENE_RUSTC` (exit 0, all three builds), bad path (exit 2).
- `examples/bare_metal.rs` builds for `thumbv7em-none-eabihf` with `--no-default-features`,
and its three host tests pass (proved / refuted / refused).
- `actionlint` clean on `.github/workflows/ci.yml`.
- CI on `5bed9d4`: **all seven jobs success**. The `ferrocene` job ran and reported its skip
rather than passing quietly — steps 5 and 6 `skipped`, step 7 emits the `::warning::`
annotation, log reads "No FERROCENE_TOKEN secret; skipping the qualified-toolchain build.
This is reported, not passed: the gate did not run." The token is masked (`token: ***`).
`cargo test --workspace` *without* `--features std` fails in `src/smt.rs` lib tests
(`std::panic::catch_unwind`). That is pre-existing — confirmed identical on a stashed tree —
and this repository only ever runs tests with `--features std`.
What Ferrocene does *not* buy, stated in the README, the tool's README and here: a qualified
compiler is not a qualified verifier, and `verif`'s engine is outside Ferrocene's
qualification scope. The gate checks the qualified compiler accepts the sources unchanged.
## Stage 3, first half: a contract may name a local that aliases an argument
The roadmap's Stage 3 listed two refusals. The smaller one — `a[k]` where `k` is a
local — turned out to be a misdiagnosis, and the misdiagnosis is the interesting
part.
The entry was documented as "there is no variable to build a chain for `k`", with
`k` assumed to be a local the contract language could not reach. rustc prints no
local for `k` at all. `let k = i;` where `i: usize` is `Copy` lowers to *no
instruction*: `a[k]` is `_1[_2]`, and the name `k` survives only as a scoped
`debug k => _2;` inside `scope 1`. So the body already used the argument as the
index; only the contract text had `k`. The fix is to resolve the name, not to bind
anything.
**The parser could not see it.** `MirFn::local_names` keeps the *first* `debug`
binding per local, and that rule is load-bearing: a scoped `debug s => _1;` after
`let s = a;` would otherwise rename the parameter `a` to `s`, and a contract
saying `a <= 127` would find only `s` and be skipped. Keeping the first binding is
what makes `a` keep meaning `a`. But it means the scoped binding for `k` is
dropped, so `k` reached the contract parser as nothing.
`MirFn::debug_aliases` now keeps every binding, in printed order, and
`MirFn::alias_locals` decides which ones may resolve. A name resolves only when
all four hold:
* the aliased local is an argument — never a temporary;
* the body never writes that local;
* the name is not already an argument's own name, so an alias cannot shadow a
parameter; and
* the name does not alias two different arguments.
The `written` set is collected from the *parsed blocks* rather than from the text,
so it is the parser — which alone knows which lines became statements — that
decides. This is what makes the rule sound on the dump alone rather than on an
assumption about what rustc prints today.
**The divergence case, measured.** `let k = i; i = 2;` does *not* print
`debug k => _2;`. rustc materialises a real local (`let _3: usize;`) and prints
`debug k => _3;`, so `k` is not an argument alias and is refused — correctly, and
for a reason the frontend can see rather than one it has to be told. The
`written` check still has to exist for the case where rustc *does* print the
alias against a written argument, which is a dump shape this frontend must not
trust. A parser-level unit test constructs exactly that dump and asserts the name
is withheld, so a refactor cannot drop the check unnoticed.
**Sign flow.** The alias names go into both `arg_vars` and `signed_args`. The
second matters as much as the first: a signed `i` aliased as `k` must make `k < 0`
a signed comparison, which is the class of bug the three-case `Sign` type exists
to prevent.
**Evidence.** `array_local_index_through_alias` verifies and
`array_local_index_tripwire` fails with a witness that pins the index — which only
happens if `k` resolved to the real index variable. `array_local_index_written_refused`
pins the divergence gate. Two parser unit tests pin the alias rule and the
`written` gate with no nightly needed. Coverage went from **44/67 to 45/69**, and
the test count from 466 to **470** (two parser unit tests, one integration test,
and the renamed corpus entries). Full `scripts/gate.sh`: **12/12 green**.
The slice half of Stage 3 landed in the same branch. Its own section above records the
soundness hole the original roadmap note had — an index-only bound is not enough, because
the chain must be exact for *every* index the slice holds, which needs `len <=
MAX_INDEX_CHAIN` as a second obligation — and the machinery that closes it.
## Stage 3 — enum discriminants are rustc's values, not declaration positions
The enum model numbered variants by their position in the declaration. That is
right for the common case and wrong the moment the source gives an explicit
discriminant, and the wrongness is a *false proof* rather than a refusal, because
the `match` arm constants come from rustc while the contract's variant constant
came from this reader.
**The bug, measured.** `pub enum Gap { A, B = 3, C }` gives `C` the discriminant
`4`. The reader dropped the `B = 3` line (it matched no known shape), so its
layout became `[A, C]` with `C` at position `1`. A contract `requires: g ==
Gap::C` then pinned the tag to `1`, the body's `switchInt` compared against the
real constants (`0`, `3`, `4`), and the contract landed on the `B` arm. The
tripwire `enum_explicit_discriminant_tripwire` — which claims the `B` arm ran —
was **verified**, i.e. a false contract proved. Before the fix the corpus read
`decided 46 of 74` with both new tests failing; after, `49 of 78` with both
refuted.
**Three places carried the position, and all three moved to the discriminant.**
`EnumDef.variants` is now `(name, payload, discriminant)` and `index_of` returns
the stored discriminant; `tag_width` is the largest discriminant's width (three
bits for `4`, not the two a count of three gives); and the tag's assumed domain
is the *disjunction of the discriminants* rather than `tag < count` — because an
assumed bound that is *false* for a real input is the unsound direction, it can
make a proof vacuous. Payload seeds are keyed by discriminant too, matching what
a `Downcast` projection carries.
**An unreadable discriminant refuses the whole layout.** Only a literal is read
(decimal, `0x`/`0b`/`0o`, optional type suffix). `B = 1 << 4` is not evaluated:
dropping the variant would shift every later discriminant and guessing one would
put a contract on the wrong tag, so the enum is dropped from the map entirely and
a contract naming any of its variants becomes a refusal. The literal reader
requires the *whole* remainder to be digits, so `1 << 4` is refused rather than
silently read as `1`.
**Two built-in hazards closed at the same time.** A qualified name
(`Shadow::Some`) now resolves against the *declared* layout first, so a user
`enum Shadow { Some, None }` is not mistaken for `Option` — pre-fix,
`enum_user_variant_not_option_constructed_tripwire` was **verified** because the
built-in `Option` numbering put `Some` on tag `1`. And a qualified name whose
qualifier is not a declared enum *and* not one of the two built-in enums
(`Option`, `Result`) is refused rather than answered by another layout that
happens to share the variant name. (The built-in case is the follow-up in the
next section: a qualified `Option::<u8>::Some` must still resolve, and a
declared layout must still win over it.)
**Evidence.** Four corpus entries: `enum_explicit_discriminant_selects_by_tag`
(verifies) with `enum_explicit_discriminant_tripwire` (refuted), and
`enum_user_variant_not_option` / `..._constructed` (verify) with their two
tripwires (refuted). Eight unit tests pin the parser and the layout reader with no
nightly needed, plus two integration tests pinning the earlier array-spelling
work. Coverage went from **45/69 to 49/78**, the test count from 470 to **480**.
## Stage 3 follow-up — three reader bugs a review found after the discriminant landed
The discriminant work above fixed the *value* a variant has. Three defects in the
same reader survived it, and all three fail in the same direction: a function
that should have been checked is instead dropped from the check set or refused,
and the user is never told. They were found by review, then reproduced against the
real code before anything was changed.
**1. A refused one-line enum swallowed everything after it.** `enum_head` returns
the parsed head of an `enum` line. For a one-line body whose discriminant is
unreadable (`pub enum E { A, B = 1 << 4 }`) it returned "a multi-line body
follows" — but the closing brace was already on that line. The caller then opened
an enum *cursor*, and every following line, including `///` contracts and the `fn`
items they belong to, was consumed as enum contents. Those functions had no
contract at all, so they were neither verified nor reported as skipped: they
silently left the check set, which is the worst failure mode a verifier has. The
head is now a three-way enum — `Inline(variants)`, `MultiLine`, `Refused` — and
`Refused` drops the layout *without* opening a cursor. The multi-line path already
closed its cursor at the brace; the one-line path now does too.
**2. A qualified standard construction resolved to nothing.** rustc prints a
standard construction with its generic arguments: `let o: Option<u8> =
Option::<u8>::Some(9)` lowers to `_1 = Option::<u8>::Some(const 9_u8)`. The
qualifier branch split the name on `::`, so the segment before the variant was
`u8` — the generic argument, not the enum — and `enums.get("u8")` found no layout.
The construction became an unmodelled read and the `match` an *unmodelled switch
discriminant*, losing a shape the unqualified spelling (`Some(9)`) handles. The
fix strips balanced `<…>` generic arguments before splitting, so the qualifier is
`Option`. Since no source file declares `Option` or `Result`, those two qualifiers
now resolve to the fixed numbering (`Some`/`Err` = 1, `None`/`Ok` = 0), but only
*after* a declared layout has had its chance — so a user `enum E { Some, None }`
still wins over `Option`'s numbering.
**3. A trailing line comment erased the whole enum layout.** `B = 3, // special`
puts the comma *before* the comment. The variant reader trimmed a trailing comma
off the raw line, but the line now ends in the comment, so no comma was trimmed
and `3, // special` went to the discriminant reader, which rejected it — and a
rejected discriminant drops the *entire* layout. Every contract naming a variant
of that enum then became a refusal. The comment is not part of the variant, so it
is stripped first, with string and character literals tracked so a `//` inside one
is not mistaken for a comment.
**Evidence.** Four corpus entries: `option_qualified_some_payload` and
`enum_trailing_comment_keeps_the_layout` (verify) with their tripwires (refuted),
plus six unit tests and two integration tests. Coverage went from **49/78 to
51/82**, the test count from 480 to **488**. Each fix was checked for teeth by
reverting it and watching its test fail: without fix 1 the contract after a
refused enum is gone (`by_fn` is empty); without fix 2 the qualified construction
is `incomplete (1 reason) - unmodelled switch discriminant`; without fix 3 the
layout is dropped and the contract is `skipped: unknown name`.
## A one-line struct body swallowed every function after it
The struct cursor had the same defect as the refused one-line enum above, in the
mirror image. `struct_head` accepted *any* line containing `{` and opened a
multi-line field cursor. For a body that closes on the head line
(`pub struct B { pub lo: u8 }`) there is no closing brace left to read, so the
cursor stayed open and every following line — the `///` contracts and the `fn`
items they belong to — was consumed as a struct field. The functions then had no
contract at all, so they were neither verified nor reported as skipped: they
silently left the check set, the worst failure mode a verifier has. The enum
reader has distinguished an inline body from a multi-line one all along
(`EnumHead::Inline`); the struct reader did not.
`struct_head` now returns `(name, closed_inline)`, and the caller reads a
one-line body's fields out of the head line (splitting on top-level commas, the
same helper the enum path uses) instead of opening a cursor. A multi-line body
still opens one. Found while probing the signedness-recording paths: a struct
field read is one of them, and the probe file's `decided 0 of 0` — no functions
at all — was the tell.
**The bug also made a test vacuous, and that is the deeper lesson.** The existing
`a_whole_struct_assignment_invalidates_its_fields` used a one-line struct, so its
function was dropped and `let Some(o) = verify_src(..) else { return }` returned
early — the test passed without checking anything. A drop is *silent* in a way a
failure is not. So `verify_src` in `tests/mir.rs` is now strict: it returns `None`
only when no nightly `rustc` is configured, and panics if a named function with a
contract is absent from the report. That converts the whole class of
"the frontend dropped it and the test shrugged" into a failure, across all 23
tests that use the helper, rather than fixing one call site.
**Evidence.** Two unit tests (`a_one_line_struct_does_not_swallow_the_next_contract`
at the spec level, `a_one_line_struct_does_not_swallow_the_functions_after_it`
end to end) plus the strict `verify_src`. Sensitivity was checked by reverting the
caller to always open a cursor: the spec test fails with `structs` empty. Coverage
held at **133/226** (no corpus file uses a one-line struct, so no live result
moved); test-count **514 to 516**. Gate green.
## A contract above a struct leaked into the next function
The `struct_head`/`enum_head` branches in `spec::extract` matched their line and
`continue`d *without* clearing the pending contract. The catch-all at the bottom of
the loop clears `pending` on "any other non-comment line", precisely so a contract
attaches to the item it was written above — but the struct and enum heads `continue`
before reaching it. So a doc comment above a struct or enum carried over to the next
`fn`, and the two contracts were merged.
**This was a false proof, not just a wrong refusal.** A leaked `requires` restricts
the inputs the postcondition is checked for, so it can only make a proof *easier*:
`requires: x == 0` above a struct made `ensures: ret == 0` for a body returning `x`
verify — the check was made only at `x == 0`. The identical function and contract
with no struct above it is refuted at `x == 1`. A leaked `ensures` was caught by the
existing vacuous-precondition detector (it made the merged precondition unsatisfiable,
`x > 100 && x < 50`), so the satisfiable direction is the one that slipped through —
and the satisfiable direction is the false proof.
The fix is one line at each head: `pending = FnContract::default();`, the same
assignment the catch-all already performs. The comment says why: a contract must
attach to the item it was written above.
**Evidence.** Two unit tests (`a_contract_above_a_struct_does_not_attach_to_the_next_function`,
`..._an_enum_...`) and a corpus test with a tripwire/control pair
(`leaked_requires_tripwire` with a struct above it, `leaked_requires_is_dropped`
without); both must be refuted. Sensitivity was checked by reverting the two resets:
the corpus tripwire *verifies* — the false proof — and the unit tests fail with the
leaked `["x == 0"]` visible in `f`'s requires. Coverage **133/226 to 133/228**
(the two new corpus functions are tripwires, so `decided` is unchanged); test-count
**516 to 519**. Gate green.
## Two names of different signedness are refused, not decided
The signed-constant refusal above closed the case where a *constant* meets an
unsigned name. The same mistake with two *names* was still decided. `a > b` for an
`i8` and a `u8` is `E0308: mismatched types`, and the reader picked signed
(`ls || rs`). That is a real reading and not a false proof, but it is a reading of a
program rustc rejects — and it opened a hole between the contract and the body: the
body reads each operand at *its own* signedness, so a contract saying `a > b` (signed)
and a body doing `ule(b, a)` (unsigned) could disagree about the same comparison.
The body's reading decides the verdict, so the contract could be checking a different
relation than it appears to.
`refuse_signed_const_vs_unsigned_name` became `refuse_mixed_signedness`: when the two
operands differ in signedness and *neither* is a constant, the shape is refused with
"operands of different signedness cannot be combined". A constant/name mix keeps the
original message. Both are `skipped` — a refusal, never a verdict — which is the core
invariant: a program rustc rejects is "the tool could not run", not "the code is
wrong".
**The check is narrow, and the narrowness is the test.** Two names of the *same*
signedness still compare; a name against a literal of either value still reads; and a
shift is exempt, because Rust lets the shift amount have its own type (`a << b` with
`a: i8, b: u8` compiles). The unit test enumerates every operator where two operands
meet, both orders, plus the legal counterparts, so a fix that refused too much would
fail it.
**Evidence.** A unit test (`two_names_of_different_signedness_are_refused`) and a
corpus test with two refused entries and a same-signedness control
(`contract_same_signedness_compare_still_reads`). Sensitivity checked by deleting the
two-name branch: the corpus entry gets a verdict (FAILED) instead of `skipped`, and
the unit test fails. Coverage **133/228 to 134/231** (the control verifies; the two
refusals are skipped, as they must be); test-count **519 to 521**. Gate green.
## An untyped constant in an equality is refused — the `==` half of the sign guess
The `Sign` model above refuses a sign-ambiguous operand at `>>`, `/`, `%`, an
ordering comparison, and a widening cast. It left `==`/`!=` readable, on the
reasoning that they "compare bit patterns" and so do not care about the sign. That
reasoning is wrong when the two readings are different *values* rather than a
different ordering of one.
`!0` has no type of its own. Rust types an untyped constant as `i32`, so `!0` is
`-1` and **`!0 == 255` is `false`**. The reader carries the complement as a bit
pattern at the *scope's* width, so for any function with a `u8` in scope it built
`255u8 == 255` — **true** — and discharged `ensures: !0 == 255` for a body returning
`x`. A false proof, and a family of them: `!4 == 251`, `(!0 << 1) == 254`, all
`verified` while Rust calls them false.
The fix: an `Opaque` operand with *no typed partner* is refused at **every**
comparison, not only the ordering ones. The rule is now uniform — no typed operand
means no recovered type means no verdict. Two bare literals stay unambiguous
(`2 == 2` reads), and any typed operand fixes the reading (`x == !0` is `x == 255`,
which verifies).
**Evidence.** Unit assertions in `a_bang_literal_is_refused_where_its_sign_would_change_the_meaning`
(`!0 == 255`, `!0 != 255`, `!4 == 251`, `!0 == !0` refused; `2 == 2`, `x == 0`,
`x == !x` read) plus a corpus test with a tripwire
(`contract_untyped_complement_equality_is_refused`) and a typed-partner control
(`contract_complement_of_literal_with_typed_partner_reads`). Sensitivity: with the
branch reverted the tripwire is `verified` — the false proof — and the test fails.
Coverage **134/231 to 135/233**; test-count **524 to 526**.
## Unary `-` on an unsigned operand is refused
`-x` for an unsigned `x` is `E0600: cannot apply unary operator `-` to type `u8``.
The reader modelled it as `0 - x` at the operand's width — a value Rust never
produces — so `requires: -x >= 0` for a `u8` was read as satisfiable and the function
was decided on a program rustc rejects. `parse_neg` now refuses a `Sign::Unsigned`
operand. A bare literal is untyped (Rust defaults it to a signed `i32`) and a signed
name is legal, so `-5` and `-x` for an `i8` still read; `-x as u8` for a signed `x`
is the only spelling rustc accepts and it still parses.
The refusal broke an existing test (`a_negation_binds_tighter_than_a_cast`) that
parsed `-x as u8` with an *unsigned* `x` to check that `-` binds tighter than `as`.
That test's own docstring already noted rustc rejects the shape — it was testing
precedence on an illegal program. The test now uses a signed `x` (which checks the
same precedence legally) and asserts the unsigned case as a refusal.
**Evidence.** Unit assertion in `a_negation_binds_tighter_than_a_cast`, a corpus test
with a tripwire (`contract_unsigned_negation_is_refused`) and a signed control
(`contract_signed_negation_still_reads`). Sensitivity: with the branch deleted the
tripwire is `verified` and the test fails. Coverage **135/233 to 136/235**;
test-count **526**.
## A widened constant fills from the value it *denotes* — the false refutation, and the false proof it hid
`resize_const` decides how a widened constant fills its new high bits. The fill has to
follow the value the constant **denotes**, and that is a three-way question the model
already answers with `Sign`: a bare literal is non-negative (zero-extend), a typed
signed constant is two's-complement (sign-extend), and an **opaque** constant (`!0`, a
fold) takes the **operand's** sign, because that is the type Rust infers for it.
Two opposite failures lived in the one line that decided this.
**The false *refutation*.** Filling from the operand's sign (`signed`) instead of the
constant's own made a bare literal sign-extend. Rust's `(255u8 as i16)` is `255`, so
`ensures: (x as i16) == 255` holds for every `u8` `x`; the reader sign-extended the
literal to `65535` and **refuted** it:
```
/// requires: x == 255
/// ensures: (x as i16) == 255
pub fn f(x: u8) -> u8 { x }
```
```
f FAILED postcondition — v1:u8 = 255 <-- false refutation
```
**The false *proof* it hid.** Switching the fill to the constant's own sign fixed the
literal, but an *opaque* constant is exactly the case where the operand's sign is the
right one: Rust infers `!0` as the operand's type, so `!0` against a `u16` is `65535`.
Holding it at the scope's width (`255`) and zero-extending *verified*
`ensures: (x as u16 + !0) == 255` for a value Rust calls `65535`. The signed case fails
the same way whenever the literal's top bit is clear: `!128` against an `i16` is `-129`,
but `0x7F` sign-extends to `127` and *verified* `== 127`. Only a complement whose top
bit is set (`!0`) happens to survive sign-extension, and that is not worth a special
case, so an opaque widening is **refused outright**.
**A fold is not opaque.** `200 + 100` is a *value*, not a width-dependent bit pattern,
so a fold of bare literals is emitted at the narrowest width that holds its exact result
and may widen exactly like a literal — `x as u16 <= 200 + 100` still reads. A fold that
*touches* a complement (`!0 + 2`) is a different thing: `!0` is the operand-width value,
so `!0 + 2` is width-dependent, and it is emitted narrow and carried as `Opaque`, so a
later widening is refused. (Emitting an opaque fold at the engine's full width instead
made every later resize a *truncation*, which *verified* `ensures: (x as i16 + 2) == !0 +
2` for `257 == 1` — a false proof.) The refusal is therefore narrow: only a width-dependent
constant, whether a bare complement or a fold that touched one.
**Evidence.** Unit tests `a_literal_widened_to_a_signed_operand_zero_fills` and
`an_opaque_constant_widening_is_refused_but_a_fold_is_not`; corpus tests with controls
(`contract_literal_widened_to_signed_zero_fills` verifies, `..._tripwire` for `254`
FAILs; the two `contract_opaque_widened_*_is_refused` entries must not verify;
`contract_fold_widens_to_unsigned_reads` verifies). Sensitivity: reverting the fill to
`signed && wide > w` brings the false refutation back, and deleting the refusal brings
*both* false proofs back (`verified` on a Rust-false equality). Coverage
**137/237 → 138/240**; test-count **528 → 530**. Gate green.
## The complement refusal was too wide — three valid shapes it dropped
Refusing an `Opaque` operand wherever the two readings differ is the sound direction, but
three of those refusals were drawn where the readings do **not** actually differ, so they
dropped postconditions Rust accepts. Each is the same mistake — a *conservative* refusal
that should have been a *narrow* one — and each is fixed by asking whether the reading is
ambiguous at that specific operator, not whether the operand is `Opaque`.
**A right shift by zero is the identity.** `!0 >> 0` is `!0` under both readings, so the
operand is unambiguous. `parse_shift` refused *every* right shift of an `Opaque` operand
before checking the amount, so `ensures: ret == (!0 >> 0)` (with `requires: ret == 255`)
was dropped. The `k == 0` case now returns the operand unchanged, keeping its `Opaque`
sign until the surrounding expression fixes a type.
**A division with a *typed* partner is not ambiguous.** The `/`/`%` guard tested
`!(sgn.eval() || rs.eval())`, and `eval()` is `false` for *both* `Unsigned` and `Opaque`.
So an unsigned name beside `!0` — `x / !0` for a `u8` — looked like a pair with no typed
operand and was refused, though `x`'s unsigned type fixes the reading (`!0` is `255`).
The test is now `Sign::resolve(sgn, rs).is_none()`: only a genuinely untyped pair
(`!0 / !1`) is refused.
**A complement *masked* to a width-independent value widens exactly.** `!0 & 1` is `1` at
any width, so `(x as u16) == (!0 & 1)` holds. The masked result was carried as `Opaque`,
so the widening was refused. `parse_bitand` now marks the result `Literal` (a
width-independent value that may widen) when either operand is a bare literal and the
pair is not signed — `&` keeps only the mask's low bits, which do not change with width.
A signed partner is excluded, because `x & 128` for an `i8` keeps bit 7 and is negative.
**Evidence.** Corpus entries `contract_complement_shift_by_zero_reads`,
`contract_complement_division_with_typed_operand_reads`,
`contract_complement_mask_widens_exactly` (all verify) against the still-refused
`contract_complement_fold_widening_is_refused`, in test
`a_complement_fold_widening_is_refused_but_masks_and_shifts_read`. Sensitivity: reverting
the `k == 0` branch drops the shift entry to `skipped`; reverting the `resolve` test drops
the division entry; reverting the `parse_bitand` mark drops the mask entry.
## A suffixed literal keeps its type — the mismatched constant pair that was decided
The tokenizer *dropped* a numeric literal's type suffix: `0u8` and `0` became the same
`Tok::Num(0)`. The reader therefore could not see that `0u8` is unsigned, and a
comparison of two constants of different signedness had no unsigned side to refuse.
`refuse_mixed_signedness` refuses a signed constant against an unsigned operand, but its
`mixed` clause required *exactly one* side to be a constant — the case of a signed
constant meeting an unsigned *name* (`x == -1` for a `u8`). Two *constants*
(`-1 <= 0u8`) fell through the clause and were read as a **signed** comparison and
silently decided. `-1 <= 0u8` is `E0277` in Rust (a `u8` cannot be negated), yet the
reader *verified* `ensures: -1 <= 0u8` by reading it as `-1 <= 0`. A whole family
followed: `-1 == 0u8`, `-1 < 0u8`, `0u8 > -1`, `-1i8 == 0u8`, `-1 <= (0u8 + 0u8)`.
The suffix is now kept as the literal's *type* — `Tok::Num(u64, Option<(u8, bool)>)`,
`(width, signed)` — so the unsigned side is visible and the literal is sized from its own
suffix, and the refusal covers the both-constants case — a signed constant cannot adopt an
unsigned operand's type whether the other side is a name or a constant. Valid pairs still
read: two constants of the same signedness (`-1i8 <= 0i8`), a bare literal against either
(`-1 <= 255`, `255u8 == 255`), and the ordinary cases.
**The width half of the same token.** Recording only the sign left the *width* to the
scope, and that was a false proof: `128i16` became the 8-bit `0x80` when only `u8` names
were in scope, and `128i16 as i32` sign-extended it to `-128`, *verifying*
`ensures: 128i16 as i32 == -128` — false in Rust. A suffixed literal is now built at its
own width and range-checked against the suffix; the true counterpart
(`128i16 as i32 == 128`) verifies, so the fix is not "refuse every suffixed literal".
When a bare literal meets a suffixed one, the *bare* one widens to the suffixed one's
width (`align_widths` picks the non-`Literal` side), which is what keeps `128i16 as i32
== 128` readable instead of narrowing the 32-bit cast down to eight bits.
**Evidence.** Unit tests `a_suffixed_literal_carries_its_type_signedness` and
`a_suffixed_literal_is_sized_from_its_suffix_not_the_scope` (the invalid pairs refused,
the valid ones read). Sensitivity: dropping the suffix again makes `-1 == 0u8` and its
siblings silently decided and fails the test; sizing from the scope again makes the
`128i16 as i32 == -128` corpus entry verify. Test-count **531 → 534**; corpus coverage
**138/240 → 142/246**.
## Toolchain — edition 2024 and the MSRV floor (1.85)
Both manifests are **edition 2024** with `rust-version = "1.85"`. The two numbers
are one decision, not two: cargo refuses edition 2024 on any compiler below 1.85,
and 1.85 is the release that stabilised it, so there is no version that takes the
edition without the floor. Raising one means raising the other.
The floor is a *lower* bound, not a pin. The crate is exercised on current stable
(1.99 at the time of writing) and the MIR frontend runs a nightly. The oracle
toolchains move independently and none of them forces the floor down: Verus tracks
stable (`channel = "1.99.1"`), Kani tracks a nightly (`nightly-2026-10-23`), and
Ferrocene — the qualified compiler, whose lag is the only one that could matter
for a safety build — is downstream of Rust 1.96. 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, because it locks out qualified
and long-term-support toolchains that lag upstream.
**The migration was three edits, all found by compiling rather than by reading:**
1. `examples/verusdiff.rs` — `filter(|(_, &l)| …)` is rejected in edition 2024
("cannot explicitly dereference within an implicitly-borrowing pattern"); it
becomes `filter(|&(_, &l)| …)`.
2. `tests/loopdiff.rs` — `gen` is a reserved keyword in edition 2024, so `fn gen(`
was renamed to `fn make_steps(`.
3. `verif-arithmetic/src/prove.rs` — three `.map_or(true, |c| …)` calls became
`.is_none_or(|c| …)`. This one is *caused by the MSRV bump*, not by the
edition: clippy only suggests `is_none_or` (1.82+) once `rust-version` permits
it, so the lint appears exactly when the floor moves. Worth knowing before
touching `rust-version` again.
**The floor is now a gate, not a claim.** `scripts/gate.sh` step 13 builds with
`1.85` (overridable via `VERIF_MSRV`) so a feature newer than the floor fails
in CI rather than in a downstream build. It follows the Ferrocene/Kani convention:
an absent toolchain, or a `thumbv7em-none-eabihf` target not installed *for that
toolchain*, is reported and skipped rather than folded into a pass. CI installs
both the 1.85 toolchain and that target for it so the gate actually runs. The gate
numbering is now **16 steps**; it was 13 when this note was written, and three steps
were appended without renumbering the earlier ones (so the "gate 3/4/9" references
elsewhere still name the same gates).
Step 13 *builds* on the floor; it also now *runs* the frontend there. `cargo check`
only proves the crates compile on 1.85 -- it says nothing about whether the MIR
frontend still works, and the frontend reads rustc's textual MIR, whose shape is not
stable across toolchains. A `const` that folds to a literal prints inline on current
stable and as a CTFE brace-block on 1.85, so a parser that knew only the inline shape
passed every gate above and silently dropped the item on the floor. Step 13 now sets
`VERIF_RUSTC` to the floor rustc and runs the frontend's own suite
(`cargo +$MSRV test --features std --test mir`) so a toolchain-shaped gap fails here
rather than being discovered downstream. See "A `const` printed as a CTFE brace-block
on 1.85" below.
The three appended steps hold the *tree* rather than the logic, and each closes a
recurrence rather than a one-off:
- **Step 14: rustdoc builds both crates with `-D warnings`.** The crate is
`#![deny(missing_docs)]`, but that only checks that a doc comment *exists* -- it says
nothing about whether an intra-doc link still *resolves*, and `cargo test` and `cargo
clippy` never run rustdoc. Four warnings had shipped: `mir/spec.rs` linked a renamed
`bind`, and `smt.rs` linked three private items (`pinned_vars`, `EvalMemo`, `eval_term`)
from public docs. `verif-arithmetic` had the same class (`prove.rs` linked its
private `forall_pair_bounded` from three public items), which is why the step checks
both crates and not just the parent. `verif` is built *three* ways -- default
(`no_std`), `--features std`, and `--all-features` -- because the doc surface differs
between them: a link to a `#[cfg(feature = "std")]` item resolves in the last two and not
the first, which is how `smtscript` shipped an unresolved link to
`Query::to_smtlib2` that only the default build could see. docs.rs publishes the
default build, so `[package.metadata.docs.rs] all-features = true` makes the published
docs the union instead.
- **Step 15: no compiled output is tracked.** `git ls-files` must not list a `.rlib`,
`.rmeta`, `.o`, `.bc`, `.d`, a `target/` path or a `__pycache__` path. This recurred:
a cleanup commit untracked six root `.rlib`s the oracle runs had left behind, and the
next `git add -A` put them straight back. A `.gitignore` cannot help -- ignore rules
are consulted only for *untracked* paths -- so the fix is a check, not a pattern.
- **Step 16: the `unsafe` surface is pinned and justified.** `SECURITY.md` told a reporter
there were *three* `unsafe` blocks in `src/`; there are two, and the paragraph named only
`smt.rs` while `sat.rs` held the second. A count in prose is a claim like any other, and
this one is security-relevant, so it is checked: the gate fails unless there are exactly
two `unsafe {` blocks, each preceded by a `// SAFETY:` in its contiguous comment block
(not a fixed number of lines -- the justifications here run to several).
## The bit-blaster walked a DAG as a tree, and no budget noticed
`wrapping_pow` at a *symbolic* exponent hung. Not slowly: the query never returned, so
`prove` printed no verdict at all, which the previous section already established is worse
than any verdict. The shape is small -- `u4`, one base variable, one `u32` exponent -- and
the arena stayed nearly empty, so nothing in the existing guards fired.
The cause is a mismatch between how the term is *built* and how the blaster *walks* it.
`pow` is a 32-step fold, and every step rebuilds the running product from the same shared
subterms, so the term is a DAG with heavy sharing. `blast` recurses as if it were a tree:
it visits a shared subterm once per path to it. For a 32-step fold that is up to 2^32 paths
through a graph of a few hundred nodes. Instrumenting the walk confirmed it directly --
u4 needed **more than 10^8 visits** to finish, and the count was identical for the BDD pass
and the SAT pass because both recurse the same way. That is not a slow answer; it is a hang,
and the query never reaches the code that would have fallen back.
Two plausible explanations were checked and were wrong before the right one landed:
1. **"The arena overflows."** No. The `overflow` guard at the top of `blast` was added for
exactly this fold, but it fires on a *full* node table, and this walk fills nothing --
it recomputes. Measurement showed `overflow == false` throughout.
2. **"The SAT fallback will finish it."** No. The fallback has the same tree-walk recursion
over the same DAG, so it hangs identically. A BDD-only memo was tried first and *still
hung on `u8`* -- the BDD pass stopped (correctly, via its arena cap) and the SAT pass
then hung, with no bound of its own. That is what put a budget on *both* passes; it was
only visible by measuring each pass separately.
The fix has two parts, and they are not redundant:
- **A memo on the BDD pass** (`BLAST_MEMO_N` slots in `Ctx`). A hit collapses the paths:
the same u4 query drops from more than 10^8 visits to **540**. It is keyed by the term id
*including* its generation bits, so the arena reset that recycles slots also invalidates
the memo -- no clearing pass, and a stale key can never match a current term. This is the
half that buys *capability*: without it a `pow` at any width answers `Unknown`, because
the budget below stops the walk before it finishes.
- **A step budget on both passes** (`MAX_BLAST_STEPS`). The memo is a cache, not a
guarantee: a term whose working set exceeds the memo would evict its own entries and
recompute. The budget bounds the *work*, and it is the part that makes "never hangs" true
rather than likely. When it trips it sets the same `overflow` flag the arena cap sets, so
the query degrades along the path that already exists -- BDD to SAT, SAT to `Unknown` --
instead of inventing a new one. The SAT pass additionally calls `Cnf::mark_overflow`,
because a step-truncated CNF must read as `Unknown`, never as a satisfiable one.
The SAT pass gets the budget but *not* a memo, and that asymmetry is deliberate. The BDD
memo's soundness is free: the arena is wiped by `with_fresh`, and the memo key carries the
generation, so a stale entry cannot match. The SAT blaster has no equivalent -- it appends
gates to a `Cnf` that is reset per query, and a memo of `Lit`s would have to reason about
whether those gate slots were reused. That is a real obligation, and measurement says it
buys nothing: a SAT memo changed no verdict, only the latency of the fallback (the same u8
query took ~80ms with it and ~860ms with the budget alone). So the budget alone carries the
SAT pass, and no cross-query cache does.
Measured after the fix: `u4` **Valid in ~34ms**, `u6` Valid in ~1.7s, `u8` **Unknown in
~80ms** -- all three *return*, and none is a wrong answer. `Unknown` at `u8` is honest: the
BDD diagram genuinely exceeds its cap there, which is the case the SAT fallback exists for,
and the fallback's own budget then declines rather than guessing.
The regression test is `a_symbolic_pow_returns_a_verdict_instead_of_hanging` in
`src/mir/intrinsics.rs`. It is *verified to hang without the fix* -- with both the memo and
the budget neutralised it ran past 90s and was killed -- which is the only thing that makes
it a regression test rather than a test that happens to pass. Two details matter: it uses a
*symbolic* exponent, because a concrete exponent unrolls the fold to one path and never
showed the blow-up; and it accepts `Valid` or `Unknown` but rejects a `Counterexample` or
`Unsat`, so it pins both termination and that the budget did not let a truncated encoding
masquerade as a complete one.
The size of the memo is a real constraint, not a free parameter. `Ctx` is already ~1.8 MB
and lives in a thread-local, so it sits close to the test harness's thread stack: growing it
by 512 KB overflows that stack. The memo is therefore small on purpose -- 128 slots, about
33 KB -- and the measurement says that is enough for the fold terms a single query touches
(`N=64` and `N=256` behave identically to `N=128` on the corpus).
## The same budget, aimed at the wrong walk: the BDD apply had no counter
The `MAX_BLAST_STEPS` budget above bounded `blast` -- the walk over the *term DAG* -- and
that was taken to mean the BDD pass could not run away. It could, through a different walk
the budget never saw. The shape was a `u64` divided by a non-power-of-two constant,
`(e / 7) == 0`, read straight out of `mir_coverage`: the process sat at 100% CPU for five
minutes and returned nothing. It was not flaky, either -- five timed runs all hung, so it
was a real shape, not a solver that happened to be slow once.
Instrumenting the two walks separately is what located it, and the numbers are the whole
story. For `udiv(x, 15)` at width 64 the term-DAG walk is **~330 steps** -- far under the
4 194 304 budget, which is why it never tripped -- while the BDD `apply2`, which recurses
over the *diagram*, passes **more than 4 000 000 calls** with no counter of its own.
Division by a constant is the shape that does this: `x / 15` is a restoring divider, and
the resulting boolean function has a BDD exponentially larger than its formula, so the
apply's recursion, not the DAG walk, is the unbounded work. A power-of-two divisor (`x / 8`)
is the opposite -- shifts, a BDD that stays linear -- which is why the sweep that found the
shift bugs never saw this, and why `x / 4` is fast while `x / 7` is not.
The fix is a third budget, `MAX_APPLY_STEPS`, charged inside `apply2` itself. It trips the
same `overflow` flag the DAG budget and the arena cap trip, so the query degrades along the
path that already exists -- BDD hands off to SAT, SAT reports `Unknown` -- rather than
inventing a new one, and the answer stays sound. `apply_steps` is a *separate* counter from
`blast_steps` because the two bound different work: a query can be small in one and huge in
the other, and a single counter would either miss the blow-up or cut a legitimate query
short.
The value, 1 << 19 = 524 288, comes from measurement, not taste. The largest apply count
over the whole test corpus -- `actuator.rs` and `realistic.rs`, every function -- is
**57 191**, so an order of magnitude of headroom above it changes no verdict; the
pathological shape exceeds 4 000 000, so an order of magnitude below it still stops the
hang. Being charged *per apply* rather than per query, it also bounds the latency: the
query now returns in about six seconds instead of never, and the corpus tally is unchanged
(`15 of 30` on `actuator.rs`, `148 of 263` on `realistic.rs`) with the z3 oracle still
`mismatch=0`.
Two things were checked and are *not* the cause, which is why the write-up says so:
1. **"It is flaky."** No. Five timed runs of the same shape hung identically, and the count
was the same 4 000 000+ applies each time. A slow-but-finite query would have finished on
one of them.
2. **"The budget already covers it."** No. `MAX_BLAST_STEPS` is charged only in `blast`, and
the DAG walk for this shape is a few hundred steps; the counter was aimed at the walk
that was *not* blowing up.
The regression test is `a_wide_constant_divisor_returns_a_verdict_instead_of_hanging` in
`tests/divmod.rs`, and it is *verified to hang without the fix* -- with the charge
neutralised it ran past 120s and was killed, which is the only thing that makes it a
regression test. It asserts `!= Valid` rather than `== Unknown`: the property is
termination, and `x / 15 == 0` is false at `x == 15`, so a `Valid` here would be the exact
unsoundness a truncated encoding must not produce. It runs `on_big_stack` because the
restoring divider needs about 4 MB of stack at these widths -- a *pre-existing* property
(the original code needs it even for `x / 4`), not something this budget changed, and the
same reason `tests/divmod.rs` and `tests/signed.rs` already spawn a 64 MB thread.
### A sweep with no timeout cannot report a hang; it reports nothing
The sweep that found the shift soundness bugs (TASK-5) compared the reader's verdict
against rustc's, shape by shape, in a Python driver. It had no per-shape timeout, and the
divisor shape above is what exposed the gap: the driver called `mir_coverage` on
`(e / (8 - 1)) == 0` and waited. A hang does not produce a verdict to disagree with, so the
sweep could not report it -- it just stopped, and the *absence* of a result was mistaken for
"still running" rather than "this is a finding". The fix to the sweep is to wrap each shape
in a timeout and treat the timeout as its own outcome, a *hang* row in the tally, not an
error and not a pass.
That change is what makes the remaining axes sweepable. Re-running the constant-expression
axes with a 20s per-shape timeout, after the budget fix:
- **Pure-constant comparisons** (no typed operand at all -- the axis TASK-6 targets), 1536
shapes: `0` soundness bugs, `0` hangs, `534` decided (`267` verified, `267` refuted) and
`1002` refused. Soundness here cannot be checked against rustc, which accepts *every*
pure-constant comparison, so the oracle is the arithmetic itself: evaluate both constants
at `i32` and compare. All 534 decided shapes match, and the refusals are correct --
`(!0) == (255)` and `(128 << 1) == 256` have no typed operand to fix the reading. The
typing rule the oracle had to learn is Rust's own: an untyped integer literal is `i32` by
default, so `(-1) < (0)` is *verified* -- read as `i32`, `-1 < 0`; read as unsigned it
would be false. The first oracle enumerated signed and unsigned at widths 8/16/32/64 and
flagged `(-1) < (0)` as a mismatch -- the oracle was wrong, not the reader, because there
is no width or sign to enumerate until a typed operand supplies one, and Rust's fallback
is `i32`.
- **Constant expressions as comparison operands**, 2052 shapes across widths 8/16/32/64:
`0` soundness, `0` hangs.
- **Constant expressions as arithmetic/bitwise operands** (`+ - * & | ^`), 3840 shapes:
`0` soundness, `0` hangs.
- **Every operator at every width against 25 constants**, 2000 shapes: `0` hangs. The
`29` shapes over 5s are all division or remainder by a non-power-of-two constant -- the
exact shapes `MAX_APPLY_STEPS` now bounds, returning `Unknown` in about six seconds
instead of never.
The recurring shape across all of it is the same one: `x / k` and `x % k` for `k` not a
power of two. `x & 7`, `x ^ 255`, `x << 3` and `x + 100` are all instant at every width --
the restoring divider's BDD is what costs, and only the divider builds it. A sweep that
times out on `x / 7` and moves on is doing its job; a sweep that waits on it is not.
## Stage 2, last bullet: the complement's width comes from the operand, not the destination
The roadmap's final Stage 2 item was one line: `Rvalue::Unary(Not)` is "handled,
but `!x` is `all_ones ^ x` only when `dest_w` is the operand's width; assert the
width rather than trusting `dest_w`. Small, and not yet measured against the
corpus."
Measuring it first, as the roadmap insists, changed the shape of the work. A MIR
probe of `!x` at `u8`, `i8`, `u32` and `bool` shows rustc always lowers it to
`_0 = Not(copy _1)` with the destination local declared at the operand's type, so
`dest_w` *is* the operand's width for every well-typed body. The code was
therefore not producing wrong answers -- a six-function probe decided 5 of 6, with
the tripwire correctly refuted and both `!x == 255 - x` and `!x == x ^ 255`
verified. What the bullet names is a *defensive* concern, not a live bug: the
mask was derived from `dest_w`, so a body where the dump and the value disagreed
about the type would have been masked at the wrong width rather than refused.
The fix derives the mask from the operand -- `smt::bits(s)`, the width the value
actually carries -- and treats `dest_w` as a cross-check: a destination local that
disagrees is refused (`Val::Unknown`) rather than masked at a width the value does
not have. The reachable behaviour is unchanged, which is the point: the change
removes a way to be wrong, it does not change an answer.
**The bigger finding is that the shape had no corpus entry at all.** `!x` is
common in real Rust and was modelled, but nothing pinned it -- the exact
"supported until contradicted" gap the standing tripwire rule exists to close.
Five entries now carry it, and each pins a different half of the model:
* `not_of_zero_is_all_ones` (`u8`) and `not_of_zero_u32_is_all_ones` (`u32`) state
the operand's width at two widths, so a mask taken at the wrong width fails the
wide one.
* `not_of_zero_is_minus_one` (`i8`) pins the sign the value keeps -- the same bit
pattern read as the operand's type.
* `not_is_255_minus_x` states the identity symbolically, so the operand is read
rather than the answer being a constant.
* `not_is_always_255_tripwire` is the evidence the operand is read at all: a
model that ignored it (a constant `255`, or `all_ones ^ 0`) would prove it. It
is refuted with witness `v1:u8 = 1`.
Coverage went from **71/123 to 75/128** decided, and the test
`the_bitwise_complement_reads_the_operands_width` pins the verdicts so a
regression is a failure rather than a quiet false proof.
The honest boundary: the *refusal* branch (a `dest_w` that disagrees with the
operand) is not reachable from well-typed MIR, so it is defensive and untested by
construction -- no corpus entry can exercise it, because rustc will not emit it.
The corpus entries pin the reachable half; the refusal is the belt to the
suspender, kept because the alternative to a refusal is a wrong mask.
## The `&mut [T]` slice argument: `&raw const (fake)` is a reference, not an unknown
A `&mut [u8]` argument was the last open item on the roadmap: `s[0] = v` was
`incomplete` *before* any write was reached, with `unmodelled assert condition:
index out of bounds`. Measuring first (the roadmap's rule) is what made the cause
visible. The frontend reads rustc's *unoptimised* `--emit=mir`, and at that
setting the bounds check on a mutable slice lowers differently from the immutable
one:
```
fn first_of(_1: &[u8]) -> u8 fn first_of_mut(_1: &mut [u8]) -> u8
_3 = PtrMetadata(copy _1); _3 = &raw const (fake) (*_1);
_4 = PtrMetadata(move _3);
_4 = Lt(copy _2, copy _3); _5 = Lt(copy _2, copy _4);
```
The immutable form hands `PtrMetadata` the slice local directly; the mutable form
first takes a *raw reborrow* of the deref, `&raw const (fake) (*_1)`, and asks
`PtrMetadata` of that. Two pieces of that string were unparsed:
* `&raw const` / `&raw mut` — the raw-borrow prefix. The parser's reference arm
stripped only `&` and `&mut`, so it was left with `raw const (fake) (*_1)`,
which is not a place.
* `(fake)` — a marker rustc prints on the place of a raw reborrow that does not
correspond to a real local. It names the same place as its operand, so it is not
a projection.
Either one alone was enough to make `_3` an unknown, and an unknown length makes
the bounds-check `assert` unmodellable, which refuses the whole function. The fix
is two small parses: `&raw const ` / `&raw mut ` are read as `Rvalue::Ref` (both
name a place, exactly as `&` does), and a leading `(fake)` is stripped from the
place. The `(fake)` strip has to happen in `parse_rvalue`, *before* `parse_place`:
`strip_annot` sees `(fake) (*_1)`, reads it as an annotated place, and strips the
outer parentheses to `fake) (*_1)` — so the marker is removed at the reference arm
where the raw prefix is already known.
This is the conservative reading: `(fake)` is dropped because it carries no
projection, and the raw borrow is a `Ref` because it names a place — the same
`Rvalue::Ref` an `&` produces. Nothing is guessed about what a pointer *is*; the
mapping `resolve` consults is recorded exactly as for `&`.
**Corpus.** Three entries now carry the slice shape, and they separate the two
things a write can get wrong:
* `mut_ref_slice_write_then_read` (`requires: s.len() > 0`) *verifies* — a write
then a read of the same index returns what was written, and the length
precondition discharges the bounds check. This is the entry that proves the
write reaches the store the read consults: had it landed anywhere else, the read
would find the seeded element and the contract would be refuted.
* `mut_ref_slice_write_then_read_tripwire` is the same body claiming the
*pre-write* value (`ret == s[0]`), which is false — a model that dropped the
write would leave the seed readable and prove it. It is refuted.
* `mut_ref_slice_write_then_symbolic_read` (`i == 0`) is the symbolic-index half:
the ite chain must be evaluated against the written element, so the false
contract is refuted rather than left undecided.
Coverage went from **75/128 to 76/131** decided. `tests/mir.rs` pins the verdicts
by name (`a_slice_element_write_reaches_the_store_the_read_consults`,
`a_slice_element_write_reaches_the_symbolic_chain`), and a unit test
(`a_raw_fake_reborrow_parses_as_a_reference`) pins the parse itself, so the guard
runs even without a nightly toolchain.
The honest boundary: only the *write-through-`&mut`* path was the gap. The
immutable `&[T]` read (`first_of`) already worked, and `&mut [T; N]` already
worked through a plain reborrow — the raw form appears only for a `&mut` *slice*,
which is why the array tripwire (`mut_ref_array_write_then_symbolic_read`) and the
slice one are separate entries rather than one.
## A `match` on a standard-library enum *argument*: the layout no source declares
Stage 3 taught the reader that `Option` and `Result` have a fixed numbering no
source file declares, so a *construction* (`Option::<u8>::Some(9)`) resolves
without a layout. The *argument* form was still missing: `match x { Some(_) => …,
None => … }` where `x: Option<u8>` came back `incomplete: unmodelled switch
discriminant`. A `match` on a declared enum argument (`Mode`) verified, and a
locally constructed `Option` verified — only the standard enum **as an argument**
was refused, which is the shape a real function has when it takes `Option<T>` or
threads a `Result`.
The cause is in `field_env`'s argument dispatch. An enum argument's tag is a
symbolic input, seeded from the argument's `EnumDef`; the dispatch looks that
layout up in `enums`, which is keyed by enums *declared in the source*. `Option`
and `Result` are never declared, so the lookup missed, no tag was seeded, and the
`switchInt` on `discriminant(_1)` had nothing to compare against. The
construction path already had the fixed numbering; the argument path had no
layout at all.
The fix reconstructs the layout from the type's own generic arguments
(`std_enum_def`): `Option<T>` is `None`/`Some(T)` at tags `0`/`1`, and
`Result<T, E>` is `Ok(T)`/`Err(E)`. The argument list is split at the *top level*,
so a nested payload (`Result<Option<u8>, u8>`) stays one type rather than being
cut at its own comma and read as two. A *declared* layout is consulted first, so
`Shadow { Some, None }` is still `Shadow` and not `Option` — the same ordering
`variant_index` already pins for constructions. Anything else (`Mode`, a malformed
`Option<u8>X`, a one-argument `Result<u8>`) yields no layout, which leaves the
argument unbound and the function refused — the conservative direction.
**Corpus.** Six entries, and they separate the tag from the payload:
* `option_arg_match` and `result_arg_match` verify (`ret <= 1` for both arms),
which only holds if the tag is seeded and the `switchInt` decides.
* `option_arg_match_tripwire` and `result_arg_match_tripwire` claim one arm's
value and are refuted — a *constant* tag would take one arm always and prove
them.
* `option_arg_payload_passthrough` (`ensures: ret <= x.Some`) and
`option_arg_payload_tripwire` (`ret == x.Some + 1`) pin the *payload*: the
body's downcast read `((_1 as Some).0)` must name the same seeded variable the
contract's `x.Some` does. A tautology such as `ret <= 255` would hold even if
the payload came back unconstrained, so it would pin nothing.
Coverage went from **76/131 to 79/137** decided. `tests/mir.rs` pins the corpus
verdicts by name, and a second test writes the shape to an isolated file so the
fix is pinned even if the corpus entry is edited; `spec::tests` pins
`std_enum_def` directly (both enums, the nested split, and the refusals), so the
guard runs without a nightly toolchain.
The honest boundary: only `Option` and `Result` are reconstructed, because they
are the two the reader already names in `variant_index`. A user enum is declared
and read normally; a *different* standard-library enum (`Poll`, `ControlFlow`)
still has no layout, so an argument of one is refused rather than guessed — the
right answer, since guessing a numbering is exactly the failure `Shadow` guards
against.
## A cast in a *contract*: the same extension rule the body already obeys
The body has modelled `as` for a while — it is what lets a narrow argument meet a
wide return — but the contract language had no cast at all, so `ret == x as u32`
came back `cannot read contract`. Any contract that related a narrow argument to a
wide return was therefore unreadable, which is a dropped obligation: a contract the
parser cannot read is a function that never gets checked. The corpus never used a
cast in a contract, so nothing tripped over it; the probe found it.
`cast_chain` applies `as <type>` to an atom, left to right, and returns the value
with the target's width and sign. The rule is *extension*, not reinterpretation:
`-1i8 as i16` is `-1`, not `255`. A widening cast of a signed source sign-extends;
an unsigned source zero-fills (`truncate`); a narrowing cast keeps the low bits.
This is the same rule the body's `Rvalue::Cast` already implements, and for the
same reason: zero-filling a signed value would prove `-1i8 as i16 == 255`, a
reachable false proof.
A cast chain is well-defined even when the first source's sign is not, because each
step's source sign is the previous step's *target* sign — which the cast just set.
So `x as u16 as u32` is two zero-fills from an unsigned source and two sign-fills
from a signed one, and the chain always carries a known sign after the first cast.
**The rule pinned by the corpus, not by a claim.** Nine entries, five true and four
tripwires. The one that matters is the pair
`contract_cast_signed_to_unsigned` (`-1i8 as u16 == 65535`, verifying) and
`contract_cast_signed_to_unsigned_tripwire` (`== 255`, refuted, witness `x == -1`).
Rust sign-extends through a widening cast *even when the target is unsigned*, so a
contract cast that zero-filled would refute the true entry and prove the false one —
the pair separates the two rules. `contract_cast_narrows_tripwire`
(`256 as u8 == 1` is false; `256` keeps the low byte `0`) pins *which* bits
narrowing keeps, and the chain pair pins left-to-right application.
Coverage went from **79/137 to 84/146** decided. `tests/mir.rs` pins the corpus
verdicts and writes the shape to an isolated file; a `spec::tests` unit test pins
the width-and-sign rule (`x as u32` is 32-bit unsigned, `x as i32` is 32-bit
signed, `x as u16 as i32` ends 32-bit signed), so the parse rule has a guard that
runs without a nightly toolchain.
The honest boundary: the target is read as a *simple* type name, so a cast to a
generic or path type (`x as Vec<u8>`, `x as T`) is not applied — the `as` is left
unconsumed and reported as a trailing token, a refusal rather than a guess. That is
the right direction: a cast whose target width is unknown cannot be sized, and
sizing it wrongly is the failure the whole rule exists to prevent.
## The missing contract operators, and the precedence they exposed
The contract expression language had `+ - * & | ^` but no `/ % << >>`, so a
contract that named a quotient, a remainder or a shift was *unreadable* — a
dropped obligation, since a contract the parser cannot read is a function that
silently leaves the check set. The SMT layer already had every one of them
(`shl`, `lshr`, `ashr`, `udiv`, `urem`, `sdiv`, `srem`) and the body used them;
only the parser never reached them.
Adding them exposed a second, quieter problem. The reader had just **two** levels
and put `|`/`^` beside `+`/`-` and `&` beside `*`, which is not Rust's order. So
`x & 1 + 1` was read as `(x & 1) + 1` where Rust means `x & (1 + 1)` — a
*different value*, not a different proof. That is a correctness trap rather than
a convenience: a contract can pass or fail against the wrong number. It had
stayed latent only because no contract in the corpus mixed the levels.
The parser is now a proper ladder, Rust's own order from loosest to tightest:
`|` < `^` < `&` < `<< >>` < `+ -` < `* / %`. Each level's operands are the next
tighter one, `parse_expr` is the entry point at the loosest level, and the width
`align_widths` and sign propagation are unchanged at every level.
Four rules came with the new operators, each mirroring a choice the body already
makes:
* **A shift's result has the left operand's width**, so the amount is a *count*
and the two operands are deliberately not width-aligned — the one place the
`align_widths` rule does not apply.
* **`>>` follows the left operand's sign.** `-8i8 >> 1` is `-4` (arithmetic), not
a large positive (logical). The sign the parser carries through decides it, the
same as the body's `shift_kind`.
* **The shift amount must be a constant.** A symbolic amount is a barrel shifter
(`smt::shift_var`), and modelling one in a contract would mean agreeing with the
body about the amount reaching the width — a case rustc turns into a panic
first. Rather than guess at that interaction, a symbolic amount is refused, so
the function stays visibly undecided. A constant at or above the width is a
compile error in Rust and is refused too.
* **`/` and `%` take the signed engine when either operand is signed**, the same
choice the body makes: the unsigned divider returns a huge positive quotient for
`-7 / 2`, a wrong value rather than a weaker proof. A literal zero divisor is
refused — Rust rejects it at compile time, so such a contract is malformed.
**Pinned by evidence, not by a claim.** Sixteen corpus entries, nine true and
seven tripwires. The signed pair with teeth is
`contract_shr_signed_is_arithmetic` (`-8i8 >> 1 == -4`, verifying) and its
tripwire (`== -1`, refuted, witness `x == -8` as the bit pattern `248`) — a
*logical* shift would give a large positive and could never be `-1`. The
precedence pairs are the ones that catch a wrong tree: `contract_precedence_and_over_add`
(`x & 1 + 1 == x & 2`) verifies while its tripwire is refuted at `x == 1`, the one
input where `x & (1 + 1)` and `(x & 1) + 1` differ. `contract_sdiv`/`contract_srem`
(`-7 / 2 == -3`, `-7 % 2 == -1`) separate the signed divider from the unsigned.
Coverage went from **84/146 to 93/161** decided. `tests/mir.rs` pins the corpus
verdicts and writes each operator shape to an isolated file; a `spec::tests` unit
test evaluates `x & 1 + 1`, `x + 1 << 1`, `x | 1 ^ 1` and `8 / 4 / 2` on the
engine, so a wrong tree shows up as a wrong *number* with no toolchain needed.
Two of my own assertions were wrong first and the tests caught them: I initially
put the additive level at the *bottom* of the ladder (reading `x & 1 + 1` as
`(x & 1) + 1`, which the tripwire refuted), and I wrote the unit test expecting
`x + 1 << 1` to be `3` when Rust makes it `4`. The code was right the second time
only because the tripwire disagreed with it first.
The honest boundary: `<<`/`>>` with a *symbolic* amount are refused, as above, and
a division or remainder by a literal zero is refused. Both are refusals rather
than guesses, which is the direction this crate always takes.
## A 128-bit type was a panic, not a refusal
Adding the contract operators put `as u128` within reach of a probe, and the tool
*died* on it: `panicked at src/smt.rs:2546: width must be 1..=64`. That is the
worst failure mode in a verifier — not a wrong answer, not a refusal, but a crash
that reports nothing and takes the run down. It was **pre-existing**: `x as u128`
in a *body* panicked too, and so did a `u128` argument, a `u128` local in a loop,
and a `u128` return. My new contract path only made it easier to reach.
The cause is one line. `Ty::width()` reports `128` for `u128`/`i128`, but every
width-taking constructor in the engine (`smt::var`, `var_named`, `truncate`, …)
asserts `1..=64`. So a 128-bit type parses, claims a width, and then asserts in
whichever constructor reaches it first — the argument seeding in `exec`, the loop
havoc, or the contract bindings. The fix is to decide the question *before* any of
them: `Ty::has_unrepresentable_leaf` (recursive, so `[u128; 4]`, `(u128, u8)` and
`&u128` are caught by their leaf) and a guard at the top of `verify_function` that
refuses the whole function. Refusing at that one point is what makes the refusal
*whole*; a partial patch would leave the other paths panicking.
The guard has to come from **two** places, because a 128-bit type can enter from
either side:
* the **function's own types** — argument, local, return — via
`first_unrepresentable_type` at the top of `verify_function`;
* the **contract text**, where `ret == x as u128` names no 128-bit local at all.
`cast_chain` now returns a `Result` and refuses a target wider than 64 bits, with
a message that blames the engine rather than the syntax — a `break` would have
left `as` as a trailing token and reported a parse error for well-formed Rust.
`Ty::width()` still reports 128 on purpose: the *constant reader* needs it to
compute `u128::MAX` and the two's-complement pattern of a negative literal, and
refusing the width there would turn a readable constant into `Other`. It is the
*local*, not the constant, that must never reach a width assertion, and
`has_unrepresentable_leaf` is the one place that is decided.
Pinned by five corpus entries and two tests. Four entries refuse (`wide_arg`,
`wide_return`, `wide_local_in_loop`, `wide_cast_in_contract`) and one,
`narrow_64_still_works`, verifies — so the guard is about the function's width, not
a blanket refusal of anything mentioning 128 bits. `tests/mir.rs` asserts each of
the four is a `Skipped` carrying a reason (a panic would fail the run rather than
the assertion), and a `spec`-level test writes `ret == x as u128` to an isolated
file so the parser refusal does not depend on the corpus. Coverage went from
**93/161 to 94/166** decided; the five new entries are four refusals and one
verification, which is why the decided *count* moved by one and the total by five.
The honest boundary: a function with any 128-bit type, or a contract casting to
one, is refused outright. Modelling 128-bit arithmetic would need the engine's
words widened past 64 bits, which is a change to the engine rather than to the
frontend, and is not attempted here.
## A negated literal reported itself unsigned, and `/ % >>` read a different number
The signedness flag is what `%`, `/` and `>>` consult to choose the signed engine
over the unsigned one, and it is inferred from the **names** in an expression: an
expression is signed when any name in it is. That is exact for the shapes the
corpus had, because every signed entry pinned a symbolic argument (`requires: x ==
-7; ensures: ret == -1`). It is not exact for `-7 % 3`, which has no name at all.
`parse_atom`'s unary minus passed the *operand's* flag through, and the operand of
`-7` is the literal `7`, which is unsigned. So `-7 % 3` came out unsigned and took
`urem`: `4294967289 % 3`, which is `0`, where Rust says `-1`. Same for `-7 / 2`
(`2147483641` instead of `-3`) and `-8 >> 1` (`2147483644` instead of `-4`).
The failure mode is the one that matters most here. It was not a refusal and not a
`Skipped` — it was a **wrong value**, and it pointed the dangerous way: a *false*
postcondition would have been refuted (fine), but the tripwires I wrote to catch a
wrong engine would have **verified**, which manufactures a false proof. A verifier
that returns a confident `verified` on a false statement is worse than one that
crashes, and that is exactly the direction this bug leaned.
The fix is one line, and the reasoning is what makes it safe rather than a patch:
**negation is only defined on a signed type in Rust** (`let x: u32 = -1;` does not
compile), so a negation is itself the evidence that the expression is signed. The
flag is set to `true` unconditionally, not `operand_sgn || true` — the operand's
flag is discarded because it is about the wrong thing.
It was found the same way the 128-bit crash was: the earlier fix (`/ % << >>`) made
a shape *reachable* that nothing had reached, and probing it against values I could
check by hand showed three "postcondition holds for no input" results where rustc
says the postcondition is true on every input.
Pinned by seven corpus entries (four that must verify, three tripwires that must be
refuted or vacuous) and two tests. The `spec` unit test asserts the flag
*directly* — `-7` is signed, `7` is not — because the flag, not the value, is the
thing that broke; and it checks the value is still a value negation (`0xF9` at 8
bits), so a "fix" that made negation mean something else fails. The `tests/mir.rs`
test writes each pair to an isolated file and asserts **both** directions, so
flipping the flag the wrong way fails there too. The same flag also decides a
*comparison* (`slt` versus `ult`), which is why `-7 < 3` was unsatisfiable rather
than false, and two of the entries pin that second family. Coverage **94/166 to
98/173** decided.
## Unary `-` binds tighter than `as`, and the parser had it the other way round
The same probing that found the signedness bug found this one immediately after:
the fix made `-x as u8` reachable, and it read as `-(x as u8)` where Rust means
`(-x) as u8`.
The **value** is the same either way — negation and truncation commute — so no
value-based test could see it. The **type** is not: Rust's is `u8`, and `-(...)` is
signed. That difference is observable through a comparison, because the flag is
what `slt`/`ult` read. `-x as u8 > 127` is satisfiable under the unsigned reading
(`x == 1` gives `255`), and unsatisfiable under the signed one (`i8` is never
`> 127`), so the tool reported a *verifiable* function as **vacuous**.
Rust states the precedence itself: `let x: u32 = 0; let y = -x as u8;` fails with
"cannot apply unary operator `-` to type `u32`", which is only true if the negation
is applied to `x` *before* the cast. (Against a signed `x` it compiles, and there
the negation is on the signed value, still before the cast.)
The fix splits the old single `parse_atom` level into `parse_neg` (the unary minus,
applied to the primary) and `parse_cast` (that result, then the `as` chain), with
`parse_mul` now entering at `parse_cast`. The four `cast_chain` calls that used to
sit on `parse_atom`'s leaves are gone, so a cast has one home.
Pinned by three corpus entries and two tests. The corpus tripwire is the one to
watch: `requires: x == 1; ensures: -x as u8 < 127` is *false* on the unsigned `u8`
(`255 < 127`), so it must be refuted — under the signed reading it would **verify**,
which is a false proof. The `spec` unit test asserts the flag on `-x as u8` (must be
unsigned), on `(-x) as u8` (also unsigned), and on a bare `-x` (still signed, so the
previous fix stands). Coverage **98/173 to 100/176** decided.
Three bugs, one shape: each fix made a shape reachable that nothing had reached, and
probing it against hand-checked answers found the next. The first two were refusals
or crashes; this one and the signedness bug were *wrong values*, which is the
direction a verifier must never fail in.
## The gap that let the early bugs through: no oracle covered the contract reader
The crate has five differential oracles (z3, Kani, Lean, Coq, Verus) and every one
of them builds its terms with `smt::` calls directly. They all start *below* the
contract reader — the layer where the first three bugs above lived. So a whole layer had
no independent check, and those bugs were found by hand-probing rather than by a gate.
`the_contract_reader_agrees_with_rustc_on_a_grid` in `tests/mir.rs` closes that gap
using the one decision procedure that *defines* Rust: `rustc` itself. Two
constructions, because the bugs needed different ones:
* **Value.** The function's body *is* the expression, so `ret` is rustc's value; the
postcondition `ret == <expr>` asserts the reader's value at the same point. The
function verifies exactly when they agree. This catches a wrong *value* — the
signedness bug, where `-7 % 3` was read as `0`.
* **Guard.** The precondition is `x == v && <expr> > t` and the body returns `1`, so
the function verifies iff rustc says the comparison holds. This catches a wrong
*type*: `-x as u8` and `-(x as u8)` have the same value, so no value check can see
the difference, but only one is `u8`, and the comparison is what reads the type.
The oracle did not stop at three. It made the next bugs *reachable*: with the reader
now trusted on the shapes the grid already covered, probing the neighbouring shapes —
`!` on a value, a constant *expression* where a literal was expected — found two more
(a wrong verdict from `!x == 5`, and a definite verdict built on `srem(x, 0)`), both
of which the grid now pins. That is the point of an oracle over a hand-written test
list: it makes the next shape a single line to add rather than a new investigation.
The grid is the point: one value per expression would have missed the signedness bug.
Each case runs the type's extremes, `-1`, `0`, `1`.
**The oracle is checked against the bugs it exists for.** A test that passes on both
the fixed and the broken code is decoration, so each fix was reverted in turn and the
oracle confirmed to fail: reverting the signedness fix makes it report `-7 % 3` at
`x == 0` as a disagreement; reverting the cast precedence makes it report `-x as u8`
at `x == 1` as vacuous where rustc says satisfiable. That the *guard* construction was
needed for the second one is itself the finding — the value construction passes on the
broken cast code, which is exactly why no value-based test caught that bug.
What it does not cover, stated plainly: the grid is finite, so it is not a proof of
completeness; and it checks the reader's direct evaluation, not the translation to
SMT, which the z3 oracle covers. Together they span contract text to verdict.
## `!` on a value is bitwise NOT, and it binds tighter than `==`
The oracle above earned its keep immediately. Probing `!` found a fourth bug, and it
is the same shape as the other three: the parser picked a different meaning than Rust
for the same characters.
`!` was handled only at the *predicate* level, where it negates a comparison. But in
Rust `!` is a unary prefix on a *value*, binding tighter than `==`, and on an integer
it is *bitwise* NOT. So `!x == 5` was read as the predicate `!(x == 5)` — that is,
`x != 5` — where Rust means `(!x) == 5`, which for a `u8` is `x == 250`. Two different
predicates: a **wrong verdict**, not a refusal. And a bare `!x` was not readable at
all, which *dropped* the obligation.
The fix splits the two readings. `bang_is_predicate` looks at the token after the `!`:
`!(...)` with a comparator inside, or `!true`/`!false`, is the predicate form and stays
at `parse_cmp`; anything else is a value form, handled as a prefix in `parse_neg`,
where it is `x ^ all_ones` — the same term `mir/exec.rs` builds for `UnOp::Not`. The
`!` is a prefix on the operand, so `!1 + 1` is `(!1) + 1` and `x & !1` is `x & (!1)`.
Pinned by four corpus entries (verify / refute / verify / verify) and one unit test
that asserts both readings of `!x == 5` as *predicates*, so the discriminator is the
predicate itself rather than a value. Coverage **100/176 to 103/180**.
One honest note on the corpus entry that looks like a tripwire but is not. The two
readings of `!x == 5` are `x == 250` (Rust) and `x != 5` (the bug), and the second is
*broader* — it admits every input the first does, and more. A broader precondition can
only produce false *refutations*, never a false proof, so there is no reverse-tripwire
direction to pin here; the entry that accompanies the verifiable one is a *control*
that must refute under both readings, which shows the tool is not simply verifying
everything. The false-proof direction for `!` is the bare `!x`, and that one was a
dropped obligation rather than a wrong verdict, because it did not parse.
## A constant expression is not a literal: fold it, then classify it
Probing the precedence grid after the `!` fix found a fifth bug, and it is about *when*
a value is inspected rather than *how* it is parsed. `const_of` answers "is this term a
literal node", and two places asked it where the right question was "does this term
*fold* to a constant":
- **A shift amount.** `x >> 1 + 1` is `x >> 2`; Rust folds the amount. The reader
tested the operand with `const_of`, saw an add rather than a literal, and refused the
contract ("a shift amount in a contract must be a constant") — a *dropped obligation*
on a shape rustc compiles. The body side had the same test, so `x >> 1 + 1` in a body
became a symbolic barrel shifter and the query came back `Incomplete`.
- **A divisor.** `x % (1 - 1)` is `x % 0`; Rust folds it and the `unconditional_panic`
lint rejects it at compile time. The zero guard used `const_of`, so it recognised the
literal `0` but *not* the folded `1 - 1`. The reader built `srem(x, 0)` — an undefined
operation the engine nonetheless evaluates — and returned a **definite verdict** from
it. That is a wrong verdict, the one outcome a verifier must not produce, and it is
the same class as the `!x == 5` bug: a decision made where a refusal was owed.
The fix is to fold before classifying, with the helpers the parser already has:
`const_value` in the contract reader (which is `smt::evaluate` with no assignment) and
`smt::evaluate` in the body. A *symbolic* shift amount is still refused and a *symbolic*
divisor is still modelled exactly, so the conservative behaviours are unchanged; only
the misclassified *constant* moves.
Pinned by four corpus entries, one integration test (`a_folded_constant_is_read_as_a_
constant`) that asserts both the read case and the refusal case, and one unit test that
checks the parse directly. Both halves are sensitive: reverting the divisor guard makes
the integration test fail with `FAILED: postcondition — v1:u8 = 3`, the verdict built on
`srem(x, 0)`. rustc treats `x % 0`, `x % (1 - 1)` and `x % (2 - 2)` identically under
`unconditional_panic`, which is the evidence that refusing them alike is right.
## After a fix, probe the neighbours — and be honest when they are already right
The two bugs above came out of probing the shapes *around* a fix. So after the folded-
constant fix I probed the four neighbouring precedences against `rustc` directly: `&`
vs `|`, `>>` vs `==`, a cast vs `+`, and unary `-` vs a cast and `%`. All four were
already correct. That is a coverage result, not a fix, and the write-up says so — a
changelog that called each probe a "bug found" would be dishonest, and the next reader
would not know which commits to trust.
What the batch adds is *evidence* for shapes that were "supported until contradicted":
six corpus entries with their tripwires, asserted end to end in
`contract_operators_and_their_precedence`, and four rows in the rustc grid. Coverage
**109/187 to 115/195**.
Two shapes are left out of the grid on purpose, and the source says why, because a
silent omission reads as an oversight:
- `x >> 1 == 2` in *guard* mode would append `> 0` and produce `x >> 1 == 2 > 0`, a
chained comparison rustc rejects. The comparison is already a predicate, so value
mode is the only construction that fits.
- `x as i16 * 2` in guard mode builds an `i16 * i16` body, whose overflow assert the
engine declines to model (`wide > 16`). The probe is then undecided and the guard
cannot read the comparison. That is the documented BDD scaling wall, not a gap.
The general rule: a grid row is only evidence when *both* the probe and the assertion
are decided. A row that fails for a reason unrelated to the property under test is
worse than no row, because it looks like a check and is not one.
## Bug 6: a radix literal was read as decimal -- a false proof
The sixth bug is the worst family in this file, and the first *false proof*: the
tokenizer read every numeric literal as decimal. The digit run stopped at the `x` of
`0xFF` and the rest was skipped as a type suffix, so the value was `0`. In a
precondition that is not a refusal, it is a wrong *number*:
```rust
/// requires: x == 0xFF // read as `x == 0`
/// ensures: ret == 0 // "proved" for a body returning `255`
pub fn f(x: u8) -> u8 { x }
```
The tool reported **verified**. `0b1010` became `0`, `0o17` became `0`. A false proof
is the one outcome the whole crate exists to prevent, so this is the most serious
entry in the series; the earlier five were dropped obligations or, in the folded-zero
case, a definite verdict from an undefined operation -- bad, but not a proof of
something untrue.
The fix reads each literal at its radix (`0x`/`0b`/`0o`, underscores, an optional
integer suffix) and, just as important, *refuses* one that is not an exact integer
rather than taking a partial value: `0b12`, `0o9`, `0xg`, `0xFFg`, and anything past
`u64` are `Skipped`, not silently truncated. A new `Tok::BadNum` carries that
refusal, so the parser reports "a numeric literal that is not an exact integer"
instead of `0`. The fix is worth nothing without the refusal half: reading at the
radix but still swallowing a bad digit would have traded one silent number for
another.
Found by a *discriminating* probe, which is the lesson. My first literal probes
(`requires: x == 0xFF`, `ensures: ret == 255`, body `255`) **verified** -- and would
have verified under either reading, so they proved nothing. The probe only had teeth
when the body returned the argument and the postcondition named the value: correct
reading gives `x == 255`, body `255`, holds; truncating reading gives `x == 0`, body
`0`, refuted. A test that passes under the bug is not a test. Every literal probe in
the corpus now has the `_control` companion that returns the argument, so the
truncated reading is a *refutation*, not a pass.
Evidence: `a_radix_literal_is_read_at_its_radix` (spec unit test, parse-level),
`a_radix_literal_is_read_at_its_radix` (integration, corpus + the `_control`),
six corpus entries, six rows in the rustc grid. The grid rows are the differential
form: `expr` is both the body (compiled by rustc to the true value) and the
postcondition (parsed by the reader), so a decimal-only reader shows up as a
disagreement, not as a silent pass. Reverting the radix read makes the grid fail with
`0xFF` expected `verified=true`, got `skipped` -- the oracle is sensitive.
Coverage **115/195 to 120/201**, test-count 540 to 542. Gate green.
## Bug 7: a signed-width literal wrapped instead of being refused -- a false proof
The seventh bug is the second *false proof*, and it is Bug 6's mirror image. The
tokenizer was fixed to read the right *number*, but the width check that decides
whether that number fits the operand asked only about *unsigned* bits. `128` for an
`i8` fits in eight bits, so it was accepted -- and the eight bits are `0x80`, which
`i8` reads as `-128`:
```rust
/// requires: x <= 128 // read as `x <= -128`
/// ensures: ret != 127 // "proved", because `x <= -128` excludes nothing
pub fn f(x: i8) -> i8 { x }
```
rustc rejects `x <= 128` for an `i8` ("literal out of range for `i8`"), and the tool
reported **verified**. The wrapping was invisible because the literal was built at
exactly the operand's width and `align_widths` returned early on equal widths -- the
signed-range check in `resize_const` never ran. The negation path had the same hole
from the other side: `-129` for an `i8` is `127` at eight bits, so `x >= -129` was
read as `x >= 127` and `ensures: ret >= 0` "held" under a precondition that admits
nothing.
The fix has two halves:
* `align_widths` no longer short-circuits on equal widths; it resizes the constant
operand (a no-op term at equal width, but the range check runs) and carries each
operand's own signedness. `resize_const` takes that flag: a bare literal is
non-negative and is checked as `+val`, while a signed bound (`i8::MIN`) or a
negation is checked as its two's-complement value. That distinction is what lets
`128` be refused while `i8::MIN` -- the same bit pattern `0x80` -- still reads.
* `parse_neg` widens a negated constant by one bit when its magnitude does not fit
signed at its own width, so `-129` survives as `-129` for the check to refuse
instead of wrapping to `127`.
`i8::MIN` is unaffected because it is a *named* bound built by `type_bound`, not a
bare literal; a fix that refused every `0x80` would have broken it, which is why the
corpus pins both sides.
A third site had the same hole: a comparison between *two constants*, where neither
operand is a typed name and the width comes from the literal itself. `align_widths`
aligned the two and returned without a fit check, so `128 <= i8::MAX` -- a `literal
out of range for i8` error in Rust -- read as `-128 <= 127`, always true. The check
now runs on both operands even when both are constants, so the shape is refused while
`127 <= i8::MAX` and `i8::MIN <= i8::MAX` still read.
Evidence: `an_out_of_range_literal_is_refused_at_the_operand_width` (spec unit test,
parse-level), `an_out_of_range_literal_is_refused_not_wrapped` (integration, six
corpus entries -- three refusals and the three legal boundaries), six corpus entries.
The integration test is sensitive in every half: reverting the `align_widths`
change makes `contract_out_of_range_literal_is_refused` *verify* (the false proof),
reverting the `parse_neg` widening makes `contract_out_of_range_negation_is_refused`
verify, and reverting the two-constant check makes
`contract_constant_vs_constant_out_of_range` verify. Each was checked by reverting
that half alone.
Coverage **125/206 to 128/212**, test-count 542 to 544. Gate green.
## A constant expression that overflows is folded exactly, not mod width
A fourth site, one level up from the literal: constant *arithmetic* in a contract.
```rust
/// requires: x <= 200 + 100 // a rustc const-eval error: `200u8 + 100u8`
/// ensures: ret <= 44 // "proved", because the sum was folded mod 256
pub fn f(x: u8) -> u8 { x }
```
rustc rejects `200u8 + 100u8` as an `arithmetic_overflow`. The reader folded the
width-8 sum the same way the engine does, giving `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 reported **verified** for a body that
fails at `x == 100`. A false proof, and the opposite direction from the literal
cases: those *widened* a precondition until it excluded nothing; this one *narrowed*
it until the postcondition held.
The mechanism is `parse_add`/`parse_mul` handing the constant operands to the
width-`w` engine operator, which wraps. The fit check in `resize_const` cannot catch
it because it only ever sees the wrapped result. The fix folds the exact value in
`i128` (`fold_const_arith`) and widens to the narrowest width that holds it, so the
ordinary fit check refuses the shape when the operand it meets is too narrow. Three
consequences:
* An unsigned expression that goes negative (`0 - 1`) is refused outright: the
reader's own model says such an expression is unsigned, and `0u8 - 1u8` is a rustc
error, so handing the comparison a negative value would only make it read the wrong
predicate.
* A result that fits a *wider* operand still reads: `x as u16 <= 200 + 100` is `300`,
which rustc accepts, so the fix does not refuse legal constant arithmetic.
* The widening is at the *expression's* signedness, not the result's. `i8::MAX + 1` is
`128`, which fits an unsigned byte but not a signed one, and rustc rejects it. A
first version of the fix widened by "does this fit *unsigned*", which left `128` at
eight bits where it read as `-128` -- a *new* false proof in place of the one being
fixed, caught by probing `i8::MAX + 1` after the fix rather than before it. The
corpus now pins that case too.
* A constant `i8::MIN / -1` or `% -1` overflows the signed operand -- rustc rejects
it at compile time and panics at runtime -- and the engine's divider would wrap it
to `MIN` and `0`. The fold refuses it.
A constant *shift* is left alone, deliberately: rustc does not treat `2u8 << 7` as an
overflow (the value wraps to `0` at runtime), only a shift *amount* at or above the
width, and `parse_shift` already refuses that.
Evidence: `an_overflowing_constant_expression_is_refused_not_wrapped` and
`an_overflowing_constant_division_is_refused` (spec unit tests, parse-level), plus
six corpus entries wired into `an_out_of_range_literal_is_refused_not_wrapped` --
`contract_constant_sum_overflow_is_refused`, `contract_constant_underflow_is_refused`,
`contract_constant_div_overflow_is_refused` and
`contract_constant_signed_sum_overflow_is_refused` (refusals), and
`contract_constant_sum_in_range_reads`, `contract_constant_sum_wider_operand_reads`
(which must read). Sensitivity was checked by reverting the fold wiring alone: the
spec tests fail and `contract_constant_sum_overflow_is_refused` *verifies* -- the
false proof -- so the test is not passing for an unrelated reason. Reverting the
signedness of the widening alone makes the `i8::MAX + 1` assertion fail, so the trap
in the fix is pinned too.
Coverage **128/212 to 130/218**, test-count 544 to 546. Gate green.
## A signed constant meeting an unsigned operand is refused, and an element's sign must reach the *parser*
Two holes in one sitting, both of the same kind: a signedness the reader *knew* but
did not *use*, so a comparison asked the unsigned question and answered "always true".
**The mixed-sign comparison.** `parse_cmp` decided a comparison's signedness with
`signed = ls || rs`, and the `||` is a disjunction over operands that Rust never lets
meet. A literal takes its type from the operand beside it, so `x == -1` for a `u8`
does not compile ("cannot apply unary operator `-` to type `u8`"), yet the reader
carried the negation as a bit pattern at the operand's width and read `x == -1` as
`x == 255`. That is a wrong *value*, and `ensures: ret == 255` was **proved** for a
body returning `x` -- the false proof, caught by probing `x == -1` against a `u8`
after a probe script showed rustc rejecting the shape. The shape is now refused
before alignment. The refusal is deliberately narrow: a bare literal is unsigned, so
`0xFF` for a `u8` still reads as `255`; two constants are already range-checked by
`align_widths`; 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 rustc rejects.
**The element's sign in the contract.** `bind_indexed_elem` recorded an element's
signedness in `elem_seeds` for the executor but never in the parser's `signed` set,
so `is_signed_name` said an `i8` element was unsigned. `xs[0] >= 0` over a `&[i8]`
then 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 identical hole, because `bind_sym_index` inserted the
chain into `vars` without inserting it into `signed`. Both sites now record the sign,
the way every other binding site (`bind_bits`, payloads, `ret` fields) already did.
The instructive part is that the corpus *hid* the second bug. The pre-existing
`signed_slice_element_tripwire` already reported FAILED, so a coverage count said the
entry was "handled" -- but it was FAILED because the *body's* reading of the element
dominated the verdict, and the body's reading is executor-side and was correct. The
parser-side bug is only visible when the element appears on the contract side alone
(`ensures: xs[0] >= 0`). A verdict that is already the expected one for a different
reason is not coverage; the new entries put the element *only* in the contract, which
is the shape the old entry could not reach. Baseline confirmed: both new entries
`verified` before the fix and `FAILED` (witness `128`) after, and removing either sign
record alone makes them verify again.
Evidence: spec test `a_signed_constant_against_an_unsigned_operand_is_refused`
(parse-level, refusal + the legal `0xFF`/`255`/signed-name cases), integration test
`a_signed_element_is_read_as_signed_in_the_contract` (refutes both tripwires and
asserts the `128` witness), and corpus entries
`contract_signed_literal_vs_unsigned_is_refused` (refused),
`contract_unsigned_literal_still_reads` (must read), and the two tripwires. The first
bug's earlier corpus addition (`signed_slice_element_ensures_tripwire`) is also what
proved the second.
Coverage **130/218 to 131/222**, test-count 512 to 514 (lib 179 to 180). Gate green.
## The comparison-level refusal did not cover the arithmetic levels
The mixed-sign fix above was written at `parse_cmp`, on the reasoning that a
comparison is where a signed constant meets an unsigned name. Probing the shape
next door showed that was too narrow. `x + -1` for a `u8` is the same rustc error
("cannot apply unary operator `-` to type `u8`") and the same wrong reading (`-1`
carried as `255`), and it is a *worse* proof: `requires: x + -1 >= 0` becomes
`x + 255 >= 0`, trivially true, so the precondition admits every input and *any*
postcondition is proved. `requires: x + -1 >= 0` with `ensures: ret != 0` verified
for a body returning `x`, which is false at `x == 0`. The comparison check never
ran, because the constant meets the name at `+`, not at `>=`.
The refusal is now one helper, `refuse_signed_const_vs_unsigned_name`, called at
every level where two operands of one operator meet. That turned out to be *four*,
not three: `parse_cmp`, the additive level, the multiplicative level, and the
bitwise levels (`parse_bitand`/`parse_bitxor`/`parse_bitor`) that sit between the
comparison and the additive levels. The first draft of this section asserted the
bitwise levels "do not carry a negation of their own, so no separate site was
needed" -- and a probe disproved it immediately: `x ^ -1 <= 255` for a `u8` was
read as `x ^ 255 <= 255`, always true, and *verified* for a body returning `x`. The
claim had been reasoned, not tested, and the reasoning was wrong; the probe is what
found the fourth level. The helper's doc comment carries the narrowness argument
once instead of four times. The legal shapes still read: `x + 255 >= 0` (unsigned
constant), `x - 1 <= 255`, `x & 255 == x`, `y + -1 <= 0` and `y ^ -1 == 0` (signed
name with a signed constant).
The lesson generalises past this bug: a signedness refusal is only as wide as the
*operator* it was written on. The reader meets two operands at four levels
(comparison, additive, multiplicative, bitwise), and a fix at one of them leaves the
other three reading the wrong value. The original comparison-level fix was found
too narrow by probing the level next door; the arithmetic fix was found too narrow
the same way, one level further out. The pattern is to *enumerate the levels and
probe each*, not to reason that a neighbour is safe.
Evidence: the spec test gained the arithmetic and bitwise cases (`x + -1`,
`x - -1`, `x % -1`, `x * -1`, `x & -1`, `x | -1`, `x ^ -1` refused; `x + 255`,
`x - 1`, `x & 255`, `x ^ 255`, `y + -1`, `y ^ -1` read), and four corpus entries
(`contract_signed_constant_sum_vs_unsigned_is_refused` and
`contract_signed_constant_mask_vs_unsigned_is_refused`, refused;
`contract_unsigned_constant_sum_still_reads` and `contract_unsigned_mask_still_reads`,
must read). Sensitivity was checked by reverting each of the three new call sites
alone: with `parse_add`'s removed,
`contract_signed_constant_sum_vs_unsigned_is_refused` *verifies* -- the false proof;
with `parse_mul`'s removed, `requires: x % -1 == 0` reads and refutes; with the
bitwise check removed, `x ^ -1 <= 255` reads as always true and verifies.
Then the enumeration was made exhaustive, because "one level at a time" is how the
hole kept being found and reasoning about the next level is what kept being wrong.
The spec test now loops over all sixteen operators: `x <op> -1` must be refused and
`x <op> 1` must read, for `<op>` in `== != < <= > >= + - * / % & | ^ << >>`. A
comparison stands alone as a predicate; a value operator is wrapped in `== 0`, which
the crate's precedence parses inner-first, so the refusal fires before the outer
comparison. The ground truth is rustc: `x <op> -1` for a `u8` is a compile error for
every one of the sixteen, checked with the compiler itself rather than assumed.
With the matrix in place, each of the *six* call sites was reverted one at a time and
the test failed every time -- comparison, additive, multiplicative, and all three
bitwise levels are individually load-bearing. The six are: `parse_cmp`'s, the
additive pair (`+`/`-`), the multiplicative triple (`*`/`/`/`%`), and
`parse_bitand`/`parse_bitxor`/`parse_bitor`.
Coverage **131/222 to 133/226**, test-count 514 held. Gate green.
## Follow-ups on the untyped-constant reader: a panic, a mask's lost type, and a vacuous test
Reviewing the signedness work found four more, each a different flavour of the same
theme — the reader answering a question it had not been asked, and a test that could not
have caught it. (A fifth surfaced while writing this up: the mask's lost type was fixed in
one direction only, and the symmetric case is the third bullet below.)
**A `u128`-suffixed literal was a panic, not a refusal.** The suffix records the type's
*true* width, and `Ty::width()` returns `128` for `u128`/`i128`. `parse_atom`'s range check
computes `1u128 << (w - 1)` and `1u128 << w`; at `w == 128` that shift overflows. In a
**debug** build it panics outright — the worst failure mode, a crash that reports nothing.
In **release** it wraps to a wrong `max`, so a 128-bit literal slips past the range check
and reaches `smt::word`, whose `1..=64` assertion is the same crash from the other side.
`0u128 == 0u128` is the minimal trigger: both literals are *small*, so the value is not the
problem, the type is. The fix refuses `w > 64` **before** the shift, with a message naming
the width and the engine limit, which is the answer `cast_chain` already gives a cast to
`u128`. The tokenizer's comment had claimed `u128`/`i128` "have no engine width" and mapped
them to 64 — but that arm was dead, because `width()` returns `Some(128)`, so the guard it
described never ran. The comment now says what the code does.
**A masked operand lost its type — twice, in two different ways.** The `parse_bitand`
refinement that made `(!0 & 1)` widen was first written on the *presence* of a literal
mask. That was too wide twice over, and each over-wide version hid a pairing rustc rejects
(`E0308`), which the reader then decided instead of refusing.
*First*, a **symbolic** operand: `x & 128` for a `u8` is still a `u8`, but the presence of
the literal `128` marked the result `Sign::Literal`, the "untyped, infer me from a partner"
state, so `refuse_mixed_signedness` accepted `(x & 128) == y` for a signed `y`. The mark was
gated on the result being *constant* — `&` cannot change a symbolic operand's type.
*Second*, a **signed constant** operand: `(-1i8 & 1)` is a constant, so the constant gate
let it through, but it is an `i8` — the mask takes the *typed* operand's type, and `==`
never coerces, so `(-1i8 & 1) == y` for a `u8` `y` is `E0308` (`expected i8, found u8`). Its
*value* is the small positive `1`, which is exactly the trap: marking it `Literal` read the
comparison as `1 == y` and **verified** it.
*Third*, the fix for the second was itself too narrow: `Sign::combine(sgn, rs) != Sign::Signed`
excluded only a **signed** typed operand, leaving the **unsigned** half open. `1u8 & 1` is a
`u8`, so `(1u8 & 1) == y` for an `i8` `y` is the same `E0308` — and it was still marked
`Literal` (an unsigned typed mask is "not signed") and **verified**. The condition is now
`Sign::combine(sgn, rs).typed().is_none()`: a constant result may be marked `Literal` only
when *neither* operand carries a type. `(!0 & 1)` has no typed operand (`!0` is `Opaque`, `1`
a bare literal), so it still widens exactly; `(-1i8 & 1)` and `1u8 & 1` keep their types and
the mixed pairings are refused.
The distinction is *typing*, not value or size or signedness alone: a mask's type is its
typed operand's type — signed **or** unsigned — and a constant that merely computes a small
positive number does not become untyped.
**The strict test guard had a hole of its own.** `verify_src` was made strict in an earlier
fix — a contracted function absent from the report is a panic, not a silent `None` — but the
assertion carried `|| report.missing.iter().any(|m| m == name)`, accepting the *same* drop
when the frontend reported it. `missing` is the drop from the frontend's side, so this
reopened the hole the guard existed to close: a test whose function the frontend drops, for
*any* reason, would still assert nothing. The `missing` clause is gone; the only pass without
an outcome is a source with no `///` at all (a caller mistake, not a drop). The guard is
split into `assert_not_dropped`, so the exact branch that was vacuous is tested without a
nightly `rustc`: a `#[should_panic]` test feeds it a `missing` list naming the function.
**Evidence.** Unit tests `a_u128_suffix_is_refused_before_the_range_shift` (three 128-bit
suffixes refused, `1u64` still reads) and the corpus entry `contract_u128_suffix_literal_is_refused`;
`a_symbolic_mask_keeps_its_type_but_a_constant_mask_still_widens` with the corpus entry
`contract_symbolic_mask_keeps_its_type` (refused) against `contract_complement_mask_widens_exactly`
(still verifies); `a_typed_constant_mask_keeps_its_type` (unit and corpus, both directions:
`contract_signed_mask_vs_unsigned_is_refused` and `contract_unsigned_mask_vs_signed_is_refused`
refused, `contract_signed_mask_with_signed_partner_reads` and
`contract_unsigned_mask_with_unsigned_partner_reads` verify) for the typed-constant mask; and
`a_dropped_contracted_function_fails_even_when_missing_names_it` +
`a_present_function_passes_the_drop_guard` for the guard. Test-count **534 → 542**; corpus
**142/246 → 144/252**. Gate green: z3 `mismatch=0`, Kani `mismatch=0`.
The lesson the four share: a refinement is only as wide as the *predicate* it was written
on, and a predicate that looks at the convenient property (is there a literal mask? is the
result constant? is it *signed*? does a name for the drop exist?) rather than the necessary
one (is the result's *type* still its operand's?) will be wrong in one direction or the
other. The mask refinement was too wide **three times** — a symbolic operand, then a signed
constant, then an unsigned constant — and each time the probe that found it was a pairing
rustc rejects but the reader decided. The pattern is to state the *type* invariant and test
both directions, not to patch the direction a single counterexample came from.
## A fixed-width constant may not meet a partner of another width
The mask work above was found by hand, one counterexample at a time. This one was found
by a *differential sweep*: enumerate the operand shapes a contract can write, ask `rustc`
whether the shape is well-typed, ask the reader what it decides, and report every shape
rustc rejects but the reader decides. Across 722 comparison shapes the sweep found exactly
one soundness hole, and it was a *new class*, not another mask:
`-1i8 < (x as i16)` was **verified**. `-1i8` is an `i8` and `x as i16` is an `i16`, so the
comparison is `E0308` (`expected i8, found i16`). Both operands are *signed*, so
`refuse_mixed_signedness` — the gate that refuses `i8` vs `u8` — passes them and the
verdict is read. Signedness was not the only type evidence, and the remaining evidence,
the *width*, was being erased: `align_widths` resizes a constant to its partner's width so
that a bare literal can be sized per use, and it did the same to `-1i8`, narrowing the
`i16` side down and deciding a program rustc rejects. The same shape appears with no name
at all — `1i8 == 1i16` — and with a bound — `(x as i16) < i8::MIN`.
The fix separates the two reasons a constant can be untyped-and-adaptable from the reason
it cannot be resized. A *bare* literal has no type of its own, so Rust infers its width
from the operand it meets — and so does a *bare negation*, `-1`, which is why
`-1 < (x as i16)` is well-typed. A suffixed literal (`1i8`), a named bound (`i8::MIN`), a
cast, or a fold with a typed operand has a width of its own, and a mismatch with a typed
partner is `E0308`. So the `Sign` model gained a `NegLiteral` state, distinct from
`Signed`:
- `eval()` is true for `Signed` and `NegLiteral` — both are signed, so `%`, `/` and `>>`
take the signed forms (`-7 % 3` is `-1`).
- `adapts()` is true for every state whose width is inferred rather than fixed —
`Literal`, `NegLiteral`, and `Opaque` (the complement of a literal, or a fold of
untyped operands: `!0`, `(!0 + 1)`) — and is what `align_widths` now keys on, so a
fixed-width constant is refused rather than resized. It is `!fixes_type()`: the
first cut listed only `Literal` and `NegLiteral`, which wrongly refused the
well-typed `(!0 + 1) == y`.
- `typed()` is `Some(true)` for `NegLiteral`, so it still forces a partner's signedness;
`fixes_type()` is true only for `Signed`/`Unsigned`, which is what a width mismatch
needs.
`combine` was rewritten to match: a pair with a *fixed* operand takes its sign; with
neither fixed the result keeps the pair's own nature — `Opaque` for a width-dependent
untyped constant, `NegLiteral` for a signed-but-adaptive value, `Literal` otherwise.
**Evidence.** The differential sweep (`rustc` as the oracle on the shape, the reader's
verdict against it) over a *wider* operand set — 900 shapes including casts, bounds,
masks, shifts and folds — reports **0** soundness holes after the fix, down from **26**
before it, with **no new** hole introduced. The 10 refusals of well-typed shapes in the
smaller set are all pre-existing and intentional (an untyped `!0` with no typed partner is
sign-ambiguous). A unit test
(`a_fixed_width_constant_may_not_meet_a_partner_of_another_width`) pins both directions —
four refused shapes and three that must read — and a corpus test asserts the tripwires
`contract_fixed_width_constant_vs_wider_cast_is_refused` and
`contract_two_fixed_width_constants_are_refused` are not decided against the control
`contract_bare_negation_meets_a_wider_operand`, which must verify. Test-count **542 →
544**; corpus **144/252 → 145/255**. Gate green.
**Followed up.** The five untyped-fold shapes named below as still open were the *next*
axis, and the change after this one closes them; see "An untyped fold that overflows its
operand width is refused" below. The `Opaque` state this fix introduced is what made the
follow-up small: the fold was already carried untyped, so the overflow only had to be
*recognised* at the fold, not re-modelled.
The lesson: signedness was never the whole type. The earlier fixes asked "same
signedness?" and the sweep asked the *pair* of questions rustc asks — same signedness
**and** same width — and only the second found this. When a gate models one axis of a
type, sweep the other axis too.
## An untyped fold that overflows its operand width is refused
The width sweep above left five shapes decided that rustc rejects, all one family: an
*untyped fold* whose exact value does not fit the operand width. `(!0 + 1) < 1u8` was
**verified**. In Rust `!0` is a `u8` `255` there, so `255 + 1` is a rustc `arithmetic
operation will overflow` error; the reader held the fold at the *scope's* width (`256`)
and let a later resize truncate it to the `u8` partner's width, reading `0 < 1`. The
equality `(!0 + 2) == 1u8` was verified the same way (`257` truncated to `1`).
This is a *different* axis from the width fix. There the fold's *type* was erased and
resized; here the type is genuinely untyped — a fold of untyped operands has no type of
its own — and the bug is that the fold's *value* depends on the width it is later read at,
which the reader does not know when it folds.
The fix is a refusal, not a new value. `fold_const_arith` already computes the exact
result and only reaches the widen-or-refuse branch when that result does **not** fit the
operand width; an `Opaque` result there is exactly the width-dependent overflow, so it is
refused rather than emitted as the scope-width value. A fold that *does* fit — `200 + 100`
is `300` at any width holding it — never reaches the branch and still reads, which is the
control the corpus pins.
**Why not narrow the refusal to the unsigned case.** Every false proof the sweep found had
an unsigned partner, so a rule that refused only unsigned consumers looked tempting. It is
unsound. A *signed* partner is just as wrong: `(!0 + 200) == x` for an `i8` `x` was
**verified** with `x == -57` (the scope-width `!0` is `255`, `255 + 200` is `455`,
truncated to an `i8`'s `-57`), and rustc rejects the fold as `literal out of range for
i8`. The fold's value is not known until its width is, whichever signedness that width
has, so the refusal covers both. The cost is real — the wider sweep's completeness misses
rise from **978** to **1626** of 13254, because the valid shapes `(!0 + 1) == x` for a
signed `x` are now refused — but a refusal is a skipped function, not a wrong verdict.
**Evidence.** The differential sweep was rewritten to read rustc's diagnostics as JSON, so
a *warning* is never mistaken for an error and each error is attributed to its primary
span (the earlier line-based parse counted warnings as errors and inflated the signed-case
count). On the corrected harness the same 13254 shapes give **0** soundness holes, down
from **40**. A unit test (`an_untyped_fold_that_overflows_the_operand_width_is_refused`)
pins three refused shapes and two that must read; a corpus test asserts the tripwires
`contract_untyped_fold_overflow_is_refused` and
`contract_untyped_fold_overflow_equality_is_refused` are not decided against the control
`contract_fitting_fold_still_reads`. Test-count **544 → 546**; corpus **145/255 →
146/258**. Gate green.
The lesson: a differential sweep is only as good as its oracle. Counting a compiler
*warning* as a rejection made the fix look incomplete and sent the search after a
narrower rule that would have re-opened the hole. Read the oracle's structured output, and
attribute each diagnostic to the span it is really about.
**Followed up.** The next operator sweep turned up the same shape one operator over — an
untyped *shift* whose width is inferred, not the fold's overflow but the operand's width —
see "A shift of an untyped constant is refused when its width is inferred" below.
## A shift of an untyped constant is refused when its width is inferred
The fold fix left the operator axis un-swept: the sweeps so far had compared constants at
`+ - * & | ^`, and had not driven `<< >>` (nor `/ %`, casts, unary or boolean operators)
against rustc. A new differential sweep over those families found **45** shapes
**verified** that rustc rejects, and every one was the same family: a shift of an
*untyped* constant.
`(255 >> 8) <= x` for a `u8` `x` was **verified**. In Rust `255` is a `u8` there, and a
shift by its own width is a rustc `arithmetic operation will overflow`; the reader read
it as `0 <= x`, true for every `x`. `(255 >> 1) >= y` for an `i8` `y` was verified the
same way, where rustc rejects `255` as `literal out of range for i8`. The left-shift forms
(`(!0 << 8) <= x`) and a wider partner (`(255 >> 16) <= a`) failed identically.
This is a *third* axis on the same theme. The width fix resized a typed constant; the fold
fix refused a fold whose value depends on its width. Here the operand is untyped and the
amount was checked against the *scope's* width — `smt::bits(left)`, 32 from the `u32` name
in scope — rather than the width Rust infers from where the shift is read, which can be as
narrow as 8 bits.
The fix is a refusal, in the same place: when the operand is untyped (`!sgn.fixes_type()`),
the shift is refused unless it is valid at *every* width it could be read at — the amount
below 8, and a bare or negated literal that fits an 8-bit signed value. An `Opaque`
operand (a complement, or a fitted fold) needs no value check: its value at any width is
`-1`/`2^W - 1`, which fits that width by construction. A shift of a *typed* name
(`x >> 1`) has a known width and is untouched, and `1 << 4` is `16` at any width, so both
still read — the controls the corpus pins.
**Why not check only the amount.** The 45 shapes split into two causes: an amount at or
above the partner's width (`255 >> 8`), and an operand out of the partner's range
(`255 >> 1` into an `i8`). Refusing only the first would leave `(255 >> 1) >= y` verified.
The operand's value is as much a width-dependent claim as the amount is, so both are
checked.
**Evidence.** The sweep drove 18744 shapes over the operator families; on it the reader
had **45** soundness holes, all shift-family, and **0** after the fix. The harness reads
rustc's diagnostics as JSON and attributes each error to its primary span, the corrected
form from the fold fix. A unit test
(`a_shift_of_an_untyped_constant_is_refused_when_it_needs_a_wider_operand`) pins five
refused shapes and five that must read; a corpus test asserts the tripwires
`contract_untyped_shift_amount_over_narrow_width_is_refused`,
`contract_untyped_left_shift_amount_over_narrow_width_is_refused` and
`contract_untyped_shift_operand_out_of_narrow_range_is_refused` are not decided against the
controls `contract_fitting_untyped_shift_still_reads` and
`contract_typed_shift_still_reads`. Test-count **546 → 548**; corpus **146/258 →
148/263**. Gate green.
The lesson: the fold fix's `Opaque` distinction generalised into a rule — a value with no
type of its own is only safe at an operator when it is valid at *every* width it could be
read at. The fold sweep asked the width question of the fold's *result*; this sweep asked
it of the shift's *operand*, and the same question found the next hole.
## The complement of an out-of-range literal is refused (the reader's own range check)
The same question the shift fix asked — *is this value valid at the width it will be read
at?* — found the next hole in the complement path. `resize_const`'s `Opaque` branch held an
untyped constant at the scope's width and truncated it to the operand with **no range
check**, because a complement's *value* is always the operand's low `W` bits and so fits
any `W` by construction. But Rust range-checks the complement's **operand**, not its value:
`!128` for an `i8` is a `literal out of range for i8` error even though the complement
`127` fits. The reader built `!128` as the constant `127`, marked it `Opaque`, truncated it
with no check, and so `ensures: y <= (!128)` read as `y <= 127` (`i8::MAX`) — a tautology —
and **verified** for a program rustc rejects. A false proof.
`Sign::Opaque` now carries the complement's operand literal (`Some(128)` for `!128`,
`None` for a fold like `!0 + 2`, whose operand is not a single literal). The payload is
the *bare-literal* operand only: a negated operand (`!(-1)`, `!(-128)`) is **not** tracked,
because Rust range-checks the negated value (`-1`, `-128`), not the magnitude (`1`, `128`),
and `!(-128)` for an `i8` is legal — tracking `128` there would be a false refusal. A nested
complement (`!!128`) propagates the innermost literal, since Rust checks that same literal
against the type the outermost complement meets. At `resize_const` the tracked operand is
checked against the type the complement meets — signed up to `2^(W-1)`, unsigned up to
`2^W - 1` — and a value that exceeds it refuses the shape.
The sweep: `diff_const.py` (rustc accept/reject via `--emit=obj` + exhaustive ground truth
over `u8`/`i8`/`u16`/`i16`) went from **23 discrepancies** to **14**, and every removed one
was the false proof — the surviving 14 are all *pre-existing* `reader=failed` on a
rustc-rejected shape (a wrong refutation, never a false proof), the broader same-family gap
below. `UNSOUND` stayed **0**. A unit test
(`the_complement_of_an_out_of_range_literal_is_refused`) pins four refused shapes and four
that read; a corpus test asserts the tripwire
`contract_complement_of_out_of_range_literal_is_refused` is `Skipped` against the decided
controls `contract_fitting_complement_still_reads` (`!127` for an `i8`) and
`contract_complement_reads_at_a_wider_operand` (`!128` for an `i16`). Test-count **583 →
585**; corpus **148/263 → 148/266** (the two controls decide, the tripwire is refused, so
the *decided* count is unchanged — the point is that the tripwire is no longer *verified*).
Gate green.
**Known, not-yet-fixed, same family (wrong refutations, not false proofs).** The 14
surviving discrepancies were the broader rule: **every literal in a constant expression is
range-checked against the inferred type**, not only the literal that meets the comparison.
`2 & 128` for an `i8` is `literal out of range for i8` even though the fold's value is `0`;
so are `255 - 128`, `200 & 63`, `100 & 255`. The reader range-checked the fold's *result*
(and the bare literal that meets a typed name) but not each operand's *literal*, so it
refused some of these via the overflow path and, where the value happened to fit, decided
them (`reader=failed`) instead of refusing — a wrong refutation on a program rustc rejects,
never a false proof, so it was a soundness-adjacent accuracy gap, not an unsoundness. **That
gap is now closed — see the next section.**
The lesson, once more: the `Opaque` distinction is a rule about *values with no type of
their own*. The width fix resized a typed constant, the fold fix refused a width-dependent
fold, the shift fix checked an untyped operand, and this fix range-checks a complement's
operand — each time the same question, asked of the next operand the reader had left
unchecked.
## Every literal in a constant expression is range-checked, not only the fold's value
The 14 surviving discrepancies from the complement fix named the next rule: **Rust
range-checks each literal and each constant `+ - *` intermediate against the type the
expression meets, not only the value the whole expression evaluates to.** `2 & 128` for an
`i8` is a `literal out of range for i8` error although the fold's value is `0`; `128 - 63`
is rejected although its value `65` fits. The reader *folds* a constant expression to a
single value (`smt::evaluate`), so the literal that caused the error is gone by the time
the comparison range-checks the result. It therefore **decided** these — `ensures: y ==
(200 & 200)` for an `i8` read as `y == 0` and *failed* — on programs rustc rejects: a wrong
*verdict*, never a false proof, but a verdict all the same.
The fix tracks an **envelope** — the `(min, max)` of the literals and folded intermediates
a constant term was built from — in a side table keyed by the hash-consed term id
(`Parser::range: BTreeMap<u32, (i128, i128)>`). Every literal-creation site records its own
value (`record_const`), every `+ - *` fold records the union of its operands' envelopes plus
its own result (`record_fold_result`), and `& | ^ << >>` propagate the union of their
operands' envelopes (`record_range_union`) because those operators add no literal of their
own. `resize_const` — the one place a constant definitively meets its type — then calls
`check_range`, which refuses if any recorded value does not fit the meeting type. Two
subtleties:
* **The pre-align operands, not the aligned ones.** `align_widths` rebuilds a constant at
the common width, and the rebuilt term carries no envelope, so each operator records the
union from the operands *before* alignment.
* **A bare literal under a unary `-` is the one exception.** `-128` is legal for an `i8`
even though `128` alone is not: Rust checks the *negated value* there, not the magnitude.
But a literal *inside* a fold is not rescued — `-(128 - 63)` is rejected for its inner
`128`, unlike `-(128)`. A `bare_literals` set of term ids tells the two apart: a negation
negates the operand's envelope (so `-128` carries `-128`, which fits) and drops the
operand's own value only when the operand is a pristine bare literal. `-(-128)` carries
`128` from the inner negation and is refused, as rustc refuses it.
One more shape the sweep found in the same family: a **complement used as a shift amount**
(`100 >> (!254)`). `!254` is `-255` at the `i32` Rust infers — a shift overflow — but `1` at
eight bits, so its value, and whether the shift is in range at all, depends on the width the
result is read at. `parse_shift` now refuses an opaque amount outright, while a bare literal
or a fold of bare literals (`1 + 1`) still reads.
**Evidence.** The sweep (`diff_const.py`, rustc accept/reject + exhaustive ground truth)
went from **14 discrepancies to 0** on the primary seed, and to **0–1** across seeds `7`,
`42`, `777` (`UNSOUND` stays **0** everywhere; the occasional residual was the same
pre-existing Opaque-fold-*value* class, wrong refutation only — **now closed, see the
sign-ambiguous-fold section below**). Unit test
`a_literal_inside_a_constant_fold_is_range_checked_too` pins seven refused shapes and six
that read, including the `-(128 - 63)` / `-128` pair; corpus test
`a_literal_inside_a_constant_fold_is_range_checked_too` asserts six tripwires are `Skipped`
against the decided controls `contract_fold_literals_in_range_still_read` and
`contract_bare_negated_bound_still_reads`. Test-count **585 → 587**; corpus **148/266 →
150/274** (six refusals, two decided controls). z3 oracle `mismatch=0`, kani
`mismatch=0`, gate green.
The lesson is the same question asked one level down: the complement fix range-checked the
literal that meets the type; this fix range-checks the literals that *fold into* it. A
folded value is a value, but the literals it was built from are still claims about a width.
## A fold of an untyped complement is refused when its value is sign-ambiguous
The residual the previous section named — the "Opaque-fold-*value*" class, 0–1
discrepancies on seeds `7`/`42` — was the same question asked of the fold's **signedness**
rather than its width. A complement has no signedness of its own: it takes the one the type
it meets gives it. `fold_const_arith` guesses that signedness from the *other* operand, and
when **neither** operand fixes a sign the guess can disagree with the reading the fold
finally gets — and the fold's value, and whether it overflows at all, change with it:
* `(!127) - 63` is `128 - 63 = 65` unsigned, but `i8::MIN - 63` — a rustc *overflow* —
signed. The reader guessed unsigned, decided `65`, and **FAILED** a program rustc rejects
(`y: i8`). `(!127) * 2` is the same shape (`i8::MIN * 2` overflows, `256` unsigned does
not).
* `(!100) * (-0)` is `E0277` (`cannot apply unary - to type u16`) when the fold meets an
unsigned type and legal when it meets a signed one. The reader guessed unsigned from the
operand it met and decided it — again a verdict on a program rustc rejects.
`fold_const_arith` now refuses an untyped fold when the two readings disagree. Two guards,
both only when **no** operand fixes a sign (`!sa.fixes_type() && !sb.fixes_type()`) and at
least one is opaque:
1. **A negated bare literal beside the complement** (`NegLiteral`) is refused outright: the
negation is legal only at a signed type, which the reader does not know.
2. **Otherwise the fold is recomputed under the other reading.** When the guess *fits* but
the other reading does not (or vice versa) the shape is refused. When the guess does
*not* fit, the pre-existing width-dependent refusal already fires and its message is
kept, so this fix only adds refusals for the shapes that were being *decided* wrongly.
The refusal is drawn at the ambiguity, not at `!`: `(!0) - 1` agrees under both readings
(`254` unsigned, `-2` signed, both in range at eight bits) and still reads; `(!127) - 63`
under a *wider* (`u16`) partner is `65345` under both readings and still reads. The trade-off
is the codebase's standing one — a genuinely ambiguous shape is **refused rather than
guessed** — so a few rustc-accepted shapes are now `skipped` where they were previously
`FAILED` (a wrong refutation, the milder error, traded for a refusal).
**Evidence.** The dedicated sweep `diff_opaque.py` (rustc accept/reject + exhaustive ground
truth, over expressions that *contain* a complement, and reporting the over-refusal quadrant
that `diff_const.py` does not separate out) went from **6/10/5 wrong verdicts** on seeds
`101`/`7`/`42` at the parent commit to **0/0/0** — and **0** on seed `777` — with `UNSOUND`
staying **0** everywhere. The primary sweep `diff_const.py` is now **0 discrepancies** on
seeds `101`, `7`, `42`, `777`, `13`, `99`. Unit test
`a_sign_ambiguous_untyped_fold_is_refused` pins the two ambiguous shapes at eight bits, the
`E0277` shape at sixteen, and three controls that still read; corpus test
`a_sign_ambiguous_untyped_fold_is_refused` asserts three tripwires are `Skipped` against the
decided controls `contract_sign_ambiguous_fold_at_wider_width_reads` and
`contract_agreeing_untyped_fold_still_reads`. Test-count **587 → 589**; corpus **150/274 →
152/279** (three refusals, two decided controls). Gate green.
The lesson, once more: the width fix asked *is this value valid at the width it meets?*; this
fix asks *is it valid at the signedness it meets?* A complement is a value with no type of
its own, and "no type" means no width **and** no sign — the reader must refuse the shape
whenever either is unknown and the answer depends on it.
## Two over-refusals in constant-fold sign handling (finding 1 and finding 2)
An AI review of the `license-arith-mir-oracle` branch flagged two shapes the reader refused
that rustc accepts. Both reproduce; both were regressions from `afc3daa` (the fold-literal
range check) and `8b761d2` (the complement-operand check).
**Finding 1 — a suffixed literal is range-checked by its *written magnitude*, not its value.**
`y == -128i8` for an `i8` was `skipped` (unreadable). `128i8` alone is a `literal out of range
for i8` error, and only `-128i8` is legal because the negation is what meets the type. The
suffixed-literal path recorded the *signed value* (`record_const`, which yields `-128` for the
pattern `0x80`), so the unary `-` then added `+128` to the envelope and refused the valid
`-128i8`; worse, the positive `128i8` — which rustc rejects — was read as the in-range `-128`.
The fix records the *written magnitude* (`record_range(v, n, n)` with `n` the parsed literal)
and inserts the term into `bare_literals`, so a direct unary `-` *replaces* the envelope
(`-128i8` reads) while `128i8` and `-(-128i8)` are refused. The same holds at `i16`
(`-32768i16` reads, `32768i16` refused).
**Finding 2 — a complement's operand envelope must not ride on the complement's *value* term.**
`x == !128 && y == 127` for a `u8` and an `i8` — both valid Rust — was `skipped`. At eight
bits `!128` is the constant `127`, which the SMT arena hash-conses with a separately written
bare `127`, so recording the operand envelope (`128`) in the term-keyed `range` map attached
it to that innocent literal and refused the whole contract. The envelope now travels in the
`Sign::Opaque` payload as an `(i128, i128)` *(min, max)* envelope instead of the `range` map.
It is unioned through folds (`Sign::union_env`) and threaded through the `&`-downgrade and the
unary `-`, both of which record it on their *compound* result term (a `Band`/`Sub` node, never
hash-consed with a bare literal) before the sign is downgraded and the envelope would be lost.
A nested complement (`!!128`) propagates the innermost envelope; `!(128 - 63)` carries
`(63, 128)` so the `128` is still refused.
**Evidence.** `diff_const.py` went from **166 discrepancies** on seed `1` at the parent
commit to **≤ 1**, with `UNSOUND` staying **0** on all ten seeds (`1 2 3 5 13 99 101 777 42 7`,
3000 iterations each ≈ 12 000 cases). The one residual is a pre-existing shift-amount class
(`31 >> (16 << 5)`), unrelated to sign handling. Unit tests
`a_suffixed_minimum_literal_is_checked_as_written` and
`a_complement_operand_does_not_pollute_a_bare_literal`; corpus test
`a_suffixed_minimum_and_a_complement_operand_are_checked_where_they_are_written`. Test-count
**589 → 592**; corpus **152/279 → 155/286**. Gate green.
The lesson: a literal's *range* is a property of how it is written, and provenance (which
literal an envelope came from) must travel with the *expression*, never be keyed on a value
term the engine hash-conses — a value term is shared by every expression that computes it.
## Two follow-ups to the constant-fold sign work (nested complement, named bound)
A second AI review of the same branch found two more shapes. The first was a **soundness
regression** the finding-1/finding-2 work introduced; the second is a **pre-existing
over-refusal** from the same root cause the memory note above already names (a value term is
shared by every expression that computes it), reached this time through a *named bound*.
**Follow-up 1 — a nested complement must *union* the envelope it inherited with the one its
operand recorded (regression, was a wrong verdict).** `y == !(!1 - 200)` for an `i8` is a
rustc `literal out of range` error for the `200`, but the reader *decided* it (baseline
`skipped`, my finding-2 code `FAILED`). The inner complement `!1` carries `(1, 1)` in its
`Sign::Opaque` payload; the fold `!1 - 200` records `200` on *its own* term via
`record_fold_result`. The outer complement's operand envelope used `env.or_else(||
self.range_of(v))`, which takes the inherited envelope *only when present* and so discards the
fold's own `200`. Fix: `Sign::union_env(env, self.range_of(v))` — the two sources are
independent and both must survive. `!(200 - !1)` and `!(128 - 63)` are refused too.
**Follow-up 2 — a named bound (`i8::MIN`) must not inherit a literal's envelope (pre-existing
over-refusal).** `y == -128i8 && y == i8::MIN` for an `i8` — both valid Rust — was `skipped` in
*either* conjunct order, as was `x == 128 && y == i8::MIN` for a `u8` and an `i8`. `i8::MIN`
and a bare or suffixed `128` are the same eight-bit bit pattern, so `smt::word(128, 8)` returns
*one* hash-consed term; `128i8` records the written magnitude `128` on it (finding 1), and
`resize_const`/the fold-union path then read that envelope back as the *bound's* and refuse a
bound that is in range by construction. Fix: build a named bound and an enum variant with
`unshared_const(k, w) = smt::truncate(smt::word(k, 64), w)`. The engine folds the `Trunc` to the
same value (`eval_term_body` folds `Trunc` of a constant), so the term *denotes* the bound
exactly, but it hash-conses separately from `word(k, w)` — no literal path ever builds a 64-bit
word for a value that fits `w`. It carries no `range` entry, so `check_range` passes it, which
is correct: the bound's fit is known.
**Evidence.** Unit test `a_nested_complement_keeps_the_fold_and_a_bound_keeps_its_own_fit`;
corpus entries `contract_nested_complement_fold_operand_is_refused`,
`contract_named_min_after_suffixed_min_reads`, `contract_suffixed_min_after_named_min_reads`,
`contract_named_min_after_bare_128_reads`, all pinned in
`a_suffixed_minimum_and_a_complement_operand_are_checked_where_they_are_written`. Differential
sweep: `UNSOUND: 0` on six seeds (`101 202 303 404 505 606`); the ≤1 residual discrepancy is
the same pre-existing nested-shift class (`-(3 << 7)`, `1 << (2 << 7)`), byte-identical on the
baseline build. `cargo test --features std` **558 → 559** passed, 0 failed (the new unit test);
corpus **287 → 291** functions typed, with the collision cases flipped from `skipped` to read.
Gate green.
The deeper lesson (already stated, now with a second example): the `range` map is keyed on the
*term*, and the engine hash-conses aggressively — not only a complement's value term but a
*type bound's* bit pattern is shared with plain literals. Any envelope recorded for one must
never be read back for another. Where a value's fit is known by construction (a bound, a
variant), give it a term of its own rather than trusting the shared one.
## A fold that touched a complement must not range-check its provisional value
The amount-width correction above and this one are the same question asked of a *value the
reader guesses* rather than one it reads. Here the guess is a signedness: `record_fold_result`
recorded a fold's own value for range-checking, but an `Opaque` fold is evaluated *unsigned*
at that point because its type is not known until it meets one. So `!1 + 1` recorded `255`
where the `i8` it finally meets makes it `-1`, and range-checking that guess refused the valid
`y == !(!1 + 1)` for an `i8`.
The fix records the result's own value only when the sign is not opaque. The operands'
envelopes still carry, so a genuine literal *under* the fold is still checked -- `!128` for an
`i8` is refused -- and the width-dependent refusal in `fold_const_arith` still fires before the
record, so no shape that rustc rejects is newly accepted.
**Evidence.** Unit test `an_opaque_folds_provisional_value_is_not_range_checked`; corpus
entries `contract_opaque_fold_provisional_value_is_not_range_checked` (reads) and
`contract_literal_under_complement_is_still_range_checked` (`Skipped`), pinned in the corpus
test of the same name. The entry was confirmed to have teeth: reverting the fix turns it red.
`cargo test --features std` 599 passed, 0 failed; clippy clean; MIR oracle `302/302 agree`;
corpus `decided 162 of 301`. Gate green.
The lesson: the reader must never range-check a *guess*. The amount floor's `i32` was a guess
about a type Rust leaves open, and the fold's unsigned value was a guess about a signedness
Rust leaves open; in both cases the guess was checked as though it were read, and a shape
rustc accepts was refused. A guess may guide a fold, but it must not become a refusal.
## A cast in a contract is a value the order can be asked about, not only a spelling to equate
The cast entries in the corpus all pin *equality*: `ret == x as u32`, and its tripwires. That
pins that a contract cast extends like Rust rather than reinterpreting, but it never asks the
reader to *decide* anything about the cast's value -- the comparison is between the cast and a
term the body also produces, so a reader that carried the cast as an opaque variable of the
right width would pass every one of them.
So the shape that was *supported until contradicted* is the cast under an order: `(x as i16) >= 0`
for a `u8` `x`, `(y as i16) <= 127` for an `i8` `y`. Both are decided by the reader's own
extend-then-compare, and both would be refused ("unknown sign") by a reader that lost the
cast's sign, which is the exact failure the equality entries cannot see. Five entries now carry
it -- three true, two tripwires:
* `contract_cast_relational_nonneg` (`u8`→`i16`, `>= 0`) and `contract_cast_relational_lt_width`
(`u8`→`i16`, `< 256`) state both ends of the zero-filled range, so neither is a constant the
reader could have folded to the answer.
* `contract_cast_relational_signed_bound` (`i8`→`i16`, `<= 127`) pins sign-extension *through the
order*: a zero-filling model would place `-1i8 as i16` at `255` and refute this at `y == -1`.
* `contract_cast_relational_signed_nonneg_tripwire` (`i8`→`i16`, `>= 0`) must be refuted at
`y == -1` (witness `v1:u8 = 128`, i.e. the bit pattern of `-128`), which a reader that dropped
the source's sign and treated the cast as unsigned would prove.
* `contract_cast_relational_positive_tripwire` (`u8`→`i16`, `> 0`) must be refuted at `x == 0`,
the lower bound the true entry above claims.
**Evidence.** The differential sweep is the reason the entries are trustworthy rather than a
guess: every cast of a small type (`u8`, `i8`, `u16`, `i16`) into every wider target (`u8`..`i32`)
under every comparison operator and constant, against an exhaustive Python model of the same
cast -- **2160 cases decided, 0 unsound, 0 discrepancies**. Two further sweeps closed the same
question for the neighbouring dimensions and are recorded here so they are not re-derived: a
hypothetical-reasoning sweep (320 `requires`/`ensures` pairs over one variable, exhaustive
ground truth) **0 unsound, 0 discrepancies**, and an end-to-end body sweep (14 arithmetic bodies
× 6 preconditions × 90 postconditions, each against a 256-value simulation) **7020 decided, 0
unsound, 0 discrepancies**.
The test `a_cast_in_a_contract_can_be_ordered` pins the five verdicts, so a reader that lost the
cast's sign is a failure rather than a quiet false proof. Corpus `decided 162 of 301` →
**`decided 165 of 306`**; `cargo test --features std` **599 → 600** passed, 0 failed. Gate green.
The lesson is the tripwire rule applied to a *value* rather than a name: "supported until
contradicted" is a statement about coverage, and a value can be read for equality in a hundred
entries while never once being asked to support an inference. The dimension to look for is the
one every existing entry holds constant -- here, that the only operator the cast ever meets is
`==`.
## A method the contract language does not read is an obligation silently dropped
The two-variable relational sweep (208 `requires`/`ensures` pairs over a `u8` `x` and `y`,
exhaustive ground truth over all 2^16 pairs) decided 120 and *skipped* 88. Every one of the 88
had the same cause: `x.wrapping_add(y)` in a contract was "cannot read contract". Since a
refused contract means the function is not verified *at all*, that is the worst outcome the
frontend can produce -- not a wrong verdict, but a silently absent one.
The fix is exact by construction, which is why it is safe: `a + b` in a contract already *is* a
bit-vector add, which wraps at the operand width, so `a.wrapping_add(b)` and `a + b` denote the
same term. `wrapping_add`, `wrapping_sub`, `wrapping_mul` and `wrapping_neg` are now read as a
postfix on an atom. The receiver's type must be *fixed*: rustc refuses `1.wrapping_add(2)` with
`E0689` (an ambiguous `{integer}`), so a bare-literal receiver is refused rather than silently
given the scope's width.
Two details are the whole subtlety, and both come from what Rust checks rather than what it
computes:
* The sugar must **not** run the constant-overflow fold. `200u8 + 100u8` is a rustc error, but
`200u8.wrapping_add(100u8)` is a legal program whose value is `44`, so the sugar takes the
engine's own wrapping value instead of `fold_const_arith`.
* The operands' literals are **still** range-checked against the type they meet: `x.wrapping_add(300)`
is a rustc error for its `300`. The wrapping semantics excuse the overflow of the *result*, not
an out-of-range literal, which is what `align_widths` already enforces.
`wrapping_neg` is `0 - x` at the operand's width and is legal for an *unsigned* receiver where
the unary `-` deliberately is not (`(1u8).wrapping_neg()` is `255`), so it is built as a `Sub`
rather than routed through `parse_neg`'s signed-only refusal.
**Evidence.** The relational sweep went from **120 decided / 88 skipped** to **208 decided / 0
skipped**, with **0 unsound, 0 discrepancies**. A second sweep pinned the sugar's *value* against
an exhaustive model over all four operators, both signednesses, and 8- and 16-bit widths:
**839 decided, 0 failures** -- where the body returns the model's constant, so only the contract's
value is under test. A third sweep, with Rust's own wrapping operation in the body, was
**0 refuted, 0 false proofs**; its 128 skips were all 16-bit `wrapping_mul` *bodies*, i.e. the
same documented scaling wall as `sat_mul`, not the contract.
The corpus carries eight entries and `a_wrapping_method_in_a_contract_is_read_as_the_operator_it_denotes`
pins them: five verified (`contract_wrapping_add_reads`, `..._sub_mul_chain_reads`,
`..._agrees_with_the_plain_operators`, `..._neg_on_unsigned_reads`, `..._neg_on_signed_reads`,
`..._add_of_constants_wraps`), one tripwire (`..._add_is_a_value_tripwire`), and two refusals
(`..._add_of_an_out_of_range_literal_is_refused`, `..._add_on_an_untyped_receiver_is_refused`).
The entry was confirmed to have teeth: returning early from `parse_wrapping_postfix` turns the
test red.
A note on the sweeps themselves, because two of them were wrong before they were right, and the
mistakes are the kind a differential oracle exists to catch. The first version wrote the *unary*
form `-127i8.wrapping_add(x)` in the contract and `(-127i8).wrapping_add(x)` in the body; Rust
binds a method call tighter than unary minus, so the two are `-(127i8.wrapping_add(x))` and
`(-127i8).wrapping_add(x)` -- different expressions, and the 220 "failures" were the sweep's, not
the engine's. The second version put the real `wrapping_mul` in the body and read the engine's
documented 16-bit incompleteness as a contract failure. A sweep that does not model its own
program correctly reports the engine's bugs as its own and its own as the engine's; each was
resolved by asking rustc what the program *means* (a MIR dump, not a guess) before believing the
verdict.
## The MIR frontend needs a `rustc`, not a *nightly* `rustc`
Two comments claimed otherwise -- `scripts/gate.sh` step 8 ("which needs nightly") and
`.github/workflows/ci.yml` ("because `rustc --emit=mir` needs a nightly") -- and both were wrong.
`-Zunpretty=mir` is nightly-only, but `--emit=mir` is stable, so a stable `rustc` reads the
whole corpus. Measured, not assumed:
| `1.85.1` (the MSRV) | `decided 185 of 340` | 142 passed |
| `1.99.1` (current stable) | `decided 185 of 340` | 142 passed |
Identical verdicts and an identical decided count on both, so the frontend is a stable-toolchain
tool. That parity is itself checked, not assumed: the first measurement of this session had the
MSRV at `181 of 340` and stable at `185 of 340`, and the four-entry gap was a real defect -- a
slice's length is printed `Len((*_1))` before 1.99 and `PtrMetadata(copy _1)` from 1.99 on, and
the parser's `trim_end_matches(')')` ate *both* trailing parens of the older spelling, leaving
`(*_1` unparseable, so the length read `Unknown` and the bounds check above `a[i]` went
unmodelled. `Rvalue::Len` is now modelled through the same `length_of` as `PtrMetadata`, and the
argument is closed with a single `strip_suffix` (see the `close_paren` note). The `Len` half was
invisible on the current toolchain alone; only running both toolchains surfaced it, which is the
point of the gate naming a second compiler.
CI still names a nightly, and that is fine -- the thing to keep straight is *why*: a
dump-format change is a real risk (the parser reads `rustc`'s text, so a printer change can break
it silently), and the `rustc_public` oracle in step 10 is what catches that. The nightly is
caution about the *format*, never a requirement of `--emit=mir`.
The `tools/mir-oracle` crate is the one piece that genuinely needs a nightly with `rustc-dev` --
it links `rustc` internals behind `#![feature(rustc_private)]` -- and it is deliberately *not* a
workspace member for exactly that reason. So "this project needs nightly" is true of a test
oracle and false of the crate and its MIR frontend. When a comment states a toolchain
requirement, check it against a second toolchain before trusting it; a wrong comment here is the
kind of thing that gets copied into a downstream build script and never questioned again.
**A second toolchain-shaped spelling: the `for`-loop range projection.** The same rule
found the next one. rustc prints the `for`-loop desugaring's `as`-projection with the
type *qualified* on current stable and *unqualified* on 1.85:
```text
1.99: <std::ops::RangeInclusive<u32> as IntoIterator>::into_iter
1.85: <RangeInclusive<u32> as IntoIterator>::into_iter
```
`names_range` required an `ops::` segment, so on the MSRV the type segment was
`RangeInclusive<u32>`, the predicate returned `false`, `classify` fell through, and
*every `for` loop over a range* was `incomplete: call to unmodelled function
<RangeInclusive<u32> as IntoIterator>::into_iter`. It was green on 1.99, so the only
thing that could see it was gate 14 -- the MSRV run -- and it did: four `tests/mir.rs`
cases (`a_signed_inclusive_range_stops_at_its_boundary`, `an_empty_inclusive_range_stays_empty`,
`a_loop_without_a_contract_names_the_missing_contract`, `the_for_loop_range_desugaring_is_modelled`)
were red on 1.85 and green on 1.99, exactly the shape the `Len`/`PtrMetadata` defect had.
The predicate now accepts the unqualified `as`-projection form too
(`name.starts_with("<RangeInclusive<") || name.starts_with("<Range<")`), pinned by
`the_for_loop_range_names_classify_in_both_toolchain_spellings`, which asserts both
spellings classify and that a user `m::RangeInclusive` is still refused.
The lesson is the one this section already states, made concrete a second time: a
predicate that keys on a *printed spelling* is a claim about a toolchain, and the only
way to know the claim holds is to run the second toolchain. The MSRV gate is not
ceremony around `cargo check` -- it runs the frontend's whole suite against the floor
rustc, which is what turns "supports 1.85" from a build into a behaviour.
**The unqualified spelling is also a name a user type can carry, so the range model
was made trait-aware -- and a review of that change found a *different*, pre-existing
false proof.** Accepting `<RangeInclusive<u32> as …>` accepts an *unqualified* type
name, and a user can write `struct Range<T>`. So the two `Iterator` methods are now
matched on the *trait* as well as the type (`names_std_range_trait`): `into_iter` only
for the standard library's `IntoIterator`, `next` only for `Iterator`. A user
`struct Range<T>` with a custom `into_iter` (`<Range<u8> as a::Custom>::into_iter`) is
refused, which is what the reviewer's report asked for.
Probing that shape turned up the real bug, and it was **not** the range model. The
reviewer's literal example -- a default `into_iter` that *panics* -- is already
**refuted** on the unmodified tree (`resolve_callee` finds the default body and inlines
it, so the panic is found). But the reviewer's *mechanism* is real: a trait **default
body** that calls a helper through `Self`:
```rust
pub trait T: Copy {
fn go(mut self) -> Self where Self: Sized { self.set(42); self }
fn set(&mut self, x: u8) { let _ = x; } // default: a no-op
}
impl T for P { fn set(&mut self, x: u8) { self.v = x; } } // the real one
```
The call inside `go` prints as `<Self as T>::set`. `call_type` gives `Self`, which no
`impl` candidate matches, so the search fell through to the *default-body* branch and
inlined the no-op `set` -- and a caller's `ensures: ret == 1` was **proved** against a
body whose real result is `42`. A false proof, **pre-existing** (it reproduces with the
`names_range` change stashed), and independent of the range model (it reproduces with
the model disabled entirely). `resolve_callee` now refuses a `Self` receiver outright:
resolving it would need the concrete `Self` the enclosing call was made with, which the
resolver does not carry, and answering it with the default is exactly the false proof.
The shape is a *refusal* now -- a lost proof, not a wrong one -- which is the honest
direction. Pinned by `a_user_type_named_range_is_not_answered_by_the_range_model` (the
range spoof, the `Self`-receiver false proof, and a positive control that a real `for`
loop still verifies); teeth confirmed by reverting the guard, which restores `verified`.
The general lesson, and it is the one this file keeps meeting: **when a report names a
mechanism, reproduce the mechanism, not the example.** The reported example was already
sound; the mechanism it described was a real hole one shape over, in a resolver the
report did not name. The probe is what separated the two.
## A tuple struct is a struct too: its fields are numbered by position
`struct_head` recognised only a *braced* body, so `pub struct Pair(pub u8, pub u8)`
was never read as a struct at all. The argument's type stayed an opaque `Other("Pair")`
with no layout, and a contract naming `p.0` was refused as "unknown name `p`" -- a
silently dropped obligation, not a wrong verdict, for one of the most ordinary shapes in
Rust. The old code documented this as a choice ("a tuple struct has no named fields to
project"), and the reasoning was sound for the reader it had: there was no way to name a
positional field. The fix is not to name it, but to number it -- the position in the
declaration *is* the MIR field index, exactly as declaration order is for a named struct.
The head parser now returns one of two shapes, and they are distinct because they carry
their fields differently: a named struct may close on its head line or need a cursor (the
`closed_inline` flag, which keeps an open cursor from swallowing every following line), and
a tuple struct carries its fields in the head and needs no cursor at all. A unit struct is
neither, so a contract naming `.0` on it stays an "unknown name" refusal rather than a
layout with no fields.
Seventeen corpus entries, pinned by six tests (`a_contract_can_name_a_tuple_struct_field`,
`a_tuple_struct_field_that_does_not_exist_is_refused`,
`a_nested_field_projection_is_read_and_agrees_with_the_body`,
`nested_leaves_under_different_paths_are_independent`,
`a_nested_field_write_through_a_mutable_reference_is_applied`,
`a_nested_seed_is_invalidated_by_a_write_and_carried_by_a_copy`):
| `tuple_struct_reads_its_field` | `&Pair`, `p.0 <= p.1` | verified |
| `tuple_struct_by_value_reads_its_field` | `Pair` by value | verified |
| `tuple_struct_signed_field_reads` | `&Delta(i8)`, `d.0 < 0` | verified |
| `tuple_struct_fields_are_independent` | `p.0 < p.1`, `ret == p.0` | **FAILED** |
| `tuple_struct_out_of_range_field_is_refused` | `p.2` on a two-field tuple | refused |
| `nested_tuple_projection_reads` | `n.p.0` | verified |
| `nested_tuple_projection_is_the_body_value` | `n.p.0 == 42`, body reads it | verified |
| `nested_tuple_projection_leaves_are_independent` | `n.p.0 < n.p.1`, `ret == n.p.0` | **FAILED** |
| `nested_path_off_the_layout_is_refused` | `n.p.q` | refused |
| `nested_named_field_reads_its_leaf` | `o.i.v == 7` | verified |
| `nested_named_field_is_the_body_value` | `o.i.v`, body reads it | verified |
| `nested_named_leaves_under_different_fields` | `o.i.v != o.j.v`, `ret == o.j.v` | **FAILED** |
| `nested_field_write_through_ref_mut_takes_effect` | `o.i.v = 5; o.i.v` on `&mut` | verified |
| `nested_field_write_through_ref_mut_is_not_dropped` | same body, `ret == 0` | **FAILED** |
| `whole_inner_write_makes_nested_seed_stale` | `o.i = Inner{..}; o.i.v` | not verified |
| `whole_struct_copy_carries_nested_paths` | `c = d; c.i.v` | verified |
Two of these are worth the ink. `tuple_struct_signed_field_reads` uses `d.0 < 0`: that
precondition is satisfiable *only* under the signed reading of the field, so a reader that
took the positional field as unsigned would find it unsatisfiable and refuse the contract as
vacuous -- `verified` is therefore the evidence the declared `i8` was read, not the dump's
unsigned default. And `tuple_struct_fields_are_independent` is the tripwire: with `p.0` and
`p.1` aliased to one variable, `max(v, v) == v` makes `ret == p.0` *true*, so a reader that
lost the second field would prove it; refuted is the evidence the two are distinct inputs.
**Evidence.** A differential grid against exhaustive ground truth over all 2^16 `(p.0, p.1)`
pairs: 7 bodies x 5 preconditions x 18 postconditions = **630 decided, 0 unsound, 0 false
refutations**; and for the signed field, 3 bodies x 4 preconditions x 36 postconditions =
**432 decided, 0 unsound, 0 false refutations**. **1078 cases, all decided, all agreeing
with the model.** A sweep that does not model its own program correctly reports its bugs as
the engine's: the first run had a `bool`-returning body in a `u8` function, which rustc
rejected, and the sweep read the resulting *driver* failure as "every case undecided" --
fixed by asking rustc what the program means before believing a verdict.
Corpus `decided 171 of 315` -> **`181 of 333`**; `cargo test --workspace --features std`
**601 -> 608** passed, 0 failed; z3 `mismatch=0`, kani `mismatch=0`. Gate green; zero
dependencies and `no_std` untouched.
Still not modelled, and named so the boundary is honest: a nested path whose *outer* field is
an array or slice (`a[0].v`, `xs[0].v`) is refused, because the chain a subscript selects is a
store entry rather than a field of a layout; and a tuple struct with more fields than
`MAX_VARS` allows refuses the binding rather than aliasing it, the same rule a named struct
follows.
## A field write through a `&mut` was dropped, which was a false proof and not a lost one
`Env::set` had an arm for `[Proj::Deref, Proj::Index(i)]` but none for
`[Proj::Deref, Proj::Field(i)]`, so `((*_1).0: u8) = const 5_u8` -- how a write to a
struct field through a `&mut` lowers -- fell to the catch-all and was dropped. The
`Deref` is what makes this shape distinct: `resolve` collapses `(*_1).0` to `_1.0`
only when `_1` is an argument whose target is recorded, so the store saw a
projection run it did not model and discarded it.
The consequence was two-sided, and both sides are worse than a missing proof:
- **A false refutation.** `c.lo = 5; c.lo` on a `&mut Config` kept reading the
*seed*, so a true contract was refuted with a witness (`v2:u8 = 0`) that no run
could produce.
- **A false proof.** With the write gone, `requires: true` / `ensures: ret == 0`
was **proved** against a body that returns 5, because the postcondition was
checked against the variable the write was supposed to replace.
The fix is one arm, `[Proj::Deref, Proj::Field(i)] => self.fields.insert(...)`,
which is the same store the read consults. The regression is toothed both ways:
`field_write_through_ref_mut_takes_effect` (`ret == 5`) must verify and
`field_write_through_ref_mut_is_not_dropped` (`ret == 0`) must be refuted. Drop the
arm again and the first fails while the second *verifies* -- the false proof comes
back, which is why both are asserted rather than only the positive one.
**The same hole one level down.** A *nested* path (`o.i.v`) needs its own store,
because a single field index cannot name a walk. Adding it exposed three sibling
rules that had to land together or the nested store would be unsound:
1. **A whole-aggregate write invalidates the leaves under it.** `o.i = Inner { .. }`
replaces the value `o.i.v` was a part of, so `forget_nested_under` drops every
chain with that prefix. Without it the seeded leaf survived the write and a
false contract about it could be *proved*.
2. **A whole-struct copy carries the nested parts.** `c = d` moved `fields` but not
`nested`, so `c.i.v` afterwards read `c`'s own seed -- a false refutation of the
true `d.i.v == 1`. `copy_parts` now moves the chains too, and `any` counts them
so a value that is *only* nested is still seen as parts rather than unknown.
3. **A nested read consults the nested store and nothing else.** `get` returns
`Unknown` for a chain of two or more fields when no contract bound it, rather
than falling through to the single-field walk, which would answer `(((*_1).0).0)`
with the *outer* field's value -- a wrong value, not a missing one.
**Evidence.** Corpus `decided 179 of 329` -> **`181 of 333`**; `cargo test --workspace
--features std` **606 -> 608** passed, 0 failed; `cargo clippy --workspace --features
std --all-targets -- -D warnings` clean; `scripts/gate.sh` green (bare-metal build,
zero-dependency and no_std gates included). Gate green; zero dependencies and `no_std`
untouched.
## A scalar reference argument's name is its *final* value; `old(name)` is its entry value
`Ty::Ref` is modelled as its referent, so a `&mut u16` argument's name in a contract
denotes the `u16` it addresses -- one word, the same one the body's `*c` reads and
writes. The first cut of C9 bound that name to the argument's *entry* value (the same
`arg_vars` map every by-value argument uses). That was a **false proof**: with
`requires: c == 0` / `ensures: c == 0` on `*c = 5`, the postcondition's `c` still named
the input, so the contract held and the function was reported `verified` for a body
that leaves 5.
The fix has two halves, and the second is the one that makes two-state specs possible:
- **A bare name in an `ensures` is the value at *return*.** The executor collects the
final value of every reference-to-scalar argument at the root `return`
(`ref_final`) and the `post` closure rebinds that argument's name to it, so the
postcondition is checked against what the body left there. A by-value argument is
*not* rebound: the body cannot write it, so its final value *is* its entry value and
a second binding would be the same word.
- **`old(name)` reaches the entry value.** The entry bindings are handed to the parser
as `old_args`, a map only `eval_ensures` fills. `old(c)` on a name with no entry
value is **refused**, not silently read as the name itself -- so `old` on a by-value
argument does not become a second spelling of the same thing. The lookup is gated on
a following `(`, so an argument literally *named* `old` still resolves.
`*c` is accepted as the explicit spelling of the referent `c` already denotes: the two
are one binding, because a contract is this crate's own language rather than a compiled
program. So the roadmap's exit shape, `fn bump(c: &mut u16)` with
`ensures: *c == old(*c) + 1`, now verifies, and its caller verifies through the inlined
body (`bump_scalar_ref_star` and `a_scalar_ref_caller` in `realistic.rs`).
The signed case is pinned by `signed_scalar_ref` (`&mut i16`, `ensures: c < 0`): an
unsigned reading would call `-1` the largest value, so the postcondition would be
refuted -- `verified` is the evidence the referent's sign was read. The false
directions are the teeth: `a_stale_scalar_ref_cannot_prove_this` (`ensures: c == old(c)`)
and `a_scalar_ref_write_cannot_prove_this` (`ensures: c == 0` on `*c = 5`) must both be
**refuted**, and each *verifies* under the pre-fix binding, which is what makes them
regression tests rather than happy-path assertions.
## A helper's write through a `&mut` argument died with the callee's frame
The inliner copied a callee's post-state back to the caller for exactly one kind of
argument: an *indexed* reference (`&[T]` / `&mut [T; N]`), which it tracked in
`Frame::by_ref_indexed` as a `(caller local, callee local)` pair. A `&mut u8` or a
`&mut Config` was not in that list, so a helper's `*v = 5` or `c.lo = 5` died with the
frame and the caller read its own seed. `requires: c.lo == 0` / `ensures: ret == 0` on
`set_lo(c); c.lo` was therefore **proved** against a body that returns 5 -- a false
proof, and reachable from ordinary code.
Three separate drops had to be repaired together, because each alone leaves the write
lost:
1. **The callee's own `(*_1) = v` was dropped.** `Env::set` resolved a lone deref of an
addressed local only via `resolve`, which rewrites an explicit `*_p` projection; but
`verify_fn` is the *only* place that marked a reference argument as dereferenceable
(`deref_ok`), and the inliner builds the callee's env itself. `(*_1) = v` there was a
deref with no recorded referent, so the write went to the catch-all. The inliner now
marks its reference arguments the same way `verify_fn` marks the root's.
2. **`set` did not strip a lone deref.** `*v = 5` on a `&mut u8` lowers to `(*_1) = v`
with an empty-projection *target*; `Ty::Ref` is modelled as its referent, so that is a
whole-place write to `_1`. `set` now strips a lone `Deref` of a deref-ok local so the
write shares the whole-place arm. `(*_1)[0] = v` and `(*_1).0 = v` keep their
projection and still reach their own arms.
3. **The write-back was indexed-only.** `by_ref` now holds *every* reference argument,
resolved through `pointee` (not `resolve`: `set5(&mut x)` hands the callee a temp
`_5 = &mut _2`, whose place has no projection, so `resolve` stops at `_5` and the
post-state would land on a dead temp). On return the callee's whole-place write,
field parts, nested parts and element store for that local are merged onto the
caller's storage. `Env::whole_writes` records which locals were assigned as a whole
place, so a helper that only *reads* through a `&mut` does not overwrite the
caller's value with the callee's unseeded `Unknown`.
The merge is per-direction: a *by-value* argument is still the callee's own copy and is
never copied back, which is what keeps `let b = f(a)` from mutating `a`.
**Carrying the state *in*, not only back.** A read-modify-write helper (`c.lo = c.lo + d`)
needs the caller's field seed to cross *into* the callee as well: with only the write-back,
the callee's `c.lo` read is `Unknown`, its add has an unmodelled operand, and the caller's
contract is left incomplete rather than checked. The argument's whole state -- element
store, single-field parts and nested parts, keyed on the pointee for a reference -- is
cloned into the callee's env. `read_modify_write_through_helper` goes from incomplete to
verified on this.
Nineteen corpus entries, pinned by four tests
(`a_helpers_write_through_a_mutable_reference_reaches_the_caller`,
`a_helpers_nested_and_read_modify_write_through_a_reference_are_modelled`,
`a_helper_write_lands_on_the_targets_projection`,
`an_element_target_is_written_and_a_by_value_copy_is_not`). The first seven are the
write-back itself:
| `helper_field_write_reaches_the_caller` | `set_lo(c); c.lo` | verified |
| `a_stale_caller_field_cannot_prove_this` | same body, `c.lo == 0` / `ret == 0` | **FAILED** |
| `helper_scalar_write_reaches_the_caller` | `set_five(&mut x); x` | verified |
| `a_stale_caller_scalar_cannot_prove_this` | same body, `x == 0` / `ret == 0` | **FAILED** |
| `helper_nested_write_reaches_the_caller` | `set_nested(o); o.i.v` | verified |
| `a_stale_caller_nested_cannot_prove_this` | same body, `ret == 0` | **FAILED** |
| `read_modify_write_through_helper` | `c.lo = c.lo + 5` one frame down | verified |
The false entries are the teeth: with the write-back removed, each of them *verifies*
against a body that returns 5, and the positive entries are refuted. Both directions are
asserted for that reason.
**The write-back keys the target's projection.** The first version of the write-back
wrote the callee's whole-place value to the caller's *local*. That is right for `&mut x`
-- `x` is the target -- and wrong for `&mut c.lo`, where the target is `c.0`: the value
landed on `c`, which put a bit-vector where a struct lives and left `c.lo` at its seed.
So `set5(&mut c.lo); c.lo` with `c.lo == 0` **proved** `ret == 0`. The merge now hands
the value to `Env::set` keyed on the target place, which files it under the field and
drops the parts that write replaces; a whole-local target additionally records the
whole-place write. Three shapes fall out of that, each with its false twin:
| `helper_write_reaches_a_field_target` | `set5(&mut c.lo); c.lo` | verified |
| `a_stale_field_target_cannot_prove_this` | same body, `c.lo == 0` / `ret == 0` | **FAILED** |
| `helper_write_reaches_a_nested_target` | `set5(&mut o.i.v); o.i.v` | verified |
| `a_stale_nested_target_cannot_prove_this` | same body, `o.i.v == 0` / `ret == 0` | **FAILED** |
| `conditional_helper_write_reaches_the_caller` | `if c { *v = 5 }; x` | verified |
| `a_conditional_helper_write_cannot_prove_this` | same body, `x == 0 && c == true` | **FAILED** |
The conditional pair is the one that pins *branch* propagation rather than the write-back
alone: the callee writes on one path and not the other, so the caller's value has to come
back from the path taken. With the write-back removed, the flag case would read the seed
and the `ret == 5` contract would be refuted while the `ret == 0` twin *verified*.
**The copy-back is per-store, and only for a whole-local target.** Gating the *element*
copy-back the same way exposed the other half of the same idea. A reference to an element
(`set_five(&mut a[0])`) hands the callee a *scalar*; the callee's store for that local is
the caller's array, carried in so its read is modelled. The callee's whole-place write
poisons that store, and copying it back unconditionally made the caller's *untouched*
`a[1]` read unknown -- an incomplete contract where a decision was available. The element
copy-back now runs only for a whole-local target, so `an_element_write_leaves_its_sibling`
decides while the false twins stay refuted.
The opposite direction is pinned in the same test: a callee that writes its own *by-value*
argument (`set_five_by_value(x)`) must leave the caller's value alone, so
`a_by_value_callee_write_stays_in_the_callee` verifies and the `ret == 5` twin is refuted.
That is the boundary the whole write-back exists to keep: a reference shares storage, a
value does not.
**Methods are inlined by their tail, and an ambiguous tail is refused.** rustc defines an
inherent method as `<impl at file:line:col>::set_lo` and calls it as `Config::set_lo`, so
the fallback name match -- which compared the call against the whole definition name --
never fired for a method: *every* method call was "unmodelled function", and a method's
write through `&mut self` was invisible to its caller. Cutting both sides to the last `::`
component fixes that, but the tail is not unique in general (`set_lo` can be a method *and*
a free function), so the match is required to hit exactly one definition. An ambiguous tail
is refused, because picking either body would inline the wrong one and *prove* a false
contract -- `an_ambiguous_method_tail_cannot_prove_this` pins that (`Widget::twist` vs a
free `twist`) and is `incomplete`, not `verified`. Six entries with their false twins,
pinned by `a_method_is_inlined_by_its_tail_and_an_ambiguous_tail_is_refused`.
The five shapes a method takes were then probed and all decide: a generic receiver
(`Wrapper<u8>` monomorphised), an associated function feeding a `&mut self` builder that
returns `&mut Self`, a trait method on a concrete receiver, and a `&self` read -- on a
tuple struct and with an argument. They are in the same test.
Two more sub-place targets are decided and in the corpus: a *reborrow* (`set_five(&mut
*r)` where `r: &mut u8`, which `resolve` collapses onto the caller's `x`) and a *tuple
component* (`&mut t.0`). Both verify, both have a refuted false twin.
A shape that is *refused* rather than decided, and named so it is not mistaken for a
decision: a place like `o.a[0]` -- an element of a struct's array field -- is not readable
in a contract (`unknown field`), because `Ty::Struct` has no layout, so a contract naming
it is skipped and a bare `ret == 5` there goes `incomplete`. That is a missing decision,
not a wrong one: the write itself lands, and no false contract is proved.
**A reference argument is read through, not just written through.** Carrying only the
target's *parts* into a callee left its argument local holding the reference temp's
`Unknown`, so `*v` was an unmodelled operand: a helper that *read* its referent (`*v`,
`*v = *v + 1`, a two-reference `swap`) could not be decided at all, while a helper that
only *wrote* (`*v = 5`) worked -- the write created the value the copy-back then read. The
value *at the target* is now carried in through `get`, not out of `locals`, because a
sub-place target has no whole-local entry.
The write-back had the matching hole, and it was a **false proof**: for a sub-place target
(`&mut o.i`) the part keys were dropped unless the target was a whole local, so
`set_inner(&mut o.i); o.i.v` read the caller's seed -- the true `ret == 5` was refuted and
the false `ret == 0` was proved. Every key is now re-based on the target's projection
(`rest ++ key`), and the carry-in is its exact inverse (drop the target's chain from the
front), routing a one-step remainder to `fields` and a longer one to `nested`. Fourteen
entries with their false twins, pinned by
`a_reference_argument_is_read_and_written_through_its_target`.
**A method receiver is a sub-place like any other argument.** With the tail match, the
carry-in and the re-based write-back in place, the receiver *shapes* decide through the
same path: a nested-field receiver (`o.i.set_leaf(5)`), two calls in sequence, a
reborrowed receiver (`let r = &mut o; r.i.set_leaf(5)`), a `&self` read feeding a `&mut`
write, and a leaf write that leaves the target's sibling at the caller's seed. Ten entries
with their false twins, pinned by
`a_method_receiver_is_a_sub_place_like_any_other_argument`. A whole-aggregate replacement
through a sub-place target (`*i = n` for `&mut o.i`) also decides: the moved value's leaf
reaches the caller's `o.i.v`, the sibling `o.j.v` keeps its seed, and a value built in a
local behaves the same -- see "A whole-aggregate replacement through a sub-place target
decides" below.
**A reference crosses a call in both directions.** A reference *returned* by a helper was
the sharpest case, and it was a **false proof**: `let r = identity(&mut x); *r = 5` lowers
to `_3 = &mut _1; _2 = identity(_3); (*_2) = 5`, so the write is keyed on a local the
*call* defined. `addressed` cannot cross a call -- the callee's local indices mean nothing
in the caller's frame -- so `_2` had no address, `*_2 = 5` was a write to a local no caller
reads, and `requires: x == 0` / `ensures: ret == 0` was **proved** against a body that
returns 5, while the true `ret == 5` was refuted. A separate `ref_origin` map records
which *caller* local a reference was built from (`_3 = &mut _1` records `3 -> 1`), is
carried into the callee for a reference argument, and is applied to the caller's
destination when the callee returns.
The guard is on the *source* of a copy, not the destination: `_3 = copy (*_1)` copies a
scalar *through* a reference, and carrying an address there gave a scalar one -- in a
two-reference `swap` both scalar copies then claimed the same storage, which broke the
swap and proved a false contract. Only a plain reference local is carried. Six entries with
their false twins, pinned by `a_reference_crosses_a_call_in_both_directions`.
**A method may return a reference to its own field.** `*c.lo_mut() = 5` was another
**false proof**. Inside the callee the returned reference is `&mut (*_1).0` -- a place in
the *callee's* terms -- and `ref_origin` recorded only a local, so the projection was lost,
the returned reference named nothing, the write was dropped, the true `ret == 5` was
refuted, and the false `ret == 0` was **proved**. `ref_origin` now holds a `Place`, and an
`arg_source` map records, for each reference *argument*, the place it denotes in the
*caller's* frame. A returned reference is translated by looking up its head in
`arg_source` and appending the returned projection: `_1` is the caller's `c`, so `_1.0` is
`c.lo`. A head that is *not* an argument is the callee's own storage, which dies at
return, so nothing is recorded and the write is dropped rather than aimed at a foreign
place. Six entries with their false twins, pinned by
`a_method_may_return_a_reference_to_its_own_field`.
**A returned reference carries its whole projection, from whichever argument.** Two
extensions of the same translation, both already covered by the `Place`-valued
`ref_origin` and the `arg_source` lookup, and now pinned. The returned place may be
*nested* (`&mut o.i.v`), so the whole projection has to survive, not just the head local;
and it may name a *different* argument than the first (`pick_second(&mut a, &mut b)`), so
the lookup must use the head local's own entry rather than assuming argument 0. A write
through a nested returned reference also leaves its sibling (`o.j.v`) at the caller's seed.
Seven entries with their false twins, pinned by
`a_returned_reference_carries_its_whole_projection`.
**A returned reference composes with its next use.** A reference from one call fed
straight into another (`write_one(identity(&mut c.lo))`), a reborrow of it (`let s = &mut
*r`), two returned references to *different* fields held at once, and a returned reference
to a *tuple component* all decide through the same `addressed` mapping. A returned place
whose key cannot be spelled stays sound-incomplete: the true contract is refused rather
than the write being dropped, which is the honest failure mode. (An *array element* was
once in this class; it now decides -- see the next paragraph.) Eight entries with their
false twins, pinned by `a_returned_reference_composes_with_the_next_use`.
**A returned reference to an array *element* re-bases onto the caller's element.** The
origin of `&mut a[0]` names the element index with a *local* (`_2` for the literal `0`),
and the whole-array form is `(*_1)[_2]` -- a deref of the reference argument followed by
the index. Two things then had to change at the return translation, and the failure mode
differs between the two forms. A *method* (`&mut self.a[0]`) carried the index local
through the call boundary, leaving a place no `elems_path` entry is keyed by: the write was
dropped and the contract was unreadable, `Incomplete` in *both* directions. A *free
function* handed the whole array (`elem_mut(&mut x.a)`) appended the argument's deref into
the middle of the caller's place: the write was dropped, the caller read its own seed, and
the false `ret == 5` was **proved** -- a false proof, not a lost one. The fix resolves the
`IndexVar` to its literal while the callee's locals are still live (`pin_index_vars`) and
strips the argument's leading deref (whose referent `arg_source` already names). The true
directions now verify and every false twin is refuted; a *symbolic* index is left unpinned,
so an unguarded `x.nth_mut(i)` stays fail-closed while `requires: i == 0` decides. Twelve
entries -- five true directions and seven false -- pinned by
`a_returned_reference_to_an_element_reaches_the_caller`.
**Two reference targets in one call stay independent.** Two `&mut` to different
*aggregate* fields (`&mut o.i, &mut o.j`) and two *elements* of one array through one
`&mut` (`set_two_elements(&mut a)`) each keep their own write, and the swap shapes read
both referents so they also exercise the carry-in. The false twins read the *other*
target and would verify if the two collapsed onto one place. Ten entries, pinned by
`two_reference_targets_in_one_call_stay_independent`.
**Not yet modelled, and *silently* so.** An *array of arrays* (`m[1][0]`) cannot be named
in a contract at all -- the refusal is `unknown name`, and an `ensures` about the value is
reported as unreadable, so such a function is *skipped* rather than decided. This is a
coverage hole rather than a soundness one (nothing false can be proved, since the contract
cannot be written). A *field whose type is an array* (`o.a[0]`) used to be in this hole and
is now modelled: the element store is keyed by the whole path, so a contract's `o.a[0]` and
the body's `(_1.0)[_2]` are one word. See "An array element reached through a field path"
below.
**An array element reached through a field path is one word.** `x.a[0] = 9; x.a[0]` lowers
to `(_1.0)[_2] = 9` and `_0 = copy (_1.0)[_4]`: the *field chain* is part of the element's
key, not the local and index alone. Before this the write landed in a store keyed by the
local and index, so the read consulted a different key, returned the *seed*, and a contract
claiming the pre-write value (`ret == 5`) was **proved** against a body returning 9 -- a
false proof, not a lost one. The store (`Env::elems_path`) is keyed by
`(local, field chain, index)`, so `x.a[0]` and `x.b[0]` cannot collide; a sibling array's
element is left alone and the two are independent. The contract side records every
array-typed field as subscriptable (`FieldEnv::path_elem_types`, both first-level `x.a` and
nested `o.i.a`), binds `path[digits]` to a variable of the element's own width and
signedness, and refuses an index past the array's declared length rather than binding a
variable for an element that does not exist. The mangled name is built from the *chain*,
never the dotted path: a `.` in a generated name would be read by the parser as a field
access. The symbolic subscript `(_1.0)[_4]` reads and writes the same store, and an index
the run cannot pin poisons the path rather than guessing. Four entries with their false
twins, pinned by `a_field_array_element_is_one_word_for_contract_and_body`.
**A field-array element crosses a reference argument in both directions.** A helper's write
to `x.a[0]` through a `&mut` lands in the *callee's* element store, so the caller's store has
to be re-based on return: unchanged for a whole-local target (`set_first_element(&mut x)`),
and prefixed with the target's chain for a sub-place one (`set_holder_first_element(&mut
o.i)` makes the callee's `_1.a[0]` the caller's `o.i.a[0]`). Without the re-base the write
died with the frame, the caller read its seed, and the false `ret == 5` was **proved** against
a body returning 9. The read direction is the same re-base run the other way, on the way
*in*: `read_holder_first_element(&o.i)` reads the caller's `o.i.a[0]`, so its contract
decides rather than being unreadable. A by-value argument is deliberately *not* carried back
(its writes die with the frame), and the sibling element of another array is untouched. Three
entries with their false twins, pinned by
`a_field_array_element_crosses_a_reference_argument`.
**A scalar field crosses a reference argument.** A helper reading `d.v` through a
`&DuoBox` and one writing it through a `&mut DuoBox` both decide: the referent's *parts*
are carried in, so the callee's `d.v` resolves to the caller's `d.v`, and the write-back
re-bases on the target's projection (empty for a whole-local target). Four entries with
their false twins, pinned by `a_scalar_field_crosses_a_reference_argument`. An enum
*payload* through a reference (`*e = E::A(5)`) stays sound-incomplete -- the discriminant
switch is unmodelled -- which is the honest refusal rather than a dropped write.
**A reference reached through another reference.** `**rr = 5` on a `&mut &mut u8`
lowers to `_4 = <retag marker> copy (*_3); (*_4) = 5` with `_4: &mut u8`, and the marker
is toolchain-specific: `no_retag copy` on 1.99+, `deref_copy` on 1.85. Neither was
recognised, so the rvalue fell to `Rvalue::Unknown`, `_4` got no address, and `(*_4) = 5`
was dropped -- the *false* `ret == 0` was **proved** against a body that returns 5 and the
true `ret == 5` was refuted. Both markers are now peeled to a plain copy, and the
deref-of-a-reference copy carries its address when the *destination's* type is a
reference (the source projection is a deref in both the reference and the scalar case, so
the type is the only discriminator). A read `**rr` had the same hole. Peeling the marker
from *every* rvalue instead of just `copy`/`move` moved 114 verdicts, most of them wrong:
`no_retag &mut _1` and `no_retag (*_1)` in receiver lowering carry meaning the copy does
not. Six entries with their false twins, pinned by
`a_reference_through_a_reference_is_not_dropped`.
**A reference to a reference across a frame is refused.** A local chain
(`(**rr).lo = 5`, or `*r = *s` between two `&mut` to different fields) resolves inside
one frame and is modelled. The *argument* case is not: `relay(&mut r)` with
`relay(v: &mut &mut u8) { **v = 5 }` has the outer referent in the caller and the callee
reaching it with its own local index, so the write was dropped and the false `ret == 0`
was **proved** against a body that returns 5. A call whose callee takes a `&mut &mut T`
is now refused outright (`call to a function taking &mut &mut T is not modelled`) rather
than modelled wrongly -- the true contract stays unproved, which is the honest failure
mode. Five entries, pinned by
`a_reference_to_a_reference_crosses_a_frame_only_when_refused`.
**A false-direction probe may never verify.** Every contract in the corpus that the body
refutes is spelled `..._cannot_prove_this`, and
`no_cannot_prove_entry_is_ever_verified` sweeps the whole file asserting that none of them
is `verified`. It is weaker than the per-shape assertions on purpose: a probe may be
`Failed`, `Incomplete` or `Skipped` and the test passes, because all three are honest
answers and only `verified` is a lie. The value is that a *new* false proof of an already
known shape now fails the gate in the commit that introduces it, without anyone having to
remember to assert the twin. The count is asserted too (`>= 40`), so the test cannot go
vacuous if the naming convention drifts. Verified to fail by injecting a true contract
under a `_cannot_prove_this` name.
**A callee contract is never assumed.** The engine inlines a callee's body rather than
trusting its `ensures`, so a lying helper cannot hand a caller a proof, and a callee whose
`requires` is *unsatisfiable* cannot be used to assume a false postcondition. The one
contract that *is* assumed is the function's **own**, and only for a self-call that names a
`decreases:` measure: there the assumption is the induction hypothesis, and the measure is
what makes it well-founded rather than circular. Mutual recursion gets no such route. One
honest incompleteness is pinned rather than left implicit: a callee's
`requires` is **not** an obligation at the call site, so a violating call is decided from
the inlined body -- sound because the body's own panics (a division by zero, say) still
fail the path, but not a precondition check. That entry is named `..._is_not_checked`, not
`..._cannot_prove_this`, so the corpus-wide probe invariant does not count it. Pinned by
`a_callee_contract_is_never_assumed`; loop-invariant initiation and preservation are pinned
by the same test.
**Environment note.** `scripts/gate.sh` step 6 hard-fails when the `z3` Python module is
missing, because an unavailable oracle is not evidence. It is a *test* oracle, not a
dependency -- the crate stays zero-dependency. A fresh container needs
`python3 -m pip install z3-solver` before the gate can go green.
**The shift amount is read at its own width.** `smt::shift_var` built its per-stage mask
at the *value's* width, so `n & mask` for `_1: u8, _2: u32` mixed 32 bits with 8; the
query came back ill-formed and the frontend answered `incomplete`. Only the symbolic path
saw it -- `evaluate` folds an ill-formed term anyway -- so `u8 >> u32` was refused while
`u8 >> u8` verified, which is why the existing shift tests (all of which pass the amount at
the value's width) missed it. The regression test must go through `prove`, not `evaluate`,
or it guards nothing; both are present and the symbolic one was checked against the
unfixed code. Pinned by `a_wider_shift_amount_is_read_at_its_own_width{,_symbolically}`.
**A constant multiply is decided without a wide multiplier.** `a * 2` at `u32` was
`incomplete` -- the general overflow path used to widen to `2w` and refuse past 16 bits --
while the same expression at `u8` verified, so the gap was width-only. With one operand a
constant, `x * c` wraps exactly when `x > MAX / c`, which is one comparison against a
compile-time constant; `i * 4` (an index scaled by an element size, usually `usize`) is the
shape it is for. Unsigned only, because the signed constant case has its own two-ended
range in `signed_mul_wraps_at`; the general signed path no longer widens either.
`overflow_pred`'s exactness is checked exhaustively at `u8` (all 256 values against every
constant) and at the `ceil(2^32 / c)` boundary for `u32` by
`a_constant_multiply_overflow_is_exact`, which was confirmed to fail on an off-by-one
predicate.
**`blast` multiplies by a constant as a sum of shifts.** With one operand a `Const`,
`Op::Mul` in `blast` is `sum over the set bits k of c of (x << k)` -- the distributive law,
so exact -- instead of the `w`-by-`w` schoolbook rows. That is `popcount(c)` shift-adds
rather than `w^2` AND/XOR rows, which is what lets the frontend's overflow predicate run at
`u32`/`usize` width for `i * 4`-shaped code (and at `i32`, which the signed bound used to
refuse). Cost at 64 bits is the *size* of the shifts, not just the popcount: `x * 4` decides,
`x * 17` (`x + (x << 4)`) is already `Unknown`. `i64` signed stays `incomplete` -- there is
nowhere to widen to at the widest width -- and is pinned by a corpus entry.
**The dropped carry, and why the first test missed it.** The shift-sum adder was written as
`out ^ shifted` and a carry, forgetting the `^ carry` in the sum; the carry-out was right, so
it agreed whenever the accumulator bit matched the shift. The first test for this swept
`x * c` exhaustively against Rust's `*` and passed -- because `evaluate`, the term folder,
has its own `wrapping_mul` and never calls `blast`. `prove` calls `blast`. A concrete test
written with `evaluate` is therefore no evidence at all about the bit-blaster, which is the
same trap the `shift_var` bug set. `tests/mul.rs` now labels each test with the layer it
covers, and the ones that matter go through `prove` against an independently built shift sum
(`smt::shl`/`smt::add`), which shares no code with either multiply arm. Both were confirmed
to fail on the dropped carry.
**The two evaluators are checked against each other, per operator.** `evaluate` (the term
folder) and `blast` (the bit-blaster behind `prove`) are independent implementations of the
same operators, and both bugs above landed in `blast` while a concrete `evaluate` test passed.
`tests/op_differential.rs` closes the class instead of the instance: for every binary operator
it sweeps the whole 4-bit domain with both operands symbolic *and* with a `Const` on either
side, and for `truncate`/`sign_extend` it sweeps narrowing and widening separately, asserting
`evaluate` and `blast` agree at every point. The two sweeps are deliberately separate: the
symbolic-only version passed on a `blast` whose constant arm had the dropped carry, because
`var * var` never reaches that arm.
**A test that does not reach the branch guards nothing.** The `truncate` sweep was first
written with only narrowing widths, so the zero-fill-on-widen branch was never taken, and a
deliberate corruption of that branch went undetected -- the same shape as the two bugs above,
one level down. Every branch named in a test's doc-comment is now confirmed to be reachable by
corrupting it and watching the test fail. That check is what the tests below are worth; the
`evaluate`-vs-`blast` sweep, the `truncate` widening sweep, and the constant-multiply arm were
each confirmed to fail on a corrupted `blast` before being kept.
**The signed story is pinned against Rust's own order.** `slt` has no `Op::Slt`: it is
`negative` and the *unsigned* `ult`, on the reasoning that equal signs make the two orders
agree and differing signs mean the negative one is smaller. That reasoning carries the
signed-cast and signed-overflow paths, so it is swept exhaustively at 4 bits against `i8` --
including the unsigned pair, since a wrong `ult` is a wrong `slt` at equal signs. The
constant-amount shifts are swept past the width too, because `blast` and the folder compute
the `k >= w` boundary in visibly different ways (`bit >= sh` and `sh < w - bit` versus
`sh >= w`), and an arithmetic shift there must fill from the sign bit rather than with zero.
Corrupting `slt` to use the wrong sign case, corrupting the `ashr` sign-fill to a zero-fill,
and making `ult` skip the top bit are each caught (`4-bit 0 < 8`, `4-bit 8 ashr at 4 bits`,
`4-bit 0 <= 8`).
**`ite` and the divider, through `prove`.** `ite` reads its condition differently in the two
evaluators -- `blast` selects on `c[0]`, the folder branches on `c != 0` -- so both arms are
swept with the condition true and false; swapping the arms is caught at `1-bit 0 ite-taken`.
The divider is *built* from primitives rather than being an `Op`, so there is no second arm to
compare against, but the built circuit is what `prove` reasons over and is a different object
from the folder that reads the same term: it is now asked point by point at widths 1, 2 and 4,
and asked its defining identity (`x == q * y + r`, and `y != 0 => r < y`) as a single validity
query. Width 1 is the important one -- `divmod` has a *separate* implementation there (`x & y`
and `x & !y`) with its own `y == 0` case, and the first version of the test asked only 4.
Dropping that `y == 0` case is caught at `1-bit 0 / 0`.
**Signed constant multiply is decided at every width, `i64` included.** The general multiply
path widens to `2w` and refuses past 16 bits; at `w == 64` there is no wider width at all, so
`a * 2` on an `i64` was `incomplete`. The constant path needs no product: `x * c` is monotone
on each side of zero, so it leaves the signed range on a prefix `x < lo` or a suffix
`x > hi`, and both bounds are a division of a range end by `c` in `i128` -- compile-time
constants. For `c > 0` the bounds are `ceil(MIN / c)` and `MAX / c`; for `c < 0` the product
*decreases*, so the two ends swap. `c == 0` is excluded (it would divide by zero) and `c == 1`
returns early. The predicate is exact, not merely sufficient, so it is checked two-sided
against Rust's `checked_mul` -- exhaustively at 2..5 bits over both signs of `c`, and at 64
bits across each constant's own boundary.
**`c == -1` does overflow, at exactly `MIN`.** The first version special-cased `-1` as never
wrapping, on the reasoning that `MIN * -1` "wraps back to `MIN`" -- which is true of the
*wrapped* result and is the overflow. `-1 * MIN` is `2^(w-1)`, one past `MAX`. That is the
weak-predicate direction, which makes an overflowing `assert` discharge; the exhaustive sweep
caught it at `2-bit -2 * -1`, and a corpus entry now pins it at `i64::MIN`. Dropping the low
bound is caught at `2-bit -2 * -2`, and swapping the negative-`c` bounds at `2-bit 0 * -2`.
**Evidence.** Corpus `decided 181 of 333` -> **`257 of 478`**; `cargo test --workspace
--features std` **608 -> 652** passed, 0 failed, on both `1.99.1` and the MSRV `1.85.1`;
`cargo clippy --workspace --features std --all-targets -- -D warnings` clean;
`scripts/gate.sh` green (bare-metal build, zero-dependency and no_std gates included), z3
`mismatch=0`, kani `mismatch=0`. Zero dependencies and `no_std` untouched.
Still not modelled, and named so the boundary is honest: the write-back merges the
callee's state for a reference argument, so a callee that stores a *coarser* shape than
the caller reads (`&mut _1.0` handed over as a whole-place target) drops the caller's
parts under `_1` rather than tracking the sub-place -- precision is lost, never a stale
value kept. A `&mut` target whose element the callee *did* write is still not copied back
(a `&mut [T]` argument is the case that is); the caller's own store keeps the value it
held, so the read is stale rather than unknown only when the caller never wrote it.
**An array handed over *as* a reference target is modelled.** When the argument is the
*array itself* rather than the whole local that holds it -- `set_first_of(&mut x.a)` or
`peek_of(&x.a)`, a `&mut [u8; 4]` / `&[u8; 4]` whose target is the field `x.a` -- the callee's
`(*_1)[0]` write is re-based onto the caller's field-path element store, so
`set_first_of(&mut x.a); x.a[0]` *decides*: the true `ret == 9` verifies and the false
`ret == 5` is refuted. This used to be a coverage hole (incomplete in *both* directions) and
is the shape the note below pinned before it was closed.
The mechanism, and why it took a second store: the callee's `&mut [u8; 4]` argument is the
array, so its element write lands in the callee's plain element store (`elems`), keyed by the
local. The caller's `x.a[0]` read consults `elems_path`, keyed by the *field chain* `x.a`. The
return path already re-based the callee's `elems_path` entries and its `fields`/`nested`
entries onto the target's chain, but the plain `elems` entries under a sub-place target were
*dropped* -- there was no key for them, and dropping is the honest direction (a stale value
would be worse). The fix is one mirrored arm: a sub-place target that *is* a field chain
(`&mut x.a`, chain `[0]`) re-bases the callee's `elems[k]` onto `elems_path[(cl, chain, k)]`,
which is exactly the key the caller's read consults. A sub-place target that is not a field
chain (`&mut x.a[0]`, `&mut t.0` on a tuple) still drops -- the `rest_chain` `None` arm -- so
an unrepresentable key is never invented. The guard is structural, not a value test: only an
*array* argument ever has plain `elems` entries at the callee's local (a struct or tuple
argument's parts live in `fields`/`nested`), so this arm cannot re-base a scalar onto an array
key. A sibling field is untouched: `set_second(&mut x.a); x.b[1]` is refuted, so there is no
cross-field contamination.
The *read* direction is the mirror and needs the mirror of the same arm. `peek_of(&x.a)` hands
the callee the array as a whole local, so the callee's `_1[k]` read consults its plain `elems`
store; the carry-in re-bases the caller's `elems_path[(sl, chain, k)]` *onto* that store when
the target chain is exactly the caller's field chain (`rem.is_empty()`), and onto `elems_path`
with the prefix dropped otherwise (the `&o.i` case). Both directions were `Incomplete` before
and both decide now, and the two are separate loops because one runs at the call and one at the
return.
It is *pinned*, and not only in the two directions that first exposed the hole. The corpus
carries `a_whole_array_target_crosses_a_reference_argument` (the true direction, `ret == 9`)
and its false twin `a_whole_array_target_cannot_prove_this`, the read-only pair
`a_whole_array_target_read_crosses_a_reference_argument` / `..._read_cannot_prove_this`, the
sibling-field probe `a_whole_array_target_sibling_cannot_prove_this`, and three shapes that
put the re-basing rule where it is easy to get it *partly* right: a read-modify-write
(`a_whole_array_target_read_modify_write`, where the carry-in and the write-back must both
fire in one call), a target two fields deep
(`a_nested_whole_array_target_crosses_a_reference_argument`, chain `[0, 0]` rather than
`[0]`), and a write that crosses two frames (`a_whole_array_target_crosses_two_frames`, where
each frame re-bases independently). Each has its `_cannot_prove_this` twin, so the corpus-wide
`no_cannot_prove_entry_is_ever_verified` invariant holds them all.
`tests/mir.rs::a_whole_array_target_decides_without_a_false_proof` asserts every one: each
true direction is `Verified` and each twin is `Failed` (or, for the read-only twin, not
`Verified`). The pin is what made closing the hole safe to do: the dangerous change is a
re-basing that connects the two stores the *wrong* way, which would turn a false twin
`Verified` before the true contract verified, and nothing else in the suite would notice. The
twins' "must not verify" assertions are the unconditional half; if a later change makes any of
these shapes incomplete again, the test fails and names the direction that broke.
Still not modelled, and named so the boundary is honest. A *scalar* element target
(`&mut x.a[0]`, a `&mut u8`) is modelled and decides -- the true `ret == 9` verifies and the
false `ret == 5` is refuted -- but an *array* element target (`&mut g.rows[0]`, a
`&mut [u8; 4]` reached through a subscript of a field whose type is an array of arrays) cannot
be named in a contract at all: `g.rows[0][0]` is refused with `unknown field`, so such a
function is *skipped* rather than decided. A *tuple* field target (`&mut w.t`) is refused the
same way (`unknown field t of w`). Both are coverage holes, not soundness ones -- the contract
cannot be written, so nothing false is proved.
**An array that is a struct *field* carries its elements when the aggregate moves.** This was
a coverage hole, not a false proof: `ArrayHolder { a: [9, 1, 2, 3] }` builds the array in a temp
whose elements live in the whole-local `elems` store, then moves it into the field
(`_2.0 = move _3`), and `Env::rebase_parts` -- which re-bases `elems_path` (field-path arrays)
and `fields`/`nested` -- did not carry `elems`. So `_2.0` held the array's *value* but none of
its elements, `x.a[0]` read `Unknown`, and the contract stayed `Incomplete` in *both*
directions. A bare array literal (`let a = [9, 1, 2, 3]; a[0]`) always worked, because there the
elements and the read share the whole-local store; only the field case had the hole, which is
why it went unnoticed. A missing value proves nothing, so nothing false was ever proved -- the
true direction was merely lost.
The fix is one mirrored pair of loops in `rebase_parts`: a *whole* source's `elems` entries move
with the value, re-keyed onto the destination -- a whole destination takes them as whole-local
`elems`, and a nested destination (`o.i = ...`) takes them under the destination's field chain
in `elems_path`. The gate is `field_steps(&src.proj)` being empty, not a type test: only a whole
source has `elems` (a nested source's elements are already in `elems_path` and were handled), so
this cannot invent an element for a sub-place move. Because `rebase_parts` runs on the
reference-argument write-back too, the same carry makes a whole-field replacement through
`&mut` (`set_holder(&mut o.i, ArrayHolder { a: [9, 1, 2, 3] }); o.i.a[0]`) decide as well.
Pinned by `tests/mir.rs::an_array_field_of_a_moved_aggregate_carries_its_elements`, whose
corpus entries are `a_struct_literal_array_element_is_read_back` (and its second-element
sibling, so a carry that pinned index 0 for all elements is caught),
`a_nested_struct_literal_array_element_is_read_back` (the longer destination chain),
`a_whole_field_assignment_carries_its_array_elements` (the same carry across a call boundary),
`a_whole_field_assignment_leaves_its_sibling` (no spill onto a neighbouring scalar), and
`an_array_field_argument_is_read_by_element` -- each with its `_cannot_prove_this` twin, so the
corpus-wide `no_cannot_prove_entry_is_ever_verified` invariant holds them too. Verified to fail
without the fix by reverting the two loops: the test then reports the true direction as
`incomplete`.
**Evidence.** Corpus `decided 289 of 538` -> **`305 of 572`** (the six array-field and six
whole-replacement true directions now decide, plus six named-`const` true directions; all their
`_cannot_prove_this` twins stay `Failed`, and two coverage-boundary entries stay `incomplete`);
`cargo test --workspace --features std` **684 -> 688** passed, 0 failed; `cargo
clippy --workspace --features std --all-targets -- -D warnings` clean; `scripts/gate.sh` 18/18
green (bare-metal build, zero-dependency and `no_std` gates included), z3 `agree=845
mismatch=0`, kani `agree=57 mismatch=0`, verus `0 differ`, rustc_public oracle `realistic.rs 634
functions typed, 638 text, 633 agree, 0 differ`. Zero dependencies and `no_std` untouched.
**The rustc_public oracle counted `const` bodies as functions, and this was found by the corpus
addition above.** Adding an expression-initialised `const` to `realistic.rs` turned gate 10 red
with `NEXT: text (absent)` -- the oracle reported a function the text frontend had dropped. It
had not: `all_local_items()` returns every item with a body, and a `const` or `static` item has
one in typed MIR, but the text dump prints an item initialised from a literal as a single line
and an item initialised from an expression with a body that is *not* introduced by an `fn`
header, so the text side sees no function there. The oracle now keeps only `ItemKind::Fn`. This
is the same class of bug the oracle exists to prevent, in the oracle itself: throwing the item
kind away made a `const` body indistinguishable from a genuinely dropped function, and the
report it produced was the one report it must never make falsely. The typed/text counts moved
from `(spurious disagreement)` to `634 typed, 638 text, 633 agree, 0 differ` -- the four-function
typed/text gap is the documented one (an item with no monomorphised body), not a disagreement.
**A whole-aggregate replacement through a sub-place target decides.** `set_whole(&mut o.i, n)`
with `set_whole(i: &mut InnerBox, n: InnerBox) { *i = n }` replaces the whole referent, and the
moved value's leaf reaches the caller: `o.i.v` reads the new value, the sibling `o.j.v` keeps
its seed, and a value built in a caller local (`let n = InnerBox { v: 9 }; set_whole(&mut o.i, n)`)
behaves the same. The re-based write-back (`rest ++ key`) re-roots the callee's `fields` entry
for the moved value under the target's chain, which is the same mechanism that carries a *leaf*
write; a whole value and a leaf are both a `fields` entry in this store, so the shape was never
actually the blocker it was once believed to be. This paragraph replaces an earlier claim that
the shape was *sound-incomplete*: that was measured on a version whose write-back dropped the
part keys for a sub-place target (the false proof the paragraph above fixes), and it is no
longer true. Pinned by
`tests/mir.rs::a_whole_aggregate_replacement_through_a_sub_place_decides`, whose corpus entries
`whole_replacement_through_sub_place`, `whole_replacement_leaves_the_sibling` and
`whole_replacement_from_a_local` each carry their `_cannot_prove_this` twin.
**A named `const` item is inlined at its use site.** rustc const-evaluates a `const` item and
prints its *body* separately (`const LIMIT: u8 = const 10_u8;`) while referring to it by name at
the use site (`_0 = const LIMIT`). The executor read only the name, so a use site was an
unreadable path constant and any contract that touched the constant was lost -- not wrongly
proved, but never decided, which for an embedded crate whose bounds checks read named constants
is the common case. `MirProgram::consts` now collects each item's value -- its printed
literal, or, when the body is an *expression* (`const NEXT: u8 = LIMIT + 1`), the value that a
concrete folder derives by interpreting that body (`fold_const_block`, in `src/mir/parse.rs`).
The folder walks the item's own basic blocks with every operand a literal, checks the body's
own `assert(!overflow)` / shift checks, resolves a branch by the discriminant's *value* (so it
follows the taken arm, never the first arm in textual order), and refuses -- leaving the item
unmodelled -- on any shape outside that subset (a call, an unresolved path, a subscript, a
failed assert, a zero divisor). It is a separate interpreter over the parsed blocks rather than
the symbolic executor, because the symbolic engine's `const` table is what the folder feeds.
An associated constant's `{constant#0}` name is still dropped. `operand` folds a use site
against that table. The key is the full printed path (`a::K`,
`low::K`), not the last segment, so two modules with a `const K` cannot collide -- a table keyed
by the last segment could read the wrong value, which would be a false proof rather than a lost
one. The item's own type suffix supplies the width and sign, exactly as for an inline literal,
so a negative `const` stays signed and a wider one keeps its width.
Pinned by `tests/mir.rs::a_named_const_item_is_inlined_at_its_use_site`, whose corpus entries
`named_const_is_read`, `named_const_keeps_its_width`, `named_bool_const_selects`,
`named_const_bounds_a_comparison`, `named_const_matches_an_equality`,
`named_negative_const_is_signed` and `nested_module_const_is_read` each carry their
`_cannot_prove_this` twin (every twin's postcondition is false on *every* input, so a regression
that guessed a value would fail the test). The expression-bodied item that used to be a boundary is now folded:
`named_const_of_an_expression_is_inlined` (its `NEXT` is `LIMIT + 1 == 11`) verifies, its
`_cannot_prove_this` twin (claiming `10`) is refuted, and `an_expression_const_keeps_its_width`
holds the folded value's width. The refusals are pinned by
`mir::parse::tests::a_const_body_outside_the_modelled_subset_is_refused_not_guessed`. A
function-local `const` is inlined for its *owner* now too: `a_function_local_const_is_inlined`.
Its *use* is printed with the enclosing function's path (`const a_local::L`) while the
*definition* is printed bare (`const L: u8 = const 3_u8;`) -- rustc emitting the qualifier only
where it is needed to disambiguate -- so the definition is recorded under the *qualified* path
the use names, and no bare key is created. The bare key is what would be a false-proof risk:
`a_local_const_is_not_in_scope_in_another_function` still holds that the bare name resolves to
nothing elsewhere. Verified to fail without the fix by neutralising the table lookup: the test
then reports the true direction as `incomplete`. The parser side is pinned by
`mir::parse::tests::named_const_items_are_collected_only_when_literal`.
## Recursion by contract: a self-call answered by the function's own contract
**The feature.** A recursive function used to be verified by *inlining* its self-call
once, which is the first unrolling and nothing more: the second level hit
`DEFAULT_INLINE_DEPTH`, and the function came back `Incomplete`. That is the honest
answer for an unrolling, but it is the wrong tool. A recursive function is proved by
*induction*, and the induction hypothesis is the function's own contract. A
`decreases:` line names the measure that makes it well-founded:
```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 }
}
```
A self-call that names a measure is *not* inlined. It becomes three obligations at
the call site (`exec::try_recursive_call`), and the result is the assumption of the
postcondition:
* **`RecursivePrecondition`** -- the callee's `requires` is *proved* of the call's
arguments. This is what restricts the assumption to calls the function itself
admits. Assuming a postcondition without its precondition would be assuming the
conclusion.
* **`RecursiveDecreases`** -- the measure is proved *non-negative at entry* and
*strictly smaller at the call*. Both halves are load-bearing: non-negativity is
what makes the order well-founded (a signed measure that runs negative would
"decrease" forever), and strictness is the progress. The comparison is `slt`/`ult`
according to the measure's own sign, so an `i8` measure is not read as unsigned.
* **assume `ensures`** -- the postcondition is assumed of a fresh `ret`, which is
written to the call's destination. The postcondition is *never proved* here;
proving it is the `return` obligations' job, and that is what keeps the base case
a real obligation rather than a free pass.
**Why it is sound.** A strictly decreasing sequence in a well-founded order is
finite, so the recursion has a base case. Nothing is assumed at the base case: the
body's `return` obligations still have to establish the postcondition on their own.
The assumption only ever replaces a *smaller* call, so the induction is on the
measure and cannot be circular. The four ways this is pinned, each with a corpus
entry that fails on the un-fixed code:
* **Positive** -- `a_recursive_identity` (`decreases: n`, `ensures: ret == n`)
verifies; before the feature it was `Incomplete` at the depth bound. Also probed
live: a `sum_down` driver and a signed `down` (`requires: n >= 0`) both verify, and
a two-argument `keep_a(a, b)` counting down on `b` verifies.
* **A wrong base case is refuted** --
`a_recursive_lie_cannot_prove_this` returns `1` at `n == 0` against
`ensures: ret == n`. If the postcondition were assumed at the base case too, this
would verify; it fails on the postcondition with a witness (`n == 0`).
* **A non-shrinking measure is refused** --
`a_recursive_call_that_does_not_decrease_cannot_prove_this` calls itself on the
same `n`. Probed live: it fails with `kind: "recursive call decreases the measure"`,
`detail: "v1:u8 = 1"` -- the smallest `n` where the call is reached, and the
call site's measure is not below the entry's. (This is a definite `Failed`, not a
`Skipped`: the check is decidable and it decides against the function. An earlier
note in this file recorded it as `Skipped`, which was wrong, and the witness as
`v1:u8 = 128`, which was stale.)
* **A signed measure that can start negative is refused** -- probed live with an
`i8` measure and no lower bound. Written as `below_zero(n - 1)` the *subtraction*
panics first at `i8::MIN` (`kind: "panic: attempt to compute \`{} - {}\` …"`,
`detail: "v1:u8 = 128"`), which masks the measure check; written with
`n.wrapping_sub(1)` -- no arithmetic overflow to hide behind -- the measure
obligation is the one that fires, `kind: "recursive call decreases the measure"`,
`detail: "v1:u8 = 128"` (the measure can start at `i8::MIN`, so the order is not
well-founded). Non-negativity at entry is exactly what supplies the basis, so this
is the check that keeps the order well-founded rather than a detail.
* **A call that leaves its own precondition is refused** --
`a_recursive_call_out_of_range_cannot_prove_this` has `requires: n <= 3` and calls
itself on `n + 1`.
**The boundary: no measure, no induction.** A self-call with no `decreases:` line
has no induction principle, so the assumption would be circular. The handler returns
`None`, the call falls back to the inliner, and the result is `Incomplete` at the
depth bound -- an honest "I could not decide", never a guess. Pinned by
`a_recursive_call_without_a_decreasing_measure_is_not_assumed` (corpus:
`a_recursive_call_that_does_not_decrease_cannot_prove_this` and the no-measure case
probed live). This is the same discipline as `Verdict::Unknown` in the engine.
**Only a self-call, and only the function under verification.** The handler fires
when `st.frame.func == root` *and* the callee's name resolves to `root` *and* the
frame has no caller. An inlined callee's frame has a different `func`, so its own
recursion is not this function's induction; and a frame with a caller is an inlined
callee, so reaching the root's name from there is not the root calling itself. The
name is resolved with the same rule the inliner uses -- exact match, else a unique
tail match, because rustc may print the call with a path prefix -- and an ambiguous
tail is not this function calling itself. A `mutual_lie` pair (two functions with
false contracts calling each other) is in the corpus and still does not verify.
**Several `decreases:` clauses are refused, not guessed.** Two measures would need a
lexicographic order and there is no way to say which the recursion counts down, so
more than one is `Skipped` with that reason rather than picking the first. A measure
that does not parse, or a call-site measure whose type differs from the entry
measure, is an unmodelled path -- a refusal, not a silently dropped check.
**The measure is evaluated once, at entry, in the entry state.** `verify_fn` computes
it there and carries `(Var, signed)` in `RecCtx`; the call site re-evaluates the same
text against the *call's* arguments. Carrying the text rather than a pre-built
predicate is deliberate: only the executor knows what the arguments hold at the
call site, and the measure must be evaluated there rather than at entry.
**Tests run without a toolchain too.** The contract reader's half is pinned in
`mir::spec::tests`: `a_decreases_clause_is_read_and_counts_as_a_claim` (a bare
`decreases:` is a claim, and its text is kept), `a_measure_takes_its_sign_from_its_arguments`
(an `i8` argument gives a signed measure through `+`), and `an_unreadable_measure_is_an_error`
(a dangling `+`, an unknown name, and an empty measure are errors rather than an
absent measure). The end-to-end half is `tests/mir.rs`'s four recursion tests, which
need a `rustc`.
## Two shapes for the prover: in the artifact, or in the build
The README's headline claim is that `verif` is a prover that compiles *into* the
artifact, so a proof can run where Z3 cannot (`examples/bare_metal.rs` is the evidence: the
decision procedure built for `thumbv7em-none-eabihf`). That is one shape. The other is the
Kani/Verus shape -- verify while the crate is built, ship none of the verifier -- and it is
reachable here for free, because the `mir` frontend is already `std`-only *host* tooling.
Put `verif` in `[build-dependencies]` and call `mir::verify::verify_file_with` from
`build.rs`, failing the build on any outcome that is not `Verified`. A build script is a
separate compilation unit, so cargo compiles it for the host, runs it, and discards it: the
BDD blasting and the CDCL fallback never reach the crate's own rlib. That is a consequence
of the build model rather than an optimisation, which is why it holds without any code
change to the crate.
**The measurements, so the "zero cost" claim is a number and not an adjective.** `release`,
`x86_64`, this repository:
| baseline, no verif | 447 728 B (binary) | 0 |
| `verif` as a dependency, never called | 447 696 B (binary) | 0 |
| `verif` in `[build-dependencies]`, called from `build.rs` | 4 860 B (rlib) | **0** |
| `verif::smt::prove` called from the crate's own code | 5 746 640 B (binary) | 26 |
So "zero cost" is true of the build-time shape and false of the embedded one -- the two
claims must not be conflated. The embedded engine's cost is the point of its existence
(a proof on the target); the build-time shape's cost is a host-side `rustc`, which the
frontend needs anyway because it shells out to `--emit=mir`.
**Pinned by gate 18, not by prose.** `tools/build-verify/run.sh` builds a *scratch* crate
under `mktemp -d` (a fixture in the tree would put a second `Cargo.toml` and a `target/`
in the repository, which gate 16 exists to prevent) and requires three things:
1. a provable contract builds **and** the verifier reports `verified` -- a `build.rs` that
silently did nothing would otherwise pass, so the positive direction alone is not enough;
2. a false contract **fails the build**, and the failure names the broken obligation
(`postcondition`, with the witness). The scratch contract is the recursion one whose
*base case* is wrong, which is exactly the mistake a circular induction would wave
through, so this doubles as an end-to-end check of the `decreases:` work; and
3. the resulting rlib carries **zero** `verif` symbols (`nm -C | grep -ci verif`).
Exit 2 when there is no `cargo` is reported and skipped, the same convention
`tools/ferrocene/run.sh` and `tools/mir-oracle/run.sh` use: a skipped gate is not evidence.
**A shell gotcha worth recording.** The scratch `Cargo.toml` is written with an *unquoted*
heredoc so `$ROOT` expands, and the first draft put a backtick-quoted `` `verif` `` in
a comment inside that heredoc. The backticks were command substitution, so the script tried
to *run* `verif` and printed `verif: not found` before continuing. It still passed
every assertion -- the failure was cosmetic -- but a gate that prints a stray error while
going green trains a reader to ignore its output. Backticks (and `$(...)`) inside an
unquoted heredoc are code, not prose.
**The full cost table, and the profile trap that makes the build row look cheap.**
`tools/shape-bench/run.sh` builds four crates that share one function and one driver, so
the only variable is how verification is attached (`no_verif`, `build_verif`,
`runtime_verif`, and `unused_verif` -- the engine linked but never called). Measured
`x86_64`, `release`, rustc 1.100, four cores:
| compile wall | 0.16 s | 3.4 s | 12.9 s | 12.7 s |
| compile CPU | 0.17 s | 5.1 s | 34.9 s | 35.1 s |
| compile peak RSS | 96 MB | 433 MB | 502 MB | 508 MB |
| binary | 438 312 B | 438 328 B | 5 775 256 B | 438 336 B |
| run wall (median/7) | 3.1 ms | 3.2 ms | 4.6 ms | 3.2 ms |
| run peak RSS | 2.1 MB | 2.1 MB | 5.6 MB | 2.1 MB |
| `verif` symbols | 0 | **0** | 42 | 0 |
The row that misleads is `verif (build-dep)` at 3.4 s: cargo compiles a
*build-dependency* with the `build-override` profile, which defaults to `opt-level = 0`,
while a normal dependency gets the release profile's `opt-level = 3`. Verified by
counting `-C opt-level=` in `cargo build --release -v` -- the build-dep crate showed
**two** `opt-level=3` invocations (its own lib and bin) and the runtime crate showed
**four** (verif, verif-arithmetic, lib, bin). Set
`[profile.release.build-override] opt-level = 3` and the build-dep wall time rises to
~12.9 s, matching the runtime crate: the work is the same, only its optimisation level
differs. So the honest statement is "build-time verification costs one optimised compile
of the engine", not "build-dependencies are inherently cheaper".
**Two measurement traps this table set, both found by review, and both worth keeping.**
They are the reason the figures above differ from the first version of this table.
1. **The runtime workload proved a tautology.** The on-target driver built
`var(16)` and proved `x.lt_val(65536) || x.ge_val(65536)`. On a 16-bit variable those
are `lt`/`ge` against a constant *at* the maximum, so both fold to a constant before the
solver sees them and the predicate is `true` with no symbolic input at all -- it
discharged nothing and the reported per-proof cost (14 µs) was the harness. The driver
now builds the *real* obligation the shared function's contract names,
`ite(x > 100, 100, x) <= 100` at 32 bits, which is ~**290 µs** per proof in-process.
The general rule the crate already states applies to a *benchmark* too: a proof whose
operands are all constants is decided without the engine, so it cannot measure it. Read
the term the driver builds, and check it is the one the table's prose names.
2. **A `fork`-based harness inflates a short measurement.** The first harness used Python's
`os.wait4` and reported `ru_maxrss`. That value is the child's resident high-water mark
*since the fork*, and `fork` copies the parent's page tables, so Python's own ~5 MB RSS
is a floor under every figure. It is invisible on a build (a `rustc` peaks at ~500 MB,
so the floor vanishes) and dominant on a run (a benchmark binary peaks at ~2 MB): the
same `no_verif` run reports **5.5 MB** through Python and **2.1 MB** through a native
launcher. The harness is now `tools/shape-bench/measurer.rs`, which reads
`/proc/<pid>/status:VmHWM` -- the measured process's *own* high-water mark, replaced by
`exec`, so the launcher's RSS cannot leak in. It also uses `getrusage(RUSAGE_CHILDREN)`
rather than `/proc/self/stat`'s `cutime`, because the latter is in 10 ms clock ticks and
reports `0.0000` for a 3 ms run.
A third trap in the launcher itself, because it is the kind that returns a *plausible wrong
number* rather than an error. The tree walk first read `/proc/<pid>/task/<pid>/children` --
the **main thread's** children -- and `cargo` spawns `rustc` from a *worker thread*, so that
file is empty and the walk saw only `cargo`: it reported a 34 MB compile peak where the
true peak was 521 MB. The launcher now finds the tree by scanning `/proc` for each pid's
parent, which is thread-agnostic. The lesson is the one the crate keeps meeting: a wrong
number is worse than no number, and the way to catch it is to cross-check the metric
against a second method (here, `wait4`'s `ru_maxrss` on a *cold* build, which the two agree
on to within a megabyte) rather than to trust the first reading.
Two smaller measurements worth keeping, both from the same harness. A dependency that is
linked but *never called* is also zero-cost (438 336 B binary, 0 `verif` symbols) -- but
that is the linker dropping an unused library, not a proof. And the engine's *per-proof*
cost, isolated in-process over 1000 repetitions, is **~290 µs** for the 32-bit `clamp100`
bound; the process-level delta (1.5 ms) is dominated by starting the process and running
the loop around the proof.
The README's table is a measurement and moves with the machine; `tools/shape-bench/run.sh`
reprints it. The *properties* -- verification at build time, and no prover in the artifact
-- stay pinned by gate 18, because a cost figure is not a property.
## The cross-tool cost table: three axes, and the caveats are the honest part
`tools/cost-bench/run.sh` measures `verif` against Kani, Verus, Coq and Lean on the *same
three functions* `examples/comparison/target.rs` uses, so the comparison is like-for-like
about the problem even where it is not like-for-like about the task. It exists because the
comparison README's one cost sentence ("`verif` decided all three functions in about 0.01 s;
Kani and Prusti take seconds to minutes") was **prose, not a measurement** -- the exact
defect this repository names repeatedly. The harness replaces it with numbers anyone can
regenerate.
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:
| `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 |
Three things about this table are the point, and each is a way a naive comparison misleads:
1. **The axes must stay apart.** Setup, per-verification and artifact are different
questions. Folding them into "which is faster" is what produces the wrong conclusion:
`verif` wins *setup* by two-to-three orders of magnitude (a crate versus a
multi-hundred-MB toolchain), is *competitive* on per-verification for this small
fixture, and *loses* the artifact axis on-target (5.3 MB and 42 symbols, where the
others ship nothing because they cannot run on the target at all). The artifact axis
lives in `tools/shape-bench/run.sh`, not here -- duplicating it would invite the false
reading that "0 bytes" is a win rather than a different shape.
2. **`verif`'s row is a different measurement.** It includes spawning `rustc --emit=mir` to
read the source -- it is the only tool whose verification step also *compiles* the code
it verifies. So "≈0.07 s" is not "the engine is 10× faster than Kani"; the engine-only
figure is ≈0.05 s (`mir_coverage`'s per-function `elapsed` column), and the gap is the
frontend's compiler call, not the decision procedure. The same fact explains the ≈97 MB
peak: it is the *tree* peak, and the heaviest process is the `rustc` `verif` spawns.
3. **Coq and Lean prove a hand-written model, not the Rust code.** Their rows are not "the
same task, slower"; they are a different task, and the transcription is the risk the
comparison README is built around. A like-for-like *engine* comparison excludes them --
they are here because the comparison README lists them for *correctness*.
Two tools the correctness table has are **absent** and the harness says so in its output
rather than dropping them silently: Prusti needs a pinned nightly and a JDK, `gnatprove`
pulls four solvers. A table that shrank without a word reads as "the tool was fast", which
is the failure mode the notes guard against.
**Three review findings on the first version of the harness, each a measured defect:**
- **Peak RSS excluded subprocesses.** `measure` ran the launcher without `-t`, so it
sampled only the direct child. `cargo kani` is a thin plugin whose work is a
`kani-driver` grandchild, and `verif`'s own driver spawns `rustc --emit=mir`; sampling
the direct child reported the *launcher's* RSS. Measured: kani 14 MB → 23 MB, and
verif 10 MB → 97 MB with `-t`. The flag changes only the peak, not the wall time
(checked by interleaving the two modes). The table above is the `-t` figures.
- **`VERUS_BIN` was cleared before it was read.** The script assigned `VERUS_BIN=""` and
then read `${VERUS_BIN:-}` as the loop's first candidate, so a caller who set only that
variable (Verus not on PATH, not at the `/tmp` default) was silently skipped -- the
variable's whole purpose discarded by the line above its use.
- **A configured build directory broke the `verif` row.** With `CARGO_TARGET_DIR` or a
`build.target-dir` in Cargo config, `cargo build` writes elsewhere while the launch path
stayed `target/debug/...`, so the harness either failed or -- worse -- silently measured
a *stale* binary left in `target/` by an earlier build. Reproduced: the env var built to
`/tmp/verif-build` (new) while the harness launched `target/debug/...` (nine hours old).
The build now passes an explicit `--target-dir` to a private directory, which overrides
both the env var and the config (verified) and keeps the benchmark from clobbering the
developer's own `target/`.
A fourth was a **label**, and a label is a claim: the table said "cold cache" while the
harness warms Kani (and now Verus) before measuring and reports the median of three warm
runs. The gap is 4× (kani ≈3.2 s / ≈256 MB cold, ≈0.7 s / ≈23 MB warm), so the label was
wrong by that much. It now says steady-state, and the cold figure is named in the caveats
so the reader can see both.
**Two more findings, and the first is a lesson about fixing one.** The `VERUS_BIN` fix
above *introduced* a regression, which a second review caught. The original script opened
the Verus block with `VERUS_BIN=""`, and that line did two jobs: it cleared a stale value
*and* it made `"$VERUS_BIN"` defined for the later `[ -n "$VERUS_BIN" ]` test under
`set -u`. Removing it to stop it wiping the caller's path left the variable *unset* when
no Verus is installed, so the test aborted the whole script -- the `verif`, `kani`, `coq`
and `lean` rows all printed, then `VERUS_BIN: parameter not set`, and the Coq, Lean and
setup measurements never ran. The fix is `VERUS_BIN="${VERUS_BIN:-}"`: it *defines* the
variable without *clearing* it, doing both jobs the `""` did except the one that was
wrong. The general shape: when a line serves two purposes, removing it for one removes the
other too, and the second purpose is the one nobody was looking at.
The second finding is a **symlink**, the same "the name is not the thing" class as the
stale-binary one. `setup` measured `dirname "$VERUS_BIN"`, and for the common
`/usr/local/bin/verus -> /opt/verus/verus` layout that is the *link's* directory -- a
shared bin dir of a few kB, with none of the 135 MB distribution (reproduced: 4 kB
measured against 132 MB real). Discovery accepts a symlink because `-x` follows it, but
`dirname` operates on the path, not the target. It now honours an explicit `VERUS_DIR`
first (it names the installation, and the old code ignored it whenever discovery
succeeded), and otherwise resolves the driver through `readlink -f` and accepts the
directory only when it carries `rust_verify`, the marker of a real distribution. A
directory that does not validate is reported "not found" rather than measured, which is
also the honest row when discovery found no driver at all -- the old code printed a size
for the `/tmp` default even when nothing was installed there.
Both were checked by reproducing them first (`VERUS_BIN: parameter not set` under `set -u`;
a symlinked driver measuring 4 kB) and then re-running the four scenarios -- absent, symlink,
`VERUS_DIR`-only, and normal -- so a fix for one did not break the others.
A third round found the **same symlink class one layer down, in `setup` itself.** The
`VERUS_DIR` branch above passed the explicit directory to `setup`, whose `du -sk` call does
not follow a *directory* symlink: `/opt/verus-current -> /opt/verus-2026` measures **0 kB**
(the link, not its target), and `setup` prints `0` as "not found on this machine" -- so a
working install whose `VERUS_DIR` is a stable version symlink reported nothing. Reproduced
directly against the helper: `setup verus /tmp/verus-current` printed "not found", the same
path with a trailing slash printed the real 1.9 MB. The finding's suggested fix (append a
trailing slash at the one call site) is *narrower than the defect*: the `kani` row passes
**file** symlinks (`~/.cargo/bin/kani` from `cargo binstall`), and `du -sk` reports 0 for
those too. The fix belongs in `setup`, so every row gets it: resolve the path with
`readlink -f` first, and add a trailing slash only when the resolved target is a directory
(a file with a trailing slash is an error). Six cases re-checked -- directory symlink, file
symlink, real dir, real file, a missing path (still "not found"), and a path that already
ends in `/` (no doubling) -- plus the exact scenario from the finding.
The general lesson, third time in this file: **a symlink is not its target, and the tool
that resolves it must be the one that reads the size.** `-e`/`-x` follow symlinks, `dirname`
does not, and `du` follows a symlink only when a trailing slash says to. Each of the three
is a different rule about the same path, so a check that is right about one is not evidence
about the others.
The honest conclusion the harness supports, and that the README states in prose: **`verif`'s
reason to exist is embeddability and no external toolchain, not raw speed.** The BDD scaling
wall is real and documented; the mature competitors have higher coverage (pointers,
aliasing, concurrency, unbounded induction). A user choosing a verifier for a normal host
build should reach for Kani or Verus; a user who needs a prover *inside* an artifact, with
no solver process and no dependency, has `verif` and little else.
Not a gate, deliberately: the numbers move with the machine, so a CI job asserting them
would fail on a slower runner for a reason unrelated to the crate. `tools/comparison/run.sh`
(gate 13) asserts the *verdicts*; this reports their cost. Exit 2 when no tool could be
measured at all.
## The MIR frontend: own text parser, `rustc_public` as the oracle only
A recurring question is why the frontend parses rustc's *textual* `--emit=mir` dump
instead of using `rustc_public` (formerly `stable_mir`), the compiler's own public API for
internals, which returns *typed* MIR and is strictly richer. The answer is that
`rustc_public` cannot be the frontend without destroying the crate's identity, and the
repository already uses it in the one place it is safe: as an oracle.
**What `rustc_public` costs, from `tools/mir-oracle/` itself.** It needs a nightly with the
`rustc-dev` component, `#![feature(rustc_private)]`, and a link against
`librustc_driver-*.so` plus `libLLVM-*`. Each of those breaks a promise the crate makes:
gate 14 pins the floor at stable 1.85, gate 5 forbids external dependencies, the README
sells "not a nightly feature", and an experimental API that moves every nightly is not a
foundation for a safety build. The oracle's own manifest says it: "the `verif` crate
must build on stable with no dependencies, and `rustc_private` is neither stable nor
dependency-free." Kani and Verus do link rustc internals -- but they are separate tools,
and the whole point here is to *not* be that.
**The parser is the cheap part, which is the fact that decides it.** `src/mir/parse.rs` is
2 157 lines; `shape.rs` another 350. The other 15 473 lines of `src/mir/` -- `exec.rs`,
`spec.rs`, `intrinsics.rs` -- are the verifier, and every one of them is needed regardless
of where the MIR came from. So "write our own MIR reader" buys the 2 507-line parser for
14% of the module, and 61% of the crate is `mir` to begin with. Swapping the frontend would
delete a seventh of `mir` and add a nightly, a compiler-internal link, and an unstable API.
**The architecture is already the right split**, and gate 10 is what makes it safe:
```
product: rustc --emit=mir (text) -> parse.rs -> exec.rs -> verdict
^ stable, zero-dep, inspectable
oracle: rustc_public (typed MIR) -> shape.rs --+
parse.rs -> shape.rs --+-> compare (gate 10)
```
A stable, dependency-free reader feeds the product; the rich, nightly API checks that
reader's *reading* against the compiler's own IR. If rustc changes the pretty-printer and
the parser drifts, gate 10 fails in CI, not in a user's build. Cheap and stable for the
product, expensive and rich for the test.
**The shape is two facts, and its blindness is a documented boundary, not a footnote.**
`FnShape` is the block count and the panic guards (kind + polarity). It therefore sees a
change in *structure* -- an extra block, a guard inserted or moved or flipped -- and cannot
see a change in *spelling*: a place, a local index, a field projection, a type. Measured, not
assumed (`the_shape_sees_structure_and_guards_but_not_places` in `src/mir/shape.rs`, teeth
confirmed by making the shape place-aware and watching it fail):
| `Len((*_1))` -> `PtrMetadata(copy _1)` | **yes** -- blind |
| operand read from `_2` -> `_1` | **yes** -- blind |
| field projection `.0` -> `.1` | **yes** -- blind |
| one block -> three blocks | no -- caught |
| `assert(c)` -> `assert(!c)` | no -- caught |
The first row is a *real* rustc 1.99 change that cost four verdicts on the 1.85 floor, and
gate 10 was silent across it; it was found by running the suite under a second toolchain.
**Gate 14 samples that coverage; it does not complete it.** It runs `tests/mir.rs` under 1.85
against the same suite on current stable, and it *skips* (reported, not passed) on a machine
without the 1.85 toolchain. Two compilers catch a spelling change only where they differ, so
a printer change that lands between them, or after current stable, is uncovered by both. The
durable check is a habit -- run the suite under a compiler you have not run before when the
toolchain moves -- and the gate is the part of it that can be automated. 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. So the correct
claim is "gate 10 checks the parser's reading of the control-flow skeleton", not "the parser
is checked". Both README sections that used to say the latter now say the former and name
the pinning test, because a gate's *scope* is a claim like any other and this one had been
stated wider than the code.
**The shape test's blind cases need parsing controls, and did not have them.** An
`assert_eq!` on two `Option`s passes when both are `None`, so a `shape_of` that failed to
parse satisfied all three "the shape is blind to X" assertions for the wrong reason -- the
test would report that the oracle cannot see a place change when it saw nothing at all.
Measured: with `shape_of` returning `None` unconditionally, the first three assertions
passed and the test failed only at the fourth (structural) one. Each comparison is now
preceded by a `parsed(src, blocks)` control that requires the dump to yield exactly one `f`
with the expected block count, so "the shapes are equal" means "identical despite the edit"
and `assert_ne!` cannot pass on two `None`s either. Teeth: the `None` mutant now fails at the
control with "the dump must parse to a function `f`", not at the fourth assertion. The
general rule is the one this file keeps meeting -- a test whose assertion is satisfied by
the *absence* of a value is not a test, and the control is what distinguishes a comparison
of two shapes from a comparison of two nothings.
**When to revisit.** Two conditions, either of which flips the decision: (1) `rustc_public`
stabilises, which would make it strictly better -- typed MIR with no parser to rot; (2) a
real need for cross-crate or generic-monomorphised verification, where the textual
frontend's "calls are inlined one level" gap (README gap 1) genuinely bites. Until then the
text parser stays. A hybrid `--features rustc-public-frontend` was considered and rejected:
a second frontend to maintain plus a nightly-only path is not worth it yet.
The `--emit=mir`-is-stable question itself is settled earlier, in "The MIR frontend needs a
`rustc`, not a *nightly* `rustc`", with the MSRV/stable parity table; do not re-derive it
here. Two things in that section were still open, and both are closed now.
**The claim was unpinned.** That section concludes the frontend is a stable-toolchain tool,
but nothing *ran* it without a nightly: `tests/mir.rs` gates every `rustc`-dependent test on
`VERIF_RUSTC`, and gate 8 used to skip when it was unset. So the conclusion held only on
machines that happened to name a compiler -- asserted in prose, checked by nothing. Gate 8
now falls back to the `rustc` on `PATH` and skips only when there is no `rustc` at all, so
the claim is exercised with no setup.
**Pinning it surfaced a latent failure.** With gate 8 able to run without `VERIF_RUSTC`,
`env -u VERIF_RUSTC scripts/test-count.sh` reported **1 test failing**, not skipping:
`a_one_line_struct_does_not_swallow_the_functions_after_it` called `panic!` on the `None`
that `verify_src` returns when no compiler is named. It was the only test in the file that
read "no compiler" as "a bug" -- the other 174 return early -- so the suite's verdict
depended on the environment. It returns early now. The general lesson: a gate that *skips*
can hide a test that *fails*, which is the same class of mistake as a gate that never runs,
and the reason a skip is reported rather than folded into a pass.
Also corrected while here: `verify.rs`'s two error strings blamed "a nightly toolchain" for
what is really a missing or empty `--emit=mir` output file -- a message that sends a reader
to install a compiler that would not have helped. They now name the actual condition, and
its doc comment and the README's source table and example no longer tell the reader to point
`VERIF_RUSTC` at a nightly.
## A function-local `const` was in scope in every function -- a false proof
Three holes, found together, all of the same family: a name or a place resolved to
something the function's own source could not have written. Each was reproduced from
real `rustc` output and each is now pinned by a test that fails if the fix is undone.
**Bug 1: a function-local `const` leaked into another function's contract.** The parser
recorded every literal `const NAME: TYPE = ...;` definition under its bare name, and the
contract reader resolves a bare name against that table. A function-local item's *definition*
is printed bare (`const L: u8 = const 3_u8;`) -- byte-identical to a crate-level item's --
so `const L: u8 = 3;` inside `first` handed `second` a bare `L` to write in its contract.
`requires: L == 3` then resolved and the function was **proved** from a foreign body: a
wrong proof, not a lost one. The *use* site is the only tell -- a crate item is used bare
(`const LIMIT`), a local one qualified (`const first::L`) -- so `bare_const_uses` collects
the bare use sites once, and a bare definition is kept only when the name is used bare
somewhere. A qualified definition still keeps its qualified key, which is what a contract
that spells the path resolves. The false twin is now `Skipped` (unreadable `requires`),
never `Verified`.
The old fixture comment claimed the bare key was "safe" because rustc qualifies a local
definition when another item shares its last segment. That reasoning was about *shadowing
between constants*, not *scope*, and it was wrong: `first`'s `L` still became `second`'s.
**Bug 2: a returned reference to a symbolic element was aimed at a caller local that
merely shared its number.** `x.nth_mut(i)` returns `&mut x.a[i]`, and inside `nth_mut` the
index is `_2`. Translating that returned reference back to the caller carried `IndexVar(2)`
across the call boundary, where `_2` is a *different* local -- with a parameter before `i`,
`_2` is that parameter, not `i`. The write `*x.nth_mut(i) = 9` landed on `x.a[zero]`, and
the contract fixed `zero == 0`, so it landed on the *seed* element and the false `ret == 5`
was **proved**.
The index cannot be pinned (the contract admits any `i < 4`), so the fix refuses the write
-- but dropping it alone is not enough. A later `x.a[0]` then falls back to its seed, which
turns the false proof around rather than removing it: `ret == 5` becomes provable. The
array's elements are *poisoned* instead (`poison_array_under`), so every read is unknown:
the write is lost, never mis-aimed, and no stale seed survives it. Both directions are
pinned as refusals -- the false `ret == 5` and the true `ret == 9` -- because a fix that
only drops the write proves the second.
**Bug 3: a closed true goal bypassed a stale premise.** `prove_implies` decides a goal that
is closed and true without building `!pre || post`, which is what lets a tiny postcondition
decide even when the premise is a large diagram. But the premise is half the claim, and the
shortcut never read it. A `pre` saved from an earlier arena names a different term in the
current one, and the shortcut returned `Valid` for it -- certifying `pre implies true` for a
`pre` that is not the one passed. The ordinary route catches this because `un_bool(pre)`
funnels through the stale check; the shortcut now asks `is_current_term` itself and returns
`Unknown`.
**Evidence.** Corpus `decided 305 of 572` -> **`312 of 588`** (the new fixtures add decided
entries and two honest refusals); `scripts/test-count.sh` **688 -> 702** passed, 0 failed;
`cargo test --features std` green on the whole workspace; `cargo clippy --workspace --features
std --all-targets -- -D warnings` clean; bare-metal (`cargo build`, no `std`) green. Gate
green; zero dependencies and `no_std` untouched.
**A boundary left documented, not hidden.** When another item shares a function-local
`const`'s last segment, rustc prints the local's *definition* qualified too
(`const f::L: u8 = const 3_u8;`). That qualified definition still enters the table, so a
contract could name `f::L` -- a path no function's source can write, but whose *value* is
correct, so this is a looser path resolution, not a wrong value. It is recorded here rather
than papered over: closing it needs the same use-site test to cover qualified definitions,
which no current fixture exercises.
## A contract on an inherent method was silently dropped -- a false proof
`verify_file_with` asks `prog.get(name)` for a function, and `MirProgram::get` matches on
the *last* `::` segment so a call written `crate::m::f` resolves. A method's dump name is
`<impl at FILE:L:C: L:C>::f`, so the tail match found it -- and then `verify_function` looked
its contract up with `specs.get(&f.name)`, the *full dump name*. The contract is keyed by the
bare `f`, the scanner records the identifier after `fn`, so the lookup matched nothing.
A missing contract is not a refusal here: `verify_function` builds `pre` and `ensures` from
`contract`, so `None` means `requires: true` and no postcondition at all. Every method with a
contract was therefore reported `Verified { obligations: 0 }` -- the body never checked. A
method whose `ensures` was false on every input came back `verified`. That is the worst
direction: a false proof, not a lost one. The free-function control in the same run correctly
`FAILED`, which is what showed the difference was the *name*, not the contract.
The fix is `Specs::resolve`, which matches exactly first and then on the last `::` segment --
the same rule the body resolution uses, so a contract is found for exactly the functions the
frontend can name. Because `by_fn` is keyed by bare identifiers, the tail match is unique by
construction and no ambiguity branch is needed.
> **Superseded (see "A contract on a nested item was keyed by its bare name" below).**
> `by_fn` is now keyed by the *full source path* (`a::f`, `T::value`, `f::g`), because a
> nested item's MIR name carries a path a bare key never had -- which dropped the contract
> and reported the body `Verified { obligations: 0 }`. `resolve` now matches the exact path,
> then a *unique* `::`-aligned suffix, and an ambiguous suffix is refused rather than taken.
> The bare-identifier reasoning above held only while every key was a bare name.
**Evidence.** Corpus `decided 312 of 588` -> **`313 of 590`** (the two new method fixtures:
the true direction is now decided *with* its postcondition checked, the false direction is a
definite refutation); `scripts/test-count.sh` **702 -> 704** passed, 0 failed; `cargo test
--features std` green; clippy (both halves) and docs clean; bare-metal builds green.
The regression test asserts the obligation *count* is non-zero, not merely `Verified` -- a
future fix that matched the name but still skipped the body would pass a verdict-only
assertion. The false twin is pinned to `Failed { kind: "postcondition" }` so an unrelated
refusal cannot satisfy it, and the corpus-wide `no_cannot_prove_entry_is_ever_verified`
sweep holds it as well.
## Four frontend findings, found by probe: one false proof and three lost proofs
Four defects in the MIR frontend, all in the "a name or a call resolved to something
the function's own source could not have written" family. They were found by hand
probes against real `rustc` output before any fix, and each is pinned by a test that
fails if it is undone. F1 was the severe one -- a genuine false proof.
**F1 (false proof): a call to an intrinsic resolved to a local function that shared its
name.** The inliner and the recursion check matched a call name to a definition on the
last `::` segment alone. rustc prints a call to `u8::wrapping_add` fully qualified
(`core::num::<impl u8>::wrapping_add`) and a *free* function named `wrapping_add` by its
bare name, so a `decreases:`-measured free function that calls the *intrinsic* on its
non-base path had that call resolved to *itself*: `try_recursive_call` -- which runs
before the intrinsic model -- assumed the function's own postcondition for the result.
`ensures: ret == 0` was **proved** while the body returns `n` for `n > 0`. The name must
be the intrinsic's *exact* tail for the collision to appear, which is why the fixture is
a plain free `wrapping_add`.
The fix is `resolve_callee`, shared by the recursion check and the inliner. After an
exact-name match (the free-function case, which rustc prints bare on both sides), a
qualified call is matched on the tail *and* on the method's `self` type. The receiver's
type is read from the local whose `debug` binding is literally `self` (`&Vec2` gives
`Vec2`), which is the one tell that separates an *instance* method from a *static*
associated function -- a static function's first parameter is an ordinary argument, and
reading it as a receiver would let an external `Vec2::m` call resolve to a local
`Foo::m(x: Vec2)`. Two guards keep the tail from resolving to the wrong body: a call
name that still carries an `<impl` projection is a `core`/`std` callee and is refused
outright (rustc never prints a *local* method call with `<impl`), and a candidate must
agree on the type -- an instance method's `self` type must equal the call's, and a
static associated function (no `self`) must have its *owner* type agree, which is read
from the `impl` block's own source line (see the section on a method contract keyed by
its bare name below). The false proof now reports `Failed { kind: "postcondition" }`.
This also *improved* the old ambiguous-tail behaviour rather than only refusing it:
`Widget::twist` and a free `twist` share the tail, and the call `w.twist(5)` names its
receiver's type, so it now resolves to the method and **refutes** the false contract
where the old code refused the whole call as `Incomplete`. The corpus fixture and the
`a_method_is_inlined_by_its_tail_and_a_shared_tail_resolves_by_type` test were updated
from "refused" to "refuted", because resolving by type is the stronger and correct
answer.
**F2 (lost proof, and a false-proof path reopened): a string literal spelled
`const NAME`.** `bare_const_uses` is the only in-dump tell between a crate-level `const`
and a function-local one. It scanned raw lines, so a `debug s => const "const LEAKY";`
binding and the `alloc` block behind the string -- both of which spell `const LEAKY` as
*data* -- looked like a bare use. That gave the local `LEAKY` a program-wide key,
reopening the exact false proof the local-const fix had closed. The scan now drops
string literals (honouring `\"` escapes) and skips `alloc` blocks whole. The local's name
must be *unique* among the file's locals for the shape to appear: rustc qualifies a
local `const`'s definition (`const f::L`) only when another local shares its name, and
prints it bare -- the colliding spelling -- when it does not.
**F3 (lost proof): a crate-level `const` a *contract* names but no body uses.** The
bare-use test is silent for a constant with no use site at all, so the definition was
dropped and the contract went unreadable. The dump cannot tell a crate-level `const`
from a function-local one, but the *source* can: a crate-level item sits at brace depth
zero. `spec::crate_level_consts` reads exactly those, and `parse_program_scoped` keeps a
bare definition when the name is used bare, is qualified, or is in that set. Reading too
much would re-open the local-leak false proof, so a local item, an associated constant,
a `const` generic parameter, and a `const` inside a string or comment are all excluded,
and the negative cases are unit-tested as well as the positive one.
**F4 (lost proof): a recursive contract that names a `const`.** `try_recursive_call`
rebuilt the contract environment from `FieldEnv::default()`, whose `const` table is
empty, so `requires: n <= LIMIT` was unreadable *at the self-call* and the whole
function came back `Skipped`. A constant has the same value at the call as at entry, so
the call site now carries the entry constants (`FieldEnv::with_consts`); only the field
bindings are rebuilt per call site.
**Evidence.** Corpus `decided 313 of 590` -> **`318 of 599`**; `scripts/test-count.sh`
**704 -> 714** passed, 0 failed; `cargo clippy --workspace --features std --all-targets
-- -D warnings` and `cargo clippy --no-default-features --lib -- -D warnings` both
clean; `scripts/gate.sh` **ALL GATES GREEN**; zero dependencies and `no_std` untouched.
Each of the four regression tests was confirmed to *fail* against the un-fixed source
(stashing only `src/mir/`, keeping the fixtures), so they are not vacuous. The F1
companions -- a free `wrapping_add_still_recurses` and a static `Recursing::wrapping_sub`
-- verify on both the fixed and un-fixed source, which is the point: they guard against
the fix *over*-refusing a real self-call, and pass either way. The static companion uses
`wrapping_sub`, not `wrapping_add`, because the free `wrapping_add` above already owns
that report name (a method's outcome key is its bare tail).
## A method's contract was keyed by its bare name -- a false proof and a lost proof
The MIR frontend attaches a contract to a function by name: `Specs::get` looked a
function's bare name up in the contract table. rustc prints a *method*'s definition as
`<impl at FILE:L:C: L:C>::bump`, whose tail is `bump`, so a contract written on an
inherent `impl` method was keyed under `bump` while the dump's body was looked up under
the tail `bump` -- which happens to match, so a *single* method looked fine. The defect
was two-fold and only the second half is obvious:
* **Two `impl` blocks that share a method tail collide.** `TaggedLeft::tag` and
`TaggedRight::tag` both key `tag`, so the later `insert` overwrote the earlier and both
methods resolved to the *survivor's* contract. Whichever direction the claims are
written, one method is checked against a contract its own source never wrote: a lost
proof for the one whose contract was dropped, and -- once the claims are the false way
round -- a **false proof** for the other. That is the severe half.
* **A static associated function's owner is not in its name.** An instance method's
receiver is recoverable (the first local whose `debug` binding is `self`), but a
*static* method has no `self`, so `<impl at …>::from` names no type at all. A call to
`u16::from` -- `core`'s conversion, which returns its argument -- then matched a local
`from` on the shared tail, and a contract claiming `ret == 99` came back **verified**
while the real callee returns `x`. The old resolver accepted a static candidate on the
unique tail alone, which is exactly this hole.
The `impl`'s own *location* is the one key both halves share, and it is printed verbatim
in the dump. `enclosing_impls` scans the source for `impl` keywords and records the
`(line, column)` of each with its owner type; `impl_location` parses the same `L:C` back
out of an `<impl at …>` name. The name carries *two* locations -- `4:1: 4:7` is the
`impl` keyword and the end of the `impl A` header -- and the **first** is the keyword's,
which is the one `enclosing_impls` records; reading the second (the natural "take the
last `L:C`" move) silently matches nothing, which is how the first cut of this fix
dropped every method to `missing`. Contracts are now keyed by `(line, col, name)`,
`MirFn` carries its `impl_loc`, and both the contract lookup and the call resolver go
through it.
The fix *improves* the static-call direction rather than only refusing it: a call to a
*local* static method (`StaticOwner::seed()`) now resolves to its own body and verifies,
where before the owner was unknown. The external call is refused -- `Incomplete`, naming
the unmodelled function -- which is the honest answer, not a proof.
**Evidence.** The pre-existing corpus is unchanged at `decided 318 of 599` (no
regression); the eight new fixtures move it to `decided 323 of 607`; `scripts/test-count.sh`
**714 -> 718** passed, 0 failed; `scripts/gate.sh` **ALL GATES GREEN**; clippy (both
halves) and rustdoc clean; zero dependencies and `no_std` untouched.
Each new test is pinned to a verdict *and* a kind: the two `tag_cannot_prove_this`
methods must fail with `kind == "postcondition"`, so an unrelated refusal cannot satisfy
them, and `TaggedLeft::tag` / `TaggedRight::tag` must both be `Verified`, which pins that
resolution found *a* contract rather than dropping the method (a missing contract means
`requires: true` and no `ensures`, which also reads as verified -- so the F4 test alone
would not catch a drop). The `mir_coverage` example now lists methods alongside free
functions and reports the `Owner::method` key when a tail is ambiguous, so a shared tail
appears once per method instead of vanishing from the scoreboard.
## A contract on a nested item was keyed by its bare name -- a dropped contract is a false proof
The method fix above keyed a *method* by its `impl`'s location. A **free function**
had no such key: `Specs::by_fn` was keyed by the bare source name, and `resolve`
matched only the exact MIR name. But rustc names a function's *definition* by the
shortest crate-unique path suffix, so a nested item's printed name carries a path
the bare key never had:
* a free function inside a `mod` is `a::f` (bare `f` only when that is already
unique crate-wide), a trait's default method is `T::value`, and a function nested
in a function is `f::g`.
None of those matched the bare key, so the contract was **dropped**. A dropped
contract is not a refusal: `verify_function` builds its precondition and
postcondition from `contract`, so a missing one means `requires: true` and *no*
`ensures` -- the body was reported `Verified { obligations: 0 }` and never checked.
A false postcondition (`/// ensures: ret == 9` on a body returning 7) came back
**proved**. Two sibling `mod`s that each declared `f` were worse: one bare key, the
later `insert` overwrote the earlier, so one body was checked against the other's
claim -- a lost proof for one, a false proof for the other.
Two scan defects sat underneath the same keying:
* **A brace-on-the-next-line header.** `impl Foo` with the `{` on the following
line raises no brace depth on its own line, so the old pop ("depth has not
increased") fired *before* the header's methods and every method contract was
keyed as a free function's -- which then never matched `<impl at …>::m`.
* **A one-line body.** `impl Foo { pub fn m(&self) -> u8 { 1 } }` raises and
returns the depth *within* the line, so a pop keyed on the final depth never
fired and the `impl` stayed open over the rest of the file, qualifying every
later function as its method.
**The fix.** `enclosing_impls` became `line_scopes`, which returns a `LineScope`
per line: the innermost `impl`'s `(line, column)` **and** the enclosing
`mod`/`trait`/`fn` names. A header frame now carries an `opened` flag set when a
brace opens under it, so the pop waits for the matching close; a header with no
brace that ends in `;` (`mod a;`) is dropped so it does not linger. `extract` keys
every non-method contract by its **full source path** (`a::f`, `T::value`, `f::g`).
`Specs::resolve` matches the exact path first (so `a::f` and `b::a::f` stay apart
once rustc prints both in full), then a *unique* `::`-aligned suffix
(`is_path_suffix`); an ambiguous suffix is **refused**, not guessed, and a refusal
shows up as `missing`, which is visible. `resolve_targets` in `verify.rs` pairs the
same path-qualified keys to MIR bodies the same way. `select` matches a request
against the key, the MIR name, or a bare tail of *either*, so `f`, `a::f` and
`Owner::f` all find their target.
## A `const` generic parameter leaked a function-local `const` -- a false proof
The const table is the second half of the bare-name story. `parse::bare_const_uses`
scans the whole crate for a bare `const NAME` use site to tell a crate-level `const`
from a function-local one (the definition alone cannot: the dump prints both
identically). But a **`const` generic parameter's** *uses* print bare too --
`fn f<const N: usize>()` is erased from the fn header while `N as u8` prints as
`const N`, the very spelling a crate-level item's use site gets. So a const-generic
`N` anywhere made `N` look "used bare", a function-local `const N` in some *other*
function kept a bare program-wide key, and an unrelated contract naming `N`
resolved to that local's value. Depending on the claim that is a **false proof**
(`requires: N != 3` on a leaked `N == 3` is a vacuous precondition) or a spurious
`Failed`. Both the inline (`fn f<const N: usize>`) and split
(`fn f<\n const N: usize,\n>`) shapes leaked.
**The fix is positional, in two places.** A `const` generic parameter is always
written `const NAME:` immediately after a `<` or `,`; a `const` *item* never is.
`const_generic_params` reads the parameter names (skipping comments and string/char
literals), and `crate_level_consts` refuses a `const NAME:` whose preceding
non-space character -- on the same line, or the previous line's last character for
a split list -- is `<` or `,`. The parser then removes those names from
`bare_const_uses`, so the const-generic's bare uses no longer mask a local item.
The name is only *removed from the bare-use set*, not refused outright: a genuine
crate-level `const N` beside a const-generic `N` is still read (pinned by
`a_crate_level_const_is_still_read_beside_a_const_generic`).
**Evidence.** `scripts/test-count.sh` **718 -> 728** passed, 0 failed;
`scripts/gate.sh` **ALL GATES GREEN**; clippy (both halves) and rustdoc clean; zero
dependencies and `no_std` untouched. Nine new integration tests in `tests/mir.rs`
and two new unit tests pin the verdicts, and each was checked for teeth by
reverting its guard: without the path keying the trait-default and module tests
report `Verified { obligations: 0 }`; without the `bare_uses.remove` loop
`a_const_generic_does_not_leak_a_local_const` fails; without `prev_last` the split
`crate_level_consts` case fails.
## An associated `const` hid a compiled crate `const` -- a lost proof, and an unclosed comment panicked
The previous commit stopped a `#[cfg]`-disabled crate `const` from letting a
function-local item of the same name take the program-wide key. It did so by treating
*any* qualified `const` use with no matching qualified definition as a function-local
item. That test is too wide: it also matches a use of an **associated** constant.
rustc uses one as `const Foo::K` but defines it as `const <impl at …>::K`, so the use
path has no definition of its own spelling -- and the blanket rule claimed the bare
tail `K`, then discarded the compiled crate `const K` (whose bare definition it thought
that use explained). A contract naming `K` was left unreadable: a lost proof, not a
false one, but a proof dropped by a rule that cannot tell the two shapes apart.
**The fix reads the path's *owning* `::` segment.** `const_mentions` now also collects
every function's own name -- the last `::` segment of a `fn …` header (`owner`, `inner`,
`{closure#0}`, and the tail of `<impl at …>::method`). `claimed_bare_const_uses` keeps a
qualified use's bare tail only when the path's prefix ends in one of those names. So
`owner::K`, `Foo::local_in_method::L` and `outer::inner::M` name a function-local item
and claim it; `Foo::K` (an associated constant) and `a::K` (a module constant) do not,
and the compiled crate constant they name keeps its bare key.
**F2: `spec::const_generic_params` panicked on an unclosed block comment.** The scanner
runs over the raw source before rustc does, so it sees malformed input. After `const` it
skips a `/* … */` comment by scanning for `*/` and then stepping two bytes past it; an
unterminated `/*` ran the scan to end-of-file and the `j += 2` stepped past the buffer,
panicking on `fn f<const /*`. The skip is now clamped (`j + 1 < len` in the loop, and the
closing `j += 2` only when `*/` was actually found), so the malformed source is left for
rustc to reject -- a refusal, not a crash.
**Evidence.** `scripts/test-count.sh` **739 -> 745** passed, 0 failed; `scripts/gate.sh`
**ALL GATES GREEN**; clippy (`--all-targets` and the `no_std` half) clean; zero
dependencies and `no_std` untouched. Four new integration tests in `tests/mir.rs` and two
new unit tests pin the verdicts. Each guard was reverted to check for teeth: without the
function-name filter `an_associated_const_does_not_hide_a_crate_const` and its unit twin
`an_associated_use_does_not_claim_a_crate_const` fail (the crate `const K` is dropped);
reading the whole path prefix instead of its last segment fails
`a_nested_or_method_local_is_not_a_program_wide_name` and
`a_method_or_nested_local_use_still_claims_its_bare_definition` (a method/nested local
leaks back in). The unclosed-comment unit test `const_generic_params_tolerates_an_unclosed_block_comment`
fails without the clamp. A `<Foo as Tr>::K` trait form was tried and dropped: the path
starts with `<`, so `const_mentions` never records it and the test could not discriminate.
## A `const` printed as a CTFE brace-block on 1.85 lost its value -- seven MSRV-only failures
The front end reads `const` items from rustc's textual MIR, and the *shape* of a
constant's body is not stable across toolchains. Current stable prints a constant that
folds to a literal inline:
```text
const K: u8 = const 7_u8;
```
rustc **1.85** -- the MSRV floor -- prints the same item with its const-evaluated body
instead, as a brace-block whose value is an assignment to the return place `_0`:
```text
const K: u8 = {
let mut _0: u8;
bb0: {
_0 = const 7_u8;
return;
}
}
```
The parser only recognised the inline form (`body.strip_prefix("const ")`), so on 1.85
every constant folded to a literal was dropped from the table. A contract that named one
then went unreadable and the function was skipped -- and because the same contract is
readable on current stable, the defect was **toolchain-shaped**: the crate's own tests
passed on 1.99 and failed on the floor it claims to support. Seven `tests/mir.rs` cases
(the const-inlining family) failed on 1.85 and passed on 1.99 for exactly this reason.
**The fix reads the block's return-place literal.** A new helper `block_const_value`
scans a brace-block body for the `_0 = const <literal>;` assignment and returns the
literal; the `const` reader falls back to it when the body starts with `{`. A block that
*computes* its value (an `AddWithOverflow`, say) has no single literal to fold and the
item is still dropped rather than given a guessed value, so the change adds coverage
without adding unsoundness.
**Evidence.** `scripts/test-count.sh` **745 -> 746** passed, 0 failed, on both the MSRV
`1.85.1` and current stable; the whole `tests/mir.rs` suite is now **209/209 on 1.85,
1.99.1 and the nightly** (it was 202/209 on 1.85 before this fix, the same 209 on the
others). `scripts/gate.sh` **ALL GATES GREEN**; clippy (`--all-targets` and the `no_std`
half) clean; zero dependencies and `no_std` untouched. The new unit test
`a_ctfe_brace_block_const_folds_to_its_literal` was checked for teeth by reverting the
fallback: it then fails with `a CTFE brace-block \`const\` must fold to its \`_0\`
literal: {}` (the item is dropped).
## A branching `const` folded to its first arm -- a false proof the CTFE fix introduced
The CTFE fix above read the first `_0 = const …` assignment in a brace-block body. That
is right for the straight-line body it was written for, and **wrong for a body that
branches**. `const K: u8 = if false { 7 } else { 8 };` is `8`, and rustc prints it as a
block with one arm per branch:
```text
bb1: { _0 = const 7_u8; goto -> bb3; }
bb2: { _0 = const 8_u8; goto -> bb3; }
```
Reading the first arm in textual order stored `K = 7`, so a contract `ensures: ret == 7`
on a function returning `K` was reported **verified** while the constant is `8` -- a false
proof, and the worst kind: it certifies a claim about a value the program never produces.
The earlier fix's tests could not see it because every constant they used was
straight-line, and the hole is *not* MSRV-only: rustc emits a brace-block for an `if`-based
constant on current stable too, so this was reachable on every toolchain, not just 1.85.
**The fix refuses to fold anything but a single straight-line return.** `block_const_value`
now requires: exactly one `_0` assignment in the body; that assignment a `const` literal;
no branch anywhere in the body (`switchInt(`, `goto ->`, a `-> [` switch target, `unwind`,
`resume`, `abort`); and the literal's block to reach `return` with only storage
bookkeeping in between. A body that fails any of these is left unmodelled, which makes a
contract that names the constant *unreadable* -- a skip, never a false proof. This is the
conservative single-block check; a future change could fold a branch whose arms agree, but
nothing needs it, so nothing does it.
**Evidence.** `scripts/test-count.sh` **746 -> 747** passed, 0 failed; the `tests/mir.rs`
suite is **210/210 on stable, 1.85, 1.99.1 and the nightly** (it was 209). `scripts/gate.sh`
**ALL GATES GREEN**; clippy (both halves) clean; zero dependencies and `no_std` untouched.
Two new tests pin it -- the unit test `a_ctfe_brace_block_const_folds_to_its_literal`
gained a branching case, and `tests/mir.rs` gained
`a_branching_const_does_not_fold_to_its_first_arm`, which asserts that `ret == 7` is *not*
verified (the false proof) and that `ret == 8` is not verified either (a skip, not a
proof). Both were checked for teeth by reverting to the naive first-literal reader: the
unit test then reports `{"K": UInt(7, Some(U8))}` and the integration test fails with
`` `K` is 8, so `ret == 7` must not be reported verified, got: verified ``.
## The Verus oracle could fail on a runner's IP limit before it ran
The `verus` CI job looked up the latest release with an *unauthenticated* call to
`api.github.com`, which is capped at 60 requests an hour per IP. GitHub's runner IPs are
shared, so the call intermittently returned `403` and the job went red at the `curl` --
before a single line was compiled. It failed this way on `057bd20` (`curl: (22) ... 403`),
and a re-run on the same commit passed; the oracle itself was green locally
(`agree=97 mismatch=0 missing=0 refuted_identity=0`). A red job that says nothing about
the crate is worse than a slow one: it trains the reader to ignore the job.
**The fix authenticates the lookup.** The step now passes `github.token` as a bearer
header on the release query, raising the limit to 5000 an hour. Only the API call is
authenticated; the asset is fetched from the redirect target, which does not take the
header. This is the only unauthenticated `api.github.com` call in the workflows -- the
Ferrocene installer uses the `releases/latest/download` path, which redirects and is not
rate-limited the same way.
**The token is fed on stdin, not in `curl`'s argv.** The first cut passed it as a
`-H "Authorization: Bearer $GH_TOKEN"` argument, which is readable from
`/proc/<pid>/cmdline` by any process on the runner -- a secret exposure (CWE-214). The
Ferrocene step in this same workflow already piped its secret on stdin, so the argument
form broke a convention the file had set. `curl` reads headers from stdin with `-H @-`, so
the call is now `printf 'Authorization: Bearer %s\n' "$GH_TOKEN" | curl -fsSL -H @- …`.
Both forms were run side by side against a slow local server and the process list read
while they were alive: the argument form showed `-H Authorization: Bearer <token>` in
`cmdline`, the stdin form showed only `-H @-`. The stdin form still authenticates -- the
API reports `limit: 5000`, not the anonymous `60`. The workflow also declares
`permissions: contents: read`: it only reads a public release and checks out the repo, so
the token needs no write scope.
## The seven-way comparison, and the model-drift trap
`examples/comparison/` proves the same three functions (`sat_add`, `clamp`, `sum_to`)
with `verif`, Kani, Verus, Prusti, SPARK, Coq and Lean, and then proves that two
injected bugs (swapped `sat_add` branches, wrong `sum_to` loop body) are refused by
every one of them. Its README is the write-up; this is the part that costs time to
rediscover.
**The Coq/Lean model-drift demonstration is the point, not a footnote.** The first
`example.v` modelled the `u16` add as ordinary `Z` integers and `coqc` *proved the
buggy `sat_add` correct*: in unbounded `Z` the sum never wraps, so the branch that
overflows on a real `u16` cannot overflow in the model. A correct proof of a false
statement. The committed version models the wrap explicitly
(`Z.modulo (a + b) 65536`) and the same false theorem is unprovable. This is the
concrete argument for why `verif` reads MIR instead of a hand-written model: there
is no transcription step, so there is no transcription to get wrong. Do not "simplify"
the Coq or Lean model back to plain integers.
**Tool quirks that cost the most time here:**
- **Lean core has no `omega` via `split_ifs`, and no Mathlib.** `omega` *is* available
(`import Init.Omega` is implicit), but `split_ifs` is Mathlib-only, so write the case
split with `by_cases` + `rw [if_pos h]` / `rw [if_neg h]`. Those two lemmas are
deprecated in 4.35 in favour of `ite_eq_left`/`ite_eq_right` but still work. A
`unfold f MAX` that does not end in `at *` leaves `MAX` opaque in the hypotheses and
`omega` then reports a bogus counterexample with `c := ↑MAX`.
- **Coq has no machine word in the standard library.** Spell the wrap as `Z.modulo _ 65536`
so `Z.mod_small` applies. `Z.land` has no upper-bound lemma in `ZArith` (searched: only
`land_diag`, `land_comm`, `land_assoc`, `land_m0/l/m1`), so a `land`-based mask needs a
hand proof; `modulo` does not.
- **SPARK (`gnatprove`) needs `use type Interfaces.Unsigned_16;`** at spec scope, or
every comparison operator in a contract is "not directly visible" and the run dies in
"generation of Global contracts" before proving anything. A loop needs **both**
`pragma Loop_Invariant` and `pragma Loop_Variant`, or termination is left as a
`medium` warning and `--level=2` is not clean. Install with
`alr toolchain --select gnat_native && alr install gnatprove`; the compiler and
`gprbuild` live under `~/.alire/libexec/spark/bin`, not `~/.alire/bin`.
- **Prusti 0.2.2 uses `body_invariant!(...)`**, not the `#[invariant]` attribute, and
needs its own pinned `nightly-2023-08-15`, a JDK 21 (`JAVA_HOME`), and `chmod +x` on
the bundled z3 or it ICEs.
- **Verus requires `decreases` on every loop** and a `main()` function; without a
`decreases` the error is `loop must have a 'decreases' clause`.
- **Kani is the one tool that needs no induction hypothesis**: `#[kani::unwind(10)]`
bounds `sum_to` because `n <= 8`. That is the honest difference -- it is a bounded
check, not a proof for all `n`.
**Ferrocene is a different axis and must not be listed as a verifier.** It is the
qualified *compiler* (TÜV SÜD; ISO 26262 ASIL D, IEC 61508 SIL 3, IEC 62304 Class C),
so it qualifies the toolchain, not the program: it compiles the buggy `sat_add`
cleanly and, with a release profile, returns `0` exactly as plain `rustc` does. It is
already gate 3 (`tools/ferrocene/run.sh`, exit 2 = absent = report and skip). A
qualified compiler is not a qualified verifier, and building with Ferrocene confers
nothing on `verif`'s engine.
**The gate enumerates examples explicitly, so new files under `examples/` are safe**,
but `gnatprove` writes `obj/` next to the `.gpr`; `examples/comparison/.gitignore`
ignores it so a proof session cannot be committed.
## Five reports against the intrinsic model: one false proof, one panic, one false claim, and two gaps
A batch of five reports against the `core`-intrinsic model. Four were real; each fix is
guarded by a test that fails without it, and the fifth was a wrong claim in the corpus prose
rather than in the engine. `scripts/test-count.sh` **760 → 764** passed, 0 failed;
`scripts/gate.sh` **ALL GATES GREEN**; clippy (`--all-targets` and the `no_std` half) and
rustdoc clean.
**Report 1 — a trait method sharing an intrinsic's name could get a *false proof*.**
rustc prints a local trait impl's *definition* as `<impl at FILE:L:C: L:C>::is_power_of_two`
but its *call* as `<u8 as Trait>::is_power_of_two`. The names never match, so the exact-name
same-dump lookup missed; `try_intrinsic` classifies on the *suffix* (`is_power_of_two`), so it
answered the call from `core`'s model before type-aware callee resolution ran. A
`Trait::is_power_of_two` for `u8` that returns `false` then *proved* `ensures: ret == true` at
`x == 1` — a false proof of a body that disagrees with `core`. The fix is two halves of one
guard: (1) the `Call` term now consults `resolve_callee` *first* and only falls through to the
model when no same-dump body exists; (2) `try_intrinsic` returns `None` for any name that does
not carry the `<impl …>` projection. The invariant that makes (2) safe is that rustc prints
*every* real `core` integer-method call with that projection (`core::num::<impl
u8>::wrapping_add`) and no local method call ever carries it, so the guard refuses only names
that could name a local body. The direction is a refusal, so a misjudged spelling loses a proof
rather than inventing one. New corpus fixtures
`trait_is_power_of_two_disagrees_with_core` (verifies) and `…_tripwire` (refutes) pin both
directions; the tripwire fails without the fix.
**Report 2 — the 64-bit bit counts panicked (or, without overflow checks, were wrong).**
`bit_count(TrailingZeros, …)` built its low-bit mask `2^k - 1` with a *host* shift and ran `k`
to `w`, so at `w == 64` the last step was `1u64 << 64`: a panic under overflow checks and,
without them, an all-zero mask that makes `x & mask == 0` true for every operand, so every
`trailing_zeros`/`trailing_ones` at 64 bits came back one too large. The last mask is now
`smt::all_ones(w)`, the same low-bit mask without the shift. The existing exhaustive bit-count
test only reaches 32 bits (`0..(1u64 << w)`), which is why it missed this; the new
`the_64_bit_counts_agree_with_rust` walks chosen separating operands at 64 bits and fails on
the old code.
**Report 3 — the mixed-add fixtures were asserted nowhere, and every one was true.** The eight
mixed-signedness fixtures added with the model had no test asserting their verdicts, and each
was true at its pinned inputs, so a regression that *proved* a false claim about them would not
have failed the suite. The fix adds the missing true pins (`checked_add_signed_in_range_is_the_sum`,
`checked_add_unsigned_in_range_is_the_sum`, `overflowing_add_unsigned_within_range_is_not_overflow`,
`overflowing_add_unsigned_past_the_top_is_overflow`) and one false tripwire per shape
(`wrapping_add_signed_wrong_value_tripwire`, `saturating_add_signed_wrong_value_tripwire`,
`overflowing_add_signed_wrong_flag_tripwire`, `checked_add_signed_none_tripwire`,
`wrapping_add_unsigned_wrong_value_tripwire`, `saturating_add_unsigned_wrong_value_tripwire`,
`overflowing_add_unsigned_wrong_flag_tripwire`, `checked_add_unsigned_wrong_value_tripwire`), all
asserted by `the_mixed_signedness_additions_verify_and_their_tripwires_refute`. The
`overflowing_add_signed_wrong_flag_tripwire` is the one a bare-carry flag model proves (checked
for teeth by breaking the model to `Some(carry)` — it then verified the false claim).
**Report 4 — the `bool` predicate was never exercised through a branch.** Every
`is_power_of_two` fixture returned the predicate, so the `bool` reached the return place and the
obligation read it there; a regression in *branching* on it would have left the tests green.
The corpus gains `is_power_of_two_branching_takes_the_true_arm`,
`…_takes_the_false_arm` and `…_of_zero_tripwire` (an `if` with different constants per arm),
asserted by `is_power_of_two_branches_on_the_predicate`.
**Report 5 — the corpus prose had the carry backwards.** The doc-comment on
`overflowing_add_signed_below_zero_is_overflow` said "the carry fires *and* the flag is set",
but for `0u8 + (-1i8)` there is no carry: the addition reads `-1i8` as `255u8` and
`0u8 + 255u8` is `255` with no carry, so the flag comes purely from the addend's sign
(`carry ^ (addend < 0)` is `false ^ true`). The claim was about the *model*, not the engine,
and it was wrong; the prose is corrected. No behaviour changed.
The lesson, again: a fixture that is never asserted is not a test, and a fixture that is always
true cannot catch a prover that says "true" too often. The negative direction has to be in the
suite, with a witness, or the standing tripwire rule is only a comment.
## `Ord::min`/`Ord::max`: the first modelled trait methods, and the guard exception they forced
The corpus's top idiom gap was `x.min(y)`/`x.max(y)`, which were `incomplete` with "call to
unmodelled function `<u8 as Ord>::min`". Modelling them is the increment; the interesting part
is *why they are hard*, because they are the first modelled shape whose call is a **trait**
call rather than a `core::num::<impl …>` inherent one, and that collides with the guard that
keeps the model from ever answering a local body.
The guard (from the Report-1 work) is: `try_intrinsic` returns `None` for any name that does not
contain `<impl`, because rustc prints every real `core` integer-method call with the
`core::num::<impl u8>::wrapping_add` projection and no local method call carries it. But a trait
call has no `<impl` by construction — it is `<u8 as Ord>::min` — so the guard would have made
`Ord::min`/`max` permanently unmodellable. Removing the guard outright is *also* wrong: it was
what allowed Report 1's false proof in the first place. The reconciliation is that the guard's
job is really done by the caller, which consults `resolve_callee` (same-dump lookup) *before*
the model. Two experiments pinned this: with the guard removed and the reorder in place, the
Report-1 soundness test still passes and the whole 216-test MIR suite stays green, which shows
the reorder — not the guard — is what carries soundness; and with the guard restored, core
`Ord::min` is unmodelled.
So the guard gains one **narrow exception**, `is_ord_callee`, admitting a name only when all of
these hold: the method is `min`/`max`; the trait path between `as` and `>` is exactly `Ord`,
`core::cmp::Ord`, or `std::cmp::Ord`; and the self type is a *primitive* integer. Each clause
closes a real hole.
- **The trait path must be the standard library's.** A local trait in a module prints its call
as `<u8 as m::Ord>::min` — trait path `m::Ord`, refused. `std::cmp::Ord` and `core::cmp::Ord`
cannot name a user item, because a user cannot define items inside `std`/`core`. So the
accepted set is exactly the prelude's `Ord`.
- **The self type must be primitive.** A user type can be `Ord`, but the model has no definition
for its `min`, so admitting it would only answer a call with no meaning. Refusing keeps the
direction conservative.
- **A crate-root trait named `Ord` is the one spelling that can still collide**, because it
prints as `<u8 as Ord>::min` — indistinguishable from the prelude's by name alone. This is
*not* closed by name; it is closed by the caller's same-dump lookup, which finds the local
body first. The corpus pins this: `ord_shim` (a module-qualified local `Ord`) verifies from
its body's constant, and the crate-root case was checked by probe.
The model itself is total and sign-aware: `min` is `ite(sle(x,y), x, y)` signed and
`ite(ule(x,y), x, y)` unsigned, `max` the same with `sge`/`uge`. The sign is not cosmetic —
`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, a *wrong value* rather than a weaker
proof. `the_ord_min_max_agree_with_rust` walks all of `u8` and all of `i8` against `core`'s own
methods, and names the separating points (`0x80`, `0xff`/`0xfe`) so a failure names the pair.
The integration test `ord_min_and_max_are_modelled_and_a_local_trait_still_wins` covers the
unsigned and signed orderings, the explicit `Ord::min` spelling, a tripwire on the method form,
and the local-trait pair — and it *fails* if the guard exception is removed (checked by
temporary revert), so the exception is load-bearing rather than decorative.
`scripts/test-count.sh` **764 → 767** passed, 0 failed; `scripts/gate.sh` **ALL GATES GREEN**.
Corpus coverage `examples/mir_targets/realistic.rs` **344 → 349** verified over 643 → 650 lines
(the two new tripwires refute, as they must). No new SMT primitives were needed: `sle`, `sge`,
`ule` and `ite` already existed.
## `From::from`/`Into::into`: the second trait-method exception, and the two-type shape
A widening conversion is the *same shape* of exception `Ord` is — a trait method whose call
carries no `<impl` — so it is admitted the same way: `classify` accepts `from`/`into` only under
the standard library's trait path, `try_intrinsic`'s `<impl` guard gains `Conversion` beside
`is_ord_callee`, and the same-dump lookup still answers any local body first.
Two things make conversions harder than `Ord`, and both are handled in the model rather than
the guard:
- **The two operand *types* differ, and both are in the name.** `Ord::min`'s operands share the
receiver's type, so one width read off the argument suffices. A conversion's whole content is
the *pair* of types, and rustc spells them in opposite positions for the two directions:
`From` is `<DEST as From<SRC>>::from` (self type = destination, parameter = source) and `Into`
is `<SRC as Into<DEST>>::into` (the other way round). `conversion_types` reads both out of the
call's own name — independent of how the executor happened to type the argument — and the
executor passes the *source* width/sign as `w`/`signed` and the *destination* width as
`result_w`. This is the one shape where those two differ by construction (the bit counts are
the other, and there the result is a fixed `u32`).
- **Only a *strict widening* is a real integer `From`.** `core` implements `From` for exactly
the strict widenings (`u8 → u16`, `i8 → i16`, `u8 → i16`, …) and nothing else, so requiring
`dst_w >= src_w` between two modelled integers accepts every real call and refuses every
malformed or same-width spelling, which is the conservative direction. The extension is by the
*source's* sign — `i8::MIN` widens to `i8::MIN` (`0xff80`), `255u8` widens to `255u16` — and
that is deliberately the *same* rule the executor's `as`-cast arm uses, so a conversion and a
cast of one shape build one term (`convert_value` is the shared helper; the unit test pins the
agreement against the real `From` impl over all of `u8`/`i8`).
The trait-path set is `From`/`Into`, `core::convert::…` and `std::convert::…`. The `std::convert`
spelling is not hypothetical: the corpus prints `<u16 as std::convert::From<u8>>::from` once a
local trait also named `From` is in scope, because rustc then qualifies the prelude trait to
disambiguate. All three are the standard library's `From` and a user cannot define items inside
`core`/`std`, so the set is exactly the prelude's; a module-qualified `m::From` is refused by
name, and a crate-root `From` — which prints as the bare `From` too — is closed by the same-dump
lookup, exactly as for `Ord`.
`scripts/test-count.sh` **767 → 774** passed, 0 failed; `scripts/gate.sh` **ALL GATES GREEN**.
Corpus coverage `examples/mir_targets/realistic.rs` **349 → 353** verified over 650 → 655 lines
(the sign-extension tripwire refutes, as it must). The strengthened
`a_static_call_resolves_to_its_own_impl_cannot_prove_this` now *refutes* with a witness
(`x == 0`) where it used to be `Incomplete` — the modelled conversion answers the call, so the
local `from` is not consulted at all. No new SMT primitives were needed: `sign_extend` and
`truncate` already existed.
### The comparison traits: the same exception, with a by-reference receiver
`PartialEq::eq`/`ne` and `PartialOrd::lt`/`le`/`gt`/`ge` are the six comparison
operators in their *trait-method* spelling, so a call prints as `<u8 as
PartialOrd>::lt` — no `core::num::<impl …>` path — and they are admitted by exactly
the same exception as `Ord::min`/`max` and `From`/`Into`: `classify` accepts the
name only when the trait path is the standard library's (`names_cmp_trait`) and the
tail belongs to the trait it names (`eq`/`ne` are `PartialEq`'s, the four orderings
`PartialOrd`'s — the crossed pairing is never emitted and is refused), the
executor's `<impl` guard gains `is_cmp_callee`, and the caller's same-dump lookup
answers a crate-root trait before the model.
Two things are specific to these shapes and both are traps:
- **Both operands are `&self`/`&other`, so the executor must follow *two*
references, not one.** The receiver goes through the existing `pointee` step (the
`is_ascii_*` receivers already do), but the *second* operand is also a reference,
and the generic operand read returns `Unknown` for a pointer. The `args.get(1)`
arm now follows the referent for a `Cmp` call, the same step as the receiver.
- **The value is the operator's comparison, not a second implementation of it.**
`cmp_pred` builds `smt::eq`/`slt`/`ult`/… — the exact terms the operators build —
so a method call and its operator spelling cannot disagree. The sign picks the
ordering: an unsigned reading of `i8::MIN < 1` is wrong because `0x80` is the
largest unsigned byte, which is why the differential test walks both
signednesses against the operators themselves (the oracle is the operator, not
the method, or it would just reproduce the model's reading).
The local-trait hazard is pinned in both directions, as for `Ord`: `cmp_shim::PartialOrd`
(a module-qualified local trait) is refused by the path, and its fixture
`local_partial_ord_lt_is_answered_by_its_body` verifies only from the body's constant
while `local_partial_ord_lt_is_not_the_model_tripwire` refutes only if the body — not
the model — answered. The crate-root collision (`trait PartialOrd` at the crate root,
which prints bare) is closed by the same-dump lookup, checked by probe.
### The owner-type gap this work surfaced, and how it was closed
While checking the local-trait case, a probe found a **false proof that predated this
increment** (confirmed on the unmodified tree): a local `impl From<u8> for u16` whose body
returns `7` was *wrongly* consulted for a real `<u16 as std::convert::From<u8>>::from(x)` call,
so a contract `ret == 7` verified. The mechanism was `resolve_callee`'s owner-type match: the
local impl's *definition* name `<impl at …>::from` shares the tail `from` with the call
`<u16 as std::convert::From<u8>>::from`, and `method_owner_type` read the owner as `u16`, which
equals the call's self type — so the local body won the same-dump lookup for a `core` call. The
gap was in the same-dump resolver, not in the conversion *model* (a fallback that is never
reached when the lookup matches), and it applied to *any* local impl on a primitive whose owner
type matched an external trait call's self type.
It is now closed by making the resolver **trait-aware**. `Specs` gains an `impl_traits` map —
the trait each `impl` block implements, keyed by the same `(line, column)` as `impl_owners`,
read by the new `spec::impl_trait` parser and qualified with its enclosing module (so
`impl From<u8> for u16` inside `mod m` records `m::From`, the path rustc prints in a call). A
*trait* call (`<T as Trait<…>>::m`) is admitted only when the call's trait path is a `::`-aligned
suffix of the candidate impl's own trait path (`trait_candidate_admits`): a bare `conv_shim::From`
is not a suffix of `std::convert::From`, so the local body can no longer answer the library call,
while the local trait's *own* call (`conv_shim::From::from(x)`) still reaches its body. A bare
`Type::m` call carries no ` as ` projection — rustc prints both an inherent method and an in-scope
trait method that way — so it keeps the owner-type match alone, as before.
The corpus pins both directions with a `conv_shim` fixture mirroring `ord_shim`:
`local_from_does_not_answer_the_std_trait` (the false proof, must refute) and
`local_from_is_answered_by_its_own_body` (the local trait, must verify). The integration test
`a_local_trait_named_from_does_not_answer_the_std_trait` **fails** on the pre-fix tree — it
reports the false proof `verified (1 obligation(s), 0 panic(s) ruled out)` — so the guard is
load-bearing, not decorative. Unit tests pin the parser (`impl_trait`) and the map's keying and
module-qualification.
`scripts/test-count.sh` **774 → 777** passed, 0 failed; `scripts/gate.sh` **ALL GATES GREEN**.
Corpus coverage `examples/mir_targets/realistic.rs` **353 → 354** decided over 655 → 657
contracts (the two new `conv_shim` entries: one verifies from the local body, one refutes the
library call it must not answer). No new SMT primitives: the guard is a name comparison, and the
model is unchanged.
## Trait identity: the bare-name and imported-trait spellings, and the self-type key
The `impl_traits` guard above compared a call's trait path with the candidate impl's own path
by `::`-aligned suffix. Two more false proofs hid behind the suffix reading, both surfaced by
adversarial review and both now closed.
**A bare name is the crate-root trait only when the crate declares one.** rustc prints a trait
in a call as its *shortest crate-unique* path. `mod m { pub trait Trait { … } }` plus a
crate-root `trait Trait { … }` makes the crate-root call print bare (`Trait::pick`) while the
module trait prints qualified (`m::Trait::pick`). A suffix match accepted `m::Trait` for the
bare call, so a contract written against the crate-root body verified from the module's body —
a false proof. The fix is `Specs::declared_traits` (the crate's own traits as module-qualified
paths, from `spec::declared_traits`) and a rewrite of `trait_candidate_admits` as an *identity*
rule: identical paths match; a bare `want` matches only the crate's *unique* trait of that name
(or the crate-root one when several share the name, which is the `have == want` case); a bare
`have` matches a qualified `want` only when the crate declares no local trait of that name, so
the bare name can only be the library trait.
**A local `impl` of an *imported* trait needs the self type, not just the trait path.** A
crate that only *imports* a library trait — `use std::convert::From;` plus a local
`impl From<Local> for u16` — prints its call `<u16 as From<Local>>::from`: the bare library
name, because the local `From` is the only one in scope. The crate declares no trait named
`From`, so `declared_traits` alone does not refuse it, and the model would answer a call the
compiler resolved to the local body. The owner (`u16`), the method (`from`) and the trait path
(`From`) all match the model's conversion, so none of them separate it. What does is the call's
*self type* (`Local`, the conversion's source, read by `call_trait_path`'s caller from between
`as` and the trait name) against the candidate impl's own self type (`impl_self_ty`, the part
between `impl` and `for`). `trait_candidate_admits` now takes both: when `want` is bare and the
crate declares no trait of that name, an impl whose self type is not a plain trait path matches
only if it equals the call's self type.
The corpus cannot express the imported spelling: its own `conv_shim::From` forces rustc to
qualify the library trait (`<u16 as std::convert::From<…>>::from`), which is the *other*
branch. The regression test `a_local_impl_of_an_imported_trait_does_not_answer_the_model` uses
its own inline source (via `verify_src`) so no local `From` competes with the import.
`scripts/test-count.sh` **777 → 780** passed, 0 failed; `scripts/gate.sh` **ALL GATES GREEN**
(clippy std + no_std, tests, no_std bare-metal, zero deps, rustdoc ×3, MSRV 1.85, artifacts,
unsafe surface still 2). No new SMT primitives: both guards are name/type comparisons, and the
model is unchanged.
## Trait identity, round three: default-body overrides, generic arguments, and the import scan
A second adversarial review of the same resolver surfaced four more defects -- two false proofs
and two lost proofs -- plus one stale doc claim and a bug in the guard added by the previous
round. All are closed here. The unifying lesson: **a trait method's identity is not its path.**
It is the path *and* the instantiation *and*, when a default body exists, whether any impl
overrides it.
**Finding 1 (false proof): an overridden method verified against the trait's default body.**
`trait T { fn value(&self) -> u8 { 1 } }` with `impl T for Foo { fn value(&self) -> u8 { 2 } }`
makes `<Foo as T>::value(&foo)` return `2`, but rustc keeps the *default* `T::value` in the dump
(printed `T::value`, no `<impl at`). `resolve_callee` looked for a default body *first* and
inlined its `1`, so a contract `ret == 1` was **proved** for code Rust returns `2` from. The
search for an `impl` candidate now runs first, and the default is consulted only when that search
finds *nothing*: an impl that does not override emits no `<impl at …>::m`, so the default is the
only body; an impl that does override contributes exactly one hit, which wins. Two or more hits
stay ambiguous and are refused rather than resolved to the default.
**Finding 2 (false proof): a local impl answered a different *instantiation* of a generic trait.**
`impl From<Local> for u16` (body `107`) and the library's `impl From<u8> for u16` share the trait
path (`From`), the owner (`u16`) and the method (`from`); only the trait's *argument* separates
them. The previous round's self-type guard was supposed to catch this, but it never fired (see
below), so `<u16 as From<u8>>::from(7u8)` was answered from the local body and `ret == 107` was
proved. The fix reads the trait's arguments on *both* sides -- `call_trait_args` from the call's
name, `Specs::impl_trait_args` (new, parsed by `spec::impl_trait_args`) from the impl header --
and requires them equal. An unreadable side is refused rather than waved through, because it
could be the impl the call did not name. `args_match` allows the one spelling gap rustc creates:
the dump prints a type by its *shortest crate-unique* path, so `impl From<crate::Local> for u16`
prints its call's argument as the bare `Local`; a bare dump argument therefore matches a
module-qualified source spelling, while a *qualified* dump argument is compared exactly.
**Findings 3 and 4 (lost proofs): an imported trait was qualified with its own module.**
`mod m { use std::convert::From; impl From<…> for u16 { … } }` records the impl's trait as the
*imported* path (`std::convert::From`), because that is what the compiler prints in the call. Two
defects broke that. First, `module_imports` reset its running map on *every* scope change, so a
nested `mod nested {}` inside `m` cleared `m`'s imports for the rest of `m`; the later
`impl From<…>` was qualified `m::From` and no call matched -- a lost proof. Imports are now kept
*per module path*, assembled from every `use` at that depth regardless of order, since Rust item
imports are order-independent. Second, the scan read one line at a time and only stripped a bare
`pub ` prefix, so a folded `use a::b::{\n C,\n};` and a restricted `pub(crate) use …` were both
missed entirely -- the same lost proof. The scan now folds a `use` item through its `;` and
`strip_visibility` handles `pub`, `pub(crate)`, `pub(super)` and `pub(in …)`.
**The previous round's guard was itself broken.** `impl_self_ty` was meant to return the
candidate's self type (the part between `impl` and `for`), but for a definition name
`<impl at …>::from` it returned the *method* (`from`). It only appeared to work because the
`have == want` arm of `trait_candidate_admits` matched first for the imported-trait case, so the
self-type arm was never reached -- and Finding 2 is exactly what slipped through. `impl_self_ty`
is removed; the argument key that replaces it is read from the *header* (via `impl_trait_args`),
where the type is unambiguous.
**Finding 5 was a stale doc claim, not a code bug.** The README and two `intrinsics.rs` comments
said a *same-width* `From` call is refused. It is not: `<u8 as From<u8>>::from(x)` is `core`'s
reflexive `impl<T> From<T> for T`, and `eval` accepts it (`result_w >= w`), modelling the source
unchanged -- which the differential oracle agrees with. Only a *narrowing* is refused. The prose
now says so, and the corpus pins the identity (`same_width_from_is_the_identity` plus a tripwire).
Regression coverage: `an_override_wins_over_the_traits_default_body`,
`a_generic_traits_arguments_separate_its_impls`, `an_imported_trait_keeps_its_imported_path`,
`a_multiline_restricted_import_is_read` (all inline, via `verify_src`), plus corpus fixtures for
the override and generic-argument directions and the same-width identity.
`scripts/test-count.sh` **780 → 784** passed, 0 failed; `scripts/gate.sh` **ALL GATES GREEN**
(clippy std + no_std, tests, no_std bare-metal, zero deps, z3 oracle 845 agree / 0 mismatch,
rustdoc ×3, MSRV 1.85, artifacts, unsafe surface still 2). No new SMT primitives: every fix is a
name, argument or scope comparison, and the model is unchanged.
## Trait identity, round four: nested trait arguments and the conditional import
A third adversarial pass over the same resolver found two more defects, both *lost* proofs, in the
two helpers the previous round added. Both are closed here. The lesson this time: **a reader added
for one spelling must be used on *both* sides, and raw source is not the enabled crate.**
**Finding 7 (lost proof): a nested trait argument lost the local body.**
The previous round added `call_trait_args` (the call's argument) and `Specs::impl_trait_args` (the
impl header's argument) and required them equal. But the two readers disagreed on a *nested*
argument: `impl_trait_args` used `spec::angle_inner` (balanced), while `call_trait_args` read to
the first `<` and then `trim_end_matches('>')`. That strips *every* closing bracket, so
`<W as Wrap<Option<u8>>>::get` yielded `Option<u8` -- which no balanced impl reading (`Option<u8>`)
equals. The argument comparison then refused the match, the call had no body, and it was reported
unmodelled: a *lost* proof (`ret == 9` for a local body returning `9` was `Incomplete`). The fix
makes `call_trait_args` read with `angle_inner` too, so both sides spell the argument the same
balanced way. Corpus: `nested_trait_arg_finds_the_body` verifies, its tripwire is refuted.
**Finding 8 (lost proof): a `#[cfg]`-disabled import displaced a live alias.**
`module_imports` reads raw source, but rustc emits MIR only for *enabled* items. A live
`use std::convert::From as Conv;` binds `Conv` to the standard trait; a later
`#[cfg(any())] use crate::Other as Conv;` binds nothing. The map was built by plain insertion in
source order, so the disabled import overwrote the live binding, the impl written with `Conv` was
recorded against `crate::Other`, and the call the compiler resolved to the standard trait matched
nothing -- a lost proof (reported `converts a type the model does not hold`). The fix records, per
binding, whether it came from an *unconditional* `use`, and a conditional binding never displaces
an unconditional one. An unconditional binding still wins wherever it appears, and a conditional
binding is still applied when it is the only one (the source cannot evaluate an arbitrary `cfg`,
so the conservative reading is "this may be off, so never let it override a definite binding").
Corpus: `cfg_disabled_import_keeps_the_live_alias` verifies, its tripwire is refuted.
**The same-line attribute form.** A `#[cfg] use …` whose attribute shares the line hides the `use`
keyword from `is_use_start`, so the import was missed *entirely* -- the same lost proof for a live
binding. `strip_visibility` now peels any leading `#[…]` attributes (with depth-matched brackets)
before reading the visibility, so `#[cfg(all())] use std::convert::From as Conv;` is read; and
`is_cfg_use` sees the same-line `#[cfg]` when deciding precedence. A `#[cfg]` attribute on the
item's own line was also previously invisible to the scanner, so it could not even be identified
as conditional.
**The multi-line attribute form.** The same hazard for an attribute that *wraps*:
`#[cfg(all(\n any(),\n))]` puts the closing `)]` on the line directly above the `use`, so a
one-line look upward sees no `#[cfg…` and treats a *disabled* import as live, displacing the live
alias (again a lost proof, `converts a type the model does not hold`). `is_cfg_use` now reads the
whole attribute block directly above the item as complete, bracket-balanced `#[…]` items
(`read_attr_run`), so a condition that spans lines is found. The block ends at the first line that
is not an attribute, so a `#[cfg]` belonging to an earlier item is never read as this one's.
Corpus: `cfg_multiline_import_keeps_the_live_alias` verifies, its tripwire is refuted.
**A quoted delimiter is not a delimiter.** The same reader counted *every* character as a bracket,
so a delimiter inside quoted text unbalanced it: `#[doc = "("]` holds an unmatched `(`, the run
never finds its closing `]`, exhausts its lines, and `read_attr_run` returns `None` -- the disabled
`#[cfg]` above it is then read as live and displaces the live alias (again
`converts a type the model does not hold`). `read_attr_run` now tracks string and character
literals (honouring backslash escapes) and skips their contents while matching `#[…]`. A `'` opens
a char literal only when it looks like one (`'('`, `'\n'`), not when it is a lifetime (`'a`), since
reading a lifetime as an unclosed literal would make every later attribute unreadable
(`is_char_literal_start`). Corpus: `cfg_quoted_delimiter_keeps_the_live_alias` verifies, its
tripwire is refuted.
Regression coverage: `a_nested_trait_argument_keeps_its_balanced_spelling`,
`a_cfg_disabled_import_does_not_displace_a_live_alias`, `a_same_line_cfg_import_is_read`,
`a_multiline_cfg_import_does_not_displace_a_live_alias`, `a_quoted_delimiter_does_not_hide_a_cfg_import`
(inline, via `verify_src`), `the_nested_argument_and_cfg_alias_fixtures_are_decided` (corpus, the
one-line, multi-line and quoted-alias directions), plus six unit tests on the readers themselves
(`leading_attributes_are_peeled_and_a_cfg_is_reported`,
`a_use_behind_a_same_line_attribute_is_still_an_import`,
`a_cfg_import_does_not_displace_a_live_binding`,
`a_conditional_binding_is_held_below_an_unconditional_one`,
`a_multiline_cfg_attribute_is_seen_above_a_use`,
`a_delimiter_inside_a_quoted_attribute_is_not_a_delimiter`).
`scripts/test-count.sh` **784 → 796** passed, 0 failed; `scripts/gate.sh` **ALL GATES GREEN**
(clippy std + no_std, tests, no_std bare-metal, zero deps, z3 oracle 845 agree / 0 mismatch,
rustc_public oracle 0 differ, MSRV 1.85, artifacts, unsafe surface still 2). No new SMT primitives:
every fix is a string read on the same two sides, and the model is unchanged.
## Preparing for crates.io: the checks that are not about correctness
The crate could pass all eighteen gates and still be unpublishable, and the
failure would only surface at `cargo publish` -- the worst moment, because an
upload cannot be undone. So the packaging work is a second set of checks, and
the interesting part is the four things it found that no compiler sees.
**A `.crate` must carry its own licence.** `verif-arithmetic/` had a
`Cargo.toml`, `src/` and `tests/` and nothing else. `cargo package --list`
showed ten files and not one of them was a `LICENSE`, so the published crate
would have shipped no licence text and no README at all -- legally
unredistributable, and a crates.io page with no documentation. It now has
`LICENSE` (a real copy, not a symlink: a symlink is not followed into the
archive), `NOTICE`, and a `README.md` whose example is pinned as a test.
**The bare-version-tag check rejected the parent's own tags.** `publish.py` was
written from a reference where a bare `v<version>` tag is refused with
`tag.startswith("v")`. That is correct there and wrong here: this repository's
parent crate is named `verif`, so its release tag `verif-v0.1.0` also starts
with `v` and was refused as "a bare version tag". The fix is `^v[0-9]` -- the
digit is what makes `v0.1.0` a version and `verif-...` a crate name. This is the
kind of defect a rename introduces: the reference's assumption was invisible
until the crate it ran against was called something beginning with `v`.
**The docs.rs metadata is load-bearing, and its absence is silent.** The default
feature set is empty (`no_std`), and the `mir` frontend and the proc-macro
surface are behind `std`. docs.rs builds the default features unless told
otherwise, so without `[package.metadata.docs.rs] all-features = true` the
published documentation would describe a crate *smaller* than the one that
ships, with no error anywhere. The first version of `check_package.sh` tested
for the key with `"docs.rs" not in str(metadata)`, which is wrong twice: the
parsed key is nested (`{"docs": {"rs": {...}}}`), and a crate with no
non-default feature needs no such table -- demanding one would be a flag with no
reader, the thing this repository argues against. The check now requires it only
where there is a feature to lose.
**Attribution is per crate, not global.** The first run reported
`verif-arithmetic/NOTICE` for `Kani` and `rustc_public`, because the scan
collected names from *both* crates' sources and then required *each* `NOTICE` to
name all of them. A project named only in the parent is the parent's to
attribute. Split per crate, the real finding appeared: `rustc_public` is
mentioned in `verif-arithmetic/src/lib.rs`, so the sibling's `NOTICE` has to name
it. Two of the four reports were the check's own bug; that is why the check was
run against a deliberately broken manifest as well.
**`verif`'s crate directory is the repository root**, so a dirty-file check
cannot attribute a root file to `verif` by path prefix -- every path is under the
root. `publish.py` relies on cargo's own `--allow-dirty` refusal for that crate
instead, which is scoped to the crate directory the way cargo intends.
`scripts/check_package.sh` is hermetic: it reads the manifests and the tracked
file list and runs no compiler, so it is cheap enough for every pull request. It
is a separate script rather than a nineteenth gate because renumbering the
existing eighteen is churn that risks the checks themselves. It, the
action-pinning check and the `package` dry-run job are all in `ci.yml`; the
release itself is `.github/workflows/release.yml`, tag-driven, one crate per tag,
because the two crates version independently.
`scripts/test-count.sh` **796 → 806** passed, 0 failed; `scripts/gate.sh` **ALL
GATES GREEN** (all eighteen). Two of the ten new tests are the pinned README
examples (`tests/readme.rs`, `verif-arithmetic/tests/readme.rs`); the other eight
come with the packaging checks. No engine change: every fix is a manifest field,
a packaging script, or a document.
## Three ways the release workflow would have failed, and one it would have caused
The release workflow was written and reviewed as a *plan*: the dry-run passes,
the notes generate, the upload runs. All three of those steps were checked in
isolation, and all three were wrong, in ways that only appear when they run in
sequence against a real repository. The pattern is the same in each: a step was
correct about its own output and wrong about what it left behind for the next.
**`notes.md` in the root dirties the crate the next step uploads.** `verif` is
packaged from the repository root -- its crate directory *is* the root -- and
`cargo publish` refuses a crate whose directory has uncommitted changes. The
notes step wrote `notes.md` there, after the dry-run and before the upload. So
the dry-run checked a clean tree, then the notes made it dirty, and the real
publish failed:
```
error: 1 files in the working directory contain changes that were not yet
committed into git:
notes.md
```
`verif-arithmetic` was unaffected, because its crate directory is the
subdirectory -- which is exactly why this was easy to miss: the sibling release
works, so the workflow looks correct until the parent is released. The fix is to
write the notes outside the checkout (`$RUNNER_TEMP`) and pass that path to `gh
release`. The dry-run and the upload now see the same tree, which is the property
that was actually wanted; "the notes exist" was satisfied either way.
This is the same defect class as the `.rlib` files gate 16 guards against -- a
step's output landing inside a crate directory -- and it is worth naming, because
the check for it already existed for a different file type.
**A manual dispatch would have packaged the branch and released the tag.** The
workflow pins `RELEASE_TAG` and checks it against the manifest version, and that
check is not enough for `workflow_dispatch`: the ref is chosen in the Actions UI,
and `inputs.tag` only controls what is *named*. If the default branch carries the
same version as the tag -- which it does right up until the release is cut --
the version check passes, the branch is packaged and uploaded under the tag, and
`gh release create --verify-tag` then attaches a release to the tag's commit.
The registry holds commit B; the release points at commit A. The version check
cannot see this, because both commits declare `0.1.0`. The commit can:
```
error: HEAD is 74018168e010 but `verif-v0.1.0` is ed0e30bcdb93; check out the tag,
not a branch
```
`ref: ${{ inputs.tag || github.ref }}` pins the checkout, and `--verify-checkout`
asserts it, so the two cannot drift. A version is a claim about content; a commit
is the content.
**A transient 404 after a successful upload aborted the whole release.** The
confirmation step called the crates.io API once and treated anything but HTTP 200
as failure. But a successful upload and an API-visible version are separate
events: the index is updated asynchronously, so the first request can 404 for a
few seconds after `cargo publish` returned success. The step then failed *after*
the crate was published and *before* the GitHub release was created -- the worst
of both, an upload that cannot be undone and no release to explain it.
`--confirm-index` now polls to a bounded deadline, retrying 404 and 5xx and
network errors, and fails fast on any other 4xx: a 403 will not become a 200 by
waiting, so retrying it only delays the report.
**And the fix for the first one would have introduced the fourth.** Moving the
notes generation into `publish.py` removed the `importlib` call the old inline
step used, but the old step *also* left a bytecode cache behind: importing a
script writes `scripts/__pycache__/` next to it, inside the checkout, which is
again a root-directory change that dirties the `verif` crate. It is untracked, so
gate 16 (which greps `git ls-files`) never saw it, and the `.crate` was fine --
but the *next* `cargo publish` would have refused. `__pycache__/` is now in
`.gitignore`, where it cannot be mistaken for a source change, and the notes step
runs the script as a program rather than importing it, so no cache is written at
all.
All three subcommands are exercised on the release path itself, and each was
tested with a negative control: `--verify-checkout` fails when the tag is absent
and when it points at another commit (including one whose version matches);
`--confirm-index` succeeds on a published crate, retries a 404-then-200, and
fails a 403 immediately rather than after the timeout.
## Migrating the corpus to `spec!`: a verdict diff is the check, and one guard hid a spelling
0.2.0 made `spec! { … }` the only spelling in this repository's own sources: the
examples, the three MIR corpora, the `comparison/` fixtures and the 149 inline
sources in `tests/mir.rs`. The work is mechanical and that is exactly why it needed
a check that is not "it compiles".
**The check is the verdict table, diffed row by row.** For each corpus file,
`mir_coverage` was run before and after the rewrite and the two tables compared:
`everyday.rs` 24 rows and `realistic.rs` 1151 rows came out byte-identical, and
`comparison_check` kept its six claims (one verified, four bug witnesses, one
degenerate). A rewrite that changed a clause's *meaning* — a body re-parenthesised
wrongly, a clause dropped, a `ret` renamed — shows up as a verdict that moved. It
is the same discipline as the SOUNDNESS ledger: the claim is about behaviour, so
the evidence has to be behaviour.
**The converter has to be a tokenizer, not a regex.** The clauses live inside Rust
*string literals*, in two shapes: `r#"…"#` raw strings, and normal strings with
`\n` escapes and `\`-continuations. A regex over the file matches the inside of a
raw string twice (once as raw, once as a normal literal), which over-counted the
work by 60% on the first attempt (785 clauses against a true 478). The working
converter walks the file once, tracking `//`, `/* */`, raw-string hashes and
escape sequences, decodes each literal, rewrites the clause run, and re-encodes
with a round-trip assertion (`decode(encode(x)) == x`).
**A clause body can be legal Rust and still break the macro matcher.** `-x as u8 <
127` parses as `as u8<127>` — the matcher reads the comparison as a generic
argument list — so the fixture stopped compiling. `(-x as u8) < 127` is the same
expression and the frontend's own parser reads nested parentheses, so the rewrite
is meaning-preserving. This is the `spec!` spelling's one ergonomic cost: a clause
is tokenised, so anything the macro matcher could mis-read needs a parenthesis.
The doc-comment form has no such problem, which is a real (if small) argument for
keeping it available.
**Three classes of source must keep `///`.** Converting them deletes the thing they
test or breaks the tool that reads them:
* the tests whose *subject* is the doc-comment reader
(`scanner_reads_contracts_and_ignores_inner_docs`,
`scanner_does_not_leak_a_contract_onto_a_later_function`,
`scanner_finds_a_pub_crate_fn`,
`a_clause_shaped_doc_comment_that_is_not_a_clause_is_refused`);
* `format!`-template fixtures, whose braces are placeholders, so a `spec!` block's
own braces would need escaping throughout — their subject is const generics,
trait paths and unwind bounds, not the spelling;
* a source that deliberately must not import `verif`.
**The migration found a real defect, and it is the lesson worth keeping.**
`assert_not_dropped` — the guard that fails a test when a contracted function is
absent from the report — decided "this source has a contract" with
`src.contains("///")`. A `spec!`-only source has no `///`, so it looked
contract-free and a *dropped* function passed the guard: the test would assert
nothing, which is the exact failure the guard was added to prevent. The marker is
now the clause *keyword* (`requires:`, `ensures:`, …), which both spellings carry.
The general shape, which this file has met before in other clothes: **a test helper
that recognises a feature by one of its spellings silently stops recognising it
when a second spelling is introduced.** The helper is not part of the feature, so
nothing points at it — only running the suite with the new spelling, which is what
the migration did.
**Evidence.** `tests/mir.rs` 359 passed / 0 failed with a nightly `rustc`;
`everyday.rs` and `realistic.rs` verdict tables unchanged; `comparison_check` 6/6;
`scripts/gate.sh` green; clippy clean on both crates.
## The docs.rs front page was three claims behind the code
The crate-level doc comment in `src/lib.rs` is not a comment. It is the page
docs.rs renders, the first thing a reader sees, and it said the crate "builds
**four** things" over a table of thirteen modules. Three of the sixteen modules
were missing from that table entirely -- `macros`, `vc` and `mir` -- so a reader
who trusted the front page would not learn that the contract vocabulary or the
real-Rust frontend existed. The `README` had the same class of drift in its own
module table (`bitblast` was absent, so the SAT fallback appeared from nowhere)
and pointed at "gate 9" for the `rustc_public` oracle, which is gate 10.
None of this is caught by the gates that existed. `#![deny(missing_docs)]` checks
that an item *has* documentation, not that the prose about it is true, and
`cargo doc -D warnings` checks that links resolve, not that the table is complete.
A count in prose is exactly the kind of claim this repository otherwise refuses to
leave unchecked, and it had been wrong in the one place with the widest audience.
What changed:
- **`src/lib.rs`** is now a landing page rather than a preamble: what the crate
is, three runnable examples (one per proof mechanism, plus a contract), a module
map grouped by purpose, the feature-flag table, and the "what this is not"
boundary. The "four things" count is gone; the map is grouped so adding a module
does not invalidate a number.
- **`verif-arithmetic/src/lib.rs`** gets the same treatment: the module table it
lacked, the `ENUM_BUDGET` honesty boundary stated once, an explicit "no feature
flags, and here is why docs.rs needs no metadata" note, and a pointer to when to
use the parent crate instead.
- **`README.md`** gains a grouped table of contents, and its module table is
complete. The stale "gate 9" is corrected to gate 10.
- **`scripts/check_doc_links.py`** resolves every internal anchor and relative
file link in the `README`, and gate 15 runs it. This is the part that makes the
rest stay true: the contents list is hand-written, so without a check it rots
the first time a heading is renamed, and a dead anchor renders as ordinary text
rather than an error. It reproduces GitHub's anchor rule (including the
duplicate-heading `-1` suffix) rather than approximating it, and it ignores
external URLs on purpose -- a network check would fail for reasons that have
nothing to do with this tree.
The examples added to `src/lib.rs` are doctests, so `cargo test` executes them:
`with_fresh` is not `std`-gated, so they run in the default build too. The
crate-docs now carry three runnable examples where they previously carried one,
and the suite count moved from 806 to 808 accordingly -- a `+2` and not a `+3`
because the old single example was replaced rather than kept. That the count
moved at all is the check that the examples are real and not prose.
## A documentation review found three claims the new docs made that were false
The rewrite above was itself reviewed, and three findings came back. All three
were real, and two of them were defects in the *checker* and the *docs* rather
than in the code -- which is the point worth recording: the material that is
supposed to be authoritative is the material least covered by the gates.
**The link checker dropped the fragment on a cross-document link.** `check`
partitioned the target into file and fragment, then used only the file part for
the existence test, so `[Ground rules](CONTRIBUTING.md#missing-heading)` passed
as long as `CONTRIBUTING.md` existed. A renamed heading in another document is
exactly the failure the checker was added to catch, and it caught it only for
same-document links. The fix reads the target file and resolves the fragment
against its anchors -- the same `anchors()` the same-document path uses -- with
the target's anchors cached per file, since the README links the same documents
repeatedly and re-reading them per link would be quadratic. Non-Markdown targets
(a `.rs`, a `.toml`) have no headings to resolve, so for those the existence
check remains the whole check. This is a textbook case of a guard that looks
comprehensive and covers one of the two shapes it must: the same-document branch
was tested, the cross-document branch was not, and the untested branch is the one
with the wider reach. The checker now also discovers its inputs (`*.md` at the
root) instead of taking the README alone, so a document added later is checked
without anyone remembering to list it.
**`saturating_add`/`saturating_sub` were described as returning `Option`.** The
table in `verif-arithmetic`'s crate doc grouped them with `checked_add` and said
"each returns `Option`, and `None` is exactly the case the machine op would have
wrapped". They return `u32` and clamp. A reader who trusted the table would write
`if let Some(x) = saturating_add(a, b)`, which does not compile -- the mildest
outcome available, since the wrong belief is "I will get a `None` and handle it",
and the whole reason to reach for the saturating form is to not handle it. The
table now separates the two families by what the caller does with the overflow.
**The third quick-start example demonstrated the runtime solver while the text
called it type-level.** `proof::Certificate::discharge` calls `smt::prove` and
returns `Option`; it is the runtime route. The compile-time route is
`assert_proof!`, which asks for a `proof::Theorem` impl and lets `rustc` refuse.
The example now uses `assert_proof!(And<Truth, Imp<Truth, Truth>>)`, and the
"three ways" table names `proof::Theorem` as the entry point, with a paragraph
that separates the two because they are genuinely easy to confuse -- the module
row for `proof` said "a Curry-Howard proof kernel plus composable `Certificate`s"
without saying which of the two the compiler checks. The compile_fail doctests
already in `proof.rs` are what make `assert_proof!` more than a naming
convention: they assert that `Falsity` and `Truth => Falsity` do not build.
## `gate.sh` needed an environment variable it did not set itself
Running the gates the way `CONTRIBUTING.md` tells a contributor to run them --
`sh scripts/gate.sh`, on a fresh checkout, with nothing exported -- failed 21
tests at gate 2. Every failure was in `tests/mir.rs`, and the message was
`reads must be present`: a frontend outcome, which reads as "the verifier is
broken". It is not. `tests/mir.rs` shells out to the compiler named by
`VERIF_RUSTC`, and the tests that need it are written to skip when it is unset --
but `verify_src` returns `None` when `rustc()` is `None`, and several tests call
`.expect("reads must be present")` on that `None`, so they *panic* instead of
skipping. Whether they skip or panic depends on the assertion each one happens to
make, which is why the count was 21 and not 239.
`gate.sh` did resolve `VERIF_RUSTC`, but in gate 8 -- the MIR frontend gate --
and `tests/mir.rs` is run by gate 2. So the variable was set for the gate that
did not need it and unset for the gate that did. It only ever worked in CI
because the workflow exports it before calling the script (to a nightly, with a
comment explaining that it must be a path and not a toolchain name), which means
the documented local command and the CI command disagreed, and the difference was
invisible until someone ran the documented one. This is the same defect class as
the release workflow above: a step correct about its own output and wrong about
what the next step needs.
The resolution block now sits at the top of the script, before gate 1, and gate 8
just reports what it resolved. The fallback is `rustc` on `PATH` -- a stable
release, which is sufficient because the frontend uses `--emit=mir` and not the
nightly-only `-Zunpretty=mir`. The run below was made with `VERIF_RUSTC` unset to
exercise exactly the fresh-checkout path that was broken, and all 239 `mir` tests
pass.
The same review turned up a false positive in the new link checker: it skipped
fenced code blocks but not inline code spans, so the paragraph you are reading --
which quotes `[Ground rules](CONTRIBUTING.md#missing-heading)` as the example the
checker exists to catch -- failed the check. A link in an inline span renders as
code and is not clickable, so `strip_inline_code` now removes those spans first,
matching backtick runs of equal length so ``a`b`` is one span.
## A second review found two more, one of them in the fix itself
**`strip_inline_code` accepted a mismatched closing run.** The first version
found the closer with `str.find("`" * run)`, which matches the *first* backtick of
a longer run. Markdown closes a code span only on a run of exactly the opening
length, so `` `[broken](#absent)`` `` is not a span at all -- the link is real and
clickable -- but `find` paired the single opener with the first backtick of the
double run, dropped everything between them, and the checker never saw the link.
The bug was in the direction that matters: not a false alarm but a *silent pass*,
and it appeared in the very function added to stop broken links slipping through.
A test with only well-formed backticks cannot see it, which is why the case to
test is the malformed one.
The closer is now found by measuring each candidate run to its end and accepting
it only when the length matches, skipping longer and shorter runs whole. The
property under test is stated as "a link is dropped only when it is inside a real
code span", and the mismatched pairs are the cases that must keep it.
**The quick-start intro promised something the third example cannot give.** It
said each of the three returns "a verdict you can inspect". `assert_proof!` runs
before the program does, so there is no verdict and nothing to inspect -- that is
the whole difference from the two runtime routes, and the paragraph immediately
below now says so. The lesson is narrower than the last one: after changing an
example to be compile-time, the sentence introducing it is still written for the
runtime version, and prose is not type-checked.
## A third review found six, two of them false proofs
The trait-contract work (below) introduced a body route that binds a *declaration's*
contract to an *implementation's* MIR. Reviewing that route and the call route
around it turned up six defects. Two could report a false claim as proved, which is
the direction this crate exists to prevent; the rest were a lost proof, a false
failure, a silent pass, and a false alarm. Each was reproduced with a probe before
anything changed, and each now has a test pinned in both directions.
**An inherited contract bound parameters by *name*, not by position (false proof).**
`Specs::resolve` handed back the declaration's contract, but the executor and the
contract evaluator bound its identifiers to the implementation's own MIR debug
names. An implementation is free to name its parameters differently, so
```rust
trait T { /// ensures: ret == a
fn f(&self, a: u8, b: u8) -> u8; }
impl T for S { fn f(&self, b: u8, a: u8) -> u8 { a } }
```
was reported `Verified`: the contract's `a` resolved to the implementation's `a`,
which is the trait's `b`. The two signatures are the same method, so their
parameters correspond by *position*; `Specs::contract_for_fn` now returns the
contract together with an `ArgRename` built by `align_signature`, and
`arg_vars_named`/`signed_args_named`/`field_env_named` bind under the declaration's
names. `FnContract::slots` keeps every position, **receiver included** -- the call
route's `params` drops the receiver because a call has no argument for it, but the
body route cannot: the receiver is position 0 of every method, and aligning without
it would shift every name by one. A declaration whose signature was not read whole,
or whose slot count disagrees with the body's argument count, is refused rather
than aligned by guess.
**A wrapped return type was read as unsigned (false proof).** The signature reader
took everything between `->` and the end of the line, so `fn ext() ->` followed by
`i8;` produced `Ty::Other("")` -- unsigned. A caller testing `ext() < 0` took the
unsigned branch and a postcondition that does not hold verified. The reader now
requires the return type's terminator on the same line and refuses the whole
signature otherwise, and `CalleeContract::sig_readable` makes the call route refuse
a signature it cannot bind positionally.
**A trait path with a relative root never met its declaration (silent pass).**
`impl crate::T for S` kept the `crate::` prefix, so it never matched `T`'s
module-qualified key: the impl was checked against nothing and the declaration was
reported as having no implementation. `qualify_trait` now resolves `crate::` (the
root), `self::` (the enclosing module) and `super::` (one level up) to the spelling
the declaration is keyed by.
**A bodyless declaration's contract was reported `missing` (false alarm).** An
`extern` item has no MIR by construction and its contract is *assumed* at each call,
which is the modular case rather than a lost proof. Reporting it `missing` made
`is_clean()` false for a file with nothing wrong. `Specs::bodyless` records those
keys so `resolve_targets` can tell them apart; the call is still verified, and an
unsatisfiable assumed postcondition still fails.
**An unreachable call was reported as a divergent callee (false failure).** The
divergence query is `find_model(path && post)`, and an unsatisfiable `path` makes it
`Unsat` for a reason that has nothing to do with the callee: the path is dead.
`try_callee_contract` now checks the path first and drops a dead one.
**A helper call inside a measured loop erased the measure (lost proof).** Entering a
callee cleared the caller's `cut` *and* its `variant_entry`, and only the cut was
restored. The resumed caller was still inside its loop with a cut and no head value,
so the back edge had nothing to compare and the loop was reported incomplete --
"the loop head was never entered" -- though its measure was sufficient. The two now
travel together in `Frame::saved_variant`.
The pattern in four of the six is the same: a value was *available* and the wrong
one was used, or a case was folded into a neighbour that shares its shape. The two
false proofs are the receiver-in-the-slot-list and the empty-return-type cases --
both places where "read what is there" quietly became "assume what is not".
## `assert!` was a dropped path, not a check -- and the shape behind it
The sixth review fixed the trait-contract route. This one came from asking a
different question: *what ordinary Rust does the frontend still refuse?* A probe
of a dozen idioms found the answer was `assert!`, the most common safety guard in
the language.
`assert!(x <= 200)` lowers to a `switchInt` that routes the *failing* case into
```
_3 = core::panicking::panic(const "assertion failed: x <= 200") -> unwind continue;
```
There is no `[return: bbN]` arm, because the call never returns. The parser looked
only for the `[return:` shape, so the terminator came back
`Term::Unknown("missing")`, the block's path was reported unmodelled, and the whole
function was `Incomplete`. Nothing was *wrong* -- but nothing was checked either,
and a verifier that silently skips the guards you wrote is worse than one that
refuses loudly.
**The fix is the sound direction, and it is the same shape as `wp`'s
`DivergentCall`.** A construct that cuts a path off must be *recorded*, because
everything downstream of it is vacuously true -- the lesson this file already
carries three times (`Assume(false)`, an unsatisfiable precondition, a
never-returning call). So the diverging call becomes a **panic obligation**: the
query is `path`, "is this call reachable", discharged by `Unsat`, exactly the
polarity of an `assert` terminator. The `switchInt` that routes into the call
already carries `!guard` in its path, so the query is really about the guard. An
`assert!` under a precondition that implies it is `Verified`; without one it is
`Failed` with the counterexample that fires it (`x = 224` for `x <= 200`), and the
report names the assertion from the message the dump passes (a string literal, or
the pieces of the `core::fmt` chain in edition 2024).
Two details that were not obvious:
* **A user function returning `!` lowers the same way** -- `_3 = die() -> unwind
continue`, no return arm. The model treats it identically, so
`if x == 0 { die(); }` is a failure at `x == 0` and is proved unreachable under
`requires: x != 0`. This is why the obligation kind is `DivergingCall`, not
`Panic`: only some of these are panics, and calling `die` a panic would be a
small lie in the report.
* **The `assert` *terminator* and the `assert!` *macro* are different lowerings.**
The overflow checks rustc emits are `Term::Assert`, which already assumed the
guard on the fall-through. The macro is a `switchInt` plus a diverging call, so
the assumption had to be made by the branch, not by the call -- the guard lives
in the *other* arm's path. `an_assert_guard_is_assumed_by_the_code_after_it`
pins it: without the assumption `x + 1` after `assert!(x <= 200)` reports a
possible overflow.
The tests are a matched pair, because a fix for a dropped path is exactly the kind
that can flip into a blanket failure: one pins the proof, one pins the refutation.
### The oracle's own argument list was the first thing the new cases caught
Adding a `panic!` to the regression corpus made gate 10 fail:
```
panic_guarded:
text : 3 blocks, panics []
typed: 4 blocks, panics []
```
The parser was right. The *oracle* was comparing two different compilations of one
file: `emit_mir` passed `--crate-type=lib --emit=mir` and **no edition**, so rustc's
default applied -- and the default is 2015, not the 2024 the crate itself is on --
while the typed side pinned `--edition 2021`. `panic!("literal")` lowers to a single
diverging call, `core::panicking::panic(const "…")`, under 2015; under 2021 or 2024
it lowers to `Arguments::from_str(…) -> [return: bb2, …]` plus
`std::rt::panic_fmt(…)`, one extra basic block. The oracle's comment claimed its
argument list "mirrors what the text emitter passes" -- it did not, and nothing had
exercised the difference until a `panic!` with a literal entered a corpus the oracle
checks.
This is the failure mode the oracle exists to prevent, one level up: a comparison
between two things that are not the same thing is not evidence, and it is worse
than no comparison because it reports a disagreement that cannot be acted on.
The fix pins the edition to **2024** on *both* sides rather than leaving either to
rustc's default. Pinning only one side is what caused the bug; leaving both
implicit would have made the tool's behaviour depend on which compiler's default it
happened to run under, which is exactly the kind of hidden input this crate refuses
elsewhere. 2024 is the crate's own edition (`Cargo.toml`), it is what the test
suite's `unsafe extern "C"` fixtures already require, and it compiles both corpora
clean on the MSRV (1.85) and on stable (1.99) -- checked, not assumed. The only
difference between the two compilations now is text versus typed IR.
The lesson is the same one this file keeps recording, in a new place: a harness
that *asserts* a property it does not itself establish will eventually assert it
about itself. The oracle's check of the parser was sound; the oracle's own inputs
were not held to the standard it held the parser to.
### What the same probe found and did *not* fix
A `for` loop is still refused, and now says so in the known gaps: `for x in 0..n`
lowers to `IntoIterator::into_iter` and `Iterator::next(&mut range)`. `next` is the
harder half -- it is a trait method that *writes through* its `&mut` argument, so
modelling it needs the `&mut` write-back the crate does not have (a reference
argument is refused for that reason). A `while` loop with `invariant:`/`variant:`
states the same iteration and is strictly stronger: the measure gives total
correctness where an unwound `for` gives a bounded check. The gap is documented
rather than papered over, and the report names the unmodelled call so it is visible
rather than silent.
## Recovering an edition-2024 `panic!` message: `core::fmt` is a two-spelling chain
The diverging-call fix above made `panic!` *checked*. It did not make it
*readable*: the report named the panic from a string literal operand, and edition
2024 has no such operand. `panic!("zero")` under 2024 lowers to
```
_4 = Arguments::<'_>::from_str(const "zero") -> [return: bb2, unwind continue];
_3 = std::rt::panic_fmt(move _4) -> unwind continue;
```
so the message is a *local* the chain built, not an argument. Reading it needs a
small model of `core::fmt`, and the model is where the two toolchains the gate
runs diverge.
**Four spellings, and the gate runs two of them.** The builders are:
| `Arguments::from_str(const "…")` | both | the literal, one piece |
| `Arguments::new_const::<P>(&PIECES)` | 1.85 (MSRV) | a promoted `&[&str; P]`, no arguments |
| `Arguments::new_v1::<P, A>(&PIECES, &ARGS)` | 1.85 (MSRV) | the same promoted array, `A` arguments |
| `Arguments::new::<LEN, A>(const b"…", &ARGS)` | stable (1.99) | one encoded byte template |
The last two are the same source text compiled by two compilers, so a model that
answers only one of them is a model that is green on one toolchain and
`Incomplete` on the other -- which is exactly what the MSRV run reported while
stable was green. Both are answered.
**Three details that are not obvious, and each cost a round trip.**
* **The promoted array is not reachable by walking a body.** The pieces live in a
`const f::promoted[0]: &[&str; 1] = { … }` item printed *outside* any function,
and the call passes `&_4` where `_4 = const f::promoted[0]`. The executor never
walks that item, so the pieces are collected at parse time, next to the other
`const` items, into `MirProgram::promoted_strs` -- the one place in this frontend
where a fact is read from the dump rather than from the function's own body, and
it is read from the *same* dump so the two cannot drift.
* **A whole-place write forgets the destination's parts.** The pieces are recorded
on the local the reference was assigned to, and the obvious place to record them
-- inside `eval_rvalue` -- is wrong: the `set` that follows calls `forget_parts`,
which clears `piece_sets` (it must, or a stale read of an overwritten local would
be a *wrong* message). The record therefore happens in the `Stmt::Assign` arm
*after* `set`, which is the only ordering that survives.
* **The byte template arrives through a local too.** On stable the template is
`_9 = const b"\x04bad \xc0\x00"` and then `new::<7, 1>(move _9, …)`, so it is
kept raw in `tmpl_bytes` and decoded by the consuming call -- the decode needs
the argument count, which only the call has.
**The placeholder count is the argument count, not the piece count.** This is the
one that produced a wrong *message* rather than a missing one.
`panic!("{} tail", x)` prints `["", " tail"]` with **one** argument, so a join that
put a `{}` in every gap would report `{} tail{}` for a message with one
placeholder -- a message that is not the one in the source, which is worse than
naming none. `join_format_pieces(pieces, args)` therefore takes the count from the
generic list (`new_v1::<P, A>` -> `A`, `new::<LEN, A>` -> `A`, `new_const` -> 0)
and appends the surplus placeholders after the last piece. `generic_arg` refuses a
missing or non-numeric item rather than guessing, so a printer change surfaces as
"unmodelled", not as a wrong message.
**The guard is the destination's type, not the callee's name.** `new_const` and
friends are printed *unqualified* (`Arguments::<'_>::new_const::<1>`), so a name
cannot tell `core`'s builder from a local function called `new`; the destination
type `std::fmt::Arguments<'_>` can, and no other call has it. The consumer
(`std::rt::panic_fmt`) *is* qualified, so its guard is on the name. Both
directions of a misjudgement are a refusal: a local `new` is left to its own body,
and an unknown `core::fmt` call stays "unmodelled".
The tests are a matched pair again, and they run under whichever toolchain
`VERIF_RUSTC` names -- so the 1.85 `new_v1`/promoted-array spelling and the stable
`new::<LEN, A>` byte-template spelling are both exercised by the gate's two
toolchains rather than by one machine's luck.
**A name must never be reported as its type arguments.** `panic!("{}", x)` has no
literal piece at all -- there is nothing to recover -- so the report falls back to
the callee's name, and the naive `name.rsplit("::").next()` gave `<u8>` for
`panic_display::<u8>` / `panic_cold_display::<u8>`. That is the mangled path the
message recovery exists to avoid, just reached from the other side. The fallback
now goes through the same generic-stripping helper the `core::fmt` dispatch uses,
so it reads `panic_display`, and `unreachable!()` / `todo!()` -- which *do* pass a
literal, `"internal error: entered unreachable code"` / `"not yet implemented"` --
keep naming the text the programmer wrote. The three are pinned together so a
change aimed at the formatted case cannot quietly regress the plain one.
One more fail-closed turn: the `panic_fmt` consumer used to record an *empty*
message when its argument was not a local it knew, which would print `panic: ` with
nothing after it. It now refuses, so the report names the call it could not model
instead of showing a blank message.
## A toolchain-shaped report, and a gate the edition work broke
Two CI-only failures on the diverging-call branch, both invisible to a green local
gate run, and both the same lesson: the *environment* is part of what a claim is
about, so a gate that names one toolchain has not checked the other.
**The panic message was read from the dump, and a nightly stopped printing it.**
`unreachable!()`, `todo!()`, `unimplemented!()` and a message-less `panic!()` used to
lower to `core::panicking::panic(const "…")` with the text as a literal, and
`panic_message` read that literal. A recent nightly lowers each to a dedicated
`core::panicking::{unreachable,todo,unimplemented,panic}_default_msg()` callee that
takes **no** literal, so the report fell back to the callee's name
(`panic: unreachable_default_msg`) and `a_literal_panic_macro_names_its_message`
failed -- on the nightly CI names, and on nothing else. The fix spells the canonical
text for those four tails, so the message is the same string stable prints. Reading
it from the compiler would make a *report* depend on the compiler version, which is a
claim the toolchain half-decides; the text is the same on both, so it is written down.
An unrecognised name still falls back to the callee, which is the honest answer.
**The edition work broke the comparison gate, and only on a machine with no
`Cargo.toml` above the fixture.** Resolving the edition instead of pinning 2024 is
right -- a verdict under the wrong edition is about a program nobody built -- but the
degenerate fixtures in `examples/comparison_check.rs` were written as loose `.rs`
files in `$TMPDIR`, with no manifest above them and no `VERIF_EDITION`, so the
frontend now refused them ("no Rust edition for /tmp/…"). It passed locally only
because the earlier gate runs had left `VERIF_EDITION` exported in that shell. The
fix gives each scratch fixture its own temp *crate directory* with a `Cargo.toml`
(`edition = "2021"`), which is what a real program has and which exercises the
manifest-resolution path rather than the override. The removal became
`remove_dir_all` on the parent.
Both are pinned by the gate's own two compilers now: `scripts/gate.sh` runs the MIR
suite under the compiler on `PATH` *and* under the MSRV, and CI runs it under a
nightly, so a dump-shape change on any of the three fails in the run that introduces
it. The general rule the pair teaches: a test that names one toolchain checks one
toolchain, and "it passed locally" is a claim about the local compiler, not about
the program.
## Four review findings on the edition and label work
A review of the diverging-call branch raised four items. Two were live defects in
this branch, one was already fixed by an earlier commit in the same branch, and one
was a test/scoreboard mismatch. Each is recorded because the *reason* recurs.
**A package that omits `edition` is Cargo's 2015 default, not an error.**
`resolve_edition` refuses a file with no edition anywhere, which is right for a
*loose* `.rs` -- it has no crate edition to infer. But Cargo assigns edition 2015 to
a `[package]` that does not state one, so the same refusal also rejected a valid
2015 package: verification stopped before `rustc` ran. The two are different
questions, and `edition_from_manifest` now answers them differently: a manifest that
declares a `[package]` with no `edition` key resolves to 2015 (`declares_package` is
the tell), while a loose file and a manifest with no `[package]` (a virtual
workspace) still yield no edition. The refusal is kept exactly where it belongs.
**A label must name the event that happens.** A reachable call to a user function
returning `!` -- `die() -> ! { loop {} }` -- is a reachable *failure*, but the
failure is a non-terminating loop, not a panic. The report said `panic: die`, naming
an event that never occurs. `Divergence::of` already distinguished `exit`/`abort`
from `panic`; an unrecognised `!`-returning callee is now labelled `diverges`. The
general rule: when a report prints a *reason*, the reason has to be the thing that
happened, not the nearest category. This was fixed earlier in the branch (`af12de8`,
"Label a diverging call by its kind"), and the review was against the pre-fix head --
worth checking a finding against the current head before acting on it.
**A scoreboard and a regression floor must count the same thing.** The corpus test
counted `Verified | Failed` as "decided" while `mir_coverage` counts only
`Verified`. A corpus function that flipped from verified to refuted would keep the
test's number and lower the printed one -- the floor and the scoreboard would
disagree about the same run. The test now counts `Verified` only, like the
scoreboard, and asserts *separately* that no function in this corpus of ordinary
Rust is refuted. The rule is the one the crate keeps meeting: a count that folds two
outcomes together cannot tell them apart, and the difference is exactly what the
check exists to see.
**A frontend behaviour change is a README change.** The edition resolution (E2) is
new user-facing behaviour -- a loose file now needs `VERIF_EDITION`, and a package's
edition comes from its manifest -- and the README's "what is read from where" table
did not mention it. The table gained an `edition` row and a paragraph on the
precedence and the loose-file override, which is what `CONTRIBUTING.md` asks for
when behaviour changes.
## A `drop` is a terminator, and the dump does not say which kind it is
C1 modelled `drop(_x)`, the terminator rustc emits for a local whose type has drop
glue. Three findings, and the middle one is the soundness boundary.
**It is a terminator the parser was reading as a call.** `drop(_2) -> [return: bb1,
unwind continue]` prints with the same `-> [return:` shape as a call, so the call
arm claimed it: the line has no ` = ` destination, so `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
any 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. (A `drop(` branch
existed before but was dead: the call arm above it matched first, because the line
contains ` -> [return:`.) The arm has to come *before* the call arm, and
`successors` has to know the terminator has a normal successor (`vec![*target]`), or
the path dies at the `drop` instead of continuing. It is a **refusal** at HEAD, not
a false proof -- confirmed by running the unmodified tree on a `Drop` whose
destructor panics (`incomplete`, "unmodelled terminator") -- so C1 closes a lost
proof, not a soundness hole.
**A glue-free `drop` is a no-op, but rustc never emits one -- so the no-op arm is
defensive, not the common case.** The tempting framing (and the ROADMAP's first
draft) was "a scalar no-op subset, the common case". Measured over `realistic.rs`,
**0 of 6** `drop` terms are glue-free: rustc emits no `drop` at all for an integer,
an array of integers, or a plain struct with no destructor. So the no-op branch
cannot be exercised through the frontend, and a test that claims to exercise it is
vacuous -- the check lives in a unit test on `drop_is_noop` instead. The arm is
kept because the alternative to a no-op is a refusal, and refusing `drop(_2)` for a
glue-free type would lose a proof; it is correctness insurance, not coverage.
**A container and a struct holding a user destructor are the same line.** The
review's suggestion was "a std container is a no-op that changes no scalar state".
That is **unsound**. The MIR probe: `fn g(w: Wrapper)` with `struct Wrapper { v:
Vec<u8> }` and `fn f()` with `struct Outer { i: Inner }` where `Inner: Drop` both
lower to the *same* `drop(_2) -> [return: bb1, unwind continue]`. The dump carries
the dropped local's type, not its drop glue, so it cannot tell a `Vec` from a struct
wrapping a `Vec<PanicOnDrop>`. Treating the container as a no-op would prove a
function panic-free whose destructor panics. So a container is **refused**
(`drop of `std::string::String` is not modelled`), which is a lost proof, never a
false one.
The three cases the executor takes, then: **no drop glue** -> no-op (defensive);
**a user `impl Drop`** -> execute its body through the inliner the method path uses
(`self` is `&mut T`, so the dropped place is the argument and the `by_ref` copy-back
carries the destructor's writes); **anything else** -> refuse. The user-`Drop` path
is what makes the review's exit criterion pass: `destructor_panic_cannot_prove_this`
is refuted with witness `v = 16` (the destructor's own assert fires), and its
guarded twin verifies.
Two smaller traps. The inliner's env-seeding was extracted into `seed_callee_env`
so the `drop` path and the call path share it -- a second copy would be a second
chance to forget one of the seven stores a reference argument carries in. And
`drop_destructor` resolves the impl by its *owner* (the `impl at FILE:L:C` location,
like a method contract), matching the type's bare name: two same-named types in
different modules that both `Drop` are an ambiguity, and the resolver refuses rather
than guessing one (probed: `m::Guard` and `n::Guard` both `Drop` -> `incomplete`).
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 can run without a compiler). The
`rustc_public` oracle agrees (862 of 881 on `realistic.rs`, 0 differ), which is what
confirms the parser reads the terminator's real shape.
## A `for`-loop invariant is over the loop's *carried* state, not the element
The `for i in a..b` desugaring is modelled (`RangeInclusive::new`/`Range::new`,
`into_iter`, `next`), so a `for` loop decides through the existing loop machinery.
Two facts about the loop variable cost time to rediscover, and both are in the MIR:
- **`i` is a scoped `debug` binding, not a `local_names` entry.** rustc prints
`scope 3 { debug i => _9; }` and `_9` is assigned only *inside* the loop body
(`_9 = copy ((_6 as Some).0)` in the `Some` arm of the `next` match). So at the
loop *header* `_9` has no value: an `invariant: s <= i` is refused as
`unknown name i`, and the refusal is *correct*. Resolving the name would read a
variable the header state does not contain -- a wrong value, not a missing one.
A `for`-loop invariant must be written over the state the loop *carries*
(`s <= 5050`), which is exactly what the header havocs and the invariant is
quantified over.
- **`next(&mut range)` mutates the range in place.** The `&mut` is followed with
`pointee` to the range local, so the `start`/`end`/`exhausted` fields `new` wrote
are the ones `next` advances -- and the advance is what makes the loop progress,
so a `variant:` can be proved against it. The inclusive range's `exhausted` flag
is set from `forward_overflowing`, so `for i in 0..=u8::MAX` marks itself
exhausted rather than looping forever; reproducing that boundary exactly is what
keeps a range loop from being a wrong proof.
## An unbounded loop is a *missing contract*, and the message must say so
`DEFAULT_UNWIND` stops a loop with no `invariant:` and no `unwind:` bound, and the
path is reported incomplete. That is honest, but the message read like a frontend
gap. It now names the remedy: "this is a missing loop contract, not an unmodelled
construct: declare `invariant:` or `unwind:` to decide it". The distinction
matters because the two incompletenesses mean opposite things to a reader -- one
says "the tool does not understand this", the other says "you did not tell the
tool what to prove" -- and a `for` loop over a range is now the second, not the
first.
## The three "failures" on this branch were all environmental
Three tests appeared to fail and none was a code defect:
- `counterexamples_really_panic` and `the_min_constant_is_the_top_bit` fail under
`cargo test --release` because the test profile turns overflow checks *off*, so
a body the engine says panics does not. The documented command is
`cargo test --features std` (debug).
- `a_package_that_omits_an_edition_is_verified_as_2015` fails when
`VERIF_EDITION=2024` is exported in the shell -- the env override outranks the
manifest, by design. `env -u VERIF_EDITION cargo test --features std` is green.
This is the same ambient-variable trap the edition gate's comment already
names; a "failure" that survives only in one shell is the variable, not the code.
## The PR #8 review, and what the fixes had in common
Nine findings from an adversarial review on upstream PR #8, all in the MIR
frontend, each reproduced before being fixed:
- **Drop glue is a *path*, not a flag.** A struct whose field has its own `Drop`
ran the outer destructor and stopped, so a panicking field destructor was never
seen and the function was a false `Verified`. The fix is to *refuse* the shape
when a field's glue is unmodelled, not to assume it is fine.
- **A bound counts the thing the caller means.** `unwind: N` counted raw block
entries, so a loop running exactly `N` iterations was rejected (the last entry
evaluates the guard and exits) and a loop-free helper called twice tripped it.
The counter now counts *latch traversals* -- one per iteration -- via a
per-function latch set. The general shape: a budget's unit must match the
quantity the user is reasoning about.
- **A `for` desugaring is not the only thing with a bound.** The same accounting
bug applied to a call, so the fix is in the shared counter, not the loop arm.
- **A quoted TOML key is a key.** `"edition" = "2024"` read as *absent* and the
2015 default applied -- a verification of a different edition from the one the
crate builds under. `workspace = "../ws"` pointing outside the ancestor chain
was not resolved either.
- **A width rule is about the *value*, not the range.** `Rotate` was admitted at
every width up to 64, but `n mod w` is a reduction only for a power-of-two `w`;
a non-power-of-two width would be a wrong value. The rule is now `w` a power of
two, and it was a *false-proof* class, not a refusal.
## The range and layout review round (PR #8 follow-up)
A second pass over the same review found six more items, this time in the range
model and the struct layout the drop-glue check reads. Two were *false proofs*
(a wrong value that decided), the rest lost proofs or wrong verdicts. Each was
reproduced against real `rustc` output before being fixed.
- **R1: a signed inclusive range's overflow flag tested the *unsigned* `MIN`.**
`RangeInclusive::next` marks itself exhausted when `start + 1` overflows, and
the flag was `succ == 0`. That is the unsigned rule; on a signed range `MAX + 1`
wraps to `MIN` (`1 << (w-1)`), not zero, so the flag never fired: `127i8..=127i8`
kept yielding past `127` into `-128`, `-127`, … until the `unwind:` bound. A
*true* contract became a bound failure. The flag is now
`succ == (1 << (w-1))` for a signed range. The tell is the same one the
`MIN`-is-not-zero note records for the contract reader: a boundary test written
as "wrapped to zero" is the unsigned half of a two-sided rule.
- **R4: `next` advanced an empty range.** The advance (`start := start + 1`) was
unguarded, so an empty `255u8..=254u8` had its `start` wrapped to `0` and the
*second* `next` returned `Some(0)` — an element Rust never yields. Rust's
`Iterator::next` leaves the range unchanged on `None`, so the advance is now
guarded by `!empty`. The exclusive twin (`255u8..255u8`) had the same hole.
Both were validated the way this crate validates a value model: a differential
oracle. 23 ranges at the `u8`/`i8` boundaries (every combination of `MIN`, `MAX`
and `0`) were counted against a compiled `rustc` execution, and the model agreed
on all 23. The oracle is what makes the fix evidence rather than a claim.
- **R2/R3: the unwind bound counted one latch, not the loop.** The counter was
keyed by the source block holding the back edge. A loop body that reaches its
header from two latches — an `if` whose arms both loop, or two `continue`s — had
each counted separately, so the *combined* trip count could exceed a declared
`unwind:` while neither latch's own count did: a two-iteration loop verified
under `unwind: 1`. A `switchInt` block also reset the count on every arm it took,
which is exactly where a `while` header (whose guard is a `switchInt`) hid the
bug — a `for` loop's header does not end in a `switchInt`, which is why the
earlier fixture passed. The counter is now keyed by the loop *header* (merging
the latches of one loop), the switch reset is removed, and `unwind: N` means `N`
iterations of the loop however the body reaches the back edge. The general
shape, again: **a budget's unit must match the quantity the caller reasons
about**, and "which block is the latch" is not that quantity — "which loop" is.
- **R5: the struct layout was keyed by the bare name.** `m::Outer` and `n::Outer`
collided in the layout table, so the drop-glue check read whichever was recorded
last. When that one is glue-free, a field with a panicking destructor vanishes
and the function is a **false `Verified`** — the worst direction. Layouts are now
keyed by the module-qualified source path (`m::Outer`), with a bare key
back-inserted at the end *only* when the bare name is unique crate-wide; two
modules sharing a name make the bare lookup miss, so the glue check reports the
shape unmodelled rather than reading the wrong layout. A miss is a refusal, which
is the honest answer when the dump's `drop(_1)` names a type two layouts claim.
- **R6: a unit struct was not a struct.** `struct Guard;` was not read as a struct
at all, so the drop-glue check saw an unknown type and refused the function — a
lost proof for one of the commonest shapes in Rust (a zero-sized marker type with
a `Drop` impl). A unit struct now has a zero-field layout, so its `Drop` body is
the only glue, and a panicking one is a real obligation. The name reader also had
to stop at `;`, or the trailing semicolon rode into the name and the lookup
missed.
- **A test that failed only because of the environment.** The `VERIF_EDITION`
override is process-global and a deliberate *override* (it is what the edition
matrix uses to force a file under another edition), so it wins over the
manifest — which is why `a_package_that_omits_an_edition_is_verified_as_2015`
failed in a shell that had it exported. The test now guards on it exactly as its
sibling unit test already did, so the suite's verdict does not depend on the
caller's environment. The same shape as the "a skipped test still reports `ok`"
note: a test whose result depends on ambient state is not a check.
**Evidence.** `scripts/test-count.sh` **914 passed / 0 failed** (was 909);
`tests/mir.rs` **318 passed / 0 failed** in debug with a nightly `rustc`; the
corpus is unchanged (`realistic.rs` 429 of 797, `everyday.rs` 16 of 21 — no
verdict moved); `cargo clippy --workspace --features std --all-targets` and
`cargo clippy --no-default-features --lib` both clean; zero dependencies and
`no_std` untouched.
## A ledger of false proofs, and the test that keeps it from going stale
The PR review's top trust item (A1) was to *track the false-proof rate*: keep a
`SOUNDNESS.md` listing every false proof with its date, root-cause class and
fixture, and pause feature work on any layer that produced one in the last two
weeks. The data behind it is real -- the review counted eleven false proofs fixed
in the nine days to 2025-11-12, and this session's own log records twenty-one
wrong verdicts in the MIR frontend across 2026-11-12 … 2026-11-16. At that rate a
`verified` is evidence that a check *ran*, not yet that it is trustworthy alone.
`SOUNDNESS.md` is now that ledger. The MIR-frontend table has a row per defect:
the symptom, the class (false proof / false refutation / lost proof / wrong
verdict), the **fixture** that fails if the fix is undone, and the date. A
following section records the engine, vacuity and handle classes from `AGENTS.md`
(a limit that truncates instead of reporting, five instances; vacuity, four; a
proof object with no lifetime, two; the unbounded kernel rule; the printer; the
`Fixed` value bugs) so the ledger covers the whole stack rather than only the
frontend.
The lesson this file keeps teaching is that **a document is a claim, and a claim
needs a check**. A ledger row naming a fixture is exactly the kind of second copy
that goes stale silently: rename `a_radix_literal_is_read_at_its_radix` and the
row still *reads* as evidence while pointing at nothing. So `tests/soundness.rs`
extracts the fixture column from the markdown, pulls every backticked snake_case
identifier out of it, and requires each to be a `fn` declared under `tests/` or
`src/`. It also asserts the four classes are defined (a row in an undefined class
is unclassifiable) and that at least eighteen fixture names were checked, so the
test cannot pass vacuously by finding no rows. Teeth were confirmed the only way
that counts: pointing one row at `a_radix_literal_that_does_not_exist` fails the
test with the fixture named.
Two smaller points. The ledger names the *class* per row on purpose, because the
clusters are the finding -- rows 1–9 of the MIR table are all the contract
reader's value/width model, rows 10–13 are all name resolution, rows 14–17 are all
a write or a path that was dropped -- and a fix that addresses one shape and not
its siblings is the recurring cause. And the exit criterion is a *clock*, not a
count: "four consecutive weeks with no new false proof", which restarts on the
most recent row (2026-11-16). Until it clears, the README says a `verified` means
a check ran, and every verdict carries the obligation it discharged.
`SOUNDNESS.md` and `tests/soundness.rs` are the A1 increment; `ROADMAP.md` marks
A1 done, and the README's layout and link sections name the new file.
## The soundness ledger needed commits and dates, and the test that reads them
The A1 increment added `SOUNDNESS.md` (the false-proof ledger) and a test that the
fixtures it names exist. Reviewing it found four holes, all the same shape: the
ledger *read* as evidence without *being* evidence, and the test could not tell.
**The ledger omitted the historical defects.** The engine and imperative
incidents were grouped as class summaries ("a limit that truncates, five
instances"), and the review's eleven earlier false proofs appeared only as a
count. That leaves those layers out of the two-week pause and makes the four-week
clock unverifiable, because a summary has no date to compute from. The fix is a
second table — rows 28–43, one per instance, with a fixture, a commit and a date —
so "when did the engine last produce a false proof" is a lookup (2026-11-16, the
unwind-bound miscount) rather than a guess. The class summaries survive as
the *clusters* paragraph, which is the finding; the rows are the evidence.
**A follow-up review found the ledger was still over-claiming, and row 22 was the
proof.** The prose said "the review's eleven earlier false proofs are rows 22–35",
but row 22 cited `a_declared_frame_longer_than_the_cap_is_refused` — which tests an
*oversized declared* frame (the havoc-buffer cap), not the *under-declared* frame
the row's symptom names. The matching regression is
`under_declaring_the_frame_is_rejected` (`1b64205`). The wrong fixture came from
the same place the earlier ones did: I read `AGENTS.md`'s prose and picked the
test it *mentioned*, instead of the test that *fails on the unfixed code*. Two
more rows had the same defect (row 36 named a MIR fixture for the wp-layer
`DivergentCall`; the wp test is `a_call_to_a_never_returning_proc_is_not_total`).
Worse, the claim itself was false: the review named **seven** commits
(`08a6065`, `d6a4690`, `dd1ca69`, `b7769c1`, `e4543d0`, `496e416`, `653a340`) and
the ledger's MIR table was missing five of their false proofs entirely. The fix
is to *verify each row's fixture against the commit that introduced it* — `git log
--all -S"fn <fixture>"` and check the cited hash appears — and to add the missing
rows (the MIR table grew to 27, the engine table to 16). The lesson is the one the
review's own finding states: **a row's symptom and its fixture must be the same
defect**, and "the commit introduced the fixture" is not enough — the fixture must
be the one that *fails* when that specific fix is reverted. The mechanical check
in `tests/soundness.rs` now also asserts the two tables' row counts, so a row that
silently vanishes is a failure.
**The MIR row dates were all wrong.** Every row said `2026-11-13` (the date the
ledger was written, not the date of the fix). The real dates came from
`git log --all -S"fn <fixture>"` — and the `--all` matters: the crate was
`discharge` until 2026-10-30 and its directory was `discharge/` until the move to
the repository root (`3797cf2`, 2026-10-27), so a fixture whose commit predates
the move is invisible to `git log -S` on the current path. The oldest MIR row is
2026-10-29, not 2026-11-13; the densest cluster (rows 1–9) is 2026-10-29 …
2026-11-02. Recovering this needed `git fetch --unshallow` — the workspace clone
was shallow, and `git log -S` over a shallow history returns the boundary commit
(`57325da`) for *every* pre-boundary query, which reads as "all fixed on the same
day". That is the trap: a shallow clone makes a history question answer with a
plausible wrong answer, not an error.
**The edition row's fixture was prose.** Row 21 named "the E4 matrix and the 2021
`extern "C"` fixture" — no backticked identifier, so the extractor found nothing
there and the 18-name minimum still passed if either edition test vanished. Both
are now named: `a_2021_only_file_is_verified_under_its_own_edition` and
`every_edition_compiles_the_corpus_to_the_same_verdicts`.
**The test promised a date check it did not make, and accepted helpers.** The
module doc said it pinned that the newest date is not in the future; no test read
a date. And `declared_fns` accepted *any* `fn` of the right name — so removing a
test while a same-named helper survived left the check green. Both are fixed:
`fns_in` distinguishes a `#[test] fn` from a plain `fn` (and a non-test match is a
failure), and `no_ledger_date_is_in_the_future` parses each row's date and
compares it to today's UTC date, computed in-process (a civil-from-days
conversion, so no dependency). A cell may also name its file (`` `tests/call.rs` ``),
which pins the test to that file — a fixture that moved files fails.
Each new guard was checked by breaking it: pointing a fixture at the wrong file
fails with the file named, naming a non-test helper (`report_source_hint`) fails
with "not a `#[test]`", a future date fails with "in the future (today is …)", a
missing commit fails with "exactly one commit", and deleting the engine table
fails the row-count floor.
The general lesson is the one this file keeps finding: **a document is a claim,
and every field of it needs a reader.** The commit column was added to make A1
computable; the test reads it. The date column was added for the clock; the test
reads it. The fixture column was there from the start; the test now reads it as a
*test*, not merely a name. A column nothing reads is the same as no column.
## A method's *membership* and its *value* are two facts, and each has its own trap
The `C6` work keeps finding the same shape in two directions, and both are worth
naming because they are easy to reintroduce.
**Membership: a shape exists on more types than the first spelling suggests.**
`div_euclid`/`rem_euclid` were modelled on the *signed* types only, on the
reasoning that "the unsigned spelling is the plain `/` and `%`" -- which is true
and is *why* they should be modelled, not why they should be refused. On an
unsigned receiver the remainder is never negative, so the Euclidean and
truncating forms coincide: the Euclidean quotient is the plain `udiv` and the
remainder the plain `urem`. The sign is the *whole* difference, so the model
picks the plain unsigned divider for an unsigned receiver and the adjusted signed
one otherwise. The trap is reading "this method is only interesting on the signed
types" as "this method does not exist on the unsigned ones" -- the two are
different claims, and `is_modelled` is where the difference lives.
**Value: a family that expresses overflow as a value can share a name with one
that panics.** The four `pow` families (`wrapping_pow`, `saturating_pow`,
`checked_pow`, `overflowing_pow`) express overflow as a value, so they are
`Intrinsic::Pow(family)`. The plain `iN::pow` **panics** on overflow and has no
family-prefixed spelling to fall back on, so it is its own shape,
`Intrinsic::PowPanic`, producing a reachable-panic obligation rather than a
value. A model that wrapped or clamped it would *hide the panic* -- the one thing
this frontend must never do. The fixtures pin the polarity by *kind* (the failure
must be a `panic` whose message names `pow`, not a postcondition and not some
later divide), so a value-only assertion cannot pass on the wrong model.
Both were pinned the same way the rest of `C6` is: a differential unit test over
the whole `u8`/`i8` domain against Rust's own method, and a corpus true/tripwire
pair whose tripwire is exactly the value a plausible wrong model computes (the
signed adjustment `% + 3`, the wrapped product). The corpus-wide
`no_cannot_prove_entry_is_ever_verified` sweep holds the tripwires too.
## The `?` operator: two calls, two enum stores, and one boundary left refused
`expr?` is modelled, and the desugaring has three steps the model has to agree on
(the dump, `--crate-type=lib`):
```text
_2 = <Result<u8, u8> as Try>::branch(copy _1) -> [return: bb1, unwind continue];
_3 = discriminant(_2);
switchInt(move _3) -> [0: bb3, 1: bb4, otherwise: bb2]; // Continue=0, Break=1
_0 = <Result<u8, u8> as FromResidual<Result<!, u8>>>::from_residual(copy _4) -> …;
```
Two modelled calls (`Intrinsic::TryBranch` / `Intrinsic::FromResidual`), both
answered from the executor's enum stores the way the `Option` methods are:
* **`branch`** writes the `ControlFlow`'s tag (`Continue` iff the receiver is on
its *success* variant: `Ok` = 0, `Some` = 1) and both payloads -- the success
value under `Continue`, the error value under `Break`. The `(_2 as
Continue).0` / `(_2 as Break).0` downcasts then resolve through
`variant_index`'s new `Continue`/`Break` numbering. A locally constructed
`Ok`/`Err`/`None` receiver has a *known* tag, so the branch is decided
statically by `smt::evaluate`.
* **`from_residual`** re-wraps the residual for the *return* enum. The residual's
own tag is not stored: it is fixed by the receiver type (`Err` for a `Result`,
`None` for an `Option`), so storing it would be a constant the caller could
never see differ. The return enum is read from the call's *self type*
(`<Result<u8, u16> as FromResidual<…>>`), which is also where the error's
conversion comes from: `Result<u8, u8>` into a function returning
`Result<u8, u16>` widens the residual through `From`, so the value is
*converted*, not copied. A model that copied it refutes the true `ret.Err == 200`
-- pinned by `result_try_widens_the_error` and its `_cannot_prove_this` twin.
Two things are worth keeping:
* **The residual tag is not the `ControlFlow` tag.** `Break` is `ControlFlow`'s
discriminant `1`; the error's *variant* number in the receiver (`Err` = 1,
`None` = 1) happens to coincide for `Result`/`Option` but is a different fact,
and `from_residual` needs the *return* enum's numbering, not the receiver's. A
cross-error-type `?` (`Result<u8, u8>` -> `Result<u8, u16>`) is the case that
separates them.
* **A nested `?` is refused, not guessed.** `Result<Result<u8, u8>, u8>` has a
`ControlFlow` whose *payload* is itself an enum, and the chain's element is an
aggregate rather than a word -- so `branch` reports "a receiver whose payload is
not modelled" and the function is `incomplete`. That is the honest boundary: the
inner payload has no single bit-vector value, and inventing one would be a wrong
value rather than a missing one.
Nineteen fixtures in `realistic.rs` cover both families, both paths, the three
known-tag receivers, a chained pair (`r?; s?`), a two-branch pair, and the
cross-error-type pair; each has its `_cannot_prove_this` twin, so the corpus-wide
`no_cannot_prove_entry_is_ever_verified` invariant holds them too. The model was
checked for teeth by neutering the `TryBranch` classification: the test then fails
on the first `verified` assertion.
## A modelled call whose result is an enum, not a value
Every modelled `core` method so far produced a *value* -- a word, a `bool`, an
`Option`'s discriminant/payload pair, or the `(value, flag)` tuple of the
`overflowing_*` family -- so the executor could always be handed one term to write
to the destination local. `Ord::cmp` is the first whose result is a **three-variant
enum with no payload**, `core::cmp::Ordering`, and the difference is where the
answer has to be written: the *discriminant* store, not the value store.
Three things make it a distinct shape rather than a `min`/`max` variant:
- **The discriminants are signed.** `Less` is `-1`, `Equal` `0`, `Greater` `1`, read
at the enum's own `i8` discriminant width. A `switchInt` on `discriminant(_)`
compares against rustc's arm constants, and `Less` prints as the eight-bit pattern
`255`. So the tag is built from the *pattern* (`(-1i64 as u64) & 0xff`), because
`smt::word` refuses a value outside the width -- the same "a literal is a claim
about a width" rule that governs the contract reader, here on the executor side.
- **The tag's width is the enum's, not the destination's.** The dump declares an
`Ordering` local as `isize` (`dest_w == 64`), but the discriminant is an `i8`, and
a tag built at 64 bits would not equal the 8-bit arm constants. The width comes
from the enum's discriminants, exactly as for a seeded or constructed enum tag.
- **The value is the sign of `x - y`, built from the comparisons the `PartialOrd`
operators already build.** `ite(slt(x, y), Less, ite(sgt(x, y), Greater, Equal))`
-- no subtraction, so nothing can wrap, and a method call cannot disagree with
`x < y`. Both operands are `&Self`, so the executor follows *both* references to
their referents (the receiver through the existing `pointee` step, the second
through the same one).
The guard is `is_ord_callee`, the same narrow rule `min`/`max`/`clamp` use: the
standard library's `Ord` path and a primitive self type. A foreign trait of the
same name (`m::Ord`, `MyOrd`, `ord_shim::Ord`) is refused by `classify`, and a
crate-root trait that prints bare is answered by the same-dump lookup first -- so
the model is a *fallback*, never an override of a real body. The operand's sign is a
*refusal* when it cannot be read: ordering `i8::MIN` unsigned places it above every
other value, a wrong ordering rather than a weaker proof.
What is *not* modelled, and the reason is worth stating: a *locally constructed*
`Ordering` (`_0 = Greater` in a `cmp` body) resolves through `variant_index`, which
knows `Option`/`Result`/`ControlFlow` but not `Ordering`. So a local trait's `cmp`
body is `incomplete` even though a `core` `Ord::cmp` call decides. That is a
`variant_index` gap -- the same "a standard enum has a fixed numbering no source
declares" problem `Option`/`Result` already solved -- and belongs with the
enum-construction work, not with the `cmp` model. Adding `Ordering` to
`variant_index` without also teaching the *contract* reader its variants would
introduce a name the two sides disagree about, which is the false-proof direction,
so the two must land together.
## A test oracle must not call a method newer than the MSRV floor
The C6 work modelled methods that are *unstable* on the 1.85 floor: `is_multiple_of`
(`unsigned_is_multiple_of`), `cast_signed`/`cast_unsigned` (`integer_sign_cast`) and the
signed `midpoint` (`num_midpoint_signed`). The *model* never calls them -- it is a term
built from primitives -- but the exhaustive differential *oracles* did, and the MSRV gate
(step 13, `cargo +1.85 check --all-targets`) compiles the test code too. So four
`E0658: use of unstable library feature` errors landed in `src/mir/intrinsics.rs`'s
`#[cfg(test)]` module, the `gates` job went red, and the failure was **invisible to a local
`scripts/gate.sh` run** on a container whose toolchain is stable 1.99+ (the features are
stable there).
The fix is to write each oracle as the *definition* the method documents, which is stable at
every toolchain:
- `a.is_multiple_of(b)` → `if b == 0 { a == 0 } else { a % b == 0 }` (`core`'s own
definition of the `b == 0` corner);
- `s.cast_unsigned() as u8` → `s as u8`, and `u.cast_signed() as u8` → `u as i8 as u8`
(a same-width reinterpretation *is* the `as` cast);
- `(x as u8).midpoint(y as u8)` → `((x as u16 + y as u16) / 2) as u8`, and the signed form
→ `((x as i32 + y as i32) / 2) as i8` (the truncating average computed in a wider type).
The two lessons. First, **the oracle is test code the gate compiles**, so an oracle written
against a newer toolchain's convenience method is a gate failure that no local run on a
newer stable reproduces -- the MSRV job is the only thing that sees it, and only when CI runs
it. Second, a replacement oracle must be *checked* against the method it replaces before it
is trusted: the four substitutes were each walked over the whole `u8`/`i8` domain against the
real method on stable 1.100, so the oracle did not silently change what it asserts. The
`is_multiple_of` case is the one worth stating: the naive `a % b == 0` alone would *panic* at
`b == 0`, so the `b == 0` guard is the definition, not a defensive extra.
This is the same class the "gate that skips can hide a test that fails" note describes, in
the other direction: a gate that *runs* on a newer toolchain than it claims to support hides
a build break that the floor sees.
## An MSRV-only lowering difference: the promoted `panic!` constant's name
The `RUSTC_BOOTSTRAP` fix above let the corpus compile on 1.85, but one MSRV failure
remained, and it was not a compile error -- it was a *verdict*: the tripwire
`user_range_into_iter_is_not_the_model_cannot_prove_this` came back `incomplete` with
`call to unmodelled function Arguments::<'_>::new_const::<1>`. The same entry refutes
(`FAILED`) on current stable. Two independent differences between the toolchains caused it,
and each is a general trap.
**1. A `panic!("literal")` lowers through a *promoted* constant on 1.85.** Current stable
prints `_3 = Arguments::<'_>::from_str(const "…")` -- one literal. 1.85 prints
`_4 = const NAME::promoted[0]; _3 = Arguments::<'_>::new_const::<1>(copy _4)`, where the
format pieces live in a `const NAME::promoted[0]: &[&str; 1] = { … }` item printed *outside*
any function. The frontend already collected those items (that is what `promoted_strs` is
for), so this half was a *lookup* problem, not a modelling one.
**2. A promoted constant's *definition* and its *use* are spelled differently on 1.85.**
Inside a trait default body, the definition is
`const a::Custom::into_iter::promoted[0]: …`, but the use is
`_4 = const <Self as range_shim::a::Custom>::into_iter::promoted[0]`. An exact-name lookup
misses, so the pieces are never found and the `new_const` call is unmodelled. Two bugs hid in
the use spelling, and both had to be fixed:
* **`split_once(": ")` cut the *definition* name short** when the name carries an
`<impl at FILE:L:C: L:C>` marker -- the marker's own `: ` is the first one. The split is now
on the *last* `: ` before the type.
* **`t.find(" as ")` misread the *use* as a cast.** The `<Self as Trait>` projection contains
` as `, and the cast arm (which must run before the `const ` arm, for the
`const 3_i32 as u32 (IntToInt)` case) matched the projection's ` as ` and read the whole
operand as a cast of the string `const <Self`. The search is now `find_top_level_as`, which
skips `<…>`/`(…)` nesting, so a projection's ` as ` is invisible and a real cast is still
found.
The reconciliation is `lookup_promoted`: after the exact match, a use whose tail is
`promoted[N]` is matched to a definition with the same tail and an *owner* that is a
`::`-aligned suffix of the use's owner (the `<T as Trait>` projection on the use side, the
qualifier on the definition side). Comparing owners rather than the last segment is what keeps
two sibling traits of the same method (`a::Custom` and `b::Custom`, each with its own
`into_iter`) from answering for one another -- the corpus carries exactly that pair, and a
last-segment match would let one trait's message resolve for the other.
The lesson generalises past this printer change: **a toolchain that lowers the same source to
a different *shape* is not a compile break, it is a coverage break.** The MSRV gate is the only
place that sees it, and it sees it as a *verdict* difference, not an error -- which is why gate
14 runs the frontend's own suite against the floor rather than merely compiling it. The
`#![feature(…)]` header plus `RUSTC_BOOTSTRAP` is what makes the corpus *compile* on 1.85; the
promoted-const reconciliation is what makes its *verdicts* agree across the floor.
## The loop cut must havoc what the loop writes *through*, not what it names
A `for` loop with an `invariant:` verified a false postcondition. The invariant was
`i <= n`-shaped, the body advanced the iterator, and the loop's exit edge was
*pruned as unsatisfiable* before the postcondition was ever checked. The tell is
that the loop obligations themselves were fine -- `LoopInvariantInit` and
`LoopInvariantPreserve` both came back `Valid` -- so the verdict looked healthy
while the function's own postcondition was never reached.
Two things were wrong, and both are the same mistake: **the havoc set named the
locals the loop *syntactically* writes, but the header state depends on the locals
it *effectively* writes.**
- **A write through a reference.** `let p = &mut x; *p += 1` lowers to
`(*_2) = ...`, whose syntactic destination is the reference local `_2`, not `x`.
`loop_writes` collected `_2`; the havoc replaced `_2`, and `x` kept the value it
had at entry. `resolve` does not help here -- it rewrites an *explicit* `*_2`
projection, and the havoc was called with a bare local. `pointee` is the one-level
value step that follows `_2` to `_1`, and the havoc now uses it.
- **A widthless local.** The iterator is a `RangeInclusive<u32>`, a struct, so
`Ty::width()` is `None` and its value lives in the *parts* stores, not in
`locals`. The havoc's `if let Some(w) = ty.width()` therefore skipped it
entirely, and the range's `start`/`end`/`exhausted` fields kept their entry
values. The fix replaces each part with a fresh value (`Env::havoc_parts`): a
word part gets a fresh variable of its own width and sign, so a model that reads
it -- `RangeInclusive::next` reads `start`/`end` -- still resolves, while a part
the store cannot re-randomise is dropped to `Unknown`.
Both are *over*-approximations, which is the safe direction: havocing a local the
loop never writes loses information, never soundness. The consequence is visible
in the probes -- a loop that writes through a reference now refutes a `true`
contract that names the entry-time value, because the header is an arbitrary
state, which is exactly the reading the invariant rule asks for.
The general shape, and the one to carry forward: **an invariant is a claim about
*every* state the header can be reached in, so the havoc set must be closed under
the loop's *effects*, not its syntax.** A reference is an effect on its referent; an
aggregate is an effect on its parts. The rule is the mirror of the `writes` frame
rule for calls -- derive the real frame from what the code *does*, and the
syntactic destination is only the first approximation of it.
The `tri_invariant` fixture had been passing *because of* the bug: its invariant
was `s <= 5050` over a body doing `s += i`, which is **not inductive** (from
`s == 5050` and `i == 100` the sum is `5150`). It verified only because the exit
edge was pruned. The fixture now uses an inductive invariant (`s = i.min(5050)`)
and a `tri_invariant_cannot_prove_this` tripwire is asserted to be refuted -- the
standing rule that a new shape is not "supported" until a tripwire fails.
### The havoc must size a local the way it was seeded, not by its declared type
The same havoc had a third miss, one level down: it read `ty.width()` on the local's
*declared* type. For a scalar local that is the seeded width, but for a **reference**
it is not -- `Ty::Ref(inner)` has `width() == None`, and the frontend models a
reference *as its referent*, so a `&mut u8` argument's value is seeded at the
referent's width (8) and lives in `locals`. Reading `width()` on the `Ty::Ref`
returned `None`, sent the local to the aggregate branch, and left the referent at
the value it held at entry. The exit guard then folded, the exit edge was pruned,
and a false postcondition was `Verified`:
```rust
/// requires: x == 0
/// invariant: x == i && i <= 3
/// ensures: ret == 0 // false: the loop increments `*x` three times
pub fn w_false(x: &mut u8) -> u8 {
let mut i = 0u8;
while i < 3 { *x += 1; i += 1; }
*x // returns 3
}
```
The fix sizes the havoc by `ty.referent()` -- the same one-level collapse
`Ty::referent` already performs for seeding -- so a written-through reference
argument is havoced like the scalar it holds. A `&mut u8` is the commonest shape,
and a `&mut u8` argument written in a loop is exactly the shape an induction over
a reference-carrying function needs.
The general rule this completes: **havoc a local at the width and sign it was
*seeded* at, which for a reference is its referent's.** `width()` answers "is this
a bit-vector type", not "how wide is the value this local holds", and the two differ
for a reference. It is the same distinction the seeding loop already makes
(`decl.referent()`), so the two now agree by construction rather than by the
havoc happening to be called on scalars only.
### The havoc must follow a call's write-through, not only its destination
The same set had a fourth miss, and this one is the frame rule the crate already
states for calls: **a call writes through its reference arguments.** `loop_writes`
collected a `Term::Call`'s *destination* local -- the fix for a counter advanced by
`i = i.wrapping_add(1)` -- but a call like `bump(x)` writes `x` (the caller local),
and its *destination* is `bump`'s return local, a different local entirely. So the
write-through was invisible:
```rust
/// requires: x == 0
/// invariant: x == i && i <= 3
/// ensures: ret == 0 // false: `bump` runs three times
pub fn call_in_loop_false(x: &mut u8) -> u8 {
let mut i = 0u8;
while i < 3 { bump_once(x); i += 1; } // bump_once(c: &mut u8) { *c += 1; *c }
*x // returns 3
}
```
`x` kept its entry value, the exit guard folded, and the false postcondition was
`Verified`. The fix folds the callee's own write set back onto the arguments the
call passed: `loop_writes` now takes `prog`, resolves each callee through
`resolve_callee` (the inliner's rule, so a `core` intrinsic and an ambiguous tail
both contribute nothing), and for every local the callee writes that is one of its
`arg_locals`, marks the caller local the corresponding argument names. Recursion is
bounded by the same `visited` set that bounds the block walk.
This is the loop-havoc twin of the call-frame rule (`writes` in `wp.rs`): a call's
frame is derived from what the callee *does*, mapped through the actuals, not from
the call's syntax. The syntactic destination of a call is only the first
approximation of its effect, exactly as the syntactic destination of `*p = v` is.
Both misses came from reading the syntax; the fix is to read the effect, which is
the direction the frame rule already documents.
### A promoted constant's projected use must name its own method
A promoted constant's *definition* is keyed by its full path
(`Custom::aaa::promoted[0]`), but a trait default's *use* is spelled with the
`<Self as Trait>` projection (`<Self as Custom>::zzz::promoted[0]`), which the exact
lookup misses. The fallback reconciled the two by owner and promotion index -- and
discarded the method segment. Two defaults on one trait each own a `promoted[0]`, so
`lookup_promoted` returned whichever the map iterated first, and the report named a
panic message the caller never reached (`"from aaa"` for a call into `zzz`).
The method segment is the missing key: the use's qualifier ends in the method
(`zzz`), the definition's owner is its qualifier minus that segment, and both must
match. A definition that still has no unique method match (two impls of the same
method on one trait) is *refused* rather than answered with one of them, because
either could be the one the use names. This is the same "refuse an ambiguous match,
do not pick one" rule the callee resolver follows, applied to the promoted table.
The shape only appears on the MSRV (1.85), which promotes a `panic!` message to a
constant and prints the use with the projection; current stable inlines it, so the
bug was invisible on the toolchain the crate is developed against -- the same
"toolchain-shaped" class the CTFE brace-block finding named.
### Interprocedural write-set discovery needs its own cycle guard
Following a resolved callee to find what it writes *through a reference* is a walk
over the call graph, and the block-visit set that bounds the walk within one
function cannot bound a cycle *between* invocations. A loop calling a
self-recursive function (`while i < 3 { s = count_down(n); i += 1 }`) therefore
followed `count_down`'s self-call forever and overflowed the stack -- a crash, not
a refusal, and one that reaches a function with *no* reference argument, because
the recursion happens before the argument filter.
The walk now carries the set of functions on the call stack (`visiting`) alongside
the per-function block set. On a cycle it does not skip the callee -- that would
drop reference writes propagated around the cycle, which is the unsound direction
-- but includes the call's *reference arguments* directly: a callee can only affect
caller storage through a reference, so those are exactly the caller locals a cycle
could reach. A recursive callee with no reference contributes nothing and the walk
terminates; one with a reference has it havoced. This is the same shape as the
inliner's `by_value_indexed`/`by_ref` split: a reference shares storage across the
boundary, a by-value argument does not.
The general rule, alongside the earlier "a bound on one resource is not a bound on
the others": a guard that stops a *syntactic* cycle (a block revisiting itself) is
not a guard against a *semantic* one (a function calling itself). Each recursion
over a structure the program can make cyclic needs the cycle set threaded through
it, and the fix is to decide what the cycle contributes rather than to cut it.
## A `Vec`'s length is a model of its own, and it must not be invented
The review's C11 exit criterion was one line: "`make` verified". `make` is
`Vec::new(); v.push(n); v.len()`, and every call was "unmodelled function
`Vec::<u8>::new`", so the whole file lost three functions to the container. The
length half is now modelled (`Env::vec_len`, a per-local length the executor
tracks; `Vec::{new, push, len}`).
Four things are worth keeping, because each is a way the model could have been
wrong rather than incomplete:
- **A `Vec`'s fields are not in the dump.** rustc prints the local as
`std::vec::Vec<u8>` and never its pointer/length/capacity, so the model holds
the *length* and nothing else. That is enough for `make`, and it is stated
rather than implied: an element read stays unmodelled.
- **`push` is `+ 1` at `usize`, which is exact.** A `Vec` cannot hold `2^64`
elements, so `len + 1` never wraps; saturating would be a weaker claim for no
reason.
- **The receiver is a reference, so the length lives on the referent.** `push`/`len`
take `&mut self`/`&self`; `pointee` follows one reference to the storage the
caller owns -- the same local `new` wrote. A receiver whose length the run never
set (a `Vec` *argument*, or one built by an unmodelled call) is a **refusal**,
never an invented number: `v.len()` on an argument is `incomplete`, not a proof
of some arbitrary length.
- **The length crosses a call boundary.** The `&mut Vec<u8>` carry-in lets a
helper read the caller's length, and the write-back lets `push(&mut v)` reach the
caller. Without both, `push_helper` refutes a true contract; the false twin pins
that the write is *seen* rather than the model returning a constant.
`drop` of a `Vec<T>` is a no-op exactly when `T` is glue-free (`Vec<u8>` yes,
`Vec<String>` no), which is the same rule the aggregate cases already follow. The
teeth are a mutation: making `push` a no-op (keeping the length) turns
`make_ok`/`two_ok` red and leaves the false twins refuted, so the test observes the
length the `push` produces, not merely that the function decides.
Two collision guards matter. A user type spelled `Vec` in a local module
(`m::Vec`) is not the standard one: `classify` refuses a path that is neither
`vec::Vec` nor a bare `Vec::` head, and the same-dump lookup answers a local body
first regardless. And `Vec::<u8>::len` is **not** read as a slice length -- the
slice path is matched on `core::slice::<impl [T]>`, so the two lengths (a slice's
symbolic input, a `Vec`'s tracked model) cannot be confused.
## A qualified type name must not resolve to a bare layout
`struct_lookup` answered *every* miss by falling back to the bare tail of the
name. The fallback exists because rustc prints a type by its shortest
crate-unique path, so a bare key is the right answer to a *bare* query. Applied
to a **qualified** query it is the wrong answer, and the wrongness is a false
proof rather than a lost one.
The measurement. A crate-root `pub struct Outer { lo, hi }` and a one-line
`pub mod m { pub struct Outer { hi, lo } }` -- the module's struct is *inline*,
so the line-oriented scanner never sees it and no `m::Outer` layout is recorded.
The dump spells the argument `&m::Outer` (qualified, because the bare name is
ambiguous), the bare key exists from the crate-root struct, and both field
projections resolved to *it*:
```rust
/// requires: o.hi == 5
/// ensures: ret == 5
pub fn wrong_field(o: &m::Outer) -> u8 { o.lo }
```
`verified`. The mirror (`o.lo == 5` / `o.hi`) verified too, which is the tell
that the two fields had collapsed to one variable. Rustc's own execution returns
`7` for `{ hi: 5, lo: 7 }`, so the contract is false and the tool proved it.
The fix is one guard: a name containing `::` (after generics are stripped) does
not fall back to the bare key. A qualified spelling is rustc's statement that the
name could *not* be shortened, so at least two types share the tail and the bare
key is necessarily another type's layout. A miss here is a refusal -- the caller
reports an unreadable contract -- which is the honest direction.
The shape is the mirror of the `Vec`/`str`/`Option` shadowing rules recorded
above, and it generalises the same way: **a lookup that is sound for one spelling
of a name is not automatically sound for another.** The bare fallback was
justified by "the bare key is only inserted when the bare name is unique", which
is true and is exactly why it is unsound for a *qualified* query -- a unique bare
key means the query should have been bare, so a qualified query that misses is
naming a type the scanner did not read.
Corpus coverage is unchanged (`realistic.rs` 630/1148, `everyday.rs` 18/21,
`actuator.rs` 18/33 before and after), so the refusal costs no decided verdict.
The lost proof it does leave -- a struct declared inline in a one-line module is
still unreadable -- is the safe direction and stays a documented boundary: closing
it needs the module scope *within* a line, which `line_scopes` deliberately does
not provide (it records the scope before the line's items open, so keying an
inline struct with it would re-open the false proof this section describes).
## A primitive name a user type can shadow: bind the primitive only when nothing declares it
Adding `str::len`/`is_empty` bound a `&str` argument's symbolic length in the
contract binder. That is right for the *primitive* `str`, and wrong for a user
type that shadows the name: Rust lets a crate write `pub struct str { .. }`, and
rustc prints a crate-root type by its **bare** name, so `&str` in the dump means
either one. The binder's early `if name == "str"` therefore bound a field-less
type over the user's struct, and a contract naming `s.value` came back `skipped:
unknown field`. An AI review caught it as a regression in the commit that added
the feature.
The fix is precedence, not a special case: the primitive is meant only when no
declared layout names `str`, so the guard is
`name == "str" && struct_lookup(structs, name).is_none()`. A user `str` then falls
through to the struct branch and its fields bind.
This is the same rule the enum path already follows -- a *declared* layout wins
over the reader's built-in knowledge of a standard type (`Shadow { Some, None }`
is not `Option`). The general shape: when the reader recognises a name by
spelling (a primitive, a standard container, a prelude enum), and a user can
write that same spelling, the *declaration* is consulted first. A spelling-based
test alone is a false match, and here the false match was a silent drop of a
field binding.
Pinned by `a_user_type_named_str_is_not_the_primitive_str`, which asserts **both**
directions (the user field resolves and refutes a fixed value; the primitive
length is still a symbolic input), so a fix that simply refused every `str`
argument fails it. Teeth checked by reverting the guard.
The `String` half is deliberate and stays a refusal: a `String`'s own type is
`alloc::string::String`, so a `s.len()` on one goes through a deref to a `&str`
local the binder never saw. That is an honest gap, not the shadowing bug.
## A stale review is not evidence the code is fixed -- reproduce every finding
A review round listed six code findings. Five named bugs the previous `Vec` round
had already fixed (`vec_elem_ty` full-path identity, `havoc_parts` clearing
`vec_len`, `collect_writes` cycle awareness, `copy_parts` moving `vec_len`,
`lookup_promoted`'s method key). Only one was live, and it was a regression the
commit under review had just introduced.
The lesson is the order of work: reproduce *each* finding against the reviewer's
own example at HEAD before acting, and record the command's output. Acting on the
five already-fixed ones would have re-done finished work; dismissing the batch as
"stale" would have shipped the live regression. The two mistakes look identical
from the outside and only the reproduction tells them apart. The reply to the
review says which five were already fixed and *how* it was checked, rather than
just "addressed".
A related trap on the other side: a finding that names a *test* can be stale too.
`walk`'s contract, `bump_n`'s contract, the left-shift pair and the unnamed-witness
assertion were all already corrected -- re-reading each one is what distinguished
"already fixed" from "still open", and two of them were fixed by an *earlier*
round that the review had not seen.
A *later* round made the same point at larger scale: twelve findings (six severe,
six non-severe), every one naming a symbol that no longer exists at HEAD --
`slice_elem_cond`, the flat element-identity representation the `ElemId` commit
(617a958) had already replaced. The tell was mechanical: `grep slice_elem_cond`
returned nothing, so the findings were written against a revision before that
commit. Each was still reproduced against the reviewer's own shape at HEAD
(`a.first().or(b.first()).or(c.first())`, a user `m::Vec`, a `Vec` moved by
`let w = v`, `unwrap_or_default` on `Result<_, Boom>`, a mutually recursive pair
called from a loop), and all twelve came back already fixed -- the positives
`verified`, the false twins `Failed` with a witness. Naming a symbol that does not
exist is the cheapest staleness signal there is; grep for it first.
The one *live* blocker in that round was not in the findings at all: clippy 1.100
promotes `too_many_arguments` to an error under `-D warnings`, so gate 1 was red
on the rollover toolchain over `fold_const_arith` (eight scalars). It reproduces on
the unmodified tree (`git stash` and re-run), which is what makes it a rollover and
not a regression. A review of *findings* is not a review of the *gate*; run the gate
on the toolchain the reviewer names, or the build stays red behind twelve green
"already fixed" replies.
## An identity is not a path, and a test that skips itself still reports `ok`
`canonical_compiler` answers "which *build* is this", as `commit-hash/host` from
`rustc -vV`, because a path cannot: `rustc` on `PATH` is the rustup *shim*, a
different file from the toolchain binary `rustup which` prints, so the two
spellings of one compiler never compare equal by path. That fix is correct, and
the three tests written beside it were wrong in two ways -- both of which are the
recurring "a test that cannot fail" class, in a new place.
**An identity was used as an executable.** `extern_compiles` *spawns* the
compiler; `Command::new("0ef1bc386…/x86_64-unknown-linux-gnu")` fails to start,
`extern_compiles` returns `false` on a failed spawn, and the cross-toolchain test
read that `false` as "the other compiler rejected the rlib" -- the assertion it
exists for -- while the *positive* half (`producer` accepts its own rlib) failed
to build and the test returned early. Net: `ok`, having tested nothing. The fix
is to keep the two apart at the source: `have()`/`active()` return `(path,
identity)` together, the *path* is what gets spawned and the *identity* is only
ever compared. The early return also became a `panic!` when the producing
compiler cannot build a trivial rlib -- a compiler that cannot compile is a
broken environment, not "nothing to test".
**The identity test assumed which toolchain was active.** It compared a bare
`rustc` against `rustup which --toolchain stable`, so under a nightly override
(or any `RUSTUP_TOOLCHAIN`) the bare name correctly resolved to nightly and the
equality assertion failed *while the identification was right*. The absolute path
must come from `rustup which rustc` with **no** `--toolchain`, which resolves the
active toolchain -- the same one a bare `rustc` dispatches to.
Both were confirmed the only way that counts: reintroduce each defect and watch
the test go red. Using the identity as the executable now panics with "the
producing compiler (rustc, identity …) must be able to build a trivial rlib";
running under `RUSTUP_TOOLCHAIN=nightly` with the `--toolchain stable` form fails
with the two identities printed, and passes with `active()`.
Two general rules, both already in this file in other words and worth repeating
because they recur: **an identity, a handle, and a path are three different
things**, and a function that takes "a compiler" has to say which it wants -- a
spawn needs a path, a comparison needs an identity, and passing one where the
other belongs fails in the *silent* direction (a failed spawn reads as `false`).
And **a test whose body can return early must prove it ran**: a skip and a pass
both print `ok`, so a skipped test is the same "green that checked nothing" as the
gate that did not run. Where the environment is genuinely absent, say so with
`eprintln!` and assert on what *was* reachable; where it is present but broken,
panic rather than return.