Wado

WEP: Writable References — A Borrow That Is Not Copied, and a Shared Cell

Context

A &T is meant to be a read-only view. It is not one when T holds a &mut F: a copy of the struct carries the &mut F with it, and so does a copy of the field, so &&mut F yields a &mut F. A function handed &T can write F.

The copy is not a bug in one rule. A &mut T is an ordinary copyable value that writes wherever it is reached from, which is what Go's *T is and not what Rust's &mut T is. Code relies on it in two different ways:

Role Example What it needs
A borrow a parameter; out: &mut String in a parser write access handed down, for a while
A shared cell cell: &mut Cell<T> in Rill's Signal<T> one object, many copies, written by &self

Signal<T> documents that a copy is the same signal, and set(&self) writes through the field. It builds the cell as a reference to a local of the function that returns it. That is a heap cell spelled as a borrow.

What other languages do

Languages with value semantics take one of three positions on a writable reference held inside a value.

Position Languages Rule
It cannot be held Swift, Hylo, Move A copyable value has no writable reference among its fields
It weakens along the path Rust, Pony, D Reached through a read-only view, it reads but does not write
It is shallow C++, C#, Zig, Go A read-only view of the holder promises nothing about what the holder points to

Only D and Pony get the transitive rule without a borrow checker, and both do it by making the permission part of the type on every path. No language found closes the escapes one at a time.

Decision

A writable reference is a borrow, and shared mutable state has a type of its own. The two roles &mut T plays today get one spelling each.

&mut T is affine

A &mut T moves and is never copied, and so is every type holding one. The existing rule that no affine value moves out of a reference then refuses &&mut T to &mut T, whether the copy is of the reference or of a struct around it.

Generic code needs nothing new. &mut F instantiates only a type parameter declared affine, so a body that copies a T out of a &List<T> never sees one. A &mut F handed to an unmarked parameter lends &F where &F meets its bounds, since the body may do no more with a &mut F than with a &F; buf.push_str(other) keeps working for an other: &mut String.

Three consequences follow, each stated in the specification:

This is not exclusivity. Two &mut x of one place stay legal, except two scoped ones in one call (below). The rule stops a read-only view from yielding write access, and says nothing about how many writers a place has.

A place writes only through writable steps

A place reached through a dereference is writable only when every dereference on the way is of a &mut. Through rr: &&mut T, an assignment to rr.x, a &mut **rr and a &mut self call are errors. Affinity does not cover these, since none of them copies. The dereference of a shared cell starts the path again: the place a cell holds is writable whatever reached the cell.

The rule for references is in force, stated in Variable Mutability. What it leaves is the copy: *h is a value of its own, and the &mut it holds writes.

A &mut is reborrowed where one is expected

It follows from affinity: without it, passing a &mut parameter to two calls in a row would be a use after a move. Where the expected type is &mut T, a &mut T reached through a writable place is reborrowed, and the original stays usable. There are no lifetimes, so the reborrow is a second reference to the same referent.

Only an expected type reborrows. let b = a; moves a, and let b: &mut T = a; reborrows it, as in Rust. Both are of a T that is RefMut: a scoped &mut binds to no variable. A return's value states the function's return type, so it reborrows, as Rust's does, and so do a literal's elements and a by-value receiver. A scrutinee, a destructuring let's value and a for's iterable reborrow as well, since a pattern or a loop reaches through the &mut rather than taking it. A branch's value reborrows where its if or match does, as Rust's coercion sites reach into a branch.

A shared cell is a reference

A value that is one object under every copy, and that a & may write, is a shared cell. A cell is a reference: a copy of it is the same cell, and it dereferences wherever a &mut does. &T is read-only as deep as the first cell, and promises nothing past it, as &R already promises nothing about a resource (Components).

Signal<T> holds a cell. A parser's out: &mut String stays a borrow, and the struct holding it becomes affine.

The cell is Shared<T>

Shared<T> is a prelude type the compiler knows, declared without a definition as Array<T> is: pub type Shared<T>;.

It is a type and not a struct, because a struct is a value: its copy is deep, an assignment to it writes field by field, and Eq, Serialize and the rest derive from its fields. Each would need an exception. A type with no definition also keeps the representation a &mut T has today, the object itself for an in-place T and a heap cell for one replaced on assignment, where a struct would add an object in front of every in-place T.

It is a name and not a keyword or a sigil. shared is already a variable name across the corpus, a keyword would need an expression form and its precedence, and every other compiler-known type (List<T>, Option<T>, String) is a name. A &shared x beside &mut x would also read as a reference to the place x, where Shared::new(x) moves the value into a cell of its own.

A closure stays copyable, and &T stops at one

A closure captures variables, and a variable two copies of a closure share is a cell in all but name. A fn closure may also capture a Shared<T> and write it. So what &T promises stops at a closure as it stops at a cell, whichever of fn and fn mut it is, and making fn mut affine would restore nothing. fn mut keeps its meaning: the closure writes a variable it captured, and calling it needs a mut root.

A closure that captures a &mut refers into an affine local, so the rule that already holds such a closure inside the local's scope (Affine Types) holds this one. That covers a binding a pattern scopes too: a closure cannot carry it past the arm that stores it back.

& of a type replaced on assignment is its value

A primitive, enum, flags, copyable variant, fn or & reference has no storage a reference could share. A &P of one is a copy of the value, wherever it is taken from: a local, a field or an element. An assignment to the place afterwards does not reach it, and for a variant neither does a write to its payload.

