Skip to content
← The design recordMemory and ownership

Memory model

Ownership with var, const and references, scoped release, Buffer<T>, and how it all lowers to Rust.

memory-model.md on GitHub →

elp memory model — how it elaborates to Rust

Companion to the front-end roadmap's Phase 1. The decision already made (see the roadmap): elp's typechecker tracks ownership/move/borrow shapes only to decide what Rust to emit — it does not reimplement lifetime inference or NLL. A bug in elp's tracking surfaces as a rustc compile error on generated code, not a shipped memory-safety hole. This document is the elaboration mapping that decision produces, validated by hand-porting a real file rather than reasoning about it in the abstract.

Companion to interfaces.md: whether a value can be captured by value at all (Finding 3, below) turned out to hinge on the general interface model — Copy/Move are ordinary, nominally-checked interfaces, not memory-model-specific magic. Read that doc for the interface story; this one stays focused on what elaborates to what.

The exercise

Source: examples/ChatRoom/components/login-form.velp, in full — chosen because it's the one real file in the corpus that actually exercises & (&email, &password) rather than just declaring &type in a signature nobody calls.

export fn LoginForm -> Component {
	export var email Optional<string>
	export *fn onSubmit(username string, password Protected<string>)

	var password Protected<string>
	var attempts = 0

	fn handleSubmit() {
		attempts += 1
		if onSubmit.isNil() {
			throw LoginError.NO_HANDLER
		}
		onSubmit(email, password)
	}

	return Form(onSubmit=handleSubmit) {
		EmailInput(&email, placeholder="Enter your email")
		SecureTextInput(&password, placeholder="Enter your password")
		Button(type=.FORM_SUBMIT) { Text("Log in") }
	}
}

Hand-elaborated:

pub struct LoginForm {
    // Exported prop. `var` inside a component is reactive (the source
    // comment says so directly: "declaring vars in a component... cause
    // reactivity") — see "Finding 2" below for why that means `Reactive<T>`,
    // not a plain field.
    pub email: Reactive<Option<String>>,
    // `*fn` prop — see "Finding 4": still nilable at runtime despite being
    // marked as a required callback, so `Option` either way. `Arc`, not
    // `Box` — see Finding 3: a closure isn't `Copy`/`Move` on its own, so
    // it can't be held directly; `Arc` is what makes holding one legal.
    pub on_submit: Option<Arc<dyn Fn(String, Protected<String>)>>,

    // Private reactive state — same treatment as `email`.
    password: Reactive<Protected<String>>,
    attempts: Reactive<i32>,
}

impl LoginForm {
    fn handle_submit(&self) -> Result<(), LoginError> {
        self.attempts.update(|a| a + 1);

        if self.on_submit.is_none() {
            return Err(LoginError::NoHandler);
        }

        (self.on_submit.as_ref().unwrap())(self.email.get(), self.password.get());
        Ok(())
    }

    fn render(&self) -> Component {
        Form::new(|| self.handle_submit())
            .child(EmailInput::new(&self.email).placeholder("Enter your email"))
            .child(SecureTextInput::new(&self.password).placeholder("Enter your password"))
            .child(Button::new(ButtonType::FormSubmit).child(Text::new("Log in")))
    }
}

