Skip to content
sherginPublic

About

Inline Lean 4 in Rust, checked by Lean and compiled to Rust

Resources

Stars

7 stars

Watchers

0 watching

Forks

Repository files navigation

inlean

Lean 4 inside your Rust source: proofs are checked by cargo build, and functions compile to plain Rust.

crates.io docs.rs CI

inlean::lean! {
    @[export midpoint]
    def midpoint (lo hi : UInt32) : UInt32 := lo + (hi - lo) / 2

    theorem midpoint_ge (lo hi : UInt32) (h : lo <= hi) : lo <= midpoint lo hi := by
      grind [midpoint]

    theorem midpoint_le (lo hi : UInt32) (h : lo <= hi) : midpoint lo hi <= hi := by
      grind [midpoint]
}

fn main() {
    println!("{}", midpoint(10, 20));                       // 15
    println!("{}", midpoint(4_000_000_000, 4_000_000_002)); // 4000000001
}

lean! is a proc macro. During cargo build the real lean binary checks the block, proofs included, and the macro translates Lean's compiled form of midpoint into Rust: main calls an ordinary fn midpoint(lo: u32, hi: u32) -> u32. @[export midpoint] gives the function its Rust name. Each theorem is a claim that Lean must prove for every pair of u32 values with lo <= hi, not for the pairs a test happens to try. The proof is what follows by: grind is one of Lean's automatic tactics, told here to unfold midpoint.

Write the midpoint the usual way, (lo + hi) / 2, and the first theorem is false: the sum wraps around past u32::MAX, so lo = hi = 2_147_483_648 gives 0. The build stops at that proof, in the Rust file:

error: `grind` failed
       case grind.1
       lo hi : UInt32
       h : lo ≤ hi
       h_1 : ¬lo ≤ midpoint lo hi
       h_2 : lo + hi = (lo + hi) / 2
       ⊢ False
       ...
 --> src/main.rs:6:7
  |
6 |       grind [midpoint]
  |       ^^^^^^^^^^^^^^^^

The ... stands for about a hundred lines in which grind lists what it derived before it gave up.

Why

A proof with the overhead of a unit test. The theorem sits next to the function, in the Rust file, and cargo build has Lean's own kernel check it; nothing reimplements Lean. You add one dependency: no build script, no second project, no command to run, no configuration.

