Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

This is the user guide for trust2-contract, a contract-based verifier for Rust.

Installation

Build trust2-contract from source on Linux AMD64, macOS AMD64, or macOS ARM64. The steps below use a local OCaml environment and Alt-Ergo as the initial prover. Commands assume Bash or Zsh.

1. Prepare the system tools

Install Git, a C/C++ build toolchain, and opam.

On Debian or Ubuntu:

sudo apt update
sudo apt install git curl build-essential pkg-config libgmp-dev opam

On macOS, install the Command Line Tools if they are not already available, then install opam using Homebrew:

xcode-select --install
brew install git opam pkg-config

For other distributions, follow the opam installation instructions. Opam may request additional system packages when resolving dependencies.

2. Get the source

git clone https://github.com/OpenSourceVerif/trust2-contract.git
cd trust2-contract

This is the repository root: it contains Cargo.toml, rust-toolchain.toml, and trust2-contract.opam. Run the remaining setup commands here unless another directory is specified. Keep this checkout: the contract library is currently used as a path dependency.

3. Set up Rust

If rustup is not installed, use the official Rust installer:

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
. "$HOME/.cargo/env"

From the repository root, check the selected toolchain:

rustc --version
rustup show active-toolchain

Rustup uses the repository’s rust-toolchain.toml and downloads its toolchain and requested components when needed. The current file pins nightly-2026-06-01 with rustc-dev, llvm-tools, and miri. Use the file shipped with your checkout; the frontend depends on Rust compiler internals.

4. Set up the OCaml environment

If this is your first use of opam, initialize it without creating a global switch:

opam init --bare

Create a local switch with the OCaml version used by the repository’s development setup, activate it, and install the project dependencies:

opam switch create . 5.3.0
eval $(opam env)
opam install . --deps-only

If this checkout already has a local switch, reuse it instead of creating it again. The dependency manifest pins a particular development revision of Why3find; use opam install . --deps-only to follow that pin.

Check that the environment exposes Why3find:

command -v why3find

In a new terminal, return to the repository root and run eval $(opam env) before invoking the verifier. This puts the local switch’s executables on PATH, including when you later enter an example directory. See opam usage for switch management.

5. Install a prover

Verification needs an external prover as well as Why3find. To start with Alt-Ergo, install it in the same switch and let Why3 detect it:

opam install alt-ergo
why3 config detect
why3 config list-provers

Confirm that Alt-Ergo appears in the detected provers. Repeat detection after installing another prover, as described in the Why3 configuration documentation.

The verifier’s default prover list is Alt-Ergo, CVC5, and Z3. The example below explicitly selects Alt-Ergo so that it only requests the prover installed in this walkthrough. Additional provers can be selected with --prover, for example --prover alt-ergo,z3 once both are installed and detected.

6. Install the verifier

From the repository root:

cargo install --path ./cargo-verify
cargo verify --help

Cargo normally installs cargo-verify in ~/.cargo/bin. Keep that directory on PATH together with the active opam switch’s bin directory.

7. Check the installation

Run the example included in the repository:

cd examples/readme
cargo verify --prover alt-ergo

This checks the Rust frontend, specification translation, and prover invocation together. A successful run should finish with a Verified summary and exit successfully; displaying --help alone only checks that the command is installed.

Continue with Basic Usage to set up your own package.

Troubleshooting

  • cargo verify is not found: check that Cargo’s installation directory is on PATH; with the default rustup setup, reload . "$HOME/.cargo/env".
  • why3find is not found: activate the local switch from the repository root with eval $(opam env) in the terminal that runs verification.
  • No matching prover: check why3 config list-provers, ensure the prover executable is on PATH, and rerun why3 config detect.
  • Rust compiler or component mismatch: run from a checkout using its pinned rust-toolchain.toml; do not substitute a different nightly.

Basic Usage

After installation, copy the repository’s rust-toolchain.toml into your package root and add trust2-contract to Cargo.toml:

[dependencies]
trust2-contract = { path = "/path/to/trust2-contract/trust2-contract" }

Replace the path with the location of the trust2-contract library inside your checkout.

Write a contract

Import the contract annotations and attach them to a function:

use trust2_contract::prelude::*;

#[precondition(x < 16)]
#[postcondition(|result| result >= x)]
pub fn square(x: u8) -> u8 {
    x * x
}

The precondition requires callers to provide x < 16. The postcondition states that the returned value, named result, is at least x.

