leanfran --lang c builds Lean blocks in C sources and generates a C11 API for definitions in a Lean 4.35.0 Lake library. The generated header also works with C++.
Install the compiler with nix profile install 'github:conao3/lean-leanfran/v<version>#leanfran', where <version> is a release. To build from a clone with elan, run lake build leanfran at the repository root and add .lake/build/bin to your PATH. Use Lean 4.35.0 and a C compiler in the consuming workspace. The clang bundled with an elan toolchain does not find the system C headers on NixOS, so build there inside nix develop .#c. The linking examples use pkg-config, GNU Make, or CMake.
Put a Lean block in a comment of a C file, and the sources in leanfran.toml:
/* leanfran:lean arith
def twice (n : UInt64) : UInt64 := n + n
theorem twice_eq (n : UInt64) : twice n = n + n := rfl
*/
#include "arith.h"
#include <inttypes.h>
#include <stdio.h>
int main(void) {
uint64_t out;
if (arith_init(NULL) != LF_OK || arith_twice(21, &out, NULL) != LF_OK)
return 1;
printf("%" PRIu64 "\n", out);
return 0;
}
[embed.c]
sources = ["*.c"]
$ leanfran --lang c sync
leanfran: 1 blocks checked and generated
$ cc -std=c11 main.c $(pkg-config --cflags --libs leanfran/leanfran.pc) -o demo
$ ./demo
42
sync also prints the progress of Lake.
In a Lake workspace with a library that contains Pricing/Core.lean, define a function to call from C.
namespace Pricing
def total (quantity unitPrice : UInt64) : UInt64 :=
quantity * unitPrice
end Pricing
From that workspace, build the module, then generate and build the bindings.
lake build Pricing.Core
lake env leanfran --lang c module generate --module-name Pricing.Core --roots Pricing.total \
--prefix pricing --output-dir out
lake env leanfran --lang c build --output-dir out
Save this consumer as main.c in the Lake workspace.
#include "pricing.h"
#include <inttypes.h>
#include <stdio.h>
int main(void) {
lf_error error = {0};
uint64_t total;
if (pricing_init(&error) != LF_OK ||
pricing_total(3, 1200, &total, &error) != LF_OK) {
fprintf(stderr, "%s\n",
error.message ? error.message : "Lean call failed");
lf_error_clear(&error);
return 1;
}
printf("%" PRIu64 "\n", total);
return 0;
}
cc -std=c11 main.c $(pkg-config --cflags --libs out/pricing.pc) -o pricing-demo
./pricing-demo
The program prints 3600. With no --prefix, the prefix is the last component of the module
name in snake case. For Pricing.Core, use core.h, core_init, and out/core.pc.
samples/ has pricing, which generates and links an API from a Lake workspace, and verified-clamp, which embeds a block and proves a C function.
leanfran --lang c sync reads Lean from block comments in C files, builds them in a Lake workspace under .leanfran/c/workspace, and writes the headers, one static library, and link settings to an output directory. The C project does not need to be a Lake project. sync writes .leanfran/.gitignore, which ignores the workspace and the lock file that keeps two commands from running at once.
/* leanfran:lean pricing
def total (items : Array (UInt32 × UInt32)) : Nat :=
items.foldl (fun acc (qty, price) => acc + qty.toNat * price.toNat) 0
theorem total_empty : total #[] = 0 := rfl
*/
#include "pricing.h"
A block starts at a /* leanfran:lean <name> line and ends at the next */. The name is an ASCII C identifier other than lf or leanfran, in any letter case. It becomes the C prefix and the Lean module LeanfranBlocks.<name>. A line uses: <name>, … directly after the first line names other blocks, and the block uses their definitions by their unqualified names. The definitions of all blocks share one namespace, so two blocks cannot define the same name. sync reports such a pair at the second block, as in src/b.c:1:1: error: Lean blocks 'a' (src/a.c:1) and 'b' both define 'spec'; …. Put a block's helper definitions in a namespace to keep their names apart. The block's Lean code can begin with import lines for modules of the [[require]] packages and for LeanCLib.C, which defines the C operations and C.Status used in Verifying C functions. A Lean string that needs */ can write it as "*" ++ "/".
Mark a struct with LF_STRUCT(<block>) and its fields with LF_FIELD("<constraint>", …) from leanfran.h. sync adds a Lean structure with the same name before the block. Each constraint becomes a proof field named <field>_<key>.
#include "leanfran.h"
typedef struct LF_STRUCT(pricing) order {
uint32_t qty LF_FIELD("ge=1", "le=1000");
int64_t price_cents LF_FIELD("ge=0");
lf_str sku LF_FIELD("min_len=1", "max_len=8");
} order;
typedef struct {
order *items;
size_t len;
} order_list;
typedef struct LF_STRUCT(pricing) {
order_list orders LF_FIELD("max_len=4");
bool express;
} cart;
def cartTotal (c : cart) : Int :=
c.orders.foldl (fun acc o => acc + Int.ofNat o.qty.toNat * o.price_cents.toInt) 0
| Constraint | Field types | Lean proposition |
|---|---|---|
ge=n, gt=n, le=n, lt=n | Integer scalars, lf_nat, lf_int | The field's integer value compared with n |
min_len=n, max_len=n | lf_str, lf_byte_array, lf_float_array, arrays | String.length or size compared with n |
Fields use bool, the fixed-width integer types, size_t, float, double, lf_str, lf_nat, lf_int, lf_byte_array, lf_float_array, another LF_STRUCT struct, or a struct with exactly T *items and size_t len for Array T. Any other field type, an unknown block, or a constraint that does not fit the field type stops sync with status 254 at the field's position.
Declare LF_STRUCT structs in a header that includes leanfran.h. The block's generated header includes that header by a path relative to the output directory and defines <prefix>_<name> as an alias, so the C program passes its own struct to the generated functions. The wrappers check each constraint and return LF_INVALID with the type and proof field, as in Invalid order.qty_ge.
LF_STRUCT and LF_FIELD expand to clang annotate attributes and to nothing for other compilers. sync, status, and check read the files with LF_STRUCT or LF_MODEL using clang -Xclang -ast-dump=json, so a project that uses either needs clang on PATH. clang takes a file's flags from the first entry for that file in compile_commands.json in the project root. A header uses the flags of the first entry that includes it. Files without an entry use cflags. clang also searches the output directory for headers, so a C file can include a block's generated header by name.
uint32_t for Char and size_t for USize. C passes scalar and lf_str arguments by value. lf_str borrows a UTF-8 byte range on input and owns an allocated, NUL-terminated byte range on output. The length counts bytes, including any embedded zero bytes. An input that is not valid UTF-8, such as a truncated sequence, an overlong encoding, or an encoded surrogate, returns LF_INVALID, as an invalid Char does.Nat and Int use lf_nat and lf_int. Initialize small values with lf_nat_from_u64 or lf_int_from_i64. Use _from_dec to parse a decimal string and _to_dec to obtain an owned lf_str. lf_nat_to_u64 and lf_int_to_i64 return false for values outside their respective ranges.Fin n uses an alias for lf_nat, and Subtype uses an alias for the C type of its underlying value.tag and an as union. The tag selects the active union member. Recursive fields that would make a C value infinitely large use pointers. A structure or inductive with one constructor and one non-proof field keeps its C shape, and its conversion follows Lean's representation of the value as that field alone.Option α uses a struct with has_value and value. Array α and List α use a typed items pointer and a len element count. An empty sequence has length zero. ByteArray uses lf_byte_array and FloatArray uses lf_float_array (double *items) with the same fields. Prod α β uses a pair struct with fst and snd.Except ε α in a return type writes the success value to out. An error returns LF_EXCEPT and stores a UTF-8 JSON representation of the payload in lf_error.message when an error pointer is provided. An enclosing IO failure returns LF_IO.Task and Thunk, are not public types. Generation stops with status 254 when a definition in --roots uses one, naming the definition and, for a nested use, the field. Without --roots, generation skips such definitions and lists them with the same reason in skipped of the summary, or as leanfran: skipped <name>: <reason> with --output text.Public function names use the module prefix and the snake case form of the final component of the Lean declaration name. Type names use the module prefix, the snake case form of the qualified Lean name, and the concrete type arguments. Pairs use pair as the base name. Generated identifiers that match a C keyword get a trailing underscore. A collision stops generation. Repeat --rename Lean.Name=c_name to choose names for individual functions, types, constructors, or fields using their qualified Lean names.
Generated functions borrow inputs, including all pointed-to data, for the duration of the call. Pass a pointer to a borrowed value for each composite argument. For output, provide writable storage and release any owned value in that storage before a new call writes to it.
On a successful call, the caller owns the output's nested allocations. Pass the output to the generated <type>_free function to release its nested strings, arrays, and recursive fields and clear the value in place. The function leaves the outer storage available to its owner. Use lf_nat_free, lf_int_free, lf_byte_array_free, or lf_float_array_free for the common types and lf_free(out.ptr) for a top-level lf_str.
Call <type>_valid(&value, &error) to check a C value before passing it to an exported function. The generated wrappers also check their inputs, including values nested in arrays, records, and variants. A failed Lean invariant returns LF_INVALID and identifies the Lean type and proof field. Generation exits with status 254 if it cannot synthesize a computable Decidable instance.
The generated header declares <type>_to_json(&value, &json, &error) and <type>_from_json(data, len, &value, &error). Free the encoded JSON with lf_free(json.ptr) and free decoded values using the same ownership rules as other outputs. The decoder takes a UTF-8 byte range and checks the same invariants when it constructs the Lean value. For example, when Pricing.total exposes UInt64, pricing_uint64_to_json encodes the result as a quoted decimal string.
Records use Lean field names, enums use constructor names, and variants with payloads use objects with a single constructor key. A record field named field? is emitted as field when its option holds a value. none encodes as null, so nested options with the same JSON representation decode to the outer none. Nat and Int use decimal JSON numbers, and the decoder also reads integral numbers such as 1.0 and 1e2. UInt64 and USize use quoted decimals without a sign or leading zeros, the strings that the pattern of the JSON Schema accepts. The generated JSON parser accepts up to 1024 nested levels. For integer fields, scientific notation can append up to 10000 decimal zeros. Decimal digits can be supplied directly for larger integers.
Generation writes <prefix>.schema.json in draft 2020-12. A single API type appears at the document root. With multiple API types, select the type in $defs using the part of the function name before _to_json. The schema follows the Go backend's rules for field bounds and recursive references.
A value handle is an owned reference to a Lean value. Use handles to pass a value through several calls while keeping its Lean representation. The generated header declares a <type>_ref struct for each type. For built-in types the name includes the module prefix, type_, and a Lean type stem, such as pricing_type_uint64_ref or pricing_type_string_ref. Use a zero-initialized struct for an empty handle and treat its obj field as opaque.
| Operation | Ownership |
|---|---|
<type>_ref_from(&value, &handle, &error) | Borrows the C value and returns an owned handle. |
<type>_ref_get(handle, &value, &error) | Borrows the handle and returns a C value with the usual output ownership. |
<type>_ref_retain(handle) | Returns another owned reference to the same Lean value. |
<type>_ref_release(handle) | Releases one owned reference. An empty handle is safe to release. |
<prefix>_<function>_ref(..., &handle, &error) | Borrows its handle arguments and returns an owned handle on success. |
<prefix>_<function>_ref_take(..., &handle, &error) | Transfers one owned reference per argument to Lean and returns an owned handle on success. An exclusive array can reuse its storage. |
Assigning a handle struct copies its pointer. Call _ref_retain whenever two owners need separate references. Release an owned output before reusing its storage. Unit-returning functions keep the status-only signature. _ref_take checks module initialization, empty inputs, and the output pointer before consuming any arguments. Once Lean runs, it consumes the arguments even if it returns LF_EXCEPT or LF_IO. Discard the transferred input handles and use the output only on success. Use an input handle’s own storage for the output when the types match and you intend to replace the transferred reference. If Lean returns an error, clear that slot before using it again.
<prefix>_init attaches its caller to the Lean runtime. After module initialization, call lf_thread_attach() on each additional C thread before it uses Lean. Call lf_thread_detach() when the thread is done with Lean, after releasing its references. Repeated attach calls on the same thread need a single detach.
Call <type>_ref_share(handle) on the owning thread before publishing a handle to another thread. Publish it with ordinary thread synchronization, such as passing it to pthread_create. Sharing marks the Lean value and its reachable objects for atomic reference counting. The caller still owns the same reference. Keep a reference alive while another thread borrows it, or transfer or retain a reference for that thread to release.
The generated headers and C sources start with the line
/* Code generated by leanfran --lang c (generator 3) from Pricing.Core. DO NOT EDIT. */
The link settings have the line after #, and the generated Lean files after --. from <Lean module> is absent in files that belong to no module, such as leanfran.h and the link settings. JSON files, .txt files and libraries have no such line.
The output directory contains <name>.h for each block, leanfran.h, libleanfran.a, leanfran.pc, leanfran.mk, leanfran-config.cmake, and leanfran-check.sh, and with LF_MODEL functions libleanfran_spec.a, leanfran-spec.pc, and the random test. sync writes leanfran.manifest.json in the project root with the hash of each block and the files it generated; commit it with the sources, together with the leanfran.lock that check writes. The link settings in the output directory hold absolute paths, so keep the output directory out of version control and run sync in each checkout. sync replaces only files that it generated, and stops with status 254 before it would overwrite any other file. leanfran_init initializes every block, and each <name>_init calls it. Link with the generated settings as described in Link the library, using leanfran as the package name.
A Makefile that includes leanfran.mk compares the Lean blocks with the generated files before make builds anything, and so does each build of a CMake project that links leanfran::leanfran. Both run leanfran-check.sh, which reads the rows of leanfran --lang c status. If the content of a block or a struct of LF_STRUCT in it has changed, or a generated file is missing, the build stops.
leanfran: the Lean block clamp is out of date; run 'leanfran --lang c sync'
With LEANFRAN_AUTO_SYNC=1, the build runs leanfran --lang c sync and continues with the new files. A change of a setting is reported by status only.
A build needs neither the compiler nor Lean's commands. Without the compiler (LEANFRAN_CLI, or leanfran on PATH), or without clang when the sources contain LF_STRUCT or LF_MODEL, leanfran-check.sh compares the text of the Lean blocks, of the lean-files, and of the headers that the LF_STRUCT structs are read from with the text that the last sync read. The rest of a C source can change. When the text differs, or a file of the output directory is missing, the build stops and LEANFRAN_AUTO_SYNC=1 has no effect. The comparison uses find, sed, sort, awk, and sha256sum or shasum. The program links Lean's runtime libraries from the toolchain directory that sync used.
leanfran: the text of the Lean blocks is not that of the last sync, and comparing the blocks needs the compiler `leanfran` on PATH (or set LEANFRAN_CLI); run 'leanfran --lang c sync'
The goals clean, distclean, mostlyclean and maintainer-clean do not compare. With pkg-config, run sh leanfran/leanfran-check.sh before the build.
Call <prefix>_init before using the exported functions. Initialization runs once per generated module, and callers may invoke its initializer concurrently. Each wrapper returns an lf_status and writes its result through the output pointer on success. An IO Unit wrapper takes no output pointer, and failed Lean I/O returns LF_IO.
The Lean runtime and its modules exist once per process. When a program links the output of several module generate runs, the first <prefix>_init that succeeds ends Lean's initialization phase, so the initialize declarations of the modules that later initializers run see IO.initializing as false. A failed initialization leaves the modules it reached partly initialized, so after one <prefix>_init returns an error, every later <prefix>_init in the process returns the same status and message without running Lean code. To combine several Lean modules in one program, embed them as blocks and call leanfran_init, which initializes all blocks before ending the initialization phase (Lean blocks).
Initialize each lf_error with {0} and call lf_error_clear to release its message before reusing it. Pass NULL when you only need the status code.
The default build produces lib<prefix>.a. Use leanfran --lang c build --shared --output-dir out for lib<prefix>.so on Linux or lib<prefix>.dylib on macOS, linked with libleanshared. The build also writes link settings for all three build tools.
out/pricing.pc in the command above. For a path containing spaces, get the flags through your build system so it can preserve argument boundaries.out/pricing.mk. Compile with $(PRICING_CFLAGS) and put $(PRICING_LDLIBS) after the source or object arguments.find_package(pricing CONFIG REQUIRED) and target_link_libraries(pricing-demo PRIVATE pricing::pricing). Set -Dpricing_DIR=/absolute/path/to/out when configuring.The generated settings use absolute paths to the output directory and the active Lean toolchain. Run generation and build again if either moves. Keep the shared library and its Lean runtime dependencies available at the recorded paths when running a dynamically linked executable.
The generated <prefix>.c holds field offsets and constructor numbers of the Lean version that generated it. It includes <lean/version.h> and stops compilation with #error when you compile it against the headers of another Lean version.
Inspect leanc --print-ldflags and the generated link settings to see which GMP your build uses. The Linux Lean distribution installed by elan can link GMP statically. To link against shared GMP, use the project's Nix Lean environment with nix develop .#c and regenerate and build the bindings with that toolchain.
GMP is available under LGPLv3 or GPLv2. If you distribute a statically linked executable under the LGPLv3 terms for GMP, see section 4 for notices, license texts, and the materials and terms that let recipients relink the executable with a modified GMP. The section also describes the shared-library option. GMP licensing and LGPLv3 section 4.
On an Intel Core i5-8400 with the standard Nix C development shell and Lean 4.35.0, summing an array of 100 line items took 7.485 µs per call through the ordinary public function and 0.078 µs per call through the value handle function. Each timing averages 100,000 calls. Each row contains a string, a quantity, and a price. The handle timing reuses an input handle created before the timed loop and includes reading and releasing each result handle. Run nix shell nixpkgs#gnumake -c make check BACKENDS=C from the repository root to run the same benchmark.
Set LEANFRAN_CLI to select the compiler executable used by host tools (default: leanfran on
PATH). Set LAKE to select the Lake executable used by the compiler (default: lake on PATH).
leanfran --lang c --version prints the release and the Lean version, as in leanfran <version> (Lean 4.35.0). leanfran --lang c --generator-version prints the version of the generated code and the C translation; sync, status, and check record it with the Lean version, so outputs and proof results stay current across releases that keep it. leanfran --lang c --help lists the commands and the exit codes, and leanfran --lang c <command> --help lists the options of a command.
leanfran --lang c sync writes the headers, the library, and the link settings. A failed proof stops the build, and a sorry gives a warning; check reports it. Lean diagnostics use the C file and line, as in src/pricing.c:12:5: error: (lean block pricing, Lean 3:4) …. A failure leaves the previous outputs unchanged.leanfran --lang c status prints <block>: stale for each block whose Lean changed and for every block after a change of [embed.c], [[require]], or [check] in leanfran.toml, the LF_STRUCT inputs, or the compiler's generator version or Lean version, <block>: missing <file> for a missing block header, c: missing <file> for another missing output file, and <block>: removed for a block that is gone. It then prints the saved state of each LF_MODEL obligation, as described in Obligations and proof status, and exits with status 1 when it prints a block row or a stale, failed, or unextracted obligation. Otherwise it exits with status 0. status runs neither Lean nor Lake.leanfran --lang c check runs sync and checks the theorems of the blocks and the LF_MODEL obligations described in Verifying C functions.sync, status, and check hash the blocks and inputs with sha256sum, or shasum -a 256 on macOS, so put that command on PATH. Without it they exit with 255.module generate and buildmodule generate reads the .olean files of built modules from LEAN_PATH, which lake env sets, and from the directories of --search-path. --import adds modules; Lean's C emitter compiles the functions, so their @[csimp] lemmas do not apply. Both commands use the Lean toolchain of LEAN_SYSROOT, or of the lean on PATH when it is not set. build runs in the Lake workspace of the working directory.
Pass fully qualified declarations separated by spaces to --roots. Omit it to select supported public definitions declared in the module. The default prefix is the last component of the module name in snake case, such as core for Pricing.Core. Use --rename <Name>=<c_name> ... to choose the C names of functions, types, constructors, and fields. Use the same output directory for generation and build. module generate writes <prefix>.h, <prefix>.c, leanfran.h, leanfran.c, leanfran.json, the Lean export module under LeanfranExport/, and the JSON runtime under LeanfranC/, which build compiles, together with <prefix>.externs.txt, <prefix>.implemented-by.txt, and <prefix>.schema.json, described in Generation checks and Validation and JSON.
To generate several modules with one command, list them in a [[generate]] table with lang = "c" in leanfran.toml and run leanfran generate. It runs module generate with one job for each module, which has its own prefix and output directory. See the generation guide for the table keys, prefixes, and output directories.
sorryAx, generation reports the declaration and exits with status 254. --allow-sorry turns this check into a warning. The module generate commands of the other leanfran backends accept such definitions.--allow-lean-import enables the compiler dependency in the generated link configuration.<prefix>.externs.txt when linking the consumer. An extern for another backend, such as go:foreign.Increment, is rejected during generation. <prefix>.implemented-by.txt lists Lean declarations that call a replacement implementation.sync, check, and status exit with 0 on success and with 1 when status finds out-of-date output or an obligation does not pass check, status, or --require proved. They exit with 252 for invalid parameters, 254 for an error in the project (a Lean diagnostic, an invalid block, LF_STRUCT, or leanfran.toml), and 255 when a tool such as lake, lean, or clang is missing or has another Lean version.
The other commands exit with 0 on success, 252 for invalid parameters, 254 for input that cannot be converted, and 255 for other errors.
C needs the project file leanfran.toml. The settings of sync, check and status describe the project root, [check], [[require]] and projects with several languages.
Put leanfran.toml in the project root. The commands search for it from the working directory, or from --dir <dir>, upwards, and stop with status 254 when it is missing. An empty file is enough.
# leanfran.toml
[embed.c]
sources = ["src/**/*.c", "src/**/*.h"]
Every key is optional. The following file uses every key. sync stops with status 254 when a [[require]] path does not contain a Lake package.
[check]
require = "proved"
[[require]]
name = "pricing_rules"
path = "../pricing-rules"
[embed.c]
sources = ["src/**/*.c", "src/**/*.h"]
lean-files = ["lean/*.lean"]
output-dir = "leanfran"
cflags = ["-Isrc/include"]
Key of [embed.c] | Meaning |
|---|---|
sources | Glob patterns for C files to scan. ** matches any number of directories. The default is ["**/*.c", "**/*.h"]. The output directory and .git, .lake and .leanfran are left out. |
lean-files | Lean files added as blocks. The file name is the block name. |
output-dir | Output directory inside the project. The default is leanfran. |
cflags | Compiler flags clang uses to read files with LF_STRUCT or LF_MODEL that compile_commands.json does not cover. |
[[require]] tables are Lake dependencies, copied to the workspace. A relative path is resolved from the project root. With require = "proved" in [check], check and status work as with --require proved. An unknown key, a value of another type, or an [embed] table of an unknown language stops with status 254 and its position, as in leanfran.toml:4:1: error: unknown key 'source'.
| Variable | Effect |
|---|---|
LEAN_SYSROOT | The Lean toolchain of module generate and build (default: that of lean on PATH). |
LEANFRAN_RUNS, LEANFRAN_SEED | The number of inputs and the seed of the random tests. |
LEANFRAN_AUTO_SYNC=1 | A build with a Lean block that is out of date runs leanfran --lang c sync --dir <root> instead of stopping. |
Put LF_MODEL(...) from leanfran.h before a C function and write the specification in a Lean block. leanfran --lang c check translates the function from clang's JSON AST into a Lean definition and checks the proofs you write about it.
/* leanfran:lean clamp
def spec (lo hi x : Int32) : Int32 := if x < lo then lo else if x > hi then hi else x
def ordered (lo hi _x : Int32) : Bool := lo ≤ hi
*/
#include "leanfran.h"
LF_MODEL("refines=spec", "requires=ordered")
int32_t clamp(int32_t lo, int32_t hi, int32_t x) {
if (x < lo)
return lo;
if (x > hi)
return hi;
return x;
}
LF_MODEL argument | Meaning |
|---|---|
refines=<name> | A Lean function with the same arguments that returns the expected result. For a function that returns lf_status with an out pointer, the result is C.Status × Option T, where T is the Lean type of *out. |
requires=<name> | A Lean function with the same arguments that returns Bool. Every obligation assumes it returns true. |
ensures=<label>:<name> | A Lean function returning Bool that takes the arguments followed by the result. Use a distinct label for each postcondition. A label is a lowercase ASCII letter followed by lowercase ASCII letters, digits, and underscores, and refines is reserved. |
spec=<block> | The Lean block that contains the names. The default is the only block in the file that contains LF_MODEL. |
Give at least one refines= or ensures=. An LF_MODEL on a declaration in a header applies to the definition. Mark a read-only array argument with LF_ARRAY(<length argument>) after a const T * parameter. The Lean definition takes an Array and derives the length argument from its size. LF_MODEL and LF_ARRAY expand to clang annotate attributes and to nothing for other compilers. sync reads LF_MODEL functions to generate the random test, so sync, status, and check need clang on PATH. leanfran --lang c --help also lists translate, which writes the translation of one C file to a Lean file, and obligations check, which checks proof modules against an obligations file. check runs both steps for a project, and the two commands help to inspect a translation.
The translator accepts static and external functions with these parts.
int8_t to int64_t, uint8_t to uint64_t, signed char and unsigned char (8 bits), short and unsigned short (16 bits), int and unsigned (32 bits), long, unsigned long, long long, and unsigned long long (64 bits), size_t (64 bits), bool and _Bool, double, LF_STRUCT structs and the generated record types passed by value, the generated enums and tagged unions passed by value, other C enums as their underlying integer type (unsigned int, or int when an enumerator is negative; not enums with a fixed underlying type or packed), and LF_ARRAY arrays. A typedef is its definition, so a typedef of size_t is USize, also as the result, as an LF_ARRAY element, and as the const T * of an LF_ARRAY parameter. An LF_ARRAY element and the out pointee can be any of these value types, including generated enums and tagged unions. A function returns one value, or lf_status with a final out pointer. An LF_ARRAY parameter and the out pointer can be restrict (const T *restrict xs LF_ARRAY(n), T *restrict out). A function whose out pointee may overlap the elements of an LF_ARRAY parameter must declare that parameter or out restrict. Following C's aliasing rule (C11 6.5p7), check reduces each type to its scalar leaves: an integer counts as its width regardless of sign, a generated enum as a 32-bit integer (it is compatible with unsigned int), and a struct or tagged union as the leaves of its fields, nested fields, and tag. The two types may overlap when a leaf of either is a character type (int8_t, uint8_t, signed char, unsigned char) or when they share a leaf, because both may then access an object of that leaf type. With -fno-strict-aliasing, any two types may overlap. Two different enums share the 32-bit leaf, and so do a struct and a tagged union that both have a 32-bit field. Integers of different widths, an integer and double, bool and an integer, and a struct whose fields are all of other widths do not overlap.switch on enumerators work. A conversion from an integer to a generated enum must be an enumerator or a constant that names a constructor.x.tag is the constructor number. x.as.<constructor>.<field> reads a field of the active constructor; reading a member of another constructor fails the translated definition with C.Exc.inactiveMember, so a refines proof also shows that the translated definition reads only the active member. The tests do not compare this with the compiled C.++, --, if, switch with break-terminated cases whose labels are integer constants or enumerators, for, while, do while, break, continue, and return.double arithmetic, comparisons, bitwise operators and shifts, &&, ||, !, ?:, array and field reads, integer conversions, and calls to other translated functions.LF_ARRAY parameters as an array argument. If the length argument is that parameter's own length argument, the caller never assigns it, and the callee's length has at most as many bits, the callee receives the whole array. Any other length n passes the first n elements. A negative n or an n larger than the array is an out-of-range index.out pointer: a call to a function that returns lf_status with an out pointer can be an expression statement or an lf_status local's initializer. It can also be assigned to an lf_status local, returned, or compared with an LF_ constant as the whole condition of an if or a loop. The out argument is &x for a local variable or parameter x of the pointee type, or the caller's own out pointer. If the callee writes *out, the call stores the value in x. Otherwise x keeps its previous value. lf_status values support == and !=, and a status function can return them.Keep other pointers, array arguments other than LF_ARRAY parameters, lf_status calls inside other expressions, lf_status values used as integers, assignments, ++, --, and the comma operator used as values, writes to fields and array elements (including tag and the as members of a tagged union), struct literals, payload structs (<type>_<constructor>_fields) used as values, pointer fields of recursive tagged unions, malloc and free, globals and static locals, I/O, goto, recursion, variadic functions, other unions, function pointers, volatile, uninitialized locals, switch fallthrough, case ranges, string literals, character constants, calls without a prototype, array parameters with a static length (xs[static 4]), variables with a cleanup attribute, decimal constants above 9223372036854775807 without a u suffix (clang reads one as unsigned long long and GCC as __int128), the floating-point environment outside modeled functions, and an out pointer next to an LF_ARRAY parameter whose element type may overlap it, with neither declared restrict. Also keep these outside modeled functions and the functions that they call: functions that are weak, overloadable, or noreturn, or have another name in the object (__asm__("name")), another calling convention, or an attribute that the translator does not know; inline functions that are neither static nor extern, because a call may use the definition of another file; and functions with the name of a function that the compiler knows, such as abs, fmax, or gamma, unless they are static, because the compiler may replace a call. check reports a function that uses any of them as unextracted with the C file, line, column, and reason. Implementation-defined behavior follows GCC and Clang: right shifts of negative values are arithmetic, and conversions to signed types wrap. double operations use Lean's Float, which rounds each operation.
The translation needs an LP64 target: short has 2 bytes, int 4, and long, long long, and size_t 8. clang reads the target's sizes with the file's compile flags, and on another target every function is unextracted. Compile the C functions that use double with -ffp-contract=off and without -ffast-math, because a compiler that fuses a * b + c into one FMA instruction rounds once and returns a different result. A function that uses double is unextracted when its flags contain -ffast-math, -Ofast, -ffp-model=, -fdenormal-fp-math=, -mllvm, another flag that changes double results, or -ffp-contract= with a value other than off, and when the target may have FMA instructions (every target except x86-64 without -mfma and -mfma4) and the flags do not contain -ffp-contract=off. It is also unextracted when the function has a target attribute, or when the file or a header has #pragma STDC FP_CONTRACT ON, #pragma STDC FENV_ROUND, #pragma clang fp, #pragma float_control, #pragma GCC optimize, #pragma GCC target, or an optimize("…") attribute. Put the flag in cflags of [embed.c] or in compile_commands.json, and build your program with the same flags. With -fshort-enums or -fpack-struct, the functions that use enums, structs, or tagged unions are unextracted. A file that is compiled as C++ has no translated functions, and neither has a file with a sanitizer that stops defined operations, such as -fsanitize=unsigned-integer-overflow -fno-sanitize-recover=all.
A proved obligation is a theorem about the translated definition. It applies to a call of the C function when the call keeps the following calling contract, which C does not check.
LF_STRUCT argument meets the LF_FIELD constraints of its fields, each argument of a generated type meets its proof fields, and each generated enum or lf_status argument holds one of its enumerators. The translated definition takes the argument as a Lean value, which carries these facts, and a proof can use them. Check a value with the generated <prefix>_<type>_valid before the call. For the order struct in Use C structs in Lean, pricing_order_valid(&o, &error) after pricing_init returns false with Invalid order.qty_le when qty is above 1000. An enum's _valid returns false with Invalid <prefix>_<enum> tag for a value that is not an enumerator.LF_ARRAY length argument equals the number of elements that the array pointer can read. The translated definition derives the length from the array's size.out points into no LF_ARRAY argument. The translated definition reads each array as an immutable Lean Array, so a write through out does not reach it. check reports a function as unextracted when C allows its out to overlap one of its LF_ARRAY parameters and neither of them is restrict. With restrict, a call that writes memory through out and reads it through the array is undefined behavior in C. For the other type pairs, any overlapping access is undefined behavior in C.compile_commands.json or cflags. check checks the flags it reads, and your build must use the same flags. A function that reads a macro of the compiler or the build, such as __clang__, __OPTIMIZE__, or NDEBUG, is the one that clang preprocesses.fesetround and a program linked with -ffast-math, which sets the processor to flush subnormal numbers to zero, change double results of C functions and of the Lean code alike.LD_PRELOAD or another shared library replaces it in the program.The trusted pieces outside each proof are the translator, clang's AST, the operation model, which gives each C operation its meaning, the Lean kernel, the C compiler, the Lean blocks, and the refines, ensures, and requires definitions you wrote, which must state what you intend. check checks each proof again with the kernel, so a proof file cannot skip it. The translated definition is elaborated with the block's module imported, so an instance that a block declares for its own types, such as BEq for an enum, gives the meaning of operators on those types. The repository tests the translator and the operation model on its own fixtures. The operation tests compare LeanCLib.C with GCC and Clang at -O0 and -O2 and match each modeled failure with the UBSan diagnostic. The translation tests compare translated functions with the compiled C. Inputs that make a translation fail must stop the C function under UBSan, and inputs that make it fail with a first out-of-range index at most 16 elements outside the array must stop the C function under ASan, which reads arrays allocated with their exact length. ASan does not detect a read that lands in another live allocation, and UBSan does not detect a read of an inactive tagged-union member, so the tests do not compare those reads with C. The random test below runs your implementation against the spec.
check writes the translation of each function and its callees to modules that LeanCModel.<block> imports in .leanfran/c/workspace. Each obligation is an abbreviation such as clamp.obligation.refines. It quantifies over the arguments, assumes for each LF_ARRAY argument that its size fits the length argument's type (xs.size < 2 ^ 64 for size_t, 2 ^ 31 for int32_t), and then assumes requires. Prove it in lean/Proofs/*.lean with a declaration named clamp.proof.refines in the namespace LeanCModel.<block>.
When two or more C files that use the same block define functions with the same name, such as static helpers, each of those functions goes into a namespace for its file, LeanCModel.<block>.<file>. <file> is the C file's path relative to the project root, prefixed with File_, with _ written as __, / as _s, . as _d, - as _h, and any other character that is not a letter or digit as _x<hex code>_. For static uint32_t twin(uint32_t) with LF_MODEL in both src/a.c and src/b.c, check reports dup.File_src_sa_dc.twin [refines] and dup.File_src_sb_dc.twin [refines], and the proofs are File_src_sa_dc.twin.proof.refines and File_src_sb_dc.twin.proof.refines in the namespace LeanCModel.dup.
import LeanCModel.clamp
namespace LeanCModel.clamp
theorem clamp.proof.refines : clamp.obligation.refines := by
intro lo hi x _
simp only [clamp, spec, Id.run]
split <;> (try split) <;> rfl
end LeanCModel.clamp
A function whose body can hit undefined behavior returns C.M α, which is Except C.Exc α. Signed overflow, division by zero, a shift count that is negative or not less than the width, a double to integer conversion out of range, an out-of-range array index, a read of an inactive tagged-union member, a non-terminating loop, and reaching the end of a function that returns a value are modeled failures. Refinement then means the translated function returns Except.ok with the specified value, so a proof also shows that the translated definition reaches none of these modeled failures on inputs that satisfy requires. A postcondition for such a function states that a successful result exists and satisfies the predicate.
leanfran --lang c check --require proved
leanfran --lang c status
check prints one line per obligation, such as clamp.clamp [refines]: proved, and writes the c section of leanfran.lock in the project root with the states and SHA-256 hashes of the inputs. Commit the lock with the sources. For a function outside the translated subset, check also prints <file>:<line>:<column>: error: unextracted <id>: <message> on stderr.
| State | Meaning |
|---|---|
proved | The declaration has the obligation's type, the kernel accepts it and every declaration outside the Lean toolchain that it or the obligation uses, and it depends only on propext, Quot.sound, and Classical.choice. |
sorry | The declaration depends on sorryAx. |
axioms | The declaration depends on another axiom. This includes tactics that add a native-computation axiom. |
missing | The proof declaration is absent. |
mismatch | The declaration's type differs from the obligation. |
failed | The proof or a declaration it uses has an error, or the kernel rejects one of them, such as one added with debug.skipKernelTC. |
unextracted | The function is outside the translated subset, its translation does not elaborate, its compile flags do not match the translation (below), or the translated definition uses an instance on types from the Lean toolchain or LeanCLib that a module outside them declares, such as a Lean block or a Lake dependency. The diagnostic gives the file, position, and reason. |
stale | status found a change to the function, a function it calls, a struct or enum it uses, the spec block, the proofs, [embed.c] or [[require]] in leanfran.toml, the compiler's generator version or Lean version, or the verdict on its compile flags since the lock was written. |
check --require proved exits with status 1 unless every obligation is proved. Plain check exits with status 1 when a function is unextracted or a proof is failed. status reads the lock, prints each obligation's saved state in the same form, and exits with status 1 when an obligation is stale, failed, or unextracted or, with --require proved, not proved. When every LF_MODEL function of a Lean block is unextracted, there is no LeanCModel.<block> module, and check skips the proof files whose LeanCModel imports, direct or through other proof files, name only such blocks.
Leanfran replaces a specification only when status reports a proved refines without
requires, the generated code can call the implementation, and its values can round-trip.
The model must not use a specification that is a candidate for replacement. If several
functions qualify for one specification, the first by function id wins.
The obligation must cover all of the specification's arguments in the same order, and the model
and specification types must match after unfolding reducible definitions such as abbrev.
The sole result exception is an Int model result for a Nat specification; that proof
guarantees a nonnegative result. Arguments coerced or supplied by elaboration do not qualify.
check writes the lock and applies the replacement. The next sync drops it if the function,
its dependencies, the proofs, or other inputs changed so that status no longer reports it as
proved. Until that sync, generated calls may still reach the changed implementation.
Random tests always compare the host function against the Lean body with no replacements.
Generated calls use libleanfran.a and resolve the C implementation at link time. The
unreplaced library libleanfran_spec.a is what the random test links. If the bridge cannot
represent an array's length in the C length parameter, it calls the Lean body instead.
A replacement needs a public block specification without @[extern] or @[implemented_by].
Functions with incompatible types, static or inline functions, duplicate names, functions
returning lf_status, and functions without parameters are not eligible. Put the implementation's
object files before libleanfran.a when linking; put a separate static library of them after it.
Calls inlined by Lean keep the Lean body; use @[noinline] to keep a callable definition.
Each accepted input calls the implementation once. The test checks refines first, then
ensures in the written order, and reports the first failure for that function. run is the
zero-based index of the original failure among accepted inputs; input shows the counterexample
after shrinking. If the host call fails, the value is failed: <reason>. If a specification
fails, the report says the spec failed and shows error: <reason>.
When the sources contain LF_MODEL, sync also writes leanfran_model_test.c and leanfran_model_test.h to the output directory and a leanfran-model-test target to leanfran.mk. The test calls the Lean body of the spec through the block's public C function in libleanfran_spec.a and compares it with your C function. It enumerates boundary values first and then uses seeded random inputs, and it discards inputs that requires rejects. The boundary values of an integer are 0, ±1, ±2, the ends of its type, and the ends of the smaller types, and for 64 bits the integers around 2^53. Those of double are the zeros, the infinities, NaN, the smallest and largest numbers, ±0.5 and other ties, and the ends of the integer types. Array elements repeat. The test fails when it discards more than 100 inputs per run. The target first compares the Lean blocks (Generated code). The test is generated by sync, so run sync or check after you add or remove an LF_MODEL function or change its signature. Until then the target runs the previous test, and status exits with status 1. Random double inputs include values from 1/16 to 32 with random mantissas. NaN results match each other, and other double results are compared bit for bit.
make -f leanfran/leanfran.mk leanfran-model-test
LEANFRAN_RUNS=10000 LEANFRAN_SEED=7 make -f leanfran/leanfran.mk leanfran-model-test
The clamp example prints clamp.clamp: 200 inputs passed (seed 1). The example below has a function that is wrong for x > 100, and its requires accepts even numbers.
fails.refines_wrong [refines]: mismatch (seed 1, run 4)
input: x=102
expected: 103, got: 102
The run is the number of the input that failed first, counted from 0 over the inputs that satisfy requires. The input is the simplest one found with the same label: numbers closer to 0, shorter arrays, false, earlier enum constructors, and tagged unions with such fields. Shrinking ends after 1,000 calls of the function, or after three calls that time out. A test checks the refinement first and then the postconditions as LF_MODEL lists them. For a postcondition, the first line says <name in the block> does not hold, and the last line is result: <value>.
The functions and the specs run in a child process. A function that gives no result has the value failed: <reason>, and the test continues with the next function.
| Reason | Failure |
|---|---|
<file>:<line>:<column>: runtime error: <message> | Undefined behavior that UBSan reports. |
AddressSanitizer: <kind> | A read or write outside an array, a stack overflow, or an invalid pointer. |
SIGABRT or another signal | A signal, such as that of abort(). The first line that the function wrote to standard error follows. |
exit status <n> | The function called exit. |
no result after 10 seconds | A call that does not end. |
A specification that fails, panics, or uses sorry is shown as the spec failed with error: <message>.
The target builds the test with your source files that contain the modeled functions, using $(CC) -fno-wrapv -fsanitize=address,undefined,float-cast-overflow -fno-sanitize-recover=all with $(CFLAGS) and cflags from leanfran.toml, and $(LDLIBS) after them for other files and libraries that they need. An array argument is a copy of exactly its length on the heap. A failure makes the test program exit with status 1 and make reports it. LEANFRAN_RUNS (1 to 2147483647, 200 by default) sets the number of inputs that satisfy requires, which the run counts, and LEANFRAN_SEED (0 to 9223372036854775807, 1 by default) sets the seed. Including leanfran.mk in a Makefile leaves its default goal unchanged.
Generated enums and tagged unions can be arguments and results. Every enum constructor is a boundary value. A tagged-union argument takes each constructor without proof fields, with boundary and random values for its fields. A function whose tagged-union argument has only constructors with proof fields is skipped. Results are compared by value: an enum by its constructor, and a tagged union by its tag and then by each field of the active constructor. A mismatch prints these values by their C names, such as kinds_shape_rect{w=0, h=0, level=kinds_level_low}. Payload fields can be the integer, bool, double, and generated enum types.
The test also covers functions that the translator does not accept, such as recursive ones and those that call abort(). It does not cover static functions, lf_status results, out pointers, structs, generated enums or tagged unions as array elements, tagged unions with other field types, or specs without a public C function or with IO. It prints a skipped: line with the reason for each. A spec whose public C function has other types than the C function fails the test of that function: the spec failed with error: argument 1 has type int32_t, the spec expects lf_str, or mismatch with the two result types (Functions of other types than their specs). The source files the test links must not define main. Nix's C compiler wrapper adds -fwrapv through its hardening flags. The target's -fno-wrapv turns it off so UBSan reports signed overflow.
Task and Thunk, is not a public type (Public types).*/, and two blocks cannot define the same name.Can you improve this documentation? These fine people already did:
conao3 & Naoya YamashitaEdit on GitHub
cljdoc builds & hosts documentation for Clojure/Script libraries
| Ctrl+k | Jump to recent docs |
| ← | Move to previous article |
| → | Move to next article |
| Ctrl+/ | Jump to the search field |