Liking cljdoc? Tell your friends :D

leanfran — prove in Lean, run in your language

Write it in Lean. Prove it in Lean. Run it in your language.

Latest release CI License: Apache-2.0 Lean v4.35.0 GitHub stars

Rust on crates.io Python on PyPI TypeScript on npm Clojure on Clojars PHP on Packagist Go on pkg.go.dev C from Git tags

Quick look | Get started | Languages | Features | Documentation & examples | Contribution

leanfran

leanfran brings Lean 4 to Rust, Python, TypeScript, Clojure, PHP, Go, and C. Write functions and proofs together, compile them to your application's language, and call them through native types. The generated code runs with a small host-language runtime, or with Lean's runtime library for C; Lean is needed to check and generate code, not to run the result.

The name leanfran comes from lingua franca (a common language), shortened from leanfranca to reflect using Lean types and specifications as a common language across host languages.

Quick look

Install the compiler leanfran and Lean 4.35.0, and start a project. The two install lines take the compiler and the Python package from master:

$ nix profile install 'github:conao3/lean-leanfran#leanfran'
$ elan default leanprover/lean4:v4.35.0
$ uv init --lib myapp && cd myapp
$ uv add 'leanfran @ git+https://github.com/conao3/lean-leanfran#subdirectory=langs/Python'

Put a Lean function and its proof in a Python file:

# src/myapp/arith.py
from leanfran import lean

arith = lean("arith", r"""
def double (n : Nat) : Nat := n + n

theorem double_eq (n : Nat) : double n = 2 * n := by
  unfold double; omega
""")

Generate the module and call it as Python:

$ uv run leanfran --lang python sync
info: leanfran-python-workspace: no previous manifest, creating one from scratch
✔ [2/6] Built LeanPythonEmbed.myapp.arith.arith (402ms)
✔ [3/6] Built LeanPythonModels (471ms)
✔ [5/6] Built LeanPythonEmbed (359ms)
Build completed successfully (6 jobs).
leanfran: 1 blocks checked and generated
$ uv run python -c 'from myapp.arith import arith; print(arith.double(21))'
42

Change the theorem to double n = 3 * n and generation stops at the proof:

$ uv run leanfran --lang python sync
✖ [4/6] Building LeanPythonEmbed.myapp.arith.arith (296ms)
src/myapp/arith.py:8:18: error: (lean block myapp.arith:arith, Lean 5:17) omega could not prove the goal:
a possible counterexample may satisfy the constraints
  a ≥ 1
where
 a := ↑n
Some required targets logged failures:
- LeanPythonEmbed.myapp.arith.arith
error: build failed
leanfran: lake build exited with 1

Every supported language embeds Lean the same way (see the table below). The output above is from the compiler and the Python package built from this repository with Lean 4.35.0.

Lean at the core

leanfran compiles Lean's compiler IR into source code for the selected language. For C, it uses Lean's C emitter and adds headers, conversion code and link settings. You can generate code from a Lean project or embed Lean blocks directly in host-language source files. Proofs are checked by Lean during generation and erased from the executable code.

LanguageStart herePackageIntegration
RustRust quick startleanfran on crates.iolean!, Rust types, Cargo build integration
PythonPython quick startleanfran on PyPIlean(...), pydantic models, Python modules
TypeScriptTypeScript quick startleanfran on npmlean(...), TypeScript types, Standard Schema
ClojureClojure quick startio.github.conao3/leanfran on Clojarsdeflean, Clojure values, JVM namespaces
PHPPHP quick startconao3/leanfran on Packagist#[Lean], #[Model], leanfran --lang php sync
GoGo quick startleanfran-go on pkg.go.devgo get github.com/conao3/leanfran-go, embedded Lean, Go module tool
CC quick startGit tags, Nix flake output #leanfranleanfran:lean comments, C headers, pkg-config, Make and CMake