This function can be used in either a library or an executable.

In a library

Place the code in src/lib.rs. From the package root, run:

cargo verify --prover alt-ergo -- --lib

The verifier checks the function under its precondition. No main function is needed.

In an executable

Place the same code in src/main.rs and add an entry point:

fn main() {
    let _ = square(4);
}

Then run:

cargo verify --prover alt-ergo -- --bin my-app

Replace my-app with your binary target’s name, which defaults to the package name in Cargo.toml. Here, main calls square with an argument that satisfies its precondition.

Both commands use the Alt-Ergo prover configured during installation. The arguments after -- select the Cargo target: --lib for a library, or --bin for an executable. Run them from the package directory, including when the package is a workspace member.

To run an executable normally, use cargo run. Ordinary builds remove contract annotations; use cargo verify to check contracts statically.

See Function Contracts for more about preconditions and postconditions.

Specification Language

Specifications describe conditions on function calls, program states, and data. They are written as Rust attributes and macro invocations.

Syntax
Specification :=
      FunctionContract
    | TypeInvariant
    | ContractStatement

Lexical Rules defines the notation and Rust syntax used throughout this reference. Logic Expressions defines the expressions from which specification conditions are formed.

The remaining chapters describe the places where these conditions apply:

Each construct is described by its syntax, semantics, examples, and implementation boundaries. The Grammar Index collects all productions.

Lexical Rules

Specifications occur within Rust source code. Function contracts and type invariants use attributes; statement annotations and quantifiers use macro invocations. Comments do not introduce specifications.

Tokens and identifiers

Identifiers, literals, whitespace, and comments follow Rust’s lexical rules. Whitespace and ordinary comments may separate tokens wherever Rust permits them. The specification language introduces no separate literal notation or mathematical Unicode operators.

The following names in the grammar refer to Rust syntax:

NameMeaningExamples
IDENTIFIERIdentifierx, result, limit
TypeTypeu8, &T, Vec<i32>
LiteralLiteral expressiontrue, 16, 0u8
PathExpression pathx, u8::MAX
TUPLE_INDEXTuple-field index0 in pair.0

Names introduced by bindings follow Rust scope rules. In a postcondition, result is an ordinary parameter name; another identifier may be used instead. In a type invariant, self refers to the value whose invariant is being described.

Grammar notation

Syntax blocks use a compact extended BNF (EBNF). Boxed monospace text denotes literal source tokens; linked names denote nonterminals.

NotationMeaning
A := BDefines A in terms of B
A BA followed by B
A | BEither A or B
A?Zero or one occurrence of A
A*Zero or more occurrences of A
(A B)Groups grammar elements

A boxed (, ) or | is a source token, not a grammar operator. Arguments? permits an omitted argument list; ","? permits a trailing comma. The Show syntax diagrams button displays the same production as a diagram.

The grammar uses unqualified names, parenthesized macro invocations, and simple parameter bindings. The Expr production describes expression structure; Rust operator precedence determines grouping. It is not an unambiguous parser grammar for all Rust expressions.

Example

#[precondition(x /* input */ < 16)]
#[postcondition(|result: u8| result >= x)]

The comment separates tokens without changing the precondition. The bars in the second attribute delimit the return-value binding.

Implementation boundaries

  • Frontend rust-llbc: uses Rust lexical rules, expression parsing, and typing and borrowing checks.
  • Backend llbc-why3: handles extracted representations rather than these lexical forms directly.

Remaining work

Distinguishing markers from ordinary names (frontend). Name-based replacement of implies and postcondition old also changes ordinary Rust names. For example, .old() in #[postcondition(|r| r == value.old())] is replaced even when it denotes a user-defined method, causing expansion to fail. Name handling needs to preserve ordinary method calls while recognizing specification markers. See Name rewriting.

Logic Expressions

Logic expressions form the conditions used in contracts, statement annotations, and type invariants. They use Rust expressions together with quantifiers, implication, and an old-state marker.

Syntax
Condition :=
      Expr

Expr :=
      Literal
    | Path
    | self
    | ( Expr )
    | UnaryOp Expr
    | Expr BinaryOp Expr
    | Expr . Field
    | Expr [ Expr ]
    | Expr ( Arguments? )
    | Expr . IDENTIFIER ( Arguments? )
    | Quantifier
    | Implication
    | OldExpression

Arguments :=
      Expr (, Expr)* ,?

