Stories: Lifetimes

See also: spec/lifetimes.md — the rules these chapters explain.

Inheriting a debt: safety without a borrow checker

This story begins where the memory story ends. That story turned down two mechanisms at once — a tracing collector and a lifetime vocabulary — and built the anchor so that a ref stays valid even when its value moves. But the anchor only answers where is the value now; it leaves open how long may a ref live. A ref that resolves correctly through its anchor is still a catastrophe if it outlives the owner it tracks: the owner drains, its storage is reclaimed, and the anchor now points at a corpse. Some rule has to guarantee the owner outlives every ref derived from it. In Rust that rule is the borrow checker, and we explicitly refused it in the memory story. So the debt the memory story took on — “refusing the borrow checker means refusing the thing that makes the move problem go away by fiat” — comes due here, and not only for moves: the whole question of ref safety and ownership transfer has to be settled without a single line of lifetime inference.

The tempting road was to keep just a little inference — track where each ref flows, compute the region it must stay valid for, and check that against its owner. That is a borrow checker wearing a smaller hat, and it loses on the same ground we had already chosen in the memory story: it makes the compiler carry a proof the source does not state, and it forbids whole patterns with errors a beginner cannot read. We wanted the rule a programmer could run in their head while reading a single function — the language-wide preference for a readable rule over a more powerful one, the foundations bet applied to lifetimes. So the resolution is almost aggressively simple: every lifetime question is decided by comparing lexical declaration scopes, and nothing else. An & may be assigned only when the target’s owner is declared in the same or a higher scope than the ref (lifetimes.md §1.1); a value may move into a new owner only when that owner sits in the same or a higher scope than the source (§1.4). A higher scope strictly outlives a nested one — that is the meaning of lexical nesting — so “the owner is declared no deeper than the ref” is exactly “the owner outlives the ref,” read straight off the source with no solver in between.

The cost is the honest cost for any syntactic approximation of a semantic property: it is conservative. There are programs that are perfectly safe — a ref whose owner happens to outlive it through some control-flow path the scopes don’t reflect — that the scope rule rejects anyway, because it judges by where values are written, not by their actual runtime behaviour. We accepted that deliberately. The whole bet of the language is that a rule you can see beats a rule that sees more; a borrow checker accepts more programs and pays for it in a proof obligation and an error vocabulary, and that is precisely the trade the memory story already declined on the program’s behalf.

What may be moved: keeping ownership subtrees whole

With scope settled, the next pressure is the move itself: of all the expressions you could write on the right of a transfer, which may the language consume? The unprincipled answer — anything that names a value — breaks the owner-uniqueness invariant the memory model rests on the moment you allow it to reach into an existing owner. So the rule narrows move-sources to two forms that share one property: each names a value owned by no one else yet (lifetimes.md §1.2). A direct owning symbol is owned only by its binding; a verb that returns an owned T hands back a fresh temporary owned by nobody at all. Moving either re-parents nothing, because there was no parent to disturb.

Everything else is a projection into an existing owner, and that is the road not taken. The obvious wish is to move a field out — Truck(car.engine) — or an element out of a container — Garage(cars[1]). Both are rejected, and the reason is that they would tear a hole in a live ownership subtree. If car still exists and you have spirited its engine away, car now owns a gap the type system swears is full; if a container yields up element 1, every index past it shifts or the slot goes hollow, and the container’s own move-and-drop machinery — the very machinery the memory story’s subscript rule was built to protect — has no way to account for the theft. We could have tried to track the holes, marking fields and slots as moved-from and forbidding their later use, but that is exactly the per-element flow bookkeeping the memory model exists to avoid. So the language forbids the move at the source instead: a field or element is not a move-source, full stop. The containing object may be moved as a whole when it is itself a move-source, which keeps the natural-grained operation available and only forbids the fine-grained theft.

The cost lands on anyone who genuinely wanted one piece out of a structure: they cannot have it by moving. They must either move the whole container or design the piece to be independently owned from the start. That is a real expressiveness loss, and it is the price of the guarantee that any value reachable through an owner is still there — that ownership subtrees are stable, not gappy.

The declaration-block rule, and the flow analysis it rules out

The scope rules state where a value may move to; this chapter is about when — and it is where the design pays the most to stay simple. A naive language lets you move a symbol from anywhere it is visible, including inside an if, inside a loop, inside a nested block. The instant you allow that, you have signed up for flow-sensitive move tracking: the compiler must reason that after if cond { consume(x) }, the symbol x is maybe-moved — moved on one path, live on the other — and must forbid every later use that cannot prove which path ran. That “maybe-moved” lattice is a substantial chunk of a borrow checker’s substance, and the errors it produces (“use of partially moved value”) are among the hardest a newcomer meets.

Zane refuses the whole apparatus with one blunt rule: a direct owning symbol may be used as a move-source only in the exact lexical block where it was declared (lifetimes.md §1.3). A symbol cannot be moved from inside a nested block, so it can never be moved on some paths but not others — the block that could move it is straight-line code, and a move there either always happens or never does. The maybe-moved state simply cannot arise, so the analysis that would track it is not needed. Parameters get the same treatment by fiat: they are treated as declared at the top of the function body block, which is exactly the place a callee is entitled to consume them.

The road not taken is Rust’s, and it is worth being clear-eyed about what it buys: flow-sensitive tracking lets you write the conditional move directly, and the compiler proves it sound. We gave that up. The cost is that a conditional move must be restructured — you compute the destination or the guard first, then perform a single unconditional move in the declaration block, rather than scattering moves across branches. For a value moved inside a loop the restriction bites hardest, and the answer is the same: hoist the decision out, move once. This is more rigid than Rust, unapologetically. The compensation is that there is no flow-sensitive move error to decipher, because there is no flow-sensitive move analysis at all — the rigidity is the simplification.

Downgrade, not poison: why there is no use-after-move-read

The previous chapter removes conditional moves; this one removes the error class that, in other languages, a move leaves behind even in straight-line code. After you move a symbol, what is the symbol? The defensive answer most ownership languages give is poison: the binding becomes unusable, and touching it — even just to read — is a compile error. That answer exists because in those languages a moved-from slot is genuinely dangerous; its contents have been logically relocated and reading them would be reading a ghost.

Zane already paid for a better answer, in the memory story. The anchor was built so a ref keeps pointing at a value through a move; a moved-from symbol is just one more reference that needs to follow the value to its new home. So instead of poisoning the symbol, the language downgrades it: after the move the symbol becomes an & value resolving through the anchor, still readable, pointing at wherever the value now lives (lifetimes.md §1.6). What it loses is only the ability to move again — it is now an &, and an & is not a move-source — which is precisely the double-move the poison rule was protecting against, achieved without forbidding the read. The consequence is stated flatly in the spec and it is a genuinely unusual property: Zane has no user-visible use-after-move error class for reads. The same holds across calls; a callee that consumes a caller’s value leaves the caller a readable downgraded &, so callee-decides move semantics (§1.5) never strands the caller with a poisoned name.

This resolution is striking for how little it costs. The downgrade rides entirely on the anchor machinery the memory model had already built and paid for, so it adds no new runtime mechanism; it removes an error class rather than trading one burden for another. It requires only that a reader remember that a move quietly demotes the symbol — engine is an owner before the move and an & after, so the same name denotes slightly different storage on either side of the move point — and that is a small fact to carry next to the use-after-move errors it retires. This is one of the places where the honest account is that the decision was close to free, because an earlier chapter’s machinery had already covered its cost.

Returning a ref without a lifetime to name it

