The C backend builds on Lean's native C emitter and runtime. It selects Lean definitions, generates a public C API and builds the library and its link settings.
langs/C/LeanC/Cli.lean parses the C backend CLI.langs/C/LeanC/Export.lean selects declarations and emits the Lean export module. Its @[export] declarations supply stable symbols independent of the Lake package name.langs/C/LeanC/Desc.lean describes public types and synthesizes evidence that proof fields are decidable.langs/C/LeanC/Json.lean emits deciders and JSON codecs as Lean source. langs/C/lean/LeanfranC/Json.lean provides the runtime parser and serializer and imports only Init. The generated export module links the runtime with the user library.langs/C/LeanC/Schema.lean emits draft 2020-12 JSON Schema from the same public type descriptions.langs/C/LeanC/Check.lean inspects reachable declarations and imports for sorryAx, compiler dependencies, externs, and implemented_by replacements.langs/C/LeanC/Header.lean emits the C11 header, conversion wrappers, and per-module initializer. langs/C/LeanC/Marshal.lean emits the conversions between C values and Lean objects and the _free functions, and langs/C/LeanC/Ref.lean emits the value handle types and the _ref and _ref_take wrappers. langs/C/support/ provides the common ABI, runtime initialization, and string and error ownership helpers.hasTrivialImpureStructure?): its Lean value is the field's value. Marshal.lean converts such a structure or inductive without a constructor object, and _from_lean writes the single constructor's tag without reading one. langs/C/tests/types/roundtrip.c checks these types with String, UInt8, Nat, Float, structure, and proof fields, and as fields of a structure.langs/C/LeanC/Build.lean uses Lake's module dependencies and native objects to assemble the library. langs/C/LeanC/Link.lean uses the active toolchain's leanc --print-ldflags output to generate pkg-config, Make, and CMake settings. Linux groups the static Lean libraries for the linker. macOS links them without GNU linker groups.langs/C/LeanC/ClangAst.lean reads compile_commands.json, runs clang -Xclang -ast-dump=json, and parses the JSON AST for LF_STRUCT, LF_MODEL, and leanfran --lang c translate. A file uses the first entry for it in compile_commands.json.langs/C/LeanC/Embed/Scan.lean reads leanfran.toml and extracts Lean blocks from C comments. Embed/Models.lean reads LF_STRUCT structs and their LF_FIELD constraints and writes them as Lean structures in the module LeanfranModels. Embed/Workspace.lean builds the blocks in .leanfran/workspace, tracks freshness with SHA-256, and publishes the project bindings together. The workspace also holds LeanCLib.C, so a block can import it.langs/C/lean/LeanCLib/C.lean defines the meaning of C arithmetic, conversions, array reads and loops, with undefined behavior as C.Exc failures. langs/C/LeanC/Verify/Translate.lean reads the clang JSON AST and translates C function definitions into Lean do blocks over LeanCLib.C. leanfran --lang c translate (LeanC/Verify/Command.lean) writes the translation of one C file as the module LeanCModel.<block> and reports each function outside the supported subset as unextracted with its position and reason. LF_ARRAY(len) marks a const T * parameter whose length is the parameter len, and the translation takes the Lean Array and derives len from its size. Generated headers mark public structures and their fields with LF_LEAN("<Lean name>") so the translation can read them by value.langs/C/LeanC/Embed/Verify.lean finds functions marked with LF_MODEL("refines=<name>", "requires=<name>", "ensures=<label>:<name>", "spec=<block>") in the project's C sources. clang reads them with the generated headers on its include path: the build directory during sync and the output directory during check and status. A definition also inherits LF_MODEL from a prototype in a header, so when a header carries LF_MODEL every configured .c source is searched, and a prototype without a definition is unextracted. Without spec=, the function uses the one Lean block of the file that holds LF_MODEL. For each modeled function and the functions it calls, it writes one module LeanCModel.<block>.<file>.Fn_<function> with the translated definition and the obligations <function>.obligation.<label>, and LeanCModel.<block> imports the modules that elaborate when at least one LF_MODEL function of the block has obligations to check. For a block whose LF_MODEL functions are all unextracted, leanfran --lang c check writes no LeanCModel.<block> module and skips the build of each proof module whose LeanCModel imports, followed through proof modules, name only such blocks. ModelFunction.home attributes a function with an invalid LF_MODEL to the one Lean block of its file. <file> is fileIdent of the C file's relative path, an injective identifier such as File_src_sa_dc for src/a.c. The definitions go into the namespace LeanCModel.<block>, except that a name translated from two or more C files of the same block goes into LeanCModel.<block>.<file> in every one of those files. ModelFunction.scope holds the file identifier of such an LF_MODEL function and becomes part of its model name, and ModelFunction.fileScoped lists the file-scoped functions of its closure, whose callers open the file's namespace. leanfran --lang c check builds these modules and each lean/Proofs/*.lean module in .leanfran/workspace, and leanfran --lang c obligations check (LeanC/Verify/Obligations.lean) classifies every obligation as proved, sorry, axioms, missing, mismatch, failed, or unextracted. leanfran.lock stores the results with one SHA-256 for the generator version and Lean version, LeanCLib.C, leanfran.toml, and the proofs, and one per function over its clang AST and callees without locations, the annotated structures, the enums whose enumerators it reads, its Lean block and imports, the target sizes, and the floating-point flags of functions that use double. leanfran --lang c status reports stale for the obligations of functions whose hash differs.langs/C/LeanC/Embed/ModelTest.lean writes leanfran_model_test.c during sync when the sources contain LF_MODEL, together with support/leanfran_model_test.h and the leanfran-model-test target appended to leanfran.mk. For each modeled function it finds the refines, requires, and ensures names among the public functions of the spec block and the other blocks, checks that their C signatures match the function, and generates a loop that enumerates boundary values, then draws seeded random values and arrays of up to 8 elements. Functions that are static, return lf_status, take or return structs, or have no matching public spec function get a skipped: line with the reason. The target saves and restores .DEFAULT_GOAL, so including leanfran.mk keeps the including Makefile's default goal.langs/C/tests/cases/ is a Lake workspace with the Lean fixtures and native oracle. langs/C/tests/link/ holds the C consumers and build fixtures. maint/C/test-diff.sh and maint/C/test-link.sh drive the checks.langs/C/samples/ holds runnable examples: pricing generates and links an API from a Lake workspace, and verified-clamp embeds a Lean block, proves its LF_MODEL function, and runs the model test. maint/C/test-samples.sh runs both. It first compares the guide's Pricing.total, main.c, first leanfran.toml, and clamp code and proof blocks with the sample files after collapsing each run of whitespace into one space, so the guide's steps run in CI.generatorVersion in langs/C/LeanC/Embed/Verify.lean identifies the generated C, the block workspace, the C translation, and the obligations. Raise it in the same change as any edit that alters them. leanfran.manifest.json and leanfran.lock key on it with the Lean version and not on the release version, so a release that keeps it leaves existing outputs and proof results current.
When changing wrappers, inspect the pinned Lean toolchain's generated C and lean.h for the exact ABI and ownership conventions. Keep the public header usable from C11 and C++ and keep the Lean runtime types inside the implementation.
Run from the repository root.
nix shell nixpkgs#gnumake -c make format BACKENDS=C
nix shell nixpkgs#gnumake -c make check BACKENDS=C
nix build .#leanfran
CI builds the Nix package and runs the C checks on Linux and macOS arm64. On Linux, CI runs
check-models and the packaging checks, check-verify, and check-integration in three
parallel jobs. On macOS, CI runs check-verify in parallel with the rest of check. The
combined check on each platform requires every job to pass. To run the full check locally in
the C shell, use nix develop .#c -c make -C langs/C check.
The differential check (maint/C/test-diff.sh) compares stdout, stderr, and process status with the native Lean oracle for successful and failing I/O. It tests calls before initialization, repeat and concurrent initialization, and initialization errors, including two generated outputs linked into one program whose shared module fails to initialize. It also checks --version, --generator-version, and the exit codes in --help, and that generate stops with one diagnostic and status 254 for a definition in Examples.Dependent whose parameter or result type depends on a parameter, and skips such definitions without --roots. To detect ownership errors in Lean objects, it counts live mimalloc blocks across repeated calls and checks that intentionally missing or extra decrements change the count. Linux also runs ASan, LeakSanitizer, and UBSan on the C conversion and support code. The type round trip in tests/types/roundtrip.c passes FloatArray values with signed zeros, infinities, and NaN through lf_float_array and checks their bits, and the script checks that definitions using Task or Thunk, directly or in a structure field, stop generation with the definition and field in the diagnostic.
The link check (maint/C/test-link.sh) exercises generation diagnostics, user-supplied externs, and compiler imports. It builds the generated wrappers as C11 and checks the public header from C++17, and checks that the generated source stops with #error against another Lean version's lean/version.h. Fixtures compile and run consumers through pkg-config, GNU Make, and CMake with static and shared libraries.
The embed check (maint/C/test-embed.sh) runs sync, status, and check on a C project with imported blocks and a standalone Lean file. It links the generated archive with pkg-config, Make, and CMake. It also checks diagnostic locations, including two blocks that define the same name, compares the output directory byte for byte after failed builds, and recomputes the manifest's compiler hash from --generator-version and the Lean version.
The JSON check, part of maint/C/test-diff.sh, compares compressed output with Lean's deriving ToJson and compares parser acceptance and output with Lean.Json.parse. It exercises failures from proof fields in C and JSON values and checks live mimalloc blocks across repeated failures. The value handle check, also part of maint/C/test-diff.sh, runs tests/types/value_handles.c with live mimalloc block counts, under ASan and LeakSanitizer, and under TSan for handles shared between threads, and runs the benchmark reported in the C guide. The schema check (maint/C/test-schema.sh) compiles the same fixture module with the Go backend and compares its draft 2020-12 schemas with the C output.
The operation check (maint/C/test-model.sh) compiles the LeanCLib.C operations through the C backend and compares them with GCC and Clang at -O0 and -O2 on boundary and seeded inputs. Inputs that the model rejects must trap under UBSan. The translation check (maint/C/test-translate.sh) translates tests/verify/translation/fixture.c, which uses every supported statement and expression, including LF_ARRAY arguments and out pointers whose elements are generated enums and tagged unions, runs the translation in a Lean executable, and compares it with the native C functions under the same compilers and -ffp-contract=off. NaN results compare equal to any NaN. Inputs for which the translation fails with undefined behavior must trap under UBSan, except out-of-range array reads, which UBSan does not detect through pointers. The driver allocates each array argument on the heap with its exact length, and the check builds it with -fsanitize=address under the same compilers and runs it with ASAN_OPTIONS=redzone=256. In-range inputs must give the translated results, and every input for which the translation fails with indexOutOfRange, and whose first out-of-range read is at most 16 elements outside the array, must stop under ASan: the at inputs with such an index and every sum_prefix input, which first reads one past the end. A read further outside can land in another live allocation, which ASan does not detect, so the check does not run those inputs. Three fixed inputs, an empty array and the indices one past each end, must report a heap-buffer-overflow. The sign_end inputs that reach the end of the function make the translation fail with missingReturn and are not run in C, and the other inputs must match. UBSan is checked on up to 20 inputs for each function and kind of failure. The check also translates tests/verify/translation/unsupported.c and compares the reported constructs and positions with unsupported.txt. Its out cases cover each type pair that may overlap an LF_ARRAY element without restrict: a character-type out or array, integers that differ only in sign, a generated enum and a 32-bit integer, two different generated enums, a struct or tagged union with a field that shares a scalar leaf with the other type, and a struct next to a tagged union that shares a field width, in both directions. The check also requires that the same pairs with restrict and the pairs that cannot overlap (integers of different widths, an integer and double, bool and an integer, a generated enum and a 64-bit integer, a struct whose fields all have other widths than the element type) translate.
The fuzz check (maint/C/test-fuzz.sh) generates C functions with maint/C/fuzz-translate.py for three fixed seeds, one with double, translates all of them, and compares the translation with the C functions on 14 inputs each, under Clang, and GCC on Linux, at -O0 and -O2. Inputs for which the translation fails must trap under Clang's UBSan. GCC folds some overflowing expressions so that UBSan does not stop them, so the GCC runs compare only the values. The check runs Python from nixpkgs with nix shell.
The verification check (maint/C/test-verify.sh) runs check --require proved and status on tests/verify/states, a project with one function for each obligation state. It checks the diagnostics of an untranslatable function, a broken proof, an unknown requires name, and an unknown block. After a body edit only that function's obligations become stale, and a whitespace-only edit keeps them fresh. A project whose obligations are all proved passes --require proved. A project whose only LF_MODEL function is untranslatable or has an unknown key, with a proof file that imports its block's model module and a second one that imports the first, prints only the unextracted row, without module errors, and check exits with status 1 and status with 0. A second project puts LF_MODEL on header prototypes, including one without a definition, and checks the refines and ensures obligations of a function that can fail. The tests/verify/records project, copied without generated files, links contract.c, which passes an order outside its LF_FIELD constraints and a grade_level value that is not an enumerator to the generated _valid functions under UBSan. The project proves functions that take an LF_STRUCT struct and a generated record and an lf_status function whose block imports LeanCLib.C for its spec. Its grade block proves functions that return a generated enum, pass an LF_ARRAY argument to another function, pass an out pointer to a generated enum, and write *out twice in an lf_status function whose LF_ARRAY parameter is restrict. Its grade and shop blocks also prove, with restrict on the array or on out, a function for each type pair that may overlap: a uint8_t out or array next to int32_t, uint32_t next to int32_t, a generated enum next to a 32-bit integer and next to another generated enum, and a generated struct and tagged union next to a 32-bit integer in both directions, and the test checks that the obligation assumes the array size fits size_t. Its compile_commands.json has two entries for the same file, and swapping them changes the translated body. A syntax error in a source makes status print the clang error, report every obligation as stale, and exit with status 1, and makes check exit with status 254 without changing the lock or the output directory. The tests/verify/trust project has a proof that uses a theorem added with debug.skipKernelTC, which is failed with the kernel's message, and a block instance on UInt32 that changes the translated +, which is unextracted. Changing the value of an enumerator that a proved function reads makes it stale. Compile commands with -ffast-math, -ffp-contract=fast, or FMA without -ffp-contract=off make the double function stale and then unextracted, and on Linux -m32 does the same for every function.
The model test check (maint/C/test-random.sh) syncs tests/verify/random and runs leanfran-model-test with Clang, and with GCC on Linux. The correct implementations pass, a static function and an lf_status function are skipped, LEANFRAN_RUNS and LEANFRAN_SEED change the run count and seed, and a Makefile that includes leanfran.mk keeps its default goal. An off-by-one implementation of at_most fails with the seed, run, input, and both results, and does not reach UBSan. With requires=small the proof of add is proved and its test passes. Without requires, the same proof is failed and UBSan stops the test at the signed overflow before any comparison. A requires that rejects every input fails the test. On Linux, a double multiply-add fails with Clang at -O2 -mfma and passes with -ffp-contract=off. The script clears NIX_HARDENING_ENABLE, and the target passes -fno-wrapv, because Nix's compiler wrapper otherwise adds -fwrapv and hides signed overflow from UBSan.
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 |