Conao3 Notes

7a37d0.md

「Three Ways to Combine Lean 4 and Rust」の 7a37d0.md です。「そのまま開く」はファイルをそのまま返します。

# Three Ways to Combine Lean 4 and Rust

Date: 2026-12-04
Updated: 2026-12-04
Tags: lean, rust, formal-verification, code-generation, lean-leanfran, tutorial
URL: https://s.conao3.com/blog/2026/7a37d0
Author: conao3 (Naoya Yamashita)

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](https://github.com/conao3/lean-leanfran) (v0.15.0, Lean 4.35.0, Rust 1.88+), along with the proof boundary and current limits.
Read [deva's Lean guide](https://deva.conao3.com/lean/) for Lean 4 syntax and proof basics, and the [leanfran overview post](https://s.conao3.com/blog/2026/21ebbd) for the full multi-language backend design.

[conao3/lean-leanfran](https://github.com/conao3/lean-leanfran): Write functions and proofs in Lean 4 and generate Rust, Python, TypeScript, Clojure, PHP, Go and C code from them

# 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](https://s.conao3.com/img/7a37d0-approaches.svg)

<table border="2" cellspacing="0" cellpadding="6" rules="groups" frame="hsides">

<colgroup>
<col  class="org-left" />

<col  class="org-left" />

<col  class="org-left" />

<col  class="org-left" />

<col  class="org-left" />
</colgroup>
<thead>
<tr>
<th scope="col" class="org-left">Approach</th>
<th scope="col" class="org-left">Implementation language</th>
<th scope="col" class="org-left">Lean needed in consumer builds</th>
<th scope="col" class="org-left">Main tools</th>
<th scope="col" class="org-left">Best fit</th>
</tr>
</thead>
<tbody>
<tr>
<td class="org-left">1. Link via C FFI</td>
<td class="org-left">Lean 4</td>
<td class="org-left">Yes (plus the Lean C runtime)</td>
<td class="org-left"><code>@[export]</code> and <code>lean-sys</code></td>
<td class="org-left">Calling Lean libraries, including Mathlib and C bindings, as-is</td>
</tr>

<tr>
<td class="org-left">2. Generate Rust from Lean</td>
<td class="org-left">Lean 4</td>
<td class="org-left">No (<code>cargo</code> alone once cached files are in git)</td>
<td class="org-left"><code>leanfran</code> ( <code>lean!</code> / <code>generate</code> )</td>
<td class="org-left">Proving pure logic such as parsers or state machines in Lean and shipping a Rust crate</td>
</tr>

<tr>
<td class="org-left">3. Verify Rust in Lean</td>
<td class="org-left">Rust</td>
<td class="org-left">No (only during extraction and proof checks)</td>
<td class="org-left">Charon, Aeneas, <code>#[leanfran::model]</code></td>
<td class="org-left">Proving properties of existing Rust functions without rewriting them</td>
</tr>
</tbody>
</table>

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](https://github.com/AeneasVerif/charon) and [Aeneas](https://github.com/AeneasVerif/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`.

```sh
nix profile install 'github:conao3/lean-leanfran/v0.15.0#leanfran'
nix profile install 'github:conao3/lean-leanfran/v0.15.0#cargo-leanfran'
```

```toml
[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.

```rust
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](https://github.com/conao3/lean-leanfran/tree/v0.15.0/langs/Rust/samples/steps/02-theorems) defines `sumTo` for the sum from 1 to `n` and checks its closed-form theorem `sumTo_closed` at the same time.

```rust
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](https://github.com/conao3/lean-leanfran/tree/v0.15.0/langs/Rust/samples/steps/09-lake-project), so `leanfran generate` writes the selected modules under `src/generated/`.

```toml
[[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](https://lookout.conao3.com/) (a GitHub Actions webhook relay), and `leanfran generate` from a `lake` project for the Japanese legal XML parser and statutory reading rules in [ritsulint](https://ritsulint.conao3.com/).
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](https://github.com/conao3/lean-leanfran/tree/v0.15.0/langs/Rust/samples/steps/10-ensures) specifies that `saturating_double` returns a value at least as large as its input.

```rust
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](https://s.conao3.com/blog/2026/e3d3ca).

`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](https://github.com/conao3/lean-leanfran/blob/v0.15.0/docs/rust-guide.md) and the [earlier lean-rs post](https://s.conao3.com/blog/2026/1ff994).