Files
aji/docs/agent/quick-reference.md
T

31 KiB
Raw Blame History

Aji Quick Reference (.aji 0.1)

Read this first; it covers most programs. Where to find the full rules is at the end. Every example below is part of a program the conformance suite checks. aji check file.aji verifies, aji run file.aji verifies and runs, aji lower file.aji prints the AIR it becomes. aji fmt file.aji prints formatted source; --check checks formatting, --write replaces the file. Formatting preserves tokens and comments; it does not verify or repair code. Diagnostics are JSON lines; fix the first one first.

Aji makes every significant action explicit — moves, borrows, allocation, closing, authority, effects, tasks, channel transfers, locking, cancellation, every failure outcome — and checks them all before running. The compiler writes the mechanics: SSA, control flow, borrow ends, frame storage, the feature header.

1. Skeleton

module demo.echo

fn main(input: cap<io.read>, out: cap<io.write>) -> void
effects [io.read, io.write]
{
    var buf: [u8; 64] = zero;
    loop {
        let n = io.stdin_read(input, mut buf) or trap;
        if n == 0 { return; }
        io.stdout_write(out, ref buf[0..n]) or trap;
    }
}
  • main's parameters are capabilities, granted by name: aji run --grant input=io.read --grant out=io.write --stdin 'hi' main.aji.
  • Every function lists its effects after the signature. A missing effect is E3101, whose suggested_effects field is the full list to write.
  • Statements end with ;; block statements do not require one. A bare if, match or {…} at statement/tail start ends at its final }. Parenthesize it to continue with an operator. Before another statement it must yield void or diverge; use ; to explicitly discard a value (E7006 otherwise). Initializers, returns and arguments use ordinary expression parsing.

2. Types

Type Notes
u8 … u128, usize, i8 … i128, isize, bool no implicit conversion
[T; N] array; [e; N] repeats e
struct P { a: u8, b: u8 } P { a: 1, b: 2 } (every field, any order), p.a
enum E { A, B(u64), C(u8, u8) } E::A, E::B(4); match with one arm per variant: E::A => …, E::B(x) => …, E::C(x, y) => … (no _)
ref<T>, mut<T>, slice<T>, slice_mut<T> borrows (§4)
own<T>, own_array<T>, region heap and regions (§6)
cap<K> authority; kinds below
file<read>, file<write>, file<append>, listener, stream linear resources
island<T>, frozen<T>, arc<T>, iref<T> object graphs (§7)
task<T>, sender<T>, receiver<T>, mutex<T> concurrency (§8)
io_error, alloc_error, cap_error built-in error enums

f32/f64 are reserved in AIR (E0006, reserved_type) and unavailable in .aji 0.1 (E7002); floating-point semantics remain Q-016.

Linear values (resources, own, region, task, endpoints, mutex) are consumed exactly once. Everything else that is a plain value is copyable.

3. Statements and expressions

let x = a + b;                 // immutable
var i: usize = 0;              // variable; reassign with i = i + 1;
var buf: [u8; 16] = zero;      // zero-initialized storage
if c { … } else if d { … } else { … }
while i < n { … }
for k in 0..n { … }            // 0 ≤ k < n
loop { … break; … continue; … }
let y = if c { 1 } else { 2 };          // value-producing if/match: tail expression without `;`
let w: u64 = match m {                  // enum match: exhaustive, one arm per variant
    Message::Stop => 0,
    Message::Value(v) => v,             // v exists only in this arm
};
match t { 0 => { … } 1 => { … } _ => { … } }   // integer match: `_` required
assert(c);                     // traps T0002 when false
return x + y + w;              // also: `trap;`
Operation Meaning
+ - * / % checked: overflow traps T0003, division by zero T0004
+% -% *% wrapping
& | ^ << >> bitwise; shift ≥ width traps T0005
== != < <= > >=, and or not comparisons, booleans
x as T lossless widening only (else E1002)
x as! T checked conversion, traps T0006
x as% T wrapping conversion
42, 42u8, 0xff, 1_000 literals; type from context or suffix (else E7007)
b"text\n" byte string, [u8; N]