What you can build

  • Proved Lean functions in your application. Keep an algorithm and its correctness proof together in Lean, then call the function generated from it.
  • Validated data at the boundary. Lean structures and inductive types map to host-language values. Supported proof fields become runtime checks for the invariants your proofs assume.
  • Specifications for host-language code. Bind supported Rust, Python, TypeScript, Clojure, PHP, Go, or C functions to Lean specifications, translate them to Lean, and check proof obligations. Each language guide describes its supported subset and verification tools.

The backends share Lean's semantics and are tested against Lean's native C backend. Their supported types, externs and host-language integrations are documented in the language guides.

Proofs are theorems about Lean definitions. The code that runs is generated from those definitions, and tests cover the step from proof to running code: each backend's emitter and runtime (for C, Lean's own C emitter and runtime and leanfran's conversion code) is tested against Lean's native C backend. A proof about a host-language function is a theorem about its translation to Lean, so the translator is outside the proof. The C proof scope and the Go proof scope list what their proofs trust.

Get started

Choose a language above and install its host package and the compiler. Lean 4.35.0 is required for generation and proof checking. One executable, leanfran, compiles to every language; --lang selects the language. With Nix, install the compiler of the release of your host package:

nix profile install 'github:conao3/lean-leanfran/v<version>#leanfran'
leanfran --lang python module generate --module-name MyModule --search-path .lake/build/lib/lean --output-file my_module.py

--lang takes rust, python, typescript, clojure, php, go or c. Take the compiler and the host package from the same release, or both from the same commit of master. The pages on master describe the commands of master: for a release, read the pages of its tag, such as v0.15.0, and put the tag in the URL. Without /v<version>, the URL installs the compiler of master. The package also holds the Lean library of the Go backend and the C support files. The #rust package adds the Cargo CLI and the Aeneas verification tools to the compiler. Without Nix, build the compiler from a checkout of a release tag with lake build leanfran.

The Rust crates require Rust 1.88, and the Cargo CLI cargo-leanfran requires Rust 1.89.

To compile the modules of a Lake package to several languages, list them in the project file leanfran.toml and run leanfran generate. It binds the types the generated modules share. See the generate guide.

Follow the Go quick start to add the Go module and tool to your application, and the C quick start to generate and link a C library. Follow the other language quick starts for their dependencies, project setup, and generation commands.

Embedded Lean blocks

In all seven languages, Lean blocks live in your source files. The host package reads them, and the compiler builds and generates them with three commands:

CommandEffect
leanfran --lang <language> syncBuilds every block with Lake, generates the host-language files, and records them in leanfran.manifest.json.
leanfran --lang <language> checkRuns sync, translates the functions bound to Lean specifications, checks their proofs, and records the results in leanfran.lock.
leanfran --lang <language> statusCompares the sources with leanfran.manifest.json, the generated files, and leanfran.lock without Lean or Lake.

leanfran sync, leanfran check and leanfran status without --lang run the command for every [embed.<language>] table of leanfran.toml in their order, and exit with the largest code. The settings of sync, check and status describe the tables and projects with several languages.

--dir <dir> selects the project directory and defaults to the working directory. The project root is the nearest directory from there upwards with leanfran.toml, or else with the package file of the language (Cargo.toml, pyproject.toml, package.json, deps.edn, composer.json, or go.mod). leanfran --lang <language> <command> --help lists the options of a command. Commit leanfran.manifest.json and leanfran.lock, which are at the project root, and the generated files; C keeps its output directory out of version control because its link settings hold absolute paths. sync keeps each language's Lake workspace in .leanfran/<language>/workspace and writes .leanfran/.gitignore, which excludes that workspace and the lock file .leanfran/lock; commit .leanfran/.gitignore too.

Exit codeMeaning
0Success.
1status printed a stale, missing, or removed line, check or status found an unextracted or failed obligation, or an obligation is not proved under --require proved.
252An argument is invalid.
254The project has an error: a Lean error (reported at the line in your source file), a block the host package cannot read, or a file in the way that leanfran did not generate.
255The environment has an error: the host package, lake, lean, clang, or sha256sum (shasum on macOS) is missing, or the compiler and the host package come from different releases.

