Making Stand Alone Programs With Lean 4
lean --run checks a file and then runs it in an interpreter. That suits the examples in this book, but a tool you hand to someone else should be one native program that runs with no Lean installed. Lean 4 builds such programs ahead of time. The compiler turns each Lean module into C, a C compiler turns the C into machine code, and the linker joins it with the Lean runtime into one executable. The Lean toolchain ships its own clang, so you need no other C compiler.
The runtime does not use a tracing garbage collector. Each value carries a reference count, and the runtime frees a value when its count drops to zero. When a function holds the only reference to an array or a map, Lean updates it in place, as the summarizer chapter showed for Std.HashMap. Sebastian Ullrich and Leonardo de Moura describe the design in the paper “Counting Immutable Beans: Reference Counting Optimized for Purely Functional Programming”. In practice, a compiled Lean program has no collector pauses and needs no large runtime.
This chapter builds programs in three ways: with Lake, by hand with lean -c and leanc, and as a Lake project that calls C code of its own.
Four Steps With Lake
Chapter 18 introduced Lake. Here are the steps again, with what each one makes.
- Create a project that builds an executable:
1 lake new my_app
2 cd my_app
- Write the entry point. A program needs a
mainin theIOmonad.lake newwrites thisMain.lean:
1 import MyApp
2
3 def main : IO Unit :=
4 IO.println s!"Hello, {hello}!"
hello comes from MyApp/Basic.lean, a library module that holds def hello := "world". Keep most of your code in the library and keep Main.lean small. Then a test program or a second executable can import the same code.
- Build the native binary:
1 $ lake build
2 ✔ [7/8] Built Main:c.o (48ms)
3 ✔ [8/8] Built my_app:exe (90ms)
4 Build completed successfully (8 jobs).
lake build turns each module into C, compiles each C file to an object file, and links the objects into one program.
- Run it:
1 $ ./.lake/build/bin/my_app
2 Hello, world!
lake exe my_app builds the program if needed and then runs it.
What the Build Leaves Behind
Lake writes the C for each module under .lake/build/ir/. Here is the start of MyApp/Basic.c:
1 // Lean compiler output
2 // Module: MyApp.Basic
3 // Imports: public import Init public meta import Init
4 #include <lean/lean.h>
Further down, the string "world" sits in a static lean_string_object, built at compile time. You never need to edit this C, but it helps to know it exists. When a program is slow, the C shows what the compiler made of your code.
The program is at .lake/build/bin/my_app. On my Mac it is 2.3 MB, and otool -L lists only two shared libraries, both part of macOS:
1 $ otool -L .lake/build/bin/my_app
2 .lake/build/bin/my_app:
3 /usr/lib/libc++.dylib (compatibility version 1.0.0, current version 1.0.0)
4 /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1356.0.0)
The Lean runtime, the parts of the standard library the program uses, and your code are all inside the one file. On Linux, run ldd in place of otool -L.
Building One File by Hand
Lake runs two tools you can also call yourself. lean -c writes the C for one file, and leanc compiles and links it with the Lean runtime:
1 $ lean -c Bayes.c Bayes.lean
2 $ leanc -O3 -o bayes Bayes.c
3 $ ./bayes
4 Prior: has-disease: 0.0100, healthy: 0.9900
5 After 1st (+): has-disease: 0.1610, healthy: 0.8390 -> MAP: healthy
6 After 2nd (+): has-disease: 0.7848, healthy: 0.2152 -> MAP: has-disease
Bayes.c has about 1,600 lines for a 56-line Lean file. Most of them are copies of list functions such as foldl that the compiler made for the types in this file. This path works for one file with no imports outside the standard library. Use Lake for anything larger, because it tracks which modules changed and rebuilds only those.
Start-Up Time
The interpreter checks the whole file before it runs it. A compiled program skips that step. I timed three of the book’s programs, built with the source_code/lakefile.toml from chapter 18, and took the median of ten runs:
| Program | lean --run |
Compiled binary |
|---|---|---|
BM25.lean |
201 ms | 3.2 ms |
Hopfield.lean |
205 ms | 4.5 ms |
SymbolicMath.lean |
228 ms | 5.1 ms |
The compiled programs start about fifty times faster. For a tool that a script calls many times, that matters. For the network programs it matters little, because they spend most of their time waiting for a reply.
A Command-Line Tool That Calls C
File: source_code/standalone/
The rest of this chapter builds textstats, a small tool that reads text files and prints word counts. It shows the parts a real tool needs: command-line arguments, an exit code, errors written to stderr, and two functions written in C. The project has this layout:
1 standalone/
2 lakefile.lean
3 lean-toolchain
4 Main.lean
5 TextStats.lean
6 TextStats/Basic.lean
7 c/native.c
8 sample.txt
The C code
Lean calls C through the @[extern] attribute. A C function that Lean calls must use the types in lean/lean.h. This file has one pure function and one IO action:
1 #include <lean/lean.h>
2 #include <unistd.h>
3
4 /* FNV-1a, 64-bit. The string is borrowed (@&), so no lean_dec_ref. */
5 uint64_t ts_fnv1a(b_lean_obj_arg s) {
6 const unsigned char *p = (const unsigned char *)lean_string_cstr(s);
7 size_t n = lean_string_size(s) - 1; /* size counts the NUL */
8 uint64_t h = 14695981039346656037ULL;
9 for (size_t i = 0; i < n; i++) {
10 h ^= p[i];
11 h *= 1099511628211ULL;
12 }
13 return h;
14 }
15
16 /* An IO action: takes the world token, returns an IO result. */
17 lean_obj_res ts_hostname(lean_obj_arg world) {
18 char buf[256];
19 if (gethostname(buf, sizeof buf) != 0) {
20 return lean_io_result_mk_error(
21 lean_mk_io_user_error(lean_mk_string("gethostname failed")));
22 }
23 buf[sizeof buf - 1] = '\0';
24 return lean_io_result_mk_ok(lean_mk_string(buf));
25 }
ts_fnv1a computes the 64-bit FNV-1a hash of a string. A Lean String is UTF-8 bytes with a final NUL, so lean_string_cstr gives a C string and lean_string_size counts the bytes, NUL included. A UInt64 in Lean is a plain uint64_t in C, with no boxing.
ts_hostname calls the POSIX function gethostname. A Lean IO action compiles to a C function that takes one extra argument, the “world” token, and returns an IO result. lean_io_result_mk_ok wraps a value. lean_io_result_mk_error wraps an error that Lean code can catch with try.
The Lean library
TextStats.lean holds one line, import TextStats.Basic. TextStats/Basic.lean holds the code:
1 import Std.Data.HashMap
2
3 namespace TextStats
4
5 -- Lowercased runs of letters and digits
6 def tokenize (text : String) : List String :=
7 let init : List String × List Char := ([], [])
8 let (words, acc) := text.toList.foldl (init := init)
9 fun (words, acc) ch =>
10 if ch.isAlphanum then (words, ch.toLower :: acc)
11 else if acc.isEmpty then (words, acc)
12 else (String.ofList acc.reverse :: words, [])
13 let words :=
14 if acc.isEmpty then words else String.ofList acc.reverse :: words
15 words.reverse
16
17 -- The n most frequent words, ties broken alphabetically
18 def topWords (words : List String) (n : Nat := 5) : List (String × Nat) :=
19 let counts : Std.HashMap String Nat :=
20 words.foldl (init := ∅) fun m w => m.insert w (m.getD w 0 + 1)
21 let sorted := counts.toList.mergeSort fun a b =>
22 a.2 > b.2 || (a.2 == b.2 && a.1 ≤ b.1)
23 sorted.take n
24
25 @[extern "ts_fnv1a"]
26 opaque fnv1a (s : @& String) : UInt64
27
28 @[extern "ts_hostname"]
29 opaque hostname : IO String
30
31 end TextStats
tokenize is the function from the BM25 chapter. topWords counts words in a hash map, sorts by count, and breaks ties by name so the output does not depend on hash order.
The last four lines bind the C functions:
@[extern "ts_fnv1a"]tells the compiler to call the C symbolts_fnv1ain place of a Lean body.opaquedeclares a constant with no definition that Lean can see. Lean cannot compute it during type checking, so#eval fnv1a "x"fails in the editor withCould not find native implementation of external declaration 'fnv1a'. Only the linked program can call it.@&marks the argument as borrowed. The C function may read the string but must not free it. Without@&, the C function owns the argument and must calllean_dec_refon it before it returns.hostname : IO Stringmakes Lean pass the world token and expect an IO result, which matches the C signature.
Give every C function that has a side effect an IO type. Lean treats a function without IO as pure, so the compiler may cache its result or skip a call whose result it does not use.
The entry point
1 import TextStats
2 open TextStats
3
4 def report (path : String) : IO Unit := do
5 let text ← IO.FS.readFile path
6 let words := tokenize text
7 IO.println s!"{path}"
8 IO.println s!" words: {words.length}, distinct: {words.eraseDups.length}"
9 let hash := String.ofList (Nat.toDigits 16 (fnv1a text).toNat)
10 IO.println s!" fnv1a: {hash}"
11 for (w, n) in topWords words do
12 IO.println s!" {n} {w}"
13
14 def main (args : List String) : IO UInt32 := do
15 if args.isEmpty then
16 IO.eprintln "usage: textstats FILE..."
17 return 2
18 IO.println s!"host: {← hostname}"
19 let mut status : UInt32 := 0
20 for path in args do
21 try report path
22 catch e =>
23 IO.eprintln s!"textstats: {path}: {e}"
24 status := 1
25 return status
main has the type List String → IO UInt32. The list holds the command-line arguments, without the program name. The UInt32 becomes the exit code, so a shell script can test it. The tool returns 2 for a usage error and 1 when any file fails. try ... catch keeps going after a bad file, and IO.eprintln writes the message to stderr.
The Lake file
The TOML format from chapter 18 cannot compile C. A lakefile.lean can, because it is a Lean program that Lake runs:
1 import Lake
2 open System Lake DSL
3
4 package textstats
5
6 lean_lib TextStats
7
8 -- Compile c/native.c with the Lean headers on the include path.
9 target native.o pkg : FilePath := do
10 let oFile := pkg.buildDir / "c" / "native.o"
11 let srcJob ← inputTextFile <| pkg.dir / "c" / "native.c"
12 let weakArgs := #["-I", (← getLeanIncludeDir).toString]
13 buildO oFile srcJob weakArgs #["-fPIC", "-O2"] "cc"
14
15 @[default_target]
16 lean_exe textstats where
17 root := `Main
18 moreLinkObjs := #[native.o]
target native.odefines a build step that produces a file.inputTextFilemakes Lake tracknative.c, so an edit to it causes a rebuild.getLeanIncludeDirfinds the directory that holdslean/lean.hfor the current toolchain.buildOruns the C compiler, here the systemcc. Lake passes the “weak” arguments to the compiler but leaves them out of the hash it uses to decide on rebuilds, which suits paths that differ between machines.moreLinkObjsadds the object file to the link step of the executable.
Older Lake files use extern_lib for this. The Lake README for 4.35.0 marks extern_lib as deprecated in favor of a target with moreLinkObjs.
Running it
1 $ cd source_code/standalone
2 $ lake build
3 ✔ [2/9] Built textstats/native.o (54ms)
4 ...
5 ✔ [9/9] Built textstats:exe (97ms)
6 Build completed successfully (9 jobs).
7 $ ./.lake/build/bin/textstats sample.txt
8 host: Marks-MacBook-Air.local
9 sample.txt
10 words: 48, distinct: 33
11 fnv1a: 38471d4670abe8e5
12 5 the
13 3 a
14 3 c
15 3 program
16 3 to
17 $ ./.lake/build/bin/textstats missing.txt
18 host: Marks-MacBook-Air.local
19 textstats: missing.txt: no such file or directory (error code: 2)
20 file: missing.txt
21 $ echo $?
22 1
I checked the hash against a few lines of Python that compute FNV-1a over the same bytes. Both print 38471d4670abe8e5. I also copied the binary to another directory and ran it there. It needs nothing from the project.
Linking a System Library
Many tools need a C library, such as libcurl for HTTP. In principle you add the library to the link step with moreLinkArgs:
1 lean_exe curlver where
2 root := `Main
3 moreLinkObjs := #[shim.o]
4 moreLinkArgs := #["-lcurl"]
Here shim.o comes from a C file that calls curl_version() and returns the result with lean_mk_string, built with a target like native.o above.
On my Mac (macOS 27, Lean 4.35.0) this failed. Lean links with its own clang and ld64.lld. First, that linker does not search the macOS SDK, so it reported library not found for -lcurl. When I added the SDK path, it could not read the SDK’s .tbd library stubs and reported malformed file.
Two changes fixed it. The environment variable LEAN_CC tells Lean which C compiler to link with, so LEAN_CC=cc uses Apple’s tools. Apple’s linker cannot find Lean’s bundled libgmp.a and libuv.a, so add the toolchain’s lib directory, which lean --print-prefix names:
1 moreLinkArgs := #["-L/Users/you/.elan/toolchains/leanprover--lean4---v4.35.0/lib", "-lcurl"]
1 $ LEAN_CC=cc lake build
2 Build completed successfully (5 jobs).
3 $ ./.lake/build/bin/curlver
4 libcurl/8.7.1 SecureTransport (LibreSSL/3.3.6) zlib/1.2.12 nghttp2/1.69.0
The path in that line holds a user name and a Lean version, so do not commit it. I keep it out of the book’s standalone project, which needs no outside library. I have not tested this on Linux.
A program that links libcurl depends on a shared library, so otool -L now lists /usr/lib/libcurl.4.dylib too. macOS includes it, so the binary still runs on a stock Mac.
Shipping the Binary
A Lean binary runs only on the operating system and CPU type it was built for. To ship for Apple silicon Macs, Intel Macs, and Linux, build on each one, or on a CI machine of each kind. lake new writes a GitHub Actions workflow that builds the project, and you can extend it to upload the binaries. I tested the programs in this chapter only on the Apple silicon Mac that built them.
To keep your users on the same compiler, commit lean-toolchain. elan reads it and installs that exact Lean version on the build machine.
Try This
- Add a
--top Noption totextstats. Parse it fromargsand passNtotopWords. - Write
fnv1ain Lean withfoldlover the bytes oftext.toUTF8. Use^^^for XOR andUInt64arithmetic, which wraps at 2^64 as the C code does. Check that both versions print the same hash. - Build one of the book’s network programs, such as
Gemini.lean, as a Lake executable, and time it againstlean --run. Most of the run time is the network wait, so the gap is smaller than in the table above.