← core

core/cap.kur

//! Branded access capabilities: one exclusive writer or a tree of shared readers.
// Resource-neutral access capabilities. A brand identifies a domain, while
// the linear token carries authority over it. The brand is Copy and grants
// no access by itself; a resource's own module must ensure that every safe
// access path is gated by the matching capability.
//
// Exclusive!['r] is the sole writer for a fresh domain. Sharing consumes it
// and creates the root of a read-only tree. Each split consumes one shared
// node and returns two freshly identified children plus a join receipt.
// Only the reassembled root can be turned back into Exclusive!['r].
//
// These types prove how access tokens are used, not that a pointer or an OS
// object was uniquely owned when branded. Resource constructors must
// establish that separate invariant themselves.

use package as core;

// A brand's witness type, `Brand['r]`: Copy, zero-size, and the only value
// that names brand 'r. `fresh()` mints a brand no other value has, returned
// as `exists 'r. Brand['r]`; `unsafe static_brand()` is the witness of
// 'static, whose obligation is that what it brands lives forever.
export builtin::{Brand, fresh, static_brand};

/// The sole read and write capability for domain `'r`.
forall 'r.
struct Exclusive! {
    marker: Brand['r],
}

/// A shared read capability for domain `'r`: one node `'q` of a tree of
/// readers.
///
/// Every shared node carries two brands, and the distinction is the design:
///
///   'r   the DOMAIN brand, the same one its `Exclusive!['r]` carries. It
///        never changes anywhere in the tree.
///   'q   the LINEAGE brand, minted fresh by `share` and twice by every
///        `split`. It names one specific node of one specific tree.
///
/// With the domain brand alone every node would be interchangeable, and the
/// writer could come back from ONE half of a split while the other half still
/// reads: share, split, resume from a leaf, free the resource, read through
/// the sibling.
/// `SharedResume!['r,'q]` instead demands the root node `Shared!['r,'q]` by
/// identity, and a leaf's sealed, freshly minted lineage cannot unify with
/// 'q. The rejection is an ordinary type mismatch, with no special rule.
forall 'r, 'q.
struct Shared! {
    marker: Brand['r],
    lineage: Brand['q],
}

/// The receipt a `Shared!::split` keeps back, which `join` turns the two
/// children back into their parent.
///
/// The join receipt names all FOUR brands: domain, parent, and both
/// children. The obvious simplification, a receipt naming only its parent
/// with `join` generic over the children, re-admits a nested-split attack:
/// split the root, split one child again, then discharge the OUTER receipt
/// with the INNER pair. The parent brand matches, so the writer comes back
/// while a sibling leaf of the first split is still live. Naming both
/// children pins each receipt to the exact pair its own split produced.
forall 'r, 'q, 'a, 'b.
struct SharedJoin! {
    marker: Brand['r],
    parent: Brand['q],
    left: Brand['a],
    right: Brand['b],
}

/// The receipt `Exclusive!::share` keeps back, which `resume` turns the
/// root of the shared tree back into the `Exclusive!['r]`.
forall 'r, 'q.
struct SharedResume! {
    marker: Brand['r],
    lineage: Brand['q],
}

impl Exclusive! {
    /// A capability for a new domain, with that domain's brand.
    ///
    /// The only minting path. Freshness prevents an existing domain from
    /// acquiring a second Exclusive! token through a copied Brand.
    fn fresh() -> exists 'r. (Brand['r], Exclusive!['r]) {
        let exists 'r. brand: Brand['r] = fresh();
        pack 'r. (brand, Exclusive!.{ marker: brand })
    }
}

// The domain's brand, sealed for this package: `core` modules open a stamp
// to build objects in the token's domain (an empty or literal `Str`, a
// region's `Ref`), while code outside `core` can hold one but never read
// the brand out of it. A witness taken from the capability alone would let
// anyone plant objects in a domain; inside `core` that is the point.
/// A domain's brand, sealed so that only `core` can read it.
forall 'r.
exposed (package) struct Stamp {
    marker: Brand['r],
}

forall 'r.
impl Exclusive!['r] {
    /// The domain's brand, sealed in a `Stamp` that only `core` can open.
    fn stamp(&self) -> Stamp['r] {
        Stamp.{ marker: self.marker }
    }

    /// Trades the capability for the root of a tree of shared readers and the
    /// receipt that turns that root back into it.
    fn share(self) -> exists 'q. (Shared!['r, 'q], SharedResume!['r, 'q]) {
        let { marker: brand } = self;
        let exists 'q. lineage: Brand['q] = fresh();
        pack 'q. (Shared!.{ marker: brand, lineage }, SharedResume!.{ marker: brand, lineage })
    }

    /// Ends the capability.
    ///
    /// A resource's finalizer can consume its exclusive token here after
    /// retiring the protected state. This does not deallocate anything.
    fn retire(self) -> () {
        let { marker } = self;
        ()
    }
}

/// A context that lends the capability of domain `'k`: the `Exclusive!['k]`
/// itself, or a value holding it, such as an arena with its capability
/// (`alloc::arena::Domain!`) or a program's own context. Code that reads or
/// writes the domain takes `&cx: C` with `where Access[C -> 'k, R]`, opens
/// it for the capability, and closes it again before it returns:
///
///     let (tag, rest) = Access[C -> 'k, R]::open(cx);
///     ... &tag ...
///     cx = Access[C -> 'k, R]::close(tag, rest);
///
/// `R` is what the context holds besides the capability, handed back whole.
/// The capability is really taken out and put back, never assumed: an
/// instance cannot make an `Exclusive!['k]` it does not hold.
forall Self -> 'k, R.
trait Access {
    /// The capability taken out of `cx`, and the rest of the context.
    fn open(cx: Self) -> (Exclusive!['k], R);
    /// The context again, from the capability and the rest `open` returned.
    fn close(tag: Exclusive!['k], rest: R) -> Self;
}

/// An `Exclusive!` lends itself, with nothing else held.
forall 'k.
instance Access[Exclusive!['k] -> 'k, ()] {
    fn open(cx: Exclusive!['k]) -> (Exclusive!['k], ()) {
        (cx, ())
    }

    fn close(tag: Exclusive!['k], rest: ()) -> Exclusive!['k] {
        tag
    }
}

forall 'r, 'q.
impl Shared!['r, 'q] {
    /// Two fresh shared readers in place of this one, and the receipt that
    /// joins them back.
    fn split(self) -> exists 'a, 'b. (Shared!['r, 'a], Shared!['r, 'b], SharedJoin!['r, 'q, 'a, 'b]) {
        let { marker: brand, lineage: parent } = self;
        let exists 'a. left: Brand['a] = fresh();
        let exists 'b. right: Brand['b] = fresh();
        pack 'a, 'b. (Shared!.{ marker: brand, lineage: left }, Shared!.{ marker: brand, lineage: right }, SharedJoin!.{ marker: brand, parent, left, right })
    }
}

forall 'r, 'q, 'a, 'b.
impl SharedJoin!['r, 'q, 'a, 'b] {
    /// The parent node again, from the two children its split produced.
    fn join(self, left_node: Shared!['r, 'a], right_node: Shared!['r, 'b]) -> Shared!['r, 'q] {
        let { marker: brand, parent, left, right } = self;
        let { marker: left_brand, lineage: left_lineage } = left_node;
        let { marker: right_brand, lineage: right_lineage } = right_node;
        Shared!.{ marker: brand, lineage: parent }
    }
}

forall 'r, 'q.
impl SharedResume!['r, 'q] {
    /// The `Exclusive!['r]` again, from the root of the shared tree.
    fn resume(self, root: Shared!['r, 'q]) -> Exclusive!['r] {
        let { marker: brand, lineage: lineage } = self;
        let { marker: root_brand, lineage: root_lineage } = root;
        Exclusive!.{ marker: brand }
    }
}