There is one spelling per construct: no +=, no alternative syntax.

4. Borrows and moves

var data: [u64; 8] = zero;
data[0] = 7;                   // element write (array variables get frame storage automatically)
{
    mut s = data;              // exclusive borrow to the end of this block (an array is borrowed as slice_mut<u64>)
    s[1] = s[0] + 1;           // checked index; out of range traps T0008
    let n = s.len;
    if i < s.len { s[i] = 0; } // no runtime check here: the verifier proves i < s.len
    let (l, r) = s.split_at(4);   // two disjoint halves of s
    …
}
slice.copy(mut out[0..4], ref data[4..8]);   // borrows as arguments end after the call
…
ref q = p;                     // shared borrow of a struct; q.a reads a field
…
*c = *c + 1;                   // through c: mut<u64>

Rules (checked by the verifier):

  • A borrow lives until the end of the block where it was bound (ref r = …; / mut r = …;). A borrow written as an argument (f(mut buf)) lives for that call. To end one early, put it in an inner { … } block.
  • Exclusive XOR shared. While a mut borrow of a place is live, no other borrow of the same place, and no direct use of it, is allowed (E2101). Disjoint fields and split_at halves are independent.
  • A borrow cannot outlive what it borrows from (E2102). A function returns a borrow only with explicit from param. Bind returned views with ref/mut; the from argument must be a named borrow. Return the bound name without move; a local-frame view cannot escape (E2108).
  • Moves are explicit: a named linear value is consumed only as move x (otherwise E7003). A fresh temporary needs no move: consume(make()). Copyable values are passed plainly; move on them is E7006.
  • Use after move is E2001, use after close/free/take E3001, a second consumption E2002, and a linear value never consumed E3002. Every path must consume it, including early returns.
  • Index proofs: inside if i < s.len { … } the access s[i] needs no runtime check.

Returned views (details in /docs/language/ownership.md):

fn first(s: slice<u64>) -> ref<u64> from s effects [] { ref item = s[0]; return item; }
fn main() -> u64 effects [] { let data = [42u64, 7u64]; ref s = data; ref item = first(s); return *item; }

5. Failure: every outcome is a match arm

match fs.open_read(c, b"/data/in.txt") {
    ok(f) => { …; fs.close(move f) or trap; }
    err(e) => { return 1u8; }
}
…
let n = net.recv(conn, mut buf) or trap;      // any non-ok outcome traps
  • Arms are named after the outcomes and the match must cover all of them (E7004).
  • or trap is the only shorthand: it takes the ok value and traps on anything else.
  • err(e) binds a real io_error. Match it like any enum, every variant and no _: match e { io_error::not_found => …, io_error::permission_denied => …, … }, or just trap.
  • Closing consumes the resource on both outcomes.

6. Authority, allocation, I/O

Capabilities are only ever received (as main parameters, passed down as arguments) or narrowed. They are copyable. A capability is needed only to acquire: the file or stream you get back carries the authority, so fs.read(f, mut buf) takes no capability. Pass a resource by name (the call borrows it); pass data with explicit ref/mut. Paths are byte strings: b"/in/data.txt".

Kind (cap<K>) Effect Operations (all fallible unless noted)
io.read / io.write same io.stdin_read(c, mut buf) → ok(n); io.stdout_write(c, ref bytes), io.stderr_write(c, ref bytes)
fs.read / fs.write same fs.open_read(c, path) → ok(f), fs.create(c, path), fs.open_append(c, path); fs.read(f, mut buf) → ok(n); fs.write_all(f, ref bytes); fs.sync(f); fs.close(move f)
net.listen / net.connect same; net.recv needs net.read, net.send_all needs net.write net.listen(c, b"127.0.0.1:7") → ok(l); net.accept(l) → ok(s); net.connect(c, addr) → ok(s); net.recv(s, mut buf) → ok(n) (0 = closed); net.send_all(s, ref bytes); net.close_stream(move s); net.close_listener(move l)
narrowing — cap.narrow.prefix(c, b"/data/logs") → ok(c2) / err(e: cap_error) (fs.read, fs.write)
clock.read, random.read same clock.monotonic(c) (infallible, u64); random.fill(c, mut buf) (infallible)
mem.alloc mem.alloc own.new(v, heap) → ok(o) / err(e); own.array(n, v, heap); own.take(move o), own.free(move o); region.create(heap) → ok(r); ref arena = r; then region.new(arena, v) → ok(p), region.array(arena, n, v); region.reset(r); region.destroy(move r); cap.narrow.budget(heap, n) → ok(small) / err(e)

