Docs · Language

Memory model

Vyi has no garbage collector, no null, and no hidden heap. Values copy, pointers are valid by construction, and memory beyond the current call comes only from an allocator you name. This page states the rules: copying, pointer validity, array pointers, fixed arrays, lifetimes and what may leave a block, and the allocator contract. Guide 09, Pointers and memory introduces them.

Value semantics

Assignment, argument passing, and return copy:

SiteRule
mut b = a, b = acopies the whole value, every field and element; the copy is independent
a call f(a)the parameter is a con binding of a copy; the callee changes its own data only by copying into a mut
return vthe caller gets a value of its own
initializing a narrower struct from a wider onecopies the shared fields and drops the rest; a copy, never an alias
Vyi
import { println } from "@fmt"

struct Point { x: i32, y: i32 }

fn main() !u8 {
    con a = Point{ x: 1, y: 2 }
    mut b = a
    b.y = 50
    println(a.y)   // prints 2
    println(b.y)   // prints 50
    return Ok(0)
}

A parameter is con, so assigning to it is an error (`cannot reassign immutable binding`). A closure captures by value too: the captured values are copied into the closure's instance when the closure is written, and the closure value is a pointer to that instance. Creating or calling a closure allocates nothing, and a closure lives in the scope where it is written (closures, guide 04).

Sharing one piece of storage between several places always takes a pointer type: *mut T, *con T, [*mut]T, or [*con]T.

Pointer validity

TypePoints atCan be absent?Writable through?
*mut Tone Tneveryes
*con Tone Tneverno
?*mut T, ?*con Tone T, or nothingyes, as an Optional you unwrapafter unwrapping, as the pointer type says
[*mut]T, [*con]Tzero or more Ts, with a lengthnever; zero length is a value, not absence[*mut] yes, [*con] no; bounds-checked
*c_ptr TC memoryyes; may be nullyes (guide 15)
  • Valid by construction. A *mut T or *con T is never null and cannot be made dangling: every form that produces one (&x, an allocator call, a parameter) points at live storage, and the lifetime rules keep it from outliving that storage. Absence is ?*mut T, an Optional like any other.
  • Write permission is in the type. Every pointer type states mut or con; a bare *T is not a type. A *mut T converts to a *con T, never the reverse. Writing through a *con is an error at any pointer depth, and the pointer's type decides, not the binding that holds it: a place reached through a *mut is writable even from a con binding. mut on the binding only lets it point elsewhere.
  • No pointer arithmetic. A pointer supports == and != only. Walk memory with an array pointer.
  • Valid is not the same as live. The compiler rules out null pointers and pointers kept past the block they point into. It does not track allocator memory: using memory after free, or arena memory after reset(), compiles and reads whatever the memory holds.
Vyi · does not compile
fn read(p: *i32) i32 {   // error: pointer type needs a mutability qualifier
    return *p
}

Array pointers: [*con]T and [*mut]T

An array pointer is a pointer and a length carried together in one value, a view over storage someone else owns. [*mut]T and [*con]T have the same representation and differ only in write permission.

PropertyRule
representationa pointer and a length in one value; the length is not part of the type
nullnever
zero lengthan ordinary value: .len is 0 and any index panics
indexingbounds-checked; s[i] panics outside 0 to s.len - 1, and a known negative index is a compile error. The last element is s[s.len - 1]
slicings[lo..hi] is an array pointer over the same storage, not a copy. Bounds count from the start and must satisfy 0 <= lo <= hi <= len; a known negative bound is a compile error, and any other bound out of range panics
.lenthe element count, an i32
.ptrthe data pointer, for C calls and allocator code
element layoutelements are contiguous, at a fixed stride per type

String literals produce them: "hello" is a [*con]u8 over bytes stored in the program. Allocators are the other source (the allocator contract).

Vyi
import { println } from "@fmt"

fn main() !u8 {
    con word = "hello"
    con tail = word[1..]
    println(tail)         // prints ello
    println(tail.len)     // prints 4
    println(word[..0].len) // prints 0
    return Ok(0)
}