Field :=
      IDENTIFIER
    | TUPLE_INDEX

UnaryOp :=
      ! | - | * | & | & mut

BinaryOp :=
      + | - | * | / | % | << | >> | & | ^ | | | == | != | < | <= | > | >= | && | ||

Condition syntax diagramConditionExpr
Arguments syntax diagramArgumentsExpr,Expr,
Field syntax diagramFieldIDENTIFIERTUPLE_INDEX
UnaryOp syntax diagramUnaryOp!-*&&mut
BinaryOp syntax diagramBinaryOp+-*/%<<>>&^|==!=<<=>>=&&||

Types and values

A Condition must have type bool. Subexpressions may have other Rust types: for example, in x + 1 <= limit, the addition produces a numeric value and the comparison produces a Boolean value. There is no separate predicate type or implicit conversion from integers to Boolean conditions.

Names refer to bindings in scope. Field access, dereferencing, indexing, and function or method calls use Rust typing and borrowing rules. Parentheses group expressions without changing their value.

Integer expressions use Rust integer types, including their finite ranges and arithmetic checks. The specification interface does not introduce mathematical integers or real numbers. An expression that indexes a collection must also satisfy the index bounds; appearing in a specification does not remove that requirement.

Operator precedence

The following groups are ordered from highest to lowest precedence. Unary operators associate to the right. Arithmetic and bitwise binary operators associate to the left. Comparisons cannot be chained directly: write a < b && b < c.

GroupOperators
Access and callse.field e[i] f(x) e.method(x)
Unary! - * & &mut
Multiplicative* / %
Additive+ -
Shifts<< >>
Bitwise AND&
Bitwise XOR^
Bitwise OR|
Comparisons== != < <= > >=
Logical AND&&
Logical OR||

For Boolean operands, !, &&, and || express negation, conjunction, and disjunction. && and || short-circuit: their right operand is evaluated only when needed. The single-character bitwise operators do not provide this short-circuit behavior.

Quantifiers bind a value of a Rust type. Implication expresses a conditional proposition. Old-state Expressions describe the pre-state marker available in postconditions.

Example

use trust2_contract::prelude::*;

#[precondition(i < values.len() && values[i] > 0)]
pub fn positive_at(values: &[u8], i: usize) -> u8 {
    values[i]
}

The condition requires a valid index and a positive element. Short-circuit evaluation ensures the second operand is evaluated only when the index is in bounds.

The frontend has extraction examples involving slice lengths, Vec indexing, field comparisons, and ordinary calls. Backend support for these expressions varies, as described below.

Conditions can also use Rust expression blocks, local bindings, casts, and branches. For example, this precondition can be extracted:

#[precondition({
    let y = x as u32;
    if flag { y > 0 } else { y == 0 }
})]
pub fn selected(x: u8, flag: bool) -> u8 {
    x
}

Enum conditions can use match, as shown in the type-invariant examples. Ordinary calls can also enter specifications, such as #[precondition(positive(x))] with a Rust function positive returning bool. Extraction does not establish that every operation involved is supported by backend verification.

Implementation boundaries

  • Frontend rust-llbc: extracts basic operations, field and slice access, ordinary calls, and conditions using if, match, and casts.
  • Backend llbc-why3: supports basic scalar expressions; slices, indexing, usize, and some enum and trait operations still have gaps.

Remaining work

Slice conditions (backend). The example’s i < values.len() && values[i] > 0 can be extracted. Verification still needs translation of slices, lengths, index types, and indexing to express that the index is valid and the element positive.

Calls within specifications (frontend and backend; rules remain open). Ordinary calls such as #[precondition(positive(x))] can enter LLBC. The frontend also accepts a call to a function that modifies global state before returning bool; Fn + Copy alone does not exclude such side effects. Which functions are admissible and how their side effects are restricted need to be defined, then enforced through frontend checks and backend logical representations. Extracting an ordinary call is not enough to establish that it can be verified as a logical condition.

Quantifiers

Syntax
Quantifier :=
      (forall | exists) ! ( QuantifierPredicate )

QuantifierPredicate :=
      | IDENTIFIER : Type | Condition

Quantifier syntax diagramQuantifierforallexists!(QuantifierPredicate)
QuantifierPredicate syntax diagramQuantifierPredicate|IDENTIFIER:Type|Condition

Semantics

forall!(|x: T| P) states that P holds for every value x of type T. exists!(|x: T| P) states that there is a value x of type T for which P holds. In both forms, P must have type bool.

