DocsLanguage Guide
Memory and Ownership
The three tiers, reference counting, move-only types, exclusivity, references and regions.
Sable manages memory for you, without a garbage collector and without lifetime annotations. Most of the time you don't think about it at all: values are copied, objects are reference counted, and memory is freed the moment nothing uses it. But Sable also lets you choose, type by type, how much a piece of data costs: no allocation at all, a bump pointer freed in bulk, or a counted heap object with identity.
This chapter explains the model behind that choice. It starts with the three tiers of storage, then covers reference counting, move-only types, how parameters own or borrow what they are given, the law of exclusivity, references and how Sable infers how long they may live, and regions. It ends with how the pieces fit together and what the optimiser does to make reference counting cheap.
The Three Tiers#
Every value in Sable lives in one of three tiers:
| Tier | Declared as | Identity | Escapes | Cost |
|---|---|---|---|---|
| 0 | struct |
no | no (copied instead) | Nothing: the bytes, inline where they are |
| 1 | a value in a region |
no | only within its region's scope | A bump of a pointer; freed all at once |
| 2 | class |
yes | yes | A 16-byte header and a reference count |
The tiers are chosen by what you declare, not by an allocator you pass around. A struct is always Tier 0, a class always Tier 2, and a region is a scope you open where you want one.
Tier 0: Structs#
A struct is a value. It has no header, no identity and no reference count. It is laid out contiguously and embedded directly wherever it is used: in a local, in another struct, in an array's elements, in a union's payload.
struct Vec3 { x: F32, y: F32, z: F32 } // 12 bytes, exactlystruct Ray { origin: Vec3, dir: Vec3 } // 24 bytes, no indirectionA struct used as some P stays a struct. A struct used as any P is put in a box, and that box is a Tier 2 allocation, which is one reason the any is written out (see Protocols).
Tier 2: Classes#
A class instance is an object on the heap with identity (=== compares it), a header and a reference count:
offset size field 0 8 type metadata pointer 8 4 strong count 12 4 weak count and flagsThat's 16 bytes, the same as Swift's object header and .NET's. It is the price of identity, weak references and full reflection.
Tier 1, regions, gets its own section later in this chapter.
Reference Counting#
Sable tracks class instances with automatic reference counting (ARC), as Swift does. Each strong reference to an object adds one to its count, and when the last one goes away the object is destroyed, at once.
Deterministic Destruction#
deinit runs at the moment the last strong reference goes away. That isn't an implementation detail you should avoid depending on; it is a guarantee, and it is why a file closes exactly when you expect:
class LogFile { let path: String init(path: String) { self.path = path print("opened \(path)") } deinit { print("closed \(path)") }}fn writeReport() { let log = LogFile(path: "report.log") print("writing")} // the last reference goes herewriteReport()print("done")opened report.logwritingclosed report.logdoneWhen an object is destroyed, its fields are released in the reverse of the order they are declared in, after its deinit runs. An object whose initialiser throws was never made: the fields it had set are destroyed, and no deinit runs (see Initialization).
Weak and Unowned References#
A strong reference keeps its object alive; that is the default. Two other kinds don't:
- A
weakreference reads as an optional,T?, and becomesnonewhen its object is destroyed. - An
unownedreference reads as a plainT, never optional. It is for a reference you know never outlives its object. Reading one whose object is gone traps. (unowned(safe)spells out this default.) unowned(unsafe)skips that check: a dangling read is undefined behaviour. Use it only where profiling says the check matters.
class Workspace { var documents: Document[>..] = []}class Document { var title: String weak var owner: Workspace? // may outlive its workspace unowned let store: Store // never outlives its store init(title: String, owner: Workspace, store: Store) { self.title = title self.owner = owner self.store = store }}Reference Cycles#
Reference counting can't free a cycle: two objects that hold each other strongly keep each other's counts above zero for ever. Sable helps you in three ways.
The first is weak and unowned, above: the way back from a child to its parent is weak or unowned, and the cycle is broken.
The second is a compile-time warning. The compiler builds a graph of which class types hold which others strongly, and warns about any loop with no weak or unowned edge, printing the path round it (S3460):
class Parent { var children: Child[>..] = [] // warning[S3460]: Child.parent → Parent}class Child { var parent: Parent?}A class that holds its own kind (a linked list's next, a tree's children) isn't warned about, and the warning sees through structs, tuples, optionals and arrays. It is a check of types, not of the objects a program actually makes, so it can't be complete, but it catches the parent and child mistake every time.
The third is a leak check at run time. Run a program with SABLE_CHECK_LEAKS=1 (or set leak-check = true in a package's profile, so that sable run does it) and when the program ends it lists the objects still alive by type, and prints each cycle among them, naming the field that holds each step:
Test.Pet.toy -> Test.Toy.pet -> Test.PetThere is no background cycle collector.
Objects That Are Never Released#
@immortal on a static let makes the objects it holds immortal: they are never counted or released, so reading them costs no retain. String literals and type metadata are immortal already. Use it for singletons that live as long as the program:
class Registry { var entries: [String: Int] = [:] @immortal static let shared = Registry()}Only the objects the global holds directly become immortal; what they hold is counted as usual.
Immutable Classes#
@immutable on a class says it is deeply immutable: its fields are all let, of types that are themselves immutable. Such an object can be shared between tasks freely, so @immutable also makes the class Sendable (see Concurrency).
@immutableclass Config { let name: String let retries: Int init(name: String, retries: Int) { self.name = name self.retries = retries }}Copies and Moves#
Sable is copy by default. let b = a copies a if it's a struct (its bytes, plus a retain for each object it holds) and retains a if it's a class reference. This is what Swift and C# do, and it is the right default for a language that should feel approachable. Moves happen in only a few places, which this section covers.
Move-Only Types#
Some values must never be copied: a file handle, a lock, a GPU buffer, a one-shot channel. Two copies of a handle would close the file twice. @noncopy on a struct or union makes it move-only: assigning it or passing it moves it, and the old binding can't be used any more. A move-only type may declare a deinit, which runs exactly once.
@noncopystruct ScratchFile { let path: String static fn create(_ path: String, _ text: String) throws(IoError) -> ScratchFile { try File.write(path, text) return ScratchFile(path: path) } fn read() throws(IoError) -> String { return try File.read(path) } deinit { try? File.remove(path) }}let a = ScratchFile(path: "/tmp/scratch")let b = a // movesprint(a.path) // error[S3057]: 'a' is used after its value was moved out of itUsing a value after it was moved is a compile error, with the line of the move in the message. This is Rust's ownership checking, but only for the types that need it: everything else stays copyable.
A move-only value passed to a function is passed by reference, without a copy, unless the parameter is consuming (below).
Explicit move#
move moves a copyable value, so that its source is dead after it:
var draft = buildLargeReport()let report = move draft // no retain: 'draft' can't be used againpool.giveBack(move buffer) // as an argument, tooUse it to save a retain when you know the source is finished with, and to say in an API that something is handed over.
Move-Only Generics#
A generic parameter is copyable unless it says otherwise, so a @noncopy type can't be the T of an ordinary generic (S3204). Write ~Copyable to lift that constraint, and the code then only moves its values:
struct Slot<T: ~Copyable> { var item: T}fn keep<T: ~Copyable>(_ x: consuming T) -> Slot<T> { return Slot(item: x)}let held = keep(ScratchFile(path: "/tmp/held"))The same can be written where T: ~Copyable. ~Copyable is only written as a generic parameter's constraint (S3203).
How Parameters Take Their Arguments#
By default a parameter is a read-only value for the length of the call. Small structs are passed in registers; classes and move-only values are passed by reference, without a retain; and a large struct is passed however the platform's calling convention decides (the difference is observable only through exclusivity). Three modifiers change that:
fn store(consuming h: ScratchFile) // takes ownership: the caller's binding is dead afterfn scale(v: inout Vec3, by f: F32) // exclusive, mutable access to the caller's variablefn area(_ r: Rect&) -> F64 // the caller's own Rect, read in placeA modifier may also be written after the colon, which reads better once a parameter has a label: fn read(into buf: inout U8[]).
consuming takes the value: a move-only argument is moved in, and the callee is responsible for it. inout borrows the caller's variable exclusively for the call, and writes back to it (see Functions). T&, a reference type, borrows the caller's storage to read in place; write it on large structs, and on functions that return a reference, which the next sections explain.
At a call, & marks an argument the call may write, and only that. It is required for an inout or out argument, and an error anywhere else (S3209):
var v = Vec3(x: 1, y: 2, z: 3)scale(v: &v, by: 2) // may be written: '&'print(area(bounds)) // read in place: plainWhat an & argument names must be a place an assignment could write: a var, a field or element of one, or a property or subscript with a setter. &xs[0] of a let xs is refused (S3010), as is &make()[0], which would write a temporary copy and drop it.
Swift's borrowing and C#'s ref aren't Sable. The words ref and borrowing are reserved only so that the compiler can tell you what to write instead (S1013).
Exclusivity#
While a call has inout access to a variable, nothing else may read or write that variable. This is Swift's law of exclusivity, and it is what makes inout safe without copies:
fn transfer(_ amount: Int, from: inout Int, to: inout Int) { from -= amount to += amount}var savings = 100transfer(10, from: &savings, to: &savings) // error: overlapping accesses to 'savings'Where the compiler can see both accesses, as here, the check is made at compile time. Where it can't — two references that may be to the same object, say — the access is checked as the program runs, and an overlap traps:
class Tally { var counts: Int[>..] = [0, 0]}fn bothUp(_ a: inout Int, _ b: inout Int) { a += 1; b += 1 }let t = Tally()let same = tbothUp(&t.counts[0], &same.counts[1]) // traps: both are accesses to one arrayPassing an element inout is an access to the whole array, which mustn't change while the element is lent. The run-time checks are on in debug builds and off in optimised ones; --exclusivity=checked (or exclusivity = "checked" in a profile) keeps them in a release build. A read of a class's let field is never checked: nothing can change it after its initialiser.
References#
A reference, written T&, is the address of a value somewhere else. You have already seen it as a parameter type. Anywhere else, &expr makes one:
struct Bag { var items: Item[>..]}var bag = Bag(items: [Item(name: "lamp"), Item(name: "rope")])let first = &bag.items[0] // an 'Item&'print(first.name) // lampA reference reads through to what it refers to: first.name is bag.items[0].name. T&? is an optional reference.
Root Inference#
What makes references safe is that every one has a root: the variable, parameter, region or global that bounds how long it can live. The compiler works out the root of every reference expression, and rejects any program in which a reference could outlive its root. You never write lifetimes.
fn longest(_ a: String&, _ b: String&) -> String& { return a.count >= b.count ? a : b}In Rust this needs a lifetime parameter, <'a>, on both parameters and the result. In Sable the result's root is inferred as {a, b}, the two parameters, and each caller checks that the result doesn't outlive either argument. That set of roots is part of the function's compiled interface, so callers in other modules check against it too, but it is never written by hand.
The rules are short:
- A reference's roots are a set of anchors: parameters, locals, regions,
staticstorage, orheap(for a class reference, which has no static bound). - A reference can be stored somewhere only if that place's root outlives every anchor of the reference.
- A reference can be returned only if its roots are all parameters,
staticorheap. - A reference can be stored into a region only if every anchor outlives the region.
Returning a reference rooted in a local is the commonest mistake, and the error says how to fix it:
error[S3061]: cannot return a reference rooted in local 'tmp' --> src/parse.sb:41:12 |41 | return &tmp.name | ^^^^^^^^^ 'tmp' dies at the end of this function |help: three ways to fix this | - return an owned value: return tmp.name.toOwned() | - allocate in the caller's region: fn f(in r: region) -> String& | - return the whole value: return tmpUsing a reference after its root's scope has ended is refused the same way.
Root inference rejects some programs Rust accepts: those that need lifetimes unrelated to any parameter, such as self-referential structs, or arena types with lifetime parameters. For those, the answer is a region, an owned value, or a class. Rejecting a complex program with a clear error is a better trade, for most code, than a lifetime syntax.
Root inference and ARC work together. A class reference has the root heap: you can always store and return it, and it costs a retain. A struct or region reference has a static root: it is restricted, and it costs nothing. Every reference the compiler proves doesn't escape is a retain and release the optimiser deletes.
References That Write and References That Read#
A reference can be written through only if it was made from a place that may be written: &x of a var, an inout parameter, self in a mutating method, a field or element of one of those, or what a mutating method returns. Every other reference only reads — a T& parameter, & of a let, what any other function returns — and a write through it is an error (S3010).
struct Node { var v: Int mutating fn bump() { v += 1 }}struct Chunk { var items: Node[>..] mutating fn at(_ i: Int) -> Node& { return &self.items[i] } // rooted in self}var chunk = Chunk(items: [Node(v: 1), Node(v: 2)])chunk.at(0).v = 10 // writes a field through the referencechunk.at(1).bump() // calls a mutating method on what it refers tochunk.at(0) = Node(v: 3) // replaces the whole of itlet r = chunk.at(1)r.v = 20 // a 'let' reference still writes: it is never reboundA store to a reference — a call that returns one, or a let that holds one — writes what it refers to. A store to a var that holds a reference rebinds it, to another reference; a var that writes may only be given references that write.
References Into an Array's Elements#
A reference to a variable or a field is safe to keep while you change the variable: the variable's storage doesn't move. A reference to an element of an array is different. It is an address in the array's buffer, which moves when the array grows, is copied when shared and written, and is freed with the array.
So a reference into an element holds an access to the variable it is rooted in, from where it's made to its last use, just as an inout argument does for a call. Meanwhile, no other use of that variable is allowed, not even a read (S3062):
let r = chunk.at(0) // holds an access to 'chunk' …r.v = 2print(chunk.items[0].v) // … which ended at r's last use: finelet s = chunk.at(0)chunk.items.append(Node(v: 9)) // error[S3062]: 'chunk' is used while a reference into it is in uses.v = 3Reading is included because a copy of the array shares its buffer, and a write through the reference after the copy would be seen by it.
When the array belongs to an object or a global, the compiler can't prove the access: another reference to the same object, or any function, could grow the array. Such a reference may be used only where it is made — not kept in a variable, passed on or returned (S3067). Writing in place, order.items[i].qty = 1, is still fine; it is the dynamic exclusivity check's job.
Regions#
A region is Tier 1: an arena that values are bump-allocated into, and that is freed all at once when its scope ends. It is the answer when you want a graph of little things — a parser's tokens and syntax tree, a request's scratch data, a frame's working set — and don't want to pay for a heap allocation and a reference count on each.
struct Expr { var op: Char var value: F64 var left: Expr&? var right: Expr&?}fn evaluate(_ e: Expr&) -> F64 { if e.op == '+' { return evaluate(e.left!) + evaluate(e.right!) } if e.op == '*' { return evaluate(e.left!) * evaluate(e.right!) } return e.value}fn calculate() -> F64 { region arena { let two = arena.alloc(Expr { op: '#', value: 2, left: none, right: none }) let three = arena.alloc(Expr { op: '#', value: 3, left: none, right: none }) let sum = arena.alloc(Expr { op: '+', value: 0, left: two, right: three }) return evaluate(sum) // an owned F64 leaves } // the whole arena is freed here}print(calculate()) // 5.0region arena { … } opens a region for the block. arena.alloc(value) moves a value into it and gives back a reference (Expr&) rooted in the region. The reference writes: through a let that holds it, or where it is made, so two.value = 4 changes the value in the region. When the block ends, by any path, everything in the region is destroyed, last first, and its memory is released in one go.
Passing a Region In#
A function that builds into its caller's region takes one with in r: region (the label is in), and references it returns are rooted in that region:
fn leaf(_ v: F64, in r: region) -> Expr& { return r.alloc(Expr { op: '#', value: v, left: none, right: none })}fn product(_ a: F64, _ b: F64, in r: region) -> Expr& { return r.alloc(Expr { op: '*', value: 0, left: leaf(a, in: r), right: leaf(b, in: r) })}region arena { print(evaluate(product(6, 7, in: arena))) // 42.0}Root inference does the rest. A reference into a region can't outlive it: returning one from the function that opened the region is S3061, and storing a reference to a local into a region is refused by rule 4. You write no annotations.
Getting a Value Out#
toOwned() on any reference copies what it refers to into a value of its own, which can outlive the region:
fn parse(_ source: String) -> Module { region arena { let tree = parseModule(source, in: arena) return tree.toOwned() }}A copied value that holds references still holds them, rooted where they were, so returning such a value out of its region is refused as returning the reference would be.
Growable Arrays in a Region#
A growable array given to alloc keeps its elements in the region's memory, grows there, and is freed with it:
region arena { let tokens = arena.alloc(Token[>..]()) // a 'Token[>..]&' that writes lex(source, into: &tokens) // an 'inout Token[>..]': what 'tokens' refers to print(tokens.count)}Only what alloc is given directly is the region's. A copy of the array that is written to becomes an ordinary heap array, as any copy-on-write array does, and one still held as the region ends is moved to the heap first.
Resetting and Nesting#
reset() destroys everything a region holds and keeps its memory for what comes next, which suits a loop that does the same work over and over. A reference made before the reset can't be used after it; the compiler tracks that through variables and loops:
region pool { for request in requests { pool.reset() let scratch = pool.alloc(Scratch()) handle(request, scratch) }}region frame = pool { … } opens a nested region in the same memory. The block allocates through frame, and pool is lent to it meanwhile, so using pool directly inside is an error. When the block ends, what it took is given back. A reference into frame can't be kept past the block.
Checking Regions at Run Time#
What the compiler can't see — a raw address kept into a region in unsafe code, a write past the end of a value through one — is caught by SABLE_CHECK_REGIONS=1. With it set, the memory a reset, a nested block or the region's end gives back is filled with 0xDE, and each value is followed by guard bytes that are checked as it is given back.
Allocators Built on Regions#
Sable.Core builds on regions for patterns they don't cover by themselves. FrameAllocator keeps a region for each frame in flight (as a renderer does, while the GPU draws the previous frame) and resets each as its frame comes round again, trapping if that frame is still held:
let frames = FrameAllocator(framesInFlight: 2)for n in 0..<4 { let frame = frames.beginFrame() let particle = frame.alloc(Particle { x: F64(n), speed: 0.5 }) particle.x += particle.speed}For memory that isn't the program's own, such as a GPU heap, BuddyAllocator and RangeAllocator hand out offsets rather than memory, and SlabPool<T> keeps values named by generational handles, so that a stale handle is refused rather than reading a reused slot.
Scoped Resources with using#
using let binds a value that is destroyed at the end of the enclosing block, with its deinit run there. Several are destroyed in reverse order. For a @noncopy resource, the binding is consumed as the scope ends, so a use after release is a compile error:
fn copyThrough(_ text: String, inside directory: String) throws(IoError) -> String { using let input = try ScratchFile.create(Path.join(directory, "in.txt"), text) using let output = try ScratchFile.create(Path.join(directory, "out.txt"), try input.read()) return try output.read()} // output removed, then inputControl Flow covers using and defer in full.
How the Tiers Compose#
The tiers are meant to be used together, and the usual shape is this: ARC at the boundaries, values in the interior, regions for the churn.
@reflectableclass Scene { // Tier 2: identity, observers, reflection private var entities: Entity[>..] = [] // Tier 0 structs, inline in one buffer fn update(dt: F32) { region frame { // Tier 1: this frame's scratch let visible = frame.alloc(Int[>..]()) for (i, e) in entities.enumerated() { if e.isVisible { visible.append(i) } } for i in visible { entities[i].step(dt) // in place: no copy, no ARC } } // released in one go }}struct Entity { // Tier 0: no header, no count var position: Vec3 var velocity: Vec3 var isVisible: Bool mutating fn step(_ dt: F32) { position.x += velocity.x * dt position.y += velocity.y * dt position.z += velocity.z * dt }}The Scene pays for reference counting once, at the top. Everything below it is bytes. The per-frame working set costs one bump pointer. And because Scene is @reflectable, an editor can still enumerate it, bind to it and save it (see Casting, Metatypes and Reflection).
Performance: Making ARC Cheap#
Naive reference counting is slow: a retain and a release around every use. Most of the cost is removed by the optimiser, and knowing what it does helps you write code it can help:
| Optimisation | What it does |
|---|---|
| Local pairing | Deletes a retain and release with nothing between them that could let the object escape |
| Borrowed parameters | A T& parameter, and a class or move-only one by default, is kept alive by the caller, so the callee counts nothing |
Guaranteed self |
Methods borrow self rather than owning it |
| Stack promotion | An object that never escapes its function becomes a stack value, with no header and no count |
| Uniqueness | A copy-on-write array skips the copy when its buffer's count is one |
| Release hoisting | Moves releases out of loops, and merges them where paths join |
| Escape summaries | Which parameters escape is recorded in each module's interface, so these work across modules without whole-program optimisation |
That last one is where Sable improves on Swift, which loses most of these at a module boundary unless the whole program is optimised at once.
Counting is also cheaper than it looks when there are threads: an object's counts are atomic only once it has been shared with another thread (see Concurrency).
The practical advice is short. Prefer structs for data. Use classes where you need identity or sharing. Pass large structs as T& when a function only reads them. Use a region when you allocate many short-lived things together. And reach for @noncopy when a value must exist exactly once.