Fixed arrays: [N]T

[N]T is N elements stored inline, and N is part of the type. A fixed array is a value: assignment copies every element. [N]T[] fills every element with zeros.

Its one member is .len, the length N as an i32 known value: the length belongs to the type, so a.len is known even when the contents are not. .len is not storage: it cannot be assigned or have its address taken. Through a pointer to a fixed array (p: *con [N]T), p.len, p[i], and p[lo..hi] mean (*p).len, (*p)[i], and (*p)[lo..hi], checked against N, with the pointer's write permission: p[i] = x needs a *mut, and the slice is [*mut]T through a *mut and [*con]T through a *con. A slice through a pointer views the storage the pointer addresses, so it may leave a block exactly when the pointer may.

The length must be a known value wherever the array itself is held: a binding, a parameter or return type, an array literal. An array type whose length is a run-time value ([n]T with a run-time n) is usable only behind a pointer or where only its size is needed, and it has no .len:

Vyi · does not compile
fn count(n: i32, p: *con [n]i32) i32 {
    return p.len   // error: this array's length is a runtime value, so it has no `.len`
}

Indexing

Every index is bounds-checked. An index is known when the compiler can evaluate it: a literal, a con bound to a known value, or an expression of those (a[N + 1], a[a.len - 1], a[-1]). A known index outside 0 to N - 1 is a compile error, and one inside needs no run-time check. Any other index panics ("array index out of bounds") when it is out of range.

Vyi · does not compile
fn main() !u8 {
    con scores = [4]i32[1, 2, 3, 4]
    con last = scores[4]   // error: index 4 is out of range for type [4]i32 (length 4)
    return Ok(0)
}

The run-time check on an index that is not known is left out when all of these hold:

  • the index is exactly the variable of an enclosing for x in lo..hi or for x in lo...hi loop (a loop variable cannot change in the body);
  • both range bounds are known values (0..4, (N - 2)..(N * 2), 0..a.len);
  • lo is at least 0, and the last value x takes (hi - 1, or hi for ...) is below N.

Nothing else is reasoned about: a[x + 1], a condition loop, and a range with a run-time bound all keep the check. In a generic function this is decided for each instance, with that instance's length and known values; so is whether an index that depends on a known parameter is known, so a[K + 1] is unchecked in an instance where it is in range and keeps the check (and panics) in one where it is not.

Slicing

a[lo..hi] on a fixed array gives an array pointer into a's own storage: [*mut]T when a is a writable place (a mut binding, or reached through a *mut), [*con]T otherwise. Open ends and ... mean what they mean for an array pointer, and bounds count from the start, so the last two elements are a[a.len - 2..]. Writes through the slice land in the array.

A slice points into its array, so the array must be a place: slicing a temporary (make()[1..3]) is an error, and a slice of a local array may not outlive the array's block, as &a may not. Known bounds are checked at compile time (a negative bound, a range outside 0 to N, an end below the start); others are checked when the slice is taken.

Vyi
import { println } from "@fmt"

fn main() !u8 {
    mut scores = [4]i32[1, 2, 3, 4]
    con middle = scores[1..3]
    middle[0] = 9
    println(scores[1])    // prints 9
    println(middle.len)   // prints 2
    return Ok(0)
}
Vyi · does not compile
fn main() !u8 {
    con scores = [4]i32[1, 2, 3, 4]
    con tail = scores[2..5]   // error: slice 2..5 is out of range for type [4]i32 (length 4)
    return Ok(0)
}

Converting between fixed arrays and array pointers

CastGivesCopies?
[*mut]T(&a), [*con]T(&a)an array pointer over the array; the length comes from the typeno: writes through it land in the array
[N]T(view)a new fixed array holding the first N elementsyes
*mut [N]T(view), *con [N]T(view)a pointer to a fixed array over the same storageno
[*mut]T(p) with p: *mut [N]Tthe array pointer again, length from the typeno
Vyi
import { println } from "@fmt"