A region allocation needs an explicit borrow of the region that outlives the allocations; region.reset/region.destroy while one is live is E2104, so end it first with a block:

{
    ref arena = r;
    let item = region.new(arena, 1u64) or trap;   // item: mut<u64>, ends with this block
    *item = *item + 1;
    …
}
region.reset(r);

err(e) binds a real value: match e { alloc_error::budget_exceeded => …, alloc_error::out_of_memory => … }.

Built-in errors are Copy data: let e = alloc_error::budget_exceeded; constructs a payload-free value without effects, allocation or authority. All registered alloc_error, cap_error and io_error variants work this way (spec 05 §14).

  • Narrowing: cap.narrow.prefix(c, b"/data") and cap.narrow.budget(heap, 4096), each giving ok(c2) / err(e).
  • Resource operands (f, s, l, endpoints) are borrowed automatically for an operation; a region is not (bind ref arena = r;); data borrows (mut buf, ref bytes) are always written.
  • Memory budgets count live bytes, so freeing returns them. In the deterministic profile mem.alloc needs a grant with a budget: --grant heap=mem.alloc:4096.

7. Graphs: island → frozen → arc

Choose by intent:

  • change a graph → island<T>;
  • read it in parallel → frozen<T>;
  • give it several independent owners → arc<T>.

Objects are addressed by iref<T> handles: copyable, compared only with ==/!=, cycles allowed. A graph holds only plain data and irefs (E2111 otherwise).

let isl = island.create(Node { value: 1, next: Link::End }, heap) or trap;   // effect mem.alloc
{
    mut g = isl;                                // borrow the island; it outlives the accesses
    let a = island.root(g);
    let b = island.alloc(g, Node { value: 2, next: Link::To(a) }) or trap;
    mut first = island.at(g, a);                // mut<Node>; one mutable access at a time
    first.next = Link::To(b);                   // edges may form cycles
}
let f = island.freeze(move isl);                // O(1), irreversible; irefs stay valid
…
    ref fr = f;                                 // frozen graphs are Share: lend fr to tasks
    let a = frozen.root(fr);
…
let shared = arc.from_frozen(move f);           // O(1); the same graph
let other = arc.clone(shared);                  // count + 1
arc.release(move other);                        // the last release frees the graph
  • island.at, frozen.at and arc.at appear only as ref x = …;/mut x = …;, with a named borrow of the owner (mut g = isl;, ref fr = f;), as for regions. frozen.at and arc.at give ref only.
  • An iref from another graph traps T0010.
  • Ownership:
    • an island is Send, not Share: move it through channels or spawn, or freeze it to share;
    • frozen and arc are Send and Share.
  • Every owner is consumed once:
    • an island by island.destroy(move i) or island.freeze;
    • a frozen graph by frozen.release or arc.from_frozen;
    • each arc handle by arc.release.
  • create, alloc and arc.new charge the mem.alloc budget. The bytes come back when the graph is freed.

8. Concurrency

Tasks, channels, select, lock/mutex, shield and the cancellation operations all work.

