Repository navigation
Engineering Zed
This page describes how the Zed compiler, runtime, and verification toolchain are architected, ordered, verified, and engineered in zedlanguage/zed.
Zed is being built from day one as a modular, self-contained Rust bootstrap compiler structured in "Zed-esque Rust"—pure value-to-value dataflow passes over flat arenas with compact Copy IDs—so that every compiler crate can be verified independently today and translated cleanly into Zed itself during the Ring R8 self-hosting bootstrap.
Every Zed program flows through a deterministic, acyclic pipeline:
Source (.zed)
-> zed-syntax (PEG-verified lexer, Pratt arena parser, round-trip formatter)
-> zed-resolve (lexical scopes, acyclic unit/import DAG, capability grants, @hash pins)
-> zed-check <-> zed-stage
(interleaved local bidirectional set-theoretic typing, occurrence narrowing,
failure-atom bubbling, and barrier-aware compile-time partial evaluation)
-> zed-zir (canonical RVSDG IR, alpha-invariant BLAKE3 content addressing,
dominator contification, Perceus borrow/reuse/drop memory planner)
-> zed-opt (28 algebraic rewrite laws, Weld builder fusion, balanced-tree reductions,
recursive deforestation, emitting machine-checkable certificates)
-> zed-verify (independent tiny-TCB certificate checker + Lean 4 --trust=0 proofs)
-> zed-codegen (SSA Cranelift JIT and AOT ELF/DWARF5 object emission + LLD linking)
-> zed-rt (standalone < 1 MB exact RC runtime + heartbeat work-stealing scheduler)
Three architectural boundaries are enforced mechanically across the repository:
-
Standalone Runtime Isolation (
zed-rt):zed-rthas zero dependencies on any compiler crate. Compiled AOT executables link onlyzed-rt, produce stripped binaries under 1 MB, and contain zero compiler symbols. -
Independent Tiny-TCB Certificate Verification (
zed-verify+ Lean 4):zed-verifydepends only on Layer-0 foundation primitives andzed-zir—it is mechanically forbidden byxtask check-dagfrom depending onzed-opt,zed-check,zed-domains, orzed-stage. Optimizations and termination/arithmetic proofs emit compact certificates verified independently byzed-verify, with core soundness proofs machine-checked in Lean 4 (lean --trust=0 -DwarningAsError=true) underverify/lean/ZedVerify.lean. -
4-Way Differential Oracle: End-to-end programs are validated for exact behavioral equivalence across four independent execution paths:
-
zed-kernel(the small trusted 7-generator reference evaluator:fam,reindex,discard,fold,fix,gen,port), - Pre-PE Cranelift JIT,
- Post-PE Cranelift JIT, and
- Standalone stripped AOT ELF executables (verified for zero leaked runtime objects).
-
Every crate dependency flows strictly downward, verified mechanically by cargo run -p xtask -- check-dag:
| Layer | Crates | Role |
|---|---|---|
| Layer 0 |
zed-span, zed-intern, zed-hash, zed-num, zed-diag, zed-ds
|
Zero/minimal-dep foundation: Copy spans & SymId interner, framed BLAKE3 content addressing, exact Int/Rat/CanonF64, structured diagnostics, shared arenas & graph algorithms. |
| Layer 1 |
zed-syntax, zed-kernel, zed-domains, zed-zir
|
Lexer & arena AST; small trusted 7-generator kernel evaluator; exact unbounded integer intervals, congruences & reduced products; canonical RVSDG ZIR, dominator contification & RC memory planner. |
| Layer 2 |
zed-types, zed-resolve, zed-check
|
Hash-consed set-theoretic type arena; lexical & acyclic multi-unit resolution with capability grants & @hash pinning; local bidirectional checker & AST-to-ZIR elaborator. |
| Layer 3 |
zed-stage, zed-opt, zed-verify
|
Interleaved partial evaluation (mix); certificate-emitting optimizer; independent zero-shared-code verifier. |
| Layer 4 |
zed-rt, zed-codegen, zed-driver, zedc
|
Standalone minimal RC runtime (zero compiler dependencies); SSA Cranelift JIT/AOT + LLD backend; incremental compiler driver & prelude linker; thin zedc CLI. |
| Tooling |
zed-benchkit, xtask
|
Strict O(n log n) 1x-vs-8x scaling harness (<= 9.0x goal / < 10.5x hard ceiling); typed Rust workspace verification CLI. |
Outside crates/, zedlanguage/zed is self-contained:
-
design/— Complete 7-part language specification and compiler architecture. -
docs/plan_dag.md— Authoritative milestone DAG covering all 10 rings, 63 macro goals, and 287 module sub-tasks. -
RUST_STANDARDS.md— Mandatory coding, ownership, complexity, and lint standards. -
verify/lean/— Machine-checked Lean 4 (--trust=0) soundness proofs for certificate verification. -
zed/grammar/— PEG lexical, surface syntax, and notation grammars. -
zed/prelude/— Standard Zed prelude (core.zed,math.zed), embedded at compile time. -
zed/corpus/— 31 end-to-end reference Zed programs, fixtures, and standalone Rust reference oracle.
Companion repositories in the zedlanguage organization:
-
zedlanguage/make-no-mistakes— Standalone interactive DAG planner and live visualizer (http://127.0.0.1:4317) used to author, verify, and trackdocs/plan_dag.md. -
zedlanguage/libzed— Standard library of the Zed programming language (placeholder repository — scheduled to be built out alongside the compiler bootstrap).
Zed is built bottom-up in 10 strictly nested architectural rings (R0 through R9). Every outer ring strictly extends all inner rings without invalidating earlier invariants or bypassing lower layers.
All 63 macro goals and 287 fine-grained Rust module sub-tasks live in docs/plan_dag.md. cargo run -p xtask -- check-dag mechanically verifies that the plan is acyclic, that Level equals exact longest-path depth, that Needs edges are transitively reduced, and that no dependency skips an intermediate ring (ring(B) <= ring(A) + 1).
| Ring | Scope | Key Deliverables | Status |
|---|---|---|---|
| R0 | Foundation & Kernel | 5-layer workspace DAG, zed-span, zed-intern, zed-hash, zed-num, zed-diag, zed-ds, PEG grammar & parser, 7-generator zed-kernel, zed-benchkit, xtask. |
Complete |
| R1 | Core Pure Language & Native JIT/AOT | Exact interval/congruence/relational domains, hash-consed set-theoretic types, RVSDG zed-zir + Perceus RC planner, bidirectional type checker, interleaved PE foundation, standalone < 1 MB zed-rt, Cranelift JIT/AOT + LLD, and 4-way differential oracle. |
Complete |
| R2 | Data Modeling, Match & Modules | Structural structs, width subtyping, with updates, UFCS & overloads, algebraic unions & exhaustive narrowing match, acyclic units with capability grants & @hash pinning, Zed prelude, contified tail calls. |
Complete |
| R3 | Collections, Joins & Multicore Parallelism | Persistent vectors, ropes, Map/Set, PAM weight-balanced augmented trees, prefix scans, 3-region relational joins, canonical balanced-tree & compensated float folds, 28 algebraic rewrite laws + Weld fusion, independent zed-verify + Lean 4 --trust=0 Farkas proof, heartbeat work-stealing scheduler. |
Complete |
| R4 | Generations, Loops, Recursion & Reuse | Acyclic DAG generations & loops (initial, ::frames[-k], while/until/break), .patch/.splice, wavefront skewing, regular recursive mu-types, structural termination + TerminationCert, Perceus in-place reuse, Value-Hole TRMC, Frame Callables, intrusive DropQueue, recursive deforestation. |
Complete |
| R5 | Streams, Waves, Ports & DBSP | Capability-based Ports (stdio, fs, clock, process, net, structured logging) & deterministic test doubles, lossless binary/text codecs, Z-set deltas, Z^-1 delay & wave scheduler, DBSP incremental operators, @memoized fact-address cache, 27 core corpus + 20 Power Gallery programs. |
Active |
| R6 | Facets, Units, Linear Algebra & Proofs | Physical units of measure & user facets, taint/capability/ordering & opt-in quantization/precision-tradeoff facets (strict IEEE fp64 default), tensor shapes & structured matrices, symbolic/AD differentiation, @ensure/@invariant discharge ladder, FPTaylor static error-bound proofs, shipped zed.proof --replay-only. |
Scheduled |
| R7 | Staging, E-Graph, SIMD & C FFI | Cross-compiler optimization survey, memoized partial evaluation (mix / Futamura projection), certificate-emitting congruence-closure e-graph, Dual-Strategy Lowering & CPU SIMD/GPU placement, symmetric O(N) DAG-preserving C FFI, embedded PEG user grammars (all 31 corpus programs). |
Scheduled |
| R8 | Self-Hosting Bootstrap | Direct 1-to-1 reimplementation of core modular compiler crates in Zed, hermetic stage1 -> stage2 -> stage3 fixpoint, TCB accounting, and post-link machine-code verification. |
Scheduled |
| R9 | Tooling, Extra Targets & Ecosystem | Incremental LSP server, Patchable UnitImages, interactive REPL/debugger, WebAssembly (WasmGC/WASI) & FPU-less MCU/HDL Fixed(m, n) backends, MLIR/LLVM & GPU/distributed targets, ecosystem libraries (libzed), and flagship applications. |
Scheduled |
Progress across all 10 rings and their internal module sub-DAGs is visualized live using make-no-mistakes:
node ../make-no-mistakes/src/server.ts --repo . --plan docs/plan_dag.md --port 4317Opening http://127.0.0.1:4317 renders the interactive layered DAG, highlights the ready frontier, surfaces critical paths and blocked dependencies, and checks structural invariants in real time as milestones transition from scheduled to active, verifying, and done.
Every sealed wave must pass a strict automated verification suite before merging:
-
Static & Formal Checks:
cargo fmt --all -- --check,cargo run -p xtask -- check-dag,cargo clippy --workspace --all-targets --all-features -- -D warnings,cargo doc --workspace --no-deps --all-featureswith-D warnings, andlean --trust=0 -DwarningAsError=true verify/lean/ZedVerify.lean. -
Tests & Coverage: Zero failed and zero
#[ignore]d unit, integration, and doc tests, plus consolidated--all-featuresllvm-covcoverage requiring>= 95.0%per-file across regions, functions, and lines. -
4-Way Differential Parity: Identical results across
zed-kernel, Pre-PE JIT, Post-PE JIT, and stripped AOT ELF (< 1 MB,0compiler symbols,0leaked runtime objects). -
Hardware-PMU Scaling Verification (
zed-benchkit): Every algorithm runs at1xvs8xinput scale under pinned hardware performance counters (ZED_BENCH_REQUIRE_PMU=1,--profile bench-test -- --test-threads=1) measuring bothRetiredInstructionsand heap-allocated bytes (<= 9.0xpreferred /< 10.5xhard limit forO(n log n),<= 2.0xforO(log n),<= 1.5xforO(1)), with explicitMustAllocate/ExpectZeroexpectations, clean measurement closures, and negative controls proving every assertion can actually fail.
Deep adversarial cross-reviews run off-DAG, pipelined one ring behind active implementation: as soon as Ring R(k) clears its own tests, coverage, differential parity, and PMU scaling checks, implementation advances immediately into R(k+1) while independent reviewers audit every crate, test, and benchmark in R(k).
- Every reported issue is independently verified against the actual source code,
design/, andRUST_STANDARDS.md—no finding is accepted uncritically. - Confirmed defects are back-patched concurrently with
R(k+1)work and re-verified across the full downstream workspace until the audit converges with zero open blockers. - Mandatory Audit Regression Tests & Benchmarks: Whenever an audit uncovers a confirmed defect, that proves the original unit tests or benchmarks failed to catch it at merge time. Every confirmed audit fix must therefore add a non-vacuous regression unit test and/or hardware-PMU scaling benchmark targeting that exact defect class.
All code follows RUST_STANDARDS.md, designed to produce fast, auditable Rust today and a direct, mechanical port to Zed in Ring R8:
-
Flat Owning Arenas &
CopyIDs: Compiler graphs, ASTs, types, and IR nodes live in flat owning arenas indexed by compactCopyu32handles. Zero borrow-checker.clone(),Rc,Arc,RefCell,Cell,Mutex,RwLock,thread_local!, orOnceLockdodges in compiler crates; recursive tree/graph traversals use explicit heap-backed worklists to guarantee stack safety on arbitrary inputs. -
Pure Value-to-Value Dataflow Passes: Every compiler pass takes immutable references to upstream arenas and returns a clean, deterministic output value plus structured diagnostics (
DiagBag), with zero hidden global state. -
Strict Complexity Ceiling & Structural Refusal: Default worst-case complexity ceiling of
O(n log n)across compiler and runtime passes. Zero silent behavior-changing arbitrary thresholds—whenever an analysis encounters an intractable construct, it returns an explicit, deterministic structural refusal diagnostic rather than silently altering program semantics. -
Strict Lints & Minimal
unsafeSurface: Workspace-wideunsafe_code = "forbid",unwrap_used = "deny",expect_used = "deny",panic = "deny",allow_attributes = "deny", and zeroignore-interior-mutabilityexemptions. Narrow#[expect(unsafe_code, reason = "...")]blocks with explicit// SAFETY:proofs are restricted strictly to low-level runtime memory management (zed-rt) and native machine-code boundaries (zed-codegen). -
Modular File & Function Budgets: Production Rust files are kept at or below 500 lines and production functions at or below 80 lines (with test files at or below 1,000 lines), keeping every module reviewable and easy to verify at
>= 95%coverage. -
Fast Incremental Builds:
opt-level = 0indev, LLD linking, modular crate boundaries, and zerodylibworkarounds.