Skip to content
Weaverv0.5.0

Memory model, revised

A revision of SPEC 6 (memory model) and 7 (resources), started from what the libraries written since showed: regex, weft/json, weft/compress. Each first implementation had to be reworked to reach its speed or its memory, by hand-made ownership choreography or unsafe, which points at choices of the model rather than at bugs.

Status: draft. Agreed as the direction: sections 1 and 2; the regimes per part (3); explicit copies, and the binding that borrows what it gave up to an object (3); what a field holds, a borrow only in a local type (3); the free at the end of the owner’s scope (5); counting only for what is declared shared, frozen parts included, shared by count without a copy (3, 5); weak references to shared values, with a weak count (7); return gives up and : yield T lends, its body returning with return; a field is exchanged, never taken; shareable resources, whose release cannot fail (9); arena objects, identity without counting for a graph one owner holds, refs as indices, a generation only where nodes are removed (7); a shared value immutable by default, modifiable on one task through mut methods behind an exclusivity flag, or across tasks through methods that synchronize themselves (9); sharing declared on the place, field, binding or parameter, shared T frozen, shared mut T modifiable on one task (9); val and var for the label, mut on the type for the content (3); correctness from signatures only, inferred summaries for optimization inside a package (9); lifetimes named by places, from and local type (9); bounds proved in common forms, checked otherwise (9); frees of a caught panic through unwind tables (6); a mut borrow in two phases (9); a migration in phases, the source made valid under both models before the switch (11). The rest is analysis. Nothing here changes the compiler yet.

The stakes:

  • Allocate and free efficiently: at the right moment, neither too early nor long after the last use.
  • No race on memory between tasks.
  • No access to freed memory.
  • No needless copy, above all of large values: neither when reading nor passing them, nor when modifying them in place.

And the dimensions the work so far showed to belong with them:

  • Spatial safety: no access out of bounds, no read of memory not yet written. The bounds checks cost regex and inflate most.
  • No mutable aliasing without tasks either: a value never changes “at a distance”, an iteration is never invalidated by the collection it walks.
  • No leak, no retention: cycles freed; a small part of a block does not keep the whole block alive.
  • Resources other than memory: files, sockets, locks, freed at a precise point, the error of their release received (SPEC principle 4).
  • Bounded memory: a stream processed in constant memory whatever its size; exhaustion has a defined behaviour.
  • A caught panic leaves memory and resources consistent, or says what it abandons.
  • Sharing without copying between tasks: a large value read by several tasks, without a copy and without an atomic count per access.
  • The unsafe and C boundary: a buffer handed to C neither moves nor dies during the call; a library encloses its unsafe behind a safe API.
  • Predictable, visible costs: no pause, deterministic release, every cost shown where it is paid (SPEC principle 5).
  1. As much as possible is guaranteed at compile time. What the compiler proves costs nothing when the program runs.
  2. The code states an intent, never a representation. It reads, modifies, gives up, defers, keeps access to a part, shares between tasks. Whether a value lives on the stack or the heap, is counted or unique, atomic or not, the compiler decides. No family of pointer types to choose from, as Rust’s Box, Rc, Arc, Cell, RefCell, Mutex and lifetimes: each answers a question the compiler should answer itself.
  3. What the compiler cannot prove becomes a check when the program runs, visible and refusable. The editor shows it; an assertion, as @assert(nocopy) does today, turns it into a compile error. No cost is hidden, and a codec can require to be entirely proven.

A regime says how a part of a value lives: where it is, when it is freed, what a write costs. Today a whole type has one regime; a value is in fact made of parts whose regimes differ. The compiler gives each part its regime from what the code does with it, but for one: sharing is declared.

Regime What it holds Freed Write Decided
inline scalars, records of scalars, tuples, fixed arrays end of scope in place compile time
unique a heap block with one owner: every ordinary value at the end of its owner’s scope in place, without a check compile time
borrowed access to a value another owns never: it does not own refused: copy it first, x.copy() compile time
linear a resource at a precise point: using, consumption, dispose in place compile time
shared a value in a place declared shared, field, binding or parameter, held by several owners; frozen without mut, never modified in place at the last release per the place and the type’s methods (section 9); a frozen one is replaced, not written at run time: the only counted one
region a node created in an arena object (section 7) with the object, all at once in place, under the object’s exclusivity compile time

Counting exists only for what is declared shared. On one thread, scopes nest like Russian dolls: a caller’s scope always encloses its callee’s, a block’s encloses its inner blocks’. A value designated from an inner scope therefore always outlives that designation, and needs no count. Counting is needed only where lifetimes do not nest: values held by several tasks, and, on one thread, one value held by several entries of a container, which leave it in an order the data decides; and the parts several values hold without modifying them, frozen (below). These are the cases where the developer declares the value shared; the compiler then chooses whether its count is atomic, as it does today for values that cross tasks.

  • Unique is the regime of every ordinary value, and what is missing today: a buffer that only one value holds pays a count and a check before each write (section 8, F1).
  • Borrowed replaces the view and copy on write. An access to a value another owns, tied to the borrower’s scope as a projection subscript … yield is today, never written; it neither keeps its owner alive nor copies it (F2, F3), and it does not modify it. It is what Rust needs lifetimes for; here the nesting of scopes is the proof.
  • Shared is explicit, so that its cost is chosen: a cache, a value several tasks read, a node several others designate.

A value is an assembly of parts of different regimes:

ZipArchive<R>
├── src: R linear: one owner, freed at a precise point
├── list: ZipEntry[] unique
└── comment: String unique

Today src makes the whole archive linear: it can neither be copied to read its list, nor lend src for a moment; zip had to add ReaderAt.duplicate(). Linearity is a property of the field, applied to the whole value. Per part:

  • the ordinary parts of a value that holds a resource are read, copied and returned freely;
  • the resource part can be taken out, or exchanged for another value, each marked at the call, the rest staying intact;
  • the container’s own dispose is kept for the containers that need one: a writer that writes its end.

Two questions, two words, each about one thing:

  • The label, val or var: can the binding be assigned another value?
  • The content, mut on the type: can the value be modified in place, its elements added, its fields assigned, its mut methods called?
val m = mut Map<String, Int>() // fixed label, content modified: m.set("a", 1)
var n = 0 // label reassigned: n += 1
val p: mut Point = origin() // p.x = 3 modifies the content
var q = Point{x: 0, y: 0} // q = other is accepted; q.x = 3 is refused
Declaration Reassign Modify the content
val x: T no no
var x: T yes no
val x: mut T no yes
var x: mut T yes yes
  • mut is deep through what the value owns: a mut Inflate modifies its out buffer, a part it owns. It stops where identity begins: a field shared Map<K, V> stays frozen in a mut object, a field shared mut Map<K, V> is modifiable through any holder (section 9).
  • Written on the type: entries: mut Map<…> on a field or a parameter’s annotation; with an inferred type, on the value, mut Map<K, V>(), mut [1, 2], as Kotlin’s mutableMapOf.
  • A scalar has no content apart from its value: n += 1 reassigns, and takes var.
  • A mut parameter receives a mut place from its caller, &xs; a method taking mut self is called on a mut value. It modifies the content, and never replaces it (below).
  • Moving may add mut: val b: mut Bytes = a, with a not used afterwards, is a move, and no one else sees the content. A borrow never becomes mut, that is the explicit copy below; a value shared never becomes shared mut (section 9).
  • A closure that modifies a captured binding receives it as a parameter would, [mut items]: its content, items.push(x). The lambda is written in the owner’s own body, where the binding is visible: a var captured [var total] may be reassigned, total += x, which a parameter may not.

A parameter is a label of the callee on a value of the caller. A mut parameter lets the callee modify the value’s content; nothing lets it replace the value. p = …, p += …, self = … are refused; p.f = …, p[i] = …, p.push(x), a mut method of p, are modifications of the content. Replacing is returning: the callee gives a new value, and the caller stores it where it decides.