mut d = data;                                   // data: [u64; 8]
scope s {                                       // every task spawned in s must be joined before the block ends (E4301)
    let (l, r) = d.split_at(4);
    let a = task.spawn(s, square, l);          // borrows are lent to the task until its join
    let b = task.spawn(s, square, r);
    let x = task.join(move a);
    let y = task.join(move b);
    …
}
  • Spawning:

    • a scope name is only the first operand of task.spawn; no aliases, move or ordinary value use (E7006);
    • effect task.spawn;
    • a value moved into a task must be Send, and data shared by ref must be Share (E4001, E4002);
    • two live tasks may not hold overlapping mut loans (E4101);
    • while lent, a borrow cannot be ended or used conflictingly (E4302, E4101).
  • Cancellation:

    • task.cancel(t) only requests it;
    • task.cancelled() reads the flag;
    • match task.check_cancel() { ok => …, cancelled => … };
    • match task.join_cancel(move t) { ok(v) => …, cancelled(t) => { task.cancel(t); let v = task.join(move t); … } };
    • shield { … } defers cancellation.
  • Waiting requires the effect task.wait. A wait completes immediately when it can; it takes cancelled only if it would otherwise wait.

  • Channels (bounded; capacity 0 = rendezvous; several senders, one receiver):

    match channel.make<u64>(2, heap) {          // effect mem.alloc
        ok(tx, rx) => {
            let tx2 = channel.dup(tx);                // another sender; close it too
            …
            match channel.send(tx, v) { ok => {} closed(v) => { … } cancelled(v) => { … } }   // a linear v: `move v`
            match channel.recv(rx) { ok(v) => { … } closed => { … } cancelled => { … } }
            channel.close_sender(move tx);
            match channel.close_receiver(move rx) { ok => {} pending(rx) => { … } }   // drain, then close again
        }
        err(e) => { trap; }
    }
    
    • A value is the sender's again on closed(v) and cancelled(v).
    • The receiver sees closed only after the buffer is empty and every sender is closed.
    • close_receiver with buffered values hands the receiver back as pending(rx): drain it, then close again.
  • Select:

    select {
        recv(rx_a) { ok(x, job) => { … } closed(job) => { … } }
        send(tx_b, move job) { ok => { … } closed(job) => { … } }
        cancelled(job) => { … }
    }
    

    Among ready arms, the scheduler's seeded choice decides. Every edge where job was not sent binds it back, after the edge's own value: ok(x, job).

  • Mutex:

    let m = mutex.make(0u64);
    lock ref m as count {                        // count: mut<u64>; unlocked at every exit of the block
        *count = *count + 1;
    } cancelled { … }
    let total = mutex.take(move m);              // needs no live borrow of m
    

    Inside a lock block no operation may wait or spawn, and no function may be called whose effects include task.wait or task.spawn (E4304). One lock at a time, so lock-order deadlocks cannot happen.

  • Atomics (the last resort, after channels and mutexes):

    let count = atomic.new(0u64);                // atomic<T>: bool or an integer up to 64 bits; linear
    {
        ref c = count;                           // every operation takes `ref`; lend `c` to tasks
        let old = atomic.add.wrap(c, 1u64, relaxed);   // swap, add.wrap, sub.wrap, and, or, xor return the old value
        atomic.store(c, 5u64, release);
        let v = atomic.load(c, acquire);
        let (prev, exchanged) = atomic.compare_exchange(c, 5u64, 6u64, acq_rel, acquire);
        atomic.fence(seq_cst);
    }
    let total = atomic.take(move count);         // needs no live borrow of count
    
    • Every operation names its ordering (E4201 otherwise):
      • load: relaxed, acquire, seq_cst;
      • store: relaxed, release, seq_cst;
      • read-modify-write: any of the five;
      • fence: acquire, release, acq_rel, seq_cst;
      • compare_exchange failure ordering, by success ordering: relaxed → relaxed; acquire or acq_rel → relaxed, acquire; release → relaxed; seq_cst → relaxed, acquire, seq_cst.
    • Effects:
      • seq_cst only: effects [atomic], and every run is an interleaving;
      • any other ordering: effects [atomic, atomic.weak].
    • Publication:
      • the writer does atomic.store(data, v, relaxed); atomic.store(flag, true, release);;
      • a reader whose atomic.load(flag, acquire) is true then sees data.
    • *c is E4202: read a cell with atomic.load(c, …).

9. Common diagnostics → repair

