Contract-based design and static verification for Rust
trust2-contract lets you attach preconditions, postconditions, type invariants, assertions, and assumptions to Rust code.
Contracts are verified statically. In an ordinary build, contract annotations are simply removed.
Research workspace: Open the website (repository: OpenSourceVerif/trust2-contract-sites).
Read the user guide and specification reference: English · 简体中文 (sources: English · 简体中文).
For local building and browsing (docs/specification-reference/book/index.html), see the manual README.
use trust2_contract::prelude::*;
#[postcondition(|c| c >= a)]
#[postcondition(|c| c >= b)]
pub fn max(a: i32, b: i32) -> i32 {
if a > b { a } else { b }
}
#[precondition(a >= b)]
#[postcondition(|c| c + b == a)]
pub fn strict_sub(a: u32, b: u32) -> u32 {
a - b
}
#[precondition(x < 16)]
#[postcondition(|x2| x2 >= x)]
pub fn square(x: u8) -> u8 {
x * x
}Verification result:
Entering directory '/tmp/.tmpj8g1QI'
Theory trust2_contract_example.Top: ✔ (3)
Proved (trust2_contract_example.mlw) ✔
Leaving directory '/tmp/.tmpj8g1QI'
Verified trust2_contract_example in 2.19s
- Linux AMD64
- macOS AMD64
- macOS ARM64
opam install . --deps-onlyEnsure that the installed why3find executable can be accessed where our verifier program is run.
See Install OCaml for information on how to access executables installed inside an opam switch.
cargo install --path ./cargo-verifyNote that this will automatically install the Rust toolchain pinned by ./rust-toolchain.toml.
-
(Recommended) Copy
./rust-toolchain.tomlto your Cargo package/workspace root. -
To specify contracts in source code, use the
trust2-contractpackage.Add
./trust2-contractas a path dependency.Run
cargo doc --package trust2-contract --no-deps --openfor documentation. -
To verify contracts specified, use the
cargo verifysubcommand.Run
cargo verify --helpfor help.
opam switch create . 5.3.0
opam install ocaml-lsp-server odoc ocamlformat.0.27.0 utop
opam install . --deps-onlygit config set core.hooksPath .git-hooks
git remote add charon https://github.com/AeneasVerif/charon.git
git remote set-url charon --push no-push
git remote add proc-macro-crate https://github.com/bkchr/proc-macro-crate.git
git remote set-url proc-macro-crate --push no-pushIf Charon depends on the openssl crate, additional steps may be required to build. See openssl - Rust.
This project patches Charon, but does not bump its version.