fn main() !u8 {
    mut stock = [3]i32[5, 6, 7]
    con view = [*mut]i32(&stock)
    con saved = [3]i32(view)
    view[0] = 0
    println(stock[0])   // prints 0
    println(saved[0])   // prints 5
    return Ok(0)
}

Stability and escape

Every piece of storage belongs to the scope that creates it and ends when that scope ends. A pointer's lifetime is the lifetime of the storage it points at, and the compiler works it out for every pointer. A function may also state how long its result lives (written lifetimes). The rule:

Blocks

BlockIts storage ends
a function or closure body, and its parameterswhen the call returns
each branch of if and elsewhen the branch finishes
each arm of switch and matchwhen the arm finishes
a loop body (for, for ... in)at the end of every pass
a defer or recover body, the block of catch { ... }when the body finishes
a bare { ... }, a value block (con x = { ... })when the block finishes

A statement ends the temporaries it creates. A temporary that directly initializes a binding is not one: it is that binding's storage, and so is a temporary written directly inside an aggregate literal (struct, tuple, fixed array, variant payload, at any depth) that directly initializes a binding. A store into a field or an element is not an initialization. The only temporary a pointer can reach is a closure's instance: con b = Box{ f: () => n } keeps the closure as long as b, while fns[0] = () => n stores a temporary of the statement (closures). A nested fn used as a value creates its instance where it is named.

Blocks nest, so their lifetimes are ordered: an inner block ends before the block around it. A binding, a pattern binder, and a loop variable belong to the block that declares them. Storage outside every block of a function outlives them all.

Within a block, each con or mut declaration opens a scope that runs to the end of the block, nested inside the scopes of the declarations before it. A binding declared later therefore ends before one declared earlier. Nothing can observe that order, since Vyi has no destructors, so the checks treat two bindings of one block as ending together, and storing a pointer to a later binding into an earlier one of the same block is allowed. With destructors, the strict order will apply to types that have one (planned).

Slots

A value has one lifetime per slot: per pointer it holds, following the shape of its type. Each pointer field of a struct is a slot, and so is what each pointer points at, at every depth: the fields of a struct a pointer points at, the elements of an array pointer or a fixed array, the payload of each enum variant, each tuple element. A struct holding a pointer to something long-lived and a pointer to something short-lived gives out the first freely; only what is read through the second is short-lived.

Some positions cannot be told apart, and everything at or below them shares one lifetime: what an interface value points at (its type is hidden), a union value (which member it holds is not known), and what a C pointer points at. A recursive type folds: in a list of nodes, the next of every node is one slot, however deep the list goes. Slots are named in source only where a signature states them (written lifetimes); a struct field may declare a name for its slot (guide 09).

Where the rule is checked

Inside a function the rule is checked wherever a pointer comes to rest, each time by comparing two lifetimes:

Where the pointer comes to restRequirement
a binding's initializer; an assignment to a binding, or to a field or element of onewhat is stored lives at least as long as the binding's block
a store through a pointer (*p = v, p.f = v, p[i] = v) or into a file-level variablewhat is stored lives at least as long as the storage written into
a callthe arguments meet every requirement of the function called (what a function keeps)
the value of an if, switch, match, or { ... } used as an expression; a break value out of a value blockit does not point into that block
a function's resultit does not point into any block of the function
Vyi · does not compile
fn main() !u8 {
    mut first = 0
    mut slots = [3]*mut i32[&first, &first, &first]
    for i in 0..3 {
        mut value = i
        slots[i] = &value   // error: this *mut i32 points into storage that ends with this loop iteration
    }
    return Ok(0)
}
Vyi · does not compile
fn main() !u8 {
    mut fallback = 3
    con p = if fallback > 1 {
        mut local = 1
        &local   // error: this block's value *mut i32 points into storage that ends with this block
    } else {
        &fallback
    }
    return Ok(0)
}

