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/Main.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.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-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-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>.Fn_<function> with the translated definition and the obligations <function>.obligation.<label> in the namespace LeanCModel.<block>, and LeanCModel.<block> imports the modules that elaborate. leanfran-c check builds these modules and each lean/Proofs/*.lean module in .leanfran/workspace, and leanfran-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 leanfran-c, LeanCLib.C, leanfran.toml, and the proofs, and one per function over its clang AST and callees without locations, the annotated structures, and its Lean block and imports. leanfran-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.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 .#c
CI builds the Nix package and runs the C checks on Linux and macOS arm64. To run the macOS check directly 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. 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 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. 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 and compares the output directory byte for byte after failed builds.
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, 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 check also translates tests/verify/translation/unsupported.c and compares the reported constructs and positions with unsupported.txt.
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 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, 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 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 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. 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 |