The binding of x extends over the closure body. That body may refer to outer bindings and contain further quantifiers. Multiple quantified variables can be expressed by nesting quantifiers or destructuring a single tuple parameter. Each quantifier accepts one parameter; a two-parameter closure such as |x: u8, y: u8| does not match the current interface.

The domain is a Rust type. For example, quantifying over u8 concerns its finite range of values, not unbounded mathematical integers. A restriction on the domain is expressed in the body: universal quantification uses a conditional property, while existential quantification requires both the restriction and the property to hold.

Examples

use trust2_contract::prelude::*;

#[postcondition(|result| forall!(|i: u8| i <= result))]
pub fn largest_u8() -> u8 {
    u8::MAX
}

#[postcondition(|result| exists!(|i: u8| i == result))]
pub fn zero() -> u8 {
    0
}

The first postcondition gives an upper bound for all u8 values. The second states that the returned value has a witness in the same type.

Both examples retain their quantifiers and return-value bindings in LLBC and generate the corresponding WhyML quantified conditions.

A tuple parameter can introduce two variables at once. This condition states that any two u8 values are equal or the returned value is zero:

#[postcondition(|r| forall!(|(x, y): (u8, u8)| x == y || r == 0))]
pub fn zero_for_pairs() -> u8 {
    0
}

This form also supports extraction and WhyML generation. Capturing other outer variables and combining nested quantifiers are discussed in the implementation boundaries below.

Implementation boundaries

  • Frontend rust-llbc: has extraction for both quantifiers and nested quantifiers, and retains tuple parameters; passing captured outer variables still has problems.
  • Backend llbc-why3: has universal and existential quantifier translation, but producing a file does not establish that bindings and conditions were handled correctly.

Remaining work

Passing outer variables (frontend extraction and backend use). This condition expresses equality between the returned value and the input, but does not currently translate correctly:

#[postcondition(|r| exists!(|x: u8| x == r && x == n))]
pub fn identity(n: u8) -> u8 {
    n
}

The example produces LLBC, but the subsequent WhyML refers to an undefined variable. Problems also occur when quantifiers reference function parameters or multiple quantifier levels capture outer variables. Extraction and translation need to pass each level’s captures correctly, keeping n associated with the input, r with the returned value, and x with the local binding.

Quantification over ranges and slices also depends on the corresponding expressions. For example, stating that every valid index refers to a positive element requires quantifiers, lengths, and indexing to work together.

Implication

Syntax
Implication :=
      implies ( Condition , Condition ,? )

Implication syntax diagramImplicationimplies(Condition,Condition,)

Semantics

implies(P, Q) expresses logical implication. Both arguments have type bool. The proposition is false exactly when P is true and Q is false; its logical meaning is !P || Q.

This equivalence concerns truth values. The current call representation does not give implies the evaluation behavior of a short-circuit operator.

Example

use trust2_contract::prelude::*;

#[postcondition(|result| implies(x > 0, result >= x))]
pub fn identity(x: i32) -> i32 {
    x
}

The postcondition requires result >= x whenever x > 0.

The frontend can extract this implication expression and retain it inside quantified conditions.

Implementation boundaries

  • Frontend rust-llbc: recognizes and retains the implies marker in LLBC, including within quantifier bodies.
  • Backend llbc-why3: does not yet translate this marker, so the example cannot complete verification.

Remaining work

Logical implication translation (backend). The example’s implies(x > 0, result >= x) needs to generate the logical condition that result >= x holds whenever x > 0. Markers within quantifier bodies need the same treatment.

Both arguments are currently evaluated, so implies(i < a.len(), a[i] > 0) cannot use its antecedent to guard indexing. Where short-circuit behavior is needed, write i >= a.len() || a[i] > 0; this remains subject to backend slice and index support. Whether implies itself should provide conditional evaluation remains open.

Old-state Expressions

Syntax
OldExpression :=
      old ( Expr ,? )

OldExpression syntax diagramOldExpressionold(Expr,)

Intended semantics

An old-state expression in a postcondition refers to the function’s pre-state: the state on entry to the function. Its purpose is to relate a returned state to an earlier one.

The current old construct provides a marker for this purpose, with the restricted interface described below. It does not yet provide a general snapshot operation on Rust expressions.

Syntax example

*old(p)

This fragment combines an old-state marker with dereferencing. The argument p must match the mutable-reference interface. Whether the fragment is admissible in a postcondition also depends on the surrounding closure’s captures and borrowing.