Code Meaning Usual repair
E7001 syntax check ;, braces, => in match
E7002 unknown name spelling; declare the variable or function
E7003 linear value consumed without move write move x (or borrow it with ref/mut if it must stay)
E7004 match not exhaustive add the arms listed in missing (integers: add _)
E7005, E1001 type mismatch convert with as, as!, as%; check borrow vs value
E7007 ambiguous literal add a suffix (0u64) or a type annotation
E2101 conflicting borrows end the first borrow earlier with an inner { } block
E2102 borrow outlives its source borrow later, or return from param
E2001, E3001, E2002 used after move / after consume / twice restructure so each linear value is consumed once on every path
E3002 linear value leaked consume it (close, free, take, join, send) on every path, including return
E3101 effect not declared copy suggested_effects into effects [...]
E7006 invalid source construct inspect stable reason; move_copy means an explicit move of a Copy value, move_borrow a move of a borrow
E3201 wrong capability kind pass the right cap<K>
E4001, E4002 not Send / not Share move owned data into tasks; share only Share data by ref
E4101 data race with a task lend disjoint parts (split_at, fields) or join first
E4301 task not joined at scope end task.join(move t) before the scope block ends
E4304 wait inside lock move the wait out of the lock block
E4201 ordering not valid for the operation use one listed in allowed
E4202 ordinary read of an atomic cell atomic.load(c, ordering)
E2111 graph content not plain data store only integers, booleans, enums, structs/arrays of them and irefs in a graph
T0010 iref of another graph use a handle with the graph it came from
T0001–T0009 runtime trap see kind and source_location

E2101/E2104 related_locations identifies the selected conflicting borrow; E4302 identifies its task's spawn. Use the source position when present; an unmapped record retains AIR coordinates and the SSA identity. These are facts, not repair instructions.

10. Standard library

Import a bundled module after the module header; call its functions by their full path. std.bytes and std.math are safe source, declare effects [] and allocate no heap. No grants are needed. Read /docs/library/std.md for the API.

module demo.standard
import std.bytes;
import std.math;

fn main() -> u64
effects []
{
    var data: [u8; 4] = zero;
    std.bytes.fill(mut data, 65);
    assert(std.bytes.equal(ref data, b"AAAA"));
    let index = std.bytes.find(ref data, 65);
    if index < data.len { assert(data[index] == 65); }
    return std.math.clamp_u64(42, 0, 100);
}

find returns the searched slice's length when absent; check before indexing. clamp_u64 traps T0002 for an inverted range. Missing import/module/member: E7002; duplicate import: E7006; wrong arguments: E7005. Aliases are unavailable; explicit generics use §12.

Endian reads/writes cover u16/u32/u64 in LE and BE. Pass a sub-slice for an offset. Reads return std.bytes.ReadUW with ok(uW)/short_input; writes return std.bytes.WriteResult with ok/short_output. A short destination is unchanged. Handle them with qualified enum patterns (not intrinsic outcome patterns):

match std.bytes.write_u32_be(mut wire[1..5], 0x12345678) {
    std.bytes.WriteResult::ok => {}
    std.bytes.WriteResult::short_output => { return 0; }
}
match std.bytes.read_u32_be(ref wire[1..5]) {
    std.bytes.ReadU32::ok(value) => { return value; }
    std.bytes.ReadU32::short_input => { return 0; }
}

The usual enum rules apply: missing arm E7004, wrong enum/payload E7005, unknown type/variant E7002. See /docs/library/std.md for signatures.

std.bytes.copy returns WriteResult; short output is unchanged and overlap rejects. find_slice returns FindResult::found(index) / not_found (empty needle: found at 0). Recoverable u64/usize arithmetic, split composition and a checked example are in /docs/library/std.md; wrapping stays +%, -%, *%.

std.utf8 validates bytes and decodes the next scalar with an explicit consumed count. std.encoding.hex and std.encoding.base64 encode/decode into mut output slices; ordinary enum results expose malformed input and short capacity, leaving output unchanged on errors. Base64 accepts canonical padded standard encoding. Signatures and a checked example are in /docs/library/std.md.

std.fmt.write_u64/i64/usize/isize write decimal integers into supplied output slices; WriteResult::ok(count) / short_output expose capacity, with unchanged output on failure. Composition and signatures are in /docs/library/std.md.