fn grow(xs: mut Int[], n: Int) { // content: elements added
for i in 0..n { xs.push(i) }
}
fn next(id: Int): Int = id + 1 // a scalar: taken, returned
fn close(sink self): State = .Closed // in `impl State`: a variant, returned
grow(&items, 3) // `&`: lent for modification, as in Rust
nextId = next(nextId)
state = state.close()
  • Why. Where a parameter may be replaced, C#’s ref, C++’s T*&, out parameters, the callee moves what the caller’s label designates, and what read the old value no longer agrees with it. With values, nobody else holds the old one, but a replacement in a callee still reads as the caller’s variable changing behind its back: self = Point{…} in a method is hard to follow as it is written. Modifying a content keeps the value the caller lent; a replacement goes through the caller’s own assignment.
  • Nothing is lost. With sink and unique values, xs = sorted(xs) moves the array there and back, without a copy. An out parameter becomes a result, a tuple or an option; a counter a returned value, or a field of a state that is modified; swap(&a, &b), (a, b) = (b, a).
  • A scalar, or an enum without data, has no content apart from its value: a mut parameter of such a type is refused, there is nothing to modify. An enum’s payload is modified in place through a match that binds it mut; its variant changes by a return.
  • A record’s fields are its content: self.x = 3 in a mut self method is a modification. Assigning all of them is too, which self = Point{…} would only abbreviate: the rule is one of reading, the callee alters what it is lent, it does not substitute it.
  • Exchanging a part stays: replace(&self.buf, with: Bytes.new()) returns the old value and leaves the new one, a primitive of core, the one replacement through a parameter, which its name says.
  • inout went: mut T and mut self replaced it, &x stays at the call, and inout is refused with the new spelling. Measured before, 1 of the 1,743 inout self and about 35 of the 534 inout parameters replaced their value: out parameters, counters, and += on arrays, a modification since, as on strings and bytes. A guarded value without content, a Mutex<Int>, changes by update(c => c + 1), which returns the new value for the lock to store.

What a content without mut gives the compiler. Its size is fixed at creation and nothing changes it while it lives:

  • a literal known at compile time, val table = [1, 2, 4, 8], goes into the program’s read-only data: no allocation, no free; moving it into a mut place copies it there;
  • a value that does not leave its scope, neither given up, stored nor returned, goes on the stack, its size known at creation, below a threshold, the stacks of tasks being small;
  • a heap block is allocated at its exact size, without spare capacity;
  • its length and elements do not change during a loop or a call: bounds proved more often (section 9), loads hoisted, LLVM’s noalias and readonly on its borrows;
  • several tasks of one scope read it through borrows, without copy or count.

The keywords follow: let becomes val, as in meta val, val ${name} in a quotation, val … else and task val; var and thread var stay; today’s global shared var, read through snapshots, becomes a value of the sync type Shared<T> of weaver.task. The editor and the LSP colour var and mut apart, since val and var differ by one letter.

Today, var a = data then a[0] = 0 reads as a modification in place; with copy on write it was a copy of the whole block, unseen. A copy of a value that holds a heap part is therefore always written, data.copy(), and modifying what one only borrows is an error:

fn edit(data: Bytes): Bytes {
val a: mut Bytes = data // a borrows data
a[0] = 0 // error: `a` borrows `data`, which it cannot modify;
// copy it, `mut data.copy()`, or modify `data` itself, `data: mut Bytes`
return a
}
  • An assignment moves or borrows, never copies. val b = a moves when a is not used afterwards, and b owns the value, which it may modify; otherwise b borrows a, and reads it. Adding a later read of a turns a move into a borrow, and a write to b into an error: never into a hidden copy.

  • Giving a value up to a function, while still using it, is an error, for the same reason: a sink argument, a return of a borrowed parameter; the callee may free it in its own scope. It asks for x.copy(), or for x to be declared shared.

  • Giving a value up to an object one still holds makes its binding a borrow of it, without anything written. After cache["a"] = blob, or self.data = blob, blob reads the value now in cache["a"], as long as the receiver stays in the caller’s hands (a local, self, a mut parameter) and is not modified: the first modification of the receiver, an insertion, a removal, giving it up or returning it, ends the borrow, the compiler not knowing whether it touches that entry. A later use is an error that names the line that ended it:

    cache["a"] = blob // blob given up to cache: blob borrows cache["a"]
    log(blob.len()) // a read: allowed
    cache["b"] = other // cache modified: the borrow ends here
    log(blob.len()) // error: `blob` was given to `cache`, modified since (line 3)

    The borrow designates the value’s heap block, which moving the value into the container does not move: a table that reorganizes itself leaves it valid. A value without a heap part is copied anyway.

  • Storing a part into a frozen place shares it, rather than copying it: a count, when no holder modifies it in place afterwards (below, frozen values).

  • To modify the original, a mut parameter: &data, the one modification in place, marked at the call (SPEC 6.2); it modifies the content, and never replaces it.

  • Values without a heap part keep their implicit copy: scalars, records of scalars, tuples and fixed arrays of them. Copying them costs what a move costs; nothing is shared, nothing is hidden.

  • A value with a resource part cannot be copied: its linear part has one owner. copy() exists for the others, written by the compiler, as deep as their heap parts go.

This converges with Rust’s split between Copy, implicit for plain data, and Clone, explicit for the rest; without lifetimes, and without the borrow having to be written, since the compiler infers it from what is done with the value.

Storing a value in an object moves its scope to the object’s: the value lives as long as whoever holds the object. An object’s field therefore holds only:

  • a value it owns: given up to it, moved, or copied, x.copy(); freed with the object;
  • a shared value: declared shared, counted, freed at its last release; frozen if not mut, as the parts a tree takes from another (below);
  • a weak reference to a shared value: it designates without owning, and its access says whether the target still exists, T? (section 7);
  • a ref to a node of the same arena object, in that object or one of its nodes: valid as long as the object lives (section 7);
  • a borrow, in a local type only: a type that carries a lifetime, whose values stay attached to a scope (section 9).

Never a borrow in an ordinary type. An ordinary object travels, is returned and stored for a long time; a borrow in it would be tied to no scope, and would need free lifetime variables and a checker following borrows through the heap, as Rust’s. A borrow lives in a binding, a parameter, the result of a projection, or a local type, and the nesting of scopes stays the whole proof.

What it implies:

  • One value in several objects is a copy in each, a frozen or shared value, or one owner and weak references in the others. Storing it a second time without one of these is an error: the binding only borrows it from the first object, and a borrow is not given up.
  • Access to a part, beyond a call, the case of a reader’s window or a parser’s pieces (F2), is not an object holding a borrow: it is a projection, fn chunk(mut self): yield Bytes, whose result the caller reads or copies in its own scope, and cannot store (section 9).

Measured on the compiler (section 11), the rules above meet their limit. Code that builds values out of parts of others it borrows, a compiler, a tree transformer, a JSON mapper, would copy at each store: 1,307 places in the compiler, each a string or an array reallocated, where copy on write increments a count today. Most of these parts are never modified again, by anyone: a name taken from one node into another.

A part no holder modifies is frozen, and a frozen part is shared by count, never copied.

  • A field no code writes in place is frozen, without anything written. The compiler sees it in the package that declares the type: no write goes beneath it, a.f.push(x), a.f[i] = v, &a.f; replacing it, node.name = other, is not such a write. The elements of arrays are frozen likewise, by their type: T[]’s elements are, when no code writes in place an element of type T. Measured on the compiler, 1,237 of the 1,361 stores into a field or an element go to such a place (section 11). Another package that writes in place a field frozen in its declaring package is told to replace it.
  • A value taken out of its place carries its position. m.remove(k), xs.pop(), replace(&place, with: v): the binding that receives the value, val t = mut m.remove(k).unwrap(), writes in place beneath it as if it wrote the place itself, since another holder may still share the value by count. Taking an entry out, modifying it and putting it back is writing that position in place. A generic body’s position, elem *, stands for every instance’s and is left out: a container’s own mut subscript takes its value out that way, its callers’ writes counting at their positions.
  • A lambda holds what it captures as val does. A capture by copy, val k = () => xs.len(), shares xs’s value by count until the lambda is released, at the end of its block, whatever its last call: a write in place to xs before then is refused, the lambda capturing a copy taken before it, val snap = xs.copy(), or living in a block that ends first.
  • A pattern’s binding holds a part as val does. if m[k] is Some(b), val Some(b) = xs.get(0) else { … }: a write in place to the place while the binding serves asks for .copy(), written on the matched value. shared T without mut freezes a place explicitly, a binding, a parameter, or a field the inference would not freeze.
  • Storing into a frozen place shares. It costs a count, not a copy, when the value stored is frozen itself, or when its owner no longer modifies it in place, which the compiler sees in the owner’s remaining scope. Otherwise the store asks for .copy().
  • Reading a frozen place gives a frozen value. A pattern’s binding over a frozen part, an element iterated, is frozen in turn, and stored elsewhere by count: what the 480 bindings of the measure become.
  • A parameter the callee keeps says so. sink T: the callee owns it, unique, and may modify it; the caller moves it, or copies it, written. shared T: the callee keeps a frozen share; the caller’s value is shared by count, and a later modification of it in place by the caller asks for .copy() at the call.
  • No write is ever checked. A unique place never receives a share: a store into it moves or copies. A frozen place is never written in place. The uniqueness check of copy on write does not come back (F1).
  • Counting stays with sharing. Frozen places are shared places; their counts are not atomic on one task, atomic for what crosses tasks.