An affine value is never copied, a &mut and an affine variant included, so a & of one names its place and sees what is written there.

Two & of one place of such a type are two copies, so ref_eq of them is unspecified, a closure's included. The guarantee that two references to one place are ref_eq holds for a type written in place and for an affine value.

Today a &i32 of a local sees a later assignment and one of a field does not. Making every &P see it is not open: Wasm GC has no pointer into a struct or an array, so it would take a heap cell for every primitive field and element.

A program Rust accepts cannot tell the difference, since Rust forbids the assignment while the & is live. &T still shares the storage of a struct, List, String or tuple, so a generic body that holds a &T across an assignment to its place answers by the kind of T.

A closure's capture is not a &P. A closure captures the variable, and reads what the variable holds when it runs, as it does today.

A write that leaves a &P behind warns

An assignment to a place while a &P taken from it is still read is almost always a mistake under the rule above. The lint stale_reference warns at the read, naming the assignment, and allow waives it. It fires where the compiler is certain: the reference, the assignment and the later read are in one body, and the type is known to be replaced on assignment. A body generic over the type is checked per instance, and the warning names the type argument that made the reference a copy: the body reads right for a struct and stale for an i32, and nothing in its source says so. It stays silent across a call. The warning is best effort and promises to find nothing, so no program is refused over it.

&mut of a type replaced on assignment lasts for a scope

A &mut P of such a type is taken only where the syntax fixes the point its value goes back to the place:

The loop walks by index a Sequence that implements IndexValue<i32> and IndexAssign<i32>: a turn reads the element, binds it, and assigns it back. List and Array are such, and so is a user collection implementing the three. A map's values are not walked this way: its index is a key, and a walk by key would look each one up twice. An IntoIterator for the &mut itself comes first, as for any operand, so elements written in place are walked as they are today.

Binding one to a variable, storing one in a value and returning one are errors, and a shared cell is what such code wants. A destructuring let and a let … else bind variables with no arm to end, so such a binding under a &mut scrutinee is an error too. The rule is by type alone: a local, a field and an element take the same &mut, so a local no longer becomes a heap cell for a reference to keep.

A generic body that only uses a p: &mut T takes every T. One that stores or returns a &mut T needs T: RefMut, as IndexRefMut::Output already does. A generic body's scope stores back only for an instance replaced on assignment: an instance written in place holds the place's own object, and copying it over itself would cost a whole list per call.

A guard only tests its arm, so writing a binding the arm holds there is an error, as Rust forbids it: a guard that fails would leave the next arm matching the value from before the write.

A variant falls under this rule whole, and is no case of its own. Its payload of an in-place type is reached through a pattern, which is the one thing a variant adds to a primitive. Giving every variant slot an object of its own, as an affine variant has, would make it an aggregate like a struct and need no rule at all. It was declined for its cost: Option<String> stops being a nullable reference, and every variant field and element gains an allocation.

The line between the two kinds of &mut is RefMut, which the specification already draws. A type with an object that is its place can be borrowed, and one without lasts for a scope:

The type &mut of it
RefMut: a struct, a tuple, List, String, i128, any affine value an affine borrow of the place
not RefMut: a primitive, enum, flags, a copyable variant, fn, & scoped, as this section states

A Shared<T> is on the second row. An assignment to a cell replaces the cell, as one to a & replaces the reference, and what the cell holds is written through *c with no &mut.

An affine variant stays on the first row. A field, an element or a payload holds it in an object of its own (Affine Types), so &mut of one names a place and is stored and returned. Giving it the scoped rule would move the value out for the scope where a copyable one is copied, and leave the place empty meanwhile. Another route would then read a moved place, which is unspecified, where it reads a stale value of a copyable one. Swift moves in and out this way and has exclusivity to forbid the other route. The object costs an allocation only where a variant wraps a resource.

A function cannot hand such a &mut back, and nothing is added to make one. The scoped forms work because the place is written where it is used: the compiler reads map[k], and stores to map[k] after. A function's result is a value with no place attached. An index and a field cover every container, on IndexValue and IndexAssign, which List, HashMap and TreeMap implement for every element. IndexRefMut keeps its Output: RefMut, and no other standard library function returns a &mut. A named accessor is written one of three ways: return the in-place object that holds the place, move the value out and back, or take a closure the accessor calls between its read and its store. An accessor that yields a scoped place, as Swift's _modify and Hylo's subscripts do, waits for a need the three do not meet.

A scope that stores back does so at every exit, whether or not its binding was written: its end, a return, a break, a continue and a ?. A trap is no exit. It does not unwind, so it stores nothing back, as it runs no drops (Affine Types). A handler always resumes or diverges, so an operation dispatched inside a scope adds no exit of its own.

A write to the place by another route inside the scope is therefore overwritten. Where clear assigns null to self.count, if let Some(n) = &mut self.count { self.clear(); *n += 1 } leaves Some. A binding of an in-place type stores nothing back, so none of this reaches it.

Swift splits the same way. An overlap it can prove is a compile error, and the rest is checked at run time, which Wado does not do. Ada leaves the overlap unspecified.

Declined

Roadmap

The corpus is rewritten to the rules, whatever it takes: no rule above bends to spare a call site. Each step leaves the tree building and its tests passing.

Two items land with the step whose rule they serve:

Known gaps

References