std.hashmap.HashMap<K,V,fn hash,fn equal> supports general owning keys/values through explicit pure ref-key operations (§12). Insert returns replaced/full key/value pairs; remove/pop move both out, get requires only V: Copy, growth is explicit and free returns nonempty maps. Full contracts are in /docs/library/std.md.

std.hashset.HashSet<K,fn hash,fn equal> uses the same policies for complete owning keys. Insert returns present(input) for duplicates, preserving the stored key, or full(input); remove/pop move stored keys out. Only new/reserve allocate with explicit authority; free returns nonempty sets. Full contracts are in /docs/library/std.md.

std.heap.BinaryHeap<T,fn before> binds pure fn(ref<T>,ref<T>)->bool effects [] as a stable strict weak order. Push returns full input; pop moves the priority root; peek requires T: Copy. Only new/reserve allocate with explicit authority; free returns nonempty heaps. Ties have no stable-order guarantee. Full contracts are in /docs/library/std.md.

std.io supplies exact stdin/file/stream reads, bounded file read-to-end and limited file copy/append with caller slices and explicit effects/authority. EOF differs from full/limit; errors report confirmed progress. Resources stay borrowed, no heap or close is hidden, and failed external writes may be partial. Full contracts are in /docs/library/std.md.

std.io.reader/std.io.writer own a file and an explicitly allocated fixed byte buffer. Use new, read/read_exact or write/flush, then finish to return the file for explicit close. Unread/failed finish returns the whole adapter; discard explicitly abandons buffered bytes and frees storage. A failed writer preserves its first error and never retries. Capacity zero uses direct I/O. Effects and ownership remain explicit; see /docs/library/std.md.

std.path provides pure slash-based is_absolute/basename/parent/extension and supplied-buffer normalize/join. Queries return Copy Range{start,end}; explicitly borrow that range from the original path. Writers preserve output on error and return the successful prefix size, with no heap or filesystem authority. Dot/parent and root rules are in /docs/library/std.md.

std.hash.fnv1a64 and crc32c hash byte slices without allocation; their _extend forms continue from a previous result. Hashes do not establish key equality or authentication. Exact algorithms and chunk/byte-order conventions are in /docs/library/std.md.

11. Package modules

Declare package inputs explicitly in aji.toml:

[package]
entry = "main.aji"
[modules]
app.model = "model.aji"

model.aji declares module app.model. Import it directly; functions, structs and enums use full names. Short names stay local to their defining module; imports grant no authority or transitive name visibility.

module app.entry
import app.model;

fn main() -> u64
effects []
{
    let pair = app.model.Pair { left: 20, right: 22 };
    return app.model.total(pair);
}

Use aji check|lower|report|run|explore --manifest aji.toml; run and explore instantiate manifest grants. A file-only command does not discover packages. Qualified workers work in task.spawn(s, app.work.run, args) with ordinary move, borrow and join rules. Missing/direct-import names: E7002; cycles/header mismatch/duplicates: E7006. Read /docs/language/modules.md for limits and file-loading rules. lower --stats counts entry source against combined AIR, so it is not a whole-package size metric.

12. Generics

Declare type parameters on functions, structs or enums: <T>, <T: Copy> or <T: Copy + Send>. Every use supplies all types: Pair<u64> in annotations, Pair::<u64> { ... }, identity::<u64>(42) and Option::<u64>::some(42) in expressions/patterns. Qualified forms require a direct import. No inference, traits, defaults or overloads. task.spawn(s, worker::<u64>, args) specializes a static worker with the ordinary ownership/effect rules.

module demo.generic
import std.option;

fn identity<T: Copy>(value: T) -> T effects [] { return value; }

fn main() -> u64 effects [] {
    let value = std.option.Option::<u64>::some(identity::<u64>(42));
    match value {
        std.option.Option::<u64>::some(n) => { return n; }
        std.option.Option::<u64>::none => { return 0; }
    }
}

