Repository navigation
Motivations and Design Philosophy Behind Zed
Zed is a general-purpose programming language built on a single premise: a program's source code directly expresses its data dependency graph. Every value is written once and read only after it is complete, and the only thing that orders two computations is one value depending on another. From that rule alone, the compiler can run ordinary code across many cores without threads or locks, reclaim memory without a tracing garbage collector, and produce bit-identical results at any core count by default.
Around that core, Zed tries to rule out whole classes of everyday bugs at compile time, with no proofs required, in a small syntax that reads like ordinary code. What the source shows is what happens: programs cannot define or overload operators, and the only implicit conversion in the language is converting a unit where a parameter, field, or key declares the unit it expects. A minimal Zed program is already statically typed, parallel, memory-managed, and deterministic before you write a single annotation. Everything you add on top (written types, laws, units, proofs, cost bounds, placement) is an optional layer that can reject a program, accept one, or make it faster, and never changes what it computes unless the change appears in a type. Beneath the surface syntax, every value is a morphism, a map from keys to values, and the compiler uses the algebra of those maps to check and optimize the program.
This page walks through the ideas that distinguish Zed, starting with the ones that change everyday programming most and moving to the more specialized features.
- Solving the multicore dilemma - Because the source code is the dependency graph, the compiler parallelizes code without threads or locks and reclaims memory without a tracing garbage collector.
- Everything is a morphism - Arrays, maps, sets, structs, blocks, functions, loops, streams, and the program itself are all maps from keys to values, read and combined the same way.
- Failure is a value - Every way an operation can fail is a named value in its result type that the program must handle or pass along, eliminating null and exceptions.
- Remapping without silent collisions - Changing keys in a way that could put two values on the same key is a compile error unless the program keeps the distinguishing key, drops the values, or specifies how to combine them.
- Loops are values - A loop describes one step from the previous frame to the next, and the whole loop is a value holding its final state and its history.
- What the checker proves on every build - Without annotations, the checker verifies failure handling, integer ranges, preconditions, collisions, termination, memory bounds, cost, determinism, and security, and reports what it could not decide.
- Error messages that show the fix - Every rejection names its cause, traces how the facts reached the site, and offers code fixes the checker has already verified.
- Numbers that never overflow or silently round - Integers have no fixed width, machine representations follow inferred ranges, exact rationals are built in, and rounding is tracked instead of hidden.
- Parallel reductions and bit-identical floats - The checker proves algebraic laws for combining operators so exact reductions split across cores, while floating-point reductions use a canonical tree for bit-identical results at any core count.
- Ports are the only outside world - Files, clocks, sockets, databases, and child processes enter only through ports, leaving everything else pure and letting any test substitute a port with plain data.
- Incremental and live programs - When an input or the source code changes, only its dependents recompute, every value traces back to its inputs, and live visualizers work in both directions.
- Cost is part of the type - Where it can, the compiler derives each function's asymptotic cost from its input sizes and checks declared bounds, algorithm switches, and memoization.
- Laws, invariants, and proofs - Programs state properties for all inputs, and the checker discharges them through a fixed sequence of methods, from finite evaluation and algebra to induction and kernel-checked proofs.
- Tests in the language - Input-output tables sit right on the functions they test, coverage comes from the checker's own scopes, and mutation testing reveals what both tests and laws miss.
- Units of measure and facets - Physical units, temperature scales, and distinct kinds of quantity are checked at compile time through facets, the same mechanism that handles taint, sort order, and rounding.
-
Secrets, untrusted input, and dependencies - Taint tracks untrusted inputs across every branch,
@cryptosafechecks secret-handling code down to the machine instructions and wipes secrets on return, and imports are hash-pinned with explicit capability grants. - Types are sets of values - Types combine with union, intersection, and difference, subtyping is set inclusion, and structs can state laws over their fields.
- Partial evaluation replaces macros - One evaluator handles build time and run time alike, replacing macros, templates, and separate compile-time languages.
- Algebra under the syntax - Category theory and abstract algebra govern the compiler's rules, e-graph optimizer, and certificate checker while staying out of the surface syntax.
- Calling foreign code - Pointer reads from C check alignment and nulls, ownership rules are explicit, foreign libraries can run in isolated and sandboxed processes, and Zed packages export cleanly to C.
- Grammars - One grammar on a struct generates both its parser and its printer, with round-trip consistency checked statically.
- Symbolic math and differentiation - Functions can be inspected as formulas and simplified, differentiated, integrated, or turned into forward- and reverse-mode derivatives with kernel-checked rewrites.
- Targets - One intermediate representation compiles to multicore CPUs, WebAssembly, GPUs, clusters, microcontrollers, and hardware synthesis, and splits client and server code along dependency edges.
- Methods are functions - Method syntax is shorthand for a function call, and a method that updates its receiver returns the receiver's next value, and a function of two parameters can be called infix.
- Intentional non-goals of Zed - Zed omits classes, operator overloading, dependent types, effect annotations, fixed lazy or strict evaluation, and user-facing categorical jargon.
Most programming languages let you read the current value of a mutable variable. That one capability causes several problems: which write a read observes depends on execution order and timing, so the program's real data dependencies stay hidden until runtime. Compilers and CPUs then spend much effort reconstructing the parallelism the source text threw away, while programmers fall back on threads and locks and end up debugging data races and deadlocks.
Zed removes the ability to read a mutable place. Every name holds one value. Inside a loop, each step's values belong to that step instead of overwriting a shared slot. When several computations contribute to the same destination, a declared combining operation merges them:
hist: int ->? int with reducer((+));
// each word pushes 1 to its length's bucket; + combines them
for w in words { hist[w.len] <- 1; };With mutable places gone, the source text directly specifies a directed acyclic graph (DAG) of values, where each loop iteration introduces its own nodes. Paths in that graph define a partial order, and any two values with no path between them can run on separate cores at the same time. Acyclicity solves memory management as well. Reference counting is exact on an acyclic graph, so a value is freed as soon as its last reader finishes, with no tracing garbage collector and no collection pauses. When the compiler can see the last reader statically, it inserts the release directly with no reference count at all, and an update to a value nobody else reads runs in place without copying. Data races cannot be expressed, and a program can block only while waiting on the outside world. See Solving the Multicore Dilemma for the full argument.
In most languages, arrays, hash maps, sets, structs, streams, functions, and loops are separate mechanisms with separate rules and separate standard-library vocabularies. Zed unifies them into one kind of value: a morphism, a map from a set of keys to values. A morphism m : K -> V assigns each key in its domain K exactly one value, and the domain travels as part of the value. The familiar constructs differ only in what their keys are and whether their values are stored or computed:
| Surface form | Morphism reading |
|---|---|
42 |
() -> int, a map from the empty key (an isomorphism: the two stay distinct types, which is why f() and f mean the same for a nullary f) |
[a, b, c] |
int[0..<3] -> T |
{ "a" -> 1 } |
a map from "a" to 1
|
{ "a", "b" } |
a set: a map sending each element to itself |
{ x = f(a); y = g(b); } |
a block: a map from the names x and y to their values |
double(positional x) = x * 2 |
a function: a map whose values are computed on demand |
for i in D { … } |
a loop: a map from D to each iteration's result |
| a changing variable | a map from step numbers to values |
| a stream | a map over an unbounded, ordered sequence of keys |
| the whole program | a map from its input ports to its output ports |
Viewed this way, a map is a memoized function and a function is a map whose entries are computed on demand. The compiler moves between stored and computed representations based on cost, and computes only the portion of a table that the program actually asks for.
Calling a function and indexing a collection are the same operation: lookup. A two-parameter function is a map of maps, so f(x, y) is f[x][y], and square brackets apply one level at a time. Field access works the same way, with p.x meaning p[#x]:
add(positional a, positional b) = a + b;
inc = add[1]; // the function b -> add(1, b)
// e = add(1); // ✗ a call supplies every parameter
greet(positional name: Utf8String, punct = "!") = "Hello, ${name}${punct}";
h = greet("Al", ...); // the function of punct: h() or h(punct: "?")Because every collection shares this shape, one small set of operations (map, where, group, join, sort, and the reduction ><) works identically on arrays, key-value maps, struct fields, loop histories, and streams. Nested collections (A -> B -> C) are maps of maps. Regrouping their levels preserves meaning as long as no inner level is empty; where an inner level could be empty, the checker warns that regrouping drops its outer key.
Every value also carries a keypath, the chain of keys that led to it across loop indices, collection keys, step numbers, and input waves. That one mechanism gives provenance (tracing any output back to the inputs that produced it), incremental recomputation keys, and data partitioning across machines. Cyclic graphs are written as maps from identifiers to nodes, Id ->? Node, so looking up a deleted node yields #notFound and dangling pointers cannot exist.
Combining two collections is a morphism operation too. Given two maps, every key falls into one of three regions: only in the first, in both, or only in the second. A join chooses for each region whether to keep it, drop it, or require the checker to prove it empty. Appending lists, zipping them, and inner, left, right, or outer joins are all instances of that choice. Because a loop that looks up keys in a second collection elaborates to the exact same term as a join, the compiler can execute a loop as a hash join or a join as a nested loop, whichever costs less:
// every order paired with its payment or #none
paid = orders.join(payments, on: #orderId, kind: #left);
// the checker must prove the two key domains equal
pairs = xs.zip(ys);Indexes follow the same principle. A table that code only scans is stored as a flat unindexed sequence; the compiler builds a key index only when the program actually performs keyed lookups.
Every language has to decide what happens when you divide by zero or index past the end of an array. Most reach for exceptions or null values, both of which let a caller forget to check until the program fails at run time. In Zed, any operation that can fail declares its failure modes right in its result type using atoms, named values such as #divByZero, #outOfBounds, or #notFound. Integer division has the type:
(div) : ((int, int \ 0) -> int) & ((int, 0) -> #divByZero)If the divisor's type already excludes 0, div returns a plain int. If 0 is still possible, #divByZero stays in the result type. Array indexing a[i] works the same way: #outOfBounds appears in the result type unless the checker proves i is in range.
Atoms are ordinary values. Code can handle them directly with match or default them away with else, or leave them unhandled so they flow into the enclosing function's result type. Here, ?. threads through nested lookups while carrying any failure along, and else supplies 8080 if anything along the chain failed:
port = parse(text)?.server?.port else 8080;As a result, Zed has no null and no exceptions to throw or forget to catch. An operation that can only fail, such as dividing by a value proved to be 0, is rejected at compile time. When a programmer writes #bug for an invariant that should hold, the checker deletes #bug wherever it proves the site unreachable; anywhere it cannot, every build emits a warning and zedc build --strict rejects the program.
Suppose revenue stores figures keyed by region, day, and product (sku), and you want daily totals per region. Dropping sku from the keypath maps multiple products onto the same (region, day) pair. In many languages and query tools, that silently triggers last-write-wins or throws a runtime duplicate-key error.
Zed treats a key transformation that could collapse multiple values onto one key as a compile error. You must keep the distinguishing key, discard the values along with the key, or state how colliding values combine with ><, the reduce operator:
// ✗ Collision: two skus land on one keypath
// daily = revenue as (region -> day -> sku -> r) into (region -> day -> r);
daily = revenue as (region -> day -> sku -> r) into (region -> day -> sku >< (+) -> r);The first line fails to compile because each (region, day) has one entry per sku. The second sums across sku with (+), making the merge explicit.
Key transformations covered by a fixed catalog of one-to-one forms need no reducer. Given words of type i -> w, writing byLower = words into (w.lower -> i -> w); binds the levels by name and keeps each word's original index i as the inner key, so two words with the same lowercase spelling remain distinct. Any key change outside that catalog is rejected identically across every build, and the error lists the legal alternatives: drop the values, keep the inner key as byLower does, supply a reducer, prove the key function injective, or group and return #collision wherever a key holds more than one value.
Because reduction is the only operation in Zed that merges multiple values into one, two writes to the same key can never race.
Imperative loops mutate variables in place and discard every intermediate state unless you manually allocate arrays to record them. A Zed loop describes one step from the previous frame to the next. Inside the body, x' names the value computed in the current step, while bare x reads the value from the previous step, or on step 0 the boundary value given by initial:
sim = loop t {
while t < maxSteps;
initial pos = p0;
initial vel = v0;
pos' = pos + vel * dt;
vel' = vel + a(pos) * dt;
until pos'.x > bound;
};The whole loop evaluates to a value. sim.pos gives the final position, sim::frames is the full history of every step, and sim::len is the step count. Reading the complete history requires a proved upper bound on the number of steps, which while t < maxSteps supplies; the until pos'.x > bound check stops the loop, yet bounds no step count on its own.
Storage follows demand. For each loop variable independently, the compiler computes how many steps back the program actually reads and keeps only that window. If nothing reads sim::frames and the body reads only x to compute x', the loop keeps at most one prior value of x. When every read of x finishes before the update, the window drops to zero and the update overwrites in place. A step can also look further back with x[t-k], in which case the checker requires an initial boundary for every negative index that read can reach.
Most compilers check types and push everything else onto runtime tests. Zed's checker proves much more on every build, with no annotations, and it reports what it could not settle instead of guessing.
Because Zed is Turing-complete, no static analysis can decide every property of every program. Every check therefore ends in one of three states: proved, refuted with a counterexample, or undecided. Undecided is never treated as proved and never treated as false. The checker runs fixed procedures of its own and never executes the program's code to discover what it does. Those checking procedures are written in Zed as part of the standard prelude and run by the compiler's partial evaluator over a small built-in base, so every conforming compiler gives identical verdicts independent of machine speed, timing, or declaration order.
On every build, the checker tracks failure atoms through every expression so unhandled failures surface in result types and incomplete match expressions fail with an example of an unhandled value. It tracks integer ranges, collection lengths, linear integer constraints, and congruences. Full linear integer arithmetic is exponential in the worst case, so the checker splits constraints into independent variable groups and applies fast, exact procedures where they fit: a complete solver for up to three variables, shortest-path potentials for two-variable difference or sum constraints (±x ± y <= c), and the Omega test run only while the constraint set does not grow, reporting anything beyond that as undecided. Whenever those checks prove an array index in bounds or a divisor nonzero, #outOfBounds or #divByZero drops out of the type.
From demands on a function's result, the checker propagates preconditions backward to callers, and @ensure requires every check inside a definition to be discharged statically instead of being left as a runtime test. It rejects key collisions unless resolved, derives work and depth costs where it can, verifies that writes to a port commute or are ordered and that parallel reductions satisfy their algebraic laws, and enforces taint and secret-handling rules. A ? placed anywhere an expression, type, guard, or proof belongs marks an unfinished hole: the build rejects the file while printing the expected type and every name in scope whose type fits.
Every build also gives each definition two verdicts, whether it terminates and whether its live memory has a proved bound, and prints a concrete diverging input when it finds one:
// ✓ proved to end: n falls by 1 at each call and stays at least 0
countDown(positional n: int[0..]) = if n == 0 { 0 } else { countDown(n - 1) + 1 };
// warning: `halve(n - 2)` is not proved to end: with `n = 1` it calls `halve(-1)`, `halve(-3)`, ... forever
halve(positional n: int) = if n == 0 { 0 } else { halve(n - 2) + 1 };
// the signature of under50 carries a + b < 50, and every caller is checked against it
@ensure under50(positional a, positional b) = (a + b).refine(v -> v < 50);
ok = under50(10, 20);
// no = under50(30, 30); // ✗ rejected at the call: 30 + 30 is not < 50Three build tiers control how strictly these findings are enforced. The default zedc build warns on any surviving #bug, any value or recursion depth without a proved memory bound, any written trust (@assume, check: #off, @fair on a port, or an ungranted foreign assertion), any foreign library running outside an isolated process (apart from the standard library's OS layer), any unproved @equivalent switch lacking test inputs, and any definition or wait not proved to end. zedc build --strict turns every one of those warnings into an error except termination and unbounded waits. zedc build --total rejects those too, including any wait without a timeout. Putting a finite @timeout on main guarantees the process stops, and the warning notes that fact, though --total still rejects it because a process killed by a deadline stops without producing a value. Explicit claims written by the author (laws, @invariant, and @ensure) must be proved in every build tier.
A strict checker is only pleasant to use if its diagnostics tell you clearly what went wrong and what you can write instead. Every Zed error names the cause, traces each step by which the relevant facts reached the failing site, and prints types in ordinary Zed syntax. When it suggests fixes, it writes them as actual code, and it runs the checker on each suggestion first so every fix it offers compiles at that site.
Given this function:
twice(x: int) = x * 2.0;the compiler responds with:
error: A decimal literal is never an `int`: `x : int * 2.0`. Try `twice(x: int) = x * 2` instead.
followed by the step-by-step derivation (noting that 2.0 is a decimal literal, that * expects matching carriers from x: int, and that Zed converts no number implicitly) and the full menu of verified replacements, such as changing 2.0 to 2, converting x with rat(x), or widening x's type if callers allow it.
Fixed-width integer overflow is a long-standing source of wrong results and security bugs. A Zed int has no fixed width and cannot overflow. Instead, its type tracks the range of values it can hold, and the compiler chooses the machine representation from that range: adding two int[0..=255] values yields int[0..=510], which fits in 16 bits. Exact rationals (rat) are built in and have no size limit either.
Zed performs no implicit numeric conversions. Writing x: f64 = 9007199254740993; fails to compile because f64 cannot represent 2^53 + 1 without rounding. Writing 1 / 2 fails too: / is exact rational or floating-point division (integer division is div), and nothing in 1 / 2 says whether you want an exact rational or a float. The error offers verified fixes such as 1r / 2 for the exact rational one-half.
Floating-point rounding is tracked statically as a facet on the type (see Units of measure and facets). Whenever a float literal or operation may have rounded, its result carries inexact(), so functions that require exact binary values can reject rounded inputs at compile time:
c = 0.5f64 + 0.25f64; // 0.75, exact: both are binary fractions, so no inexact()
d = 0.1f64 + 0.2f64; // 0.30000000000000004 with inexact()
twice(x: f64 with inexact(false)) = x * 2.0;
// u = twice(d); // ✗ Rounded value at a parameter that refuses it: d rounded at 0.1f64 and +The same static-fact mechanism tracks float steps that can produce NaN, overflow to infinity, divide by zero, underflow, or lose precision through cancellation or absorption. Marking a function @fpstrict turns any potential NaN into the failure atom #NaN and warns at each of the other hazards. For stricter numeric code, a @checked float type surfaces all of those conditions, along with infinity, as failure atoms that must be handled before the next operation. A @checked integer type caps its range and returns #overflow if a result leaves it.
Complex numbers, quaternions, and octonions are built into the numeric library, and vectors and matrices carry their dimensions in their types, so multiplying matrices of incompatible shapes is caught at compile time.
Splitting a reduction xs >< (+) across CPU cores requires knowing that + is associative; otherwise different groupings can produce different answers. Zed's checker does not trust comments or unchecked annotations. It attempts to prove an operator's algebraic laws (associativity, commutativity, idempotence, and identity) directly from its definition. Once proved, the compiler splits the reduction into a parallel tree across cores.
User-defined combining functions receive the same analysis. If the checker proves your combining function associative, its reduction parallelizes automatically. If the operator breaks a required law, the build fails with a concrete counterexample: xs >< ((a, b) -> a - b) is refuted at (0, 0, 1). Even left-to-right folds that carry running state can parallelize when their step has a small closed composition. For example, this maximum-prefix-sum fold:
xs.foldl((0, 0), ((s, b), x) -> (s + x, max(b, s + x)))is recognized as a matrix product over the (max, +) semiring. Because matrix multiplication is associative, it runs as a parallel prefix scan without any annotation.
Floating-point arithmetic does not fit this picture, because IEEE 754 addition is not associative. In most parallel runtimes, summing floats across 8 cores gives different low-order bits than summing them across 16 cores. By default, Zed keeps parallel float reductions deterministic. Every float reduction uses a canonical tree whose shape depends only on the element count, never on thread count or schedule, so the result is bit-identical across runs, machines, and core counts while still running in parallel with logarithmic depth. To keep the rest of the float path consistent, the compiler never contracts a multiply and an add into one rounding unless the code explicitly calls fma, and elementary functions such as exp and sin are correctly rounded.
When you want a different point on the accuracy-versus-speed curve, you name the policy right on the reduction: compensated runs Neumaier's compensated summation on the same canonical tree for higher accuracy at roughly 1.5 times the cost, while unordered allows arbitrary grouping and ordering for speed and records that variation in the result's type:
total = readings >< (+); // canonical tree: same bits at any core count
precise = readings >< (+) compensated; // Neumaier summation on the same canonical tree
fast = readings >< (+) unordered; // any grouping or order; type records the variationCode that can read the system clock, open a file, or hit a database from anywhere is hard to reason about and hard to test. In Zed, a program interacts with the outside world exclusively through ports: standard streams, files, clocks, sockets, databases, and child processes. Everything outside ports is pure. Execution begins at main, which receives the program's command-line arguments, environment, and standard streams:
main(m: MainArgs) {
m.stdout <- "Hello, world!";
}Two operations on the same port must either commute (as declared by the port kind) or be ordered by data dependency or @after, so external output never depends on thread scheduling.
Because ports are explicit boundaries, tests can swap any port for plain data or a small function. Testing deadline logic against a fixed clock needs no mock framework:
late(positional deadline: Instant) -> bool = now().s > deadline.s
test with now = () -> Instant(s: 3600r) { Instant(s: 3599r) -> true, Instant(s: 3600r) -> false }Persistent storage and wire decoding fit the same model. A database table is a typed partial map whose fields are checked against its SQL schema at build time, and byte streams decode through layered codecs whose round-trip laws the checker verifies:
orders: OrderId ->? { total: rat, note: Utf8String | #none }
with store(postgres(dbUrl, table: "orders", schema: sql("db/orders.sql")));
events = m.stdin::bytes.via(utf8Text().then(json(Event)));Ports also carry operational policies directly in the language: retries with backoff, hedged requests to a second peer, circuit breakers, and rate limits. The checker rejects retry on any operation that is not safe to repeat, such as writing to a raw socket or calling a stateful foreign function. Back-pressure lives only at ports, as in input = m.stdin with bound(256, overflow: #block);, because the compiler sizes every internal queue directly from the dependency graph (and rejects any program whose graph it cannot determine statically; a bound written on an internal queue is only checked against that derived size). Child processes are launched directly from argument arrays with no shell, and they never outlive the parent Zed process.
When you edit one cell in a spreadsheet, you expect only the dependent cells to recalculate, and you expect the exact same answer a full recalculation would give. Zed programs work that way by default. Because values are never mutated in place, changing an input triggers recomputation only along its downstream cone in the dependency graph, and the incremental result always matches recomputing from scratch. Spreadsheets, build systems, and reactive user interfaces are ordinary Zed programs with no separate framework required.
Every value's keypath records the input, step, and element that created it. That lets a program inspect where any value came from and lets a debugger step backward through execution. Since a loop's history is a plain value, undo is a lookup in an earlier frame:
run = loop t { while t < edits::len; initial doc = empty; doc' = doc.patch(edits[t]); };
past = run::frames[run::len - 1].doc else empty; // the document one edit agoThe source code of a running program is itself an input stream, so saving an edit arrives like any other input wave. By default (Replay), the runtime runs the edited program on the recorded inputs and recomputes only what changed, updating past values as well while comparing prior outputs instead of writing them again. For a long-running server that does not keep its full input history (Continue), the edited program resumes from its current frames. A generation variable keeps its state unless its type changed with no migration function provided; in that case it restarts from initial, along with every generation variable that depends on it, and the runtime reports every variable that was restarted, dropped, added, migrated, or renamed.
Visualizers can draw any value in place as a picture whose elements carry their originating fact addresses. Clicking a drawn element jumps to the source line that produced it, selecting source highlights what it drew, and dragging an element on screen updates the literal in the source that controls it.
A function that feels instant on ten test items can turn out to be quadratic on ten thousand. Where its analysis applies, the Zed compiler derives each function's asymptotic work and depth as a symbolic bound over its input sizes, readable at compile time as f::cost. You can state an explicit bound with @cost, and the build fails if the derived bound exceeds it or cannot be bounded:
// ✗ rejected: the inner loop makes the cost O(n ^ 2), and the message offers @cost(O(n ^ 2))
@cost(O(n))
table(positional n: int[0..]) = for i in 0..<n { for j in 0..<n { i * j } };Two related annotations tighten performance choices without sacrificing soundness. Placing @equivalent on a size-based if that switches between two implementations (say, insertion sort for small arrays and merge sort for larger ones) claims that both branches produce identical outputs. The checker tries to prove equivalence and rejects the build if it finds a counterexample. When it cannot prove equivalence, the program runs the if as written and zedc test compares both branches on the test inputs named in the annotation (omitting those inputs draws a warning in zedc build and fails --strict). Placing @memoized on a function asks the compiler to cache results by argument, and the build rejects it if the function can return different results for identical arguments, such as by reading a port.
Unit tests check the inputs you thought to write down. A law states a boolean property over typed parameters for every possible input, and the checker tries to prove it on every build:
law sixDivides(x: int) = (x^3 - x) mod 6 == 0; // proved
law fourDivides(x: int) = (x^3 - x) mod 4 == 0; // ✗ refuted at x = 2, where x^3 - x is 6Parameters can carry where guards to restrict the domain, as in law noOverdraft(s: Account, t: Txn where t.amount > 0) = (apply(s, t) else s).balance >= 0;. To discharge a law, the checker walks a fixed, deterministic sequence of methods from cheapest to strongest:
- Exhaustive evaluation over small finite domains whose members are listed in the source.
- Decision procedures for the types involved: linear integer arithmetic, polynomials, divisibility, bit operations, and lattice and algebraic normal forms. Recursive calls are unfolded at most once per path and never executed, so a law mentioning
ack(4, 2)never tries to compute it. - Rewriting with laws that have already been proved.
- Induction over recursive types, along the call structure of recursive functions, and over loop steps.
- Case splits on unions,
matchexpressions, and conditionals. - Bounded model checking up to bounds explicitly written in the program.
- Generated property tests over sampled inputs.
- A written or pinned proof verified by a small, independent proof kernel.
A refuted law fails the build with its counterexample. An undecided law fails the build as well, reporting which step stopped and what goal remains; passing property tests alone never counts as a proof. You can either supply a proof or mark the claim as an explicit assumption with @assume, which the default build warns about and zedc build --strict rejects. Every proved law enters the optimizer as a valid rewrite rule.
The same machinery checks other claims. @invariant(p) on a loop proves that p holds at initialization and across every step, then makes p available to laws about the loop's result:
sumTo(positional n: int[0..]) = loop {
initial i = 0;
initial s = 0;
while i < n;
@invariant(2 * s == i * (i + 1) && i <= n) s' = s + i + 1;
i' = i + 1;
};
law sumLoop(n: int[0..]) = 2 * sumTo(n).s == n * (n + 1); // proved from the invariant@ensure checks that refinements vanish statically, and writing a result type narrower than a function body's inferred type creates an obligation the checker must prove in the same way.
When automatic steps stop short, you write a proof directly, either as a chain of equalities or by calling tactics such as byInduction, bySimp, and byCases. Tactics are ordinary Zed functions running at compile time that construct Proof values, as in Lean, so you can write your own without extending the trusted proof kernel. The kernel's verdict is pinned by content hash beside the source and rechecked whenever the code changes:
law square(ring: CommRing(T), a: T, b: T) = (a + b) * (a + b) == a * a + 2 * a * b + b * b
proof {
(a + b) * (a + b)
== (a + b) * a + (a + b) * b
== a * a + b * a + (a * b + b * b)
== a * a + 2 * a * b + b * b
}Interfaces such as CommRing can include law members that every implementing value must satisfy. State machines check the same way TLA+ checks them: loop invariants express safety, uncontrollable environment choices enter as parameters, and any counterexample comes back as a step-by-step trace value you can replay in the debugger.
Tests in Zed live right beside the definitions they exercise as plain data tables mapping inputs to expected outputs:
double(positional x) = x * 2 test { 0 -> 0, 2 -> 4 }Any test table can substitute ports with values, as shown in Ports are the only outside world. Because the dependency graph knows which functions depend on an edit, test runs re-execute only the affected slice.
Three built-in tools push testing further than hand-picked cases. zedc cover inspects the checker's own branch scopes and reports every if and match arm as reached (with a concrete input), unreachable, or undecided. Marking a function over a finite domain with @exhaustive tests every input at build time; even all 2^32 inputs of a single-argument f32 function finish in minutes. Finally, zedc test --mutate mutates one operator at a time (changing + to - or <= to <) and reports any mutant that neither the test tables nor the laws catch:
next(positional x: int) = x + 1;
law nextGrows(x: int) = next(x) > x;Here, mutating + to - is caught because nextGrows is refuted at x = 0. Changing x + 1 to x + 2 slips past and is reported as undetected, noting that nextGrows still holds. Adding law nextExact(x: int) = next(x) == x + 1; closes the gap and catches both.
Adding meters to seconds, or mixing pound-seconds with newton-seconds, is a common mistake that a compiler has all the information to prevent. Zed values can carry physical units that propagate through arithmetic automatically. A unit-polymorphic function written without annotations, such as sq(x) = x * x, accepts any ordinary ratio unit u and returns u^2, while rejecting shifted scales like °C and logarithmic units where squaring makes no physical sense. Conversion factors are computed exactly at compile time and rounded once on floats. Distinct kinds of quantity stay incompatible even when they share base dimensions, so torque (N m #torque) and energy (J, also N m) cannot be accidentally added.
Temperature scales need their own rules because a temperature reading is a point on a shifted scale, not a difference. Subtracting two Celsius readings produces a difference in Kelvin, and converting to Kelvin shifts by 273.15, while adding two readings is rejected:
noon = 20.0f64 with units("°C");
morning = 12.5f64 with units("degC");
rise = noon - morning; // 7.5 with units("K")
absolute = noon.to("K"); // 293.15 with units("K")
// both = morning + noon; // ✗ No `+` of two point readingsComparing two values of the same numeric type in different units of the same kind works automatically whenever their ratio is an exact rational, so 7 bit < 1 B evaluates cleanly without rounding either side. Comparisons whose ratio involves π (such as degrees against radians) require an explicit .to(...) so the rounding site is visible. Comparing a point reading in °C with a value in K also requires .to(...), since K could mean either an absolute temperature or a difference; two point readings on the same underlying scale, such as °C and a program-defined °F, compare directly as readings. Logarithmic values compare only within the same logarithmic unit.
Units are one instance of a broader mechanism called facets: typed properties attached to ordinary types and checked by one unified engine instead of separate type systems. Taint (untrusted input or secrets), sort order (such as descending or locale collation), and inexact (rounding on floats) are all facets too. Dropping a removable facet must be written explicitly with without, and the checker confirms the value actually carries the facet being dropped:
n = 1200 with units("m");
label = "${n}"; // "1200 m"
column = "${n without units("m")}"; // "1200"Security bugs usually come from three sources: untrusted data reaching a sensitive sink, secret keys leaking through timing side channels, and third-party dependencies doing more than they were asked to do. Zed addresses all three at compile time.
Data arriving from an untrusted source carries a taint facet. Taint propagates through every operation that reads the value, including implicit control-flow dependencies through if and match branches, until the value passes through a declared sanitizer. SQL injection therefore fails to compile:
// rows = exec(db, "SELECT * WHERE name = " ++ userName); // ✗ untrusted input reaches a clean sink
rows = exec(db, "SELECT * WHERE name = " ++ sanitize(userName));Cryptographic secrets face a different threat: an attacker can infer key bytes from branch timing, cache-line access patterns, or variable-time CPU instructions. Functions marked @cryptosafe(#secret) are checked all the way down to machine code so that branches, memory addresses and allocations, operands of variable-time instructions (such as division or floating point), and early exits or port calls cannot depend on values tainted #secret. On return, the runtime wipes those secret bytes from both memory and registers:
type SecretByte = u8 with taint(#secret);
@cryptosafe(#secret)
tagsMatch(expected: [SecretByte; 16], got: [SecretByte; 16]) =
(0..<16).map(i -> bitXor(expected[i], got[i])) >< bitOr == 0;Third-party libraries are constrained by content addressing and explicit capabilities. When you import a unit, the build records the content hash of the resolved code directly in the import line, so an upstream change cannot enter the build unnoticed. Without an explicit grant in the project manifest, an imported dependency has no access to foreign libraries, stores, or ports of its own; it can touch only the ports its callers hand it. Updating an import to a new hash reports every export whose type, proof grade, or reached ports changed (flagging any port the manifest does not grant) and runs the previous version's test tables against every export that kept its name and type:
// the build writes the hash; any change to the library produces a new hash
import geometry.shapes @hash("…");In Zed, a type is a set of values. You combine types with union (|), intersection (&), and difference (\), and one type is a subtype of another when every value in the first belongs to the second. There is no nominal class hierarchy to design up front.
Conditionals in if and match narrow types directly by set arithmetic: testing v is T narrows the true branch to old & T and the false branch to old \ T. An incomplete match is rejected with a concrete example of an uncovered value. Structs can also attach laws that every constructed value must satisfy:
struct Span { lo: int, hi: int, law ordered() = lo <= hi }Recursive union types automatically support .fold, which traverses a structure bottom-up and passes your combining function each node with its recursive children already folded.
C has preprocessor macros, C++ has templates and constexpr, and many other languages add a separate compile-time dialect alongside the main language. Zed uses one evaluator for everything. Any expression whose inputs are known at build time is evaluated then by the same evaluator that runs the program. Constants, specialized code, generic serializers, and compile-time type inspection (T::shape) all come from partial evaluation, leaving no need for macros or templates.
The standard JSON decoder illustrates how this works. It is ordinary Zed code that inspects T::shape and T::fields to see what a struct looks like. When the target type is known at build time, partial evaluation strips away the generic dispatch and emits a dedicated decoder for that struct alone. When the input text is also a literal, the entire parse folds into a constant:
struct User { id: int, name: Utf8String }
// specializes to a direct decoder for User, with no intermediate JSON tree
u: User | #parseError(..) = Json.decode(text);
// input is known at build time, so this folds to a constant User value
ok: User | #parseError(..) = Json.decode("{\"id\": 5, \"name\": \"John\"}");If a build-time evaluation exceeds the compiler's partial-evaluation budgets, it stays in the residual program and runs at runtime, producing the exact same result. When a static check depends on a value that exceeded a budget, the build stops with an error naming the budget, because every static check must settle at compile time. The checker's own prelude procedures run on this same evaluator, though they treat user code strictly as syntax data and never call it; a check only asks the evaluator for program values it needs, such as a bound n in int[0..=n]. Programs can also invoke the same specialization machinery at runtime via compile.
Category theory and abstract algebra explain why program transformations preserve meaning, yet languages that expose monads, functors, and natural transformations on the surface often end up hard to read. Zed puts the algebra in the compiler and keeps the syntax plain. No Zed program names a categorical concept; you encounter the math only as simple, consistent rules and clear error messages.
Every core rule in the language reflects a mathematical property. A reduction xs >< op is the unique homomorphism out of a list (or, when op is commutative, out of an unordered bag) that respects op, which is why every valid parallel split gives the same answer. On a recursive type, .fold is the unique function satisfying its fold equation, so the compiler can fuse folds and prove equalities between them without induction:
type Tree = #leaf | Node;
struct Node { l: Tree, v: int, r: Tree }
size(positional t: Tree) = t.fold(n -> match n { #leaf -> 0, Node(l:, r:) -> 1 + l + r });
mirror(positional t: Tree) =
t.fold(n -> match n { #leaf -> #leaf, Node(l:, v:, r:) -> Node(l: r, v:, r: l) });
// proved without induction: both sides satisfy size's fold equation, and that fold is unique
law sizeMirror(t: Tree) = size(mirror(t)) == size(t);Key transformations follow the same discipline. Pushing keys (rekey), pulling by lookup, and grouping are linked by adjunctions, and the collision rule is the condition under which pushing keys still produces a single-valued map (the key map is one-to-one, or a reducer merges collisions). A join followed by a reduction is a matrix product over a semiring, such as (max, +) for longest paths or (min, +) for shortest paths, so it parallelizes like matrix multiplication. Generic functions that only rearrange values commute with map by naturality, letting the compiler slide operations through maps. In the checker, the adjunction between image and preimage turns a demand on an output into the weakest precondition on inputs, while failure follows the exception-monad laws so checks move safely across operations.
Time and change share the same roots. Incremental recomputation and automatic differentiation are both derivatives, and reverse-mode differentiation is the transpose of the graph's push and pull edges. When a fold uses a group operation such as integer +, single-element edits update the aggregate in constant time by subtracting the old value and adding the new.
Because two algebraically equal programs can have very different run times, the optimizer never treats a rewrite as free. It applies proved laws inside an e-graph, a structure holding many equivalent forms at once, and extracts the form with the lowest cost according to the cost model. A small certificate checker, separate from the optimizer, independently verifies every rewrite step.
Calling into C is where memory safety usually ends. Zed keeps the boundary explicit and predictable. When Zed reads through a pointer received from C, a misaligned address halts the program immediately with a fixed exit status (3), and a null pointer where the declared type forbids null evaluates to #invalid. Assumptions that no runtime read can verify, such as whether a C struct matches the declared layout, are recorded as stated assumptions on the foreign declaration and listed in the build report.
Ownership across the boundary follows clear defaults. Arguments passed to C are lent for the duration of the call unless the signature declares that C retains them. A pointer returned from C is copied at return unless its type attaches a release function, it is memory Zed lent earlier and C is handing back, or the signature marks it @borrowed:
@foreign struct Sample { t: u64, value: f64 }
@foreign("sensor", "sensor_free") @nonblocking
freeSamples: (p: Ptr([Sample] with length(1024))) -> #ok | #lost;
@foreign("sensor", "sensor_read")
readSamples: (count: i32) -> Ptr([Sample] with length(1024)) with release(freeSamples);Zed restores its pinned floating-point environment whenever a foreign call returns, so C libraries compiled with aggressive math flags cannot silently alter rounding modes in Zed code. To prevent a buggy C library from taking down the whole program, adding isolate: true runs the library in a separate child process and turns crashes into ordinary failure values such as #signal. An isolated library can also be confined with restrict, using the operating system's sandboxing controls to limit files, networking, and subprocesses. Going the other direction, Zed packages export cleanly to C with a generated header.
Hand-written parsers and printers for the same data format almost always drift apart over time. In Zed, a single grammar declaration on a struct produces both its parser and its printer, with the round-trip guarantee that serializing a value and parsing the result returns the original value. For that guarantee to hold on unions and choices, the canonical text emitted for each alternative must parse back to that same alternative; the checker verifies this emission-disjointness wherever it can and reports any case it cannot discharge:
struct Vec3 grammar { "(" x: f64 "," y: f64 "," z: f64 ")" }
v = Vec3.parse("(1.0, 2.0, 3.0)") else Vec3(x: 0.0, y: 0.0, z: 0.0);
s = v.serialize; // "(1.0,2.0,3.0)"Grammars cover binary wire formats using the same bit-width, endianness, and length facets used for foreign structs. String types can also be constrained by a grammar directly, replacing ad-hoc regular expressions with checked types such as type Ident = Utf8String matching grammar { alpha (alpha | digit)* };.
Because a function's syntax tree is ordinary data via ::source, programs can inspect functions as mathematical formulas. A symbolic algebra library written in Zed handles simplification, expansion, factoring, substitution, differentiation, series expansion, integration, and equation solving. Every algebraic step carries a justification verified by the proof kernel, and the function's parameter types serve directly as the mathematical assumptions:
p = ((x: rat) -> (x + 1r)^2)::source;
e = expand(p); // the tree of (x: rat) -> x^2 + 2r * x + 1r
d = derivative(p); // the tree of (x: rat) -> 2r * x + 2r
i = integral(p); // the tree of (x: rat, c: rat) -> x^3 / 3r + x^2 + x + c
f = compile(i); // the compiled function itselfintegral returns an antiderivative with a constant of integration c, backed by a kernel-checked proof that differentiating the result yields the original formula and that the antiderivative is defined wherever the formula is. When no closed form can be produced, it returns #noClosedForm with one of three specific reasons: the antiderivative leaves the number type (x over int integrates to x^2 / 2, which is not an int), no elementary antiderivative exists (as with exp(x^2), accompanied by a proof), or the expression lies outside the fragment the library decides. As with any operation that can only fail, an integration call that always produces #noClosedForm is a compile error:
// ✗ always #noClosedForm(why: #notInCarrier): x^2 / 2 is not an int
// bad = integral(((x: int) -> x)::source);Because parameter types act as assumptions, ((x: int, y: int[1..]) -> (x * y) div y)::source simplifies cleanly to x. On floating-point formulas, real-number identities are applied only when explicitly requested, because rewriting floats under real algebra changes the rounded function they compute.
Automatic differentiation uses the exact same ::source representation for forward mode (jvp), reverse mode (vjp and gradient), and Hessian-vector products (hvp):
loss = ((w: [f64]) -> w.map(x -> x * x) >< (+))::source;
g = gradient(loss); // a tree equal to (w: [f64]) -> w.map(x -> x + x)
h = hvp(loss); // a tree equal to (w: [f64], v: [f64]) -> v.map(y -> y + y)At a kink or tie, such as abs at 0, differentiation returns #notDifferentiable(at: s) naming the site instead of silently picking a one-sided slope. The same library also normalizes Boolean formulas, minimizes them, and checks satisfiability and equivalence.
Because Zed's intermediate representation preserves the full dependency graph, domain bounds, and algebraic metadata, one program compiles across very different hardware: multicore CPUs (Linux on x86-64, ARM64, and RISC-V, plus macOS and Windows), WebAssembly, GPUs, multi-node clusters, and microcontrollers. Programs whose regions all have static schedules also compile to hardware synthesis. The compiler itself compiles to WebAssembly and runs directly in a browser.
Distributed execution uses the same dependency graph. Cutting a program along graph edges splits it across machines, and the compiler generates the serialization and message contracts between sides directly from the crossing types. A client and server can therefore be written and type-checked as one program:
req: Stream(Query);
resp: Stream(Answer);
main() {
resp <- req.map(q -> lookup(db, q) else #unknown);
}Zed has structs, structural interfaces, and uniform call syntax, and method syntax is shorthand for a function call. A method that updates its receiver is an ordinary pure function that returns the receiver's next value ahead of its declared result. The caller either binds both values or writes the call short with *.:
c', v = c.bump(3); // c' is the next value of c, and v is the result
// v = c*.bump(3); // shorthand for the same call in place of the line aboveParameters are passed by name unless declared positional, except that a function of one parameter accepts its argument either way, since there is nothing to swap. A plain-named function of two required parameters can also be written infix, which keeps the function's name visible in the source:
plus(a: Point, b: Vec) = Point(x: a.x + b.x, y: a.y + b.y);
q = p ~plus~ v; // the call plus(p, v)A language is defined as much by what it leaves out as by what it includes. Zed leaves out these on purpose:
- Classes, inheritance, and object identity. This is for simplicity: structs, structural interfaces, and method syntax over plain functions already cover what classes are used for, so classes would be a second way to write the same program. Object identity would also bring back shared mutable objects, which Zed removes to make data races impossible.
-
Operators defined or overloaded by programs, so that
+and*mean the same thing in every program. Where a program can redefine an operator, a reader cannot tell whata + bdoes or what it costs without finding the definition, and the compiler cannot rely on laws such as associativity, which parallel reductions need. - Dependent types, so that type checking stays decidable. Once a type can contain an arbitrary program term, checking a type needs deciding whether two programs are equal, which no checker can always do, and programmers end up writing proofs just to get code accepted. Zed's value ranges and set types give most of the same checks without that cost.
-
Effect annotations. In languages that have them, such as checked exceptions in Java or
asyncin many languages, one annotation spreads through every caller's signature, and a small change deep in a program forces edits all the way up. Zed needs none, because the only effects are reads and writes on ports, and those are ordinary data. - A fixed lazy or strict evaluation order. Lazy evaluation by default makes memory use hard to predict and causes space leaks, where unevaluated work piles up. Strict evaluation by default computes values that nothing reads. Because a Zed program's meaning does not depend on evaluation order, the compiler chooses the order for each value by cost.
- Categorical abstractions in the surface language, such as user-defined monads and functor classes. These ask every programmer to learn a large mathematical vocabulary, and programs that need several monads at once must stack them in a fixed order, which is hard to get right and hard to change. As Algebra under the syntax explains, that math stays inside the compiler.