Leo3: Rust Bindings for Lean4
Leo3 provides safe, ergonomic Rust bindings to the Lean4 theorem prover, inspired by PyO3's architecture.
Quick Start
Requires Lean 4.25.2 (install via elan).
[]
= "0.2.1"
use *;
Features
Type Conversions
Bidirectional conversions between Rust and Lean types via IntoLean / FromLean traits:
| Rust | Lean | Wrapper |
|---|---|---|
String, &str |
String |
LeanString |
u8–u64, usize |
UInt8–UInt64, USize |
LeanUInt* |
i8–i64, isize |
Int8–Int64, ISize |
LeanInt* |
f32, f64 |
Float32, Float |
LeanFloat32, LeanFloat |
bool |
Bool |
LeanBool |
char |
Char |
LeanChar |
Vec<T> |
Array |
LeanArray |
Option<T> |
Option |
LeanOption |
Result<T, E> |
Except |
LeanExcept |
(A, B) |
Prod / Sigma |
LeanProd / LeanSigma |
| — | List |
LeanList |
| — | HashMap / HashSet |
LeanHashMap / LeanHashSet |
| — | RBMap |
LeanRBMap |
| — | Nat / Int |
LeanNat / LeanInt |
| — | Sum, Fin, Subtype, BitVec, Range |
corresponding wrappers |
Procedural Macros
#[leanfn] — Export Rust functions to Lean:
#[leanclass] — Expose Rust structs as Lean external classes with auto-generated FFI wrappers and Lean source declarations:
#[derive(IntoLean)] / #[derive(FromLean)] — Automatic conversion derive macros.
Meta-Programming
Full access to Lean's kernel and elaborator:
LeanEnvironment— Create and manage declaration environmentsLeanExpr— Build expressions (binders, applications, literals, lambda, forall)LeanDeclaration— Define axioms, definitions, and theoremsMetaMContext— Type inference, type checking, definitional equality, proof validation- Tactic support
IO & Runtime
- IO operations: console, filesystem, environment variables, process, time
LeanClosure— Create and apply Lean closures from RustLeanTask/LeanPromise— Parallel computation with combinators (join,race,select,timeout)LeanModule— Dynamic loading of compiled Lean shared libraries- Tokio bridge for async integration
LeanThunk— Lazy evaluation
Architecture
leo3/
├── leo3/ # Safe high-level abstractions
├── leo3-ffi/ # Raw FFI bindings to Lean4's C API
├── leo3-build-config/ # Build-time Lean4 detection and configuration
├── leo3-macros/ # Procedural macro entry points
├── leo3-macros-backend/ # Procedural macro implementations
└── leo3-ffi-check/ # FFI layout validation (à la pyo3-ffi-check)
Design
Lean<'l>token proves runtime initialization at compile-timeLeanBound<'l, T>(lifetime-bound),LeanRef<T>(unbound),LeanUnbound<T>(thread-safe) smart pointers with automatic reference counting#[repr(transparent)]zero-cost wrappers- Copy-on-write semantics for
&mut selfFFI methods - Worker thread architecture for all Lean runtime calls (avoids mimalloc heap issues)
- Version support: Lean 4.20.0–4.30 with
#[cfg(lean_4_25)]gates
Comparison with PyO3
| PyO3 | Leo3 |
|---|---|
Python<'py> |
Lean<'l> |
Bound<'py, T> |
LeanBound<'l, T> |
Py<T> |
LeanRef<T> |
#[pyfunction] |
#[leanfn] |
#[pyclass] |
#[leanclass] |
Development
LEO3_NO_LEAN=1
License
MIT OR Apache-2.0