Implementation boundaries

  • Frontend rust-llbc: recognizes the old marker but does not yet fully represent entry values; its current interface accepts only mutable references.
  • Backend llbc-why3: old-state translation is not implemented.

Remaining work

Entry values of mutable parameters (frontend and backend). The following example aims to describe an increment but cannot currently be used:

#[precondition(*p < u32::MAX)]
#[postcondition(|_| *p == *old(p) + 1)]
fn increment(p: &mut u32) {
    *p += 1;
}

In verification mode, this form is blocked by the closure’s Copy requirement. The frontend needs to let postconditions refer to entry values and distinguish them from return-state values. The backend needs to use that representation to establish the relationship. The intended property is that *p is one greater than its entry value; the interface may change with the state representation.

The scope of old-state support for fields, compound values, and aliased data remains to be defined.

Function Contracts

A function contract specifies conditions required when a function is called and conditions guaranteed when it returns normally.

Syntax
FunctionContract :=
      Precondition
    | Postcondition

FunctionContract syntax diagramFunctionContractPreconditionPostcondition

Semantics

Preconditions describe the caller’s obligations and the assumptions under which the function body is verified. Postconditions describe the function’s obligations on return.

Attributes precede the function definition. Preconditions and postconditions may be repeated and interleaved. All stated preconditions are required; all stated postconditions are guarantees to establish. A postcondition alone does not assert termination.

A postcondition binds the returned value with a closure parameter. See Return-value binding. References to an earlier state use Old-state Expressions, whose current interface is restricted.

Example

use trust2_contract::prelude::*;

#[precondition(x < 16)]
#[postcondition(|result| result >= x)]
pub fn square(x: u8) -> u8 {
    x * x
}

The precondition restricts x to values whose square fits in u8. The postcondition requires the returned value to be at least x.

This example supports both frontend extraction and backend verification. Preconditions and postconditions can also be used separately, or repeated on the same function.

Conditions on methods can refer to self. The following contract can be extracted and translated to WhyML:

pub struct Counter {
    value: u32,
}

impl Counter {
    #[precondition(self.value < 10)]
    #[postcondition(|r| r == self.value)]
    pub fn get(&self) -> u32 {
        self.value
    }
}

Implementation boundaries

  • Frontend rust-llbc: supports preconditions/postconditions on ordinary functions and methods with bodies.
  • Backend llbc-why3: supports basic scalar-function contract verification; generic functions and trait declarations still have translation limitations.

Remaining work

Bodyless declarations (frontend). Macros currently carry conditions through the function body, so this form cannot expand:

trait Reader {
    #[postcondition(|result| result <= 100)]
    fn read(&self) -> u8;
}

Conditions need to be stored on the method declaration for later handling of implementations and calls. How implementations inherit contracts, and whether they may strengthen guarantees, remains to be defined.

Special function forms (frontend). Expanding #[precondition(x < 100)] const fn f(x: u32) -> u32 { x } calls non-constant helper functions. Extracting #[postcondition(|r| r > 0)] async fn f() -> u32 { 1 } encounters unsupported coroutine types. Supporting these forms requires accommodation of constant contexts and of the value obtained when an async function completes, respectively.

Preconditions

Syntax
Precondition :=
      # [ precondition ( Condition ) ]

Precondition syntax diagramPrecondition#[precondition(Condition)]

Semantics

#[precondition(P)] requires the Boolean condition P to hold on entry to the function. At a call, the caller must establish P; when verifying the function body, P is an assumption.

The condition may refer to the function’s parameters, a method receiver, and other names visible at the definition. It does not bind a return value. Multiple precondition attributes require all of their conditions to hold.

Example

use trust2_contract::prelude::*;

#[precondition(divisor != 0)]
pub fn quotient(value: u32, divisor: u32) -> u32 {
    value / divisor
}

The precondition excludes division by zero. A call with divisor == 0 fails the stated requirement.

Basic parameter conditions support frontend extraction. Existing backend examples include constraining a square calculation with x < 16 and unsigned subtraction with a >= b.

Implementation boundaries

  • Frontend rust-llbc: supports basic parameter conditions, method receivers, and multiple preconditions.
  • Backend llbc-why3: supports translation and verification of basic scalar conditions.

See Function Contracts for bodyless declarations and Logic Expressions for conditions involving slices and other expressions.

Postconditions

