Skip to main content

verif/
lib.rs

1#![cfg_attr(not(feature = "std"), no_std)]
2#![forbid(unsafe_op_in_unsafe_fn)]
3#![deny(missing_docs)]
4//! # verif — in-code formal verification for Rust
5//!
6//! SPARK/Ada earns its reputation in safety-critical work because the proof
7//! tooling is *part of the language and part of the artifact*: `gnatprove` sits
8//! next to `gnatmake`, and the contracts (`Pre`, `Post`, `Type_Invariant`,
9//! `Assert`) are first-class syntax the compiler knows about. Rust ships with a
10//! spectacular type system and no such prover.
11//!
12//! This crate is an experiment in closing that gap from inside Rust itself. It
13//! embeds a **bit-blasting decision procedure** — formulas are lowered to
14//! Reduced Ordered Binary Decision Diagrams, which are a canonical form, so
15//! equivalence is node identity — and builds the modules below on top of it.
16//!
17//! ```
18//! use verif::prelude::*;
19//!
20//! // ∀ x:u8. (x & 0x0f) < 16  — decided by the embedded engine
21//! let proved = verif::smt::with_fresh(|| {
22//!     let x = var(8);
23//!     (x & 0x0fu32).lt_val(16).prove().is_proved()
24//! });
25//! assert!(proved);
26//! ```
27//!
28//! # The three ways, in code
29//!
30//! The same obligation, discharged three ways. The first two return a verdict you
31//! can inspect at run time; the third is settled before the program runs, so it has
32//! no verdict to return. None of them ever reports `Valid` for something false.
33//!
34//! ```
35//! use verif::prelude::*;
36//!
37//! // 1. Symbolic: for every input, via BDDs. Fast, but can say Unknown.
38//! let symbolic = verif::smt::with_fresh(|| {
39//!     let x = var(8);
40//!     smt::prove_implies(x.le_val(200), x.le_val(255)).is_proved()
41//! });
42//! assert!(symbolic);
43//!
44//! // 2. Exhaustive: every input of a small domain, no size wall, never Unknown.
45//! assert!(for_all_u8(|a| a <= 255));
46//!
47//! // 3. Type-level: the kernel builds a proof term and `rustc` checks it, so a
48//! //    falsehood fails to compile rather than returning a verdict.
49//! use verif::proof::{And, Equals, Imp, Truth};
50//! assert_proof!(And<Truth, Imp<Truth, Truth>>);
51//! assert_proof!(Equals<u8, u8>);
52//! ```
53//!
54//! A contract you can state in the source and check at run time, with the same
55//! predicate usable symbolically:
56//!
57//! ```
58//! use verif::prelude::*;
59//!
60//! // Pre/post as a symbolic obligation: `requires x <= 200` and
61//! // `ensures x <= 255`; the engine proves the implication.
62//! let v = verif::smt::with_fresh(|| {
63//!     let x = var(8);
64//!     let contract = ensures(requires(x.le_val(200)), x.le_val(255));
65//!     contract.discharge()
66//! });
67//! assert!(v.is_proved());
68//! ```
69//!
70//! # What you get, in one line each
71//!
72//! `no_std` by default, zero external dependencies, a fixed-size heap-free arena,
73//! and `#![forbid(unsafe_op_in_unsafe_fn)]`. The engine links `core` and nothing
74//! else, which is what a bare-metal safety build wants; the host-side tools (the
75//! MIR frontend, the file-backed helpers) are behind the `std` feature.
76//!
77//! # The three ways this crate proves something
78//!
79//! ```text
80//! 1. symbolic      smt::prove(p)              -- for all inputs, via BDDs
81//! 2. exhaustive    exhaustive::for_all_u16(p) -- every input, no size wall
82//! 3. type-level    proof::Theorem             -- the compiler checks the proof term
83//! ```
84//!
85//! They are deliberately different tools, and each has a different honesty
86//! profile. The symbolic engine is the fast, general one but can return
87//! [`smt::Verdict::Unknown`] at the BDD size wall. Enumeration is a complete
88//! proof that never says "unknown", but only for small domains. The kernel makes
89//! *composition* of proofs machine-checked by `rustc`. A serious safety argument
90//! uses all three, and says which one it used.
91//!
92//! | # | Mechanism | Entry point | Complete? | Can it lie? |
93//! |---|---|---|---|---|
94//! | 1 | Symbolic — BDD, then CDCL SAT fallback | [`smt::prove`], [`sym`] | no (scaling wall) | no — it returns `Unknown` |
95//! | 2 | Exhaustive — every input of a real domain | [`exhaustive::for_all_u8`], [`exhaustive::for_all_u16`] | yes, small domains | no |
96//! | 3 | Type-level — Curry–Howard kernel | [`proof::Theorem`], `assert_proof!` | yes, for composition | no — it will not compile |
97//!
98//! The third row is the one to read carefully, because two things in this crate
99//! are easy to confuse. `assert_proof!` is a *compile-time* obligation: it asks
100//! for a [`proof::Theorem`] impl and `rustc` refuses if the proof term cannot be
101//! built, which is why a falsehood is a build error and not a bad verdict.
102//! [`proof::Certificate::discharge`] is the *runtime* solver route: it takes a
103//! predicate to the `smt` engine and returns `Option`, so it can answer `None` at
104//! run time. Both are useful; only the first is checked before the program runs.
105//!
106//! # Module map
107//!
108//! ## The engine
109//!
110//! | Module | What it is |
111//! |---|---|
112//! | [`smt`] | The decision procedure: bit-vector terms, ROBDDs, [`smt::Verdict`], counterexamples, the `no_std` arena. |
113//! | [`bitblast`] | The bit-level term graph → CNF lowering, used by the SAT fallback. |
114//! | [`sat`] | The CDCL SAT solver used as the fallback past the BDD wall. |
115//!
116//! ## Specifications and proofs
117//!
118//! | Module | What it is |
119//! |---|---|
120//! | [`sym`] | A symbolic DSL: operator overloading so a specification reads like code, `(x + y).eq(y + x).prove()`. |
121//! | [`logic`] | Checked and saturating arithmetic plus a Q16.16 [`logic::Fixed`] type, each with proofs attached. |
122//! | [`mod@proof`] | The Curry–Howard kernel: [`proof::Theorem`] propositions whose proof terms `rustc` checks at compile time (so `Truth => Falsity` does not build), plus runtime [`proof::Certificate`]s for an engine-produced proof. |
123//! | [`mod@contract`] | Runtime `requires`/`ensures`/`assert` over concrete values, with structured errors. |
124//! | [`vc`] | [`vc::requires`]/[`vc::ensures`]/[`vc::invariant`], [`vc::verify_body`], and the [`vc::Verified`] witness. |
125//! | [`wp`] | Weakest-precondition generation for statements, loops and calls, with a per-rule [`wp::Report`]. |
126//! | [`mem`] | A bounded symbolic array with a proved [`mem::Mem::read`] / [`mem::Mem::store_wp`] frame condition. |
127//! | [`quant`] | Bounded quantifiers, expanded into finite conjunctions and disjunctions. |
128//!
129//! ## Complete by enumeration
130//!
131//! | Module | What it is |
132//! |---|---|
133//! | [`exhaustive`] | Complete proofs by enumeration over `u8`/`u16` domains: no size wall, no `Unknown`. |
134//!
135//! ## The proved arithmetic, and its symbolic oracle
136//!
137//! | Module | What it is |
138//! |---|---|
139//! | [`arith`] | The sibling crate `verif-arithmetic`, re-exported: total integer operations and a refinement-typed [`arith::Bounded`], each with an enumeration proof carried in the artifact. `no_std`, `#![forbid(unsafe_code)]` and dependency-free on its own. |
140//! | [`primitives`] | The symbolic *oracle* for those same operations: the obligations restated at widths enumeration cannot reach, cross-checked against it by `tests/oracle.rs`. |
141//!
142//! ## Interop and ergonomics
143//!
144//! | Module | What it is |
145//! |---|---|
146//! | [`smtscript`] | SMT-LIB2 export, so an independent solver can decide the same condition. |
147//! | [`macros`] | `spec!` (in-code contracts), `verify!`, `verify_implies!`, `contract!`, `proof!`, `assert_proof!`, `check!`, `verify_exhaustive!`. |
148//!
149//! ## Verifying real Rust (`std` only)
150//!
151//! | Module | What it is |
152//! |---|---|
153//! | `mir` | Verify **real Rust**: read `rustc`'s own MIR, symbolically execute it, and discharge rustc's overflow, underflow and division-by-zero asserts plus contracts written as an in-code `spec! { … }` block. |
154//!
155//! The `mir` frontend is the only module that needs a compiler at run time, so it
156//! is behind the `std` feature. Its page appears in this documentation only when
157//! that feature is enabled (the published docs on docs.rs are built with
158//! `--all-features`, so it is there).
159//!
160//! # Feature flags
161//!
162//! | Feature | Default | Effect |
163//! |---|---|---|
164//! | *(none)* | yes | `no_std`, zero dependencies, `core` only. The engine, the DSL, the kernel, the contracts, `wp`, `mem`, `quant`, `exhaustive`. |
165//! | `std` | no | Adds the `mir` frontend, the thread-local arena used by the host-side test suite, and the file-backed helpers. |
166//!
167//! There is no `alloc` feature and no allocator anywhere: every structure is
168//! fixed-size, and the arena has a documented capacity rather than growing.
169//!
170//! # What this is not
171//!
172//! It is not a replacement for SPARK's proof tooling, and it does not make
173//! arbitrary Rust correct. It reasons about **bit-vectors and boolean
174//! predicates**, plus one bounded *array* ([`mem`], addressed by an integer). It
175//! does not model pointers, address arithmetic across objects, aliasing or
176//! concurrency: you cannot state "this pointer is valid" or "these two threads do
177//! not race". The BDD engine is not a CDCL SAT solver: equalities between two
178//! wide multipliers can hit the size wall, in which case the honest answer is
179//! [`smt::Verdict::Unknown`].
180//!
181//! Read each module's page — and the crate `README`, which records the claim each
182//! feature makes and the check that backs it — before trusting a green test.
183//!
184//! # Where to read more
185//!
186//! - The `README` is the long-form document: one section per claim, with the
187//!   gate that holds it.
188//! - `CONTRIBUTING.md` covers the ground rules and the gate script.
189//! - `SECURITY.md` covers reporting a **soundness bug** — a false `Valid` —
190//!   which is the vulnerability class that matters in a verifier.
191//! - `AGENTS.md` is the engineering log: why each decision was made, including
192//!   the ones that were reversed.
193
194pub mod bitblast;
195pub mod contract;
196pub mod exhaustive;
197pub mod logic;
198pub mod macros;
199pub mod mem;
200#[cfg(feature = "std")]
201pub mod mir;
202pub mod primitives;
203pub mod proof;
204pub mod quant;
205pub mod sat;
206pub mod smt;
207pub mod smtscript;
208pub mod sym;
209pub mod vc;
210pub mod wp;
211
212// The proved runtime primitives live in a sibling crate so that the arithmetic a
213// safety build ships is `no_std`, `#![forbid(unsafe_code)]` and dependency-free
214// on its own, with its proofs carried inside it. Re-exported as `arith` so the
215// module reads `verif::arith` rather than the `verif::verif_arithmetic` stutter,
216// and so the caller never has to name the workspace layout.
217pub use verif_arithmetic as arith;
218
219/// The names you almost always want: the prover entry points, the symbolic
220/// constructors, and the verification macros.
221pub mod prelude {
222    pub use crate::contract::{Contract, ContractError};
223    pub use crate::arith::prove::{self as arithmetic_proofs, Verdict as ProofVerdict};
224    pub use crate::exhaustive::{
225        find_violation_u8, find_violation_u8_2, for_all_u8, for_all_u8_2, for_all_u16,
226    };
227    pub use crate::logic::Fixed;
228    pub use crate::primitives::{safe_add, safe_div, safe_mul, safe_rem, safe_sub, Bounded};
229    pub use crate::proof::{Certificate, Implication};
230    pub use crate::smt::{
231        self, all_ones, and, bits, eq, eq_const, find_model, iff, implies, index, ite, mul, not, or, prove,
232        prove_equiv, prove_implies, ule, ule_const, ult, ult_const, var, var_named, word, Cex, Pred,
233        Var, Verdict,
234    };
235    pub use crate::vc::{ensures, invariant, requires, verify_body, verify_contract, Verified};
236    pub use crate::mem::{declare as declare_memory, Mem};
237    pub use crate::smtscript::Query;
238    pub use crate::wp::{
239        verify as verify_program, verify_modular, verify_proc, Correctness, Proc, Rule, Stmt,
240    };
241
242    // Macros live at the crate root; re-export them so `use prelude::*` is enough.
243    pub use crate::{
244        assert_proof, check, contract, proof, spec, verify, verify_exhaustive, verify_implies,
245    };
246}