Passing a pointer down into a call is always allowed, and so is keeping it in a binding of the same block or of a block inside it. A pointer to storage of an outer block may be stored anywhere inside that block.

A binding holds everything ever stored into it, wherever in the function the store is written: once h = &x appears, h is as short-lived as x throughout the function. Returning h, or storing it into something that outlives x, is an error even on a path where h was pointed elsewhere first.

A result that points into the function is reported as `frame-bound pointer *con i32 escapes via return`, and the message goes on to suggest memory from an allocator that outlives the call, or returning the value itself. A store names what ends and what holds the pointer: ``this *mut i32 points into storage that ends with this loop iteration, but slots outlives it``.

The storage written into. For *p = v, p.f = v, and p[i] = v it is the storage p points at; for w.list.items[i] = v it is the storage w.list.items points at, reached through w. The compiler bounds how long that storage may live from everything the pointer may point at: a binding of the function, a slot of what a parameter refers to, a file-level variable, constant data (which lives for the whole program), or allocator memory (which lives as long as the allocator; see the allocator contract). Each pointer is followed on its own, so a holder whose alloc field points at something long-lived does not make the buffer its items field points at long-lived. A stored value is compared slot by slot: each pointer it holds must outlive the storage it lands in. A store through a pointer to a binding also becomes part of what that binding holds:

Vyi · does not compile
struct Holder { target: *mut i32 }

fn main() !u8 {
    mut count = 1
    mut holder = Holder{ target: &count }
    con hp = &holder
    if count > 0 {
        mut local = 2
        hp.target = &local   // error: this *mut i32 points into storage that ends with this block
    }
    return Ok(0)
}

Memory from an allocator lives as long as the allocator's mem slot, which Allocator.alloc declares ('(a.mem), below). For an arena that is the arena itself; for a fixed-buffer allocator, the buffer it carves. A collection over a local arena may therefore hold pointers to bindings declared beside the arena, and values (a String) whose allocator handle points at that arena.

Behind an interface value the object's type is hidden, and everything it reaches has one lifetime. A requirement an implementation places purely on its own receiver (an arena linking a chunk from its parent into its chunk list requires what the parent refers to to outlive that list) is therefore not read through the interface. It is checked where the value becomes an interface value (&arena passed for an Allocator), against the value's real fields, and a value that breaks it is an error there.

No temporary can have its address taken: &, slicing, and a pointer-receiver call each need a place.

What a function keeps

A function may store a pointer it is given somewhere its caller can still reach: into what another parameter refers to, or into a file-level variable. It then requires that argument to live at least as long as that place, a condition on every caller written like a parameter lifetime: p '(s) (the argument for p lives at least as long as what the argument for s refers to), or p '(registry) for a file-level variable. A requirement relates slot to slot: val '(v.items) says what val points at must outlive what the items field of what v points at refers to, and for a struct argument, key 'alloc(m.keys) names the slot alloc of the argument for key.

Unwritten, the requirement is inferred from the body (the editor shows it): from the function's own stores, and from the requirements of what it calls, through any number of calls and through recursion. Each call checks every requirement of the function called with the arguments passed; one that does not hold is an error at the argument, naming the parameter and what it must outlive. A parameter with no inferred or written lifetime is borrowed for the call, and anything may be passed for it.

What is calledWhat it requires
a function or method with a bodyits written parameter lifetimes, else what its body shows
a C functionnothing: its parameters are borrowed for the call
a method through an interface valuewhat the implementations the program uses require: slot by slot where the object behind the value is known at the call, else for everything it reaches as one. Its result is what the interface method's written result lifetime declares, when it writes one
a function valuenothing, unless the function type's parameter carries a lifetime: then that

A function that keeps an argument cannot become a plain function value, whose parameters are only borrowed. It can where the function type's parameter carries a lifetime long enough, checked at each call with the arguments passed (guide 09).

Written lifetimes

