← core

core/mem.kur

//! Memory ownership and access vocabulary built from brands and linear values.
// `core::mem` -- the memory-ownership vocabulary. None of these types are
// primitives: they are ordinary library code built on brands and
// linearity.
//
// THIS MODULE ALLOCATES NOTHING. It is the allocator-free half of the
// vocabulary: `Ref`, `Region!` and the receipts that split, share and
// restore a region. The records that own heap storage -- `Owned!` and
// `Allocation!`, with `Owned!::new`/`into_value`, `Allocation!::adopt`,
// `adopt_value`, `release` and `close` -- live in `alloc::owned`, the allocator
// layer, which builds and ends regions through this module's public
// operations: `unsafe Region!::from_raw` to make one over a block it owns,
// `Region!::retire` to end one, and `lend`/`lend_in` to reach an `Owned!`'s
// value in place. The rest of this header describes the whole vocabulary
// across both modules.
//
// ---------------------------------------------------------------------
// THE VOCABULARY
//
//   Owned![T]            (`alloc::owned`) sole ownership of one
//                        heap-allocated `T`.
//                        Carries no brand, because nothing else can
//                        name this storage: there is nothing to
//                        witness, and nobody to witness it to.
//   Allocation![T,'r]    (`alloc::owned`) the right to FREE one block -- its base
//                        address and its extent -- under brand 'r.
//                        Linear, `restricted`, unprojectable.
//   Region![T,'r]        the right to ACCESS that same block, under
//                        the same 'r. Linear. `open` is the operation
//                        that splits an `Owned![T]` into these two.
//   RegionResume![T,'r]  the receipt `share` keeps back when it trades
//                        a `Region!` for a witness plus a description,
//                        and the only route back to the `Region!`.
//   Ref[T,'r]            a `Copy`, freely-duplicated DESCRIPTION of a
//                        place inside 'r's domain. Carries no
//                        authority of its own whatsoever.
//   Exclusive!['r]       `core::cap`'s one live exclusive witness for 'r;
//                        what a `Ref` must be presented alongside
//                        (`with`, `copy`). A `Region!` holds it.
//   Shared!['r,'q]       `core::cap`'s read-tree node over 'r: read-only
//                        authority at lineage 'q (`Ref::read`).
//                        `Exclusive!::share` mints the root; `split`,
//                        `join` and `SharedResume!::resume` are `core::cap`'s.
//
// Authority is split along two axes at once, and the table is easier
// to read once that is said out loud. `Allocation!` vs `Region!`
// splits FREEING from ACCESSING. `Ref` vs `Exclusive!` splits DESCRIBING a
// place from being ALLOWED to touch it. A `Ref` on its own is inert,
// which is exactly why it is allowed to be `Copy` and to be forgotten
// with no disposal ceremony at all.
//
// ---------------------------------------------------------------------
// THE LIFECYCLE, AND WHY `close` TAKES THE WHOLE REGION
//
//     Owned::new(v)            -> Owned![T]
//     owned.open()             -> (Allocation![T,'1], Region![T,'1])
//     &region.replace(v2)      -> T        -- the region stays in place
//     region.share()           -> (Exclusive!['1], Ref[T,'1], RegionResume![T,'1])
//     back.resume(write)       -> Region![T,'1]
//     alloc.close(region)      -> Owned![T]
//     owned.into_value()       -> T        -- frees the storage
//
// and, for raw storage that is not a single `T` value at all (what
// vectors and arenas want), the same two records minted directly
// from a `Uninit!` and retired back to one:
//
//     Allocation::adopt_value(uninit, v) -> (Allocation![T,'1], Region![T,'1])
//     unsafe Allocation::adopt[T](uninit) -> (Allocation![T,'1], Region![T,'1])
//     alloc.release(region)    -> Uninit!   -- `T` Copy: the value is given up
//     unsafe alloc.release_storage(region) -> Uninit!
//                                          -- any `T` the caller accounts for
//
// `close` and `release` both demand the COMPLETE `Region![T,'r]`
// back, never merely a witness of 'r. A reclaim that asked only for the
// witness would let a caller hand some other pointer-carrying value to
// someone else, reclaim and free the block, and leave that someone
// holding access to freed memory: a use-after-free from safe code. No
// such shape is expressible here: there is nothing `open` hands out that
// `close` does not ask for, because the pointer-carrying half IS the
// region and the region is the argument. `open` immediately followed by `close` round-trips;
// `open`, then `close`, then a use of the region does not compile,
// because the region is gone.
//
// The same sentence, from the other end: `Allocation!` alone can
// never free anything. Deallocation requires proof that every access
// capability minted over the block has come home, and the only proof
// this module accepts is the region itself.
//
// ---------------------------------------------------------------------
// EVERY TYPE IN THIS FILE IS `restricted`, `Ref` included: no other
// module can write their struct literals or destructure them. For the
// capability types that is what makes a witness unforgeable; for `Ref`,
// see the comment on the struct below. Restriction governs only who may
// write the literal, so it is equally important that no exported function
// converts a copied `Brand` into authority: `core::cap::Exclusive!::fresh`
// is the only way to mint an `Exclusive!`, and it mints a fresh brand
// every time. A copied `Brand` is therefore inert.
//
// Every allocation goes through `alloc::heap::HeapAllocator`, from
// `alloc::owned` -- never from this file.
//
// ---------------------------------------------------------------------
// WHY THE ACCESS OPERATIONS HAVE THE SHAPES THEY DO
//
// For any `T`, the contained value is looked at or changed only by
// operations that touch it exactly once each way -- moved out, moved back
// in: `Region!::replace`, and `Ref::with`, `update`, `update_in` and
// `replace`. None is a plain `read`/`write` pair. That is forced, not
// stylistic: a `read` would have to duplicate, and a `write` would have
// to silently discard, a value of a still-abstract, generic `T`, and
// whether either is legal can only be judged where `T` is known. The
// plain forms exist where `T: Copy` says so: `Ref::copy` (what
// `with(&cx, |v| (v, v))` returns), `Ref::set` and `Ref::read`.
//
// `Region!::replace` needs NO witness: holding the region at all is
// already proof that nothing else can be touching the block, because
// the region is unique and linear and every route that could hand out
// a second access capability consumes it. `Ref::with` does need the
// matching `Exclusive!`, which is the same mechanism that makes reclaiming
// the storage safe regardless of how many `Ref` copies of that brand
// are still lying around: using any of them requires presenting this
// exact `Exclusive!` again, and once it is consumed none of them ever can
// be (brands are never recycled).
//
// Raw, freshly allocated memory enters the `Exclusive!`/`Ref` discipline
// through `Allocation!::adopt_value` (or the unsafe `adopt`, for a block
// whose `T` is already there) and leaves through `Allocation!::release`
// (or the unsafe `release_storage`, for a `T` that is not `Copy`).
// Freeing never takes its address from a `Ref`: a `Ref` is `Copy` and
// freely projectable, so the base it names is a convention of the caller
// rather than a property of the value. An `Allocation!` carries the base
// and the extent the allocator itself reported.
//
// `Owned!::into_value` and `HeapAllocator::drop` (on the `Uninit!` that
// `Allocation!::release` returns) are the terminal operations for storage;
// `Region!::retire` and `Exclusive!::retire` end a capability without
// touching storage. Every other method converts one linear resource into
// another (`Owned!` <-> `Allocation!`+`Region!`, `Uninit!` <->
// `Allocation!`+`Region!`, `Exclusive!` <-> `Shared!`+`SharedResume!`,
// `Shared!` <-> two `Shared!`s + a `SharedJoin!`) and makes none
// disappear. Without terminal operations, a function whose return carries
// no linear resource (`main`, most notably) could never close out an
// allocation it obtained.
//
// ---------------------------------------------------------------------
// A NOTE ON SENDABILITY. `Exclusive!`, `Shared!`, `SharedJoin!`,
// `SharedResume!`, `Link!` -- every capability struct whose fields are
// all `Brand`s -- are permissions, not data. Any notion of sending values
// between threads must not be derived for them merely because their
// runtime representation is empty: an empty representation is a
// statement about code generation, and sendability is a statement about
// who may hold authority over a brand at once.
//
use package as core;