Only the shares of values that are modified stay declared, shared mut T (section 9): freezing is the compiler’s finding, as principle 2 wants. What remains for wv migrate to write is the exception: a store of a part still served elsewhere into a field or an element written in place, 124 in the compiler and 1 in std, takes .copy(), or shared T on the field; a parameter kept becomes shared T, or sink T if the callee modifies what it keeps. A frozen part costs a count per store and per release, as copy on write does today, but only there: the buffers of a decoder, unique, keep their unchecked writes.

Onto the heap goes what the compiler cannot size or date: the contents of String, Bytes, T[], Map; the field that closes a cycle in a recursive enum; a closure’s environment that escapes; a Lazy, a shared value, an actor; a block that leaves an arena, copied out.

Off the heap, today: every heap block is counted.

allocation ─► count = 1 ──logical copy──► count = n
│ ▲ │
│ └── write while n > 1: the whole block copied
│
├─ view data[a..b]: count + 1, the whole block stays alive
│
└─ last release ─► freed
(when depends on who lets go last:
known only at run time)

Off the heap, proposed: an ordinary block has one owner, and its free a place in the text.

allocation ─► owned by a binding ──given up──► owned by the receiver
│ (sink, return, container)
├─ borrowed by inner scopes: no count, no retention
│
├─ assigned: moved, or borrowed; copied only where
│ the text says `.copy()`
│
└─ end of the owner's scope ─► freed
declared shared ─► counted; freed at the last release

As in C++, the question that matters is where each free is placed:

Approach Who places the free Where
C the programmer where they think it is over: leaks, double frees, use after free
C++ (RAII) the compiler, at the end of the owner’s scope; unique_ptr moves the free with ownership, shared_ptr defers it to the last release static, but for shared_ptr; nothing checks that a raw reference does not outlive its target
Rust as C++, checked: end of scope or move; borrows proven shorter than the owner static, but for Rc and Arc
Swift, Weaver today the last release dynamic, the compiler removing the counts it finds useless
Garbage collection the collector later
Weaver, proposed the compiler, at the end of the owner’s scope; the last release for what is declared shared static, but for shared

The moment: the end of the owner’s scope. A unique part is freed when its owner’s scope ends, or goes with its owner when given up (sink, a return, a move into a container), as in C++ and Rust: the moment reads in the text, and does not change when a read is added further down. Freeing right after the last use, as Swift does, frees earlier, but moves the free whenever a use is added or removed, and makes the cost of a line depend on lines below it. A scope ended earlier, a block, frees earlier on purpose.

Moving is not freeing. Whether an assignment is a move or a borrow depends on whether the source is used afterwards: val a = mut data moves the block to a if data is not read again, and a may then modify it. That decision reads the last use; the free of the final owner stays at the end of its scope. The last use decides who owns, the scope decides when the owner frees.

What each situation becomes:

  1. An assignment. val b = a: if a is not used afterwards, a move; otherwise a borrow, since a’s scope encloses b’s or a outlives the reads, and b cannot modify it. A copy is written, a.copy(), and its free is that of a new owner. No count, and no hidden copy.
  2. A path that depends on a condition. Ownership leaves on one branch and not the other: a flag on the stack, as Rust’s drop flags, keeps the free at a fixed point, only its firing conditional.
  3. A container. Its elements are its own: freed by its free, as a vector’s destructor frees them, or given up when removed.
  4. One value in several entries. Storing a value into a second entry, or a second container, needs x.copy(): two values. To keep one, the value is declared shared, and counted.
  5. Identity and cycles. A node several designate has no one owner: it is shared, its back edges weak (section 7).
  6. Crossing tasks. A value given up to a task, sink, keeps a static free; a value several tasks hold is declared shared, and its count is atomic.

Only cases 4 to 6 count, and only when the code says so.

6. Placing the frees: an algorithm, case by case

Section titled “6. Placing the frees: an algorithm, case by case”

A sketch of the pass that places the frees, run on each function once its code is lowered; then each situation as a short program and the sequence of its ownership. Sketch, not implementation: it shows where a free lands, and that no copy is ever placed by it.

for each function f:
for each owner o in f // a binding, a temporary, a parameter given as sink,
// whose value holds a heap part
if o's value is declared shared:
release(o) at each end of its scope // freed at the last release
continue
if o is assigned from p: // `val o = p`, never a copy
if p is not used afterwards → move: o owns p's block
else → borrow: o owns nothing, frees nothing;
a write to o is a compile error
if o is p.copy() → o owns a new block, written in the text
exits(o) = the ends of o's scope, and the points where o is given up:
`sink` argument, `return`, store into a field or a container,
capture by a closure that escapes
if o is given up on every path → no free in f: the receiver owns it
if o is given up on no path → free(o) at each end of its scope
if o is given up on some paths → a flag on the stack, set where it is
given up; at each end of its scope:
if !given(o) { free(o) }

The frees at the end of a scope run in the reverse order of the bindings, as C++ destroys; a linear part is disposed of there, its error returned or handled (SPEC 7.3).

fn longest(path: String): Int ! IoError {
val text = Fs.readText(path)! // allocation
val lines = text.split("\n") // allocation
return lines.map(l => l.byteLen()).max() ?? 0
} // free(lines), free(text), in that order
sequenceDiagram
  participant F as longest
  participant H as heap
  F->>H: allocate text
  F->>H: allocate lines
  Note over F: reads only
  F->>H: free lines (end of scope)
  F->>H: free text (end of scope)