A function's result lifetime is worked out from its body. It may instead be written after the return type as a lifetime annotation: an apostrophe and names in parentheses joined with &, as in '(a & b). A , separates pointer levels, outermost first: '(reg, row, text) for *mut *mut *con u8. Each name is a parameter, the receiver, or a file-level variable, and the result lives as long as what every one of them refers to (what the parameter points at, never the parameter itself). A file-level variable lives for the whole program, so naming one says the result does too.

Vyi
import { println } from "@fmt"

struct Pair { a: i32, b: i32 }

fn larger(p: *mut Pair) *mut i32 '(p) {
    if p.a > p.b { return &p.a }
    return &p.b
}

fn main() !u8 {
    mut pair = Pair{ a: 3, b: 9 }
    *larger(&pair) = 1
    println(pair.b)   // prints 1
    return Ok(0)
}

A written result lifetime is a contract, checked from both sides:

SideWhat is checked
the bodyevery returned value lives at least as long as declared: it may hold what a listed parameter points at, or what is read through it, but not what an unlisted parameter points at, and not a binding of the function
each callerthe call's result lives as long as the arguments passed for the listed parameters (a listed file-level variable adds nothing); the caller's own checks use that, not the body

Declaring a shorter lifetime than the value has is always accepted. A recursive function with a written result lifetime needs no inference.

A parameter may carry an annotation too: p: *mut Point '(l) says the argument lives at least as long as what l refers to and everything reachable through it. It is the parameter's contract (what a function keeps): callers are checked against it, and the body may keep p only where it covers. A closure literal may also name a binding it captures in a parameter annotation; each direct call of the closure is checked against it.

Slots in an annotation

Several annotations may follow one type, each for a slot of a struct:

WrittenCovers
'src(x)the slot src: the fields that declare it, and everything below them
'parser.src(x)the slot src of the struct held in the field parser
'(x)every position no named annotation of that type covers

On a pointer to a struct the unnamed form covers what the pointer points at, and slot names are those of the struct behind it. A slot name is one a field declares ('src, '_, or mapped from a nested struct, as in 'src('text)), or the name of a visible field with no slot name. Inside the parentheses a reference is a name or a path from a parameter: x.src (a slot or a visible field), x._ (every slot one layer down), x[_] (the elements of an array pointer or a fixed array). A bare name means what x refers to and everything reachable through it; a path means only the slots it names. Each annotation is a contract for the positions it covers; positions none covers are inferred from the body. A result position a written slot covers may hold a parameter's slot whose own written lifetime ties it only to references the result lists.

ErrorWhen
`T has no slot or visible field x `the struct has no such slot, or the field is private to another file
`T is not a struct, so it has no slot x `a slot named on a type that is neither a struct nor a pointer to one
`slot x is named twice`two annotations of one type name the same slot
`field f has type T, which carries no pointer`a slot declared on a field with no pointer
`field f has type T, which is not a struct`a field maps the slots of a type that has none
`T holds no elements`[_] on a type that is neither an array pointer nor a fixed array
a parse errora slot declared outside a struct; a name marked with ' in the parentheses outside a struct; a plain name in the parentheses inside one; '_ with parentheses; a slot on a function type's parameter in a struct field

Where an annotation may be written

  • after a parameter's type, or a result type;
  • on a struct field, as a slot;
  • on the parameters of a function type that is a parameter's type, in the unnamed form only, naming another parameter of the enclosing function or a file-level variable;
  • after an interface method's result type, and as a slot in an interface's body (interface methods).

Receivers, C functions, bindings, casts, type bindings, a struct nested in a type argument, and function types anywhere else carry none.