The last hole is the one lifetime annotations were invented for. A function returns &T; the scope rules of the first chapter govern assignments within a scope, but a return value crosses out of the function entirely, into a caller scope the function cannot see. What stops &Int bad() from returning a ref to its own local value, which dies the instant the function returns? In Rust the answer is a lifetime parameter 'a that ties the result’s validity to an input’s — exactly the 'a vocabulary we refused, in the memory story, to make the source speak.

The replacement is, once more, a rule you can check by looking: a function may return an &T only when that reference is rooted in one of the function’s parameters, with this counting as a parameter (lifetimes.md §1.7). The reasoning is that a parameter’s owner necessarily lives in the caller’s scope — the caller had to hold a real place to pass it — so a ref rooted in a parameter is automatically rooted in an owner that outlives the call. A ref rooted in a local is rooted in an owner that dies with the call, so it is rejected. No annotation is needed because the rule does not express which caller scope the result is valid in; it only requires the result to trace back to one the caller already owns, and that is enough to be safe.

This is coarser than 'a, and that is the cost. Lifetime parameters can express relationships this rule cannot — a result valid for the shorter of two inputs, a struct that borrows for a named region — and Zane simply cannot express those relationships. The expressiveness lands, as the memory story warned, on the library author: a function that needs to hand back a reference must arrange for it to flow from a parameter, and a design that needed to mint and return a fresh interior reference has to be rethought. In return the caller gets the same bargain the whole document makes — a returned &, once the function compiles, is known to rest on ground the caller already holds, and no one had to learn a borrow vocabulary to get there.

Consumed or borrowed: the parameter that lives at the call site

The downgrade chapter closed on a claim it had not fully earned: that a callee which consumes a caller’s value leaves the caller a readable &, never a poisoned name. It never pinned down when a passed reference is actually consumed, and the spec, read closely, gave two answers that could not both be true. One section described passing by the callee’s behavior: store the value and it moves, leave it alone and ownership stays with the caller. Another described a plain reference parameter as swallowed — frame-local to the callee, gone when the call returned. The first says the value survives in the caller’s hands; the second says it dies in the callee’s frame. A reader trying to answer the plainest possible question — engine Engine(); car Car(engine), where the constructor takes engine and does nothing with it, now what? — found the document contradicting itself.

The contradiction was not cosmetic, because the downgrade rule had already spent the caller’s safety on one of the two answers. If a swallowed value is frame-local and dies with the call, then the caller’s downgraded & — the reference the previous chapter guaranteed stays readable — points at a corpse the instant the callee drops it. The very mechanism that made “no use-after-move-read” true depended on the passed value outliving the call, and one of our two accounts quietly denied it. We had shipped a latent dangling ref and hidden it inside a wording disagreement.

The tempting repair was to keep the “swallowed, frame-local” reading and simply forbid the drop: make a callee that takes a reference have to re-home it, and error otherwise. That works, but we chased it and it kept forcing the value out of the caller. Re-home into the return, and the caller must now write x = f(x) to catch its own value coming back — a manual reassignment at every call, the ceremony we least wanted. Downgrade the caller no matter what, and we were back to spending the caller’s ownership on every call that only needed to look at the value. Each variant treated the callee’s frame as the value’s home and then negotiated the value’s escape. The negotiations were the smell.

The move that dissolved all of it was to deny the premise: a parameter is not part of the callee’s body scope at all. It belongs to the call-site scope, one level up, and the callee is merely handed owning access to it for the duration of the call. Once the parameter lives above the body, the body draining says nothing about the value’s fate — a local that received it falling out of scope does not drop it, because the value was never the local’s to drop; the compiler moves it back up to where it came from. The plain question answers itself: the constructor that does nothing with engine hands it back, and engine in the caller was never in danger, because it never left the caller’s scope.

With the parameter rehoused, “consume” stopped being a behavior we had to observe and became a boundary we could name. A verb consumes a parameter exactly when the value escapes into storage the caller still tracks: into another parameter’s owning storage, or into the return value. Those are the only two exits from a call that land the value in storage the caller can name afterward — an argument it still holds, or a result it catches. Everything else the callee does with the value — reading it, threading it through locals, lending it to nested calls — leaves it inside the call-site scope, so the caller keeps it whole. This is the general shape, and it reaches past parameters: a scope may take an owner from a higher scope, provided the value goes back to that scope, and the two ways back are the two exits a call actually has.

We had briefly wanted to keep returns out of the exits, precisely to kill the x = f(x) reassignment. We let them back in, because forbidding them made constructors impossible to state — a constructor’s whole job is to consume its arguments into the object it returns — and because the reassignment worry has a cleaner answer than a prohibition: a non-Void return simply cannot be ignored. If the value can ride out on the return, then dropping the return on the floor would drop the value, so we require every returned value to be bound or consumed. The constructor case then needs no special pleading: car Car(engine) consumes engine into the returned object, the caller binds car because it must, and engine downgrades to an & that now resolves into the car — every rule already in place, nothing added for constructors.

The last question was how a caller knows which happened, since island!startMatch(player) and boat!loadCar(car) look identical and yet one hands player back while the other swallows car into the boat. We refused to answer it with a new annotation. Zane already infers effect levels rather than making the source spell them, and consumption is the same kind of fact, so we made it inferred too: the compiler computes, per parameter, whether a verb consumes or borrows it, starting from the verbs that store or return directly and propagating outward to their callers. What keeps this from becoming the flow-sensitive tracking we spent an earlier chapter refusing is the declaration-block rule: a parameter can only be moved in straight-line code, so it goes into a local or out through an exit as two separate static cases, never consumed on one branch and borrowed on another. The classification is a single bit per parameter, and it determines the caller’s state — borrowed leaves a full owner, consumed downgrades to an & or is caught as the return — which is the refinement the downgrade chapter was missing: it is not that every call downgrades the caller, but that only a consuming one does.

The costs are real and we name them. The inference is interprocedural, so a verb’s parameter modes are no longer a local fact — they depend on the verbs it calls, and a change deep in a call chain can flip a caller’s parameter from borrowed to consumed. We accept the whole-program coupling because the alternative was an annotation on every reference parameter, and the language’s standing bet is to infer what it can rather than make the source carry it. A sharper-edged cost is that a program’s well-formedness now depends on the build: a plain T parameter a verb only reads should be an &T, and we make that an error only in release builds, letting development builds run with the looser form so a half-written function still compiles. Two builds can therefore disagree on whether the same source is legal — a genuine wart, chosen deliberately because the strict form reaches users and the loose form helps while the code is still moving. And there is one intent we refused to let you express at all: you cannot take a reference and destroy it early, before the caller’s scope ends, because a passed value always outlives the call. Destruction stays tethered to the owning scope draining, exactly as the lifetime rules demand; a function that wants a value gone cannot grant that wish, and that is the price of a parameter that always belongs to someone above.

The signature is the whole contract: retiring inferred consumption

The previous chapter closed on a design we were briefly proud of: consumption as an inferred fact, computed per parameter the way effect levels are, so the source never had to spell out whether a passed value came back. Reading it again with colder eyes, we found that we had actually built a rule you could not run in your head — the one property the first chapter swore every lifetime rule in this document would keep. Standing at a call site, looking at something(car), a reader had no way to answer the plainest question there is: is car still mine after this line? The answer lived elsewhere entirely — inside something’s body, and inside the bodies of everything something called, since the classification was interprocedural. The signature, the one declaration right there on the page, gave no answer. Whether car survived as an owner or quietly became a tether was a fact you had to go read another function to learn, and it could flip out from under you when that other function changed. We had traded an annotation we didn’t want to write for a magic we couldn’t see, and on this codebase that is a bad trade every time.