fn save(sink log: Bytes) ! IoError { Fs.write("out.log", log)! } // free(log) here
fn run() ! IoError {
val log = mut Bytes.new() // allocation
log.extend(header())
save(log)! // given up: no free in run
}
sequenceDiagram
  participant R as run
  participant S as save
  participant H as heap
  R->>H: allocate log
  R->>S: sink log (ownership moves)
  Note over R: log is gone, nothing to free
  S->>H: free log (end of save's scope)

3. An assignment: move or borrow; a copy is written

Section titled “3. An assignment: move or borrow; a copy is written”
fn report(data: Bytes) {
val view = data // data used afterwards? no matter: view only reads, a borrow
print(view.len())
} // nothing freed for view
fn edit(data: Bytes): Bytes {
val a = mut data.copy() // the copy, written: a owns a new block
a[0] = 0
return a // a given up: no free in edit
}
fn reuse(sink data: Bytes): Bytes {
val a = mut data // data not used afterwards: a move, nothing copied
a[0] = 0 // a owns the block: modified in place
return a
}
sequenceDiagram
  participant D as data (caller's)
  participant A as view / a
  participant H as heap
  Note over D,A: report, view only reads
  A-->>D: borrow: no count, no copy
  Note over A: view's scope ends inside data's: nothing to free
  Note over D,A: edit, data.copy() written
  A->>H: allocate and copy, where the text says so
  A->>H: a returned: the caller frees it at the end of its scope
  Note over D,A: reuse, data not used afterwards
  D->>A: move: the block changes owner, nothing copied

Writing to a in edit without .copy() is a compile error, not a copy.

fn route(sink msg: Bytes, urgent: Bool) {
if urgent {
send(msg) // given up on this path
}
log("routed")
} // free(msg) only if it was not given up
sequenceDiagram
  participant R as route
  participant S as send
  participant H as heap
  Note over R: given(msg) = false, a stack flag
  alt urgent
    R->>S: sink msg
    Note over R: given(msg) = true
    S->>H: free msg (end of send's scope)
  else not urgent
    Note over R: msg stays
  end
  R->>H: end of scope: if !given(msg) free msg

5. A container: its free frees its elements

Section titled “5. A container: its free frees its elements”
fn names(): String[] {
val out: mut String[] = [] // allocation
out.push(read()) // the string moves into out: no free here
out.push(read())
return out // out given up: no free in names
}
sequenceDiagram
  participant N as names
  participant C as caller
  participant H as heap
  N->>H: allocate out
  N->>H: allocate s1, s2 (read)
  Note over N: push, s1 and s2 owned by out
  N->>C: return out (ownership moves)
  C->>H: end of caller's scope: free s1, s2, then out

6. One value in several entries: a written copy, or shared

Section titled “6. One value in several entries: a written copy, or shared”
val blob = load() // 50 MB
cache["a"] = blob.copy() // blob still used below: the copy is written
cache["b"] = blob // last use: blob moves into the entry
val blob: shared Bytes = load() // declared shared: counted, not copied
cache["a"] = blob // count 2
cache["b"] = blob // count 3
cache.remove("a") // count 2
// freed when the last entry or binding lets go
sequenceDiagram
  participant B as blob
  participant C as cache
  participant H as heap
  Note over B,C: ordinary value
  B->>C: entry "a": blob.copy(), written
  B->>C: entry "b": move, blob not used afterwards
  Note over C: two values, each freed with its entry
  Note over B,C: declared shared
  B->>H: count + 1, entry "a"
  B->>H: count + 1, entry "b"
  C->>H: remove "a": count - 1
  C->>H: last release: free blob

Sharing is declared on the place, here a binding; shared without mut freezes the value (section 9).

7. Identity: a shared node, a weak back edge

Section titled “7. Identity: a shared node, a weak back edge”
type Node = { name: String, children: (shared mut Node)[], weak parent: Node? }
fn tree() {
val root: shared mut Node = Node{name: "root", children: [], parent: None} // count 1
val leaf: shared mut Node = Node{name: "leaf", children: [], parent: weak root} // root's weak count 1
root.children.push(leaf) // leaf's count 2
} // release(leaf): count 1, root.children still holds it
// release(root): count 0, root freed, and its children:
// leaf's count 0, leaf freed; its weak parent dropped
sequenceDiagram
  participant T as tree
  participant R as root (shared)
  participant L as leaf (shared)
  participant H as heap
  T->>H: allocate root, count 1
  T->>H: allocate leaf, count 1
  L-->>R: weak parent: weak count of root 1, strong count unchanged
  R->>L: children.push(leaf): leaf count 2
  T->>H: end of scope: release leaf, count 1
  T->>H: end of scope: release root, count 0: free root
  H->>L: root's children released: leaf count 0, free leaf
  Note over L: an access to parent after root's free gives None

Node itself is an ordinary type: the nodes are shared because they are placed in shared mut places, where root.children is modified on one task, behind an exclusivity flag (section 9); (shared mut Node)[] qualifies the elements of children, not the array. A tree one owner holds is rather an arena object, without counts (section 7). A Node whose parent were strong would be refused: the edge from Node to Node through children and parent forms a strong cycle.

fn index(sink doc: Bytes): Promise<Int> = spawn(() => count(doc)) // doc given up to the task
fn both(shared doc: Bytes) {
val a = spawn(() => count(doc)) // two tasks hold doc:
val b = spawn(() => words(doc)) // shared, counted atomically
...
}
sequenceDiagram
  participant M as main task
  participant T1 as task 1
  participant T2 as task 2
  participant H as heap
  Note over M,T1: index, doc given up
  M->>T1: sink doc (ownership moves)
  T1->>H: free doc (end of the task's scope)
  Note over M,T2: both, doc declared shared
  M->>H: atomic count + 2
  M->>T1: doc
  M->>T2: doc
  T1->>H: atomic release
  T2->>H: atomic release: count 0, free doc

Of the eight, only 6, 7 and 8, where sharing is declared, leave anything to run time. Every free has a place the compiler computes, and every copy a place in the text.

9. A panic caught: the frees of the abandoned frames

Section titled “9. A panic caught: the frees of the abandoned frames”

A panic that goes up to a barrier, Panic.catching, runs the frees of every frame it abandons, as C++ and Rust unwind. Done ahead of the model, on today’s counts (phase 0, section 11).

  • Unwind tables, nothing on the normal path. In a function that owns something, a call that can panic becomes an LLVM invoke; its landing pad runs what the end of the scope would have run, frees and disposals, reading the same flags of values given up (case 4). Temporaries, and the parts of a value under construction, are freed by the same pad.
  • A forced unwind to a setjmp barrier. The runtime knows the chain of barriers, so no search phase is needed: a panic calls _Unwind_ForcedUnwind, whose stop function stops at the barrier’s frame and longjmps to it, as glibc unwinds pthread_cancel. A forced unwind runs cleanups only: C’s personality of libgcc, __gcc_personality_v0, is enough.
  • using, defer and errdefer go through the landing pads too: the runtime’s chained list of cleanups, pushed and popped at each scope, goes, and the normal path gets faster than today.
  • Tasks. The stack of each task ends with a frame whose CFI stops the unwinding; a panic in a launched task frees its whole stack before its executor applies its policy.
  • Without a barrier, nothing is freed. The program stops: the landing pads run disposals and defers, as today, and skip the frees, the system taking the memory back, on a test of a global flag.
  • abort mode: no landing pads, no tables, Panic.catching refused, as Rust’s panic=abort.
  • After the catch, memory is safe: a value lent as mut by the abandoned code stays whole, a field being exchanged, never taken. Its logical invariants may be broken halfway, which the code that catches repairs, by going into a safe state; no annotation, unlike Rust’s UnwindSafe. The exclusivity flag of a shared mut value under modification is reset by the pad, without poisoning, as Mutex.with releases its lock.
Borrow Weak pointer Arena handle (Handle<T>)
Owns the target no no no
Can outlive the target no: refused at compile time yes yes
Access direct, no check a check that gives T? a generation check, then panic or None
Cost none a weak count; a test per access a test per access
Lasts the borrower’s scope free: can be stored free: a copyable value
In a field never yes yes

The borrow is the static form of the weak pointer: it needs no test because the compiler proves it does not outlive its target. The weak pointer is the dynamic form, for relations whose duration is known only at run time. Handle<T> is already a weak pointer, a generation in place of a weak count.

Needing an arena for every cyclic structure puts a choice of representation on the developer. But a cycle needs identity: two nodes that designate each other are each one object that several designate, where with value semantics a node designated twice is a copy. Weaver has two forms of identity today: the arena handle, and the shared type, whose fields do not change (SPEC 8.3), so that a parent cannot be linked after the fact.

Weak pointer (Swift) Generational reference (Vale) Cycle collection (Nim ORC)
Principle the back edge is marked weak one owner; other references carry a generation, checked on access counting, and a collector for the types that can form cycles
Written weak parent: Node? on each back edge nothing beyond “non-owning reference” nothing
Cost a weak count; a test per access a generation test, removed where the compiler proves validity an occasional pass, on cyclic types only
Release deterministic deterministic deferred for cycles become unreachable
Risk a forgotten weak leaks an access to a freed object: panic, or None a part of garbage collection

Retained: the weak reference to a shared value, with a weak count, as Swift. It is the cheapest: a weak count in the shared value’s header, which only shared values have, and a test only on an access through the weak reference, which gives T?. Nothing for the values that are not shared, where the generational reference costs a word per object and constrains the allocator. Cycles thus go through shared: identity is a shared value’s, the strong edges count, the back edges are weak.

The risk is a forgotten weak: a cycle of strong edges never freed. The compiler can refuse it at compile time, as principle 1 asks: the graph of the types whose shared fields designate one another is known; a cycle in it whose edges are all strong is an error, which names the edges where one weak breaks it. A cycle of values formed through a type that does not show it, a shared field of a generic T instantiated with its own type, is checked at each instantiation.

shared gives identity to values held by independent owners, at the cost of their counts. A graph that belongs to one owner, a syntax tree, a DOM, the compiler’s own tables, needs identity without counting: an arena object. Its scope is an arena for what it contains. A third kind of value with a life cycle of its own, beside resources:

Ordinary value Resource Arena object
What sets it apart nothing a release action, close, flush it owns a region where its nodes live
Freed at the end of its owner’s scope at the same point, by its dispose, with its error at the same point, with its whole region at once; only nodes with parts on the heap are walked to free them
Copy .copy(), explicit refused .copy(): the region copied as is, then the nodes’ owned parts; no ref remapped
Internal designation none none ref Node: an index into the region; no count, no test unless the object removes nodes
type Node = { name: String, children: ref Node[], parent: ref Node? } // internal refs
arena type Tree = { root: ref Node? } // owns every node of its region
val t = mut Tree()
val r = t.add(Node{name: "root"}) // allocated in t; r: ref Node, valid while t lives
val l = t.add(Node{name: "leaf", parent: r}) // a cycle, r and l, without a count
t[r].children.push(l) // modified under t's exclusivity: no check
} // end of t's scope: its whole region freed at once
  • The region follows the object. Storing an arena object in a field, or giving it up, moves its scope, and its whole region with it: the rule of storing into an object, for a group. The arena { … } block of SPEC 6 becomes its particular case: an arena whose scope is a block.
  • A node is created by t.add(…), which takes it and returns its ref, and reached by t[r], a projection: a borrow of t, read, or modified under t’s exclusivity. A type with ref fields lives only in a region; a temporary of it is built only to be given to add.
  • A ref is an index into the region, 32 bits: compact, serializable as is, kept unchanged by a copy. It is a plain value and may be held outside the object, the selection of an editor. A ref of one tree used on another stays memory safe, caught by the bounds or by the generation, but may designate the wrong node: the limit of Rust’s slotmaps, which a mark of the object detects in debug builds. No region is ever written.
  • Removing a node. An arena type that offers no removal is a pure arena, without checks: a node lives until the object dies. One that offers t.remove(r) frees the node at once and reuses its slot; its refs then carry a generation, checked at each access, visible and refusable as every check. Only the objects that remove nodes pay.
  • No check on modification. Whoever holds the object as mut modifies any of its nodes, under the object’s exclusivity, proven at compile time.
  • Allocation is fast: a region grows by consecutive blocks and is freed at once.
  • A value leaves a node by .copy(), which copies it to the ordinary heap, as leaving an arena block detaches it today.
  • Sharing and tasks take the object as a whole: given up to a task, or declared shared, its nodes with it.

The two answers to identity do not overlap: shared, with its counts, for identity held by independent owners; arena objects, without counts, for a graph one owner holds. The Arena<T> of weaver.collections, with its handles checked at each access, becomes an option a library may still choose, not the way to build a cycle.

Each measured on the libraries written in October 2026.

  • F1. Uniqueness checked at each write. A write into an array checks that its block is not shared; the check leaves a loop for a local, not for a field of mut self, where a codec’s or an automaton’s state lives. deflate: arrayUnique took 27 % of compression; worked around by taking the tables’ addresses once per loop, in unsafe, from twice zlib’s time to 1.02 to 1.08 times. inflate takes its output buffer out of self for its fast path; regex empties a field so that its table becomes unique again.
  • F2. A view is a counted value, not a borrow. It retains its whole block, and a write into the block while it lives copies the block. weft/json, a 40 MB document read into a tree: views 0.85 s and 453 MB, copies 1.15 s and 615 MB, against jq’s 1.08 s; copies kept, so as not to retain the windows. A Reader cannot lend its window: gzip through weft/compress copies into its caller’s buffer, 5 % slower.
  • F3. A resource never leaves its container. Ownership or a borrow for one call, nothing between; no exchange that leaves the container valid. zip: ReaderAt.duplicate() added so that each entry can read the archive’s source. Generic code treats any R as a resource: using r = JsonReader.new(src) required there, refused for JsonReader<StdinLock>.
  • F4. Exclusivity is coarse. self.insert(t, self.strstart) is refused, though the Int is read before the call begins: some twenty temporaries added in json and compress for that rule alone, the same pattern in the compiler. Rust solved it with two-phase borrows.
  • F5. Mutable state in a closure cannot be kept. A [mut x] capture does not escape: weaver.test’s runner turned its cache of case tables into a type.
  • F6. The safe path is slow. Bounds, overflow and uniqueness checks add up in loops; an index read from a table, codes[bits.and(mask)], is checked although masked. regex: its automaton’s loops in unsafe, 94 to 61 ms on -c [0-9], against GNU grep’s 57.

Two concepts are missing from the model, behind F1, F2, F3 and F6: uniqueness as a static property, and a borrow a function can return. F4 and F5 are rules set at their coarsest, which change without changing the model.

9. Beyond a call: returning, lending, sharing

Section titled “9. Beyond a call: returning, lending, sharing”

A method’s result is either given up to the caller, : T, or lent, : yield T; the signature says which, and the caller knows whether it owns the result or borrows it. The body returns either with return.

Where the value returned comes from return gives up What happens
created in the method yes it changes owner; its free moves to the caller’s scope
a parameter received as sink yes the method gives it back, modified or not
self consumed, sink self yes, its fields the object goes, its parts go to the caller: finish(sink self): W
a field of mut self only by an operation that takes it out pop(), remove(k), or an exchange, replace(&self.buf, with: Bytes.new()), which returns the old value and leaves a valid one; return self.buf alone is an error, the field would be empty
a field of a read self, or a borrowed parameter no a : yield T declaration lends it, or .copy() gives up a copy

A field is never taken, only exchanged. An object stays whole, and the free of each of its parts keeps a fixed point. The same exchange takes a resource part out of its container (section 3).

What the compiler knows of a callee: its signature

Section titled “What the compiler knows of a callee: its signature”

Correctness depends on signatures only: whether code compiles, where its frees and copies go. A change in a function’s body never breaks its callers, compilation stays separate, and calls through a contract or a closure, of which only the signature is known, follow the same rule.

The caller needs to know The signature says
whether an argument is kept sink; otherwise a borrow, valid by nesting
whether an argument is modified mut T, its content; never replaced
whether the result is its own : T, given up
whether the result is lent, and from what : yield T, from self for a method, from the shortest of its borrowed parameters for a function, or as from names it
until when a value given to a container stays borrowed the container’s first mut call
whether a closure argument is kept sink; otherwise it is not kept, and may borrow the caller’s state
whether an argument is kept sink, as its owner; shared, as a frozen share; otherwise it is only read during the call

Optimization may use inferred summaries, as the error set of fn t() ! is inferred: which shared mut values a function can reach, which indices it keeps in range. They only remove run-time checks, and stay inside a package: an assertion that no check is left may rest on a summary from the same package, but across packages only on signatures, so a change of body in a dependency never makes it fail.

Lifetimes cannot all be avoided; they are never named. Rust’s 'a is a variable that only links places; Weaver writes the places themselves, a parameter or a path to a field.

A lent result: from. The default, self or the shortest of the borrowed parameters, covers most functions and is shown greyed in the editor; from names the source otherwise, one or several parameters or a path.

// Rust: fn lookup<'a>(table: &'a Map<K, V>, key: &K) -> &'a V
fn lookup(table: Map<K, V>, key: K): yield V from table

A value that holds a borrow: a local type. Only a local type has borrow fields, or fields of a local type: the keyword is required, since adding a borrowed field changes where the type may go, a change of API. The borrow field is the dependency: an Iter depends on what was given to items when built. It propagates without being written: a local type Parser = { lexer: Lexer, borrow arena: Arena } depends on what its Lexer depends on, and on arena, what Rust writes Parser<'src, 'a>.

A local value may Example
be a field of another local type lexer: Lexer above
be an element of a container, which becomes local val iters: Iter<T>[] = …
be returned, with its dependency fn iter(self): Iter<T>, … from self.src
cross an await in its task its source lives in the same frame

It never goes into an ordinary type, a shared place, another task, or a closure that is sink: it would outlive its source. A self-borrowing object, { arena: Arena, borrow ast: Node from self.arena }, is refused, as in Rust: moving it would break the borrow; the arena object answers that need. A borrow held by a local value freezes its source until that value’s last use; the free stays at the end of the scope.

// Rust: struct Iter<'a, T> { items: &'a [T], i: usize }
local type Iter<T> = { borrow items: T[], i: Int }
fn iter(self: T[]): Iter<T> // depends on self, by default
fn next(mut self: Iter<T>): yield T? from self.items

from self.items says the element lent lives as long as the collection, not the iterator: the distinction Rust writes with 'a, read here as a path. A view that must be stored is a counted share of a shared buffer instead. Never written: variance, 'static (an owned value needs none), for<'a> (a closure not sink uses a borrow during the call only). Errors speak of bindings and lines:

error: `v` is modified while `it` borrows it
12 | val it = v.iter() // it borrows v
14 | v.push(x) // modifies v
15 | it.next() // it still used here

Lending a part of self: method projections (F2)

Section titled “Lending a part of self: method projections (F2)”
impl Inflate {
fn chunk(mut self): yield Bytes ! CompressError { // `yield`: the result is lent
self.fill()!
return self.out[self.given..self.pos] // a view of self, not a copy
}
}
val c = z.chunk()! // c borrows z
out.write(c)! // a read: allowed
val d = z.chunk()! // z modified: c's borrow ends here
use(c) // error: `c` borrows `z`, modified since (line 3)
  • The result borrows from self, or from the only borrowed parameter; otherwise the declaration is an error.
  • It lives in a binding of the caller, is not stored in an object, and is not given up: to keep it, .copy().
  • Its borrow ends at the first modification of its owner: the rule of the binding that borrows what it gave up (section 3).
  • yield in the declaration, return in the body. The signature says the result is lent; the body is written as any function’s, its return checked to give a part of self or of the borrowed parameter, never a value it owns. A lent return, not a coroutine: a subscript, which runs code after its yield, keeps its form.

What it changes on the cases measured:

  • inflate, gzip: chunk() gives the decoded window without copying it, the 5 % gone. Reader keeps read(&buf), which copies by nature; BufReader gains chunk().
  • weft/json: r.str() lends a string, from the window, or from an inner buffer when it holds escapes; typed decoding and the tree write .copy() where they own, the traversal allocates nothing. The gain of views, 0.85 s against 1.15 s, without their retention.
  • tar: r.chunk() for an entry’s content.

Traversing a collection without copying it (weaver#10)

Section titled “Traversing a collection without copying it (weaver#10)”

Reading lends, modifying is in place, keeping is written .copy(): a loop over a collection follows the rule a single access already follows, m[k] lending its value and a pattern on it borrowing what it binds.

Measured before: 100,000 values of ten counted fields, traversed twenty times, for (_, v) in m takes 1,230 ms, iter() alone 710, copying the table’s slots, and each next() gives up a copy of its key and value; a for over an array of the same values, 2 ms.

  • A lent result has its effect. fn get(self, k: K): yield V? returns its value without a count: the caller frees nothing, and its binding borrows until the source is modified (method projections, above). Until now only a read subscript lends; a function declared : yield T is checked as lending, then gives up a counted copy.

  • A lent aggregate. A tuple, an option or a record that the return builds from lent parts is lent whole, Some(self.items[i]) or (e.key, e.value): the caller frees neither it nor its parts. A part created rather than lent makes the return an error: it lends all, or gives all up. A fallible result, yield T ! E, lends its value and gives up its error, which fail creates: chunk() above.

  • What a lent result may be. A part of self or of a parameter it reads, a field, an element, a view, what a lending subscript reads; a constant, "" or None, or a value nothing counts; an if, a match or a ?? each of whose branches lends; the result of a function that lends from what this one lends; an aggregate of these; a val or a pattern’s binding holding one of these. A value the function creates, an interpolation, a literal array, a .copy(), is refused: such a function gives its result up, without yield, and the result moves to the caller without a copy.

  • Lent where nothing can end the loan. A lending function returns its result without a count, whatever calls it; the caller keeps it so only when what it lends from is a path the caller borrows, which it can neither modify nor consume while the result serves: a parameter it reads, self included, a loop’s variable or a pattern’s binding. From a value the caller owns, which a sink argument may consume, or modifies, it counts the result and owns it, as before: val n = c.name() then c.dispose() reads no freed value. An any’s relay counts what an implementation lends under a contract that gives.

  • A borrowing iterator. A collection’s iterator is a local type whose borrow field designates the collection’s storage without a count, built without copying and lending what it reads:

    local type MapIter<K, V> = { borrow slots: MapEntry<K, V>?[], i: Int }
    fn iter(self): MapIter<K, V> // depends on self
    fn next(mut self): yield (K, V)? from self.slots

    It lives in the loop’s frame, and the collection is frozen while it does: the rules of a local value (above).

  • A contract that gives, an implementation that lends. The contract stays Iterable<T>, fn next(mut self): T?: a generator gives up what it creates, utf8Chunks, map, a range. An implementation may lend instead, yield T? from …. Code that knows the type sees borrowed bindings, and writes .copy() to keep one; generic code, checked against the contract, receives owned values, the compiler counting a reference where it keeps one, collect for instance, a copy the call names.

  • Modifying in place: an iterating projection. for (k, mut v) in m modifies each value where it lies. m is lent to the loop, which uses it in no other way: neither its size nor its keys change, as for for mut x in xs. A place cannot be returned, references being second class (section 7): a cursor’s next could lend a value, not where it lies. The collection declares instead a projection that walks its storage and yields each element’s place in turn, and the loop’s body runs at each yield, as m[k] += 1 runs at a mut subscript’s:

    impl<K, V> Map<K, V> {
    property each(mut self): (K, mut V) {
    for i in 0..self.slots.len() {
    if self.slots[i] is Some(mut e) { yield (e.key, &e.value) }
    }
    }
    }

    The loop finds the projection by its name on the collection’s type: no contract says, for any T, which of its parts are places, and generic code modifies no collection in place.

    Its result type marks with mut the parts yielded as places, &e.value; the others are read. A key, yielded as a value, stays read-only, which keeps the table’s order valid: for (mut k, v) in m is refused, “a key is read-only while its entry is in the table: remove it, then insert another”. Nothing is copied, nor taken out and stored back, as a mut subscript of Map does for one entry. continue ends the body’s turn, the projection’s code after its yield then running; break leaves the projection’s loop at once, from its yield, and the code that follows that loop runs; return leaves the function, the projection’s rest with it.

  • What still copies says so. m.keys(), m.values(), m.entries() build arrays, copies their names announce; a loop that keeps a value writes .copy().

A zip entry reader is an object, which cannot hold a borrow: lending the archive’s source to it goes through sharing. A resource can be declared shared, counted, and disposed of at the last release, under two conditions:

  1. Its release cannot fail, Disposable<Never>. The last release can happen in any holder, where no code expects an error: a fallible one would be lost, against principle 4. A file open for reading, a lock, a read-only mapping are shareable; a file open for writing, Buffered, a GzipWriter, whose last flush can fail, stay linear.
  2. Through a share, only methods taking self are called, never mut self, as for any shared value. For a file: readAt, a positional read without a cursor (pread), is allowed, and several readers read at once without disturbing one another; read, which moves the file’s cursor, is refused, two holders sharing a cursor mixing their positions. ReaderAt is exactly a shared file’s interface.
type ZipArchive<R: ReaderAt> = { shared src: R, list: ZipEntry[], comment: String }
using zip = ZipArchive.open(ReadFile.open(p)!)! // the file: count 1
using r1 = zip.reader(e1)! // count 2: r1 holds the source
using r2 = zip.reader(e2)! // count 3: two entries read at once
// end of scope, reverse order: r2 (2), r1 (1), zip (0): the file closed

duplicate() is no longer needed: no dup per entry, no extra descriptor. The count is atomic only if a reader goes to another task, whose methods taking self must then be safe concurrently, as pread is. Duplicating stays a valid linear answer, each reader owning its own descriptor, at a system call and a descriptor each.

On the place, not on the type’s declaration. Sharing is a property of a use: a Map is shared where a cache needs it, and is an ordinary value everywhere else. shared T and shared mut T qualify the type of a place, as mut T does (section 3): a field, cache: shared mut Map<String, Bytes>; a binding, val blob: shared Bytes = load(); a parameter that keeps a part, doc: shared Bytes; a generic argument, Map<String, shared Bytes>. The qualifier applies to the type that follows, suffixes included: shared mut Node[] shares the array, (shared mut Node)[] each node. Storing a unique value into a shared place converts it, once: it moves into a counted block. No Rc<T> is ever written; the type stays Map.

Modifying a shared value modifies the same value for all its holders: reference semantics, wanted, since that is what identity means. Graphs one owner holds are arena objects (section 7); what remains are values held by independent owners: a cache several components use, a list of observers, a configuration reloaded, a connection several requests use. Two dangers: two overlapping accesses on one task, a modification under way and a callback that modifies the same object; and two tasks modifying at once. Three levels, read on the place and on the type’s methods together: mut says whether the shared value can still change, which must be known at compile time when parts of it spread into fields and tasks. As everywhere, val and var only say whether the label is reassigned.

Place What its holders do Across tasks Check
shared T read, through methods taking self: the value is frozen for all yes none
shared mut T modify, through methods taking mut self no: it stays on its task an exclusivity flag, unless proven useless
shared T holding a value of a sync type, made to be shared between tasks, an atomic, a lock, a channel, a pool modify, through its methods taking self, which synchronize yes the synchronization the methods do
  1. Immutable by default. A value shared without mut is read from anywhere and crosses tasks freely, its count atomic if needed, without a check: configuration, reference data, shared results.

  2. shared mut makes it modifiable on one task, through the type’s mut methods. The compiler refuses to give it up to another task or to let one capture it. Its modifications go through a non-atomic exclusivity flag, which catches the overlap:

    cache.update(k, () => cache.clear()) // the closure modifies cache during its modification: panic

    The flag goes where the compiler sees that no call made during the modification can reach the object; it is visible in the editor and refusable by assertion, as every check (principle 3).

  3. Shared between tasks, the methods synchronize. A value that crosses tasks and changes is of a type made for it, and changes only through methods taking self, which guarantee their own synchronization, as SPEC 8.3 says today: its fields that change are synchronized types of the standard library, an atomic, a lock, a channel, written in unsafe behind a safe interface; only the implementation answers for it. An actor is the form where that synchronization is a queue of messages, written by the compiler.

  • A shared value never goes into a shared mut place, where it would stop being frozen; a shared mut value does not become shared while other modifiable parts of it exist.
  • shared mut on a sync type adds nothing: a warning.
  • The types of the last row keep a mark on the type: their safety comes from their implementation, not from a use. Today’s shared type becomes sync type, since shared now names a place.

A call with a mut argument, self included, runs in four steps:

  1. Reserve the place: evaluate its path, left to right, the indices and subexpressions of a[f()].push(…), without touching the value.
  2. Evaluate the other arguments, left to right. They may read the place reserved, and modify it: each is evaluated whole before the call.
  3. Activate the exclusive borrow: resolve the place from the path of step 1; an index is checked here, after the arguments.
  4. Call.
Code Today Proposed
self.insert(t, self.strstart) refused accepted: the Int is read before
m.set(k, m.get(k) + 1) refused accepted: get’s loan ends before activation
a.push(a.pop() ?? 0) refused accepted: pop ends before push begins
a[i].push(a.pop() ?? 0) refused accepted: a[i] resolved after pop, with its bounds check
m.set(k, m.get(k)), a value on the heap refused refused: a borrow given to a sink; the message suggests .copy()
f(&self.buf, self.buf.view()) refused refused: a loan living during the call, a real alias

An argument may touch the place reserved as long as what it produces no longer refers to it when the call begins: an owned value, or a borrow already ended. Rust’s two-phase borrows allow only reads during the reservation, vec.push(vec.pop().unwrap()) being refused; here the arguments are evaluated whole and the place resolved at activation. Assignments follow the same rule: a[i] = a[j] + 1, x.total += x.items.count, evaluate the path, then the value, then write. Disjoint fields in one function, self.out.push(self.window[p]), do not overlap; a mut method called on self reserves the whole of self.

Each a[i] checks its index at run time today. Three cases:

Proved, no check Example Why
a loop bounded by the length for i in 0..<a.count { a[i] } a cannot change size during the loop: exclusivity forbids it
direct iteration for x in a, a.iter() no index
an index masked into a fixed table head[h & 0xFFFF], head: [UInt16; 65536] the mask bounds it
an index of a type too small to overflow table[b], b: UInt8, a table of 256 the type bounds it
an index guarded by a comparison if i + 1 < a.count { a[i + 1] } a dominating condition, simple linear arithmetic
  • Checked once. for i in start..<end { a[i] } checks end <= a.count at the loop’s entry rather than at each turn; visible and refusable as every check (principle 3). An assertion written by hand, assert end <= a.count, serves as the proof.
  • Checked at each access. An index computed opaquely, a[f(x)]; across functions, a summary inferred inside the package may remove the check, never beyond. Where each cycle counts, a[unchecked: i] in unsafe.
  • Measured, phase 0. The first two forms are proved in the lowering (compiler/lower/bounds.wft); the others LLVM already removes. Once a function is inlined, LLVM also removes those two: wv keeps 4,174 index checks of 4,210, at the same speed. Checking once at a loop’s entry changes what a loop that leaves by break before the faulty index does; it needs two versions of the loop, left until a measure asks for it.
  • Not done, for now: integers with a range, Int<0..N>, or preconditions in signatures, requires i < a.count: a proof system of its own. The list of proved forms grows when a measure justifies it.

The frictions of section 8, measured against the model as it stands.

Friction Where it stands What remains
F1 uniqueness checked at each write solved: an ordinary value is unique, written in place without a check; taking a buffer out of self (inflate) or emptying a field (regex) are no longer needed a modifiable shared value on one task checks an exclusivity flag, unless proven useless (section 9)
F2 views counted: retention, copies on refill solved: a borrow neither retains nor copies; method projections, : yield T, lend a part of self (section 9); BufReader.chunk() reads without copying a JSON tree still allocates per string: real ownership, now explicit
F3 a resource never leaves its container solved: linearity per field frees the ordinary parts, generic and concrete code agree; a resource whose release cannot fail is shareable, read through self only (section 9); a field is exchanged, replace a fallible resource, a writer, stays linear, by design
F4 coarse exclusivity solved: a mut borrow in two phases, the arguments evaluated before it is activated (section 9) a loan living during the call stays refused, a real alias
F5 mutable state in a closure in part: a closure argument is not kept by default and borrows the caller’s state; one kept is sink (section 9) an escaping closure owning its state, given up to it, as an object owns its fields
F6 the safe path is slow solved for the common forms: the uniqueness check is gone; loops, masks and guarded indices are proved, other loops checked once (section 9) opaque indices stay checked, or unchecked in unsafe; overflow checks are not a memory matter
F7 a part stored in several values is copied at each store solved: a part no holder modifies is frozen, shared T without mut, shared by count (section 3); a parameter kept is shared T or sink T measured by phase 2 (section 11): of 1,361 stores in the compiler, 1,237 frozen and 124 copies written; in core and std, 109 and 1

Against the stakes of section 1: allocation and release are static, at the end of the owner’s scope, counting reserved to shared; no race, a value crossing tasks being given up or shared and counted atomically; no access to freed memory, borrows following the nesting of scopes, weak references checked; no needless copy, copies being explicit and a binding borrowing what it gave up; no retention, no view being counted, strong cycles refused at compile time; sharing between tasks without a copy, a count per share, not per access; a frozen part stored in several values without a copy, a count per store. Spatial safety: bounds proved in the common forms, checked otherwise.

What the model creates, settled since: caught panics, freed through unwind tables and landing pads (section 6, case 9); the migration of existing code (section 11).

About 97,000 lines rely on today’s model, the compiler 61,900, std 13,200, weft 9,900, the examples 8,300, core 3,600, with 243 test programs; and the compiler is built by the seed, which knows only the old model.

Code valid under both models. The old model copies on write, where a binding is modified while its source still serves. A .copy() written at exactly those points changes neither the behaviour nor the performance under the old model, and makes the code valid under the new one; elsewhere the source is no longer used, and the new model moves it. The source migrates first, then the compiler switches at once.

Phase Content The language changes?
0. Independent of the model the inout borrow in two phases (F4); landing pads in place of the list of cleanups, and the frees of caught panics, releasing today’s counts; bounds proved no
1. Syntax accepted, without effect val beside let; mut T, shared T, shared mut T, sync type beside shared type, from, local type, arena type with t.add and t[r], [inout x], .copy(); then the seed regenerated, the source converted from let to val, and let removed additions only
2. The analysis, reporting the compiler runs the new analysis beside the old one and warns, with a fix: an implicit copy, y.copy() to write; a modified borrow; a field taken rather than exchanged. wv migrate applies the fixes, and sorts each var: reassigned, it stays var; modified in place, val … = mut …; both, var … = mut …. An inout parameter that never replaces its value becomes mut T, mut self; one that does is rewritten by hand to return it; then inout is refused. The source becomes valid under both models no
3. The switch the compiler goes to the new model, at once for the whole build: unique blocks without a count, sharing only in shared places, views by borrow, frees at the end of scopes; the seed regenerated yes
4. Cleanup the warnings become errors; arrayUnique and counted views leave the runtime; the temporaries of F4 and the unsafe of F1 are removed —
  • A switch for the whole build: packages of both models together would need two representations of blocks, counted or not, and a conversion at each boundary. Phase 2 making all the source valid under both, no coexistence is needed: the seed compiles the source of phase 2, and the compiler built from it switches.

  • Measuring before committing. Phase 2 gives the real size of the work before the model is touched: the warnings per category, in the compiler, std and weft. A category that explodes, patterns of the compiler the analysis refuses, is known before the switch, and a rule may be revised.

  • The switch, step by step. The lowering already gives each variable its value, which it frees when leaving its scope; a read borrows; a store takes a reference of its own, a count, unless the value is an owned temporary, which moves. The switch removes what copy on write still adds to that: the counts of values that move, the check before each write, the counts of views. It is a mode of the lowering, chosen for the whole build, core and std included, so that each step is measured against the other mode on the same source:

    Step Content Checked by
    3.1 Moves the checker marks the last use of an owned local that gives it up, a sink argument, a store, a return; the lowering moves it, without a count, and does not free it at the end of its scope; a local given up on one path only carries a flag (section 6, case 4) the benches; the counts the compiler makes compiling itself, measured
    3.2 Unique on write a mode where the check before a write in place, arrayUnique, the reservation of a string, stops the program when it finds a shared block outside a shared mut place, at the write’s position: each stop is a copy the source lacks, or a case the analysis misses the benches and the compiler compiling itself, in this mode, without a stop
    3.3 Writes without check the lowering no longer writes the check, except in a shared mut place, where it is the exclusivity check; .copy() copies its blocks down to the frozen positions, which it shares by count, since a write may now go beneath the top of the copy, b[0].push(x) the benches; the time and size of the compiler
    3.4 Views by borrow view, chunk, slices: a borrow of the block, without a count, valid as long as its source, which the lent results of phase 1 already tie the benches; the mode of 3.2
    3.5 The switch the mode becomes the default: the compiler built by the seed rebuilds itself in the new model, which builds it again to a fixed point; the seed is regenerated from it the fixed point; all the benches; the final measure, time, peak memory, counts

    A unique block keeps its header, its count at 1: the layout of blocks, which the runtime and C extensions read, does not change during the switch. Removing the count of unique blocks is left to phase 4, measured then. WEAVER_REAL_COPY, which copies only the top block, goes at 3.3.

  • Step 3.1 is done, behind WEAVER_MOVES=1. A val, a var or a sink parameter given up whole by its last use moves: the lowering leaves its slot empty, which frees nothing at its scope’s end, on that path only, without a flag. A use in a defer counts as one at the end of the scope. A pattern’s or a loop’s binding does not move: it is a part of what it matched, which the lowering frees whole. The compiler built so compiles itself and passes all the benches; its IR has 7.8 % fewer retains, 13,648 against 14,796, for the same time: a count on one task costs little, the check before a write is what 3.2 and 3.3 remove.

  • Steps 3.2 to 3.5 are done, 2026-11-04. The model is the compiler’s only one: moves, bindings that borrow their place, read subscripts that lend, .copy() down to the frozen positions, writes in place without reading their block’s count, a view or a literal copied first. The missing copies are errors in every build. A result a call lends, : yield T, unwrap, ??, a branch giving a place, is followed to its place: a binding modified in place, a store or a sink argument of it copies it, and a function returning parts of self or a borrowed parameter lends them or copies them. The compiler rebuilds itself to a fixed point, the seed is regenerated from it, all the benches pass; it compiles itself up to its LLVM IR in 14.2 s and 1.20 GB, as the last compiler of copy on write did, 13.9 s and 1.22 GB: the counts of unique blocks, kept, are phase 4’s.

  • Lent through patterns and conversions, 2026-11-04. A pattern over a lent result binds parts of its source; views and conversions, bytes, utf8, trim, view, lend their receiver’s block, judged by its position. A lent value stored serves as long as its source does. The copy judges a record’s field by its own position, an element by its type’s.

  • Slices lend too, 2026-11-09. A slice, b[a..b], is the view b.view(a..b) written otherwise, and lends its source’s block; a binding over a binding that borrows borrows that binding’s source, down the chain; a variant holding a view, Some(t), holds its source’s block. A place replaced whole by a view of itself, xs = xs[1..], is no store. Missed, a view returned from a mut self method saw its buffer’s next writes: HTTP fields read from a connection showed the body read after them (HISTORY 421, 422).

  • Phase 4 has begun, 2026-11-04, with F1: deflate writes its tables by index, without unsafe. The check before a write, which reads no count since the switch, only that the array covers its block, is inlined; a loop makes an array field of mut self unshared once, as it did a local, and for i in 0..self.head.len() proves its indices. Against zlib: 1.04 to 1.09 times its time, 0.96 to 1.05 with the addresses taken in unsafe. Phase 4 is closed: the temporaries F4 required are read in their calls again. Two of its items stay, by measure: array.unique, inlined, guards a view or a literal written and no longer shows in a profile; the count of a unique block stays, its increments taking 4.3 % of the compiler compiling itself, its decrements and frees 8.6 %.

  • Identity, 2026-11-04. shared mut T is core’s SharedBox<T>: a block of one slot, the value, its exclusivity flag and the table of its weak references, which every holder designates and writes in place, the switch’s writes needing no check. A weak field is a WeakBox<T>?, which shares that table: the value’s free marks it, a read then gives None. Strong fields around a cycle of types are refused, a value that would cross tasks too.

  • Where it stands. Phase 0 is done: two-phase inout borrows, landing pads freeing on a caught panic, bounds proved in two forms. Phase 1 has val, sync type, [inout x], mut T, shared T, shared mut T, mut before a value, .copy(), yield T from …, local type and borrow fields, and arena objects, on today’s copy on write, several types of node, generic ones, and removal behind @removable; and the module’s shared var became a Shared<T> value. Phase 1 is done. Phase 2 has begun: val … = mut … modifies its content in place, and wv migrate rewrote the vars of the compiler, weft and the examples, 1,427 into val … = mut … and 69 into var … = mut …, then those of core and std, 238 and 8; then the implicit copies, 156 written .copy(); then the values given up while they serve, 127 copies and 21 accessors that lend, : yield T, Option.unwrap lending and take giving up. A resource given up while it serves is refused by today’s compiler already; a field taken out of an inout self became a copy.

  • The measure of the stores. The last category, a part borrowed and stored into another value, counted 1,307 places in the compiler, 94 in core and std, a few in weft and the examples. By source: 480 bindings of a pattern or a loop over a borrowed value, 384 parameters, 379 locals read again, 64 parts of self. Written .copy(), each would become a real copy after the switch, where copy on write counts today: the model gained frozen parts (section 3), shared by count without a check. By destination, fields and elements together, shorthand fields {name} included: 1,237 stores into places no code writes in place, frozen by inference, and 124 into places written in place, written .copy() by wv migrate (41 of them elements check.Param, 17 ir.Func); in core and std, 109 frozen and 1 copy.

  • Parameters modify, never replace. wv migrate rewrote into mut T, mut self, [mut x] or [var x] the inouts that never replace their value, about 2,300 in the compiler, core, std, weft and the examples; the others, 36, were rewritten by hand into a result, a record of state modified in place, replace, or update on a lock.

  • Parameters kept. A read parameter the callee stores into an object, a field, an element, a push, outlives the call: when that place is frozen, the parameter is written shared T; when it is written in place, the store already copies. wv migrate wrote 432 shared T, 313 in the compiler and 56 in core and std. At each call, an argument given to a shared parameter that its owner then modifies in place gains .copy(): 27 of them, an ownership state passed then lent, a substitution kept by a closure; a write to the owner whole, a mut self method, reaches the part only if its position is written in place somewhere. No parameter became sink T by this measure: what a callee modifies of what it keeps, the store copies.

  • The final measure. The source now writes what the model needs: in the compiler, 386 .copy(), 315 shared T, 1,585 mut parameters, 1,308 val … = mut, 10 lending accessors; in core and std, 35, 56, 260, 325 and 13; in weft and the examples, 46, 36, 409, 302 and 2. Built with WEAVER_REAL_COPY=1, .copy() gives an array, a string or bytes a block of its own, its elements shared, as the model will: the compiler, compiling itself up to its LLVM IR, takes 12.7 s either way, within 1 %, and 4.5 MB more of its 1.2 GB at its peak; a whole build, LLVM’s optimization included, 200 s either way. The copies the model writes do not cost; what the switch removes, the uniqueness check before each write and the counts of unique blocks, is not measured here, it can only gain.

  • Phases 0 and 1 serve at once: two-phase borrows, frees on panics and bounds are gains without risk.

None on the model.