Three uses are decided and not built, and the compiler rejects them today:

  • lifetimes on an interface method's parameters (planned): the compiler reports `a lifetime on an interface method's parameter is not supported yet`, and a call through the interface requires what its implementations require;
  • slots stated where an interface type is written, as in s: *mut Source 'buf(text) (planned): the compiler reports that *mut Source is not a struct, so it has no slot buf;
  • a result lifetime on a function type, fn(x: [*con]u8) [*con]u8 '(x) (planned).

A written result lifetime states a lifetime only. '(a) says the result is valid as long as what a refers to; it does not say the result is what a holds. Each position it covers is storage of its own that lives that long, and a value stored into it must live as long. Where a body is visible, what the result may hold is still read from it. Where the result points at something holding pointers, it may also point into what a listed parameter refers to, or hold that parameter's pointer of the same type, and a caller writing through the result reaches that parameter.

Interface methods

An interface method may name its receiver and write its result's lifetime, and the interface's body may declare slots of the object behind its values: an apostrophe and a name. @mem declares Allocator this way:

Vyi
import { OutOfMemory } from "@mem"

interface Allocator {
    'mem,
    fn (a: *mut Allocator) alloc(size: i32, align: i32) OutOfMemory![*mut]u8 '(a.mem),
    fn (a: *mut Allocator) free(buf: [*mut]u8),
}

The receiver is the interface itself or a pointer to it, and names the object behind the interface value: '(a) is everything behind it, and '(a.mem) its mem slot. A call through the interface gives what the declaration says. Each implementation maps its own slots onto the interface's through its written result lifetime ('(a) maps mem to the object itself, '(a.buf) to its buf slot), and one that writes none maps it to the object. Where the object behind the value is the caller's own binding, the slot is read through its type's mapping: memory from a fixed-buffer allocator over a local buffer may not leave that buffer's function. An implementation's result lifetime may promise more than the interface's ('(a.buf) or '(c) where the interface says '(a)), never less.

Closures

A closure value, fn(SIG), is a pointer to the closure's instance (the values it captured, held by value) together with its code. Because it is a pointer, the rule applies to it unchanged:

What is done with a closureResult
called where it was writtenallowed
passed down into a call that only borrows itallowed
assigned to a binding, field, or element in an outer scopeerror at the store
given as the value of an outer blockerror
returnederror, unless it points at something that outlives the call
handed to a function that keeps itchecked at the call, against that function's lifetime on the parameter

A value lives no longer than the shortest thing it points at, so a closure that captured a pointer lives no longer than what that pointer refers to. A named function used as a value, and a closure that captures nothing, have no instance and may go anywhere. A closure outlives its scope only by being put into an allocator, alloc.put(*closure) (where *closure is its instance), and then lives as long as the allocator (the allocator contract). A template ($"...") is a closure too: it lives where it is written, and .string(alloc) renders text to keep.

A closure's own lifetime may be written by putting the literal in parentheses and annotating the whole, ((p: *mut Point) *mut i32 => &p.x) '(owner): the closure must live at least as long as what owner refers to, and whatever holds it treats it as ending with owner.

Stable pointers

A pointer whose storage is outside every block of the function is stable: it may be returned and stored in long-lived structures. A pointer into a block of the current function is frame-bound.

Stable sourceWhy
allocator results (alloc, new, put)allocator memory lives as long as the allocator
file-level con and mut bindingsthey live for the whole program
known valuesa known value you point at is stored in the program (string-literal bytes are the everyday case)
parametersfrom the body, the caller's storage outlives the call
aggregates of stable pointerswhat you build from stable pointers is stable
Vyi
import { println } from "@fmt"

mut visits = 0

fn visitsPtr() *mut i32 {
    return &visits
}

fn main() !u8 {
    *visitsPtr() = 41
    println(visits)   // prints 41
    return Ok(0)
}

A local con is frame-bound, known initializer or not:

Vyi · does not compile
fn dangling() *con i32 {
    con local: i32 = 42
    return &local   // error: frame-bound pointer *con i32 escapes via return
}

Three things state a lifetime the analysis cannot see for itself: the :<markStablePtr() decorator on a binding, the cast from a *c_ptr T to a ?*mut T or ?*con T (whose null check is the visible boundary code), and a written lifetime. transmute (from @intrinsics, wrapped by @mem's transmuteTo) gives the same pointer reinterpreted: each pointer level of the result is the operand's, and a store through it is checked like any other. A level the operand has no pointer for (a pointer made from a number) makes no claim; what it points at is yours to vouch for. What a C function returns comes from the C side, which lives for the whole program; '(c), naming the @c namespace, says so in an annotation (@io's args() is declared '(c)). The standard allocators need no decorator: their result lifetime is declared.

The allocator contract

All heap memory comes through the Allocator interface from @mem. An allocator is a value you pass.

MethodSignatureContract
allocfn alloc(size: i32, align: i32) OutOfMemory![*mut]u8exactly size bytes, aligned to at least align; on failure Err(OutOfMemory), never null and never an empty view
freefn free(buf: [*mut]u8)takes the [*mut]u8 that alloc returned; may do nothing
newfn (a: Allocator) new(known T: type) OutOfMemory!*mut Tone T: sizeof T bytes at alignof T
newfn (a: Allocator) new(known T: type, count: i32) OutOfMemory![*mut]Ta buffer of count elements
putfn (a: Allocator) put(v: _) OutOfMemory!_stores a copy of v and returns a pointer to it; put(*closure) stores a closure's instance and returns the closure
deletefn (a: Allocator) delete(ptr: *mut _)the counterpart of single new and put; the size comes from the pointer's type
deletefn (a: Allocator) delete(ptr: [*mut]_)the counterpart of buffer new; the element type comes from the buffer

Failure is in the type, OutOfMemory, handled with try, catch, or match like any error (error model). Only alloc and free are interface methods; new, put, and delete are methods on the interface, so an allocator that implements alloc and free has the whole API. Memory from an allocator lives as long as the allocator, so a closure put into a local arena cannot be returned from the function that owns the arena.

AllocatorMemory fromfreeReclaiming
systemAllocatorthe platform heapfrees that allocationper allocation
FixedBufferAllocatora buffer you provide, often a stack arraydoes nothingreset() makes the whole buffer available again; a full buffer fails with OutOfMemory
ArenaAllocatorchunks from a parent allocator, taken as neededdoes nothingreset() reclaims everything at once and keeps the chunks; deinit() gives them back

@mem also provides PageAllocator and TestingAllocator (@mem).

Vyi
import { Allocator, ArenaAllocator, OutOfMemory, systemAllocator } from "@mem"
import { println } from "@fmt"

fn scores(alloc: Allocator) OutOfMemory![*mut]i32 {
    con list = try alloc.new(i32, 3)
    list[0] = 42
    return Ok(list)
}

fn main() !u8 {
    mut arena = ArenaAllocator.new(systemAllocator)
    con list = try scores(&arena)
    println(list[0])   // prints 42
    arena.reset()      // list must not be used after this
    return Ok(0)
}

What lives where

StorageWhat goes thereLifetime
the stacklocals, parameters, temporaries, whole aggregates inlinethe declaring block, at most the call
program dataknown values a pointer reaches: string-literal bytes, file-level con datathe whole program
file-level storagefile-level mut bindingsthe whole program
allocator memoryonly what you alloc, new, or putuntil free, delete, or reset, per the allocator

The stack has a fixed size: 1 MiB on wasm, the operating system's main-thread stack on x86-64 and arm64. A program that needs more, usually through runaway recursion, ends with a stack overflow, which is not a panic: no defer runs and nothing can recover it. On wasm every function that uses stack memory checks the limit when it is called, so an overflow never writes below the stack into program data. Natively the operating system's guard page stops the program, and a function whose frame spans more than a page touches each 4 KiB page in order as it reserves the space, so no frame can step over the guard page. Choosing the wasm stack size is (planned).

No language construct (closures, interfaces, errors, enum payloads) allocates heap memory; a closure reaches an allocator only through put. Aggregates store their fields and elements inline, and () has size zero. Sizes and alignments depend on the target; ask with sizeof T and alignof T, which give known values.

See also: guide 09, Pointers and memory, known values, and @mem.