The tempting patch was to keep the inference and merely surface it — show the computed consumed-or-borrowed bit in tooling, let a reader hover a call and be told. But that concedes the whole game. If you need a tool to tell you the effect of a line of your own code on your own value, the language has already failed the read-it-in-your-head test, and dressing the failure in a hover tip does not undo it. The other patch was to keep inference for the common case and add an annotation for when you wanted certainty, which is the worst of the three: a rule that is sometimes inferred and sometimes written, so a reader must first work out which mode is in force before working out anything else. Every repair kept the callee’s body in charge of the caller’s fate and then aimed to make the body’s verdict easier to fetch. The verdict itself was the problem.

So we cut it. Passing an owning value to a plain T parameter downgrades the caller’s symbol to a tether, full stop, and the callee’s body gets no vote. T in the signature means the caller gives this up; &T means the caller lends it and stays the owner. That is the entire contract, and it is legible from the call site because it is legible from the signature — the only declaration a caller was ever reading. A verb that just glances at its argument and a verb that squirrels it into a field now look identical to the caller, and that is exactly right: both asked for T, both took an owner, and reading the value instead of storing it does not un-ask the question the signature posed. As the decision was put to us: “nothing in the body changes what the signature already said.” If a verb only needs to look, its author must declare that in the one place the caller reads — by taking &T.

The mechanism this rests on was already built and already paid for. A passed value still belongs to the call-site scope, so it outlives the call whatever the body does with it; and the downgrade-not-poison rule already turned a moved-from symbol into a readable tether through the anchor rather than a poisoned name. Passing to a T parameter is now simply a move like any other — the argument is a move-source, the symbol downgrades, the anchor keeps it resolving to wherever the value comes to rest. The elaborate part of the old design had been the exception: the borrowed case, where we chose not to downgrade because the body happened not to store the value. Deleting the exception removed no machinery; it removed a special case, and left passing-an-owner as an ordinary instance of the move rule this document already had. The old wart went with it — the passing mode no longer depends on the build, because there is no read-only-T-should-be-&T judgment left to relax in development and enforce in release. A read-only T is simply legal, and simply downgrades the caller, like every other T. Doing nothing with a parameter is still a release-build error, but that is the general unused-parameter rule, owner or not, and never had anything to do with consumption.

Getting an owner back, when you genuinely need it, is an explicit act rather than an inferred gift: the verb returns the owner and the caller binds it. That gives clean names to the two ways a verb can swallow an owner you hand it, told apart by its return — it relays it (T, and returns an owner you can rebind) or consumes it (T, returns nothing, keeps the value) — beside the &T tether, which swallows nothing and leaves you the owner outright. car2 Car = repair(car) says in plain sight that repair relayed the car and handed it back; there is no inferred alternative hiding behind it in which the same line would have left car an untouched owner. The reassignment is not noise obscuring a simpler truth — it is the truth, written where you can see it.

We first drew that last line too hard. To stop a dropped return from stranding the caller’s tether, we made binding mandatory — a non-Void return could not be ignored. But the danger dissolves the moment you notice the value need not die when it goes unbound: it can float to the enclosing scope, an anonymous owner living exactly as long as any scope-owned value, the caller’s tether resolving into it. Nothing dangles, nothing is silently destroyed. And floating turned out more uniform than the mandate it replaced: passing an owner already leaves you a tether to a value that floats at the call-site scope, and ignoring a returned owner now has the identical effect — one rule, not a rule plus an exception. So binding stopped being an obligation and became a choice: take owning privilege, or don’t. The choice even reads at the call site, since a caught return is exactly the mark that the caller wanted ownership back.

The cost is real and we name it. Handing an owner to a verb that only reads it is still perfectly legal — it just downgrades you to a tether, like any T pass. The convenience of keeping owner privilege afterward for free is gone; to keep it now you pass &T, deciding at the parameter’s declaration that reading was all you meant. The loss is a genuine one in terseness, paid at every call that needs to lend-and-keep: what the inference used to hand back for free now costs either an &T at the parameter’s declaration or a bound return at the call site. We took it deliberately, because the terseness it bought was precisely the terseness that hid the answer to is this still mine, and the standing bet of this whole document is that a rule you can see beats a rule that saves a keystroke. We also gave up the small elegance of parameter modes being inferable rather than declared: & on a read-only parameter is load-bearing now where it used to be optional, and a signature that gets it wrong is wrong at the call site rather than merely suboptimal. That, too, is a fair price for a contract that states its meaning in the one place everyone reads.

No rule to spare: the specific hole each restriction plugs

The chapters to here have each defended a choice: lexical scope over a borrow checker, downgrade over poison, the signature over inferred consumption. Set end to end they argue well for the shape of the system and hardly at all for its individual rules, and on re-reading, that gap troubled us. A reader could finish convinced that Zane simply favours blunt lexical rules as a matter of taste, and draw the reasonable-sounding conclusion that any one of them could be loosened a little, for convenience, at no real cost. That conclusion is wrong, and wrong in a specific respect: each restriction is the minimal guard against one particular separation of a host from the value it hosts, and every one we imagined relaxing let back in exactly one concrete corruption. We had described the rules; we had never lined them up beside the disasters they exist to prevent. This chapter does that, once, because the honest case for the strictness is not the elegance of the system but the ugliness of what each rule is holding back. (The terms shift here from the earlier chapters’ owner and tether to host and guest; the memory story records why the names changed. The rules are the same rules.)

Start with the guest-assignment rule (lifetimes.md §1.1). It forbids binding an & to a host that lives in a lower scope than the guest, and only that direction — binding to a host in the same or a strictly higher scope is always fine, because a scope that encloses the guest outlives it by construction. The rule looks like fussy bookkeeping until you write the program it rejects:

outer Node()
r &Node = outer
{
    inner Node()
    r = inner
}
r:inspect()          // inner drained at the closing brace; r resolves to reclaimed storage

Nothing here is exotic — a guest reassigned inside a block, the sort of line anyone writes without thinking. And the runtime does its half perfectly: the anchor keeps r resolving to wherever inner’s value went, which after the brace is storage the scope has already reclaimed. The rule is the only barrier between “the anchor tracks the value faithfully” and “the anchor tracks the value straight into its grave.”

What keeps the rule from being mere caution is that it waves the mirror image straight through. Bind a guest to a host that encloses it and there is nothing to check — the host cannot drain before the guest does:

outer Node()
{
    r &Node = outer   // legal: outer encloses the block, so it outlives r
    r:inspect()
}

Here r is the short-lived reference; it is gone at the brace while outer lives on, never for a moment tracking a value younger than itself. The restriction bites on exactly one direction because only one direction is dangerous — loosen it to allow the nested host and you have not bought a small convenience but reopened use-after-free in ordinary syntax.

The returned-reference rule (§1.7) is the same hole seen from across a call boundary, which is why it needs its own guard rather than folding into §1.1: a return leaves the function’s scopes entirely, into a caller the function cannot see. Let a function return an & to anything at all and this compiles:

&Node bad() {
    value Node()
    return value   // value dies as the frame unwinds; the caller is handed an & into reclaimed storage
}

value is gone the instant bad returns; the caller receives a live-looking guest onto a dead slot. Rooting the returned & in a parameter is exactly the condition that rules this out — a parameter’s host necessarily lives in the caller’s scope, so a reference that traces back to one is guaranteed to rest on ground the caller still holds. And “rooted in a parameter” is read transitively: the returned & may pass through an intermediate & binding, so long as that binding itself roots in a parameter. The coarseness is the whole point — the rule never names which caller scope the result is valid for, only that it traces to one the caller already owns, which is all safety requires and needs no annotation to state.