Use the compiler and the host package from the same release. When they come from different releases, sync, check and status exit with 255 and one line that names the release to install: the compiler reads the version of the installed host package before it runs it, and the host package stops when an older compiler passes it sync, check or status. sync, check and status run sha256sum on Linux and shasum on macOS and exit with 255 when that command is not on PATH, so CI jobs that run them need it.

Upgrade from 0.14.0

Upgrade to 0.15.0 first, with the commands below, and then follow Upgrade from 0.15.0: later compilers do not recognize the files that 0.14.0 generated. Upgrade the compiler and the host package to the same release (a 0.15.0 compiler with a 0.14.0 host package, or the reverse, exits with 255 and names the release to install), then run the commands below of 0.15.0 once in each project and commit the result. status prints the files that sync will delete as <path>: removed lines. Delete .leanfran/workspace/ and .leanfran/sync.lock if they are in the project.

LanguageRun onceCommit
Pythonleanfran --lang python sync --package <dir> for each package, then check for a package with @model functionsleanfran.manifest.json, .leanfran/.gitignore, leanfran.lock
TypeScriptleanfran --lang typescript sync --package <dir>, then check for a package with model(...) functionsthe deletion of .leanfran/blocks.json, leanfran.manifest.json, .leanfran/.gitignore, leanfran.lock
PHPleanfran --lang php sync, then check for a project with #[Model] functionsthe deletion of each output directory's leanfran.json, leanfran.manifest.json, .leanfran/.gitignore, leanfran.lock
Goleanfran --lang go sync, then check for a module with //leanfran:model functionsthe deletion of each package's leanfran.json, leanfran.manifest.json, .leanfran/.gitignore, leanfran.lock
Cleanfran --lang c sync, then check for a project with LF_MODEL functionsleanfran.manifest.json, .leanfran/.gitignore, leanfran.lock

sync deletes the files named in the deletions above. Commit after check: until then, status reports every function as stale, and in TypeScript the generated modules lack the calls into proved TypeScript functions. In C, sync also deletes <out-dir>/leanfran.manifest.json; if .gitignore lists leanfran.lock, remove that line so that the lock can be committed.

Upgrade from 0.15.0

The options, commands, environment variables and exit codes of every language follow one form. The old names are gone: an old option or command exits with 252. Change the scripts and CI jobs that use them.

In each project:

  1. Upgrade the compiler and the host package to the same release.
  2. Move the settings to leanfran.toml as the settings table says.
  3. Rename the labels, options and theorems of the source table.
  4. Follow the Rust or Clojure migration if applicable. Run leanfran --lang <language> sync, then check for a project with verified functions, and commit the result. Until then, status reports the old entries as stale.
  5. If you link libleanfran.a in C, link the implementations of any functions that replace proved specifications as well. Put implementation object files before -lleanfran, or a static library that holds them after it. For tests that need the original Lean definitions, use LEANFRAN_SPEC_LDLIBS from leanfran.mk, leanfran-spec.pc (pkg-config), or leanfran::spec (CMake) instead. See C linking and replacement.

Settings from 0.15.0

Language0.15.0Now
AllThe options of each languageOne leanfran.toml at the project root with [check], [[require]], [embed.<language>] and [[generate]]. An unknown key or a value of another type exits with 254 and its position
AllThe directory of --dir or --package, or the nearest package fileThe project root is the nearest directory upwards with leanfran.toml, or else with the package file of the language. A directory with neither exits with 254
Python--package <dir> for each packagepaths in [embed.python], or the package src/<name> or <name> of the project name in pyproject.toml; a package removed from them loses its generated files
TypeScript"leanfran": { "tagKey", "option" } of package.jsontag-key and option in [embed.typescript]. Only status detects a change of them; lean(...) at run time does not
PHPextra.leanfran.paths and extra.leanfran.require of composer.jsonpaths in [embed.php], and [[require]]
Gopaths and require of leanfran.config.jsonpaths in [embed.go], and [[require]]
Csources, lean-files, cflags and out-dir at the top level of leanfran.tomlsources, lean-files, cflags and output-dir in [embed.c]
Rust[package.metadata.leanfran] require of Cargo.toml, LEANFRAN_REQUIRE[check] require = "proved". LEANFRAN_REQUIRE has no effect
Clojuredeflean generates the code when it expands, in .leanfran/cache/leanfran --lang clojure sync generates the code in _lean/ next to the namespace, and deflean reads it. Commit the code, and delete cache/, out/ and the Lake files directly in .leanfran/
ClojureNo settings of defleanpaths in [embed.clojure], and [[require]]
Clojureleanfran.typed/check compares a function with its modelleanfran.typed/check-translation, which runs the model that sync generated, for the functions with marks and those that a block names in (clojure f ...). :at metadata of the function lists the types of :at. leanfran.typed/check compares a function with the specifications of its marks :refines, :requires and :ensures
ClojureThe option :throws of checkRemoved. A function that throws fails check, and passes check-translation
[[generate]]out-diroutput-dir