use core::cap::{Access, Brand, Exclusive!, Shared!};
use core::ptr::NonNull;

// The size of a type in bytes, `sizeof[T]()` (0 for a zero-size type);
// `unsafe alloca[T]()`, room for one `T` in the calling function's frame,
// freed when it returns (a linear value stored there must be moved out
// first: nothing tracks it); and `enum_variant`, the index of an enum value's
// variant in declaration order: `enum_variant(&place)` reads it from a
// place, and `enum_variant(value)` returns the value beside it.
export builtin::{sizeof, alloca, enum_variant};

// Every owner and capability type here is `restricted`: construction and
// destructuring are confined to this module. `Owned!` and `Allocation!`
// are `alloc::owned`'s, restricted there.

/// A description of the place of a `T` in domain `'k`, read or written by
/// presenting that domain's capability.
///
/// `Ref` only ever stores a pointer, never `T` inline, so it is Copy
/// whatever `T` is: both `Ref[u32, 'k]` and `Ref[Owned!, 'k]` are Copy.
///
/// `Ref` is restricted because pairing an arbitrary pointer with an
/// arbitrary brand is itself authority once one capability covers a whole
/// domain (`Exclusive!['k]`, `StaticRead`). Without it, safe code could
/// re-brand any pointer it can read off a view (`Slice::into_parts`,
/// `Ref::into_parts`) -- e.g. wrap a stale slice's pointer as a `Ref` of a
/// live brand and read it through an unrelated `Exclusive!` of that brand,
/// or forge a `'static` view of heap memory. `from_raw` below is the only
/// way in from another module.
///
/// The pointer is a `NonNull`: a `Ref` always describes a live `T`, so an
/// `Option[Ref[T, 'k]]` (or a list's link) is one word.
forall T, 'k.
struct Ref {
    ptr: NonNull[T],
    marker: Brand['k],
}

// Access authority is `core::cap`'s, not this module's: `Exclusive!['r]` is
// the one writer for domain 'r and its `Shared!` read tree the readers
// (the tree's lineage brands and four-brand join receipt are documented
// there). This module only pairs them with memory: a `Ref[T,'r]` describes
// a place in domain 'r, and `Ref::with`/`copy`/`read` demand the matching
// capability. Memory types that own a domain hold its `Exclusive!` rather
// than a bare brand, because only `Exclusive!::fresh` can create one.

/// The right to access one block holding a `T`, under brand `'r`.
///
/// `Allocation!` (`alloc::owned`) is the right to free a block;
/// `Region!` is the right to access it, under the same brand.
forall T, 'r.
struct Region! {
    ptr: *T,
    cap: Exclusive!['r],
}

/// The receipt `Region!::share` keeps back, and the ONLY route from an
/// `Exclusive!['r]` back to a `Region![T,'r]`: the base pointer plus the
/// brand, and nothing else. No extent, because `resume` reconstructs a
/// `Region!`, and a `Region!` carries none (the extent lives in the
/// `Allocation!`, which `share` does not touch).
///
/// Structurally `Allocation!` minus the extent, but a separate type:
/// `close`/`release` demanding a complete region is the invariant the
/// whole design rests on, and merging the deallocation record with the
/// access-recovery token would let one value stand in for both.
forall T, 'r.
struct RegionResume! {
    ptr: *T,
    marker: Brand['r],
}

// `Region!::split` and `Restore!::merge` below decompose one exclusive region into one independently branded
// sub-region per FIELD, each with its own fresh `Exclusive!` capability,
// and a receipt that reunites them.

/// The tie between a part of a split region and the region it came from.
///
/// `Link!['f,'r]` names BOTH brands: the fresh child brand `'f` a part was
/// minted under, and the parent brand `'r` it was split from. If `Link!`
/// named only the parent, a caller could build a fake part (any
/// `Region![F,'f2]` it already owns, paired with a `Link!['r]` naming the
/// real parent) and feed it to `merge` in place of a real one, smuggling
/// access to memory that was never part of the split. Naming the child
/// too means a `Link!` is only ever produced alongside the exact
/// `Region!` `split` made it for (`split` builds it from the fresh brand
/// `make_split_part` returns with that region), so a parent brand cannot
/// be paired with an arbitrary region.
forall 'f, 'r.
struct Link! {
    child: Brand['f],
    parent: Brand['r],
}

/// The receipt `Region!::split` keeps back: the base pointer and the
/// parent's own `Exclusive!['r]`, held while the parts are out. Like
/// `RegionResume!` it leads back to a `Region![T,'r]`, but it is a
/// different type, for the reason `Allocation!`/`Region!` are two types:
/// `share`'s receipt and `split`'s
/// receipt account for two different events, and merging them would let
/// one value stand in for both. Restricted, and `merge` is the ONLY
/// producer of a `Region![T,'r]` from one, as `RegionResume!::resume` is
/// for its receipt.
///
/// `merge` rebuilds the `Region![T,'r]` from `self`'s OWN stored pointer,
/// NEVER from a part: parts are permutable (nothing pins field 0's part to
/// field 0's storage once opened), so a `merge` that derived the parent's
/// base address from a part would read the wrong offset back the moment a
/// caller reordered the product. `Restore!` makes the correct base address
/// available without touching a part at all.
forall T, 'r.
struct Restore! {
    ptr: *T,
    cap: Exclusive!['r],
}

/// Lends `*p` to `f` in place: `f` gets the value through `&`, and the value
/// it leaves there is `*p` afterwards. `unsafe &*p` lends the target
/// itself, so the call passes `p`. Caller: `p` points at a live `T` that
/// nothing else reads or writes while `f` runs.
forall T, Ret where Sized[T].
unsafe fn lend(p: *T, f: closure(&_: T) -> Ret) -> Ret {
    f(unsafe &*p)
}

/// `lend`, with a context `cx` lent to `f` beside `*p`: the other values the
/// closure works on, which it could not capture (a closure that may go
/// uncalled captures only `Copy` values). Bundle several into one struct.
/// Caller: as for `lend`.
forall T, C, Ret where Sized[T].
unsafe fn lend_in(p: *T, &cx: C, f: closure(&_: T, &_: C) -> Ret) -> Ret {
    f(unsafe &*p, &cx)
}

/// A `u8` followed by a `T`, whose size gives the alignment of `T`.
///
/// For every layout the C backend gives a type, `sizeof[T]` is a multiple
/// of its alignment, so in `{ u8, T }` the value starts at the alignment
/// and the aggregate's size is `alignment + size`. `AlignProbe` is that
/// aggregate, never built; `alignof` only takes its size.
forall T.
struct AlignProbe {
    prefix: u8,
    value: T,
}

/// The alignment of `T` in bytes, as C lays it out: a power of two, 1 for
/// a zero-size type.
forall T.
fn alignof() -> usize {
    sizeof[AlignProbe[T]]() - sizeof[T]()
}

/// Exchanges the values of two places.
forall T.
fn swap(&a: T, &b: T) {
    let x = a;
    a = b;
    b = x;
}

/// Puts `val` in `dst` and returns what was there: how a linear value in a
/// place is swapped out, where `dst = val;` would drop the previous one
/// (`let old = mem::replace(&self.slot, fresh);`).
forall T.
fn replace(&dst: T, val: T) -> T {
    let old = dst;
    dst = val;
    old
}

forall T, 'k.
impl Ref[T, 'k] {
    /// A `Ref` to the `T` at `ptr`, in the domain `marker` names.
    ///
    /// The one way to build a `Ref` outside this module. Caller: `ptr`
    /// points at a live `T` inside the domain `marker` names, so that
    /// presenting that domain's capability (`with`, `copy`, `read`) really
    /// authorizes the access. So `ptr` is never null.
    unsafe fn from_raw(ptr: *T, marker: Brand['k]) -> Ref[T, 'k] {
        let p = unsafe NonNull::new_unchecked(ptr);
        Ref.{ ptr: p, marker }
    }

    /// The pointer and brand of this `Ref`.
    ///
    /// The safe inverse of `from_raw`, like `Slice::into_parts`: the
    /// pointer and brand grant nothing by themselves, and turning them
    /// back into a `Ref` needs `from_raw` again.
    fn into_parts(self) -> (*T, Brand['k]) {
        let { ptr: p, marker: m } = self;
        (p.as_ptr(), m)
    }

    /// The address this `Ref` describes, for identity comparisons
    /// (`a.address() == b.address()`). Safe: it reads no memory, and turning
    /// an address back into a pointer needs an `unsafe` cast. Values of a
    /// zero-size `T` have no bytes and may share an address.
    fn address(self) -> usize {
        let { ptr: p, marker: m } = self;
        let raw = p.as_ptr();
        unsafe (raw as usize)
    }

    /// Calls `f` on the value, moved out, and puts back the value `f` returns,
    /// under the capability `cx` lends.
    ///
    /// Requires presenting the live `Exclusive!` of the matching brand, lent
    /// by a context that holds it (`core::cap::Access`); nothing about `self` or
    /// the capability is inspected at runtime, the brand match is already
    /// enforced by the call's own type-check.
    forall Ret, C, R where Access[C -> 'k, R], Sized[T].
    fn with(self, &cx: C, f: closure(T) -> (T, Ret)) -> Ret {
        let (tag, rest) = Access[C -> 'k, R]::open(cx);
        let { ptr: nn, marker: m } = self;
        let p = nn.as_ptr();
        let v = unsafe *p;
        let (v2, ret) = f(v);
        unsafe *p = v2;
        cx = Access[C -> 'k, R]::close(tag, rest);
        ret
    }

    /// Calls `f` on the value where it lives: `f` gets it through `&` and
    /// its changes land in place, with no copy of the value in or out. The
    /// same witness as `with`.
    forall Ret, C, R where Access[C -> 'k, R], Sized[T].
    fn update(self, &cx: C, f: closure(&_: T) -> Ret) -> Ret {
        let (tag, rest) = Access[C -> 'k, R]::open(cx);
        let { ptr: nn, marker: m } = self;
        let ret = unsafe lend(nn.as_ptr(), f);
        cx = Access[C -> 'k, R]::close(tag, rest);
        ret
    }

    /// Puts `val` in the place and hands back the value that was there:
    /// `with`'s store, with no closure. The same witness as `with`.
    forall C, R where Access[C -> 'k, R], Sized[T].
    fn replace(self, &cx: C, val: T) -> T {
        let (tag, rest) = Access[C -> 'k, R]::open(cx);
        let { ptr: nn, marker: m } = self;
        let p = nn.as_ptr();
        let old = unsafe *p;
        unsafe *p = val;
        cx = Access[C -> 'k, R]::close(tag, rest);
        old
    }

    /// `update`, with a second place `other` lent to `f` beside the value
    /// (`lend_in`).
    forall X, Ret, C, R where Access[C -> 'k, R], Sized[T].
    fn update_in(self, &cx: C, &other: X, f: closure(&_: T, &_: X) -> Ret) -> Ret {
        let (tag, rest) = Access[C -> 'k, R]::open(cx);
        let { ptr: nn, marker: m } = self;
        let ret = unsafe lend_in(nn.as_ptr(), &other, f);
        cx = Access[C -> 'k, R]::close(tag, rest);
        ret
    }
}

forall T, 'k where Copy[T], Sized[T].
impl Ref[T, 'k] {
    /// A copy of the value, read under the capability `cx` lends.
    ///
    /// `with`'s most common case: read the current value without changing
    /// it. `T` comes from `r`'s own type, so a bare `r.copy(&tag)` needs no
    /// annotation. Needs `T: Copy` because the value is handed back as the
    /// result while also staying in place, which duplicates it.
    forall C, R where Access[C -> 'k, R].
    fn copy(self, &cx: C) -> T {
        // The same read `with(&cx, |v| (v, v))` performs, without the
        // closure call and the store of an unchanged value.
        let (tag, rest) = Access[C -> 'k, R]::open(cx);
        let { ptr: nn, marker: m } = self;
        let p = nn.as_ptr();
        let v = unsafe *p;
        cx = Access[C -> 'k, R]::close(tag, rest);
        v
    }

    /// Puts `val` in the place; the value there before is dropped, which
    /// `T: Copy` allows. `replace` hands it back.
    forall C, R where Access[C -> 'k, R].
    fn set(self, &cx: C, val: T) {
        let old = self.replace(&cx, val);
    }

    /// A copy of the value, read through one node of the domain's
    /// shared-read tree. Any node
    /// will do: they all permit reading, and none permits writing.
    forall 'q.
    fn read(self, &cx: Shared!['k, 'q]) -> T {
        let { ptr: nn, marker: m } = self;
        let p = nn.as_ptr();
        let v = unsafe *p;
        v
    }

    // There is no scoped, callback-shaped form of a read tree (a `view`
    // or `with_readers(f)` that shares, calls `f`, and resumes). Its
    // callback would have to be `closure(Shared!['k,'q], Ref[T,'k]) ->
    // (Shared!['k,'q], Ret)` with 'q minted by `share` inside the function,
    // and no spelling of that type checks: 'q free in the callback type is
    // not bound by the function's `forall`; 'q bound by the `forall` cannot
    // unify with the sealed fresh brand; and closure types have no
    // higher-rank binders, while `exists` is result-only. The same holds for
    // any freshly branded capability, so every read-tree protocol is written
    // flat at the call site: `share`, `split`, read, `join`, `resume`.
}

forall T, 'r.
impl Region![T, 'r] {
    /// A region over the `T` at `ptr`, under the capability `cap`.
    ///
    /// The way into a region over memory this module did not allocate:
    /// `alloc::owned`'s `Allocation!::adopt`, or a program's own
    /// storage. Caller: `ptr` is not null, also for a zero-size `T` (`share`
    /// makes a `Ref` of it, which is never null), and points at an
    /// initialized `T`, aligned for `T`, in at least `sizeof[T]()` bytes,
    /// that nothing else can reach while 'r lives; and `cap` is the only
    /// capability over 'r -- in practice, fresh from
    /// `Exclusive!::fresh`, so no existing `Ref` of brand 'r describes other
    /// memory. The region's `replace` and `share` read and write the `T`
    /// with no further check.
    unsafe fn from_raw(ptr: *T, cap: Exclusive!['r]) -> Region![T, 'r] {
        Region!.{ ptr, cap }
    }

    /// Ends the region and its domain: the capability is retired, so no
    /// `Ref` of brand 'r can be used again. The storage is untouched;
    /// whoever holds the matching `Allocation!` decides what happens to
    /// it, which is why `release` and `close` take the whole region.
    fn retire(self) -> () {
        let { ptr: p, cap } = self;
        cap.retire()
    }
}

// A separate `impl` block for `replace`'s premise: a raw read or write is
// at a type of non-zero size, which `Sized[T]` says of `T`.
forall T, 'r where Sized[T].
impl Region![T, 'r] {
    /// Reads the contained `T` out and writes a new one in, exactly once
    /// each way: the only access operation a region has that does not give
    /// the region up. There is no `Region!::with`, because `Ref::with`
    /// already has that shape, and getting to a `Ref` is what `share`
    /// (below) is for.
    ///
    /// No witness parameter: holding a `Region![T,'r]` is already proof
    /// that nothing else can touch this block, because a region is linear,
    /// unique, and consumed by every operation that could hand out a second
    /// capability over the same brand -- and `Allocation!::close`/`release`,
    /// which reclaim the storage, demand the region itself.
    ///
    /// Sound for any `T`, `Copy` or linear, for `Ref::with`'s reason: the
    /// previous value is moved out and returned to the caller, `val` is
    /// moved in, and neither is duplicated or discarded here.
    fn replace(&self, val: T) -> T {
        let { ptr: p, ..rest } = self;
        let old = unsafe *p;
        unsafe *p = val;
        self = Region!.{ ptr: p, ..rest };
        old
    }
}

forall T, 'r.
impl Region![T, 'r] {
    /// Splits the region into its capability, a `Ref` to the value, and the
    /// receipt that puts the two back together.
    ///
    /// Trades the region -- one linear value that both describes the block
    /// and authorizes touching it -- for the two-axis split the module
    /// header describes: an `Exclusive!['r]` that authorizes and does not
    /// describe, a `Ref[T,'r]` that describes and does not authorize, and a
    /// `RegionResume![T,'r]` that is the receipt for putting them back
    /// together. No brand is minted: all three carry `self`'s 'r, so the
    /// `Ref` works with `Ref::with`/`Ref::copy` like any other
    /// `Exclusive!`/`Ref` pair, and the `Exclusive!` is the same type every
    /// container threads.
    ///
    /// `share` CONSUMES the region. `close`/`release` demand a
    /// `Region![T,'r]` that, once shared, only `RegionResume!::resume` can
    /// produce -- and `resume` demands this exact witness back. So storage
    /// cannot be reclaimed while the witness is out. The `Ref` left over
    /// after resuming is inert: it is `Copy`, it may outlive everything,
    /// and it authorizes nothing once the `Exclusive!['r]` is gone for good
    /// (brands are never recycled, and `Exclusive!::fresh` mints only fresh
    /// ones).
    fn share(self) -> (Exclusive!['r], Ref[T, 'r], RegionResume![T, 'r]) {
        var { ptr: p, cap } = self;
        let stamp = &cap.stamp();
        let { marker } = stamp;
        // A region's pointer is never null (`from_raw`'s contract).
        let r = Ref.{ ptr: unsafe NonNull::new_unchecked(p), marker };
        let back = RegionResume!.{ ptr: p, marker };
        (cap, r, back)
    }
}

// A separate `impl` block because splitting alone needs premises on `T`:
// `replace`/`share` never look past `T`'s opacity. A method's own `where`
// belongs to a `forall` that binds something, and `split` binds nothing of
// its own, so the premises on the impl's parameter `T` go on an impl block
// of its own. `Exposed[*T]` is the shape authority: `T` is abstract here,
// and `foreach *F of *T` needs to see `T`'s product shape to traverse it
// field by field. `Sized[T]` says `T` has a finite layout of non-zero size:
// a traversal of `*T` for a generic `T` takes it as the evidence that `T`
// has the layout whose field offsets it computes.
forall T, 'r where Exposed[*T], Sized[T].
impl Region![T, 'r] {
    /// Splits the region into the receipt that merges it back and one
    /// sub-region per field of `T`, each under a fresh brand and tied to
    /// the parent by a `Link!`.
    ///
    /// Each sub-region is usable (ordinarily via `Region!::share`) without
    /// any two sub-regions' `Exclusive!`s being interchangeable. `split`
    /// gives up the region's capability to the receipt and builds every
    /// `Link!` from the parent brand read from that capability, so the parts
    /// of one split are made once, here.
    ///
    /// A part does NOT bundle an `Exclusive!`
    /// (`exists 'f. (Exclusive!['f], Region![F,'f], Link!['f,'r])`):
    /// a caller could `Region::share` the
    /// part's region to mint a SECOND live `Exclusive!['f]` beside the
    /// bundled one, and two live writers for one brand is a safe
    /// use-after-free and double free. A part's writer is obtained the
    /// ordinary way, by calling `share` on its `Region![F,'f]`.
    ///
    /// No new brand for 'r: the caller's `Region![T,'r]` already proves
    /// everything needed. The fresh brands the parts are minted under are
    /// the per-field ones, each strictly smaller in scope than 'r.
    fn split(self) -> (Restore![T, 'r], foreach *F of *T => exists 'f. (Region![F, 'f], Link!['f, 'r])) {
        var { ptr: p, cap } = self;
        // The parts' parent brand is this region's own witness, read inside
        // `core` and never handed out.
        let stamp = &cap.stamp();
        let { marker: parent } = stamp;
        let parts = foreach f: F of p {
            let exists 'f. (child, k) = unsafe make_split_part[F](f);
            pack 'f. (child, Link!.{ child: k, parent })
        };
        (Restore!.{ ptr: p, cap }, parts)
    }
}

/// A region over `field` under a fresh brand, and that brand:
/// `Region!::split`'s per-field step. A separate function, not inlined in
/// `split`'s `foreach` body, because the `exists 'f. (...)` a `foreach`
/// component produces must be a SEALED RETURN: `Exclusive!::fresh` mints and
/// seals one brand per call.
///
/// It mints the child brand and hands back only that, never a `Link!`. A
/// helper taking the PARENT brand as a parameter and returning a `Link!`
/// would forge authority: a `Brand['r]` is `Copy` and readable off any live
/// `Ref` naming 'r, so it proves nothing about holding 'r. `split` instead
/// reads the parent brand from the region's own `Exclusive!['r]` and builds
/// each `Link!` itself.
///
/// `unsafe fn` because it takes a raw pointer that is trusted, unvalidated,
/// and immediately wrapped in a `Region!`, and any module can call it, not
/// only `split`. Caller: `field` addresses initialized storage of `Field`
/// that no other live capability covers, as for `Region!::from_raw`. `split` meets it with field pointers computed by
/// `foreach` over a region it gave up exclusively. The part returned
/// carries only its own fresh brand; since `Link!` is built by `split`
/// alone, a part over unrelated storage can never be merged into a parent.
forall Field.
unsafe fn make_split_part(field: *Field) -> exists 'f. (Region![Field, 'f], Brand['f]) {
    let exists '1. (k, cap) = Exclusive!::fresh();
    let child = Region!.{ ptr: field, cap };
    pack '1. (child, k)
}

forall T, 'r.
impl RegionResume![T, 'r] {
    /// The region again, from the capability `share` handed out with this
    /// receipt.
    ///
    /// `Region!::share`'s exact inverse, and the only producer of a
    /// `Region![T,'r]` for an 'r that `adopt` has already sealed.
    ///
    /// Demands the EXACT witness, not merely an `Exclusive!` of the same
    /// shape: 'r is fixed by `self`'s type, and the only `Exclusive!['r]`
    /// that ever exists for it is the one `share` returned beside this
    /// receipt. An `Exclusive!` from another region carries another brand
    /// and does not unify, and one cannot be forged from a copied `Brand`.
    ///
    /// Both weaker signatures would be unsound:
    ///
    ///   fn resume(self) -> Region![T,'r]
    ///       hands the region back with the witness still live: resume,
    ///       `close`, free, then read through a surviving `Ref`.
    ///   forall 'q. fn resume(self, w: Exclusive!['q]) -> Region![T,'r]
    ///       demands a witness, just not THIS one: discharge region A's
    ///       receipt with region B's witness, free A, read A.
    ///
    /// The pointer comes from `self`, never from a `Ref`. A `Ref[T,'r]` is
    /// `Copy` and may name any element (`Slice::get_ref`), so if `resume` took one,
    /// a caller could rebuild the region over an interior element and hand
    /// THAT to `close`. It takes the witness, which carries no pointer, and
    /// reads the base out of the receipt, which is linear, restricted and
    /// unprojectable.
    fn resume(self, w: Exclusive!['r]) -> Region![T, 'r] {
        let { ptr: p, marker: m } = self;
        Region!.{ ptr: p, cap: w }
    }
}

// `where Exposed[*T], Sized[T]`: `merge`'s `foreach` maps `parts`, a value
// of a `foreach` type over `*T`, and a map needs the shape of that source,
// as the traversal of the pointer in `split` does.
forall T, 'r where Exposed[*T], Sized[T].
impl Restore![T, 'r] {
    /// The parent region again, from every part `Region!::split` made.
    ///
    /// `Region!::split`'s exact inverse. Consumes the WHOLE product -- every
    /// part, in whatever order the caller hands them back -- and `self`, the
    /// receipt `split` kept. Four properties carry the soundness:
    ///
    ///   1. `Link!` names both brands (see the struct).
    ///   2. `Restore!` is one-shot: it is consumed by value here, so a
    ///      second `merge` on the same receipt is unspellable.
    ///   3. No public operation consumes a single `Link!` in isolation: the
    ///      only way to discharge one is inside this `foreach`, which maps
    ///      the whole product together with `self`, or not at all (a map
    ///      consumes each component of its operand exactly once, and a
    ///      product holding linear parts cannot be dropped).
    ///   4. The returned `Region![T,'r]` is rebuilt from `self`'s own
    ///      pointer and capability, never from a part, since parts are
    ///      permutable (see `Restore!`).
    ///
    /// Each part is destructured only to CONSUME it: the child's
    /// capability is retired and its link discarded. Nothing about the
    /// child's pointer or brand flows into the rebuilt parent; that pointer
    /// addresses one field, not the whole block. What the map makes,
    /// `foreach *F of *T => ()`, is `Copy`, as its body mentions no `F`.
    fn merge(self, parts: foreach *F of * T => exists 'f. (Region![F, 'f], Link!['f, 'r])) -> Region![T, 'r] {
        let { ptr: p, ..rest } = self;
        let done = foreach part of parts {
            let exists 'f. (child, link) = part;
            let { ptr: cp, cap: child_cap } = child;
            let retired = child_cap.retire();
            let { child: lc, parent: lp } = link;
            ()
        };
        Region!.{ ptr: p, ..rest }
    }
}