The destination-scope rule (§1.4) closes the mirror image of §1.1. There the danger was a guest reaching down to a short-lived host; here it is a value moved down into one:

node Node()
{
    sink Node()
    sink = node       // node's value is now hosted by sink
}
node:inspect()        // sink drained at the brace, taking the value with it

The move re-parents node’s value into sink, whose scope closes at the brace and destroys everything it hosts. But node did not vanish when it was moved — it downgraded to a guest (§1.6) that stays readable, and after the brace that guest resolves, through the anchor, to a value the inner scope already destroyed.

The rule waves the opposite move through, and the symmetry with §1.1 is exact — swap which host is nested and the same assignment is safe:

sink Node()
{
    inner Node()
    sink = inner      // legal: sink encloses the block, so it outlives inner's value
}
sink:inspect()        // sink now hosts the value; nothing was stranded

A value born in the inner block and moved up into sink lands in a host that outlives the scope it came from, so no guest is left tracking a short-lived value. The rule bites only on the lifetime-sinking direction, the only direction that can strand a guest. It is close kin to the declaration-block rule, and for the same reason: both are about a move crossing a scope boundary it has no business crossing.

That declaration-block rule (§1.3) guards a subtler failure — not where a value goes, but whether it went at all. Allow a symbol to be moved from inside a nested or conditional block and you get this:

car Car()
if damaged {
    scrapyard!crush(car)   // consumes car — but only on one path
}
car:inspect()              // on the crushed path, a read of a value already consumed

Now car’s state at the last line depends on a runtime condition: hosted on one path, downgraded on the other. A compiler that wanted to allow the conditional move would have to track that split — the maybe-moved state that flow-sensitive move analysis exists to compute, and whose errors (“use of partially moved value”) are among the least legible any ownership language produces. The loop case is sharper still: a move inside a loop body consumes on the first iteration, and the second iteration moves an already-downgraded guest — a double consume with no single line to blame. Confining moves to the declaration block makes the move straight-line code, where it either always runs or never does, so the maybe-moved state cannot arise and the analysis that would chase it is never needed. The rigidity is the simplification: you restructure the conditional move — decide first, move once — and in exchange the whole category of partial-move errors does not exist.

The last of the five is the rule whose loosening looks most innocent and costs the most to allow: the move-source restriction (§1.2), which forbids moving a field or a container element out. Truck(car.engine) reads like the most natural statement in the world — take the engine, give it to the truck — and that is precisely the theft the rule forbids:

engine Engine()
car Car(engine)
truck Truck(car.engine)   // imagine it allowed: engine spirited out of car
// car and truck now both host the one engine — and both destroy it when their scopes drain

Move the engine out and car is left hosting a gap the type system still swears is full; the single engine has two hosts, and deterministic destruction — the guarantee the whole document is built to deliver — dutifully destroys it twice. A container element is worse, because pulling element 1 out either leaves a hole every later index must dodge or forces a shift the container’s own move-and-drop machinery cannot account for. We could have tracked the holes — mark a field or slot as moved-from and forbid its later use — but that is the per-element flow bookkeeping the entire design exists to avoid. So the rule forbids the fine-grained theft at the source and leaves the natural-grained operation intact: a whole car may be moved when it is itself a move-source; only reaching into a live host to steal a piece is denied.

Laid side by side, the five stop looking like a taste for blunt rules and start looking like their true form: five different doors onto the same room, each the minimal lock against one specific separation of a host from its value — a guest outliving its host (§1.1, §1.7), a value sinking below a guest that still tracks it (§1.4), a value consumed on some paths but not others (§1.3), a value stolen from a host that still counts it (§1.2). None substitutes for another; each closes a gap the others leave open. That is the answer to the reader who finds them rigid and wonders where the slack is: there is none to give, because loosening any one is not a gentler version of the same safety but a specific, nameable crash let back in. This is restriction as information at the level of a single document — every rule that forbids a program is carrying a fact the compiler would otherwise have to prove — and that the readable rule and the fast language coincide is the standing bet, not a coincidence.

The cost of buying safety this way is real, and it is not the false rejections — those the first chapter already owned. It is that the safety arrives as a list rather than a principle. A borrow checker derives every one of these cases from a single notion, a lifetime outliving a borrow; learn that idea and you hold all of it at once. Zane asks its reader to carry five separate rules instead, and only a chapter like this one shows them the five are a set with no member removable. We think that is the right trade — five rules you can each check by eye against the code in front of you beat one proof you must trust a solver to have carried — but it is a genuine trade, and a chapter that presents the rules as self-evidently a system, rather than a hard-won set each earning its place, is the chapter we had before this one.

Where a guest may be rooted

The five rules of the previous chapter were each a lock against one separation of a host from its value. Narrowing the guest source, over in the memory story, turned out to change what two of those locks are guarding, and the adjustment is small enough to state precisely and worth stating because the reasoning is easy to get backwards.

The scope check (§1.1) did not change at all — it still checks only whether the target’s host is declared in the same or a higher lexical scope than the guest — but it now sits behind a prior question, because a source that is not a guest source never reaches the scope check in the first place. The visible effect is that the canonical illegal example is no longer the interesting example. r = innerNode, rejected for scope, used to be the rule’s whole face; now the more common rejection is r &Node = node, refused before any scope is compared, and the example that still exercises the scope rule has to reach through a field to get there. That is a small loss of pedagogical clarity in exchange for a large one of exposure: the rule that used to be the only barrier between a program and a dangling guest is now the second line of defence.

The rule that did change is the rule governing returns (§1.7). It used to state that a returned &T must be rooted in a parameter, which was the right rule when there was only one kind of reference parameter to be rooted in. With three, “a parameter” is no longer specific enough, and each of the other two fails for its own reason. A swallowing T parameter is a bare symbol in the call-site scope, and a bare symbol is not a guest source — so the returned guest could not have been minted in the first place. A 'T borrow fails harder: the borrow ends when the call does, and a guest rooted in one would outlive the very access it was derived from. So the rule now names the guest parameter specifically. This rule is right rather than merely tighter because the three modes each answer the rule’s real question — may this outlive the call? — and only one of them answers yes.

The same reasoning had to be pushed one step further than the rule’s own text, and this is the part that is easy to miss. Refusing to return a 'T parameter is pointless if you may instead return a guest minted from one of its fields: this.weapon on a borrowed subject would escape just as surely as this would, wrapped in one layer of indirection. So a field access rooted in a borrow is not a guest source either. We debated allowing it — the caller’s object does outlive the call, so the guest would in fact be live — and rejected it on the grounds that “in fact live” is not the standard. The compiler would have to reason about the relative scopes of two objects across a call boundary to know it, which is the interprocedural analysis this whole document exists to avoid. A borrow that does not escape, with no exceptions and nothing to check, is worth more than a borrow that escapes safely under an argument only the compiler can follow.

Nothing else moved. The downgrade rule (§1.6) still turns a moved-from symbol into a readable guest, and it is worth being clear that this is not in tension with the new source rule: the downgrade is an operation the language applies to a slot, not a guest a program mints, and the reader never writes it. The signature-is-the-whole-contract rule (§1.8) simply grew a fourth entry — a verb may now borrow an argument as well as take a guest, relay, or consume — and the entry it grew is, satisfyingly, the entry that leaves the caller in the strongest position: still the host, with the callee unable to keep anything.