(throw → Result/Err is now a real decision, not just an illustration — see error-handling.md: throw is sugar for return Err(...), no bubbling, no boundary. The builder-block calls → method-chained .child(...) calls are still just illustrating some plausible lowering so the ownership-relevant parts have real code around them; Form's actual runtime shape is a separate, later design question.)

What confirmed cleanly

  • fn handleSubmit() / fn render (implicit) → both become plain &self methods. No &mut self needed anywhere, which is not obvious up front — see Finding 2 for why.
  • export *fn onSubmit(...) → Option<Arc<dyn Fn(...)>> on the struct. .isNil() → .is_none(), direct. The Arc isn't a component-specific detail — see Finding 3: it's the general mechanism for holding any function value at all.
  • Calling handleSubmit as a value (Form(onSubmit=handleSubmit)) → a &self-capturing closure, once handleSubmit only needs &self (which it does, per Finding 2). This was the thing most likely to not work — a method needing &mut self cannot be closed over from a &self context — and it resolves itself once the state layer is right.

Finding 1 — plain (non-reactive) var/const mutability, resolved

Every var/& in the login-form exercise is either a reactive component field or a reference to one, so this was originally flagged as unexercised. It's resolved now, not by a new example, but by taking var/const at face value: var means mutable, const means it never changes, full stop — nothing about how it's referenced needs to add anything on top of that. var x → let mut x, const x → let x. No further annotation is needed at the binding site because the binding already says everything there is to say about mutability.

const buys stack allocation of the binding and rules out any reallocation-through-mutation of it, but it isn't a blanket "always stack, never heap" guarantee — a type that's heap-backed by its own construction (a growable collection, say) is still heap-backed when const-bound. What changes is that nothing can grow/reallocate/mutate it afterward, which is most of the stack-allocation argument, not literally all of it.

This finding used to end by flagging &x → &x/&mut x as an assumed-but-unconfirmed mapping, to be revisited with a synthetic example before Phase 2 relied on it. That's no longer needed — see Finding 4 below, which derives the &/&mut choice directly from var/const plus usage, closing the gap without a synthetic example being required.

Finding 2 — reactive var needs interior mutability, not a plain field

This is the load-bearing discovery. var fields inside a component body are documented as reactive ("observed for changes... cause reactivity"). The naive elaboration — a plain struct field, mutated via &mut self — breaks immediately: render needs to hand EmailInput something it can write through as the user types, and handleSubmit needs to increment attempts, but render also needs to hand out handleSubmit itself as a callback (Form(onSubmit=handleSubmit)). A &mut self-requiring method cannot be closed over from inside a &self method — there's no &mut self available to capture. Something has to give, and it can't be "make render take &mut self" — that doesn't fix handleSubmit also needing exclusive access at the same time render is calling it as a value.

The resolution: reactive fields are wrapped in an interior-mutability cell (Reactive<T> above — a stand-in name; the real wrapper is a runtime-design question, not this document's). Once mutation lives inside the cell (self.attempts.update(...)) rather than at the struct-field level, both render and handleSubmit only ever need &self, and the closure-capture problem disappears because there's no &mut self requirement left to conflict with anything.

Consequence for Phase 2 (typecheck): ownership-shape tracking needs two modes, not one:

  • Plain .elp script-level var/const → ordinary Rust let mut/let, real borrow-checking, exactly as the roadmap assumed.
  • Reactive var fields inside a .velp component body → interior mutability, &self-only methods, no real Rust borrow-checking of the reactive value itself (the cell absorbs it) — a different lowering rule keyed off "is this binding inside a component and therefore reactive," not a smaller version of the same rule.

This isn't a reversal of the "mirror Rust ownership" decision — plain script code still elaborates directly and rustc still backstops it. It's a scope correction: that decision covers script-level bindings, and reactive component state needs its own elaboration rule sitting next to it, not underneath it.

Finding 3 — functions are reference-only values, and Copy/Move are what govern capturing anything by value

Started from a narrower question — "how does LoginForm hold a reference to a closure owned by its parent" — and generalized further than expected.

The starting rule: you can't pass a function by value. A closure is never moved or copied directly; holding one always means holding a reference to somebody else's. Option<Box<dyn Fn(...)>> (the original draft above) is wrong under that rule — Box owns the closure, so constructing a LoginForm would have to move a closure into it, which is exactly the "pass by value" the rule rules out.

The fix isn't a bespoke "functions are special, always borrowed" rule, though — it falls out of a more general one, and this is the part worth stating precisely: elp has no capture-list syntax, and no per-variable move/reference/copy annotation at the closure site at all. Instead, whether a value can be captured into a closure (or passed by value, generally) is governed entirely by whether its type implements Copy or Move — two ordinary interfaces (see interfaces.md), checked nominally, no interface-level magic. A closure/dyn Fn type implements neither by default (its captured internals are opaque), so it can't be captured or passed directly — the same rule that applies to any other type that hasn't opted in to Copy/Move, not a special case for functions.

Arc<dyn Fn(...)> is the way out, and it's not a function-specific mechanism either: Arc<T> implements Copy (cloning it is a cheap refcount bump, not a deep copy of T), so wrapping a closure in Arc gives you something that is legally capturable/storable. Reactive<T> (Finding 2) is expected to work the same way — its own Copy implementation clones the underlying Arc/Rc handle rather than deep-copying the value, which is what lets a reactive field be captured into a closure without a lifetime parameter appearing anywhere. One mechanism (type-level Copy), not two.

Arc specifically, not Rc — elp's concurrency model is Go-style spawned coroutines (see grammar-script-notes.md gap #1), so reactive state and captured callbacks need to be sound across concurrent access; Rc/ RefCell aren't thread-safe and would be the wrong choice even though they're cheaper.

Consequence for Phase 2: ownership-shape tracking needs a "does this type implement Copy or Move" check wired in wherever a value is captured into a closure or passed by value — this isn't a separate closure-specific rule, it's the same interface-conformance check Phase 2 needs for Copy/Move generally, just applied at every capture/pass-by- value site rather than only at explicit-copy call sites.

Superseded by this finding: an earlier version of this discussion proposed a move-keyword capture-list syntax (C++-style, per-variable move/reference/copy annotations at the closure site) as the mechanism. That's dropped — it's not needed once capturability is a property of the type rather than the capture site, and it would have been redundant with the Copy/Move interface check besides.

Amendment to Finding 3 — superseded by aliasing.md

Finding 3 concludes that Arc<T> and Reactive<T> implement Copy and calls this "one mechanism (type-level Copy), not two."

That economy is false, and examples/Buffer was written to prove it. A split-pane editor needs both semantics in one program, and under Finding 3's rule both are spelled the same way:

Cursor implements Copy      // duplicates are INDEPENDENT
Buffer implements Copy      // duplicates ALIAS the same cell

The full design, the corpus evidence, and the three drafts rejected on the way to it are in aliasing.md, which is authoritative. Only the corrections to this document are recorded here.

What it changes in Finding 3

  • Reactive<T> is a lowering name, not an elp type. The user-facing aliasing types are Shared<T> (immutable, Copy), Confined<T> (mutable, one thread) and Synchronized<T> (mutable, cross-thread).
  • The last two are Move, not Copy, and a second handle comes from .alias(). So a type holding one is not Copy, transitively, by the ordinary field-wise rule and not by a special one.
  • Duplicate is a third conformance alongside Copy and Move, naming the .copy() the corpus has used since the beginning. It promises independence, which is why the aliasing handles are not in it: .copy() never aliases and .alias() always does.
  • Finding 3's claimed benefit survives in a better form: a capture or pass-by-value site still asks one question — "is this type duplicable" — and the type now carries whether duplicates alias instead of hiding it in a conformance.

What it confirms in Finding 6

Finding 6 put references in a free tier: "a reference (&T, for any T) is unconditionally cheap to copy… the same Arc<T>/Reactive<T> pattern — a cheap-to-copy handle whose own copyability is entirely independent of whether the thing it points to is copyable."

Shared<T> is exactly that rule given an owning form — &T with a refcount instead of a lifetime — so it is Copy for any T, including Shared<[string]>. Finding 6 generalised correctly; it just had no type to name.

Where Finding 6 was too broad is the Arc/Reactive half of that sentence: a mutable handle is cheap to duplicate and the duplicate is not independent, so it belongs in Duplicate rather than the free tier. The reference half is unaffected, because a &T cannot be written through without &var.

Finding 4 — &x doesn't need a mutable/immutable spelling, resolved

elp's grammar has one ref-type spelling: &type, &self, &ident. Rust has two: &T and &mut T. For the reactive fields in the login-form exercise, that was never a gap: EmailInput(&email, ...) elaborates to &self.email — a plain shared reference to the Reactive<T> cell — because writes go through the cell's own API, not through a Rust-level &mut. The open question was whether that generalizes to plain, non-reactive values, where there's no cell absorbing the mutation.

It generalizes, and the single spelling turns out not to be hiding any real ambiguity — var/const (Finding 1) already supplies the half of the answer that isn't pure usage:

  • If the referent is const, the reference can only ever elaborate to &T. There's no case where &mut T is legal, because nothing can mutate through it — the binding forbids that outright, so there's nothing to disambiguate.
  • If the referent is var, the reference elaborates to &T or &mut T chosen per call site, by whether the callee actually mutates through that specific reference — the same way Rust's own borrow checker already decides &/&mut from usage rather than from a keyword written at the reference site. elp never needed a &mut spelling because that choice was always fully determined by what the code does, not something a developer needed to declare.

The enforcement side of this is what makes it more than a convenient default: passing a const binding into a function whose body mutates through that parameter is a compile error at the call site, not silently allowed or silently promoted. The diagnostic should name the fix directly, in the same spirit as the Copy/Move errors in interfaces.md — something like "x is const and cannot be passed where mutation is required — declare it var if it needs to change."

Amended by reactivity.md. Two things above are too strong once the component tree is retained rather than a single expression:

  • EmailInput(&email, ...) elaborating to &self.email, "a plain shared reference to the Reactive<T> cell", holds only while the parent strictly outlives the child. A child component is a retained object, not a scoped callee, so a reactive prop is shared ownership — a refcounted handle — rather than a Rust borrow. A borrow does not extend the referent's lifetime; the constraint runs the other way.
  • The single spelling with inferred mutability stays for ordinary function calls, where the call is scoped and the callee's signature is one hover away. In prop position the capability is written explicitly, because the handle outlives the call and data flow is what a reader scans markup for. There, & is a capability grant rather than a borrow.

Consequence for Phase 2: deciding & vs &mut for a plain-value reference requires looking at how the reference is used inside the callee — mirroring how closure capture mode already has to be inferred from usage rather than annotated. const-ness of the referent is then a hard constraint checked against that inferred usage, not a separate, independent rule.

Amended again, by FFI: there is one place with no callee to read. The whole finding rests on inferring mutability from what the callee does through the reference. At an @external declaration the callee is C, so there is no body, and the one mechanism that let elp avoid a &mut spelling has nothing to work with at exactly the boundary where mutation matters most.

So at an @external declaration, &T means the callee may read and write. Inference's absence resolves to the conservative side rather than to a marker. It costs the information that sqlite3_errmsg(db &Sqlite3) does not write, which buys nothing for safety and matters only for optimisation — and it needs no new syntax, which is the point.

That is also the whole answer to C out-parameters, and the reason elp needs no Out<T> or out spelling for the scalar case. sqlite3_open writes a sqlite3* through a sqlite3**, and the thing being passed is not a mutable reference to a value — there is no value yet — but a slot that may be empty, which Optional<T> already is:

var db Optional<Sqlite3> = null

match sqlite3_open(&c, &db) {
	0    -> ...
	code -> throw DbError.CANNOT_OPEN { path, message = "sqlite error {code}" }
}

Optional<Sqlite3> niche-optimises to a nullable pointer, so &db is sqlite3** at the ABI. Two designs were considered and dropped:

  • &mut, scoped to @external declarations only. It describes the wrong axis. The difficulty is emptiness, not direction: you cannot take a mutable reference to a Sqlite3 that does not exist yet.
  • An Out<T> slot type. It is &Optional<T> with extra vocabulary, and it resembles Binding<T> closely enough to invite the question — the roles are the same, a read-write reference to storage owned elsewhere. But reactivity.md defines Binding<T> as a retained, shared connection, so it is a refcounted cell with a notification list: writes trigger reactivity, aliasing.md ties it to the cell thread, and it is never Sendable. None of that belongs anywhere near sqlite3_open, and its layout is nothing like T*. So the resemblance is at the role and the machinery is actively unsuitable.

Irreducible, and not a gap: a status code and an out-slot are two returns the C ABI does not relate, so nothing in elp can relate them either. 0 from sqlite3_open is the only evidence the slot was written. Reading an Optional<T> and letting the status code say whether to trust it is an honest reflection of the ABI rather than a weakness in the model.

What this does not cover is arrays. vkEnumeratePhysicalDevices wants a contiguous allocation whose address the driver writes into, and Optional<T> is one slot. See "Collections hold values, not places" below.

Amended a third time, and this one reverses half of it: &var T is a parameter spelling after all. Ratified after "One hole, reported nine times", below, found that the absence of it is nine gaps wearing different hats.

The finding's argument was that mutability is determined by what the callee does, so nobody needs to declare it. That is true, and it is an argument about necessity, not about where the information belongs. Three places have no callee body to read, and the amendment above already conceded the first of them:

no body to infer fromstatus before
an @external declarationconceded above — &T resolved to read-write
an interface method requirementcollections.md wrote fn hash(&self, into &var Hasher) anyway
a function type — fn(&var Document)unnoticed, and it is the decisive one

The third is why this could not stay open. A function type has no body by construction, so update(fn (&var T) -> R) -> R — the transform closure the next section ratifies, and the fix for all nine gaps — cannot be written down at all without this spelling. examples/Undo/types/edit.elp has held const apply fn(&var Document) in a field since before the question was asked.

And a fourth reason, which applies even where a body exists: an exported function's contract must not depend on its implementation. Whether f mutates its argument decides whether a const binding may be passed to it, which is observable at every call site in every other module. Inferring it from the body makes the public contract a consequence of private code, which is the one thing export exists to prevent.

The rule

  1. At a declaration, &var T is required for any parameter the function mutates, and the body is checked against the signature rather than the signature inferred from the body. &T is read-only, and const on the referent remains the hard constraint Finding 4 made it.

  2. At a call site, &var x is required and must agree with the declaration. This is the half of Finding 4 that is reversed. The original reasoning — that a developer need not declare what is already determined — does not reach the call site, because there the marker is not a declaration but an assertion that matches one. What it buys is the one thing this language could not show: that a call mutates its argument. The corpus wrote it unprompted at 47 sites across five programs.

  3. A receiver is never marked. doc.replace(…) takes &var self and the call says nothing, as in Rust's v.push(x). Marking arguments and not the receiver is the established convention and the receiver is already named by the method.

  4. Re-borrowing a &var parameter is a &var argument, nothing special: examples/Worker/types/job.elp writes self.value.hash(&var into) and it is correct as written.

  5. &var paths are exclusive. Two &var arguments to one call may not overlap, and a &var path may not coexist with any other path to the same storage for its duration. This is Rust's rule and there is no cheaper one; it is also what the "two live mutable paths" objection in "One hole" wanted and could not state.

  6. Projection is allowed through fields, and nowhere else. &var self.root is legal, because the path is statically known and the exclusivity check can see all of it — and because the corpus already does exactly this in receiver position, in every file, undeclared (self.nodes.set(at, node) needs &var self.nodes). A rule that permits it as a receiver and forbids it as an argument has no content. What stays forbidden is projection through a collection index (&var children[i], where the container may reallocate) and out of a cell (&var c.contents, which is the guard this file rejected). Those two are what the transform closure is for.

  7. At an @external declaration, C's const is the answer — a const T* parameter is &T and a writable T* is &var T. This replaces the conservative blanket above, which was adopted only because no spelling existed. The cost is that correctness now rests on transcribing the header faithfully, which is already true of every other part of an @external declaration and is the register aliasing.md puts that boundary in.

    Refined by the corpus scan, and it is narrower than it sounds. Applied literally, SQLite takes a non-const sqlite3* for every call including sqlite3_errmsg, so every handle parameter in the corpus would become &var and the distinction would carry no information. It does not, because &var can only mean something where elp owns the storage C writes into — which is exactly the three boundary forms this file already has:

    boundary form&var?what it means
    an opaque handle, &T over an @external typenothe handle is the pointer; there is no elp storage, so C's constness is invisible and unenforceable
    a slot, &Optional<T>yes, when C writes itthe out-parameter case — sqlite3_open's db, every Vulkan vkCreate*
    an extent, &Buffer<T>yes, when C writes itC may write the elements. It never means C may replace the buffer: the length and the address are elp's.

    That is also the answer to the question this rule left open, and the migration it implies is the one the corpus actually got: nine slots and three extents, and not one handle.

  8. Exclusivity holds at an @external call too, and the aliasing case is declared rather than excepted. This rule said the opposite for a day and the correction is worth keeping on the page, because the first answer was the obvious one and the second is better.

    The problem is real. examples/Playhead makes the corpus's most real-world FFI call, and the C signature takes two output pointers that it passes the same buffer to:

    fluid_synth_write_s16(synth, frames,
                          buffer, 0, 2,    // left:  offset 0, stride 2
                          buffer, 1, 2)    // right: offset 1, stride 2
    

    One allocation, two logical channels, offset and stride as arguments — the shape that probe's FINDING 3 cites as the reason Buffer<T> needs no layout parameter. Written as two &var arguments it violates rule 5, and the first answer here was to except it: exclusivity is between elp-side paths and cannot reach across the boundary, because the C ABI has no aliasing model.

    True about C, and the wrong place to spend the exception. The aliasing is a property of the call, not of the boundary, and a binding can say so:

    @external(.C, library = "fluidsynth") {
    	export fn writeInterleaved(
    		symbol      = "fluid_synth_write_s16",
    		synth       &FluidSynth,
    		frames      int,
    		out         &var Buffer<int16>,
    		leftOffset  int,
    		leftStride  int,
    		rightOffset int,
    		rightStride int,
    	) -> int
    
    	export fn writePlanar(
    		symbol = "fluid_synth_write_s16",
    		synth  &FluidSynth,
    		frames int,
    		left   &var Buffer<int16>,
    		...
    	) -> int
    }

    Two elp declarations over one C symbol, which is the same mechanism examples/VulkanTriangle's count-then-fill already needs and which is already parked as a symbol = argument in the Open list below. The interleaved form takes one &var and the lowering emits the pointer twice with the two offsets; the planar form takes two, which genuinely are distinct allocations. Neither declaration aliases on the elp side, so rule 5 needs no exception at all.

    What it costs: an @external declaration no longer maps one-to-one onto the C signature, and "transcribe the header faithfully" is the rule that makes @external auditable. The answer is that the arity difference is the information — a reader sees that this binding is the interleaved mode, which the faithful transcription does not say anywhere.

    One consequence for codegen survives from the first answer: a &var argument at an @external call lowers to a raw pointer rather than &mut, because the thunk hands the same address to C twice and two &mut to one allocation is undefined behaviour in Rust whatever C does. That is now confined to the generated thunk instead of appearing in user code.

  9. A pattern is a projection, which settles matching through a reference. Matching a &var T binds each payload field as a &var path; matching a &T binds &T. This needs no separate decision because rule 6 is the decision — match self { .LEAF { entries } -> … } and &var self.entries name the same storage by two spellings, and the exclusivity check sees the same path either way. It was listed as a prerequisite of the transform closure (tree-places.elp GAP 3) rather than as something with its own answer; it turns out to be a consequence.

What Finding 4 keeps. Everything about the read-only case: &x needs no marker, const is the default, and the diagnostic for passing a const binding where mutation is required is unchanged. What it loses is the claim that one spelling suffices, and it is worth being plain about why it looked true for so long — the corpus it was derived from mutates through a receiver or through a cell in every single case, so the one position that needs the spelling never appeared.

Finding 5 — pure fn + borrowing, resolved

No function in the login-form exercise is marked pure, so the roadmap's "how pure fn interacts with borrowing" question wasn't exercised by it. Resolved anyway, by tracing it against findings already made rather than by example:

  • Parameters are immutable, unconditionally, no carve-out. pure fn's existing "immutable arguments" rule means a parameter can never be reassigned, full stop — not "unless the mutation doesn't escape." This isn't restrictive in practice because of the next point.
  • Copy is the entire escape hatch. If a computation needs a mutable value derived from an immutable argument, copy it into a fresh local binding and mutate that — a distinct value, not the argument. Primitives get this for free; object types need Copy explicitly, the same opt-in already required everywhere else Copy matters. See Finding 6 for the syntax this needs when the argument is itself a reference rather than an owned value.
  • References into parameters can only ever be &T. This used to fall out of Finding 4's inference — a parameter is const-for-the-body, so any &ident into it elaborated to &T. Under the third amendment it is a rule rather than a consequence: a pure fn may not declare &var on a parameter, and may not pass one of its own parameters to a &var argument. Same outcome, stated directly, and better — it is now visible in the signature instead of emerging from the body.
  • "Long-lived borrows" (the roadmap's original phrasing) were already impossible, purity or not. Finding 3 already says a closure can't capture anything that isn't Copy/Move, and a bare &T isn't either by default — so a pure fn can't smuggle a borrowed parameter into a returned/stored closure any more than a non-pure fn can. Nothing purity-specific needed here.
  • Returning a reference derived from a parameter (pure fn firstWord(s &string) -> &string) is unaffected by purity — ordinary borrow-return shape, same as any function.
  • Calling other functions from a pure fn body must itself stay pure — already covered by the existing "no external calls" rule in grammar-script-notes.md, not a new restriction added here.

Finding 6 — getting a value out from behind a reference needs its own syntax, and its own ownership story

Came out of a counter-argument to Finding 5: "copy it into a fresh local" is fine as a rule, but what does that look like when the argument you're holding is already a reference? myPureFn(*dereffed, &reffed) — who owns what, when, and why.

Three distinct call-site forms, three distinct ownership stories:

  • Bare x (no sigil) — pass by value. Governed entirely by Finding 3's Copy/Move check on x's own type. Ownership either transfers (Move) or a fresh independent copy is made (Copy) at the call.
  • &reffed — pass a borrowed reference. No ownership change at all. Callee gets temporary access, &T or &mut T per Finding 4 (always &T into a pure fn). Ownership stays exactly where it already was.
  • *dereffed — dereffed is itself a reference (&SomeType). * dereferences it and copies the referent, producing a new, independently owned value that belongs to the callee's parameter from the instant of the call. Whatever dereffed pointed to is untouched afterward — still valid, still owned by whoever owned it before. Only legal if SomeType implements Copy. It can never mean "move the value out from behind dereffed" — moving out of a shared reference is unsound for the same reason Rust itself forbids it (something else may still hold a reference to that slot); rejected with a Copy/Move-style diagnostic ("cannot copy SomeType through a reference — it doesn't implement Copy"), not silently deferred to whatever error rustc would eventually produce on the generated code.

The principle this establishes, generally, not just for pure fn: implicit reference-to-value coercion is banned. If you're holding a &T and a call site wants a T, the compiler never silently inserts a copy — * makes that copy visible in source. Same ethos as the ?-operator objection in error-handling.md: anything that duplicates a value should be a token someone typed, not something inferred on their behalf.

Does this mean every type needs its own &FooBar implements Copy {} block? No — and this is worth being precise about, because it's a different question than whether FooBar itself is Copy. A reference (&T, for any T) is unconditionally cheap to copy — duplicating it just duplicates a pointer-sized handle, never the referent — so &_ belongs in the same "free, no declaration" tier as primitives, not in the ordinary nominal-Copy-conformance tier objects live in. It isn't a new rule either: &_ is just the simplest case of the pattern Arc<T> and Reactive<T> already established in Finding 3 — a cheap-to-copy handle whose own copyability is entirely independent of whether the thing it points to is copyable. You can always copy a &FooBar to get a second reference to the same FooBar, even when FooBar itself isn't Copy at all. What actually gates on FooBar: Copy is specifically the deref — *dereffed copying the referent out — not the reference handle itself. One is compiler-intrinsic and universal; the other is the ordinary, explicitly-declared conformance this whole document already depends on.

Implementation status: prefix-* is now real. parse_unary (crates/parser/src/ast/expression.rs) recognizes * as a fourth unary operator alongside !, -, &, sharing the same STAR token kind binary Multiply already used — grammatical position (start of an operand vs. between two operands) disambiguates the two, the same way Rust/C resolve it, and 1 * *x parses as multiply-of-a-deref to confirm it. This is parsing only: * produces a UNARY_EXPR node in the CST, the same as !/-/& do; the Copy-gated semantics described above (only legal when the referent type is Copy, never a move) are a typecheck-time concern for Phase 2, not enforced by the parser. Also worth flagging so it doesn't read as a conflict: *fn already exists as a declaration-position prefix (the required-callback marker seen in login-form.velp) — a different grammatical slot from expression- position *, not in conflict, but the same character doing two unrelated jobs is worth naming rather than leaving implicit.

Visibility — private by default, export to expose

Fields and component members are private by default; export exposes them. Same keyword as top-level declarations, same single meaning everywhere: visibility, and nothing else.

This is what makes the interface model's same-name field/method rule (interfaces.md) pay off — storage stays private while a same-named method is the public path, so a type controls what callers get at that name and can change it later without touching a call site.

export does not confer reactivity

Reactivity is keyed off var inside a component body, exactly as Finding 2 established — not off export. The two axes are orthogonal:

privateexported
var in a componentreactive local statereactive prop
field on an objectplain private fieldplain readable field
*fn callback(illegal)callback prop

*fn is the one exception to export-is-optional: a callback slot can only be filled from outside, so a private one could never hold a value. Rejected at parse time rather than parsed into something provably nil.

A prop is just the intersection — a reactive var that happens to be public. The corpus already depends on this being orthogonal: login-form.velp's private password and attempts are reactive without being exported, and Finding 2's whole lowering rule keys off "is this binding inside a component", not visibility. If export also meant "reactive", those two mechanisms would collide on the same job and the private-but-reactive case would contradict it outright.

Arguments are constant; props are reactive

A component can receive data two ways, and they mean different things:

  • Arguments (fn Message(from User, body string) -> Component) are constant inputs. Plain owned values, no cell, no observation.
  • Props (export var email Optional<string> in the body) are reactive. Reactive<T>, observed, re-render on change.

The wrinkle worth stating because it will be misread: passing a reference to a reactive cell as an argument (EmailInput(&email, ...), which the corpus does) keeps the argument binding constant while writes through the reference still drive reactivity. Constant binding, reactive pointee — the two aren't in conflict, and & is what carries the difference.

What "private" scopes to — the type, reached through self

A private field is reachable only through self, and only from the type's own implementations. Not package-private, not file-private (file location carries no compiler meaning anyway — interfaces.md open question #2). fn ChatState.usersInRoom(&self) may read self.usersInRoom; a free function holding a ChatState may not read its fields at all, whatever file it lives in.

The model is Lua's: a method is a free function whose first argument is the receiver, and self is the whole of its access to the instance. That's why the boundary is the type rather than a lexical block — a dotted method body isn't lexically nested inside the object it belongs to, so what scopes the access is "is this an implementation of this type, reaching through self".

Consequence worth knowing up front: this is stricter than Rust, where any code in the defining module can touch any instance's private fields. Here, a second instance of the same type is not reachable — given fn Foo.equals(&self, other &Self) -> bool, self.x is legal and other.x is not; other is reachable only through its public methods. That lands closest to the interface isolation rule (interfaces.md), which already says a default method body may only call methods, never touch fields — so the concrete-type rule and the interface rule agree rather than pulling apart. It does mean Equatable-shaped comparisons are written against methods on other, which is a real ergonomic cost and the thing most likely to be argued with later.

Parsed. export var/export const/export *fn now dispatch in statement position (parse_statement), so the prop forms this document elaborates finally parse where they're actually written — inside a component body. They previously had no dispatch arm at all and fell through to the expression parser. The parser accepts them in any block, deliberately: it can't distinguish a component from a plain fn returning Component, so "props only exist in components" is a semantic check for a later pass. A bare *fn (no export) is a parse error — see the table above.

Props cross the boundary by move, or copy if that's all there is

An exported component prop is reactive within the component and fed from outside. The value transfers by move, falling back to copy only when the type implements Copy and not Move — move is the preferred direction, not the fallback. So Copy/Move conformance decides the prop-passing mechanism; it isn't a component-specific rule.

This splits prop dataflow cleanly in two, which is worth stating because the corpus uses both:

  • Moved in (Message(from=user, body=text)) — one-way. The parent gives the value up; there is no path back.
  • Passed by reference (EmailInput(&email, ...)) — two-way. The callee writes through the reference into the caller's reactive cell.

Amended by reactivity.md for reactive values. Move is right for plain values and wrong for reactive ones: moving a reactive value severs the subscription that makes the prop reactive at all. A reactive prop crosses as a handle, and there are three modes rather than two — a dead snapshot (what a move gives, almost never wanted), a read-only live share (no sigil), and a writable live share (&). The middle one is the mode this section was missing.

No package-level variables or globals

Beyond objects, components and interfaces, elp has no package-level variables and no global values. There is no file-scope mutable state for anything to share, which is part of why "private" can be scoped to the type without leaving a hole — there is no ambient scope for a value to leak into.

The rule targets package-level state, so const is unaffected — a compile-time constant has no identity to share. BlogStyle/constants.elp (export const FONT_COZETTE) and screens/home.velp (const NAME) stay exactly as written.

Enforced in the parser. Top-level var is a parse error naming the alternative: "elp has no package-level variables; use const for a file-scope constant, or hold mutable state in an object or component". var is still dispatched as a declaration keyword rather than dropped from the keyword list, so the message comes out here instead of the expression parser failing on a stray var. Block-scoped var is untouched.

Fields carry var, and that is what grants writes — resolved

The question was whether export on a field grants writes as Rust's pub does, or reads only. Rust's answer hands out unmediated mutation and the access-flow control above evaporates precisely when someone reaches for it; read-only exposure preserves the invariant story but makes two-way binding into a model field impossible, which is most of what a form does.

Both answers are wrong because the question is wrong. It asks for one global answer to a per-field decision, and the reason it looked global is a gap: object fields currently carry no mutability marker at all. Locals distinguish var from const; fields do not.

export object ChatState {
	usersInRoom [User] = []     // private, immutable
	messages [Message] = []
}

Give fields the marker and the question answers itself:

declarationoutside the type
const field Tnot visible
var field Tnot visible
export const field Tread
export var field Tread and write — &obj.field is legal

Amended by aliasing.md. This table originally had a bare field T form and said const is "not accepted on a field: it is the default, and two spellings for the default is one more than the language needs." The corpus writes const on 72 fields and bare on none, so the rule was both unimplemented and unloved — and it gave two spellings for immutable against one for mutable. A field now spells const or var, exactly like a local, and bare is an error. One spelling each, zero migration, and a reader never has to decide whether a missing word meant immutable or meant the author forgot.

The marker governs rebinding only. Whether anything can be written through the field is a property of the field's type — a Confined<Style> is writable through a const field — and that is what decides Copy eligibility. Two independent axes; see aliasing.md, "Copy is field-wise".

The migration cost is zero. No object field in the corpus is ever mutated in place — Post, Content, ApiError, ChatAppState, ChatState, Author, User, BlogPostParams are all constructed whole and replaced via copyWith or Self { ... }. Every existing field is correct as written, and var has no corpus instance yet.

That is worth stating plainly: this is a forward-looking rule, not one the corpus demanded. It earns its place by closing the export question with a mechanism instead of a blanket answer, and by giving &obj a precise meaning — a binding to the object through which each field is writable only if that field says so, rather than a blanket grant that would launder past visibility. See reactivity.md, "Bind the field, not the object".

Release — defer x.release(), and no keyword

Move gives at-most-once release and never at-least-once. A dropped Connection leaks the C allocation and nothing notices. Three unrelated probes reached for a construct here independently — examples/SqliteBinding for exactly-once release, examples/VulkanTriangle twice over, and aliasing.md noticing that Synchronized<T>'s two closures are the same shape — which is still the strongest convergence in the corpus and is about the problem, not about any answer to it.

The answer is two lines of ordinary code

const db = Connection.open(path)?
defer db.release()

db.prepare("select 1")

defer already exists (reactivity.md), already runs on normal exit, cancellation unwind and panic unwind, and already runs LIFO within a scope. release takes &self. There is nothing else.

with ... as x { } — designed, never ratified, deleted

A statement form was designed here on 9 November — with expr as x { }, multiple bindings released in reverse, and a Scoped interface whose release(self) the compiler called at every exit. Deleted on 2026-11-20, by the decision-maker, with the reasoning stated as: keep magic words low and let the engineer write explicit code to do explicit things.

It is worth recording how it survived eleven days, because the mechanism was not a bad idea and the process was the failure. It was introduced in the same commit that deleted a different keyword I had invented (490a1b7, "Design scoped release, and delete the out keyword I invented"), justified by the three probes above asking for the problem, and written up as a finished section rather than a proposal. Nobody ratified it; the record simply stopped asking. It was flagged by the decision-maker asking where it had come from, after seeing the unrelated Synchronized.with method six times in the corpus and the statement once.

What the comparison showed. Eleven rows separate a with from a defer and exactly one of them was a difference in capability:

with was a defer that could consume. defer db.release() with release(self) by value needs to know the value is still owned at scope exit — drop flags and moved-out analysis, the cost this document refuses for RAII. with dodged it by never giving the block ownership: the binding was a borrow, so consuming at exit was unconditionally legal.

Everything else defer already did, or neither did. So the whole keyword rested on release taking self, and release now takes &self.

What that costs, stated rather than discovered later

&self is not free, and all three costs are the kind the engineer can see:

At-least-once is a lint, not a guaranteeForgetting the defer leaks, exactly as forgetting the with did — a Scoped type never bound by a with was never released either, and nothing warned. examples/Json/internal/parser.elp had already said so in passing: "defer is at-most-once-if-you-write-it, same as with." So this is not a regression; it is the same hole, now visible. The candidate is the @MustUse-shaped lint rejected in November as "catches the common case and nothing else" — which is now the only candidate, and the common case is what the corpus has.
Double release becomes spellableBy-value release made it unspellable; &self does not. sqlite3_close twice is undefined behaviour. Two mitigations, neither ratified: a lint for a release called outside a defer, or the type guarding itself with a var released bool and &var self — one field, no language surface, and the kind of explicit thing this decision prefers.
Ordering is the author'sReverse release across several with bindings is now LIFO across several defers, which is the same guarantee from the same mechanism — but only for resources released in one scope. VulkanTriangle's renderer-before-window ordering spanned two files, and it now holds because main writes two defers in acquisition order rather than because the construct arranged it.

What deleting it dissolved

Four open questions were about the construct and go with it:

  • Whether a with block may yield. defer has no block to yield inside.
  • Early return out of a with block. defer specifies all three exits.
  • A ? inside a with block. Same answer, and it was opened an hour before the deletion by SqliteBinding's first real call site.
  • A consuming binding. The whole of it was in service of by-value release.

What it leaves, which is less than it looks

  • Whether release may fail. Survives, unchanged: sqlite3_close returns a status and release returns nothing, so a failing release is dropped. Connection.close(self) still exists returning Either, and the engineer now chooses between them at the call site rather than the construct choosing. That is strictly better for this question.
  • A resource assembled for a caller (VulkanTriangle GAP 4) — and deleting the keyword narrows the candidates to one. A plain defer is wrong there because it runs on success too, and the handles must leave with the returned value. The consuming binding is gone. What is left is defer with an exit binding — defer (exit) { … }, one grammar rule on a keyword that already exists, which is a smaller ask than either deleted thing. Until then the error path is the goto fail ladder written out, which is what the corpus has and what explicit means here.
  • A resource acquired in a loop. A defer in a loop body runs at the body's exit, which reactivity.md calls a footgun and which is in fact exactly right for a per-iteration resource. The case that stays unanswered is n handles that must survive the loop and be released on a later failure.
  • A resource owned by a platform runtime (examples/Playhead's AudioDriver). Unchanged and unhelped: there is no scope to attach a defer to either, so the platform's teardown callback calls release by hand. This was never a construct question.
  • Scoped survives as a marker, demoted. It names the obligation and gives the lint above something to key on; the compiler no longer calls it. One thing is lost with the keyword: release(self) was "the second and harder witness for a by-value receiver", and that witness is gone. Connection.close(self) is the remaining one, so functions.md's by-value receiver gap stands on one leg.

Why none of this reopens the lock guard

aliasing.md rejected a lock guard object because yield points are invisible, so a guard could be held across a yielding call and deadlock with nothing in the source marking the boundary. A defer that releases a lock has exactly the same problem, and the with block's marked boundary never fixed it either — the yield inside was still invisible.

So release is for resources, not for locks. A resource needs release once and in order; it does not need exclusivity between statements. Synchronized<T> keeps its two closures (update and read) for the reason already recorded.

The handle-less case needs no construct either

examples/VulkanTriangle found that glfwInit/glfwTerminate are process-global with nothing for a tier to describe. A token type still fixes it, and it needs no keyword:

const glfw = Glfw.initialised()?
defer glfw.release()

Summary for Phase 2

elp constructRust elaborationConfidence
Script-level var xlet mut xDecided (Finding 1)
Script-level const xlet xDecided (Finding 1)
Component var x (reactive)Reactive<T> field, interior mutabilityConfirmed by this exercise
&type / &ident on a reactive fieldrefcounted handle to the Reactive<T> cell, not a plain shared refAmended by reactivity.md (props are shares, not borrows)
& in prop positionconstructs a binding from a cell, forwards one it is given; written at every writable call siteDecided (reactivity.md)
export var on an object fieldthe only form granting outside writes; bare fields are immutable and privateDecided (this document, above)
&type / &ident on a plain const value&T, alwaysDecided (Finding 4)
&type / &ident on a plain var value&T or &mut T, inferred from callee usageDecided (Finding 4), mechanism not yet in the typechecker
Component methods (render, event handlers)&self, never &mut selfConfirmed by this exercise, contingent on Finding 2
*fn callback propsOption<Arc<dyn Fn(...)>>Confirmed by this exercise, contingent on Finding 3
Capturing any value into a closure, or passing it by valueLegal iff the type implements Copy/Move (interfaces.md); no capture-list syntaxDecided, mechanism not yet in the typechecker
pure fn parametersconst-for-the-body; refs into them always &TDecided (Finding 5)
x (bare) at a call siteCopy/Move per Finding 3, unchangedDecided
&x at a call siteBorrow, no ownership change, &T/&mut T per Finding 4Decided
*x at a call site (x itself a reference)Deref-and-copy the referent; legal iff referent type is CopyDecided (Finding 6); * prefix parses today, Copy-gating is Phase 2
A value read out of a collectionA copy; mutating it does not touch the collection, and a write-back (map.set(k, v)) is required and explicitDecided (core-language-probes.md, store.elp)
&T itself (the reference, not its referent)Unconditionally Copy for any T, compiler-intrinsic — same "free" tier as primitives, not ordinary nominal conformance. Amended: a field may not hold a borrow (aliasing.md), because a field outlives the call that bounds a borrow and this row then makes it a free duplication routeDecided (Finding 6), amended by aliasing.md
Shared<T> (immutable alias)Refcounted handle, Copy for any T — the owning form of the row aboveDecided (aliasing.md)
Confined<T> / Synchronized<T> (mutable alias)Refcounted handle, Move; a second handle via .alias(), never Copy — so any type holding one is not Copy, field-wiseDecided (aliasing.md)

Every row in this table is now decided in rule; nothing here is left genuinely open. Three rows were reopened after this sentence was first written and are now closed again by aliasing.md — the capture/ pass-by-value rows said Copy/Move when the tier they needed was Duplicate, and the two aliasing rows above did not exist because the types did not. The third was the &T row, and it was a soundness bug rather than an omission: &T is Copy because T's only mutators are elp code honouring the borrow, which stops being true at an @external type whose mutators are in C. A borrow is bounded by its call, so the amendment is that a field may not hold one. What remains is implementation, not design: Copy/Move depend on interfaces.md's open questions (nominal-conformance syntax, whether default methods can depend on other interfaces) being settled first; the var/&mut usage-inference rule needs the same callee-body analysis machinery closures already require for capture mode; and the Copy-gating on * (legal only when the referent type implements Copy) is a typecheck-time check, not yet written — the parser already accepts prefix-* (crates/parser/src/ast/expression.rs), it just doesn't know yet whether a given use of it is sound. None of that blocks Phase 2 from starting — it's real work Phase 2 does, not a question Phase 2 is waiting on an answer to.

Collections hold values, not places

A value obtained from a collection is a copy. Mutating it has no effect on the collection, and persisting the change requires an explicit write-back:

.RESOLVE(code, reply) -> {
	match links.get(code) {
		nil  -> reply.send(Err(StoreError.NOT_FOUND(code)))
		link -> {
			link.hits += 1
			links.set(code, link)      // required, not optional
			reply.send(Ok(link))
		}
	}
}

This is the consistent reading of the old corpus's state.messages.copy().append(...) — a line that never type-checked, since collections.md returns unit from a mutating method (core-language-probes.md §16) — and it is the conservative choice: an API that forgets the write-back is a visible no-op rather than an invisible aliasing bug.

The cost is verbosity, and it is accepted deliberately — the cheaper spelling (map.get(k) yielding a mutable place, or an update(k, fn) helper) can be built in elp later without changing the semantics. A language rule that hands out hidden aliases cannot be walked back.

Later is now. update(at, fn (&var T) -> R) -> R is ratified in aliasing.md and listed in collections.md, and the judgement above held: it changed no semantics, because the transform's critical section is syntactically total and the element never leaves the collection. The sentence to keep is the last one. What was ratified is the cheaper spelling, not a mutable place — there is still no expression anywhere in elp that produces one.

One hole, reported nine times — there is no place you can hand out

Written after examples/Recalc found a cell cannot mutate a Move aggregate, which turned out to be the ninth report of a single absence. It belongs here rather than in aliasing.md because the absence is in this file's subject, and because Finding 4 is where it starts.

&var self on a method receiver is the only mutable access in the language. Finding 4 settled that &x needs no mutable spelling because the choice is determined by callee usage, and that is right — for a parameter. What it was taken to mean is that elp needs no notion of a mutable place anywhere, and the consequences landed in places Finding 4 never looked at. Mutable places do exist internally, as the inferred &mut T; what does not exist is any way for a library type to expose one. &var self is the sole exposure, and it is receiver-only and whole-value.

Every one of these is that absence, and they were filed as nine unrelated gaps across four probes:

reportwhereclosed by
&var self.root — a projection into a fieldcore-language-probes.md, "Mutable paths into an interior node"&var T, rule 6
&var to a local, and re-borrowing a &var parametersame&var T, rules 2 and 4
matching through a referencesame&var T, rule 9
whole-value assignment through a referenceexamples/QuadTree GAP 4self = … in a method, by precedent
collections hold values, not placesabove, in this filethe transform closure
&var T as a non-receiver parameter, 16 call sitesOpen, in this fileitself
a cell's only write is whole-valuealiasing.md, "the loosening is already indicated"the transform closure
Map.get on a Move value has no meaningcore-language-probes.md §12the transform closure, partly — see there
a Move resource inside a cell cannot be releasedexamples/Playhead GAP 6the transform closure, plus .take()

The right-hand column was filled in afterwards, and it is the point: two decisions close nine reports, which is what being one absence predicted.

Three things follow, and they are the reason this is worth a section.

1. It is not a corner, it is an unfinished edit. A cell's write surface was never decided. aliasing.md records that Synchronized<T> got .update(fn (T) -> T) as a correction, made while migrating examples/Pipeline. Confined<T> predates that correction and never received it. One cell was revised and the other was not, and the asymmetry has been reasoned backwards into a principle since.

2. The fix is already parked in this file. "Collections hold values, not places" accepts its verbosity on the grounds that "the cheaper spelling (map.get(k) yielding a mutable place, or an update(k, fn) helper) can be built in elp later without changing the semantics." That is the same fix the cell needs, named and judged purely additive, one type away from where it is wanted. What was never done is notice that the two are one thing.

3. Confinement is being used as a general answer to aliasing questions and is not one. aliasing.md justifies the cell's .get()/.set() pair because the cell thread makes the sequence atomic. core-language-probes.md had already answered that argument for a different probe: "Cell-thread confinement does not help: it rules out interleaving, and this is straight-line aliasing inside one turn." Confinement orders turns. It says nothing about two live mutable paths within one.

All nine are now closed, by two decisions, which is the strongest evidence this section was right that they were one thing: &var T as a parameter (Finding 4's third amendment) and the transform closure (aliasing.md). The three residuals that survive are each a different question wearing a gap's number — a consuming .take() on a cell, a borrowing Map.get, and a once-only closure — and none of them is about handing out a place.

What this does not excuse. The reason guards were rejected — aliasing.md's invisible yield points — is a good reason, and it applies to any mutable place whose lifetime spans statements. So the exposure wanted here is not Rust's RefMut or Swift's inout-by-default; it is the lexically bounded form the corpus already reached for twice, a transform closure, whose critical section is syntactically total. Rust's RefCell::replace_with<F: FnOnce(&mut T) -> T> is that shape and is the one to copy, because the payload never leaves the cell and so there is no hole to re-enter.

Which makes the &var T Open item above load-bearing for nine gaps rather than for 16 call sites, and its stated leaning — that the spelling has to exist and the call sites are what Finding 4 forbids — the thing to ratify first.

Tested, and it holds. examples/QuadTree/tree-places.elp rewrites the deepest mutation in the corpus with projection forbidden, and needs none: the recursion supplies the depth, so one closure appears in the source per level of nesting, not per level of descent. Of that probe's six gaps, one reframes (the corpus already uses receiver-position projection in every file — self.nodes.set(at, node) needs &var self.nodes), two resolve, one is promoted to a prerequisite, one turns out to be independent and mis-evidenced, and one is untouched.

One caveat, and it is not in this section's favour. The hypothesis is about the write side. The read side has a separate hole: children[i] being a copy is an invisible no-op when writing and correct and quadratic when reading, since copying a node copies a subtree once per level. The write hole's fix is purely additive; the read hole runs into three ratified decisions at once (values-not-places, no borrow in a field, no unreachable expression), and the cheap way out is copy-on-write rather than an indexed borrow. See that probe's FINDING 5 and GAP 8.

A recursive value type needs an indirection, not a box

examples/QuadTree GAP 1 asked for this and examples/Interpreter FINDING 1 supplied the evidence it had been missing: Expr.BINARY holds two Expr directly, so size(Expr) = tag + 2 * size(Expr) has no finite solution, and unlike QuadTree's own enum there is no array anywhere to supply an indirection. An AST is the most common recursive type any language compiles, and examples/Editor then found a second blocked program — an undo stack needs path-copying, which is a rope, which is this.

Ratified: a field marker, not a type. Swift's precedent is one keyword: indirect enum Expr { case binary(Expr, Expr) }, where the marked case's payload is stored behind a heap allocation and the enum's own size becomes a pointer. The box is invisible: a pattern match binds an Expr, not a Box<Expr>, and there is no deref at any use site.

The rule

indirect is a modifier on a field declaration. An enum case's payload entries are fields, so one rule covers both declaration forms and reads the same in each:

export enum Expr {
	LITERAL { of int },
	BINARY { op Operator, indirect left Expr, indirect right Expr },
}

export object ListNode {
	var value int,
	indirect var next Optional<ListNode>,
}
  1. It is a layout instruction, and the field's type is unchanged. The field is stored behind one allocation. A pattern match binds an Expr, a field read yields an Expr, and there is no deref at any use site. The marker appears in the declaration and nowhere else — not in a signature, not at a call, not in a pattern.
  2. It is required, never inferred. A declaration whose layout does not terminate is an error, recursive_layout, and the message names the fields that would break the cycle. Inferring the box would hide an allocation, and this language spells cost out: .copy() is explicit and Buffer<T> is deliberately not atmospheric.
  3. It may be written where it is not required. On a non-recursive field it moves a large payload out of line. That is not a special case; it is the same instruction with no cycle to break.
  4. The box is immutable: an indirect field may be replaced, never written through. node.next = .SOME(other) rebinds the field and is allowed — it swaps which box this value points at, and no other holder observes it. node.next.value = 5, and any &var method call on a path that passes through an indirect field, is an error: write_through_indirect. This is Shared<T>'s rule and it is here for Shared<T>'s reason.
  5. The marker does not change the containing type's tier. Copy stays field-wise: an indirect field is Copy when its type is, because under rule 4 an immutable alias is observationally identical to a copy (aliasing.md). .copy() on an indirect field copies the pointer, for the same reason — which answers one case of that file's open "how deep is .copy()" question. If the field's type is Move the containing type is Move, field-wise, and that case turns out to be the interesting one: see the consequences below.
  6. == compares pointees. The box is invisible and operators.md has no ===, so structural comparison is the only answer consistent with the rest of the marker. The implementation may short-circuit on pointer equality; that is an optimisation, not a semantic.

One cost, accepted. Swift's case-level marker boxes a whole payload once; a field-level marker boxes each marked field, so BINARY is two allocations where Swift's is one. The field-level rule is kept because it is one rule rather than two, and because a case-level form can be added later as sugar for "mark every field of this case" without changing what any program means — the same additive argument "Collections hold values, not places" uses above. Migrating examples/Interpreter priced it (that probe's finding 10: eight allocations for a three-node expression, against Swift's three) and also supplied the better answer: coalescing one case's indirect fields into a single allocation is invisible under rule 1, so it is a codegen choice rather than a second piece of syntax.

Why a marker rather than a Boxed<T>

Boxed<T> is the obvious alternative and Rust is the argument against it. Box<T> had to become a lang item to support moving a value out of it, and fifteen years later a user still cannot write an equivalent — there is no DerefMove. A privileged type that no library can match is exactly the bucket stdlib-boundary.md says to keep empty.

A marker adds no type. It is a layout instruction, so there is nothing to privilege, nothing to name, and nothing a user is unable to compete with. It is both the smaller change and the barer one, which is that file's rule working.

Rust Box<T>Swift indirectproposed
user names a typeyesnono
visible at the use site*b, &*binvisibleinvisible
works on an object, not just an enumyesno — enum onlyyes
mutable through ityesn/ano — see below
privilegedyes, a lang itemno type to privilegeno type to privilege

Two decisions Swift's answer does not make for us

1. It should apply to a field, not only to an enum case. indirect is enum-only in Swift, so a recursive struct is still illegal there and people reach for a class. elp has object and enum as peers and a rule covering one but not the other would need a justification there is no material for. A per-field marker covers both and reads the same in each.

2. The box is immutable, and that fixes its tier. This is the load-bearing choice. An indirect field is a refcounted allocation, so:

  • immutable — the box is Shared-shaped, and the containing type is Copy, by the same argument aliasing.md already makes for Shared<T> ("an immutable alias is observationally identical to a copy"). Copying an Expr copies a pointer and retains.
  • mutable — the box would be Confined-shaped, which drags in the entire write-surface problem: a cell holding a Move aggregate cannot have its fields updated, five sightings and counting. GAP 1 and the write surface would become one gap.

So the box is immutable, and the cost is stated rather than hidden: a recursive value type is built, not edited. Rebuilding a path is how a persistent structure works anyway, which is exactly what examples/Editor's undo needs, and examples/Interpreter's AST is immutable by nature.

What that buys, beyond the obvious. examples/Interpreter FINDING 3 found that a closure value cannot own its body — the AST arrives as &Expr, a field may not hold a borrow, so Shared<Expr> was forced and with it the conclusion that "the AST must be built into cells up front", a representation decision imposed on the parser by one arm of the evaluator. With an immutable indirect, Expr is Copy and CLOSURE { body Expr } works directly. That finding dissolves.

And what it does not cover, stated so the scan can check it: an in-place mutable recursive structure. The claim worth testing against the whole corpus is that there is no such type — QuadTree's is array-indirected and needs no marker, examples/LruCache showed the mutable list is unnecessary, and examples/Recalc's graph is an arena. If the scan finds one, this decision is the thing it falsifies.

Smaller consequences

  • The marker is required, never inferred. Inferring "this type is recursive, box it" would hide an allocation, and the surrounding style makes cost visible — .copy() is explicit, Buffer<T> is not atmospheric. The diagnostic on the unmarked version is what teaches it, which is what examples/Interpreter's FINDING 1 asks for.

  • Copying retains; borrowing does not. @abi(.C, realtime) forbids a refcount decrement reaching zero, so an indirect value may be walked through a borrow in a realtime body but not copied into one or dropped there. The same is already true of Shared<T>, so this adds no rule. It does mean an interpreter cannot build or discard an AST on the audio thread, which is the realistic version of the restriction.

  • A Move chain needs no refcount at all. Rule 5 makes a recursive type whose field type is Move itself Move, so the box has exactly one owner and can be a unique allocation rather than a shared one. Rule 4 still applies — immutability is about the write surface, not about sharing — but the realtime consequence above softens to the allocator alone, and the implementation has a cheaper representation available without a second marker to select it.

  • Layout interaction. An indirect field is pointer-sized, so a recursive type could satisfy Atomic<T>'s eight-byte requirement. Harmless, and worth noting so it is not mistaken for a bug when the layout pass reports it.

  • Freeing a long chain is unbounded recursion, and it is the runtime's problem. The box is refcounted, so dropping the head frees it, which drops the field it contains, which frees that — one native frame per link, on a chain whose length may come from input. examples/Untrusted has it with a comment thread.

    Two things make this worth stating here rather than leaving to an implementation. The scoped-release section above compares with against RAII and says "recursive release of fields (drop glue): no", which is true, is about Scoped, and reads as covering this when it does not. And the standard fix — an iterative drop that walks the chain unlinking as it goes — is exactly what rule 4 permits and exactly what a program cannot write, since the drop is not a program. Rust has the same bug for a long Box chain, which makes it a known cost of the technique rather than a surprise.

    The remediation is a runtime obligation and it costs the language nothing — written down because an obligation nobody records is not one. A chain unlinks iteratively in constant extra space. A tree — examples/Json's JSON, examples/QuadTree — needs either an explicit worklist, which asks for memory in order to release memory, or pointer reversal in the Deutsch–Schorr–Waite manner, which needs the boxes to be temporarily mutable. Rule 4 forbids that to a program and says nothing about the runtime, which is what makes the obligation dischargeable rather than a design flaw.

Buffer<T> — contiguous storage, and where an address may exist

The rule above leaves one thing unsayable, and it is correct for every corpus use but one: there is no way to hand out the backing storage of a collection. An array out-parameter needs exactly that. vkEnumeratePhysicalDevices(instance, &count, devices) is called twice — once with no buffer to learn the count, once with an allocation the driver writes into — and the second call needs the address of contiguous memory.

Optional<T> answered the scalar case (Finding 4) and cannot answer this one, because there is no single slot. So this is a named type, and the design below is deliberately scoped: it settles identity, ownership and who may hold an address, and defers element formats, growth, alignment and mapped memory, because those can be added without contradicting anything here.

Five demands, and the fifth is a different type

demandwantsfrom
array out-parameteran addressable extent C writes intoexamples/VulkanTriangle
byte access for stringa UTF-8 sequence read as bytesstrings.md, open
CString conversionbytes plus a terminatorexamples/SqliteBinding
vertex and image datatyped elements, tightly packedVulkan, unwritten
mapped memorya view over storage someone else ownsVulkan, mmap, unwritten

The first four want storage. The fifth wants a view, and collapsing the two into one type is the mistake this section exists to avoid. It would go wrong in three places the language has already taken a position on: a view is a borrow and aliasing.md says a field may not hold a borrow, while an owner can be a field; an owner frees and a view does not, so their tiers differ; and Glfw.release invalidating every Monitor is the same failure as a view outliving its storage, so the validity gap applies to views and not to owners.

So: Buffer<T> owns. Views are a separate thing, and a view is a borrow — see "Views are borrows" below.

The decisions

1. Buffer<T> is not [T], and not a mode of it. [T] is a collection of values: it hands out copies, it is Duplicate, it grows, and it has no addressable interior. Buffer<T> is contiguous storage with an extent. Conversion is explicit in both directions (Buffer.from(xs), buffer.toArray()). The rule above therefore stands unqualified, with no exception carved into it, and Buffer<T> is simply not a collection. The cost is one conversion at the boundary, which is where it belongs.

2. There is no address-producing expression in elp. No .storage(), no .pointer(), no cast. &buffer passed to an elp fn is an ordinary borrow and carries no address; the address appears only in the lowering of an @external call. This is what keeps "collections hold values, not places" true of Buffer<T> as well: its elp face is values-not-places like every other collection, and at(i) returns a copy. The examples/VulkanTriangle draft's .storage() spelling is deleted, the way out was.

3. At an @external boundary, &Buffer<T> lowers to T* — a pointer to the first element, not a {ptr, len, cap} struct. Length travels as its own parameter, as it does in C. Writability needs nothing new: &T at an @external declaration is already conservatively read-write.

4. Capacity is fixed at construction; 0 <= length <= capacity; at(i) traps for i >= length. So no uninitialised element is reachable from elp, by construction rather than by discipline.

5. The only way to get length > 0 is to supply every element. Buffer<T>.filled(n, value), Buffer<T>.from(xs [T]), or append. There is no setLength, no assumeFilled and no Zeroable — and that matters more here than it would in Rust, because aliasing.md makes unsafe an FFI-only concept with no block form, so an assert-initialised operation would have nowhere to live.

6. Therefore an array out-parameter of handles is &Buffer<Optional<T>>. This is the scalar rule at a second arity, not a new mechanism:

export fn vkEnumeratePhysicalDevices(instance VkInstance, count &Optional<int>, devices &Buffer<Optional<VkPhysicalDevice>>) -> int
var gpus = Buffer<Optional<VkPhysicalDevice>>.filled(found, nil)
vkEnumeratePhysicalDevices(instance, &count, &gpus)

Every slot is initialised to nil before the call, the driver overwrites some prefix, and an unwritten slot reads back nil — which is true. It leans on Optional<T> being layout-compatible with T, and that promise was already made for vkCreateInstance(..., instance &Optional<VkInstance>): spending it a second time costs nothing new. It should be written down as a boundary layout guarantee rather than left implied, which is the existing @external struct-layout open item.

This works because a handle has a null niche. For an element type that is a declared C struct there is no niche, and none is needed: filled(n, zeroStruct) satisfies decision 5 directly. Both routes initialise every element, which is the only thing decision 5 asks.

7. Buffer<T> implements Move. Not Duplicate, deliberately, although Duplicate is defensible for an owning allocation and [T] has it. Three reasons: adding a conformance later is additive and removing one is not; [T] already covers "a duplicable sequence"; and Move turns out to be load-bearing for FFI retention below, which was not the reason it was chosen but is the better one. Sendable when T: Sendable.

8. Buffer<T> is imported, not atmospheric. It fails name-resolution.md's criterion — the compiler cannot name it in a diagnostic without help, since no grammar or desugaring produces one. That also disposes of a name collision for free: examples/Buffer declares its own Buffer, a text-editor handle with entirely different semantics, and simply does not import the stdlib one.

9. Buffer<T> conforms to Index and Iterable<T> — the same trapping [] / Optional-returning get table as every other collection, so there is nothing extra to learn.

Views are borrows, and that answers the transient-pointer row

A view is wanted for sub-ranges, for zero-copy bytes out of a string, for mapped memory, and — the case that forced the question — for a parameter of a foreign callback. An audio callback receives float *out: storage the host owns, valid for the duration of the call and not one instruction longer.

That is exactly the third row of aliasing.md's foreign-pointer table, the one recorded as having no tier that fits. It has one now: it is not a value, it is a borrow. A borrow may not be a field, may not be captured by a closure (Finding 3), and dies at the end of the call — which is the transient-pointer contract, obtained from rules decided for other reasons.

Two consequences fall out with no declaration needed. A view is never Sendable, under any T, because it cannot be captured and therefore cannot cross. And a view cannot outlive the callback that received it, because borrows already cannot escape.

The spelling is reserved (Span<T>) and the surface is deferred. What is decided is that it is borrow-shaped rather than a Copy value, because that is the part which would be unfixable later.

Where C may hold an address — the out-of-line principle

Decision 2 says no elp expression produces an address. A C API that retains a pointer — an audio driver, a persistently mapped buffer, io_uring — needs one to exist anyway, so the question is what may be pointed at. The answer is not "whatever C asks for":

C may hold the address of elp memory only where that memory is out-of-line and kept alive by something other than a stack frame.

Two things in elp qualify, and probably nothing else ever will:

  • a Buffer<T>'s elements — the allocation is out-of-line, so moving the Buffer<T> value (ptr/len/cap) does not move the storage. That is a representation promise and is stated here deliberately, because it is what makes retention safe at all.
  • a cell's contents — Confined<T> and Synchronized<T> are refcounted, so the allocation outlives any particular handle.

A bare elp value never qualifies: it is in-line and it moves. So "address of a local" is not a feature elp lacks — it is a thing that cannot be sound here, and this is the principle that says why.

The three boundary forms, and nothing else

spellingC seeskept valid by
&Buffer<T>T* to the elementsthe call
Buffer<T> by valueT* to the elementsownership transferred; the registration reclaims
Opaque<Cell<T>>void* to the cell contentsthe registration's own field

The first two mirror a distinction already decided for handles: sqlite3_close(db Sqlite3) takes its handle by value and sqlite3_step(stmt &Sqlite3Stmt) borrows, and that already means retained versus borrowed for this call. Storage means the same thing one layer down. And because Buffer<T> is Move (decision 7), the by-value form removes it from the caller — so the lifetime hazard is not checked, it is absent. elp cannot race C for an extent it no longer has.

Opaque<T> is a boundary spelling, not a value type. It appears only in @external and @abi signatures; an elp body passes a cell and receives a cell, and the void* exists only in the lowering. Passing a cell as Opaque<T> does not retain it — nothing increments a refcount for C, because C cannot decrement one and every registration would leak. It is a borrow, and the registration's own field is what keeps the cell alive. See aliasing.md for the callback rules and functions.md for @abi(.C).

The table is drawn at the level of how C names a thing, deliberately not at the level of what discipline governs access. That is what lets a new cell kind arrive without touching it: aliasing.md adds Atomic<T> for threads that cannot take a lock, and Opaque<Atomic<int>> works with no change here.

Opaque<T> earns a spelling of its own for one reason: it is the only place in the language where a type is a claim rather than a fact, since C may hand back any void* at all. That parallels an @external type's declared tier being the one place a user gets stdlib's privilege.

Open within contiguous storage

  • Element reinterpretation — buffer.view<Vertex>(), planar versus packed pixels, endianness, stride. Kept deliberately out of Buffer<T>'s identity so there is no format parameter to be stuck with. It needs a layout answer, which is already open.
  • Growth beyond capacity. Safe to add later: no address outlives a single external call except by the retention forms above, and those move the buffer out of elp's hands entirely. The one hazard is a C library that calls back into elp and appends during a retained call.
  • Alignment and over-alignment. For SIMD and GPU it is a constructor and additive. Not additive for a lock-free ring buffer, whose producer and consumer indices must sit on separate cache lines or every write invalidates the other core's copy — so a stdlib Ring<T> is the first consumer that cannot wait, and field-level alignment is a different question from buffer over-alignment.
  • Mapped and adopted storage. It wants Scoped release, which an ordinary heap buffer must not have — which is evidence it is a different type, not another constructor on this one.
  • string byte access. s.bytes() -> Buffer<uint8> copies, and that is correct but not free; the zero-copy form arrives with views. Still gated on the undesigned numeric tower.
  • symbol = on @external, and it now has two customers rather than one. vkEnumeratePhysicalDevices(instance, &count, null) passes NULL where &Buffer<...> is expected and Optional<&T> is barred, so the count-then-fill call is genuinely two operations over one C symbol. Rule 8 above found the second customer: fluid_synth_write_s16's interleaved and planar modes are two operations over one symbol too, and declaring them separately is what lets exclusivity hold unconditionally rather than needing an exception at the boundary. Two unrelated probes, one mechanism, and the second one makes it load-bearing for a rule rather than for ergonomics.
  • &var T as a non-receiver parameter. Ratified, in Finding 4's third amendment above, and the leaning recorded here was half wrong: the spelling does have to exist, but the call sites were right and Finding 4's call-site rule is what gives way. &var doc stays &var doc.