[{"data":1,"prerenderedAt":4},["ShallowReactive",2],{"HAJbbRufGb":3},"# Zean\n\n**Translate Zig functions into executable Lean models and prove their behavior.**\n\nZean captures Zig's analyzed intermediate representation (AIR) and emits\nLean program definitions. You write specifications and proofs in separate\nfiles, then regenerate the model when the Zig code changes. Our model is\ncurrently incomplete and translation is restricted to supported operations.\n\nFor memory safety, a reusable verification library generates proof obligations\nfrom the translated program using Lean 4.35's `Std.WP` and `vcgen`. You supply\ncontracts and loop invariants, then discharge the remaining obligations in Lean.\n\nNote: This initial release of this project was written with AI assistance mostly\nusing GPT-6 Astra over the course of two months. It is extracted from our formal \nverification work for [oksolc](https://github.com/okcontract/oksolc), a Solidity \ncompiler written in Zig.\n\n## Try the Ziglings memory-safety demo\n\nWith **Zig 0.17.1** and **elan** installed, run from the repository root:\n\n```sh\nelan toolchain install leanprover/lean4:v4.35.0\nzig build ziglings\n```\n\nThe [tutorial](examples/ziglings/README.md) follows two familiar Ziglings lessons:\n\n| Exercise | Checked property of the derived runtime kernel |\n| --- | --- |\n| 038: initialize both characters | Reading either gold slot is safe after both writes, without assuming initial contents |\n| 054: give a many-pointer a length | Reads stay within the caller's initialized byte region and preserve memory |\n\nYou supply the caller contracts; reusable verification rules discharge the\nmemory obligations. Broken variants demonstrate an uninitialized read and an\ninvented slice extent. The command checks the proofs, requires false claims to\nfail, and runs the two officially corrected upstream exercises on Zig 0.17.1.\n\nThe formal proofs cover the captured runtime kernels described in the tutorial.\nThe original exercises, including their printing code, receive separate native\ncompatibility checks. Retained captures let you run the demo without building\nan instrumented compiler.\n\n## More demos\n\nContinue with the [buffer update](examples/buffer/README.md), or follow the\n[copy-loop tutorial](examples/copy/README.md) for initialization, framing and\nhelper contracts. The [verification guide](docs/verification.md) explains how\nto apply the same machinery to another supported function.\nThe [manifest-based client](examples/client/README.md) captures and verifies\nyour own function without adding a new tutorial command or changing the verifier.\nIts [caller/helper variant](examples/client/calls/README.md) uses the explicit\ncall-stack interpreter and verifies a caller from a separately checked helper\ncontract, with readable generated function tables.\nThe [byte-scanning client](examples/client/scan/README.md) adds a loop invariant,\nearly returns, and a helper call inside the loop.\nFor runtime helper calls, the [call-chain example](examples/calls/README.md)\nshows a caller reusing checked callee contracts across actual runtime calls.\nThe [standard-library example](examples/stdlib_replace/README.md) goes beyond\nthe tutorials: it verifies an unchanged `std.mem.replaceScalar(u32)` specialization,\nwith a separately checked AIR-to-model correspondence certificate.\nThe [compatibility probes](examples/compatibility/README.md) also show examples\nthat still reject, so these results should not be read as general Zig support.\n\n## Follow a small program update\n\nStart with a counter that advances without overflowing:\n\n```zig\npub export fn advance(value: u8) u8 {\n    return if (value \u003C 255) value + 1 else 255;\n}\n```\n\nThe [handwritten proof](lean/Compiler/Tutorial/Counter/V1/Proofs.lean) establishes\nthat, for every valid byte input `x`, the generated model returns\n`min(x + 1, 255)` successfully. A second theorem proves that the result never\ndecreases and never exceeds 255.\n\n```sh\nzig build counter-run\nzig build counter\n```\n\n`counter-run` runs the working Zig examples. `counter` checks their native\nresults, generated-source identities, Lean proofs, and expected proof failures.\nThe example includes generated models from real native AIR captures, so these\ncommands need no instrumented compiler.\n\nThe [counter tutorial](examples/counter/README.md) follows the complete lifecycle:\n\n1. Write the byte counter and prove its behavior.\n2. Change the step to two and see an incomplete edit overflow at input 254.\n3. Fix the guard, regenerate the model, and update the proof.\n4. Apply the same reasoning to a `u32` counter, proving the contract for all\n   2³² inputs without enumerating them.\n\n## Prove a buffer update safe\n\nThe [buffer tutorial](examples/buffer/README.md) takes the next step: prove that\na Zig function updates exactly one element of a writable buffer and preserves\nsurrounding memory. Its Lean proofs cover arbitrary valid caller heaps, buffer\ncontents and 64-bit indices under explicit storage contracts.\n\n```sh\nzig build buffer-run\nzig build buffer\n```\n\nAn off-by-one edit demonstrates both an invalid access and a write outside a\nsmaller logical buffer that still lies inside allocated memory. A repaired\nversion restores the contract. Like the counter, it includes real captured\nmodels, separate handwritten proofs, and automated fresh capture and proof\nreplay. These are memory-safety proofs for the supported models; caller storage\nassumptions and source/compiler correspondence remain explicit.\n\nThe [copy example](examples/copy/README.md) uses the same verifier for a loop\nover a readonly source and an initially uninitialized destination. Its contract\nproves memory safety at every execution prefix; successful completion copies\nthe contents and preserves the source and surrounding memory. Run `zig build copy`\nto check the proofs, native controls and three intentionally false proof clients.\n\n## What a proof establishes\n\n```text\nZig source → captured AIR → generated Lean model → handwritten Lean proofs\n```\n\nLean checks proofs about execution in the selected model, including its explicit\nfailure outcomes. The counter's successful-return theorem rules out arithmetic\nfaults for every input in its stated domain.\n\nSource admission, the Zig frontend, capture instrumentation, and the native\nbackend remain trusted boundaries. Model proofs and matching native object\nbytes do not establish whole-compiler correctness. See\n[architecture and trust](docs/architecture.md) for the exact boundaries.\n\n## Capture and translate a program\n\nTo generate a new model, first build an instrumented Zig compiler using the\n[toolchain guide](docs/toolchain.md). An ordinary Zig installation can run the\nexamples and tests; producing AIR records requires the instrumented compiler.\nNative capture tooling supports macOS and Linux.\n\nFor example, capture and translate the original counter:\n\n```sh\nzig build capture -- \\\n  --toolchain /path/to/instrumented-build/report.json \\\n  --source examples/counter/v1/counter.zig \\\n  --root counter.advance \\\n  --output /tmp/counter-capture\n\nzig build run -- translate \\\n  --capture /tmp/counter-capture/report.json \\\n  --root counter.advance \\\n  --profile scalar \\\n  --namespace MyCounter.Generated \\\n  --output /tmp/counter-model\n```\n\nThe output bundle contains:\n\n| File | Purpose |\n| --- | --- |\n| `Generated.lean` | Executable program data; regenerated by the translator |\n| `manifest.json` | Source, AIR, capture, producer and model identities, plus verification scope |\n\nTranslation validates every selected root before publishing the bundle. Use a\nnew output directory for each run, and keep captures and compiler builds in a\nseparate working directory. Repeat `--root` to select more functions; their\nfinal name components must be unique.\n\nFor `scalar`, `memory` and `loops`, add `--certify /tmp/certificate-evidence` to check\nAIR-to-model correspondence in Lean before publication. The generated theorem\ncompares an independent Lean interpretation of the captured data with the emitted\nprogram. This checks the lowering step; source capture, JSON lifting and native\ncode generation remain trusted. See the [admission specification](docs/admission.md).\n\nBuild the reusable model library and check the generated module:\n\n```sh\nzig build lean-framework\nelan run leanprover/lean4:v4.35.0 lake env lean /tmp/counter-model/Generated.lean\n```\n\nAdd your specification and proofs in separate Lean files. The tutorial shows\nhow to organize those files and update them after a source change.\n\n## Supported fragments\n\n| Translation profile | Supported operations |\n| --- | --- |\n| `scalar` | Selected integer/Boolean operations, casts and structured control |\n| `memory` | Typed pointers, allocation, loads/stores and retained slice guards |\n| `loops` | Memory operations with resumable loops |\n| `aggregate` | Complete aggregate declarations, fields and aggregate operations |\n| `word-bytes` | Restricted initialized `u32` byte views with checked provenance |\n| `word-byte-loops` | Word-byte access with resumable loops |\n| `calls` | Finite memory programs with an admitted direct-call closure |\n| `call-loops` | Looping callers with finite, separately verified callees |\n| `nested-calls` | Acyclic calls to looping callees, with safety over all finite observation budgets |\n\nThese profiles describe admitted AIR, rather than general Zig language support.\nStandalone translation currently admits ReleaseFast AIR. Memory profiles\nhave additional target and contract restrictions; see the\n[supported routes](docs/architecture.md#supported-routes).\n\nThe [native tooling guide](docs/native-tooling.md) describes capture, source-owner\nvalidation, certified translation, and proof replay. The repository includes\nthe inputs needed for its portable examples and regression checks. New captures\nrequire an instrumented build of the public, pinned Zig release.\n\n## Build and contribute\n\nVersions are pinned in [.zigversion](.zigversion) and\n[lean-toolchain](lean-toolchain). The build uses elan by default; select an\nexisting matching Lake executable with `-Dlake=/path/to/lake`.\n\n| Command | What it does |\n| --- | --- |\n| `zig build` | Build and install the native CLI |\n| `zig build test` | Run native translation, admission, process, and tutorial regressions |\n| `zig build lean-core` | Check the core verification API and its dependencies |\n| `zig build lean-framework` | Check reusable semantics, optional verification domains and correspondence |\n| `zig build lean-examples` | Check tutorial and component proof clients |\n| `zig build lean-regressions` | Check retained captures, standard-library cases, controls and baselines |\n| `zig build lean` | Check the full Lean library and admission controls with two workers |\n| `zig build fmt-check` | Check Zig formatting |\n| `zig build check -Doptimize=ReleaseFast` | Run portable checks, including compilation of newly emitted Lean |\n| `zig build counter` | Check the complete counter lifecycle |\n| `zig build buffer` | Check buffer safety, update behavior and off-by-one proof failures |\n| `zig build copy` | Check copy-loop safety, helper contracts and initialization/bounds/aliasing controls |\n| `zig build calls` | Check a captured call chain through reusable callee contracts |\n| `zig build stdlib-replace` | Check an unchanged standard-library loop and its initialization/permission controls |\n| `zig build wp-proofs` | Check generic verification rules against interpreter and fault controls |\n| `zig build benchmark -- --output /tmp/proof-cost` | Measure fresh proof elaboration with warm library dependencies |\n\nTo recapture the tutorial and replay its proofs against fresh definitions:\n\n```sh\nzig build counter-regenerate -- \\\n  --toolchain /path/to/instrumented-build/report.json \\\n  --output /tmp/counter-evidence \\\n  --check\n```\n\nThis also produces an evidence archive containing source and proof inputs,\nAIR, native objects, manifests and process receipts. The\n[validation guide](docs/validation.md) documents the full `release-check` gate,\nincluding fresh memory and slice audits. Portable CI runs native Debug tests\nand ReleaseFast checks. See [contributing](CONTRIBUTING.md) for fixture and proof\nconventions.\n\n## Explore the repository\n\n- [Counter tutorial](examples/counter/README.md): program, capture, proof and update.\n- [Buffer tutorial](examples/buffer/README.md): memory safety, surrounding-memory preservation and a broken update.\n- [Copy tutorial](examples/copy/README.md): loop invariants, initialization and compositional inline-helper contracts.\n- [Verification guide](docs/verification.md): contracts and automation for other supported programs.\n- [Architecture](docs/architecture.md): translation routes, models and trust boundaries.\n- [Toolchain guide](docs/toolchain.md): build the instrumented compiler and capture AIR.\n- [Native tooling](docs/native-tooling.md): capture, source ownership, translation and proof replay.\n- [Validation](docs/validation.md): regression coverage, release checks and recorded evidence.\n\nImplementation lives in [`src/`](src/), models and proofs in [`lean/`](lean/),\nand regression fixtures in [`test/`](test/). Generated programs are kept\nseparate from handwritten proofs.\n\nLicensed under [Apache 2.0](LICENSE). See [NOTICE](NOTICE) for attribution.\n",1795286032053]