Syntax
Postcondition :=
      # [ postcondition ( ResultPredicate ) ]

ResultPredicate :=
      | IDENTIFIER (: Type)? | Condition

Postcondition syntax diagramPostcondition#[postcondition(ResultPredicate)]
ResultPredicate syntax diagramResultPredicate|IDENTIFIER:Type|Condition

Semantics

#[postcondition(|result| Q)] requires the Boolean condition Q to hold on normal return, with result bound to the returned value. Verification of the function must establish this condition under its preconditions.

Multiple postconditions state simultaneous guarantees. They do not specify whether the function terminates or what happens on a panic.

Return-value binding

The parameter name is arbitrary: result is not a keyword. Its type is the function’s return type and may be written explicitly. A function without a declared return type returns ().

Function parameters and method receivers are referenced from the surrounding scope. A captured reference does not by itself denote a snapshot of the data it points to. The intended pre-state notation and its implementation limits are described under Old-state Expressions.

Example

use trust2_contract::prelude::*;

#[postcondition(|value: u32| value == x)]
pub fn identity(x: u32) -> u32 {
    x
}

Here value denotes the returned value, and x is the input used in the comparison.

Return-value conditions support frontend extraction and basic backend verification. For example, a maximum function can separately declare result >= a and result >= b, guaranteeing that its result is at least both inputs.

Implementation boundaries

  • Frontend rust-llbc: supports return-binding closures, references to input parameters, and multiple postconditions.
  • Backend llbc-why3: supports basic scalar return-value conditions; relationships involving mutable references and old state remain incomplete.

Remaining work

Passing a function directly (frontend). The following form passes Rust type checking but fails during specification extraction:

fn positive(value: u32) -> bool {
    value > 0
}

#[postcondition(positive)]
pub fn one() -> u32 {
    1
}

Writing the same condition as #[postcondition(|value| positive(value))] allows extraction. A directly supplied function still needs to be associated with the return-value condition, or rejected with a clear diagnostic at the entry point. Verification limits on the call itself are described under Logic Expressions.

Before/after relationships. Stating that *p is one greater on return than on entry still requires old and a complete state representation for mutable references. Capturing p alone does not establish an entry-value snapshot.

Statement Annotations

Statement annotations express conditions at a particular point in a function body.

Syntax
ContractStatement :=
      Assertion
    | Assumption

ContractStatement syntax diagramContractStatementAssertionAssumption

Semantics

An assertion states a condition to establish at its location. An assumption supplies a condition for reasoning from that location. Both may refer to variables in scope and describe the state at the annotation.

Example

use trust2_contract::prelude::*;

pub fn check(x: u8) {
    contract_assume!(x < 16);
    contract_assert!(x <= 15);
}

The assertion follows from the preceding assumption. This does not prove that x < 16 holds for every call to check.

Implementation boundaries

  • Frontend rust-llbc: supports assertions and assumptions, retaining their conditions, kinds, and positions.
  • Backend llbc-why3: translates them to WhyML assert and assume, respectively.

See Assertions and Assumptions for specific uses and limitations.

Assertions

Syntax
Assertion :=
      contract_assert ! ( Condition ) ;

Assertion syntax diagramAssertioncontract_assert!(Condition);

Semantics

contract_assert!(P); requires the Boolean condition P to hold at that point. It introduces a proof obligation using the function’s preconditions, preceding assumptions, and the effects of the preceding program statements.

Example

use trust2_contract::prelude::*;

#[precondition(x < 16)]
pub fn bounded_square(x: u8) -> u8 {
    let y = x * x;
    contract_assert!(y <= 225);
    y
}

The assertion describes the local value y after multiplication.

The frontend can extract local assertions of this form. It can also retain ordinary calls in conditions, such as contract_assert!(decuple(9) == 90).

Implementation boundaries

  • Frontend rust-llbc: extracts assertion conditions and retains their positions in function bodies, including within branches.
  • Backend llbc-why3: translates them to WhyML assert; further verification depends on the expressions and program operations involved.

Shared limitations are described under Logic Expressions. Ordinary builds remove contract assertions; runtime checks use Rust’s assert!.

Assumptions

Syntax
Assumption :=
      contract_assume ! ( Condition ) ;

Assumption syntax diagramAssumptioncontract_assume!(Condition);

Semantics

contract_assume!(P); introduces the Boolean condition P as a hypothesis at that point. It does not introduce an obligation to prove P.

