Stories: Algebraic Data Types
See also:
spec/adt.md— the rules these chapters explain.
Separate enum and variant keywords
The first question a sum type raises is whether payloadless constants and payload-carrying alternatives are one construct or two. Almost every modern language answers one; we answered two, deliberately, knowing that. The mainstream — Rust, Swift, OCaml, Haskell — gives you a single construct that covers both payloadless constants and payload-carrying alternatives. enum Color { Red, Green, Blue } and enum Expr { IntLit(String), Flip(Box<Expr>) } are the same keyword, one general sum type that degenerates to a plain constant set when none of the cases happen to carry data. It is a clean, celebrated unification, and it is the road we did not take.
We did consider it — a single unified sum construct sat with us for a while — but it never actually cohered, and the more we looked the less sense it made. The two roles a “sum type” is being asked to fill are not one idea seen at two zoom levels; they are different ideas. A set of colors, weekdays, operators is a set of interchangeable peers: you iterate them, ordinal-index them, build a total table over them, ask “which one is this” and get a uniform answer for every case. A sum like Expr is the opposite — its cases are heterogeneous, each carrying its own payload, and they share only the fact that a value is exactly one of them at a time. Fold both into one keyword and the peer operations — iteration, total mapping — get quietly mixed with cases where they are meaningless, because you cannot iterate the values of IntLit(String) the way you iterate Red, Green, Blue. The unification buys one keyword and pays for it by blurring the line between “uniform peers” and “tagged payloads,” which is exactly the line we care about.
So Zane splits them. An enum is a closed set of lowercase, payloadless peers of one uniform category. A variant is a sum type whose members each carry a payload. The property that determines which construct you have is uniformity — the substitutability of intent — not structure: the moment a case needs its own heterogeneous payload it is a variant, and as long as the members are interchangeable it is an enum. Keeping them apart lets each stay simple — enums uniform and tabulatable, variants heterogeneous and dispatched — instead of overloading one construct with both jobs.
The same strong stance shows up in what we refused to build on top: no interfaces, no constraints over enums. The temptation is to let two enums that keep appearing together share some abstract contract. But if two enums genuinely travel together all the time, that is evidence they are one enum and should be merged; and if they do not, wrapping them in a variant plus a few matching functions is a fair price for a rare case. Building open-extension machinery for a situation that resolves itself either way is overengineering, so there is none.
The cost is real and we are not going to pretend otherwise. Two keywords is more surface than one, and there is now a judgement call at the boundary — is this type an enum or a variant? — that the unified design never forces you to make. Going against a near-universal convention also has a teaching cost: a programmer arriving from Rust reaches for one enum to do both jobs and has to be retrained. And splitting the constructs is what creates the loose end that enum maps later have to tie off — because once enum members are payloadless on principle, per-member data has to attach from outside the members, which is more machinery than just writing a field on a case. We think the clarity is worth all of it, but it is not free.
One body, product or sum
Having split variant off from enum, the variant still needs a body — a notation for its members and their types — and here the pull was the opposite of the last chapter. There, we resisted unifying two constructs; here, we leaned into a symmetry that was genuinely there. A variant’s body is a set of named, typed members. So is a struct’s. Rather than invent a second grammar for that, Zane makes them byte-for-byte identical: struct { a A; b B; } and variant { a A; b B; } share one body shape, and only the keyword changes.
The road not taken was a dedicated sum syntax — Rust’s Ctor(T) cases with their own parenthesized payloads, OCaml’s | Ctor of t bars. Those read fine, but they invent a distinct notation for a member that is structurally identical to a struct field: an identifier and a type. Reusing the struct body instead makes the and/or duality legible at a glance — same body, struct means has a and b, variant means has a or b — and the keyword flips four properties in lockstep. Meaning flips from and to or. Construction flips from “set all members” to “set exactly one.” Layout flips from the sum of the member sizes to a tag plus the max. And the read flips from total to partial: reading e.a on a struct always gives you an A, but reading e.a on a variant gives you an A only if a is the live case.
That partial read is the one consequence worth dwelling on, because it could have gone several ways. A case that is not live has no value to hand back, and the usual answers are a sentinel (null, a zero value) or a silent failure. Zane makes the read abortable instead — a bifurcated return that flows through the ordinary ?/?? error path — so a partial read is honest about being partial and cannot be mistaken for a total one. A single-payload case, once bound, behaves as its payload, so you reach through it directly; but you only get there by acknowledging the read might not fire. The primary consumer is never meant to be the ad-hoc member read anyway — it is exhaustive dispatch, the subject of the next two chapters.
Orthogonal to all of this is the value/reference axis, and it is what determines recursion. A plain variant is a value sum — copied on assignment, transitively a value, and therefore non-recursive; a #variant is a reference sum with identity that may hold & payloads and may recurse. This is not an ADT rule so much as the whole language’s identity-is-opt-in commitment showing up here: a value type cannot hold the & that a recursive case must box through, so a recursive sum like Expr has to be a #variant, never a value variant. The indirection is always an explicit & — no hidden auto-boxing, the way Box is hidden in some languages — because ownership and references are explicit everywhere in Zane. The deeper argument for why a value type is closed inline storage that cannot recurse belongs to the memory story; here it is enough that the same body grammar serves all four kinds and the # modifier is what determines which may recurse (see memory.md §2.10 for the transitive-value rule).
The cost of the shared body is small but worth naming: you cannot tell a product from a sum by looking at the body, only by reading the keyword in front of it, and a variant can never grow a surface that deliberately reads differently from a struct even where that might aid a reader. We think making the duality visible is worth giving up that freedom, and in practice the keyword is right there. It is a far cheaper cost than the cost the next chapter takes on.
Escaping the matcher machine
With variants defined and their reads made honest, the real question is how you consume one — and this is where Zane departs hardest from the ML tradition, out of a concrete irritation rather than a theory. The irritation is scale. Textbook pattern matching is always shown on a toy: three or four cases, a one-line body each, the whole match fitting in a tidy block. The sum types we actually care about are not like that. An AST Expr has dozens of cases, and the logic for each is not a one-liner — it is real work, sometimes a lot of it.
Pour that into the ML answer — a single match/case expression with the scrutinee on top and every arm below — and two problems appear at once. First, it becomes a matcher machine: one enormous expression that every case’s logic is crammed inside, the function equivalent of a thousand-line switch. Second, and this problem actually shaped the design, the structure forces depth. The match is one level of nesting; each arm’s body is a second; so the substantial per-case work starts two levels deep and only goes deeper from there. You pay indentation on precisely the code that matters most — the handler bodies — in every single arm, permanently. For a handful of arms that is invisible. For thirty arms of real logic it is a tax you notice every day.
The move that gets out of this came first, before any inline match syntax existed, and it is the heart of the whole design: bind the arm to the function itself. Instead of arms nested inside a match expression, each case-handler becomes an ordinary top-level function overloaded on the case:
String exprToString(x Expr.intLit) => toString(x)
String exprToString(x Expr.floatLit) => ...
The dispatch is unwrapped — spread flat across named definitions rather than stacked inside one expression. Every handler body sits back at its natural, single level of depth. There is no matcher machine, because there is no one place the cases pile up; there is just a family of ordinary functions that happen to share a function name and partition a variant between them. The arm bodies that would have sat two levels deep are now function bodies one level deep, and each can grow as large as it needs to without dragging the others down with it.
The compiler makes this safe by treating all overloads of one function name over a variant’s cases as a single match set and checking that the set covers every case — an incomplete set is a compile-time error. It lowers to a runtime tag jump, distinct from ordinary static overload resolution (see functions.md §4.4): a value whose static type is the whole variant becomes an O(1) jump over the case overloads, while a value already narrowed to a case picks its arm statically with no jump at all. Two rules fall out of doing dispatch this way. Exhaustiveness is checked per package, not per variant — the arms of one match must be co-located so a single compilation unit can verify completeness — which is what lets the type stay closed while operations stay open: any package may import a variant and declare its own complete match over the cases, because the cases are fixed and all visible, but no one may split one match across packages. And a whole-variant overload f(x V) cannot coexist with case overloads f(x V.case) for the same name, because a call would be ambiguous between matching V directly and unwrapping it; forbidding the coexistence removes the ambiguity by construction.
The cost is the mirror image of the benefit, and it is a genuine one. Unwrapping the dispatch into separate functions destroys locality. You can no longer see all thirty arms in one place; they are scattered across the package, and the shape of the dispatch — the fact that these functions together partition Expr — is implicit in the set of overloads rather than visible as a single block. For a reader whose question is “what are all the cases and how is each handled,” the very matcher machine we were fleeing is actually the better artifact, because it is one block you can read top to bottom. That tension — flat but scattered, versus nested but co-located — is real, and it is exactly what pushed us to add an inline form as well, which is where the next chapter starts. There is also plain extra machinery here: the per-package exhaustiveness rule and the mutual-exclusion rule are two rules a reader has to hold that a simple local match would never need.
Variants, not patterns
The scattering that case overloads cause made us want a second, local form — a construct for the times when a handful of arms genuinely belong together in one place and you would rather see them as a block than hunt for them across a package. That is the match expression: a scrutinee and a flat [ ] list of callables, dispatching on the tag to the callable whose parameter type matches the live case. It came second, after case overloads, and it is deliberately the small-scale tool, not the tool you reach for at AST scale.
Its defining choice is that it has no special arm syntax — the arms are ordinary function values, lambda literals or named lambda-variables, so an arm can be named, reused, and passed like any other callable. That is very much in the grain of the rest of the language, which keeps reaching for existing machinery instead of minting new syntax. But we will be honest that we are not sure it is right. The match expression may conform to that generality too hard: insisting an arm is just a function value whose parameter type happens to be a case buys consistency, but the surface it produces — a bracketed list of lambdas — is arguably more ceremony than the common case deserves, and a dedicated arm might simply read better. We have not settled this, and the opinion may move; we are recording it here as a live tension rather than dressing it up as a finished win. It is the one part of this document we would least defend to the death.
Underneath both dispatch forms sits the decision the whole area actually rests on, and it is a decision about scope, not mechanism. The ML and Rust world calls this feature pattern matching, and that name smuggles in a whole kit: nested patterns that reach several layers down in one arm, or-patterns, guards, as-bindings, structural destructuring of tuples and records and literals. Zane takes none of it, on purpose. Our disagreement is with the framing itself — “pattern matching” runs together two separable operations: dispatching on a sum’s tag, and destructuring arbitrary shape. We think the tag-dispatch is the part that carries the weight, and the “pattern” half is not that important. We care a great deal about variants; we care very little about patterns. So Zane matches variants — a one-level tag unwrap, a single-payload case behaving as its payload once bound — and stops there. No nested dispatch, no guards, no shape-binding.
Refusing full structural patterns rests on two arguments, and the second argument really convinced us. The first is the familiar argument: a pattern language is a second language — its own grammar, its own binding rules, its own nesting — grafted onto the host, and Zane spends its whole budget avoiding exactly that kind of bespoke sublanguage. But the sharper argument is that deep patterns reintroduce the very nesting we just spent a chapter escaping. A nested pattern is depth in the matcher; the entire move of the last chapter was to flatten dispatch outward into functions rather than push it inward into richer arms. Those two instincts point in opposite directions, and once we saw that, the choice made itself: Zane flattens. Adding nested patterns would undo the property that makes the design ours.
We want to state the OCaml comparison without flinching, because it cuts both ways. Measured on structural pattern matching as such, Zane is deliberately weaker than OCaml — it cannot destructure three levels deep in a single arm, and when you genuinely need that you nest matches, or reach through abortable member access, by hand. That is a real expressiveness cost and we are not going to hide it behind the “it’s a non-goal” phrasing. But measured on the job sum types usually do — dispatching over a large closed set of cases, each with real work — case overloads are, we would argue, better than a thirty-arm match, because they do not pay the nesting tax. The bet the whole design makes is that the second workload is the common and important workload for the data we care about, and the first is rare enough to do by hand when it comes up. Whether that bet holds across everything people build is the open question this chapter leaves on the table.
The costs, gathered in one place: deep destructuring is manual and occasionally clumsy; the match expression’s generality is possibly overbuilt for its job; and standing against the “pattern matching” grain has a teaching cost every bit as real as the cost in the first chapter — newcomers arrive looking for guards and nested patterns and meet a smaller, sharper tool instead, and some of them will read the smallness as a gap rather than a stance. The abort integration that lets a match pass an abortable arm’s failure one level up is the one place this all reconnects to the wider language (see error-handling.md §3.5).
Payloadless peers keep their data outside
Splitting enum from variant and keeping enum members strictly payloadless raises an obvious question: where does per-member data go? A weekday has a display name, a color has an RGB triple, an operator has a precedence. In the unified world you would just write the datum as a payload on the case. Zane forbids that by construction — the moment a member carries data it is no longer an interchangeable peer — so the data has to attach from outside the enum entirely.
The answer is the enum map: a package-scope, exhaustive, access-only declaration that pairs each member with a value and is read field-style.
Colors.colorName String [ red = "Red", green = "Green", blue = "Blue" ]
Colors.red.colorName // "Red"
It names the property at the site where it is read, it reserves no keyword — deliberately, so Map and Dict stay free for a future dictionary type — and it is checked exhaustive exactly the way a match set is, so a forgotten member is a compile error rather than a hole. The reason it is a map and not a payload comes straight back to the first chapter’s criterion: intrinsic data would make the member a variant case, whereas external data keeps the members payloadless and the data uniform, which is precisely the enum’s defining property preserved rather than broken. A variant would never need an enum map, because a variant’s data is intrinsic to each case by definition; the map exists specifically because an enum’s does not.
One further line we drew: an enum map is not a passable value. The mapping is static — there is nothing to dispatch over, only a result to read — so making it a first-class value would give runtime identity to a table that has no runtime behavior. A genuinely dynamic Colors → String transform already has a construct; it is a lambda, String[Colors]. Keeping the static table and the dynamic transform as different constructs means the map stays the simple static lookup it is, and anyone who needs real dispatch reaches for the function type instead of stretching the map to cover a job it was not built for.
The cost is the cost the first chapter warned was coming. Per-member data now lives away from the member — you declare Colors in one place and its colorName table in another, and adding a member means touching every map that ranges over the enum (the exhaustiveness check will at least tell you which). For data that is genuinely intrinsic and always present, that separation can look like bureaucracy next to just writing a field on the case. But that friction is also a signal worth listening to: if the data really is intrinsic to each member, you probably did not want an enum at all — you wanted a variant, and the map’s awkwardness is the design’s signal of that mistake.
Variants deserve a central place
Everything to this point describes the dispatch we actually committed to — and then we talked ourselves out of its most distinctive piece, the case overloads. The case overloads of Escaping the matcher machine were built to kill the nesting tax, and they do kill it, but the longer we sat with the picture the more one cost swallowed the win. Spreading a variant’s handling across a family of top-level functions buys flatness by spending locality: there is no longer any single place where the whole variant is seen being dealt with. And for a variant — of all types — that is exactly the wrong property to give up. A sum’s entire meaning is “one of these N things,” and the view you most want in front of you is all N handled together, as one exhaustive picture. Scatter that across N definitions and you have hidden the one structure that was worth showing. The dispatch table is not boilerplate to be dissolved; it is the artifact. Variants deserve a central place.
That sentence is what kickstarted the redesign, and its first consequence was the admission that we had misdiagnosed the original problem. The nesting tax was real — a thirty-arm match with fat bodies does bury its important code two levels deep — but the fault was never the block, it was the fat arms. Keep the block and keep the arms thin, each one a shallow dispatch that hands off to a flat top-level function, and the tax simply is not paid: the block holds the dispatch, which is what you want central, while the work lives in ordinary functions the arms call. We had thrown out the central place to solve a problem that only ever needed the arms to lose weight. So the case overloads were the detour, and the small match expression we had kept as a secondary form was the right primary shape all along.
Making the block central let us delete the machinery it had been carrying precisely in order not to be central. The old arms were function values selected by their parameter type — an arm was a lambda whose parameter happened to name a case — and that contortion existed only to keep arms first-class and reusable. A central block does not need reusable arms; it needs the cases laid out in one place. So the parameter-type dispatch went, and the per-arm return-type ceremony went with it: the block declares its one result type once, at the front, not on every arm. A block needs instead an arm that reads as the construct it already is in Zane — a declaration. x strLit => body binds x, whose type is the case strLit, with the Expr. supplied by the scrutinee, exactly the way x Int binds a value elsewhere; the casing rule carries the whole binding with no new syntax. The binder is optional — a bare strLit => body when the body needs no payload — because an unbound head introduces no parse ambiguity and Zane already leaves names optional in the same spirit, most visibly in the ? error handler that binds ? err { } or does not.
Grouping several cases into one arm is where the surface paid us back for moving to a block. With the arms living in { }, the [ ] that the old match had spent on its arm list was free again, and a bracketed set of cases is exactly what it should be spent on: x [intLit, floatLit] => body. This is the same bracket that declares a set of peers in enum [ red, green, blue ], now selecting a set of cases — grouping cases in a match rhymes with grouping members in an enum, which is the kind of internal echo we trust. A singleton is then just the one-element case of a group, and the bracket stays a case selector, never a type: for a single case the binder is its payload as before, and for a group — whose payloads differ — the binder widens to the variant, so no anonymous unnamed type is ever conjured and the “every type must be named” rule stays whole.
The last change the central place forced was the removal of the default arm, and this is the part we feel most strongly about. A catch-all carries no type information; it covers only “every case not matched above,” and that set is implicit and unstable — it silently changes when the variant grows a case or when another arm is edited. So a new case added to Expr would vanish into the default without a word, which is precisely the accident exhaustiveness exists to prevent. A central place is only worth having if it is complete, and a default is an escape hatch out of completeness. So there is none: every case is named, singly or inside a [ ] group, and adding a case to the variant becomes a compile error at every match until someone decides where it goes. That is the whole point restated as a rule — the variant’s central place must account for the variant, all of it, out loud.
None of this is free, and the bill lands in the same spot the default was covering. “Everything else” now has to be enumerated: a thirty-case variant where you truly handle two specially and the rest identically makes you list the twenty-eight, by name, in a bracket. That is more to type, and it is deliberately so — the list is a checked record, and the compiler keeps it honest as the variant changes — but it is real friction, and it is loudest where several scrutinees are matched together and a “regardless of state” arm has to spell out every state. The other cost is the cost we opened with, now paid from the other side: choosing a central block over scattered overloads trades the flat top-level-function style for locality. Open operations survive — any package can still write its own f(e Expr) => match e { ... } over an imported variant — so nothing is truly lost there, but the particular pleasure of a variant’s operation being a loose family of same-named functions is gone, on purpose, in exchange for being able to read the whole operation in one place. We think that is the right trade for a sum type. And it is still, unchanged, variants and not patterns: the block dispatches on the tag and nothing deeper, and bracket-grouping is a set of tags, never a step toward matching shape.
One extension came later, and from a deliberate stock-take: after weighing where this design still lagged OCaml, we wanted to know which absences were principle and which were merely missing. Most of the elimination gap — nested patterns, guards — we were content to keep as principle. But one was not a matter of taste. OCaml matches a pair of values in one go, and a great many real dispatches — state machines above all — are joint, keyed on two tags at once rather than one. So we added multi-scrutinee matching: a match takes a bare comma-separated list of scrutinees, and each arm gives one selector per position. The tell that this stays on the right side of the variants-not-patterns line is, once again, a missing pair of parentheses. match state, event is several variants matched together; wrap it as (state, event) and you have named a tuple to take apart, which is the pattern-matching road. Bare, it is only ever tag dispatch — now across a product of tags rather than one, the and to the arm-group’s or. The cost is the cost the no-default rule already charges, paid again on the product axis: exhaustiveness becomes the cross-product of the case sets, so a “whatever the state, on reset” arm has to name every state, and the table grows with each variant it joins. We judged that verbosity a fair price for finally being able to write the one shape the single-scrutinee block genuinely could not — the joint transition table.
The group is sugar, not a widening
The central block shipped with a group-binder rule we got wrong on the first pass, and it broke the very sentence the last chapter ends on: bracket-grouping is a set of tags, never a type. We believed that and then wrote a binder rule that quietly broke it. A single-case arm x strLit binds x at that case’s payload — obvious. But a group arm x [intLit, floatLit] groups cases whose payloads may differ, and we had to define the type of x in that arm. Our first answer was that it widens to the whole variant: give the binder the one type that covers every case in the bracket and the arm still type-checks. It looked conservative and safe.
It is neither, and we did not catch it ourselves — it surfaced in a conversation where someone repeated their model back to us, assuming a group was simply several arms sharing a body, and we realised their assumption was better than our spec. The trouble with widening is not its waste, real as that waste is. It is that it un-does the match. The arm’s whole reason to exist is that the tag jump has just proven x is one of {intLit, floatLit} — that proof is the block’s whole purpose. Widening then re-types x as the entire variant, which is strictly less than what was just established, so to actually use x you must abort-read it back into a case: re-running, by hand, the dispatch the jump already performed. You narrow, then un-narrow in the same breath. A construct whose one job is to pin down a tag cannot be allowed to throw that tag away as it binds it.
Stated that plainly, the fix is forced, and there were only ever three ways to type the binder. Keep widening — incoherent, for the reason just given. Narrow the binder to a sub-variant {intLit, floatLit} — this keeps the tag, but it conjures a type nobody named, and “the bracket is a selector, not a type” was a rule we had just spent a whole chapter defending; we were not going to break it one section later to patch a binder. Or the third road: stop treating the group as a construct that has a type at all, and treat it as pure syntax. x [intLit, floatLit] => body is nothing but x intLit => body; x floatLit => body; written once — two arms, each binding x at its own payload, each checked on its own. That was the model the conversation handed us, and it is the model that keeps every earlier promise at once: the tag is preserved, because each stamped arm carries its exact case; no unnamed type appears, because each binder is an already-named payload; and the bracket is a purer selector than widening ever made it, because now it selects nothing but the set of arms to stamp out.
The amount that disappears when the group is only sugar settled it. The binder-type rule we had been agonising over does not get rewritten — it gets deleted, because a group binder does not exist, only ordinary single-case binders in arms that were written together. Exhaustiveness needs no special clause: N stamped arms cover N tags. The one-result-type rule already covers them. Even the multi-scrutinee grouping we had worried about separately falls straight out — [a, b], [c, d] is just the cross-product of stampings, which is exactly the cross-product exhaustiveness the joint block already demanded. A rule that dissolves three special cases into one desugaring is almost always the right rule; we should have reached for it before inventing a type for a bracket that never needed one.
The cost is real and it lands in one place: the binder can no longer stand for the whole variant, ever. Under widening you could write x [a, b] => useVariant(x) and hand the whole value off; now x is a payload in each stamped arm, and that call does not type-check unless useVariant is overloaded across the payloads. The answer is that the scrutinee is still in scope — an arm that needs the variant reads the scrutinee, not the binder — which is clean except where the scrutinee is an unnamed temporary and there is nothing to refer to, a narrow corner we are recording as a known edge rather than papering over. The deeper cost is set by the no-interface stance: because Zane has no contract spanning arbitrary types, the only operation you can apply to a binder shared across differing payloads is a call to a function overloaded for each, so a shared binder pays off exactly where such an overload family already exists and does nothing for a genuinely heterogeneous “everything else” group — which is why those groups are, in practice, left unbound. That is the honest shape of it: the sugar is free and the per-case checking it implies is free, and the one capability it lacks is a common interface, which we deliberately chose not to have. It remains, throughout, variants and not patterns — the stamped arms are more tag arms, never a step toward matching shape.
Naming a case, not calling a constructor
Everything to this point had been about consuming a variant — the central block, the stamped arms, the tag jump — and along the way we noticed we had never stated how one is built. The gap was hiding in plain sight. The struct/variant symmetry table carried a “Construct” row whose variant cell read “selects exactly one case,” and that cell pointed at nothing: no section, no syntax, no example anywhere actually built a value. A reader could declare an Expr, could match an Expr, and had no sanctioned way to make one.
The obvious first reach was init{ }, the tool a struct already uses — and it does not fit, for exactly the reason the symmetry is worth having. init{ } means set every field, once each; a sum sets one case, not all. To borrow the braces for a variant we would have to flip that one rule from “all” to “exactly one” while keeping the syntax identical, which is precisely the same-look-different-meaning trap the shared body already walks a fine line around. The body grammar can be identical because the keyword shows which reading applies; an init{ } that silently meant “all” under struct and “one” under variant would be the same syntax with no keyword to carry the difference. Construction had to look different — and the table had stated as much all along, listing construction as one of the four properties the keyword flips.
So we went the other way and asked what a variant already looks like when you read one. A case is reached as Expr.intLit — type on the left, case on the right, the same Type.member selection a field read uses and the same shape an enum member is named by. Give that selector an argument and it becomes the way you build one: Expr.intLit("5") names the case, hands it its payload, and yields an Expr with that case live — and because a case carries exactly one payload type, there is exactly one argument to give. We want to be careful about naming this form, because the tidy word for it is a trap. It is not a constructor. A struct’s constructor is a verb — a real declaration you can write, overload, and give a running body (see the types story); naming a variant case is none of that. It is built-in syntax with no verb behind it, the direct way to write down a sum value — closer to an integer literal than to a call. Nothing is generated, nothing is declared; the case names itself. The payload still sits at an ordinary coercion site, so implicit conversions fire there like any argument; a payloadless enum member is the very same form with the argument list dropped, Colors.red the nullary case; and the whole form is an expression, so it drops into a return, a call, or another case’s payload with no statement-form carve-out.
One real choice was left, and a reader is most likely to prod it: the type of e in e Expr.intLit("5"). A case can be projected as a type — the spec leans on Expr.intLit as a parameter type elsewhere — so one coherent answer is that the shorthand declares e at that narrowed case type, which then widens to Expr where it must. We tried that framing and dropped it, because it smuggles a whole subtyping story in through a construction shorthand and it fights a variant’s one purpose. A sum exists so a value can be any of its cases; the normal value to hold is the variant, roaming across cases, its reads abortable precisely because the live tag is not statically known. Construction should hand you that, not a pinned single-case view you never asked for. So we drew the line at the parentheses: Expr.intLit bare, in a type position, is the projected case type; Expr.intLit(…), with an argument list, builds a value, and it yields the whole Expr. The .intLit picks which case is live; it does not pick the variable’s type. Both e Expr = Expr.intLit("5") and the bare e Expr.intLit("5") therefore land e at Expr, and the shorthand is genuinely the same instantiation form a plain String("hi") uses, not a second channel. We weighed a third spelling that some of us liked at first — a direct e Expr.intLit = "5", assigning the payload straight into the case — and it loses on every count: = is field-write syntax, so it reads as setting a member the variant does not keep standing by; it would need bespoke declaration-coercion machinery that the paren form gets from the ordinary argument rules for free; and, fatally, it is a statement, so it can be neither returned nor passed, which a value form must be. Only the paren form is an expression.
The last question to pin was where construction stops, and it fell straight out of a line already drawn. A payload that is itself built — a struct, or another variant — is made on its own and passed in: Expr.op(BinOp.fromParts(a, b)), the inner value first, the case wrapping its result. What we refused is reaching through the case: no Expr.op.fromParts(…) dotting into the payload’s own construction, no Outer.a.b(…) threading one case into the next in a single chain. That refusal is not a new rule — it is variants, not patterns read in a mirror. On the consuming side we match one tag and go no deeper, and to reach an inner case you match again; on the constructing side we name one case and go no deeper, and to fill an inner case you name another. Dotting through would be nesting in the value form — the exact dual of the nested pattern we refused, over a whole chapter, to grow in the matcher — and those two instincts have to point the same way or the design is lying to itself. The cost is the honest cost and it is the same tax, paid on the other axis: a deeply nested value is a deeply nested stack of explicit forms, with no inline literal to flatten it, which is more to write than a language that lets you spell the whole shape in one go. We think it is worth paying on construction for the same reason we judged it worth paying on consumption — one level, named, and you nest by hand when you need depth.
Recursion through hosting, not &
The sum mould had been settled for a long while before anyone tried to build a tree out of one, and the tree could not be written. Every rule involved had been agreed separately and looked reasonable alone — a value type is closed, a recursive member needs indirection, indirection is &, an & comes only from a guest source — and together they made the most ordinary use of a variant impossible to write without inventing storage that models nothing. This chapter is the unpicking of that, and it ends up removing a rule we had not thought was involved: that a recursive structure must be rooted in a field.
Here is the smallest interesting variant there is — a two-case expression tree, and the program that builds 3 + 2 out of it:
type Operation = #struct { left Expr; right Expr; op Operator; }
type Expr = #variant { op Operation; intLit String; }
program Expr = Expr.op(Operation(Expr.intLit("3"), Expr.intLit("2"), Operator.add))
It was rejected, and not for the reason you would expect. The recursive members had to be &Expr, an & has to be minted from a guest source, and Expr.intLit("3") is a temporary — not a place expression at all (memory.md §2.8). So every child had to be parked in storage first, given a name it had no use for, purely so that a reference could point at it. At its worst that meant inventing a type for the parking:
type Leaves = #struct { a Expr; b Expr; }
leaves Leaves(Expr.intLit("3"), Expr.intLit("2"))
program Expr = Expr.op(Operation(leaves.a, leaves.b, Operator.add))
Leaves models nothing. It is scaffolding the rule demanded, and leaves.a is a name for a value that should have been a sub-expression. When a language makes you introduce storage in order to use its own sum type, the rule is wrong — not awkward, wrong — because putting values in a variant is most of a variant’s purpose.
That lit the fuse — not a size calculation, but the amount of code we had to write in order to use a variant at all. Once we were looking at it that way, the deeper mistake was visible behind it, and it is not about recursion at all: inlining is the wrong default, because a member’s size is not always knowable where it is embedded. A statically sized reference-type instance was stored inline in its host slot, on the reasoning that # buys identity and should not force an allocation. That holds only while every type’s size can be settled by looking at its parts. A sum’s still can be — a variant is its tag plus its widest case, one fixed size like everything else — but it is settled by all the cases at once rather than by the member in front of you. Follow that chain around a cycle and there is no size to settle on at all. Inline-by-default treats “the size of a T” as a fact available at the point of embedding, and for exactly the types this chapter is about, it is not. Recursion is where that assumption stopped being survivable, but it was never sound; it was merely unfalsified.
That reframes the role of the &. It was not expressing aliasing at all — it was being used as indirection, conscripted to break a containment the layout rule could not handle. Those are two jobs sharing one spelling, and only one of them is what a guest is for. An AST child is not aliased by its parent; it is owned by it, created for it, dying with it. Everything above is what it looks like when an owning relationship is forced through a non-owning handle: the ownership has to be parked elsewhere, and Leaves is where it got parked. The rooted-in-a-field rule was the same admission promoted to a principle — we had told ourselves a root belongs in a field of the object that owns the structure. It does not. That is just where a root is forced when the spine is made of guests.
The fix was already in the building. A List is a fixed-size handle stored inline whose payload lives in the scope’s dynamic region — finite where it is embedded, arbitrary where it actually lives, and hosting throughout, since a list owns its elements. That is precisely the shape a recursive member needs. So a recursive member stays an ordinary hosting member and the compiler boxes it (adt.md §4), and the program at the top of this chapter compiles exactly as written, with no name given to anything that did not need one.
Nothing is added to the surface, and that is deliberate rather than convenient. The programmer writes left Expr; boxing happens because inline placement does not exist for that member, in the same way and for the same reason that list elements are placed out of line. We considered the alternative honestly — Rust’s road, a Box<T> written in the source — and it fails against a load-bearing rule: # marks a distinct type, not a box, and placement has never been a language-visible property. A type whose whole meaning is “this one lives elsewhere” would sit in signatures forever, re-opening an axis we spent a chapter closing. We are also retiring a sentence we had stated as a principle: the old section closed with “indirection is always explicit &; there is no hidden auto-boxing,” and this design does hidden auto-boxing. What that sentence was protecting is worth keeping and is untouched — aliasing is never implicit, and a guest never appears where nobody wrote &. It was over-protecting placement, which the memory model had already declared unobservable.
One question the fuse did not raise but a spec has to answer: which members get boxed. Take the cycle above: Expr.op reaches Operation, and both Operation.left and Operation.right reach back. Several different cuts make every type finite — dropping Expr.op alone does it, and so does dropping Operation.left and Operation.right together — so “box the recursive member” does not name one answer. Minimal cutting is a trap, because the minimum feedback set is not unique: a type’s layout would depend on an ordering nobody wrote down, and adding a member could silently move where the indirection sits. We took the coarse rule instead — a member is boxed wherever its edge lies on a cycle — which is order-independent, decidable from the declarations with no search, and readable off the page. We wrote it as an “exactly when” at first, and review was right to push: a biconditional also forbids boxing off a cycle, which would stop an implementation from placing a fat variant case out of line even when that is plainly the right call. Required on a cycle, permitted elsewhere, per type; nothing observes the difference, because no operator exposes a type’s footprint. The cost is that a two-type cycle boxes on both hops, so descending one level of an Expr tree costs two indirections where a hand-tuned scheme would charge one. Predictable layout is worth more than the hop.
The other cost is that moving a tree moves the tree: rehosting relocates every boxed descendant into the destination scope’s dynamic region, so a move is O(tree) where the & version relocated nothing. That is not a side effect but a restatement of what changed — the children are owned now, and owned storage travels with its owner, which is the price a List has always paid for its backing store. Where a boxed payload lives, and how large a block it requests, belongs to the region chapter.
The return is mostly deletion. Leaves goes, and with it the reflex of inventing a type to satisfy a rule. The rooted-in-a-field rule goes entirely — a tree may be rooted in a local, a field, or a container slot, because there is no guest in the spine to root. And & stops being overloaded: it marks aliasing and only aliasing, which is the relation a parent back-pointer, a symbol table naming nodes, or a genuine graph edge needs — the shapes where hosting could not have expressed the relationship anyway. A cycle of hosts is a contradiction; a cycle of guests is a graph. Giving each spelling one meaning is worth the indirection it costs.
A value sum may recurse
Boxing settled how a recursive type is laid out, but it left one restriction standing on one side of the # axis: a value sum still could not contain itself. That looked as settled as the rest — until a reviewer asked why, and the answer did not hold up once we said it out loud.
One pair of declarations existed in this document purely to demonstrate that restriction:
type Countdown = variant { done Unit; more Countdown; } // was: ILLEGAL
type Chain = #variant { done Unit; more Chain; } // legal
Both are legal now. One body, product or sum put it the other way — a plain variant was “copied on assignment, transitively a value, and therefore non-recursive”, and the # was “what determines which may recurse” — and that therefore is the word that stopped being true. Transitively-value does not imply non-recursive; it never did, and we could not say why we had believed it. The reasoning that separated the two declarations, and the two arguments we withdrew to get here, belong to the memory story. On this side, the question is the shape of the sum mould once the restriction is gone.
It looks like the mould we said it was. The struct/variant symmetry has always been that one body grammar serves product and sum, and the # axis crosses it without touching the shape — four combinations, one grammar. Recursion was the exception to that, and it was a loud one, because a sum that cannot contain itself cannot be the structure sums are most often reached for. A list, a tree, an expression grammar, a JSON document: the textbook uses of a sum type are all self-referential, and every one of them was forced onto the reference side regardless of whether identity was wanted. Countdown above wants nothing from #. It has no identity worth naming, nothing points at it, and it is small. It was a #variant because the layout rule required one.
Now the choice between those two declarations is an ordinary choice, made on ordinary grounds. Do you want this value copied, or moved? Countdown is copied — assigning it duplicates the whole chain, and the copy shares no node with the original. Chain is moved, has identity, and its children are hosted. Neither is the “real” answer for trees; they are two different data structures, and a language that offers a sum mould should let you write both.
The cost is where recursion always puts it, and for a value sum it lands more often. Boxing costs an indirection per level either way. A reference tree pays O(tree) when it is rehosted, which is an operation you perform deliberately and rarely. A value tree pays O(tree) on every copy — an assignment, or a field, container, or return store whose source is an existing value rather than a freshly built one. Those are the operations that look free. That is worth saying plainly rather than discovering: a recursive value type is a fine Countdown and a poor thousand-node AST, and the reference form is what the AST wants, for the reason it always did.
What did not change is that a value sum still cannot carry a String. That is not a leftover of the old restriction; it is the rule that survived it — a reference type is made to be moved, not copied, and a value that held one would have to mint a second identity or share a host. So the # on Expr was never really about its recursion, which is the observation that started this. It carries intLit String. It was always going to be a reference type.
A variant payload is not a guest source
The struct/variant symmetry had one more edge than the declaration grammar made obvious. A struct field and a variant case payload are both named members, both selected with a dot, and both may even be boxed by the same placement rule. That made it tempting to let both originate a guest. Their storage lifetimes are not symmetric. A struct field’s slot exists for as long as the struct that contains it; a variant payload exists only while its tag is live.
So adt.md §3 does not make a case projection a guest source. Code that starts from a reference variant and needs durable access takes a guest to the whole variant and performs the abortable case read through that guest when it needs the payload. The stable identity stays at the sum; the tag-dependent storage stays tag-dependent. If the payload value is itself an &T, reading it is still a copy of that already-existing guest rather than a new guest minted from the case slot.
That restriction alone was not the whole lifetime answer. An object may already have a guest while it is a stable symbol and then be moved into a hosting case. When the tag later changes, the old payload place disappears but the earlier alias still exists. The memory rule therefore gives a disappearing contingent payload a same-owner float: unless the object is explicitly moved elsewhere, it becomes anonymously hosted by the variant’s owner scope and its old guests continue to reach it. The case slot does not survive, but the object’s lexical owner does.
The cost is split cleanly. At the surface, a caller cannot capture a hosting case payload once as a durable & and forget that the payload was conditional; it keeps the containing variant and acknowledges the case again at use. Underneath, a reference payload displaced without being relayed can remain alive until the owner scope drains. Keeping those two costs separate preserves the product/sum symmetry where it is real — names, body grammar, placement — without pretending the members have the same lifetime.
A match parenthesizes its scrutinees, and a block arm ends on its brace
The bare scrutinee list did not survive the parser. Multi-scrutinee matching had kept the list bare because a parenthesized (state, event) looked like a tuple, and the compiler then found that a bare list has no single reading. An expression may end in a brace of its own: a field-constructor call, a map literal, a call’s trailing argument. So the { after the last scrutinee has two possible owners, and a binary operator gives each of them a complete parse. x Foo = match A { } <= B { } reads both as (match A { }) <= (B { }) and as match (A { } <= B) { }. Every binary operator the language has produced the same two parses, and { has no precedence level that could rank them. The compiler treats two accepting parses as a defect in the grammar, never as a choice to settle afterward, so the scrutinee list had to end before the brace was read.
Parentheses end it, and they cost the least of the marks that could. The worry that kept the list bare does not hold up against the rest of the language: Zane has no (a, b) expression, so (state, event) has no tuple to turn into. The ( ) delimits a list the way it delimits an argument list, and the arms still select tags position by position, with cross-product exhaustiveness (adt.md §5.6). If the language ever gains tuples, a tuple scrutinee will need parentheses of its own inside these.
The arm terminator moved in the same change, for a reason of its own. The spec had given every arm a ;, like every other entry of a { } body. The compiler had applied the brace rule to arms instead: an => expr arm ends with a ;, and an arm whose body is a block is ended by its closing brace, as a statement that ends in } is (lexical.md §6.1). Both rules are uniform. They differ over which uniformity an arm belongs to, and we chose the statement’s. An arm with a block body reads as a selector followed by a body, and a body that closes on a brace takes no ; anywhere else in the language, at package scope or inside a verb (the chapter on declarations).
The costs are two. Every match now writes two more marks. And an => expr arm keeps its ; even when its expression ends in a brace, where a statement whose expression ends in one takes none, so a reader learns that an arm’s terminator follows the form of its body, not the last token of its expression.