Skip to content

Latest commit

 

History

History

class-integration

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 

README.md

class-integration: #[leanclass] + codegen end-to-end template

A complete Lean↔Rust template for Leo3's macro pipeline. Where examples/lake-integration hand-writes raw extern "C" functions and matching Lean declarations, this example shows the differentiated workflow:

  • a Rust cdylib built with #[leanclass] (external objects with methods and #[getter] / #[setter] accessors), #[leanfn] and #[leanmodule];
  • Lean-side extern declarations generated by leo3-codegen from metadata embedded in the compiled binary — nothing in lean/ is written by hand except Main.lean, the lakefile and the library root;
  • a Lake package that consumes the generated declarations, constructs objects, calls methods and verifies every result at runtime (non-zero exit on any mismatch).

Layout

examples/class-integration/
├── gen-lean.sh                  # build cdylib + run leo3-codegen (reproducible)
├── native/                      # Rust cdylib
│   ├── Cargo.toml               # leo3 path dependency, `macros` feature
│   ├── build.rs
│   └── src/lib.rs               # #[leanclass] Account + #[leanmodule] functions
└── lean/                        # Lake package
    ├── lakefile.lean
    ├── lean-toolchain           # Lean v4.30.0
    ├── Account.lean             # generated (class)
    ├── ClassIntegration/
    │   └── Native.lean          # generated (module)
    ├── ClassIntegration.lean    # library root (imports the generated modules)
    └── Main.lean                # executable: calls + runtime verification

Prerequisites

  • Rust ≥ 1.88 (rustup)
  • Lean v4.30.0 via elan — or lemma if you are behind a restrictive proxy. You do not need to install the toolchain manually: lake reads lean/lean-toolchain and fetches it on first use.
# elan
curl https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh -sSf | sh
# verify
rustc --version   # rustc 1.88+
lean --version    # Lean (version 4.30.0, ...) — optional, lake auto-installs

Build and run

cd examples/class-integration

# 1. Build the cdylib and (re)generate the Lean declarations.
#    LEO3_NO_LEAN=1 inside the script keeps the cdylib from linking
#    libleanshared; the Lean executable provides the runtime at load time.
./gen-lean.sh

# 2. Build the Lake package (auto-installs Lean v4.30.0 on first run).
cd lean
lake build app

# 3. Run it. The dynamic linker needs to find the cdylib:
LD_LIBRARY_PATH=../native/target/release .lake/build/bin/app   # Linux
DYLD_LIBRARY_PATH=../native/target/release .lake/build/bin/app # macOS

Expected output:

== ClassIntegration.Native (#[leanmodule] + #[leanfn]) ==
ci_add(20, 22) = 42
ok   ci_add = 42
ci_banner("counter", 8) = counter has 8 ticks
ok   ci_banner = counter has 8 ticks
ci_sum(#[10, 20, 30]) = 60
ok   ci_sum = 60
== Account (#[leanclass]) ==
ok   Account.owner = Alice
ok   Account.balance (new) = 0
ok   balance after deposits = 150
ok   withdraw 30 succeeds = true
ok   balance after withdraw = 120
ok   overdraft refused = false
ok   balance unchanged = 120
ok   set_balance = 42
ok   describe = Alice (balance: 42)
ok   map Account.owner = [Ada, Bob]
All checks passed.

Any mismatch throws IO.userError, so a failing check exits non-zero — the example doubles as an executable test of the whole pipeline.

How it works

Rust → metadata → Lean declarations

#[leanclass] / #[leanfn] / #[leanmodule] generate the extern "C" wrappers and embed structured binding metadata (JSON) into the cdylib. leo3-codegen reads that metadata straight out of the binary — no Lean runtime required — and emits one .lean file per class/module:

# what gen-lean.sh does, spelled out:
cd native && LEO3_NO_LEAN=1 cargo build --release && cd ..
cargo run -p leo3-codegen --manifest-path ../../Cargo.toml -- \
    native/target/release/libclass_integration.so -o lean

The generated files are committed so the Lake package builds without Rust; re-run gen-lean.sh whenever native/src/lib.rs changes and commit the diff. CI verifies the committed files match the codegen output.

Calling convention

Generated declarations follow Lean's extern convention, and the macro-generated wrappers match it exactly:

Lean type C representation in the wrapper
UInt8–UInt64, Int8–Int64, USize, ISize, Float32, Float unboxed scalar (uint64_t, int32_t, float, ...)
Bool / Char unboxed uint8_t / uint32_t
String, Array T, Option T, Except E T, Prod A B boxed lean_object*
class types (Account) boxed external object (lean_object*)

So Account.balance : Account → Int64 calls int64_t __lean_ffi_Account_balance(lean_object*), while ci_add : UInt64 → UInt64 → UInt64 calls uint64_t ci_add(uint64_t, uint64_t). Higher-order use (List.map Account.owner) also works: the Lean compiler emits its own boxed adapters that unbox into the same symbols.

Method semantics

Rust shape Lean-visible declaration
fn new(owner: String) -> Self Account.new : String → Account
#[getter] fn balance(&self) -> i64 Account.balance : Account → Int64
#[setter] fn set_balance(&mut self, v: i64) Account.set_balance : Account → Int64 → Account
fn deposit(&mut self, amount: i64) Account.deposit : Account → Int64 → Account
fn withdraw(&mut self, amount: i64) -> bool Account.withdraw : Account → Int64 → Prod Account Bool

&mut self methods are copy-on-write: when the Lean value is shared (refcount > 1) the wrapper clones the inner Rust value into a fresh external object, so mutation never leaks across references. Methods that both mutate and return a value surface as Prod so neither piece is lost — destructure with let (acct, ok) := Account.withdraw acct 30.

The class type declaration

Generated class files introduce the type through NonemptyType:

opaque Account.ffi : NonemptyType
def Account : Type := Account.ffi.val
instance : Nonempty Account := Account.ffi.property

This is the standard library's own pattern (IO.RealWorld): a bare opaque Account : Type would not elaborate, because opaque declarations require an Inhabited/Nonempty instance and every constructor/updater declaration returns the class.

Troubleshooting

  • undefined symbol: lean_alloc_object (or similar) at startup — the executable was linked before the cdylib gained new runtime references. Lake does not track the cdylib as a dependency; relink after rebuilding native code: rm -f .lake/build/bin/app && lake build app.
  • error while loading shared libraries: libclass_integration.so — set LD_LIBRARY_PATH (Linux) / DYLD_LIBRARY_PATH (macOS) to ../native/target/release as shown above.
  • no leo3 metadata found in library from codegen — rebuild the cdylib first (gen-lean.sh does both steps).
  • Lean toolchain download fails behind a proxy — install the toolchain with lemma (proxy/mirror-aware elan replacement); lake picks it up through PATH.

See also