Settings left in an old place of TypeScript, PHP, Go, C or Rust exit with 254 and a message that names the new table.

Sources from 0.15.0

Language0.15.0Now
Clojure:use of deflean:uses. Another unknown key is an error
CThe line imports: <name>, … of a blockuses: <name>, …
TypeScriptThe label returnsNat and the theorems <function>.proof.returnsNatreturns_nat
Every language with ensuresAlso labels with other characters, such as inRangeA label matches [a-z][a-z0-9_]*. refines is reserved, and so is returns_nat in Python, TypeScript and Rust
Every generated fileA first line in the form of each language, none in Clojure and CCode generated by leanfran --lang <language> (generator <N>) from <Lean module>. DO NOT EDIT. in a comment
Files that sync overwrites or deletesFiles with the header of leanfranThe files of the manifest, and those whose first line names the language and a Lean library of its workspace
Go and PHP module generate --output-dirDeletes other generated files of the directoryGo deletes nothing. PHP deletes the files of an earlier run of the same module
CA spec whose public C function has other types than the LF_MODEL functionskipped: in the model test, which passes
CA typedef of size_t in a signature, and a typedef as a resultUInt64, and a result typedef is unextracted

Random tests from 0.15.0

0.15.0Now
Number of inputs256 in Rust, 100 in Clojure, 200 in the others200, or LEANFRAN_RUNS (1 to 2147483647), which counts the inputs that satisfy requires
SeedThe default of the library in Rust, Python, TypeScript and Clojure, 1 in the others1, or LEANFRAN_SEED (0 to 9223372036854775807)
Value out of rangeDifferent in each languageleanfran: <name> must be a decimal number between <least> and <most> (got <value>)
Environment variable of proptestPROPTEST_CASESNo effect
FailureDifferent in each language<id> [refines]: mismatch (seed <seed>, run <n>) or <id> [<label>]: <spec> does not hold (seed <seed>, run <n>), then input: and expected: …, got: … or result:
Name of the specificationDifferent in each languageThe name in the block, such as atLeast
A function or a specification that throws or panicsDifferent in each languagefailed: <exception> as the value of the function, or the spec failed and error: <exception>
Few inputs satisfy requiresDifferent in each languageFails with <id>: only <n> of <m> inputs satisfied requires (seed <seed>) after 100 discarded inputs per run

With PHP, Verify::checkModel takes ?int $runs = null, ?int $seed = null.

Calls to proved implementations

Generated code can call a host function in place of its Lean definition after check proves an eligible refines obligation. Random tests still compare the host function against the original Lean definition. How the generated code finds the host function depends on the language:

LanguageHow it finds the host functionIf the implementation is not present
RustA direct call within the same crateThe implementation must be present at build time
PythonLooks up the function in its module when calledUses the Lean definition if the module or function is not available
TypeScriptImports the host module in the generated codeThe host module must be present at import time
ClojureResolves the Var when calledUses the Lean definition if the Var is unavailable or unbound
PHPLooks up the function or loads its class when calledUses the Lean definition if the function or class is not available
GoCalls the function directly in the same package; other packages register the function when they loadUses the Lean definition until the other package registers its function
CResolves the function when linkingLinking libleanfran.a fails if the definition is missing

Rust from 0.15.0