A proof that does not hold is a compile error. So is a sorry (Lean's placeholder for a missing proof), an axiom beyond Lean's standard three, and native_decide, which trusts compiled code instead of the kernel. Each is reported with its line and column in the Rust file.

What comes out is ordinary Rust. Nothing of Lean is linked or shipped: no C toolchain, no runtime to start. A block over fixed-width scalars expands to safe Rust; any other block calls a small runtime written in Rust. inlean and its runtime have no third-party dependencies. A call that takes a u64 and returns it costs 0.4 ns on an Apple M1 Pro (measurements).

Rust types in, Rust types out. Values cross as u32, String, Vec<T>, Option, Result, tuples and HashMap. Lean structures and inductive types become Rust structs and enums, with their doc comments, derives and generic parameters. An argument is passed by value, which moves a string or byte array in without a copy, or by reference.

Your Rust takes part in the Lean code. A crate's own type can stand for a Lean type, such as ruint's U256 for BitVec 256. An opaque type carries any Rust value through Lean unconverted, and adds nothing to what is trusted. A Lean declaration can run a Rust function of the crate, with its Lean body as the model that proofs use. Rust's own Vec, VecDeque, HashMap and HashSet are usable inside Lean, so a theorem can be about code that changes a Rust HashMap in place.

Only the author needs Lean. Commit the results to .inlean/, and the crate builds with no Lean downstream, on docs.rs and offline. CI checks the committed results against Lean.

What is trusted is written down. Your definitions are verified. Lean's compiler and inlean's translator and runtime are trusted, and tested against real Lean on roughly 35,000 results. Anything more a crate trusts is one named line in its Cargo.toml, and appears in the documentation of every exported function that can reach it.

A tour

Rust types in, Rust types out

inlean::lean! {
    structure Line where
      item : String
      quantity : UInt32
      unitPrice : UInt64

    inductive OrderError where
      | empty
      | noQuantity (item : String)
      | tooLarge (total : Nat)

    @[export order_total]
    def orderTotal (lines : Array Line) : Except OrderError UInt64 := do
      if lines.isEmpty then throw .empty
      let mut total := 0
      for l in lines do
        if l.quantity == 0 then throw (.noQuantity l.item)
        total := total + l.quantity.toNat * l.unitPrice.toNat
      if total >= 2 ^ 64 then throw (.tooLarge total)
      return total.toUInt64
}

fn main() {
    let tea = Line { item: "tea".into(), quantity: 2, unit_price: 450 };
    let milk = Line { item: "milk".into(), quantity: 0, unit_price: 120 };
    println!("{:?}", order_total(&[tea.clone()]));       // Ok(900)
    match order_total(vec![tea, milk]) {
        Err(OrderError::NoQuantity { item }) => println!("no quantity: {item}"),
        other => println!("{other:?}"),
    }
}

Line is a pub struct with fields item: String, quantity: u32 and unit_price: u64. OrderError is a pub enum with variants Empty, NoQuantity { item } and TooLarge { total }, where total is an inlean::Nat, Lean's unbounded natural number. Except is Result. The first call passes a slice, which is copied; the second gives up a Vec, and its strings move into Lean without a copy.

Proofs about Rust's own collections

use std::collections::HashMap;

inlean::lean! {
    import Inlean
    open Inlean

    instantiate HashMap String UInt64
    instantiate Vec String

    @[export total]
    def total (prices : HashMap String UInt64) (order : Vec String) : UInt64 :=
      order.toArray.foldl (fun sum item => sum + (prices.get? item).getD 0) 0

    @[export restock]
    def restock (prices : HashMap String UInt64) (item : String) (price : UInt64) :
        HashMap String UInt64 :=
      prices.insert item price

    theorem restock_get (prices : HashMap String UInt64) (item : String) (price : UInt64) :
        (restock prices item price).get? item = some price := by simp [restock]
}

fn main() {
    let prices = HashMap::from([("tea".to_owned(), 400), ("milk".to_owned(), 120)]);
    let prices = restock(prices, "tea", 450);   // moves in, is changed in place, moves out
    let order = vec!["tea".to_owned(), "milk".to_owned(), "tea".to_owned()];
    println!("{}", total(&prices, &order));    // 1020
}

With import Inlean, a HashMap in the block is the standard library's HashMap, held by Lean as it is and changed by Rust's own code, with nothing converted or copied at the boundary. Proofs see a model of the map in Lean, whose simp lemmas make restock_get a one-line proof. Each instantiate line names the element types a collection is used at. Collections has the operations, the models and what can be proved.

Rust functions inside Lean

/// `a * b / c` in 128 bits; `None` when `c` is zero or the quotient needs more than 64 bits.
pub fn mul_div(a: u64, b: u64, c: u64) -> Option<u64> {
    if c == 0 {
        return None;
    }
    u64::try_from(a as u128 * b as u128 / c as u128).ok()
}

inlean::lean! {
    @[extern "mul_div"]
    def mulDiv (a b c : BitVec 64) : Option (BitVec 64) :=
      if c.toNat == 0 || 2 ^ 64 <= a.toNat * b.toNat / c.toNat then none
      else some (BitVec.ofNat 64 (a.toNat * b.toNat / c.toNat))

    @[export quote]
    def quote (amount price scale : BitVec 64) : Option (BitVec 64) := mulDiv amount price scale

    theorem quote_zero (x y : BitVec 64) : quote x y 0 = none := by
      simp [quote, mulDiv]
}

fn main() {
    println!("{:?}", quote(1 << 40, 1 << 20, 1 << 10)); // Some(1125899906842624)
    println!("{:?}", quote(u64::MAX, 2, 1));            // None
}
[package.metadata.inlean.trusted]
"mulDiv" = "crate::mul_div"

@[extern] marks a declaration whose code comes from elsewhere. The line in Cargo.toml says it is mul_div, and the Rust generated for quote calls it. The body of mulDiv is its model: quote_zero is proved about the model, and holds for the program if mul_div returns what the model returns. Nothing can check that, so the crate says it by name, and so do the docs of quote:

Trusted, not checked: `crate::mul_div` runs for `mulDiv`.

An @[extern] declaration that Cargo.toml does not name fails the build. Rust functions in a block has the rules and how to test such a function against its model. Such a declaration can also take a Lean function, which the Rust function receives as a closure, and be generic in a type (functions as arguments). The collections build fold, any, all, filter, map and find? on it (operations that take a function).

Your own types

A Rust type of the crate takes part in a block at one of three levels, each named in a table of Cargo.toml:

Level What Lean code does with the value What the crate trusts
primitive computes with it as a Lean type, such as ruint's U256 as BitVec 256, converted at each crossing that its conversions are total, and a round trip returns the same value
opaque carries it unconverted, and cannot look inside or make one nothing about the type
foreign carries it unconverted; Rust functions operate on it, and proofs use a Lean type of the block as its model that each of those functions matches its model

Choosing a level compares them, and compares the collections of import Inlean with Lean's own. The crate inlean-numeric has primitive types for num-bigint and ruint, so that Nat, Int and BitVec can be their BigUint, BigInt and Uint (big-integer libraries).

How it works

  1. The macro recovers the exact text of the block, so that Lean's positions map back to lines and columns of the Rust file.
  2. It runs Lean 4.36.0 on the block, which checks every proof and compiles every definition. A small driver reports Lean's messages, the exports and their signatures, the compiler's intermediate representation of everything they reach, and what breaks the trust policy.
  3. inlean fails the build on anything the policy rejects, and translates the intermediate representation into Rust that takes the place of the block.
  4. The result is cached by the block's text.

A block that Lean has not seen costs about 1.2 s of build time; an unchanged block costs nothing on rebuild. Under rust-analyzer the macro never runs Lean and answers from the cache: a block resolves in the editor once cargo check has compiled it and the file that holds it is next edited. Until then its functions are unresolved, and the macro reports no error. DESIGN.md has the details.

Getting started

cargo add inlean

inlean needs Rust 1.88 or later and a macOS or Linux build host, x86-64 or ARM64. It needs Lean 4.36.0, exactly that release, only when a block has no committed or cached result. The macro looks for it in the directory named by INLEAN_LEAN_TOOLCHAIN, then in elan (Lean's toolchain manager), then in its own cache. If none has it, the macro says so on stderr and downloads the official release once per machine: 638 MB, 2.3 GB on disk, about a minute, checked against its published SHA-256. To avoid the download, run elan toolchain install leanprover/lean4:v4.36.0 first. To forbid it, set INLEAN_OFFLINE=1; a block that needs Lean then fails with an error that says how to install it.

A block takes one of three forms:

Form Use it for
lean! { ... } definitions and proofs in plain ASCII; the block must lex as Rust tokens
lean!(r#" ... "#) any Lean text, with Unicode (∀, ≤, ⟨⟩) or primes (x')
lean_file!("src/proofs.lean") real proofs, with Lean's own editor support: goals, hovers, errors as you type

The editor support needs a lean-toolchain file containing leanprover/lean4:v4.36.0 in or above the file's directory. The path is relative to Cargo.toml, and a change to the file rebuilds the crate.

To build without Lean downstream, commit what Lean said about each block:

INLEAN_VENDOR=1 cargo build       # write every block's result to .inlean/
INLEAN_VENDOR=check cargo build   # in CI: fail if a result is missing or differs from Lean's

Building covers the toolchain, committed results for a published crate, and the environment variables.

What is proved, and what is trusted

A theorem in a block is a theorem about your definitions, checked by Lean's kernel. What turns them into the Rust that runs is trusted: Lean's compiler, inlean's translator and runtime, the conversions at the boundary, and the collections of import Inlean, which are trusted to match their models in Lean. Lean's own native code has the same shape of trust, through Lean's compiler, a C emitter and a C runtime. Tests compare the generated code with real Lean on roughly 35,000 results and check that calls leave no live objects behind; the runtime's tests also run under Miri, which checks its unsafe code.

A crate can trust more, for itself only: each entry under [package.metadata.inlean.trusted] has a Rust function run in place of a Lean declaration. Without such an entry, a crate trusts nothing beyond the above. What is proved, and what is trusted lists what fails the build, and principle 3 says why.

Documentation

License

MIT OR Apache-2.0. inlean-runtime contains functions ported from the runtime of Lean 4 (lean.h), which is under the Apache License 2.0; see its NOTICE.

About

Inline Lean 4 in Rust, checked by Lean and compiled to Rust

Resources

Stars

7 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages