Files
aji/docs/rfcs/0005-frame-storage-borrows-arrays.md
T
dev 210af812cf rfc: 0005 frame storage, second-class borrows and arrays (Proposed)
Phase 1 memory design for features ownership and arrays, recording the
owner's decisions on Q-009 (second-class borrows, `from` on returns),
Q-010 (static-only region generations) and phase order (no heap in
Phase 1; Own, heap and regions move to Phase 2).
2026-10-04 12:59:36 +03:00

15 KiB

RFC 0005: Frame Storage, Second-Class Borrows and Arrays

Status: Proposed
Scope: AIR format 0, features ownership and arrays
Language version: 0.1
Supersedes: —

Decisions already taken by the language owner (2026-10-04) and recorded here:

  • Q-009: borrows are second-class; a function returns a borrow only with an explicit from %param.
  • Q-010: region generations are checked statically only (applies when regions is specified in Phase 2).
  • Phase order: Phase 1 has no heap. Own<T>, heap allocation and regions move to Phase 2, after capabilities.

Motivation

Phase 1 must give AIR mutable memory, references and bounds-checked arrays while keeping the verifier simple enough to be specified exactly. Allocation needs authority (cap<mem.alloc>, spec 05), which does not exist before Phase 2, so Phase 1 uses frame storage only: storage that lives exactly as long as a function activation.

Invariants

For every program accepted with ownership and arrays:

  1. No dangling borrow. A borrow never outlives the storage it was derived from. Frame storage dies at function return; no borrow of it survives the return.
  2. Exclusive XOR shared. For overlapping storage, at any program point there is either one live mut borrow (possibly with live descendants) or any number of live ref borrows, never both. Direct access to a local (local.load, local.store, local.zero) counts as a short access of the whole local.
  3. No uninitialized read. Storage is read or borrowed only after it is definitely initialized on every path.
  4. No out-of-bounds access. Every element access is either proven in bounds by the spec-defined fact analysis (§6) or checked at runtime and traps with T0008.
  5. Explicit live ranges. Every borrow created in a function ends at a visible point: borrow.end, or ret when it is the returned borrow.

1. Features

Feature Depends on Contents
ownership — local<T>, ref<T>, mut<T>; local.*, borrow.*, load, store; from on returns
arrays ownership [T; N], slice<T>, slice_mut<T>; array.splat, borrow.index, slice.*, guard

Registry changes: arrays gains the dependency ownership; regions moves to Phase 2 and depends on capabilities, effects, ownership; a new reserved feature heap (Phase 2: Own<T>, own.alloc, own.free) depends on capabilities, effects, ownership; islands lists the new closure. A reserved feature borrow_joins (see §5.4) is added without a phase.

2. Types

Type Class Notes
local<T> storage frame storage holding a T; only an operand of local.* and borrow.*
ref<T> borrow shared borrow
mut<T> borrow exclusive borrow
[T; N] value array of N values, 1 ≤ N ≤ 2^32; copyable when T is
slice<T> borrow shared borrow of a contiguous range
slice_mut<T> borrow exclusive borrow of a contiguous range

T in these types is a value type: not void, never, a storage type or a borrow type.

Second-class rule. Storage and borrow types MUST NOT appear as struct fields, enum payloads, array elements or the T of another storage or borrow type (E1001). A storage type MUST NOT appear as a function parameter, return type or block parameter (E1001). A borrow type MAY appear as a function parameter and, with from, as a return type (§5.3). As a block parameter type it requires the reserved feature borrow_joins (§5.4).

All value types of format 0 and Phase 1 are copyable. Move-only values arrive with heap in Phase 2.

3. Syntax additions

function     = "fn" global "(" [ param_list ] ")" "->" type [ "from" local ] NL …
type         = … | "local" "<" type ">" | "ref" "<" type ">" | "mut" "<" type ">"
                 | "[" type ";" int_lit "]" | "slice" "<" type ">" | "slice_mut" "<" type ">"
instruction  = [ local { "," local } "=" ] operation      ; multi-result, used only by slice.split

Multi-result binding is new syntax for new instructions only; existing instructions keep a single result.

4. Instructions

Common contract unless stated: no effects, no capabilities, no synchronization. "Owned borrow" means a borrow created in the current function (§5.1).

ownership

Instruction Operands → result Verifier Runtime
%s = local.alloc T → local<T> storage is uninitialized allocates frame storage, freed at return
local.store %s, %v local<T>, T no live borrow of %s (E2101); initializes %s writes %v
local.zero %s local<T> T zeroable: integers, bool, arrays and structs of zeroable types (E1001); no live borrow (E2101); initializes writes all-zero value
%v = local.load %s local<T> → T initialized (E1010); no live mut borrow of %s (E2101) reads
%r = borrow.ref %x local<T>, ref<T>, mut<T> → ref<T>; slice<T>, slice_mut<T> → slice<T> §5.2; locals must be initialized (E1010); child of %x unless %x is a local shared view of the same place
%m = borrow.mut %x local<T>, mut<T> → mut<T>; slice_mut<T> → slice_mut<T> §5.2; locals must be initialized (E1010); child of %x unless %x is a local exclusive view of the same place
%f = borrow.field @S.f, %b ref<@S>/mut<@S> → ref<F>/mut<F> child of %b; distinct fields are disjoint reference to the field
borrow.end %b owned borrow no live children (E2102); not a parameter (E2107); not already ended (E2106) none
%v = load %b ref<T>/mut<T> → T %b usable for reading (§5.2) reads
store %b, %v mut<T>, T %b usable for writing (§5.2) writes

arrays

Instruction Operands → result Verifier Runtime
%a = array.splat [T; N] %v T → [T; N] — every element is %v
%e = borrow.index %b, %i ref/mut of [T; N], or slice/slice_mut of T; usize → ref<T>/mut<T> child of %b traps T0008 if %i ≥ length
%e = borrow.index.proven %b, %i as above %i < length proven (§6), otherwise E2103 no check
%s = slice.make %b ref<[T; N]>/mut<[T; N]> → slice<T>/slice_mut<T> child of %b whole array
%n = slice.len %s slice<T>/slice_mut<T> → usize — length
%t = slice.sub %s, %lo, %hi slice, usize, usize → same slice type child of %s traps T0008 unless lo ≤ hi ≤ len
%l, %r = slice.split %s, %mid slice, usize → two slices of the same type two children of %s, disjoint traps T0008 unless mid ≤ len
slice.copy %dst, %src slice_mut<T>, slice<T>/slice_mut<T> both usable (§5.2); they cannot overlap by §5.2 traps T0008 unless lengths are equal; copies elements
guard %c bool adds a fact (§6) traps T0002 if false

New trap code: T0008 trap.out_of_bounds.

5. Borrow rules

5.1 Owned and lent borrows

  • A borrow created in the function (borrow.*, slice.make, slice.sub, slice.split, or the result of a call to a function with from) is owned by the function.
  • A borrow-typed function parameter is lent: the caller keeps it alive for the whole call. A lent borrow is never ended by the callee (E2107) and need not be ended.
  • Every owned borrow MUST be ended exactly once on every path that reaches ret, either by borrow.end or by being the returned value of ret … from (§5.3); otherwise E2105. Paths ending in trap have no obligation.
  • Using a borrow after it has been ended is E2106.

5.2 Places, overlap and access

Every borrow has a root (a local or a lent parameter), a path from the root (field names, a slice range, or an element), a mode (ref/mut) and a parent (none for borrows taken directly from a local or a parameter).

  • Two paths overlap unless they diverge at different fields of the same struct, or they are the two results of one slice.split (and descendants of each).
  • Element borrows (borrow.index) and sub-slices of the same parent all overlap each other.
  • Creating a borrow conflicts with every live borrow whose path overlaps when either is mut (E2101).
  • A borrow with live children is frozen: it may still create further children that do not conflict, but it cannot be read, written or ended while a live child conflicts with that use (E2101, E2102 for ending).
  • A ref borrow is usable for reading; a mut borrow is usable for reading and writing, in both cases only if not frozen by a conflicting child.
  • There is no implicit conversion between borrow types: a mut/slice_mut borrow is passed where a shared one is expected only through an explicit borrow.ref (E1001 otherwise).
  • call: each borrow argument is lent to the callee for the duration of the call. Arguments are checked as if each were a new borrow of its operand at the call: a mut argument conflicts with any other argument that overlaps it (E2101).

5.3 Returning a borrow

fn @f(…, %p: slice<u8>, …) -> ref<u8> from %p declares that the result borrows from the argument passed for %p.

  • from names a borrow-typed parameter; its mode must allow the result mode (mut result needs a mut/slice_mut parameter) (E1001).
  • A borrow-typed return without from is E2102.
  • ret %b in such a function requires %b to be %p or a descendant of %p (E2102). At ret, the only live owned borrows may be %b and its owned ancestors, which are transferred to the caller with it; any other live owned borrow is E2105.
  • At the call site, the result is a new owned borrow whose parent is the argument passed for %p; the argument cannot be ended before the result (E2102).

5.4 Joins and loops

The set of live owned borrows MUST be identical on every edge into a block (E2105, reported at the block). In particular a borrow created inside a loop body is ended before the back edge. Because states must match exactly, loops need no widening and the analysis is a single pass in reverse postorder plus one check per back edge.

Borrow-typed block parameters are reserved for the feature borrow_joins. Without it they are rejected with E0006 reason feature_not_declared. Using a feature gate, rather than a permanent type error, keeps the door open without breaking the format-0 freeze (spec 07 §8.7).

6. Bounds facts