0.15.0Now
leanfran.lockTOML in the crateThe rust section of the JSON lock in the project root. Remove the TOML lock and regenerate it with leanfran --lang rust check; the compiler rejects a non-JSON lock with exit code 254
Generated code of lean!.leanfran/cache/.leanfran/rust/cache/. Change include of Cargo.toml
Generated Lean packagelean/lakefile.toml, lean/lean-toolchain and lean/LeanRustGen/Remove those generated files. The disposable workspace is .leanfran/rust/workspace/; move additional Lake dependencies into [[require]] and a shared package directory into [lake] packages-dir
Handwritten Leanlean/Proofs/, lean/External.lean, lean/ExternalTypes.leanKeep lean/Proofs/ at the project root, move both external files into it and use the Proofs.External and Proofs.ExternalTypes imports
Function IDs and status rowscrate::<module>::<function>; function and obligation on separate lines<crate_name>::<module>::<function> [<label>]: <state>, and <id>: removed for a function only in the lock
State of an unjudged obligationuncheckedstale
Function without obligationsmodel onlyNo row
A proof file changed since checkNot detectedstatus reports stale. Put the proof gate in CI with leanfran --lang rust check --require proved; it does not run in cargo build, which also no longer shows proof warnings or proof status in rustdoc
Rust version1.881.88, and 1.89 for cargo-leanfran
A spec of other types than its function, a wrong label of ensures, a generic function without instancesA rustc error that stops the buildThe crate builds. check and status give the state that Lean finds, unextracted for a wrong label, and only the test of the function fails (Functions of other types than their specs)

Clojure from 0.15.0

0.15.0Now
Workspace and output.leanfran/, with cached Clojure in .leanfran/cache/Remove the old generated Lake files and cache. Keep .leanfran/clojure/workspace/ out of Git; commit the generated _lean/ next to each namespace and the manifest and lock at the project root
Handwritten LeanLean sources alongside the old Lake workspaceKeep proofs in lean/Proofs/ (module prefix Proofs); put reusable Lean modules in a separate Lake package and list it in [[require]]
Lock and function IDsNo lock-based proof statusThe clojure section of leanfran.lock records function IDs as <namespace>/<function>, shown by leanfran --lang clojure status

Commands, JSON, environment and exit codes from 0.15.0

