Conao3 Notes

Three Ways to Combine Lean 4 and Rust

You can combine Lean 4 and Rust in three ways: link the Lean runtime over C FFI, generate Rust code from Lean IR, or extract existing Rust functions into a Lean model for verification. Pick an approach based on whether your build environment can host Lean and whether you have a Rust implementation in place.

Below, I compare the three approaches and walk through a minimal Rust setup with leanfran (v0.15.0, Lean 4.35.0, Rust 1.88+), along with the proof boundary and current limits. Read deva's Lean guide for Lean 4 syntax and proof basics, and the leanfran overview post for the full multi-language backend design.

Three approaches and how to choose

Two factors separate the three paths: which language holds the implementation, and whether you can ship the Lean runtime with the binary.

img

Approach Implementation language Lean needed in consumer builds Main tools Best fit
1. Link via C FFI Lean 4 Yes (plus the Lean C runtime) @[export] and lean-sys Calling Lean libraries, including Mathlib and C bindings, as-is
2. Generate Rust from Lean Lean 4 No (cargo alone once cached files are in git) leanfran ( lean! / generate ) Proving pure logic such as parsers or state machines in Lean and shipping a Rust crate
3. Verify Rust in Lean Rust No (only during extraction and proof checks) Charon, Aeneas, #[leanfran::model] Proving properties of existing Rust functions without rewriting them

C FFI links Lean's C backend output and libleanshared into Rust, so you can call Mathlib and external C libraries with no subset restrictions. That freedom costs build simplicity: both consumers and CI need the Lean 4 toolchain and shared libraries, and you manage reference counts across the FFI boundary by hand.

leanfran compiles Lean's intermediate representation (Lean.IR) into plain Rust source files. Commit the generated Rust files and cache to your repository, and routine cargo build and cargo test runs need neither Lean nor the C runtime. The generated runtime also targets wasm32-unknown-unknown.

To keep an existing Rust implementation intact, use Charon and Aeneas to translate Rust functions into Lean 4 models and prove properties about them. leanfran wraps extraction, random testing, and proof tracking inside Cargo via the #[leanfran::model] attribute.

Minimal steps to write Lean and call it from Rust

leanfran offers two entry points for Rust callers: the inline lean! macro inside a Rust source file, and leanfran generate to emit Rust modules from a standalone lake project.

Install the compiler and cargo-leanfran on the development machine where you run code generation, then add the crate dependencies to Cargo.toml.

nix profile install 'github:conao3/lean-leanfran/v0.15.0#leanfran'
nix profile install 'github:conao3/lean-leanfran/v0.15.0#cargo-leanfran'
[dependencies]
leanfran = "0.15.0"

[build-dependencies]
leanfran-build = "0.15.0"

Add one line to build.rs so the build script loads the cached Rust output during compilation.

fn main() {
    leanfran_build::Builder::new().compile().unwrap();
}

Embed small logic with the lean! macro

For compact state transitions or numeric routines, you can place Lean definitions and theorems right inside a Rust file using a lean! block. This excerpt from step-02-theorems defines sumTo for the sum from 1 to n and checks its closed-form theorem sumTo_closed at the same time.

leanfran::lean! {
    pub mod sums;
    r#"
    def sumTo : Nat → Nat
      | 0 => 0
      | n + 1 => sumTo n + (n + 1)

    theorem sumTo_closed (n : Nat) : 2 * sumTo n = n * (n + 1) := by
      induction n with
      | zero => rfl
      | succ n ih => simp only [sumTo]; grind
    "#
}

#[cfg(test)]
mod tests {
    use super::sums;
    use leanfran::Nat;

    #[test]
    fn sum_to() {
        assert_eq!(sums::sum_to(100u64.into()), Nat::from(5050u64));
    }
}

Run leanfran --lang rust sync whenever you edit a block; Lean checks the theorem and writes the generated Rust into .leanfran/rust/cache/. The public API exposes safe snake_case Rust functions such as sums::sum_to, and proof terms stay out of the compiled binary.

Generate modules from a lake project for larger codebases

Once definitions and lemmas grow, you want editor Infoview feedback and multiple Lean files. Keep the Lean code in a normal lake project and place leanfran.toml at the crate root, as in step-09-lake-project, so leanfran generate writes the selected modules under src/generated/.

[[generate]]
lang = "rust"
lake-dir = "lean"
output-dir = "src/generated"
path = "crate::generated"
modules = ["Stats.*"]

I use the lean! macro for the event state machine in gh-lookout (a GitHub Actions webhook relay), and leanfran generate from a lake project for the Japanese legal XML parser and statutory reading rules in ritsulint. In both workflows, committing the generated files lets cargo test pass without Lean on the machine. In my local check with rustc and cargo alone, the full test suites for step-02-theorems, step-09-lake-project, and step-10-ensures finished in 10 seconds.

Verify existing Rust functions in Lean

To keep the implementation in Rust, put the specification in a lean! block and annotate the Rust function with #[leanfran::model]. This example from step-10-ensures specifies that saturating_double returns a value at least as large as its input.

pub mod spec {
    leanfran::lean! {
        #[lean(imports = ["Aeneas"])]
        pub mod double;
        r#"
        open Aeneas Aeneas.Std

        def ge (x r : Std.U32) : Bool := decide (x.val ≤ r.val)
        "#
    }
}

use spec::double;

#[leanfran::model(ensures(ge = double::ge))]
pub fn saturating_double(x: u32) -> u32 {
    if x > u32::MAX / 2 { u32::MAX } else { x * 2 }
}

leanfran --lang rust check invokes Charon and Aeneas to extract saturating_double into a Lean model, emits the proof obligations, checks your proofs under lean/Proofs/, and writes the status into leanfran.lock. Aeneas models integer overflow and panics as Result.fail, so closing this proof establishes that x * 2 does not overflow for any u32 input and the result is at least x.

Before you write a single proof, cargo test runs proptest against boundary values and random inputs (200 cases by default) to catch mismatches between your Rust code and the Lean spec. Set LEANFRAN_REQUIRE=proved in Cargo.toml or the environment to fail the build whenever a Rust edit makes a proof stale.

Proof guarantees and limits

Separate what the Lean kernel proves from what you trust outside the kernel. The kernel checks that your theorems hold for your Lean definitions. Whether those definitions match your intent, and whether the translators (leanfran IR codegen and runtime, or Charon and Aeneas extraction) match Rust semantics, sits outside the proof.

To shrink that gap, leanfran runs differential tests in CI comparing generated Rust output against Lean's C backend. If you want to check whether your theorems leave holes in coverage, pair them with mutation testing in leanassay.

leanfran v0.15.0 has three main limits:

  • The generated runtime targets Unix (Linux and macOS) and wasm32-unknown-unknown; Windows support is absent.
  • Reference counting on ordinary objects is non-atomic, and Task runs on the calling thread instead of spawning OS threads (use Lean<L> handles to pass values across threads).
  • #[leanfran::model] supports the safe Rust subset that Aeneas extracts, excluding unsafe, interior mutability, concurrency, floating-point values, and some string methods.

Closing

Start small when bringing Lean 4 into a Rust project: extract pure calculations or parsers with clear boundaries using lean! or leanfran generate instead of verifying an entire codebase at once. If you are adding specs to existing Rust code, begin with #[leanfran::model] and proptest random tests, then prove the critical functions in Lean.

For type conversions, thread handles, and all 17 walkthrough steps, see the leanfran Rust guide and the earlier lean-rs post.