std.option.Option<T> has some(T)/none; std.result.Result<T, E> has ok(T)/err(E). is_some::<T> and is_ok::<T, E> classify Copy specializations; match to extract payloads. Owning payloads follow §13; borrowed payloads reject. Unknown names: E7002; missing/extra arguments, duplicate/unknown constraints or expansion limits: E7006; unsatisfied constraints: E7005 with parameter, constraint, found. Borrow conflicts, moves, effects and cleanup keep their existing rules.

Each required specialization is checked as concrete code; an unused template body is not a proof for future types. Copy gives no arithmetic or ordering operation. Read /docs/language/generics.md for exact Copy/Send/Share/Freeze/Local rules, deterministic keys and fixed limits; /docs/library/std.md for option/result contracts.

An operation is an explicit static parameter, with exact parameter/return types and effect set. Select a declared function with fn path (generic: fn path::<args>); fn F forwards a bound operation. It has no runtime value or captures; F is only a direct call or task.spawn worker. Different operations produce distinct nominal instances. Mismatch: E7005; escaping/shadowing F or borrowed return contracts: E7006. Effects and capability arguments remain explicit.

module demo.static_functions
fn identity(value: u64) -> u64 effects [] { return value; }
fn apply<T, F: fn(T) -> T effects []>(value: T) -> T effects [] {
    return F(move value);
}
fn main() -> u64 effects [] { return apply::<u64, fn identity>(42u64); }

13. Linear aggregates

A struct/enum/fixed array containing owners or resources is linear. Construct with move; consume it completely. Read Copy fields normally. A linear enum needs exhaustive match move; even none must be consumed. No partial moves or automatic cleanup.

struct Item { owner: own<u64> }
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {
    let owner = own.new(42u64, heap) or trap;
    let value = Item { owner: move owner };
    let (part) = struct.unpack(move value);
    return own.take(move part);
}

[move a, move b] constructs ordered array elements; let (a,b) = array.unpack(move data); extracts every element. value.swap(mut place, move replacement) returns the old complete value. own.pack(move value, heap) has ok(owner) and err(error, original_value); own.take extracts linear content, while own.free cannot destroy it. Dynamic heap arrays/regions/frame storage remain Copy-only. Owning std.option/std.result use ordinary linear enums; is_some/is_ok retain Copy constraints. Full contracts: language/linear-aggregates.md.

14. Buffers and Vec

buffer<T> uniquely owns capacity and an initialized prefix, including owners/resources. Allocate with buffer.new<T>(capacity, heap) (mem.alloc); borrow the handle first for len/capacity/reserve/push/pop/view. reserve(b, capacity, heap) grows explicitly, charging old+new capacity at the peak. Push never grows: full returns the original item. Pop moves the last element out. Free succeeds only when empty; otherwise it returns the buffer. No destructor drains it.

fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {
    let data = buffer.new<own<u64>>(1, heap) or trap;
    let item = own.new(42u64, heap) or trap;
    var answer: u64 = 0;
    { mut b = data;
      buffer.push(b, move item) or trap;
      let last = buffer.pop(b) or trap;
      answer = own.take(move last);
    }
    buffer.free(move data) or trap;
    return answer;
}

ref values = buffer.view(b); / mut values = buffer.view(b); borrow only the prefix. A live child view/task loan blocks shape changes, even a no-op reserve. Read Copy elements; use value.swap to replace linear elements, consuming the returned old value. Full contracts: language/buffers.md.

Import std.vec for Vec<T> and new/len/capacity/reserve/push/pop/free/get/replace, each explicitly specialized ::<T>. new/reserve require mem.alloc; push is bounded, get requires Copy, pop returns std.option.Option. Failure variants retain ownership: full(item), out_of_bounds(item), not_empty(vector). Match move on linear results; import std.option to name its variants. Signatures: library/std.md. Inside a specialized generic body, move name also accepts complete Copy bindings and retains their availability; monomorphic Copy moves and moves of borrows still reject.

std.deque uses the same explicit allocation, returned-ownership and empty-only free contract, with push_front/push_back and pop_front/pop_back. Indices count from the front. Each capacity slot charges Option (tag plus payload); reserve preserves order and needs old+new quota. It uses existing source primitives; signatures and representation invariants stay in library/std.md.