A fact i <u n (unsigned comparison of two usize values) holds at an instruction if one of these dominates the instruction:

  • a cbr on %c = lt.usize %i, %n or %c = gt.usize %n, %i, along the true edge, into a block whose only predecessor is that cbr's block;
  • a cbr on %c = ge.usize %i, %n or %c = le.usize %n, %i, along the false edge, under the same single-predecessor condition;
  • a guard %c with %c one of the comparisons above, for the instructions that follow it in its block and the blocks it dominates.

borrow.index.proven %b, %i is proven if %i is a const.usize k and the length of %b is a static N > k, or if a fact %i <u %n holds where %n is either slice.len %b (the same SSA value %b) or a const.usize k with k ≤ N for a static length N. Nothing else is a proof; in particular no arithmetic reasoning is performed. This is the complete, normative analysis: an implementation MUST NOT accept more or fewer programs.

7. Runtime and interpreter

  • Frame storage is allocated by local.alloc and released at return; no code runs at release.
  • The interpreter represents a borrow as (storage, path) and a slice as (storage, path, offset, length). It performs no alias or liveness checks at runtime: the verifier guarantees them. Bounds checks run exactly where §4 says.
  • Behavior is deterministic; storage addresses are never observable.

8. Diagnostics

Code Kind Meaning
E1010 init.read_uninitialized (existing) local read or borrowed before definite initialization
E2101 borrow.mutable_alias (existing) conflicting borrow or access
E2102 borrow.outlives_owner (existing) borrow escapes its storage, parent ended before child, or borrow returned without valid from
E2103 memory.out_of_bounds (existing) borrow.index.proven without a proof
E2105 borrow.not_ended owned borrow live at ret or live on only some edges into a block
E2106 borrow.use_after_end borrow used or ended after it was ended
E2107 borrow.not_owned lent (parameter) borrow ended by the callee
T0008 trap.out_of_bounds runtime bounds check failed

Structured fields: function, block, inst, borrow (SSA name), root, and for E2101 the conflicting borrow conflicts_with.

Valid example

module example.copy_core
air 0
lang 0.1
features [arrays, ownership]

fn @copy(%dst: slice_mut<u8>, %src: slice<u8>) -> void
effects []
entry:
    slice.copy %dst, %src          ; traps T0008 on length mismatch
    ret

fn @main() -> u8
effects []
entry:
    %buf = local.alloc [u8; 8]
    local.zero %buf
    %m = borrow.mut %buf
    %s = slice.make %m
    %four = const.usize 4
    %lo, %hi = slice.split %s, %four
    %src = borrow.ref %lo          ; shared view: no implicit mut -> shared conversion
    call @copy(%hi, %src)          ; disjoint halves: accepted
    borrow.end %src
    borrow.end %lo
    borrow.end %hi
    borrow.end %s
    borrow.end %m
    %v = local.load %buf
    ...

Rejected examples

    %a = borrow.mut %buf
    %b = borrow.ref %buf           ; E2101: %a is live and mut
fn @leak() -> ref<u8>              ; E2102: borrow return without `from`
    %x = local.alloc u8
    %v = local.load %x             ; E1010: not initialized
    %e = borrow.index.proven %s, %i  ; E2103: no fact %i <u slice.len %s
    %r = borrow.ref %buf
    ret %v                         ; E2105: %r not ended

Diagnostics and compatibility

Additive under spec 07 §8.7: new types, instructions, codes and a trap code, all inside the features ownership and arrays. The phase-1 conformance test use_after_move (needs Own<T>) moves to Phase 2.

Spec integration

On acceptance: spec 03 (§3, §4, §6, §9–§11: frame storage, second-class borrows, slices, initialization), spec 07 §8 (syntax, multi-result), spec 07a (instruction contracts), spec 08 (§5–§6 facts; analysis order types → init → borrows → bounds), reference/air-text.ebnf, reference/air-features.md, reference/error-codes.md. Plan: Phase 1 and Phase 2 files.

Alternatives considered

  • Explicit lifetime parameters (Rust-style): more expressive (borrows in structs) but a much larger verifier and diagnostics surface. Rejected by Q-009.
  • Implicit borrow end at last use (non-lexical lifetimes): fewer instructions, but live ranges become an inference result instead of a visible fact. Explicit borrow.end makes the verifier's transfer function local and diagnostics exact.
  • Pure value semantics (arrays updated functionally, no borrows): aliasing becomes impossible, but conflicts with spec 03's borrow model and makes I/O buffers awkward before ownership-passing I/O exists.
  • Runtime generation checks for regions: rejected by Q-010.
  • Heap in Phase 1 without capabilities: would grant implicit authority and require an incompatible change later.

Unresolved questions

  • Whether borrow_joins should be specified in Phase 2 or later.
  • Whether slice.copy should also exist as a proven variant without the length check (not needed for Phase 1).