Commands and options0.15.0Now
Project directory of sync, check and status in Python, TypeScript and PHP--package <dir>, required in Python and TypeScript--dir <dir>, the working directory by default
Rust embedded blocks and proof statuscargo leanfran init, extract, check and statusleanfran --lang rust sync, check and status. Install cargo-leanfran for the compiler to scan and translate Rust
Clojure embedded blocks and proof statusdeflean generates the block on loadleanfran --lang clojure sync, check and status. deflean loads the generated code
Build a Lake package and generate its modules in Rust, TypeScript and Clojureproject generate, TypeScript generateA [[generate]] table of leanfran.toml and leanfran generate
Rust proof checkcrate check --lake-dir <dir>obligations check --lake-dir <dir>
Clojure generationmodule generate-namespace --namespace <ns> --strip-namespace <Name>module generate --clojure-namespace <ns> --namespace <Name>
Clojure ns form--forms-only, --no-forms-only--forms-only
C generationgenerate --roots a,b --out-dir <dir>, which builds the module with Lakelake build <Module>, then lake env leanfran --lang c module generate --roots a b --output-dir <dir>
C librarybuild --out-dir <dir>build --output-dir <dir>
Go package name of module generate--package <name>--go-package <name>
Types defined outside the module in Rust--type-path <Name>=<path>--type-module <Name>=<path>
Lean version of the compiler--lang go --lean-version--version, which prints leanfran <version> (Lean <version>) with and without --lang
Usagehelp, module help--help or -h after leanfran, after --lang <language> and after each command
Rust CLI versioncargo leanfran --version prints cargo-leanfran <version>leanfran --lang rust --version prints leanfran <version> (Lean <version>)
Arguments of a commandRust, Python, TypeScript and Clojure accept the options of another command, and the last value of a repeated option countsAn option that the command does not list, or a repeated one with a single value, exits with 252
JSON of module generate0.15.0Now
Name of the generated module in a jobrust_path, python_path, go_path, php_namespace, ts_rootpath
Types defined outside the jobtype_paths in Rust; type_modules with module, php_namespace, or stringstype_modules, an array of {"namespace", "target"}
Python models in a job"adopt": true in type_modulesmodel_modules, an array of {"namespace", "target"}
A job with an unknown keyIgnored in Rust, Python, TypeScript, PHP and GoExits with 252 and names the job and the key
SummaryCounts or lists, different in each languagemodule, files, functions, externs, skipped, data, and error for a failed job
Environment variable0.15.0Now
Automatic sync of the Python and TypeScript runtimesLEANFRAN_PYTHON_AUTO_SYNC, LEANFRAN_TS_AUTO_SYNCLEANFRAN_AUTO_SYNC
Clojure workspaceLEANFRAN_CLJ_WORKSPACE (earlier development builds: LEANFRAN_CLOJURE_WORKSPACE)No workspace override; use leanfran.toml for the project and Lake settings
Rust buildLEANFRAN_OFFLINE, LEANFRAN_REQUIRENo offline flag or build-time proof gate. The build uses the committed code; opt in to generation with LEANFRAN_AUTO_SYNC=1
Lake executablelake on PATH for Rust lean!LAKE, or lake on PATH
Exit code0.15.0Now
--lang <language> without a command0, and the usage on standard output (252 in C)252, and the usage on standard error
status with a failed or unextracted function0 without --require proved1
--modules or --module-name names a module that is not in the search path252254
A missing directory252 for generate --dir and the Rust --lake-dir, 255 for the C build254
leanfran generate with a failed lake build255254
leanfran generate with an invalid leanfran.toml252254
Several failed --batch jobsThe first code in Python, TypeScript, PHP and GoThe largest code
An error such as an output file that cannot be written, in Clojure254255
Rust CLI with invalid argumentscargo leanfran exits with 2leanfran --lang rust exits with 252
Rust CLI with a project or environment errorcargo leanfran exits with 1leanfran --lang rust exits with 254 or 255
Rust status with a stale, failed, unextracted or removed functioncargo leanfran status exits with 0leanfran --lang rust status exits with 1

Messages start with leanfran: in every language, where 0.15.0 writes leanfran --lang <language>:, leanfran-go:, cargo leanfran: and others. Errors with a position start with <file>:<line>:<column>: error:, also for a function that cannot be translated (error: unextracted <id>: <message>).

Documentation

LanguageQuick startFull guideExamples
RustSetup and first blockTypes, verification and CLIRust samples
PythonSetup and first blockModels, verification and CLIPython samples
TypeScriptSetup and first blockSchemas, verification and CLITypeScript samples
ClojureSetup and first blockTypes, verification and CLIClojure samples
PHPSetup and first blockEmbedding, types, verification and CLIPHP samples
GoSetup and first blockEmbedding, types, verification and CLIGo samples
CSetup and generationEmbedding, types, verification and linkingC samples

Contribution

New language support is welcome! Use the latest Claude Opus, OpenAI Sol, or a model with a comparable score on the Artificial Analysis Intelligence Index, and ask your coding agent to follow this guide:

Read docs/add-language.md and add support for <LANGUAGE> to leanfran.

Development

The repository has a shared Nix environment and Lean toolchain, with language-specific source and packages under langs/. Use .#php and .#php85 for PHP 8.4 and 8.5, and .#go and .#go126 for Go 1.27 and 1.26.

nix develop
make check
make check BACKENDS=Python

See CONTRIBUTING.md for build targets, formatting, packaging and the coordinated release process. Implementation notes live in docs/; maintenance tools live in maint/.

License

Apache-2.0.

Can you improve this documentation? These fine people already did:
conao3, Naoya Yamashita & github-actions[bot]
Edit on GitHub

cljdoc builds & hosts documentation for Clojure/Script libraries

Keyboard shortcuts
Ctrl+kJump to recent docs
←Move to previous article
→Move to next article
Ctrl+/Jump to the search field
× close