Conclusions obtained using the assumption are conditional on it. An inconsistent assumption makes subsequent proof obligations vacuous.

Example

use trust2_contract::prelude::*;

pub fn assumed_bound(x: u8, flag: bool) {
    if flag {
        contract_assume!(x <= 10);
        contract_assert!(x < 11);
    } else {
        contract_assert!(x <= 255);
    }
}

On the branch where flag is true, the assumed bound implies the following assertion; the other branch does not use that assumption. Frontend extraction and WhyML translation retain this branch structure. The annotation neither checks nor establishes the bound for the caller.

Implementation boundaries

  • Frontend rust-llbc: extracts assumptions, distinguishes them from assertions, and retains their enclosing branches.
  • Backend llbc-why3: translates them to WhyML assume; further verification depends on the expressions and program operations involved.

Shared limitations are described under Logic Expressions. Assumptions create no obligation to prove themselves, and ordinary builds do not use them to filter inputs.

Type Invariants

Syntax
TypeInvariant :=
      # [ invariant ( Condition ) ]

TypeInvariant syntax diagramTypeInvariant#[invariant(Condition)]

Semantics

#[invariant(P)] associates a Boolean condition P with a struct, enum, or union. Within the condition, self refers to the value whose invariant is described. The condition expresses a property that valid instances are intended to satisfy.

Declaring an invariant and enforcing it at program boundaries are separate capabilities. The current implementation provides declaration and extraction; automatic enforcement is not yet implemented.

Example

use trust2_contract::prelude::*;

#[invariant(self.start <= self.end)]
pub struct RefRange<'a, T: PartialOrd> {
    start: &'a T,
    end: &'a T,
}

The condition requires the start of the range to be no greater than its end. The type parameters and their bounds remain available in the invariant.

The frontend can extract this generic struct invariant and retain its association with the type.

An enum can describe a condition for each variant:

#[invariant(match self {
    Self::Empty => true,
    Self::Range { start, end } => start <= end,
})]
pub enum Range {
    Empty,
    Range { start: u32, end: u32 },
}

The frontend can extract this match self condition. Union conditions can also be extracted; reading a field still requires unsafe under Rust rules:

#[invariant(unsafe { self.x <= 100 })]
pub union Data {
    pub x: u32,
    pub y: u32,
}

These examples show how conditions are associated with types; they do not establish automatic backend enforcement.

Implementation boundaries

  • Frontend rust-llbc: extracts invariants on structs, enums, and unions and retains their association with the type. Multiple conditions on one type currently need to be combined with &&; repeated attributes conflict.
  • Backend llbc-why3: does not yet use these conditions to establish invariant checks. Declaring an invariant does not yet guarantee valid objects.

Remaining work

From type conditions to checking obligations (backend; checking points remain open). This type requires x <= 100, but constructing an invalid instance does not yet automatically generate the corresponding check:

#[invariant(self.x <= 100)]
pub struct B {
    pub x: u32,
}

pub fn invalid() -> B {
    B { x: 200 }
}

The frontend stores x <= 100; the generated WhyML does not yet use it. The condition needs to participate in verification of object creation, modification, and external use. Which boundaries require checks, whether modifications may temporarily violate the condition, and how it is restored when a borrow ends remain to be defined.

Grammar Index

This page collects the core productions in one place. Follow nonterminal references to the corresponding topic for meaning, examples, and implementation status.

See Lexical Rules for the notation and Logic Expressions for operator precedence. This index and the topic pages are generated from the same grammar definitions.

Syntax
Specification :=
      FunctionContract
    | TypeInvariant
    | ContractStatement

FunctionContract :=
      Precondition
    | Postcondition

Precondition :=
      # [ precondition ( Condition ) ]

Postcondition :=
      # [ postcondition ( ResultPredicate ) ]

ResultPredicate :=
      | IDENTIFIER (: Type)? | Condition

TypeInvariant :=
      # [ invariant ( Condition ) ]

ContractStatement :=
      Assertion
    | Assumption

Assertion :=
      contract_assert ! ( Condition ) ;

Assumption :=
      contract_assume ! ( Condition ) ;

Condition :=
      Expr

Expr :=
      Literal
    | Path
    | self
    | ( Expr )
    | UnaryOp Expr
    | Expr BinaryOp Expr
    | Expr . Field
    | Expr [ Expr ]
    | Expr ( Arguments? )
    | Expr . IDENTIFIER ( Arguments? )
    | Quantifier
    | Implication
    | OldExpression

