# inlean
Write Lean 4 inside a Rust source file and call the result as an ordinary Rust function.
```rust
inlean::lean! {
@[export saturating_double]
def saturatingDouble (x : UInt32) : UInt32 :=
if x <= 2147483647 then 2 * x else 4294967295
theorem saturatingDouble_max : saturatingDouble 4294967295 = 4294967295 := by decide
}
fn main() {
println!("{}", saturating_double(21)); // 42
println!("{}", saturating_double(3_000_000_000)); // 4294967295
}
```
`lean!` is a proc macro. At compile time it runs the real `lean` binary on the block. Lean
checks the block, proofs included. The macro then translates Lean's compiler output for the
exported functions into Rust. `@[export saturating_double]` is Lean's attribute for giving a
function a stable external name; here that name becomes the Rust function. Nothing of Lean is
linked into your program: the result is plain Rust that calls a small runtime crate.
The goal is seamless use of Lean from a Rust program: Lean code is built by cargo with the rest
of the application, and its values appear as Rust types. Running existing Lean programs is not
the goal. This is an early prototype. The five
[principles](https://github.com/shergin/inlean/blob/main/docs/principles/README.md) say what a
user gets and decide trade-offs; the design, status and limits are described in detail in
[DESIGN.md](https://github.com/shergin/inlean/blob/main/DESIGN.md).
## Using it and building
Add it from crates.io with `cargo add inlean`, or with `inlean = "0.1"` under `[dependencies]`
in `Cargo.toml`. It needs Rust 1.88 or later and a macOS or Linux build host, x86-64 or ARM64.
CI tests it on macOS ARM64 and Linux x86-64; macOS x86-64 and Linux ARM64 have not been run.
Lean is needed by the author of a block, not by everyone who builds it: a crate that commits
its results (see [Committed results](#committed-results)) builds with no Lean at all. The
macro looks for Lean only when a block has to run it: when the block has no committed result
and no result in the local cache. It needs Lean 4.36.0, exactly that release, and looks in the
directory named by `INLEAN_LEAN_TOOLCHAIN`, then in elan (Lean's toolchain manager), then in
inlean's own cache directory. If none has it, the macro downloads the official release archive
from GitHub into the cache directory, and says so on stderr first. The download is 638 MB and
takes 2.3 GB on disk; on a fast connection it takes about a minute (measured on macOS ARM64).
The archive is checked against its published SHA-256 before it is unpacked. It happens once
per machine. To avoid it, install the toolchain with
`elan toolchain install leanprover/lean4:v4.36.0` or point `INLEAN_LEAN_TOOLCHAIN` at one. To
forbid it, set `INLEAN_OFFLINE=1` or `CARGO_NET_OFFLINE=true`; cargo's `--offline` flag alone
does not reach the macro. A block that needs Lean then fails with an error that says how to
install it.
After that, each block that Lean has not seen costs about 1.2 s of build time. Results are
cached by the block's text, so an unchanged block costs nothing on rebuild. Under
rust-analyzer the macro never runs Lean. It answers from the cache, so a new block resolves in
the editor after the first `cargo check`.
## What works today
Inside a block, Lean code may use `Nat` and `Int` (arbitrary precision), strings, arrays,
lists, byte arrays, `Std.HashMap` and `Std.HashSet` (Lean's own implementation), structures,
`Option`, closures, `for` loops, float literals and the usual math functions, along with
recursion, `match`, `where` clauses and helper functions. A block over
fixed-width scalars only expands to safe Rust. Any other block expands to `unsafe` functions
over inlean's own object runtime, behind safe wrappers.
Exported functions are `pub` in the Rust module where the macro is used. Each block is its own
Lean file: blocks do not see each other's definitions. Values cross the boundary as the types
Rust programs already use:
| `UIntN`, `IntN`, `USize`, `ISize`, `Bool`, `Char`, `Float`, `Float32` | `uN`, `iN`, `usize`, `isize`, `bool`, `char`, `f64`, `f32` | same |
| `Nat`, `Int` | `impl Into<Nat>`, `impl Into<Int>`: a machine integer, the type, or a reference to it | `inlean::Nat`, `inlean::Int` |
| `String` | `impl Into<String>`: a `&str`, or a `String` that is moved in | `String` |
| `ByteArray`, `FloatArray` | `impl Into<Vec<u8>>`, `impl Into<Vec<f64>>`: a slice, or a `Vec` that is moved in | `Vec<u8>`, `Vec<f64>` |
| `Array α`, `List α` | `&[T]` | `Vec<T>` |
| `Option α` | `Option<T>` | `Option<T>` |
| `α × β` | `(A, B)` | `(A, B)` |
| `Except ε α` | `Result<T, E>` | `Result<T, E>` |
| `Std.HashMap κ α`, `Inlean.Map κ α`, `Std.HashSet κ` | `&HashMap<K, V>`, `&HashSet<K>` | `HashMap<K, V>`, `HashSet<K>` |
| a structure or inductive type of the block | `&` a generated Rust struct or enum | the generated type |
Nested types use the result form, so `Array String` is `&[String]`. Lean names the error type
of `Except` first, Rust last: `Except String Unit` is `Result<(), String>`. A `String` or `Vec`
passed by value is moved in without a copy, and a result is moved out when nothing in Lean
still refers to it. Arrays and lists are converted element by element; a map or set is rebuilt
through Lean's own constructors on each crossing. `inlean::Nat` and `inlean::Int` accept any
unsigned or signed integer, convert back with `TryFrom`, and print, parse, compare and hash.
They are not `Send`.
```rust
inlean::lean!(r#"
import Std.Data.HashMap
@[export word_counts]
def wordCounts (words : List String) : Std.HashMap String Nat :=
words.foldl (fun m w => m.insert w (m.getD w 0 + 1)) {}
@[export xor_bytes]
def xorBytes (data : ByteArray) (key : UInt8) : ByteArray := Id.run do
let mut out := data
for i in [0:data.size] do
out := out.set! i (data.get! i ^^^ key)
return out
"#);
fn main() {
let words = ["to", "be", "or", "not", "to", "be"].map(String::from);
let counts = word_counts(&words);
println!("{}", counts["to"]); // 2
let secret = xor_bytes(b"hello".to_vec(), 0x2a); // the Vec is moved in
println!("{:?}", xor_bytes(secret, 0x2a)); // [104, 101, 108, 108, 111]
}
```
A `structure` declared in the block becomes a `pub struct` with public fields; any other
inductive type (a type defined by its constructors) becomes a `pub enum` with named-field
variants. Fields and parameter names are `snake_case`, variants `UpperCamelCase`. The types
derive `Clone`, `Debug` and `PartialEq`, and also `Eq` and `Hash` when they hold no float and
no map, so they can be map keys. They keep Lean's doc comments and use `Box` where a type
contains itself. Type parameters make them generic: `structure Pair (α β : Type)` is
`Pair<T0, T1>`, and `Pair Nat String` in a signature is `Pair<Nat, String>`.
```rust
inlean::lean!(r#"
inductive Priority where
/-- A job in a queue. -/
structure Job where
title : String
priority : Priority
minutes : UInt32
inductive Tree (α : Type) where
| leaf
| node (left : Tree α) (value : α) (right : Tree α)
def Tree.insert (t : Tree UInt32) (x : UInt32) : Tree UInt32 :=
match t with
| .leaf => .node .leaf x .leaf
| .node l v r => if x < v then .node (l.insert x) v r else .node l v (r.insert x)
@[export by_minutes]
def byMinutes (js : Array Job) : Tree UInt32 :=
js.foldl (fun t j => t.insert j.minutes) .leaf
inductive ParseError where
| empty
| badChar (pos : Nat) (c : Char)
@[export parse_nat]
def parseNat (s : String) : Except ParseError Nat := do
if s.isEmpty then throw .empty
let mut n := 0
for c in s.toList, i in [0:s.length] do
if !c.isDigit then throw (.badChar i c)
n := n * 10 + (c.toNat - '0'.toNat)
return n
"#);
fn main() {
let job = Job { title: "backup".into(), priority: Priority::High, minutes: 90 };
match by_minutes(&[job.clone(), Job { minutes: 30, ..job }]) {
Tree::Node { left, value, .. } => println!("root {value}, left {left:?}"),
Tree::Leaf => println!("empty"),
}
if let Err(ParseError::BadChar { pos, c }) = parse_nat("12x") {
println!("{c:?} at {pos}"); // 'x' at 2
}
}
```
### Two maps
`Std.HashMap` is Lean's own verified implementation, translated like any other code.
`Inlean.Map`, from `import Inlean`, keeps its entries in a Rust `HashMap`, in insertion order.
It has `insert`, `insertMany`, `get?`, `getD`, `contains`, `erase`, `filter`, `mapValues`,
`modify`, `alter`, `size`, `isEmpty`, `toList`, `toArray`, `keys`, `values`, `fold`, `ofList`,
`ofArray`; `{}` is the empty map. Proofs use lookup lemmas (`get?_insert_self`, `get?_erase_of_ne`,
...) or its model, a list of entries (`toList_*`). It is trusted, not verified: its Rust code is
tested against that model. `#eval` cannot run it. Pick `Std.HashMap` when the map's own code
must be verified, `Inlean.Map` for Rust's map or insertion order. Both cross as `HashMap`.
```rust
inlean::lean!(r#"
import Inlean
open Inlean
@[export first_seen]
def firstSeen (words : Array String) : Array String :=
(words.foldl (fun (m : Map String Unit) w => m.insert w ()) {}).keys.toArray
theorem first_seen_abc : firstSeen #["b", "a", "b"] = #["b", "a"] := by decide
"#);
// first_seen(&["to", "be", "or", "not", "to", "be"].map(String::from)) is ["to", "be", "or", "not"]
```
Differences from Lean: `panic!` and an out-of-bounds `arr[i]!` panic in Rust, where Lean prints
a message and continues. Lean rejects `@&` (borrowed) parameters on exports. Not yet at the
boundary: types with parameters that are not types (`Vec3 (n : Nat)`), indexed types, types
with a parameter no field uses, and types with a proof as a field (the build fails and names
the field). Not yet inside a block: thunks, `Float.toString`, IO. A block that reaches a
missing runtime primitive fails to compile and names it. An unsupported boundary type fails
like this:
```
error: `force` takes `t : Thunk UInt32`, a type that cannot cross into Rust yet (supported: the fixed-width integers, Bool, Char, Float, Float32, Nat, Int, String, structures and inductive types of the block, ByteArray, FloatArray, Std.HashMap, Std.HashSet, Inlean.Map, and Array, List, Option, Except and pairs of these)
--> src/main.rs:3:9
|
```
## Three ways to write a block
| `lean! { ... }` | short definitions in plain ASCII |
| `lean!(r#" ... "#)` | anything with Unicode (`∀`, `≤`, `⟨⟩`) or primes (`x'`) |
| `lean_file!("src/x.lean")` | real proofs |
The token form must lex as Rust. Unicode operators, primes in names, `//`, backslash and
backtick do not, and `·` for proof bullets must be written `.`. The raw string form, used in
the example above, has none of these limits. For anything longer, keep the Lean in its own
file. A `.lean` file gets Lean's own editor support (goals, hovers, errors as you type) if a
`lean-toolchain` file containing `leanprover/lean4:v4.36.0` sits in or above its directory.
The path is relative to the crate's `Cargo.toml`, and the crate is rebuilt when the file
changes: `inlean::lean_file!("src/proofs.lean")`.
## What fails the build
Any error Lean reports, including a proof that does not go through; `sorry` (Lean's placeholder
for a missing proof); any axiom other than Lean's standard three (`propext`, `Classical.choice`,
`Quot.sound`); `native_decide` and `bv_decide`, which trust compiled code instead of the kernel;
`unsafe`, `@[implemented_by]` and `@[extern]`.
`native_decide` and `bv_decide` prove a claim by running compiled code, so a proof that uses
them trusts Lean's compiler, not only its kernel. That is why accepting them is an opt-in, made
per crate and visible in review: `trust-compiler = true` under `[package.metadata.inlean]` in
the crate's `Cargo.toml`.
Errors point at the Lean code in your Rust file. A `sorry` left in the first example prints:
```
error: `saturatingDouble_max` depends on `sorry`
--> src/main.rs:6:13
|
```
## What "proved" means here
What is verified is your definitions: a theorem in a block is a theorem about them. What is
trusted is everything that turns them into the Rust that runs: Lean's compiler, inlean's
translator and runtime, and `Inlean.Map`
([principle 3](https://github.com/shergin/inlean/blob/main/docs/principles/3-what-you-proved-is-what-runs.md)).
Differential tests cover that step: the suite compares the generated code with real Lean on
roughly 35,000 results, including big-number arithmetic and string positions, and checks that
calls leave no live objects behind. This is the same shape of trust as Lean's own native code,
which goes through Lean's compiler, a C emitter and a C runtime.
## Committed results
What Lean says about a block depends only on the block's text and the Lean release. A crate can
keep those results in `.inlean/`, next to its `Cargo.toml`, and commit them:
```
INLEAN_VENDOR=1 cargo build # write every block's result to .inlean/
INLEAN_VENDOR=check cargo build # fail if a result is missing or differs from Lean's (for CI)
```
By default a committed result is used when there is one; otherwise the local cache, otherwise
Lean. With `.inlean/` committed, building the crate, or anything that depends on it, needs no
Lean and downloads nothing: not for downstream users, not on docs.rs, not offline. The author
runs `INLEAN_VENDOR=1` before committing and CI runs `INLEAN_VENDOR=check`, so a committed result
is never older than its block
([principle 5](https://github.com/shergin/inlean/blob/main/docs/principles/5-lean-stays-out.md)).
Stale files are not removed; to start clean, delete the directory and write it again.
A crate published to crates.io has to carry `.inlean/` in its package. Cargo leaves the
directory out when the crate is not in a git repository, since it then skips directories whose
names start with a dot, and when the crate has an `include` list that does not name it.
Packaging does not notice: the verification build of `cargo package` and `cargo publish` finds
the missing results in the author's local cache. Check that `cargo package --list` lists the
files in `.inlean/`, or run `INLEAN_VENDOR=check cargo package`, which fails if a block's
result is missing from the package.
## Environment variables
| `INLEAN_LEAN_TOOLCHAIN` | Use the Lean 4.36.0 toolchain in this directory. |
| `INLEAN_OFFLINE` | Never download Lean. |
| `INLEAN_CACHE_DIR` | Where results and the downloaded toolchain are kept. Default: `~/Library/Caches/inlean` on macOS, `$XDG_CACHE_HOME/inlean` or `~/.cache/inlean` elsewhere. |
| `INLEAN_VENDOR` | `1`: write results to `.inlean/`; `check`: fail if a committed result is missing or stale. |
| `INLEAN_TIMEOUT` | Seconds Lean may take on one block before the build fails. Default: 300. |
## 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](https://github.com/shergin/inlean/blob/main/crates/inlean-runtime/NOTICE).