The honest cost here is not a rejected program but a redistribution of where the reader’s attention has to go. Before, a reference parameter’s mode was visible in one bit — & or not — and the question “what happens to my object” had two answers. Now there are three signatures to read and three answers, and the difference between two of them (&T and 'T) is invisible at the call site by design, because the whole point is that the call site should not need the difference. The programmer who wants to know whether their host survives a call still reads exactly one declaration, the signature; there is just more in it than there used to be.

Simplifying the return-root rule

The previous chapter tightened the return rule and was pleased with itself for it. It had stated, of the older and looser version, that “a parameter” was the right rule “when there was only one kind of reference parameter to be rooted in” — and with three kinds, it named the guest parameter specifically and gave each rejected mode its own reason. Both of those reasons have since been withdrawn, and the rule they were propping up went back to the sentence it started as.

The withdrawal is told in the memory story: a bare symbol is a guest source again and the borrow mode is gone. Follow the consequences through §1.7 and both exclusions evaporate. A swallowing T parameter was excluded because it is a bare symbol and a bare symbol was not a source — but it is one now. A 'T borrow was excluded because it expires with the call — but there is no 'T.

Interestingly, the rule which survives is not the old rule restored by accident. It has a reason the old rule never articulated, and the reason is stronger than either exclusion it replaces: a parameter belongs to the call-site scope (§1.5). Both modes have that property, which is why both are roots. A guest rooted in a parameter names an object hosted in the very scope the returned value is landing in, so the scope comparison has both declarations in front of it at the call site and rejects the cases that would dangle — including the case that looks alarming, where the argument was declared in a block nested below the binding that takes the return. Nothing about that check reaches across the call boundary, which is the property this document is organised around.

A local is still not a root, and the difference is that it is now excluded for the true reason rather than a proxy for it. return value on a body-scope local fails because that scope drains at the return, full stop — not because of anything about where a guest may be minted. When we were routing the rejection through guest sources we were using a source restriction to enforce a lifetime property, and it happened to catch this case; it is better stated as the lifetime property it always was.

The one line of the previous chapter that needs correcting rather than superseding is its account of §1.1. It reported that the scope check had become “the second line of defence”, with the guest-source question in front of it catching the common case. That is no longer the shape: nearly every place is a guest source, so §1.1 is the front line again and does essentially all of the work. Its canonical illegal example goes back to being the example about scope, which is the rule’s actual subject.

An & store compares root symbols

With the returned-guest root settled, one case was still open — and it is not one the previous chapters had occasion to look at, because it is not a question about where a guest may be rooted or minted. It is a question about a guest’s fate afterwards.

The comparison §1.1 makes is exact for an & symbol, whose scope is fixed the moment it is declared and cannot change afterwards. An & field is a different shape: its scope is its container’s, and a container moves. So the comparison made when the field is written can be falsified later by a statement that never touches the field at all:

parked Car(outerHolder.engine)
{
    innerHolder Holder(Engine(Int(2)))
    arriving Car(innerHolder.engine)   // §1.1 satisfied: both in this block
    parked = arriving                  // a move, not an `&` assignment
}                                      // innerHolder dies; parked.engine names its storage

Every line passes. §1.1 fired at the construction and was right at the time. The move is checked by §1.4, which compares the value’s scopes and says nothing about what the value contains. Between them the two rules cover both directions a value can travel and neither looks at the guest riding inside it.

There is an asymmetry underneath that we had not noticed we were relying on. §1.4 exists to stop hosting from sinking into a nested scope. For a guest held inside the moved object the danger runs the other way — raising the container above what its guests name — and we had only ever constrained one of the two.

Our first instinct was to pin the value: an object holding an & may not be rehosted into a higher scope, full stop. That is decidable from the type alone, using the same transitive walk the value-downstream rule already performs, and it needs no new machinery. It is also wrong in the case that matters most. A parent pointer — parent &Node on a node stored in root.children — is the commonest reason anyone wants an & field at all, and pinning would forbid appending the child to the very tree its guest points at. A rule whose first casualty is the canonical use of the feature is not a conservative rule, it is a broken one.

That failure showed us the missing property. A parent pointer is safe not because of its scope but because of its structure: the guest names an object in the same hosting tree as the object holding it, so the two move together and cannot come apart. §1.2 already guarantees that, by refusing to let a subtree be prised out of its tree. So tree membership survives every operation that relocates a value, where scope survives none of them. It covers nothing about a host that simply dies, which is the limit we come back to at the end of this chapter.

For a while we worked to make that the whole rule — an & may only name an object inside its own tree — and it fails from the other side. A short-lived wrapper over an object handed in, a type anyone writes without thinking, has no shared tree with the object it points at:

Unit report(io std$IO) {
    terminal Terminal(io)   // io belongs to the call site and outlives the body
    terminal!print("hi")
    return Unit()
}

Perfectly safe, and a blanket tree rule forbids it. The resolution was to stop treating the two as rivals. Tree membership is not an alternative to the scope comparison; it is the permission to move. A guest that names an object inside the value it rides in satisfies any destination, because it travels. A guest that does not is fine wherever it currently sits, and must be re-examined if the value is raised. Both readings live in the carried-guest rule, and neither had to displace the other.

The second realisation changed the shape of the fix, and it came from asking when the check should run. We had been trying to make the wiring-time check strong enough to survive everything that could happen later, which is why every version of it was either unsound or absurdly strict. It does not have to survive anything, because a raise is a statement the compiler can see. Check at the rise and the question of whether an earlier check has gone stale never arises: there is no earlier check to go stale.

That would have been the end of it, except for a program with no rise in it anywhere:

Unit setEngine(this Car, engine &Engine) mut { this.engine = engine; return Unit() }

Unit main(car &Car) {
    engine Engine()         // a local of main
    car!setEngine(engine)   // car names something above main
    return Unit()
}                           // engine dies; car.engine is left naming its storage

Nothing moves. The argument reaches a parameter in the call-site scope, and inside the body this and engine are both call-site scope, so every scope comparison in sight compares equals. And this is the shape memory.md §2.9 had been holding up as the canonical use of an & parameter. What the callee cannot see is whether the caller’s engine is hosted above or below the object this names — and it never can, because that is a fact about two of the caller’s symbols, one frame away.

We tried hardest to fix this by narrowing where a guest may be minted. If only a guest could be a guest source — an &T parameter, this, a guest local rooted in one — then every guest would name an object at the call-site scope or above, the highest any frame can rehost anything, and the whole class of problem would be structurally impossible. It is an elegant rule and we followed it far before noticing it has no base case. A parameter is fed by the caller’s guest source, a guest local by another guest source; the recursion bottoms out only at a package constant, or at this — whose subject expression nothing checks, and cannot check, because terminal!print("hi") on a local you own has to work. The subject position is not a leak in that rule. It is the only place the language mints a guest at all, and a rule that closes it is a rule that deletes guests.

So the restriction had to land on the store rather than the source. Our first answer took that literally and syntactically: both paths of an & store must begin with the same root symbol. It is a comparison of two identifiers, it needs no scopes and no induction, and it holds however many frames a guest has travelled through, because it looks at the two paths in front of it rather than at their history. Everything reachable under one name is one tree, so a guest written through a name travels with what it points at and goes when the tree goes.

We shipped that, alongside an enumeration of the four ways a value can be raised, and lived with it long enough to notice we did not like it. The next chapter replaces it, because the rule was correct but not memorable.

The owner lifetime replaces the same-root rule

The same-root rule was correct as far as we ever managed to push it, and the raise enumeration next to it caught every program we could write. It was not, however, memorable. Four raise forms, a walk over owning edges, a carve-out for init{ } because a half-built object has no root to share, and a separate scope comparison for & symbols that the field rule did not use. Each piece was justified on its own and none of them followed from any of the others. A language whose reference rules take a page to enumerate has not found its rule yet; it has found a list of the places its rule was supposed to be.

The tell was the carve-out. init{ } was exempt from the root comparison because the object it fills does not exist yet — which is to say, the rule could not be stated for the one place where every & field in the language is first written. Everything the exemption let through then had to be caught downstream, and that is what the four raise forms were for. The enumeration was not a companion to the root rule. It was the patch over the hole the root rule could not cover.

Without naming it, we had actually been recognising exactly one kind of lifetime. A hosting tree is a lifetime: everything under one root dies when the root does. That is what “same root symbol” tests, in a syntactic disguise. But a block is a lifetime on precisely the same terms — everything it owns dies when it drains, there is no user code between one death and the next, and nothing in the language can observe an order among them. We had been comparing blocks in §1.1 since the beginning and comparing trees in the field rule, and we had never noticed that the two comparisons were the same comparison over two instances of one idea.

Give it a term — an owner — and state where each place gets one. A symbol is owned by its declaring block. A field or element is owned by its root symbol’s owner, never its own. A parameter and an init{ } have no owner in the body at all; each stands for a path in the caller’s frame. Then the whole of it is one sentence: a store is legal when every host the stored value names, directly or through a guest it carries, has an owner that outlives the destination’s owner.

The four raise forms evaporate, and not by being absorbed into a longer sentence. They were four syntactic occasions on which a value changes lifetime, and a value changes lifetime by being stored — an assignment, a move, a return, an argument. There was never anything to enumerate. We had enumerated because we were looking for the places a check could go stale, which is a question you only have to ask if you believe some checks run once and stay believed.

Two restrictions we had assumed were consequences of the root rule turned out to be consequences of nothing, and both were losses.

The first is that a field is not confined to its own tree. Under owners it inherits its root symbol’s owner, so an object and the target of its & field may be siblings in one block, and terminal Terminal(io) on two locals is exactly as legal as it always looked. The root rule forbade that shape and then re-permitted it through the init{ } carve-out, which is a strange move for a rule to make and should have been read as a symptom.

The second is setEngine. The previous chapter recorded its death and the installEngine that replaced it, and argued that taking hosting instead was the more honest signature. That argument was rationalisation. A verb that stores a guest it was handed is an ordinary need — a setter, a registry, anything wired after construction — and the reason we could not check it was never that it is unsafe. It is that the callee is looking at two parameters and cannot see where either argument is hosted, which is a fact about the caller’s frame that no rule inside the body will ever reach.

So stop trying to decide it in the body. What the body can state is where the value comes to rest: engine lands at this.engine. That goes into the signature, and each call substitutes the paths it actually wrote and compares owners like any other store. car!setEngine(engine) on two locals of one block passes; the same call with an argument from a nested block does not. The one-hop-two-hop laundering that killed the this-rooted softening we considered is closed by the summary being transitive: a verb that passes its guest parameter on to setEngine records the resting place it inherits, the way effects.md §5.2 already propagates effects it does not itself perform.

That summary is the price, and it is a real one. A verb’s &-storing behaviour becomes public API — derived from the body, published with the signature, binding on every caller. It also inherits the shape of the carried-guest walk, and for the same reason: a resting place is a path of owning steps that stops at an &, because the guest’s target is hosted at a place the caller’s argument path does not reach. Rooting a path at an &T parameter is fine — the caller names that one. Stepping through an & further along is not, and pushing on where the boundary sits turned up a rule we had stated too loosely one section earlier. “A field is owned by its root symbol’s owner” is only true of a path made of owning steps; go through an & and the place you land on belongs to a tree the root does not name, and has no owner at all. It may be read. It may not be written. That is not a rule about signatures, it is the owner definition finally stating which paths it covers. The root rule bought its way out of exactly this by making the storing verb inexpressible, so there was nothing to summarise; we are now paying the bill it declined. We are careful not to have reopened §1.8: the summary records where a parameter lands, never whether passing one downgrades the caller. That second question is still answered by the declared mode alone, and inferring it from the body is the mistake an earlier chapter of this story is named after.

The orphan in memory.md §2.9 survives all of this, and now for a reason it can state. Binding a swallowed parameter into & storage is still illegal, and it is the single case no argument path rescues: the caller gave up its host in the act of passing, so at the call site there is no path left on the source side for the comparison to name. Every other refusal in this area is a comparison that failed. That one is a comparison that cannot be set up.

None of this touches the other way a guest can be left naming nothing. Everything above is about a value moving away from what it points at. A host can also simply die while the guest is still there — an element removed from a container, a #variant slot changing case — and neither of those is a store, so no rule here reaches them. memory.md §2.8.1 enumerates two fates for a hosted object, moved and overwritten, and states that they “never compete, because an object cannot both leave and die in the same step.” That is true, and the pair is not exhaustive: an overwrite leaves a successor occupant for the guest to carry forward to, and a removal leaves nothing. We are leaving that open deliberately rather than answering it here, because it is a different question with a different shape, and answering two at once is how the first version of this chapter got written three times.

The rejected design that needed no signatures

The chapter above ends by paying a bill: the owner rule publishes, with each verb’s signature, a summary of where it stores its & parameters. It is worth writing down the design that never incurs it, because we did not reject that design for being wrong, and because this corner of the language is significant enough that a future revisit should start from what we already know rather than rediscover it.

Push the owner idea one step harder and init{ } stops being a constructor at all. It becomes an empty template of the object under construction — a template you fill in field by field, whose root is init itself:

Main() {
    init.io = IO()
    init.terminal.io = init.io   // legal: both rooted at `init`
    return init
}

Now the root comparison holds everywhere with no exception, including inside a constructor, because init is a root like any other. Which makes Terminal(io &IO) => init{io} illegal — init and io do not share one. An & may only ever be created pointing inside the tree that will hold it, structurally, at the moment it is written. No deferral, no call-site substitution, no summary published in a signature. And no init{ } carve-out either, because the case the carve-out existed to excuse cannot happen.

That is a stricter language than the language we have and a strictly cheaper one to check. Every complaint this story makes about the raise enumeration it answers better than the owner rule does: nothing crosses a call boundary, so there is nothing to enumerate and nothing to publish. If the whole design had to be defended on the count of “how much does a compiler have to know about a function it cannot see”, this version wins outright, because the answer is nothing.

What it costs is wiring, in two places, and both are severe enough that we did not take it.

A package can no longer ship a constructor that takes a guest. A type Logger = #struct { out &Writer } cannot come with a Logger(out &Writer), because that constructor is precisely the illegal form. Whoever embeds a Logger has to reach into its out field from their own init to wire it — so every borrowing type leaks its internals to its user, and the encapsulation a library exists to provide is gone for the entire class of types that hold a reference. That is not a restriction on what a guest may point at. It is a restriction on who is allowed to write the pointing, and it lands on exactly the boundary a package is supposed to be.

And a standalone &-holding local stops being expressible. terminal Terminal(io) on two siblings of one block — the most ordinary use of a guest there is, and the program this entire line of work started from — has no shared root to satisfy the rule and no aggregate to be embedded in. Under this design a type with an & field is usable only inside a larger tree whose constructor wires it. An object holding a reference is no longer an object in its own right; it is a fragment of a tree, and stating that out loud honestly describes the design’s commitment.

We are recording this rather than merely declining it because the trade is not settled forever. The owner rule buys library wiring and standalone locals with a per-signature summary that is load-bearing for soundness: omit a resting place and a dangling guest gets through.

The effect summaries it is modelled on are not the reassuring analogy they look like, and the difference is worth being precise about. Effects have a safe direction that is also a usable one — effects.md §5.4 classifies a callee the compiler cannot see at the strongest level, which costs precision and nothing else, and the program still compiles. Over-recording a resting place is safe in the same direction, but the conservative default for a callee whose body is unavailable would have to be every parameter may come to rest anywhere reachable, which rejects very nearly every call. There is no degraded mode to fall back to. The summary has to be present and correct, not merely bounded — a heavier obligation than the effects analogy suggests on first reading, and the reason this is a debt rather than a convenience.

The empty template buys a checker with no interprocedural component at all, and pays in expressiveness that is visible in every program rather than in an obligation that is invisible until it breaks. If the summary turns out to be the wrong debt — too costly to compute, too brittle across separate compilation, too surprising once a library author discovers that where they store a parameter is public API — this is the road back. A successor design would have to buy off the two costs above, and it should buy them off knowingly rather than meet them again by accident.

Place lifetimes inside a live owner

The owner chapter deliberately left one dangling-guest shape open: the owner could remain alive while a particular place inside it disappeared. An element removal and a variant case change were the examples. We had found the right lifetime for a hosting tree and still assumed, incorrectly, that every place inside that tree persisted for the whole owner lifetime.

The first correction belongs to guest creation. memory.md §2.8 distinguishes a readable place from a place stable enough to originate a new guest. A path crossing a subscript cannot mint one, and neither can a variant-case projection. Code that starts from contingent storage keeps a guest to the stable container or reference variant and repeats the changing projection at use.

That looked complete until review reversed the order of events. Mint the guest first, while the host is still a stable symbol, and then move that host into a container element or variant payload. The guest follows the object, and the moved-from symbol itself becomes another guest. Now the contingent place may disappear even though no guest was ever minted through it. The owner comparison did everything it guaranteed — every alias is owned no higher than the destination — and the object could still have been destroyed too early. The missing distinction was not another owner. It was the case of a place that ends before its owner does.

lifetimes.md §2.1 now makes that explicit. A disappearing contingent reference host does not end the object’s owner lifetime. Unless the object is moved elsewhere, it floats into an anonymous host belonging to the same owner scope and dies when that scope drains. This is not a new longer lifetime and it is not guest-driven retention: the float happens regardless of whether any guest exists. It is the hosting rule acknowledging the rule §1.1 had stated all along — an element or member reached by owning steps has the root’s owner, and losing the particular place need not cost that owner.

That choice keeps the lexical model closed. We do not need per-guest invalidation, reference counts, or a flow-sensitive rule pinning objects after aliasing. The cost is that an unrelayed reference object displaced from contingent storage may remain alive to the end of its owner scope even if it is unreachable. That is the price of keeping destruction a function of lexical hosting rather than of guest liveness, and it is bounded at exactly the owner the existing comparison already uses.

A moved host is spent, not a guest

Downgrade, not poison rested on a premise it never stated: that turning a host into a guest changes nothing a reader has to notice. That chapter described the cost as remembering that a move “quietly demotes the symbol”, and called it a small fact to carry. The doubt about that sat with us for a long time before we acted on it. Downgrading would only have been simpler if hosts and guests had identical use-site semantics, and they do not. They share surface syntax: a method call, a field access, and a mut call are written the same way on either (memory.md §2.7). But the same = overwrites a host’s slot and repoints a guest (§2.5). A host is a move-source and a guest is not, so passing one to a swallowing parameter is legal and passing the other is an error. And a mutation through a downgraded name reaches into an object that now lives in somebody else’s container. A downgraded symbol is a name whose operations change partway down a block while its declaration still reads engine Engine.

That is three costs, not one. The programmer has to track, deep in a function, that a symbol declared T has become an &T, and nothing at the use site shows it. The compiler has to carry two kinds of symbol under one declared type, and give the moved-from slot a tether, which requires allocating an anchor on a move for an object nobody ever guested, just so the old name keeps resolving. And the rule looks unpredictable, because what a line does to engine depends on a move several lines up.

This was not the first time the alternative came up. When bare symbols became guest sources again, a proposal to make a moved-from symbol spent came with it, and the memory story declined it: at the moment of the move the symbol and any guest to it name the same object, so the readings coincide. That was true, and it answered a different worry, about which object a guest names. It left open whether the moved-from name still behaves like its declaration, and that question finally settled this.

The name came with the proposal and we kept it. A spent casing has done its job and is empty, and it can be reloaded, which is the whole life of the symbol: it handed its object on, holds nothing, and keeps the slot for another. We weighed vacant, which conveys the same emptiness, but in the host-and-guest register a vacancy is room for a guest, which points the reader at exactly the wrong relationship.

So a moved symbol is now spent (lifetimes.md §1.6). It denotes no object, and any use of it is a compile-time error until a store refills it. Passing a host to a plain T parameter spends it the same way, because that pass is a move (§1.8). We did not go as far as Rust’s poison, where a moved-from binding is dead for good. The relay pattern depends on a name taking a host back — player = island!returnPlayer(id) — and a spent symbol keeps its full slot, so refilling it costs nothing.

Refilling raised the one question we did not see coming. A store into an outer symbol from a nested block passes every lifetime rule, because the value moves up into a host that outlives it. But after if(ready()) { engine = Engine(); } the symbol would be hosting on one path and spent on the other, which is the maybe-moved state the declaration-block rule exists to prevent, arriving from the other side. The lifetime rules could not catch it, because they govern where a value may go and nothing about the state a symbol is left in. What catches it is the principle already behind §1.3, stated once for both directions: a symbol changes between hosting and spent only in its declaration block. That needed no new mechanism. It also closed a gap the downgrade rule had carried unnoticed, where a conditional re-host left a symbol “host or guest” and whether it could be moved again depended on the path.

The cost is that an error class comes back. “Zane has no use-after-move error for reads” was an unusual claim to be able to make, and we can no longer say it. The error that returns is the easy kind of error, though. Moves are never conditional, so the compiler can always name the one line that spent the symbol. The idiom of handing an object over and continuing to look at it now takes one more line: mint a guest before the move and read through that. We think the extra line is the point, since it is the one place the programmer states that they are keeping a view of an object they gave away. A relayed return that goes unbound still floats, and the caller reaches it only through a guest it minted beforehand. And the destination-scope rule stays exactly as necessary as before: the example that motivated it no longer compiles as written, but a guest minted before the move opens the same hole, and §1.4 is what closes it.

Running the examples

Every rule in this document had been argued on paper, and every example beside it had been checked by reading. That changed when the compiler gained a test suite for the memory model, and the suite was built the obvious way: take each example the spec gives, write it as a program, and run it. Three of the spec’s own examples failed to match the prose around them, and one store the comparison had never been asked about turned out to need it. None of the four was a new idea. Each was a place where two rules we already had disagreed, or where a rule stopped one case short.

The missing store was abort. lifetimes.md §1.1 listed the places its comparison is made — an assignment, a move, a return, an argument — and a value aborted with is none of those. So a verb could abort with a guest to its own local, the caller’s handler could bind it, and the handler would read a host the drain had already ended. The test that found it read back garbage. We had said in the error-handling story that failure leaves a call by its own door, typed just as the primary door is. A door out of the call is a store into the caller, and we had built the comparison for one door and forgotten the other. The decision took no deliberation: an abort is a store, identically to how a return is a store. It is held to the same roots, and the handler’s binder stands where the call’s result would have stood, naming what the call’s arguments name. Nothing about it is new machinery; the comparison simply runs in one more place, which is why it costs nothing a reader has to learn.

The second failure was enterMatch, the relay §1.8 had used to show a spent symbol taking a host back: player = island!returnPlayer(playerId). The compiler refused it, and the compiler was right, because player is a parameter and effects.md §2.4 makes every parameter but this read-only. The spent-symbol chapter had leaned on the same line, and it was written before anyone held it against the effect model. There were two ways to make the spec consistent. The case for letting a spent parameter be refilled is real. A parameter is a symbol in the call-site scope, §1.3 already lets it be moved at the top of the body, and refilling is the whole point of a spent symbol keeping its slot, so the relay would have read with one name instead of two. We decided against it because of the slot’s location. A swallowed parameter’s storage is the caller’s, so a refill would be the callee writing into a caller’s slot that the caller’s own symbol has already given up and no longer names. Read-only parameters exist so that the kind of verb bounds what it can write, and this would have been the first exception to that bound, carved out to save one line. We kept parameters read-only. The relay moves player into a local first and refills the local, and the cost is exactly that one line.

The third was the constructor in §1.10, init{io; terminal = Terminal(io);}, offered as the ordinary way a value comes to carry a guest to its own field. Read entry by entry it moves io into the field and then mints a guest from io, which is spent by then, and §1.6 forbids that. The spec had never stated the order in which init{ } runs its entries, so the example was not wrong under every reading, only under the reading the compiler had picked. We could have made the entries simultaneous, one store of a whole object, so that every entry saw the parameters as they were on entry. That would have kept the example as written, at the price of a second evaluation model that holds inside init{ } and nowhere else, and of deciding afresh what an entry that calls a verb may observe of another. We chose written order, the order every other block runs in, and wrote the example the other way round: mint the guest from io, then move io in, and the guest follows it.

That repair ran straight into memory.md §2.9, which said a swallowed parameter may never be bound into & storage. Read literally, it forbade the reordered constructor as firmly as the original. Its reason did not apply, though. The rule exists because a swallowed value stays at the call site, so a guest to it that leaves inside an object names storage the caller has given up, and no argument path can locate it. When the body moves the value into the same object, the guest names a host inside that object and travels with it, which is the case §1.10 calls satisfied at every destination. So the rule narrowed to what it was always protecting: a swallowed parameter may be bound into & storage when the body also moves it under the same root. wrap(engine Engine) => Mount(engine), where the guest leaves and the engine does not, stays illegal. The cost is that a reader now has to notice the order of a constructor’s entries. Swap two entries that look independent and the constructor stops compiling, with an error about a spent symbol on a line that seems not to have moved anything.

Lifetime rules after settled and roaming hosts

The memory story split a reference-type host into a settled one that never moves and a roaming one that nothing guests, and turned a bare reference parameter into a borrow. Most of the rules this story built were about a guested object changing hosts, and they went with that combination.

The largest was the parameter that lives at the call site. A swallowed value belonged to the caller’s scope however the callee used it, so a local that received it had to hand it back when it drained, and the caller’s spent slot went on holding a value it no longer named. Every hole the memory test suite found in this area came out of that arrangement. A ^T parameter now really takes the host: it is the body’s own, it dies with the body unless the body moves it on, and the caller’s symbol is spent with nothing behind it, since a roaming host had no guests to keep the object alive for. The relay the spent-symbol chapter leaned on still reads the same — take ^Player, return ^Player, bind it — but nothing in it now depends on the call site keeping anything.

The destination-scope rule lost its job. It existed because a moved object took its guests along, so moving it to a scope that drained sooner would strand them. A roaming host has no guests to strand, and a settled one does not move, so its owner is fixed where it settles. What a roaming value carries in its & fields is still compared at every store, as the check that fired once required; that comparison never depended on the moved object being guested.

Two rules from running the examples went the same way. A swallowed parameter may no longer be bound into & storage under any condition, because there is no swallowed parameter; a ^T parameter is roaming and cannot be guested. And the float that kept a contingent occupant alive for its guests is gone with the guests: a list element or a variant payload is roaming, so when its place disappears it is destroyed unless it is moved out first. That abort is a store, and that init{ } runs in order, both stand.

Returned guests narrowed too. A returned or aborted &T must be rooted in an &T parameter. this is a borrow, a bare parameter is a borrow, and a ^T parameter dies with the body, so none of them is a root any more. The cost is the cost the memory story names for getWeapon: an accessor that hands out a guest into its subject is a function over &T, not a method.

A call through a function value is taken to store every reference

The resting-place summary closed the gap a reference could be laundered through by passing it one frame further than the check looked. Probing the compiler showed one frame it never looked into: a call through a function value. A lambda has a body, but a function value is called by its type, and a lambda-variable may be reassigned, so at the call there is no body to read a summary from. The compiler recorded nothing for such a call, and a mut lambda that stored its &Port parameter into its subject carried a reference to an inner block’s owner straight past the store rule. The probe then wrote through it into an unrelated object that had reused the slot.

There were two honest ways out. A function type could carry a summary of its own, so that Unit[this Plug, &Port] mut would also say where the &Port comes to rest, and every lambda passed for it would be checked against that promise. It is precise, and it is new syntax on every function type that takes a reference, written by every programmer who passes one, for a fact most such types would never use. The other way is to assume the worst at the call. We took that one (lifetimes.md §1.11): a call through a function value is checked as though every parameter came to rest in the result and, when the type is mut, in this. The read-only analysis already treated the same calls this way, so the two analyses now match on the permitted behaviour of an unseen body.

The cost is the lambda that only reads. A mut function value that counts the ports it is shown, without keeping any of them, is refused when it is shown one owned in a block nested inside its subject’s, because the call cannot distinguish it from the lambda that keeps them. The fix in such a program is to hand it a reference whose owner is scoped as high as the subject, which is usually where the owner already lives. If that cost turns out to bite in real programs, the summary on the type is still available, and nothing in the conservative rule stands in its way.

Package constants become return roots, and an &T parameter stops being a store root

The same probing turned up two sentences that contradicted the rules around them, in opposite directions.

The first was too strict. The settled-and-roaming chapter narrowed a returned reference to one rooted in an &T parameter, and §1.7 said “nothing else is a root” while listing only locals, ^T parameters and borrows as excluded. A package constant was not mentioned, and the compiler accepted &Engine constRef() => garage anyway, because the store rule §1.7 claims to follow allows it: a package constant lives for the whole program, so it outlives every scope a caller could bind the result into. Nothing about the call site needs checking. We made the sentence match the rule’s long-standing intent (lifetimes.md §1.7): a returned reference may be rooted in an &T parameter or in a package constant.

The second was a clause no program could exercise. §1.11 recorded a resting place when a verb stored a reference into a place reachable from this, from the result, or “from another &T parameter”, and the owner-lifetime chapter had been content that rooting a path at an &T parameter was fine because the caller names it. But the effect model makes every parameter other than this read-only, together with everything reached through it (effects.md §4.1), so other.leaf = leaf and other!setLeaf(leaf) are both refused before resting places come into it. A reader of the lifetimes document alone would have expected the store to be legal. We could have carved an exception into the effect model for a verb that wires one argument into another. We kept parameters read-only without exception instead, and took the clause out: a resting place is rooted at this or the result, and a verb that wires two objects together is a mut method on the object that keeps the reference. That costs nothing that was ever expressible.