Arguments :=
      Expr (, Expr)* ,?

Field :=
      IDENTIFIER
    | TUPLE_INDEX

UnaryOp :=
      ! | - | * | & | & mut

BinaryOp :=
      + | - | * | / | % | << | >> | & | ^ | | | == | != | < | <= | > | >= | && | ||

Quantifier :=
      (forall | exists) ! ( QuantifierPredicate )

QuantifierPredicate :=
      | IDENTIFIER : Type | Condition

Implication :=
      implies ( Condition , Condition ,? )

OldExpression :=
      old ( Expr ,? )

FunctionContract syntax diagramFunctionContractPreconditionPostcondition
Precondition syntax diagramPrecondition#[precondition(Condition)]
Postcondition syntax diagramPostcondition#[postcondition(ResultPredicate)]
ResultPredicate syntax diagramResultPredicate|IDENTIFIER:Type|Condition
TypeInvariant syntax diagramTypeInvariant#[invariant(Condition)]
ContractStatement syntax diagramContractStatementAssertionAssumption
Assertion syntax diagramAssertioncontract_assert!(Condition);
Assumption syntax diagramAssumptioncontract_assume!(Condition);
Condition syntax diagramConditionExpr
Arguments syntax diagramArgumentsExpr,Expr,
Field syntax diagramFieldIDENTIFIERTUPLE_INDEX
UnaryOp syntax diagramUnaryOp!-*&&mut
BinaryOp syntax diagramBinaryOp+-*/%<<>>&^|==!=<<=>>=&&||
Quantifier syntax diagramQuantifierforallexists!(QuantifierPredicate)
QuantifierPredicate syntax diagramQuantifierPredicate|IDENTIFIER:Type|Condition
Implication syntax diagramImplicationimplies(Condition,Condition,)
OldExpression syntax diagramOldExpressionold(Expr,)

Implementation Notes

Reading implementation boundaries

Each construct page distinguishes frontend rust-llbc from backend llbc-why3. Here, the frontend includes macro expansion, Rust typing and borrowing checks, and extraction to LLBC. The backend translates specifications in LLBC to WhyML for verification.

Successful extraction does not establish backend support. Producing a WhyML file does not establish that it passes Why3 checking or that its obligations have been proved.

Examples show existing uses. “Remaining work” describes concrete scenarios, current obstacles, and the properties they are intended to express. Unsettled semantics are identified explicitly. These descriptions do not assign development stages, priorities, or an exhaustive support scope. See Sources and Test Coverage for implementation sources and repository tests.

Shared conventions

  • Rust typing and borrowing: conditions return bool and use Rust’s type system. Apart from type-invariant methods, specification closures require Fn + Copy; modifying captures or moving out non-Copy values may violate these requirements.
  • Ordinary builds: specification annotations are removed. Successful ordinary compilation does not establish that specifications pass verification-mode checks.
  • Normal returns: postconditions describe normal-return properties without also declaring termination or post-panic state.

Name rewriting

Contract macros recursively rewrite implies, and postconditions also rewrite old. Quantifier macros do not perform these rewrites themselves; an enclosing contract macro handles them.

Current replacement is name-based and also affects ordinary same-named methods such as value.old(). The frontend needs to distinguish specification markers from ordinary Rust names. See Lexical Rules for a concrete example.

Rules still to be defined

Admissible function calls and restrictions on side effects are discussed under Logic Expressions. The program boundaries at which type invariants hold are discussed under Type Invariants. These rules affect frontend and backend behavior; the concrete scenarios are retained without fixing a complete design in advance.

Sources and Test Coverage

The following sources describe frontend extraction, backend translation, and existing coverage.

Frontend rust-llbc

Backend llbc-why3

Test coverage

Frontend integration cases include preconditions, postconditions, assertions, a generic struct invariant, and combinations of universal quantification, implication, and container access. The to_sorted body is a placeholder returning an empty vector; it illustrates extraction rather than a verified sorting algorithm.

The repository frontend integration examples do not yet include contract_assume! or exists!. Both have extraction implementations; problems with outer captures are described in the quantifier implementation boundaries. old has name-rewriting tests but no complete old-state specification integration case.

Saved backend end-to-end results cover basic preconditions/postconditions for max, strict_sub, and square. Assertions, assumptions, and quantifiers have translation implementations but are not included in these end-to-end cases.