Memory
The kinds of name, the block lifetimes the compiler checks without being told, the annotations, destructors, crossing a domain, places and ref, and the raw tier.
Every value in a sysl program is named in one of a few ways, and the declaration that names it says which. This page is the whole of the model: the kinds of name, the lifetimes the compiler works out from blocks with nothing written, the few annotations that exist for code it cannot see, what a destructor guarantees, and where the guarantees stop.
If you do not write *T, you cannot segfault. The safe subset — values, references, weak
references, arrays and views — has no use-after-free, no null dereference, no out-of-bounds access
and no dangling pointer. The one unsafe primitive over memory is the raw pointer, and it is
greppable: a program’s exposure to C’s hazards is the lines with a * in the type, the
import sysl.raw.ptr_cast lines, and the subscripts it asked by name not to check —
get_unchecked, set_unchecked and an @unchecked block.
The kinds of name
| kind | what it is | who frees it | needs an allocator |
|---|---|---|---|
T | a value — in a register, a stack slot, or inline in something bigger; copied | nobody; it goes with its block or its container | no |
&T | a counted reference to a heap object | the compiler, when the last reference goes | to make one |
weak T | a reference that does not keep its object alive, read as an Option | — | no |
&sync T | a &T whose count is atomic: the one kind that may cross a domain | the compiler | to make one |
*T | a machine address | you | no |
[]T, []const T | a view: owner word, address, length | its owner | no |
ref x = place is a declaration, not a kind. Buf, Frozen, Map and
the other collections are library types built from these. There is no other kind.
struct Point
x: int
y: int
var here = Point(1, 2)
var shared: &Point = Point(3, 4)
var raw: *Point = &here
print(here.x, shared.x, raw.x)
1 3 1
The choice is per declaration, not per type. The same struct Point is a value, a heap object
and a pointer’s target above. This is C’s arrangement rather than Swift’s or Scala’s, where a type is
struct or class once and for all: a page-table entry, a temporary in a loop and a shared
configuration object may be one type held three ways.
The value is the unmarked default, because it is the only kind a kernel can use. A module that
has given up the allocator cannot make a reference, so a reference default would make the unmarked
spelling the illegal one exactly where value semantics matter most. With T the default, T works
in both worlds, *T covers pointers, and &T appears in allocator-free code only where something
else handed one over.
T — values
A value lives inline. Assignment and argument passing copy it, as in C:
struct Counter
n: int
var a = Counter(1)
var b = a
b.n = 99
print(a.n, b.n)
1 99
There is no move semantics and no use-after-move: a is a whole Counter after b = a, and
always will be. A value holding a &T field is still a value, and copying it retains that field,
so the copy is independently safe. Where a copy is a local’s last use the compiler hands the value
over instead (below), which
changes how many counts are taken and nothing a program can observe.
&T — counted references
A &T refers to a heap object managed by ARC: the compiler emits the retains and releases, and
the object is destroyed the moment the last strong reference goes. It is shared and freely
aliased, mutable through any alias (there is no borrow checker and no exclusivity rule),
non-null, and automatically managed:
struct Counter
n: int
var a: &Counter = Counter(1)
var b = a
b.n = 99
print(a.n, b.n, a == b)
99 99 true
The same two lines as above, and the declared kind is the only difference: b = a copied a
Counter there and made a second reference here. Two live mutable aliases are what Rust exists to
prevent; permitting them is the deliberate trade, paid for at run time by counting, and it buys a
language with no lifetimes written and nothing to prove to a checker.
There is no allocation keyword. A construction written where a &T is expected puts the
object on the heap, and with no expectation a construction is a value:
struct Process
id: int
priority: int
spawn(id: int) -> &Process = Process(id, 0)
var p = spawn(7)
var q: &Process = Process(8, 1)
var v = Process(9, 2)
print(p.id, q.id, v.id)
7 8 9
The positions that fix the expectation are the ones that already state a type: a declared local, a
parameter, a return type, a struct field, an enum variant’s payload, an element of an array or a
slice, a part of a tuple, a generic argument and a parameter of a callable type. The rule is about
types, not syntax: a T where a &T is expected goes on the heap, whatever produced it. An if,
a match and a loop yield through their branches, so the expectation reaches each branch on its
own — a value branch and an already-reference branch meet at &Point, and what is already a
reference passes through untouched. A scalar is referenced the same way:
var n: &int = 41
print(*n + 1)
42
A reference is never null. There is no null in the safe subset; something that may be absent is
an Option[&T], and a match is the only route to it. A box is made from what the allocator answers,
and a null answer traps before anything is stored, exactly as a failed array allocation does — a
program that must answer the refusal instead asks with a fallible twin
(below). The one &T that reads as null is one in storage the language
did not lay out and the program zeroed
(below).
An Option of a reference is one word
Option[&T] and Option[&sync T] are guaranteed to be the address alone, with None as null —
the same size and alignment as the reference, with no tag beside it. A reference is never null, so
nothing is lost, and the absent reference costs nothing over the present one, whether it sits in a
local, a field, an array element or module storage; a zeroed one is None. The same holds on every
target: on a 32-bit one it is four bytes.
A raw *T may be null, so an Option[*T] keeps its tag, as Rust’s does, and Some(null) stays
apart from None — in a local, through generic code, and in a Buf[*T] holding a null element:
struct Node
value: int
struct Link
next: Option[&Node]
print(sizeof(Option[&Node]), sizeof(&Node), sizeof(Link), sizeof(Option[*Node]))
var empty: [4]Option[&Node]
val p: *Node = null
print(empty[3].is_none(), Some(p).is_some())
8 8 8 16
true true
So an Option[*T] is not C’s nullable pointer, and an extern or @export naming one is refused
(ffi.md). A raw pointer that is never null,
*nonnull T, has the niche a reference has: an
Option[*nonnull T] is one word, and it is C’s nullable pointer. The guarantee is for a thin reference: a
&Shape of a trait is two words, the value and its table, and an Option of one keeps its tag, as
does an Option of a weak T and every other enum.
An allocation that may fail
The allocator may answer null: libc’s malloc does for a size it cannot give, and a pair a
manifest names (allocator { alloc, free }, packages) — a kernel’s heap — may
answer null whenever it is out of room. Every allocation the language makes traps on that answer
before anything is stored: a box, a slice, a string (a concatenation, a rendering, str_cast), a
buffer’s growth, a task’s frame. The trap is the one every other check stops with — status 133, no
message — after what was printed so far is flushed.
That is the right default for a program with nowhere to go when memory runs out, and the wrong one for
a kernel, whose system calls answer ENOMEM and carry on. So each allocating member of the library
has exactly one fallible twin, named try_ and the member’s own name, which answers
Result[_, AllocError] (sysl.alloc) and never traps on the
heap’s refusal: Buf.try_push, try_reserve, try_extend, try_insert, try_copy, try_buf,
try_buf_with_capacity, try_buf_filled; StrBuilder.try_push and its siblings, try_finish,
try_str_builder, try_cstring; and try_box(v) for the box a &T of v would be. AllocError is
CapacityOverflow — the size does not fit in a usize, and the heap was not asked — or OutOfMemory.
import sysl.alloc.try_box
import sysl.buf.{Buf, buf}
struct Point
x: int
y: int
main()
var b: Buf[u64] = buf()
b.try_reserve(usize(1) << 61) match
Ok(_) -> print("reserved")
Err(e) -> print("refused:", e, b.len())
val p = try_box(Point(1, 2))
print(p.is_ok(), p.unwrap().y)
refused: capacity overflow 0
true 2
A refused twin leaves nothing half-built: the buffer keeps its elements, its count and its storage;
the value it was handed is not kept; nothing allocated before the refusal stays allocated. Rust’s
try_reserve family and Rust for Linux’s try_push and Box::try_new are the same bargain. A twin
still traps on what is a mistake in the program rather than a refusal — an index past the end, a
buffer never given storage.
The twins are written over two raw-tier forms, try_slot_storage(n) and try_heap(v)
(below); a program writes the twins.
An export can answer every refusal inside its call instead. @out_of_memory(value) beside an
@export turns an allocation refused anywhere the call reaches, a twin or not, into value for the
export’s C caller. Every frame in between is unwound by returning, its defers, errdefers and
destructors run, and nothing it made stays allocated. That is the form for a library whose C API
answers an out-of-memory status (ffi).
References compare through their referent
== and != on two &Ts (or two &sync Ts) compare the objects as T does wherever T has an
Eq, written, derived or a built-in’s, and a &T hashes as T does wherever T has a Hash.
That is Rust’s &T rule:
struct Point derives Eq, Hash
x: int
y: int
main()
val a: &Point = Point(1, 2)
val b: &Point = Point(1, 2)
print(a == b, a != b, a === b, a === a)
true false false true
=== and !== are identity, always, and take two references or two pointers of one type and
nothing else — an integer has no identity apart from its value:
main()
print(1 === 1)
'===' compares the identity of two references or pointers, and int is neither — '==' compares its value
A trait object’s identity is the value it was made from, so it also meets an object over another trait, or a reference of the type it holds (traits).
- Where
Thas noEq, a reference is its own identity:==asks whether the two name one object, and the hash is the address’s, so aMap[&Node, V]keys by identity — what a hash-consing table wants. - A bound gets the same answer: inside a
[K: Hash + Eq]body at&Node,k.hash()andk.eq(o)areNode‘s where it has them and the address’s where it does not. A member call written on a reference reaches the referent’s own (r.hash(),r.eq(*s)). A struct derivingEqorHashover a&Tfield, and a tuple of references, compare and hash each reference the same way. - A method the referent declares itself wins at a member call, and only there. An inherent
hashoreqwith noimpl Hashorimpl Eqis whatr.hash()calls on a&Node,&sync Nodeor*Node, but==, aMapkey and a bounded body still see aNodewith neither, and use identity. - A referent with an
Eqand noHashmakes a reference that is no key, and is refused rather than keyed wrongly. To key by identity where the referent defines equality, wrap the reference inByAddress, whoseEqis===and whoseHashis the address’s. - A reference to a reference compares as the inner reference does. A trait object (
&Shape) has no==, and its===compares the objects. A pointer compares and hashes by address, whateverTdefines. There is no ordering on a reference or a pointer. Its other bounds a reference meets through its referent (generics).
import sysl.container.{Map, map}
struct Tag derives Eq
id: int
main()
val tags = map[&Tag, int]()
print(tags.len())
Tag defines 'Eq' but not 'Hash', so a reference to it compares by its value and has no hash that agrees
weak T — breaking cycles
A cycle of strong references keeps itself alive — a parent holding its children while each child holds
its parent. A weak T does not keep its referent alive: when the last strong reference goes the
object is destroyed and every weak reference to it becomes empty.
struct Node
label: string
parent: weak Node
parent_of(n: &Node) -> string
n.parent.get() match
Some(p) -> p.label
None -> "(none)"
var root: &Node = Node("root", None)
var kid: &Node = Node("kid", root)
print(parent_of(root), parent_of(kid))
(none) root
- It is a type, not an operator. A
&Tbecomes aweak Twherever aweak Tis what the context asked for, and never the other way: becoming a&Tis the operation that can fail. - Reading one is a question,
get(), answeringOption[&T]with a count taken for the caller. No field, method or==is reached through a weak reference directly. - An empty one is written
None— the weak reference’s own empty value, not anOption— and it is the zero value ofweak T, so a struct with a weak field still has one.Noneis also the only default aweak Tparameter can have: anything naming an object would have to outlive every frame. weak &Tsays the mode twice, andweak sync Tis refused: upgrading an atomic weak reference is a compare-and-swap loop against a count another thread may be driving to zero.- Everything a
&Tmay point at — a struct, a scalar, an array, a generic instance, a trait object, a type parameter — may be held weakly.
struct Node
v: int
var r: &Node = Node(1)
var w: weak &Node = r
'weak Node' is already a weak edge to a counted Node, so the '&' says the mode a second time — write 'weak Node'
A weak reference may not be made from a value with nowhere else to live: boxing a construction straight into a weak position would leave the weak edge its only holder, and the object dead before the statement ended.
struct Node
label: string
parent: weak Node
var kid: &Node = Node("kid", Node("root", None))
print(kid.label)
a weak reference does not keep Node alive, and nothing else here holds this one
&sync T, *T and []T
&sync T is a &T with an atomic count, a distinct type with no conversion either way, chosen
where the object is allocated. It is the only kind that may cross a concurrency domain
(below).
A method’s reference receiver is one kind or the other, as its parameters are: a &self method
is called on a &T, and a &sync self method on a &sync T. A &self body retains and releases
its receiver with an ordinary count, which would race another thread’s on the same object; a
&sync self body may hand its receiver to another thread, where a &T may not go. The rule holds
for a field reached through a reference, a capture, self inside another method, a bound of a
generic, and a trait object’s slot alike, and @unchecked(Share) does not lift it, since it promises
the writes, not the counts. A method that only reads is written self, which either kind reaches.
struct Cell
n: int
impl Cell
get(&self) -> int = self.n
val c: &sync Cell = Cell(2)
print(c.get())
'get' takes '&self', and this receiver is a '&sync Cell' — '&Cell' and '&sync Cell' are distinct types, and neither converts to the other: a '&self' method may retain or release its receiver with an ordinary count while another thread holds the same object. Declare 'get' with '&sync self', or with 'self' where it only reads
struct Cell
n: int
impl Cell
get(self) -> int = self.n
keep(&sync self) -> &sync Cell = self
val c: &sync Cell = Cell(2)
print(c.get() + c.keep().n)
4
A field reached through a &sync T is read-only. Every thread holding the reference reaches the
same object at once, so a plain store races theirs: two c.n += 1 lose updates, and two stores of a
counted field release one value twice. An assignment, a compound assignment, a *self member called
on the field or on the object itself, a writable view of an array field, and a write further down
through a plain struct field are each refused, unless one of three things holds:
- the field is an
Atomic, written through its members — or a struct made only of atomics, locks and guarded fields, whose*selfmembers can write nothing else; - a
@guardsnames aprivatefield, so only the type’s own members write it. That they take the lock is not checked: the members are trusted. The library’sMutexandGuardedtake it in every member (aMutexfield is one, and the library’s locks —SpinLock,SleepLock,Condvar,Barrier,Channel— are used through their own members); - the type is
@unchecked(Share), the other trusted form: the program’s promise that its writes are synchronised another way.
A field that is itself a &sync U may be read, and its own fields follow the same rule. A *T
reached through one leads to storage the object does not hold, and is the raw tier’s as everywhere. An
@unchecked block licenses unchecked indexing, not a race, so a write inside one is refused all the
same.
struct Cell
n: int
val c: &sync Cell = Cell(0)
c.n += 1
this '+=' writes a field reached through a '&sync Cell', which is read-only: every thread holding the reference may reach it at once, and a plain write would race theirs. Make the field an 'Atomic', name it in a '@guards' (the field is then private, so only the type's own members write it, and they must take the lock, which is not checked), or write '@unchecked(Share)' above 'Cell' where its writes are synchronised another way
The counter that is meant to be shared is an Atomic:
import sysl.sync.Atomic
struct Hits
n: Atomic[int]
val h: &sync Hits = Hits(Atomic(0))
h.n.add(2)
print(h.n.load())
2
*T is C’s pointer: no length, no count, manual lifetime. The address of the frame’s own storage
is checked by the lifetime rules below; past that it is the raw tier, which carries
C’s whole surface because a subset would only mean a kernel that could not be written here.
bump(n: *int)
*n += 1
var counter = 41
bump(&counter)
print(counter)
42
A view is three words: { owner, ptr, len }, 24 bytes on a 64-bit target. ptr and len name
the range and owner keeps the bytes alive, since sysl has no collector to find an object from an
interior pointer. Taking a view of heap storage retains, dropping one releases, slicing stays O(1),
and a view of heap storage survives the buffer growing or being dropped:
tail() -> []int
var xs: []int = [1, 2, 3, 4]
xs[2..]
var t = tail()
print(t.len, t[0], t[1])
2 3 4
owner is null when there is nothing to keep alive — a view of static data, of a *T region, or
of a local fixed array — and retaining or releasing such a view is a no-op, so allocator-free code
slicing a static or stack buffer pays nothing. A view of a local array is the case the compiler checks
(escape analysis). A string is exactly an immutable, validated []u8, with
one representation and one implementation.
Library types: a Buf is a shared handle
Buf[T] is a handle to a counted block, so assigning a Buf makes a second name for the same
buffer, as assigning a &T does, and a push through either is seen through both:
import sysl.buf.{Buf, buf}
var a: Buf[int] = buf()
val b = a
b.push(1)
print(a.len(), b.len())
1 1
A Map and a Deque are handles the same way. A buffer crosses a domain
only frozen.
Lifetimes are blocks
A *T is a type, so once one exists it can be carried anywhere — which is wrong for the address of a
local, good only until its block closes. Nothing in a type says how long storage lives. What the
compiler can see is what each body does with each address and view, so it works that out, and
nothing is written for any of it: no lifetime parameter, no @escaping, no “this result views
that argument” marker. The rules are twelve, and each section below is one of them.
A block’s local lives as long as its block
Frame storage ends with its block. Frame storage is a local, a by-value parameter or (self), or
a field or element of one; its block is the innermost one declaring it — a function body, an if or
else arm, a match arm, a for, while or loop body, a nested block. A loop body’s local is a
new variable every turn. A temporary ends with its statement.
So the address of a block’s local may not be kept anywhere still there after the block — a local of an
enclosing block, a field of one, a buffer an enclosing block holds, a closure stored in one — however
it gets there: through a local, a struct or variant built around it, a closure that captures it, a
call that answers it, a callee that stores it into what another argument points at, or a block or
break that yields it.
run()
var spare = ""
var q = &spare
if true
var s = "abc".copy()
q = &s
print(*q)
'&s' is the address of 's', a local of the 'if' block, and it is kept in 'q', which outlives that block — keep the value itself, or declare 's' where 'q' is declared
What a block lets go of when it closes is what its locals hold — a Buf‘s elements, the object a
&T names, a value with a Drop — so a pointer into that storage is refused where it is read after
the block:
import sysl.buf.{Buf, buf}
run() -> int
var n = 0
var p = &n
if true
val b: Buf[int] = buf()
b.push(41)
p = &b[0]
*p + 1
print(run())
'p' points into storage 'b' holds, and 'b' was let go of where its block ended — so this would read freed memory
Inside the block, and into it, the address is free: a local of the same block or a deeper one may hold it, a borrowing callee may be handed it, and an enclosing block’s local may be pointed at from inside. What leaves the block by value is a copy, and is never refused.
The entry file’s statements are the outermost block
The top-level statements of the file a program starts in are the program’s outermost block, and
their locals live until the program exits: that frame is laid down before anything else runs and given
back only as it ends. So it is the one body the outliving rules pass over — its locals’ addresses may
be stored in module storage, and a plain spawn may borrow them — and every other frame is held to
them:
static var held: *int = null
var n = 41
held = &n
print(*held + 1)
42
A borrowed pointer cannot escape
An address or a view of frame storage outlives its block when it is:
- returned, directly or inside whatever carries it back;
- stored anywhere the block cannot show is its own — module storage, the heap, a field reached through a pointer it did not make, a buffer’s slot;
- handed to a parameter that keeps it;
- captured by a kept closure;
- held by a task not awaited, or a thread not joined, inside the block — a call of an
asyncfunction is accepted only where its task is awaited orblock_on‘d before the lending frame ends (a task holds its arguments), and a thread that borrows a frame is started on a scope.
Unknown means foreign, and outliving is refused, except that a frame array or a closure box moves to the heap instead (escape analysis). The rule, asked at the call:
The address of storage that is not the program’s to give away — a local, a parameter’s place, a field of a value in the frame, a value made in place — may not be passed to a parameter that keeps it.
struct Registry
last: *int
remember(*self, p: *int)
self.last = p
run(r: *Registry)
var n = 5
r.remember(&n)
'remember' keeps its parameter 'p' (it is stored in 'self.last'), and '&n' is the address of a local of 'run'
A function that reads and writes through what it is handed, and passes it only to callees that only
use it, keeps nothing, and the address of anything may be passed to it — every *self method called
on a local is checked this way, and almost all of them keep nothing.
Returning the frame’s own storage is refused — whether it is the body’s value, a return‘s, an
arm’s tail, or wrapped in ptr_cast. (self) is a copy in the frame, so a (self) method handing out
a field’s address is the usual way to write it by accident. Storage reached through a pointer or a
reference — *self, &self, a *T or &T parameter, an element of a []T — is the caller’s to
keep alive, as module storage is, and may be answered. &make() makes a slot in the frame
(addressing a value), so returning it is refused the same way.
import sysl.raw.ptr_cast
struct Rec
a: int
b: int
struct Ev
rec: Rec
key(self) -> *u8 = ptr_cast(&self.rec)
the address of 'self' is returned, but '(self)' is a copy of the receiver in this frame, and its storage ends when the function returns — return the value itself, or take '*self', so the address is of the caller's value
Storing through an out-parameter is the caller’s to judge, but the address of a function’s own local written through any out-parameter — or through a pointer read out of one — outlives it:
leak(out: **int)
var n = 1
*out = &n
'&n' is the address of a local of 'leak', and it is stored in '*out', which outlives 'leak' — store the value itself, or storage that lasts
Storage the frame cannot show is its own is foreign. A place reached through what a call answered
— current().p, a chain of calls, a trait object’s answer, a local bound to any of them, an element of
a Buf — may be held by someone else long after the frame is gone. A call that answers its argument is
no exception: what else it may answer is not something its signature says. The frame’s own places stay
open — a local, a field or element of one, and what a local bound once to such an address, or to an
object the frame made, points at — and an address that lasts (module storage’s, or one a parameter
brought) may go anywhere.
struct Slot
p: *int
var the_slot = Slot(null)
current() -> *Slot = &the_slot
remember()
var n = 1
current().p = &n
'&n' is the address of a local of 'remember', and it is stored in 'current().p', which 'remember' cannot show is its own storage — store the value itself, or storage that lasts
An address held inside what is handed over
A function may let out what it reads through a pointer as well as the pointer itself. So the address of a local stored in a struct, an array or a view whose address goes to a callee is refused when the callee lets out what it reads there — stores it, pushes it, puts it in a heap object, hands it to a callee that does, or answers with it:
var last: *int = null
struct Holder
p: *int
keep(h: *Holder)
last = h.p
run()
var n = 5
var h = Holder(&n)
keep(&h)
'keep' lets what it reads through its parameter 'h' outlive the call (it is stored in 'last'), and what is read through '&h' holds the address of a local of 'run'
A callee that only reads through it, copies out a number rather than an address, or lets out only what it reads a step further — through the address the struct holds, which is not this frame’s storage — is accepted. How the address got there does not matter: copied out of a field, read through a pointer, chosen by a branch, stored after the struct was made, or answered by a call, it is followed into whatever is handed over at whatever depth, and asked of what the callee lets out of what it reads that many steps through its parameter. The fields are told apart: what the callee lets out is asked of the field the address sits in (a field of a field; an array field’s elements all alike; a union’s members are one field), and a read the callee cannot place by field — through a copy of the pointer, or the pointee whole — counts for every field.
Keeping is read off bodies
A parameter is kept if its body lets it, or a field path of what it points at, outlive the call, and the answer is followed into every callee, computed callees first, and settled over recursion at a fixed point: a recursive function keeps a parameter when one of its paths does.
import sysl.buf.{Buf, buf}
static var all: Buf[*int] = buf()
collect(p: *int)
all.push(p)
relay(p: *int) = collect(p)
run()
var n = 1
relay(&n)
'relay' keeps its parameter 'p' (it is passed to 'collect', which keeps it), and '&n' is the address of a local of 'run'
Taken back before it returns
A store into foreign storage that the same body overwrites on every way out is not a keep —
written over in the body, in a defer, or by a callee whose own body writes it on every way out. That
is how a sink is lent to a module for the length of a call:
static var spare = 0
static var held: *int = &spare
store(p: *int)
held = p
clear()
held = &spare
run() -> int
var n = 41
store(&n)
val seen = *held + 1
clear()
seen
print(run())
42
The place may be reached through a pointer, spelled out (s.vm.con) or through a local holding it
(val vm = s.vm), so long as the store and the overwrite are known to reach the same storage: a local
bound once holds one pointer, and a pointer read out of memory is the same one until a call, or a
store of a pointer of its type, may have changed it. A way out that skips the overwrite — an early
return, a ?, a call that never comes back, a break past it, one match arm without it — leaves
the pointer held, and writing a different place (another global, another field, the same field of
another instance) takes nothing back:
static var spare = 0
static var held: *int = &spare
store(p: *int)
held = p
clear()
held = &spare
run(c: bool)
var n = 1
store(&n)
if c then return
clear()
'store' keeps its parameter 'p' (it is stored in 'held'), and '&n' is the address of a local of 'run'
A local holding a copy of the parameter is followed along the same ways. Written over with
something else on every way to where it is stored, answered or its address handed over, it no longer holds the
parameter there; written over on only some — an if without an else, a loop body that may not run,
one match arm, a break or continue past the store — it still does. Only a store of the whole
local counts as writing it over: a store through a pointer to it, or in a closure’s body, does not;
and the parameter stored back into it, by the body or by a callee handed its address, makes it a copy
again:
static var spare = 0
static var held: *int = &spare
note(p: *int)
var q = p
print(*q)
q = &spare
held = q
run()
var n = 41
note(&n)
run()
print(*held)
41
0
static var spare = 0
static var held: *int = &spare
note(p: *int)
var q = p
if *p > 50 then q = &spare
held = q
run()
var n = 41
note(&n)
'note' keeps its parameter 'p' (it is stored in 'held'), and '&n' is the address of a local of 'run'
The same holds of an answer (below): a copy written over on every
way to a return or to the body’s result is not what the function hands back there.
static var spare = 0
static var held: *int = &spare
pick(p: *int) -> *int
var q = p
print(*q)
q = &spare
q
run()
var n = 41
held = pick(&n)
run()
print(*held)
41
0
Handing it back is not keeping it
An answer made of arguments is lent for as long as those arguments live in the caller.
field(s: *S) -> *int = &s.y keeps nothing; the caller follows the answer as it follows the argument,
so keeping the answer is keeping the argument, and a function may not hand back an answer made of its
own frame:
struct S
x: int
y: int
field(s: *S) -> *int = &s.y
run() -> *int
var s = S(1, 2)
field(&s)
'field(&s)' is returned, but it holds the address of a local of 'run', whose storage ends when 'run' returns
What a value is built of goes wherever any part of it is read out: a field of a struct or a
tuple, and an element of an array, a literal’s or a local’s, is the value it was built from. So
[&y][0] is &y, and a closure placed in an array literal and read back out of it is the same closure
— one that a callee keeps lives on the heap, as it would if it had never been in the array:
leak(n: int) -> *int
var y = n
[&y][0]
'[&y][0]' is returned, but it holds the address of a local of 'leak', whose storage ends when 'leak' returns
struct Owner
n: int
struct Holder
act: &Fn() -> int
kept(run: &Fn(int) -> int) -> &Holder = Holder(() -> run(1))
make(o: &Owner) -> &Holder = [kept(k -> k + o.n)][0]
main()
val h = make(Owner(41))
print((h.act)())
42
A pointer the callee read out of what it was handed — q.first() answering self.head — is
somebody else’s address, and is the caller’s to keep.
Only a type that can hold an address carries a loan
An int, a bool, a float, a bare enum and a struct with no pointer in it answer nothing about
where their arguments lived, so Ok(n) after a C function filled &n is an ordinary value. A C
function’s pointer answer is taken to be made of its pointer arguments that could hold what it points
at — one to the same type or to a struct holding it, and bytes from bytes, as strchr‘s is — and not
of an out-parameter of another type, so a handle a library allocated is not made of the *i32 it
reported an error code through.
An object behind a trait holds an address only where some type the program makes one of does. A
program’s build sees every type erased to each trait, so a &Shape whose every implementation holds
only numbers and counted references is as plain as they are, wherever it sits — the answer itself, a
field, an Option, a weak Shape — and a closure handed a local’s address may answer one:
trait Shape
area(self) -> int
struct Sq
s: int
impl Shape for Sq
area(self) -> int = self.s
through(f: &Fn(*int) -> &Shape) -> &Shape
var x = 3
f(&x)
main()
print(through((p) -> Sq(*p)).area())
3
One implementation that can hold the address — a *int field, a closure, an object of a trait that
can — makes every object of the trait able to; a generic trait is asked at its own arguments. A closure
behind a &Fn may hold anything, and so may every object in a build that does not see every table —
build-lib, and build-c, whose C half can be handed an object made where the build cannot look:
trait Shape
area(self) -> int
struct Sq
s: int
impl Shape for Sq
area(self) -> int = self.s
struct Pt
p: *int
impl Shape for Pt
area(self) -> int = *self.p
through(f: &Fn(*int) -> &Shape) -> &Shape
var x = 3
f(&x)
main()
var y = 1
val a: &Shape = Pt(&y)
print(through((p) -> Sq(*p)).area() + a.area())
'f' is returned, but it holds the address of a local of 'through'
An address as an integer leaves the analysis
An address as an integer is a number: usize(&marker) stored, handed on or handed back keeps
nothing, and outlives nothing. It is how a program measures its stack:
var top: usize = 0
mark()
var marker = 0
top = usize(&marker)
here() -> usize
var marker = 0
usize(&marker)
main()
mark()
print(here() > 0 && top > 0)
true
Turning that number back into a pointer is the program’s responsibility. ptr_cast of an integer
is unchecked, as an as usize round trip is in Rust: the compiler follows no address through an
integer — not through module storage, a field, a parameter, an answer or arithmetic — and refuses
nothing; a ptr_cast read after the frame has returned compiles just the same and reads whatever the
slot holds by then. No unsafe block is asked for, and @unchecked has nothing to do with it: the
import sysl.raw.ptr_cast a file must write is where a reader finds every round trip. The address
kept as a pointer is still the analysis’s:
var top: *int = null
mark()
var marker = 7
top = &marker
mark()
'&marker' is the address of a local of 'mark', and it is stored in 'top', which outlives 'mark'
Where no body is in sight, the call borrows
A call the compiler cannot follow into a body is answered by its signature, and the answer is the one C programs live by — a pointer handed to a call is borrowed for the call:
| what is called | what it keeps |
|---|---|
| a sysl function | what its body keeps |
| a method through a trait object | what the trait’s declaration of the method says: nothing, unless it says @keeps(p), or @keeps(self) for the object itself; an async method’s task holds every argument until it is awaited |
a closure, a &Fn | nothing, unless its type marks the parameter @keeps; what is read through one it marks @lets_out may be kept |
| a function through a pointer | nothing, unless the pointer type marks the parameter @keeps or @lets_out |
an extern | nothing, and nothing it reads through a pointer, unless its declaration says @keeps(p) |
- The answer is fresh — an
extern‘s is storage the library made — unless the declaration says@answers(p), and then it is made of whatpwas handed. An inline-assembly output is fresh the same way. The answer of a call through an object may be made of the receiver, and of nothing else unless the declaration says@answers(p)— Rust’s elision rule for a method. A callable’s type cannot say@answers, so a call through one may answer with anything it was handed. - A body reached through such a type that keeps an unmarked parameter is refused where it is
written: an
implmethod keeping what its trait’s declaration does not name, a closure keeping its parameter, a function whose address is taken keeping one. The declaration of anexternis trusted: a C function holding a pointer past the call without saying so is a wrong declaration. - There is no whole-program answer: no table of the bodies a call through an object or a pointer may land in is consulted, since which one it lands in is decided when the program runs.
@answers(s)
extern "strchr" c_strchr(s: *u8, c: int) -> *u8
static var spare: u8 = 0
static var held: *u8 = &spare
find()
var text: [3]u8 = [104, 105, 0]
held = c_strchr(&text[0], 105)
'c_strchr(&text[0], 105)' holds the address of a field of 'text', a local of 'find', and it is stored in 'held', which outlives 'find'
trait Bump
bump(*self, n: *int)
struct Keeper
held: *int
impl Bump for Keeper
bump(*self, n: *int)
self.held = n
'bump' keeps its parameter 'n' (it is stored in 'self.held'), but a method of 'Bump' borrows its parameters for the call
A default is a promise, so the body behind it is held to it. That is what makes a lock’s with
safe without an annotation: the closure it calls borrows the value’s address for the call, and a
closure that keeps it is refused where it keeps it — the one mistake a returned address could not
prevent, using it after the release:
struct Cell
v: int
with[R](*self, body: *int -> R) -> R = body(&self.v)
static var spare = 0
static var kept: *int = &spare
var c = Cell(1)
c.with((v) -> *v += 1)
print(c.v)
c.with((v) -> kept = v)
a closure borrows what it is handed for the call, and this one keeps its parameter 'v' (it is stored in 'kept')
A closure is judged where it is written, capture by capture, by what its body lets out of each,
and again at every call it is handed to, so it makes no difference whether a call runs it, it is boxed
behind a &Fn, or a @scoped member runs it later. A capture holding the frame’s address that the
body stores in module storage, or into what a parameter of the closure points at (a lock’s with
hands the body the value a module lock guards), outlives the frame. So does &capture written in the
body: the closure holds the capture by value in its own storage, and the refusal points at the closure,
never into the body of whatever runs it. A capture of a heap value or a plain number is stored freely.
static var idle = 0
static var kept: *int = &idle
run(f: () -> unit) = f()
closure() -> int
var n = 5
val p = &n
run(() -> kept = p)
0
print(closure())
a closure lets its capture 'p' outlive the call (it is stored in 'kept'), and 'p' holds the address of a local of 'closure' — capture the value itself, or storage that lasts
A callable that keeps what it is handed
A callback that keeps what it is handed — an interpreter’s primitive putting its handle into the term
it builds, a visitor collecting nodes — says so in its type, with
@keeps on the parameter:
&Fn(@keeps *Handle) -> Step, or *extern(*M, @keeps *isize) -> unit for a function pointer. A
closure or function taken at that type may keep that parameter, and every other parameter is still
borrowed. A call through the type is held to the mark the way a call of an extern is held to its
@keeps(p): the address of storage that ends is refused there, and a function handing its own
parameter on there keeps it. A pointer that keeps nothing stands where a marked one is asked for,
never the other way round.
import sysl.buf.{Buf, buf}
struct Handle
n: int
type Visit = &Fn(@keeps *Handle) -> unit
var seen: Buf[*Handle] = buf()
visit_one(f: Visit)
var mine = Handle(1)
f(&mine)
a call through '&Fn(@keeps *Handle) -> unit' keeps its parameter 1 (its type says '@keeps'), and '&mine' is the address of a local of 'visit_one'
Without the mark, the closure is refused where it keeps the parameter, and told the type that would let it. An unmarked parameter is answered by the type, never by the closures made at it: the call borrows the argument and everything read through it, so a closure that lets out what it reads through a pointer is refused as well, whatever any caller hands it.
import sysl.buf.{Buf, buf}
struct Handle
n: int
var seen: Buf[*Handle] = buf()
val f: &Fn(*Handle) -> unit = (h) -> seen.push(h)
a closure borrows what it is handed for the call, and this one keeps its parameter 'h' (it is passed to 'push', which keeps it) — whoever calls it may hand it the address of their own storage. Copy what this needs into storage of its own, or let it keep it by marking the parameter '@keeps' in the type it is made at: 'Fn(@keeps *Handle) -> unit'
A call through a function pointer borrows every argument, so a function whose address is taken is held to that where it is written — even one that only stores what it is handed into what another parameter points at, such as a primitive writing its stack pointer back into the machine — unless every type its address is taken at marks the parameter:
struct M
sp: *isize
type Code = *extern(*M, *isize) -> unit
halt(m: *M, sp: *isize)
m.sp = sp
var stack: [8]isize
var m: M
m.sp = &stack[0]
val f: Code = &halt
f(&m, m.sp)
'halt' keeps its parameter 'sp' (it is stored in 'm.sp'), and its address is taken — a call through a function pointer sees no body
A loop nothing leaves is a way out of a function whose address is taken, holding what it holds
at its head. Called where its body is in sight, such a function never returns to its caller, whose
frame therefore outlasts everything it stores; but a pointer may be handed to a starter —
Context.start, spawn — that returns while the body runs
on, so an entry that stores its argument and then loops is refused as one that returns, and so is an
entry that hands its argument, at any depth, to a function that stores it and loops for ever:
import sysl.fiber.{Context, Stack, switch}
struct Job
home: Context
me: Context
var held: *Job = null
var job = Job(Context.new(), Context.new())
serve(j: *Job)
held = j
loop
switch(&j.me, &j.home)
entry(j: *Job)
serve(j)
main()
val s = Stack.reserve(65536).unwrap()
job.me = Context.start(s, &entry, &job)
switch(&job.home, &job.me)
'entry' keeps its parameter 'j' (it is passed to 'serve', which keeps it), and its address is taken — a call through a function pointer sees no body
A callable that only lets out what it reads is marked
@lets_out:
*extern(@lets_out *Heap) -> unit. A function or closure taken at the type may let out what it reads
through that parameter, and is still refused where it keeps the parameter itself. A call through the
type borrows the argument — a collector’s heap on the caller’s stack may be handed there — but what is
reachable through it may be kept anywhere, so storing the address of storage that ends into it before
the call is what is refused.
A stored callback keeps what it captured, and nothing else. Storing a closure — in a field, module
storage, a buffer, a trait’s implementation — is refused only where it captured an address that is not
the program’s to give away; one capturing nothing, a number, a &T, a string or a struct by value may
be stored anywhere. A trait’s method borrows a view it is handed the same way
(traits).
static var later: &Fn() -> int = () -> 0
install(f: &Fn() -> int)
later = f
run()
var n = 7
val p = &n
install(() -> *p)
'install' keeps its parameter 'f' (it is stored in 'later'), and '() -> *p' holds the address of a local of 'run'
Escape analysis
A frame array or closure box that would outlive its block moves to the heap, silently. Its type
stays the same, --explain-escapes lists every move, and it is refused only where there is no
allocator. A view of a local fixed array has a null owner and is good only while the frame lives, so
the compiler finds the views for which that matters:
| a view of | owner | safe to keep? |
|---|---|---|
| a heap buffer | the buffer | yes — retained |
| static data, a string literal | null (immortal) | yes — never freed |
a *T region | null | the programmer’s problem — unless a @views(self) member hands it out |
| a local fixed array | null | only while the frame lives |
A view of a local array escapes when it is returned (directly or inside a struct, an enum, an
Option, a tuple or one slot of a multi-result list), stored into anything that outlives the frame,
passed to a parameter the callee keeps, captured by a closure that escapes, or assigned into a local
that escapes (resolved as a fixed point over the function’s locals). Indexing, iterating, sub-slicing
into a local that stays local, comparing and passing to a callee that only reads allocate nothing.
Field by field: a callee storing s.a lets out the view in s.a and not the one in s.b — of a
struct built where it is passed (keep(Pair(xs[0..<2], ys[0..<2]))), or bound to a local never
assigned again nor lent by address (val pr = Pair(…) then keep(pr)), since a local assigned again
is a single value that lets out everything it views — and a
result whose type cannot hold a view is not taken for one. An element read out of a view is a copy:
a callee that keeps the strings of a []string, or answers one of them, lets out what those strings
view and not the array the slice was taken from, unless an element holds an array of its own in place. A call with no body — through a trait
object, an extern, a &Fn, a function pointer, or an async call whose task is not awaited where it
is made — lets out what its declaration says, and a view handed to a callable is promoted, since no
type says a view is only borrowed.
With an allocator, the array is promoted: allocated as a counted buffer instead of a stack slot,
with the view’s owner pointing at it, and nothing else changes:
render() -> []u8
var line: [8]u8
line[0] = 104u8
line[1] = 105u8
line[0..<2]
var l = render()
print(l.len, l[0], l[1])
2 104 105
- The array keeps its type, and only its storage moves. A promoted
[8]u8is still a[8]u8— a constant length, a value that copies on assignment, every index emitted as before. - Which array moves is the root of the escaping view. An index step is walked through, since an element of a local array of arrays is part of that array; a field step is not. Only arrays both viewed and escaped move.
- A temporary moves too. An array the frame computed and nobody named — a literal, a call’s answer
such as a
[32]u8digest sliced straight into module storage, a field of either — is nobody’s, so it is this frame’s, and a view of it that gets out is given storage of its own. A...Tvariadic packs its arguments into exactly such a literal. A literal written where a[]Tis expected and handed to a call that keeps nothing of it, and whose answer could not carry a view of it, is laid in the frame and allocates nothing. - A view that outlives its scope is promoted too, not only one that leaves the frame: a
temporary’s view kept in a local read on later lines, and a view of an array declared in a loop body
or an
ifarm kept in an enclosing block. Nothing moves where nothing outlives anything. - Module storage is never a root, whatever the path to it; it outlives every frame where it is.
- An element of a view or of a
Bufis not the frame’s storage:rows[i][..]andb[i][..]carry the owner of the storage they live in, and outlive the buffer growing or being dropped. A program’s own container writesindex_viewto answer its storage’s view, and is the same — it is never written for it, and a view of part of an element through the trait’s default is refused (arrays); one whose elements are its own bytes is the frame’s where it is, so a view of part of one may leave a frame only when the container lives in module storage or behind a*T.
Two roots have nowhere to be promoted to, and are refused: an array a caller passed by value, which is the caller’s layout, and an array that is a field of a named struct on the frame, since a field moves only with its struct. A part of a temporary is not one of them: the whole temporary moves.
first_two(a: [4]int) -> []int = a[0..<2]
print(first_two([1, 2, 3, 4]).len)
a slice of an array this frame owns is returned, so it would outlive the array, and the storage is not this body's to move — 'a' is an array this body holds by value without having declared it, such as a parameter, so there is no declaration to move. Declare it as a '[]T', which makes a buffer of its own and owns it, or as a '&[N]T' where the length is fixed
Without an allocator every promotion is a compile error at the view, and so is every literal
argument a callee keeps. A @no_alloc module is told it declared so; a machine whose manifest says
capabilities { heap = false } is held to the same line in every module, and the refusal names the
machine ('thumbv7em-freestanding' provides no allocator) rather than leaving the link to say
undefined symbol: malloc. Growable arrays, escaping closures and &T creation are refused there the
same way.
@no_alloc
first() -> int
var keep: []int = []
for i in 0..<3
if i == 0 then keep = [i * 10][..]
keep[0]
print(first())
this view of an array literal is kept in 'keep', which outlives it, so the array would move to the heap to outlive its statement — and this module declared '@no_alloc', so there is nothing to move it into
A box nothing keeps is laid in the frame
The same analysis runs the other way for a &T. A box the frame builds and nothing keeps past the
frame is laid in the frame, not on the heap: the header and the payload a heap box has, counted the
same way, in a slot of the frame. The destructor still runs when the last count goes, at the end of
the scope as before; only the allocation is gone. A factory — a function whose answer is a box it
built and kept nowhere else — lays that box in its caller’s frame wherever the caller keeps it no
longer than itself. So does a function whose answer is the box another factory’s call answers it,
kept nowhere else: counter_plus below hands its caller’s slot on to counter, however deep the
chain.
struct Counter
n: int
counter(start: int) -> &Counter = Counter(start)
counter_plus(start: int) -> &Counter
val c = counter(start)
c.n += 1
c
struct Res
n: int
impl Drop for Res
drop(self) = print("closed", self.n)
read(r: &Res) -> int = r.n
main()
val c = counter(5)
c.n += 2
print(c.n)
print(counter_plus(1).n)
val r: &Res = Res(1)
print(read(r))
print("end")
7
2
1
end
closed 1
None of the boxes above touches the heap. A box stays on the heap wherever it may get out: stored
anywhere but a local of the frame (module storage, a field reached through a reference or a pointer,
a buffer, another box), returned other than as a factory’s answer, captured by a closure, handed to a
parameter whose body may let it out or answer it into something that does, weakened, given up with
into_raw, carried out of a loop by break, or held by a local that outlives the loop turn that
built it. A view of an array inside a box owns the box, so a view that gets out keeps its box on the
heap. Each capture of a closure is a holder of its own: a closure handed to a parameter of its own
type that captures the box beside something else, and keeps only that something else
(each(xs, x -> pool.append(node)) keeps node, not pool), leaves the box in the frame; one that
stores the box through another capture, or hands it to a call that keeps it, does not. A call through a trait object or a callable is a call of every body its table may hold — in
a program, which sees every table there is, each method or closure of that trait at the receiver’s own
arguments; the box stays in the frame where none of them lets it out. A call with no body in sight — a
C function pointer, an extern, a trait object or a callable in a library, which may be handed one
whose table it never saw — answers “it may get out”, as does a task’s body and a payload over a
kilobyte, which every frame of a recursion would pay for. A recursion is settled at a fixed point:
a box handed to a recursive function, or to a cycle of functions calling one another, stays in the
frame unless one of their paths lets it out. A &sync T is never laid in a frame.
trait Reader
read(self, p: &Point) -> int
struct Point
x: int
y: int
struct Sum
k: int
impl Reader for Sum
read(self, p: &Point) -> int = p.x + p.y + self.k
main()
val r: &Reader = Sum(1)
val p: &Point = Point(3, 4)
print(r.read(p))
8
Neither r nor p touches the heap: the one table of Reader holds a read that only reads both. Nothing here is visible to the program but the allocator: a
frame box prints, compares and drops exactly as a heap box does.
Where every share of a frame box is taken and given back by the body that laid it, the compiler
counts them, not the program. No count is taken or given back at run time: the point where the
last share would have gone runs the destructor and lets go of what the payload holds, exactly where
it ran before, on every way out of the scope — the end of a block, a return, a ?, a break or
continue out of the loop turn that built it. c and r of the first example, a box held by two locals, a
temporary handed to a call, a box a closure captures, a box lent to a callee that takes shares of its
own, a box handed to a call through a trait object or a callable whose every body leaves it alone (p
above), and a trait object or a callable that is itself a frame box, held in a local and called or
handed to a call that leaves it alone (r above): each is counted by the compiler. A local that may
hold one of two boxes — one assigned again — or the answer of a call that may be the box itself,
leaves that box counted at run time, as above; the program cannot tell the two apart. So does a trait
object held inside another value (an Option[&Reader]), and a closure capturing a box handed through
a table.
Promotion is silent, not hidden
--explain-escapes reports every promotion and the route that forced it — one line per array, in
source order, on stderr, accepted by every subcommand, at the view that forced the move rather than
the declaration. This is Go’s -m. A program that must not allocate says no alloc, and the
compiler then enforces it rather than reporting it.
$ sysl build --explain-escapes tty.sysl
tty.sysl:31:12: 'buf' is promoted to the heap, because this view of it is returned
The .bytes of a string that may hold its bytes in itself
is a slot of the frame in the same way, and a view of it that outlives the frame is a copy, reported
on its own line at the .bytes:
name.sysl:8:5: 's.bytes' is the bytes of a string that may be held in the string itself, so it is copied to the heap, because this view of it is returned
sysl test takes the flag as a build does, and sysl test <library> --std --explain-escapes is how
the standard library’s own promotions are listed.
A box the frame does not lay is reported too, after
the arrays and closures: one line per &T construction and per factory call whose box is on the
heap, at the construction or the call, naming the first way out the analysis met. Where the box
is handed to a callee that lets it out, the line says how that callee does, in parentheses, as far
down as the calls go. A box laid in its frame says nothing, and nor does a factory’s own answer,
which each of its calls reports where that call put it.
struct Counter
n: int
var kept: Option[&Counter] = None
counter(n: int) -> &Counter = Counter(n)
keep(c: &Counter)
kept = Some(c)
count(n: int, c: &Counter) -> int
if n == 0
keep(c)
return c.n
count(n - 1, c)
main()
val a: &Counter = Counter(1)
kept = Some(a)
keep(counter(2))
print(count(3, Counter(3)))
val quiet: &Counter = Counter(4)
print(quiet.n, kept.unwrap().n)
kept = None
3
4 3
$ sysl run --explain-escapes counters.sysl
counters.sysl:19:23: a 'Counter' is boxed on the heap, because it is stored in 'kept' on line 21
counters.sysl:22:10: what 'counter' answers is boxed on the heap, because it is handed to 'keep' on line 22, which keeps its parameter 'c' (it is stored in 'kept' on line 9)
counters.sysl:23:20: a 'Counter' is boxed on the heap, because it is handed to 'count' on line 23, which keeps its parameter 'c' (it is handed to 'keep' on line 13, which keeps its parameter 'c' (it is stored in 'kept' on line 9))
A recursion is reported by what its body does at the bottom: count hands its parameter on to
itself and lets it out only through keep, which is the reason given.
The other reasons a line gives are the rest of the ways out listed above:
stored in a place that is not the frame’s own (“is stored in ‘h.c’”), returned other than as a
factory’s answer, captured by a closure, built into another box or into a value with a destructor,
weakened, carried out of a loop by break, kept in a local that outlives the loop turn that built
it, handed to a call with no body in sight, a payload over the kilobyte a frame lays, a destructor
that may let its payload out, a body that is async, and a factory whose parameter is lent by
address, which therefore has no frame entry.
The idiom worth reaching for first, even with an allocator, is return a count and let the caller
slice its own buffer — what snprintf does, and what most kernel code wants.
Views own their heap storage, and a lent view takes no count
A view of heap storage owns a count of it, so it survives growth and drop and may escape. A view that is only lent — handed to a call, or held in a local that never outlives its block — needs no count of its own while its parent’s count holds the storage (what a count costs).
A view of storage inside a &sync T may therefore be lent, but may not escape. A count taken
through a view is the ordinary one, so such a view takes none at all: sum(f.data[1..<3]) on a
&sync Flash is accepted, and the same view returned, stored past the frame, captured by a kept
closure or held by the callee is refused. The box must be reached through a binding that keeps
holding it, in a body and in a module initializer alike — not a field of another box, a module
var, or a local the body stores into
(arrays) — and the view may not be held in a local declared outside that
binding’s block, since the binding, and the box with it, ends there. Such a view is a []const T,
its elements being read-only through the &sync:
struct Flash
data: [8]i32
make(k: i32) -> &sync Flash = Flash([k, k, k, k, k, k, k, k])
main()
var v: []const i32 = []
if v.len == 0
val b = make(7)
v = b.data[0..<2]
print(v.len)
is kept in 'v', a local of the body, which outlives that block
A view borrowed from its receiver
A null owner is right for static data and wrong for memory a C library owns: an object wraps the
library’s handle, frees it in its destructor, and hands out a view of what the handle points at, which
nothing keeps alive. @views(self) on the member says so, and the compiler holds every caller to
it:
extern "malloc" c_malloc(n: usize) -> *u8
extern "free" c_free(p: *u8)
struct Column
p: *u8
n: usize
@views(self)
bytes(&self) -> []const u8 = self.p[0..<self.n]
impl Drop for Column
drop(self)
print("freed")
c_free(self.p)
open(n: usize) -> &Column
val p = c_malloc(n)
for i in 0..<n do p[i] = u8(65 + i)
Column(p, n)
sum(xs: []const u8) -> int
var t = 0
for x in xs do t += int(x)
t
run()
val c = open(3)
val v = c.bytes()
print(v.len, v[0], sum(v[1..<3]))
run()
3 65 133
freed
The view is an ordinary []const u8. The mark adds one lexical fact: the view lives no longer than
the name it was called through, and four things are refused:
- a receiver that is not a name — a temporary is freed at the end of its statement;
- the view leaving the function that holds its receiver — returned, or what the body comes to,
unless the member is itself
@views(self)and the view is borrowed from its ownself; - the view stored where it outlives the receiver — a local bound before the receiver, a field reached through a reference or pointer, module storage (a local bound after it, or a struct value one holds, closes first and is fine);
- freeing the receiver while a local holding the view is in scope — assigning the name, a
*selfcall on it, or a call that may write an object of its type.
One thing changes at run time, and it is what those four rules make safe: a member that takes
*self reads self.bytes of a string where the caller holds it. A string of a few bytes
holds them in itself, so
s.bytes is ordinarily a copy in the frame that took it, and a member answering that copy would
have to copy it again to the heap to hand it back. In a @views(self) member taking *self the
string is at the caller’s address, which the view may not outlive and which may not be written while
it is held, so the view is made over that storage — no slot and no copy, short or long. A (self)
member, or one without the mark, keeps the copy. Search.view_in_place is written this way, which is
why a search of a short string allocates nothing:
trait Bytes
@views(self)
lend(*self) -> []const u8
impl Bytes for string
@views(self)
lend(*self) -> []const u8 = self.bytes
var s = 1234.to_string()
val b = s.lend()
print(b.len, b[0])
4 49
What a view is copied into — a sub-slice, a struct or Option around it, a closure capturing it, a
name a pattern binds, a loop variable over a view of views — is borrowed from the same receiver; a
value that cannot hold a view (v.len, v[0], a rendered string, a &sync T) is borrowed from
nothing. A call handed the view answers with it only where its body does: encode(out.view_mut())
answering a Result[Buf[u8], string] it built is borrowed from nothing, while id(v) -> []u8 = v
hands the view straight back. A call through a function value or a trait object names no body, so
its answer is taken to hold everything it was handed.
extern "free" c_free(p: *u8)
struct Column
p: *u8
n: usize
@views(self)
bytes(&self) -> []const u8 = self.p[0..<self.n]
impl Drop for Column
drop(self) = c_free(self.p)
open() -> &Column = Column(null, 0)
print(open().bytes().len)
'bytes' answers a view borrowed from what it is called on, and that is the value 'open' answers — a temporary, freed at the end of this statement
extern "free" c_free(p: *u8)
struct Column
p: *u8
n: usize
@views(self)
bytes(&self) -> []const u8 = self.p[0..<self.n]
impl Drop for Column
drop(self) = c_free(self.p)
run()
var c: &Column = Column(null, 0)
val v = c.bytes()
c = Column(null, 0)
print(v.len)
'v' is a view borrowed from 'c', and this assignment could free what it views
It is narrow on purpose. The mark names only self, marks only a member whose result is a view
([]T, []const T, string), and is in no type: no lifetime parameters, and no borrow tracked
through a struct a member returns. A trait member may carry it, and then a call through a trait object
is held to it; an implementation inherits it, and an implementation may not add it where the trait’s
member lacks it. A marked member is called only on a value (Column.bytes(c) is refused). A member
whose answer is simply read out of its receiver’s storage needs no mark: the compiler works that out
from the body (below).
Nothing moves under a live interior name
While a pointer, a ref or a view into relocatable storage is live, what could move or free that
storage is refused: a @relocates call, an assignment to an owning step of its path, and a write
through a second name. The check is decided from types and from what callees’ bodies write, and never
asks where the name is used — the question that would need lifetimes.
The one rule: what may move underneath it
A stored address is only as good as the storage staying where it is. C# has ref locals and needs no such rule, because its collector keeps the old array alive; sysl has none in this tier:
struct Table
cell: []int
swap(*self)
ref e = self.cell[0]
self.cell = [0; 8]
print(e)
end Table
var t = Table([1, 2, 3])
t.swap()
'e' is a 'ref' standing on storage this assignment would release, so the name would be left pointing at freed memory
While a ref is live, no step of its place that could come to name different storage may be assigned, and no mutating method may be called on a prefix of one. The discriminator is ownership, not indirection — only a step that releases something when overwritten can strand it:
| step | hazard? | why |
|---|---|---|
a &T | yes | overwriting it drops what it held, and that release may be the last |
a view ([]T) | yes | the same — a view owns its buffer |
a *T | no | a raw pointer owns nothing, so p = q frees nothing |
| a field, a fixed array, or an element of one | no | that storage is the enclosing object’s bytes |
A step is held still when it is an owning step the path goes through, so the place itself is
never held: ref r = h.node names the slot, and r = other and h.node = other are one statement
written two ways, while h = other on a &Holder is refused. Writing a value that holds an owning
step by value writes the step too (h = H(…)). A program reaching its tables through a *Self
receiver has no owning step in its chains and is asked for nothing.
- A
*selfcall on the owner is refused whether or not that method reassigns anything — a module compiles against signatures, and the cost is writing the ref one line later. - A call that runs a closure writing an owning step is refused — the closure handed directly,
through a local, a
&Fnor a struct, or called; one writing only storage the ref does not stand through is run without complaint. - A
@relocatesmember moves a container’s storage whatever its receiver mode. ABufis a handle, sopushtakesselfand still reallocates; each member that can move the storage or give an element up is marked, and the mark is what the check asks.
import sysl.buf.{Buf, buf}
var b: Buf[int] = buf()
b.push(1)
ref first = b[0]
b.push(2)
first = 5
'first' is a 'ref' standing on an element whose storage 'push' could move or give up, since it is '@relocates'
A *T taken by & into the same storage is held to the same rule for as long as it is live — the
pointer, a copy, or an address computed from it. A pointer has no block, so what counts is its last
use on any path, a later turn of a loop and a defer (a use on every way out of its block) included;
once the last use is behind it, the storage may move freely. A pointer kept in a local aggregate is
followed through it, and so is one into what a match arm, an is test or a for bound out of a value
made for it.
import sysl.buf.{Buf, buf}
run() -> int
val b: Buf[int] = buf()
b.push(41)
val p = &b[0]
for i in 0..<100 do b.push(i)
*p + 1
print(run())
'p' is a pointer to an element whose storage 'push' could move or give up, since it is '@relocates', and it is used after this call
A function handed the buffer is asked what its body does with it: one that calls a @relocates
member on a parameter, or hands it on to one that does, may not be handed a pointer into that argument
too, nor may the pointer be used after the call.
A second name for the same object is held to the rule. Whether two &Ts or Bufs name one object
is a run-time fact, so the question is asked of types: while a ref stands inside storage a value
of type T holds, writing storage held in any T other than along the ref’s own path is refused —
directly, or by a call whose body (or anything it reaches) may write a T. A call through a closure
names no body and is refused; a call through a trait object is a call to the method in that slot of
every table the program has for the trait, in a program’s own build, and names no body in a library’s
(edge cases); a function with no body in the program is judged by what it can get hold of. A callee reaching a @relocates member on a buffer of the
ref’s type writes it too, however it got the buffer.
struct Node
cell: []int
struct H
node: &Node
var h = H(Node([1, 2, 3]))
ref e = h.node.cell[0]
val n = h.node
n.cell = [7; 8]
e = 5
'e' is a 'ref' standing on storage held in a 'Node', and this assignment writes one that may be the same object by another name
A root the body holds is no other name’s to free. A ref whose place starts at a parameter or a
local of its own body, through a &T or a view, stands in an object that slot keeps alive for the
whole call — a parameter by the caller’s
guarantee, a local by its own count — so a call
that may write a T by another name writes beside the ref, never under it. Only writing the slot
itself could let the object go, and a call can do that only through the slot’s address: an & of it,
a ref bound to it, or a nested function’s environment, anywhere in the body. Such a body is asked
about the slot’s type as before, and so is a root in module storage; an owning step past the root (a
&Child field) is asked about by its holder’s type whatever the root is.
struct Inner
n: int
bump(*self) = self.n += 1
struct Node
id: int
inner: Inner
next: Option[&Node]
impl Drop for Node
drop(self) = print(s"drop ${self.id}")
touch(o: &Node) = o.next = None
walk(node: &Node, other: &Node)
ref r = node.inner
touch(other)
r.bump()
print(s"bumped ${r.n}")
val b: &Node = Node(2, Inner(20), Some(Node(1, Inner(10), None)))
walk(b.next.unwrap(), b)
print("back")
bumped 11
drop 1
back
drop 2
touch lets go of the only field that held node 1, and the caller’s guarantee for
b.next.unwrap() is what keeps it until walk returns.
What stays open is everything that cannot be the ref’s storage: other fields of the ref’s own object
along its path (h.node.count = 2 beside ref e = h.node.cell[0]), values of unrelated types, calls
whose bodies only read, and anything once the ref’s block has closed. A view of a buffer is not a
pointer into it: it keeps its storage, so growing the buffer under a view is accepted. What this does
not make safe is a *T: a ref rooted at a raw pointer, or storage reached through a reinterpreting
cast, is the raw tier’s bargain.
Capture follows keeping
A borrowed closure refers to its captures, and a kept closure holds copies. A closure that is
returned, stored where it outlives the block, handed to a parameter that keeps it, built in an async
body, or erased into a &sync Fn holds a copy of each variable, taken when it is built; otherwise it
holds each variable by reference, and a write in it is a write to the variable. A val array, struct,
string or other aggregate is held the same way, by reference where the closure is borrowed, and so is
one a scoped thread shares with the frame that opened its scope
(expressions).
A reference to a local costs a pointer and takes no count, and a borrowed closure handed on as a &Fn
is built in the frame:
import sysl.buf.{Buf, buf}
each(xs: []int, f: int -> unit)
for x in xs
f(x)
var best = 0
var xs = [3, 9, 2]
each(xs[..], n -> if n > best then best = n)
var n = 1
val peek = () -> n
var kept: &Buf[&Fn() -> int] = buf()
kept.push(() -> n)
n = 5
print(best, peek(), kept[0]())
9 5 1
A write to a copy that is read after it would be lost, and is refused — where the closure never reads the capture back, or the enclosing body uses the variable after the closure (expressions). So is a write to a by-value parameter that nothing reads after it (declarations):
var later: Option[&Fn() -> unit] = None
install(f: &Fn() -> unit) = later = Some(f)
var hit = false
install(() -> hit = true)
print(hit)
this closure captures by value, since it is handed to 'install' on line 6, which keeps its parameter 'f' (it is stored in 'later'), so it holds a copy of 'hit' — so assignment would reach that copy rather than the variable it came from, and nothing in the closure reads it back. Where you mean to change 'hit', hold it as a '&bool' and write through it, or have the closure return the value
struct Counter
n: int
bump(c: Counter) = c.n += 1
var c = Counter(1)
bump(c)
print(c.n)
this '+=' changes 'c', a copy of what the caller passed, and nothing reads 'c' afterwards, so the change is lost — take 'c: *Counter' to change the caller's value, or return the value
A value’s own storage is not foreign
Where it is stored decides, not only that it is. None of these is a keep:
- a pointer stored into what it points at — a node linked to itself, a struct whose field points into its own buffer — which ends exactly when that storage does;
- nodes linked inside one local or one local array;
- a store into what another parameter points at, which is the caller’s to judge: if that argument points into the caller’s frame, the pointer stays in the frame too — so an out-parameter writes into the caller’s storage;
- a value pushed onto a
Bufthe function made itself, held only as long as that buffer — unless the buffer gets out (returned, stored, captured by a kept closure, handed to a keeping callee) or something read back out of it is kept. A buffer the function was handed, reached through aref, or copied from module storage is not its own.
struct Node
next: *Node
v: int
link(a: *Node, b: *Node)
a.next = b
put(out: **Node, v: *Node)
*out = v
run() -> int
var nodes: [3]Node = [Node(null, 1), Node(null, 2), Node(null, 3)]
var last: *Node = null
link(&nodes[0], &nodes[1])
link(&nodes[1], &nodes[2])
put(&last, &nodes[2])
nodes[0].next.next.v + last.v
print(run())
6
The annotation layer
Every annotation is a promise the compiler checks against the body where it has one, and trusts where it has none. They exist for the code the rules above cannot see into:
| spelling | where | says |
|---|---|---|
@keeps(p) | extern, trait method | p may be held past the call (ffi, attributes) |
@keeps *T | a parameter of a callable or function pointer type | the same, for whatever is made at that type |
@lets_out *T | a parameter of a callable or function pointer type | what is read through it may be held past the call; the pointer itself is borrowed |
@answers(p) | extern, trait method | the answer is made of p |
@scoped(p) | a primitive | p is held only while the caller waits — a scope’s join, an await, a wake |
@bounded(f) | a function, a member | every run of the callable f finishes before the call returns, so a closure written there may capture the caller’s views and addresses (attributes) |
@views(self) | a member | the view it answers is borrowed from the receiver |
@relocates | a member | it may move or give up the receiver’s storage |
@crossing(p) | a function, a member | p reaches another concurrency domain (below) |
ptr_cast, @unchecked | expression, block | the unchecked tier; usize(p) is a number, and the compiler follows no provenance through integers |
Released in another context, the primitive says @scoped. A scope’s join, the deliver that ends
an await, a kernel’s wake hold a pointer past the call and let go of it somewhere the compiler
cannot follow, while the caller is suspended or still inside its scope. The primitive declares it once
with @scoped(p) and
is trusted, so block(&local) and await read(&buf) carry no annotation. Handing p on to a callee
that keeps it is refused unless that callee says @scoped too.
Threads
A thread borrows a frame only inside a scope
A *T that crosses into another domain is kept: the thread may read it after the starting call
has returned, so spawn(&work, &local) is refused whether or not the handle is joined afterwards —
spawn‘s arg is @crossing, and the refusal names what works:
import sysl.threads.*
struct Tally
n: int
add(t: *Tally)
t.n = t.n + 1
count() -> int
var t = Tally(0)
spawn(&add, &t).unwrap().join()
t.n
print(count())
'spawn' keeps its parameter 'arg' (it reaches another concurrency domain), and '&t' is the address of a local of 'count' — a thread that borrows the frame of 'count' is started on 'sysl.threads.scope', which joins it before the scope returns; anything else is handed storage that lasts
scope joins every thread started on it before it returns,
whichever way its body leaves, and its spawn is
@scoped(f),
so a closure started there may hold a view of the caller’s array or the address of its local — Rust’s
std::thread::scope:
import sysl.threads.scope
halves() -> int
var v = [0; 8]
val all = v[..]
val half = all.len / 2
scope((s) ->
s.spawn(() -> for i in 0..<half do all[i] = 1)
s.spawn(() -> for i in half..<all.len do all[i] = 2))
var sum = 0
for x in v do sum += x
sum
print(halves())
12
- What a scoped thread borrows has to outlive the
scopecall, not only the body, so the body’s own locals, a nested block’s and its temporaries are refused (Rust’s'envagainst'scope). A helper handeds, and a wrapper forwarding tospawn, are held the same way. A scope nested in the body may borrow the outer body’s locals. - Every road to the scope is held the same way: a closure the body builds and hands on — to a
loop’s helper, two closures deep, or bound to a local first — and a body handed to a helper along
with
slend what they capture tositself, so the body’s locals are refused there too. A closure handed toscopeorscope_in, or to a wrapper of them, is lent a scope that call makes in its own frame and joins before it returns, so it may borrow the frame that wrote it. - A fan-out needs no joining loop: whatever the body leaves unjoined, the scope joins. A handle’s
joinanswers what its closure answered, andscopewhat its body answered. A function handed the*Scopemay start threads with its own caller’s storage; one opening a scope of its own keeps nothing it is handed. A scope may be opened inside a scoped thread, and its threads may borrow that thread’s locals. A program with no heap opensscope_in, whose thread records are slots the caller lays out, and starts threads withstart(&body, arg), which may be handed a local’s address on the same terms. - A wrapper keeps what it hands
spawn, so a frame address handed to it is refused at the wrapper’s call, and the refusal still names the scope. - A plain
spawnis for storage that lasts — a box shared as&sync, or module storage — so the thread may outlive its caller and never be joined. The entry file’s own statements are exempt: their frame outlives every thread.
import sysl.threads.scope
halves() -> int
scope((s) ->
var v = [0; 8]
val all = v[..]
s.spawn(() -> all[0] = 1)
v[0])
print(halves())
'() -> all[0] = 1' holds a view of 'v', a local of 'call' — a thread started on a scope may borrow only storage that outlives the 'scope' call, and 'v' does not; declare 'v' before 'scope'
A closure the body hands on starts its threads on the same scope:
import sysl.threads.scope
each(xs: []int, f: &Fn(int) -> ()) = for x in xs do f(x)
halves() -> int
scope((s) ->
var v = [0; 8]
val all = v[..]
each([1, 2], (i) -> s.spawn(() -> all[i] = i))
v[1])
print(halves())
a closure lets its capture 'all' outlive the call (it is passed to 'spawn', where the scope that lent it holds it until the 'scope' call returns), and 'all' holds a view of 'v', a local of 'call' — a thread started on a scope may borrow only storage that outlives the 'scope' call, and 'v' does not; declare 'v' before 'scope'
A scoped thread may be lent a reference
A closure written where scope‘s spawn takes it may capture a &T, a Buf, a Map, a view of
references or strings, and a struct or tuple of them, beside what it could capture before. It is
not handed a &sync copy of any of it: it is lent what those reach, for as long as the closure is
held, which is until the scope call that ran it returns.
import sysl.container.{Map, map}
import sysl.threads.scope
struct Tables
names: Map[string, int]
lookup(t: &Tables, name: string) -> int = t.names.get(name).unwrap_or(-1)
val t: &Tables = Tables(map())
t.names.put("f", 1)
t.names.put("g", 2)
val r: int = scope((s) ->
val a = s.spawn(() -> lookup(t, "f"))
val b = s.spawn(() -> lookup(t, "g"))
a.join() + b.join())
print(r)
3
- What is read may be kept. A reference read out of a lent graph is an ordinary
&T: a child may push it into aBufof its own, answer it fromjoin, and the caller holds it after the scope with its count right. - Every count change on what a lend reaches is atomic while the lend lasts, and plain again after it: the objects the captures reach are marked when the child’s closure is made and unmarked when it is let go of, after the scope has joined the child. A lend inside a lend leaves the outer one’s marks alone. A program that lends nothing is compiled exactly as it was; one that lends compiles the standard module’s bodies itself, so that every one of them asks about the mark.
- What the lent graph reaches through a trait object or a closure is lent too, and a
&Fnin it may be called. AnAtomic, aMutexor a@guardsfield it holds is written through its members as it is in a&sync T. - Nothing a lent reference reaches may be written while the scope runs — by a child, by the scope’s
body, or by anything either calls. A field assigned, an element stored, a
push, aput, a*selfmember called on something it reaches: each is refused. What a child made itself — an object, aBufof the lent element type — it writes freely, and the lent graph is written again once the scope returns.
import sysl.buf.{Buf, buf}
import sysl.threads.scope
struct Node
name: string
val all: Buf[&Node] = buf()
all.push(Node("a"))
all.push(Node("b"))
val kept: Buf[&Node] = scope((s) -> s.spawn(() ->
val mine: Buf[&Node] = buf()
for n in all do if n.name == "b" then mine.push(n)
mine).join())
all.push(Node("c"))
print(kept.len(), kept[0].name, all.len())
1 b 3
A write to what a lend reaches is refused where it is written, in a child:
import sysl.buf.{Buf, buf}
import sysl.threads.scope
struct Node
name: string
val all: Buf[&Node] = buf()
all.push(Node("a"))
scope((s) -> s.spawn(() -> all[0].name = "x").join())
this '=' writes 'all[0].name', a field of a 'Node' that 'all' reaches, and 'all' is lent to the threads of this scope, which may be reading it at the same moment. Make the change after the scope returns, or build a 'Node' of the child's own and write that
and in the scope’s body, which runs beside its children, through whatever it calls:
import sysl.container.{Map, map}
import sysl.threads.scope
struct Tables
names: Map[string, int]
lookup(t: &Tables, name: string) -> int = t.names.get(name).unwrap_or(-1)
val t: &Tables = Tables(map())
val r: int = scope((s) ->
val a = s.spawn(() -> lookup(t, "f"))
t.names.put("h", 3)
a.join())
print(r)
this 'put' writes through 't.names', which this scope lends to the thread spawned at 12:21, and that thread may be reading it at the same moment. Make the change before the scope or after it returns
The scope’s frame holds what it lends still: a lent local may not be assigned until the scope returns.
import sysl.container.{Map, map}
import sysl.threads.scope
struct Tables
names: Map[string, int]
val r: int = scope((s) ->
var tb: &Tables = Tables(map())
val a = s.spawn(() -> tb.names.len())
tb = Tables(map())
int(a.join()))
'tb' is lent to the threads of this scope, so it may not be assigned until the scope returns
What the compiler cannot see into is refused where something is lent: a call through a closure or
a trait object in a library, which can be handed one whose body it never saw; a call through a
function pointer; inline assembly that writes memory. A program sees every closure and every table it
made, so there such a call is judged by the bodies it may run. A foreign call writes what it is handed
a writable pointer to, and what C can call back into — except where it cannot call back: a symbol the
program exports itself runs only that function, and the standard library’s output (every print
and eprints) and a scoped thread’s join and lock waits run no code of the program’s, so a child that
prints beside a lend is not refused for what some other function writes. An Armv6-M board, which
cannot change a count indivisibly, cannot lend at all.
A lent value handed to C goes only through a parameter C cannot write through — a *const T or a
[]const T; anything else is refused, since C could change what the other threads are reading:
import sysl.threads.scope
extern memset(p: *u8, c: i32, n: usize) -> *u8
struct Rec
data: [8]u8
val r: &Rec = Rec([65; 8])
scope((s) -> s.spawn(() -> memset(&r.data[0], 0, 8)).join())
'r' is lent to the threads of this scope, and the C function 'memset' is handed it through 'p', a '*byte' it may write through while they read it. Declare the parameter a '*const' pointer or a '[]const' view, or hand C a copy
A destructor
impl Drop for T says what a type does when the last reference to one of its values goes. It
declares one member, drop(*self), answering nothing, which an implementation writes drop(self)
where a copy of the value will do (below). It is for the
resource the language does not manage — a descriptor, a mapped region, a handle a C library made —
said once, beside the type:
struct Handle
id: int
impl Drop for Handle
drop(self) = print("closing", self.id)
hold()
val h = Handle(7)
print("working")
hold()
print("done")
working
closing 7
done
defer is the other way to say it, and neither replaces the other. defer close(f) covers every
site a program can name; under ARC a value can also die where there is no site to write one — an
element of a []&Handle goes when the slice does — and there only a destructor can be written. Where
both work, the destructor is written once and a caller cannot forget it.
It costs nothing to have. Release already calls through a per-payload hook, and a destructor is a call at its top. A destructor is in the program only where the program holds a value of its type, so a library type’s destructor costs a program that never makes one nothing, and on a bare-metal target the hooks it would call are not asked for.
What ARC and Drop guarantee:
- Every heap object is released exactly once, on every path: a
return, a?, abreak, acontinue, amatcharm, adeferand an unwound temporary. - The order is Rust’s: locals in reverse order of declaration at the end of their block, each deferred statement in its written place among them; temporaries at the end of their statement; fields and elements in declaration and index order.
dropruns before the object’s own fields are released, seesselfintact, and may not resurrect it. Adrop(*self)is handed the object’s own storage, and its fields are released as it leaves them.- A type with
Dropis a reference type, so only&Tof it exists. - A copy of a value retains its
&Tfields. - Cycles leak unless broken with
weak.
A type with a destructor is a reference type
A value type is copied, and a copy is not a second resource, so a destructor runs only for a value on
the heap. Building one makes a &T, with nothing written — an inferred local, a temporary, a
branch, a field, an element, an Ok — and a position naming the count keeps it (val t: &sync Thing = Thing(1); a trait object boxes on its way in):
import sysl.buf.{Buf, buf}
struct Thing
n: int
impl Drop for Thing
drop(self) = print("drop", self.n)
struct Holder
inner: &Thing
open(n: int) -> Result[&Thing, string] = Ok(Thing(n))
hold()
val a = Thing(1)
val h = Holder(Thing(2))
var all: Buf[&Thing] = buf()
all.push(Thing(3))
all.push(open(4).unwrap())
print("holding", a.n, h.inner.n, all.len())
hold()
print("done")
holding 1 2 2
drop 3
drop 4
drop 2
drop 1
done
Every spelling that would hold one by value is refused, with the &T to write: a binding, a
parameter, a result, a field, an enum payload, module storage, and any of those inside a Buf, an
Option, an array, a slice or a tuple — at every level that owns the resource, not only the outermost:
struct Encoder
state: *u8
impl Drop for Encoder
drop(self) = print("closing")
open() -> Result[Encoder, string] = Ok(Encoder(null))
print("ready")
'open' hands back 'Encoder' by value, inside 'Result[Encoder, string]', and 'Encoder' has a 'Drop' — a type with a destructor is a reference type, and building one makes a '&Encoder'. Write '&Encoder' in its place
struct Thing
n: int
impl Drop for Thing
drop(self) = print("drop", self.n)
struct ByValue
inner: Thing
print("ready")
field 'inner' of 'ByValue' holds 'Thing' by value and 'Thing' has a 'Drop' — a type with a destructor is a reference type, and building one makes a '&Thing'. Write '&Thing' in its place
A copy is never made into a second owner. The one by-value value a program still sees is a copy —
a method’s self, or *r — which may be read and passed to a method, but not boxed:
struct Thing
n: int
impl Drop for Thing
drop(self) = print("drop", self.n)
hold(r: &Thing)
val c: &Thing = *r
print(c.n)
hold(Thing(1))
this makes a '&Thing' out of a copy of a 'Thing' value, and 'Thing' has a 'Drop' — the copy would be a second owner of the resource, and its destructor would run once for each. Only building one makes a '&Thing': hand over the reference that already holds it
A generic is asked at the instantiation: its signature (id[T](x: T) called with *r binds T
by value, and the refusal names the parameter), a generic type by what its fields hold (Box[T]
holding a &T may be bound to Thing; Buf[Thing] and Option[Thing] may not), and its body,
once per instance, naming the instance and the call that asked for it:
struct Thing
n: int
impl Drop for Thing
drop(self) = print("drop", self.n)
peek[T](r: &T) -> int
val copy = *r
0
print(peek(&int(1)))
print(peek(Thing(2)))
'copy' holds 'Thing' by value and 'Thing' has a 'Drop' — a type with a destructor is a reference type, and building one makes a '&Thing'. Write '&Thing' in its place (in 'peek[Thing]', called from
@consumesis unchanged, and there is no use-after-move.- A destructor needs an allocator: a
@no_allocmodule building one is refused witha reference needs an allocator. Where there is none,deferis the tool. - An error path needs closing by hand: where a C call hands back a handle and fails, the result
is an
Err, no box is ever made, and the handle is closed where it stands. - A handle that hands out a second value needs no second type. A
(self)method cannot name its box, so boxingselfis refused; a&selfmethod is handed the box, and the value it builds takes a share rather than becoming a second owner. - It is not called for a value in a reference cycle, nor for module storage at exit: there is no exit pass, so a buffered writer held in a static is flushed by the program.
A destructor handed its own storage
drop(self) is handed a copy; drop(*self) is handed the object itself. A (self) method
copies the value it is called on, and for a destructor that reads a field to close what it names, a
copy is all it needs. A destructor that gives C back the address of the object — a node it linked
into a C list, a key it registered, storage it must wipe before it is freed — needs the address every
(*self) method saw while the object lived, and drop(*self) is handed exactly that:
static var registered: usize = 0
struct Key
bytes: [4]u8
impl Key
register(*self)
registered = usize(self)
impl Drop for Key
drop(*self)
print("same storage:", usize(self) == registered)
self.bytes = [0, 0, 0, 0]
hold()
val k = Key([1, 2, 3, 4])
k.register()
print("holding", k.bytes[0])
hold()
holding 1
same storage: true
- The trait declares
drop(*self), and adrop(self)stands for it as a(self)member stands for any trait’s(*self)one (traits); neither form replaces the other. - It is the same address wherever the object lives: a box on the heap, one laid in a frame, one a
module
varholds, one a field of another object holds. - A write through it is the object’s own. A field it replaces is released once, as any assignment’s old value is, and the fields are released as the destructor leaves them, not as they were when it was called.
drop(&self)is refused, as any receiver the trait does not declare: a&selfwould take a share of an object whose count has already reached zero.
When a value is dropped
A reference goes at the end of the block that holds it, so a local in a loop is dropped at the end
of every trip, and a continue or break drops it as the trip’s end would:
struct Res
name: string
impl Drop for Res
drop(self) = print(s"drop ${self.name}")
for i in 0..<3
val r = Res(s"trip $i")
if i == 1 then continue
if i == 2 then break
print(s"body $i")
print("after")
body 0
drop trip 0
drop trip 1
drop trip 2
after
- A temporary is dropped at the end of its statement, a value made only to be handed to a call among them.
- Assigning to a variable drops what it held, at the assignment. A write to a field of a struct
with an
invariantdrops it once the struct has been re-checked (errors). - Taking a value out of an enum, or binding it in a
match, shares it rather than moving it, and a closure holds what it captured until it is itself dropped; the value goes once, with the last share. - Every way out of a block drops what it holds — its end, a
return, a?, abreak, acontinue— innermost block first. A trap runs nothing: no destructor and nodefer.
In what order
Within one value the order is the declaration’s — a struct’s fields as declared, a tuple’s by position,
a slice’s or a Buf‘s elements by index — and teardown is depth first, so each field comes apart whole
before the next. Teardown runs from a worklist rather than by recursion, so a million-node list comes
apart in constant stack:
import sysl.buf.{Buf, buf}
struct Res
name: string
impl Drop for Res
drop(self) = print(s"drop ${self.name}")
struct Inner
x: &Res
y: &Res
struct Outer
a: &Inner
b: &Res
c: (&Res, &Res)
hold()
val o: &Outer = Outer(Inner(Res("a.x"), Res("a.y")), Res("b"), (Res("c.0"), Res("c.1")))
var all: Buf[&Res] = buf()
all.push(Res("e0"))
all.push(Res("e1"))
print("made")
hold()
made
drop e0
drop e1
drop a.x
drop a.y
drop b
drop c.0
drop c.1
A destructor runs before the fields of the value it tears down, and its own locals are dropped at the end of its body — still before those fields:
struct Res
name: string
impl Drop for Res
drop(self) = print(s"drop ${self.name}")
struct Node
leaf: &Res
impl Drop for Node
drop(self)
val note = Res("a local of drop")
print(s"drop node, ${self.leaf.name} still here")
hold()
val n = Node(Res("field"))
print("holding")
hold()
holding
drop node, field still here
drop a local of drop
drop field
What a destructor may do
It borrows self rather than taking a count — the count is already zero. It may read every field,
call any function, build and drop values, and keep a share of a field, which then goes with its last
share rather than with the value. It may not keep the value itself: boxing self would be a second
owner of what is being torn down. A weak reference to the value already reads as gone while its
destructor runs, since the count is zero before it is called.
struct Node
n: int
var saved: Option[&Node] = None
impl Drop for Node
drop(self)
saved = Some(self)
main()
print("ready")
this makes a '&Node' out of a copy of a 'Node' value, and 'Node' has a 'Drop' — the copy would be a second owner of the resource, and its destructor would run once for each
Where defer sits
defer is the answer for what the language does not own: a
descriptor, a FILE*, a block from malloc, a lock. Leaving a block undoes it in reverse — each
deferred statement reached and each local declared, last first — so a defer runs after every local
declared below it and before every local above it, and every local it names is still alive. It owns
nothing and allocates nothing, so it stays available under no alloc. A trap runs nothing. A
return, break, continue and ? undo the blocks they leave in the same order; an
errdefer runs only when the function is failing. So a lock
defer-unlocked stays held while everything made under it is given back:
struct Conn
name: string
impl Drop for Conn
drop(self) = print(s"close ${self.name}")
serve()
val a: &Conn = Conn("a")
print("lock")
defer print("unlock")
val b: &Conn = Conn("b")
defer print("flush")
val c: &Conn = Conn("c")
print(s"serve ${a.name}${b.name}${c.name}")
serve()
lock
serve abc
close c
flush
close b
unlock
close a
Crossing a concurrency domain
A &T‘s count is not atomic, so it is safe within one concurrency domain and nowhere else: a
&T may not leave its domain. &sync T is the exception, a distinct type with no conversion
either way — a count is atomic or not from the moment the object exists:
struct Cell
n: int
send(c: &sync Cell) -> int = c.n
var c: &Cell = Cell(1)
print(send(c))
'&Cell' and '&sync Cell' are distinct types, and neither converts to the other: a count is atomic or it is not from the moment the object is allocated, and a conversion would put an ordinary retain beside an atomic one. Allocate Cell as a '&sync Cell' where it is constructed
Taking a share is a relaxed increment; giving one back is a release decrement, and the share reaching
zero acquires before destroying, so the freeing thread sees every other thread’s writes (a fence acquire, or an acquire load under -fsanitize=thread, which does not model a standalone fence).
&sync T makes the reference safe to share, not the object safe to mutate: its fields are
read-only through it unless they are atomic, guarded by a lock, or the type promises
@unchecked(Share). A &T in @thread_local storage belongs to one thread and needs no &sync.
Module storage reached from another domain
A closure erased into a &sync Fn is asked about what it captures and about the module storage it
reaches, however many calls down. What may be reached is what may be captured, less a string: a
scalar, an Atomic, a &sync T, a raw pointer, @thread_local storage, and a val laid down as
constant data (a val over a slice literal is one; a val over a call is not, and a []T without
const is writable). A string in module storage is refused where a captured one is not, because
nothing copies it on the way. An interrupt handler — the interrupt convention, or
@domain(interrupt)
— is held to it too; a bare @export is not, since nothing says a second domain exists until @domain
does.
struct Cell
n: int
static var shared: &Cell = Cell(1)
bump()
shared.n += 1
val job: &sync Fn() -> unit = () -> bump()
job()
print(shared.n)
a closure shared between two domains may be called from either, so every count it reaches has to be atomic — but the module storage 'shared' it reaches, which 'bump' reads, is a '&Cell', whose count is not. Hold it as a '&sync Cell' ('06')
A guarded value crosses with its lock
A Mutex[Map[...]] may be reached from another domain, whatever it holds. Mutex[T] is
@guards(inner) over a Guarded[SleepLock, T] that is @guards(value): its members are the only way
to the T, each takes the lock first, and a guarded field that is itself guarding is looked through.
What leaves through with or try_with is held to the rule a capture is, at the call: an int
passes, and so does a value built fresh inside the closure — a literal, a .copy() of a string, a
Buf it makes and fills with copies, as long as that local goes nowhere but out through the answer
(stored anywhere else as well — pushed into the guarded value, bound to a second name, handed to a
function, its address taken — it is refused). A .copy() of a Buf is fresh where its elements hold
no count, and one of strings or Bufs copies only the handles. A value read out of the guarded one
still shares its count, and is refused; the guarded value held as a &sync Mutex[...] and captured
crosses whole. A struct of the program’s
own opts in with @guards(field) over a private field: the compiler checks that the field is
private, so only the type’s own members write it, and trusts those members to take the lock, as
Mutex and Guarded do in every member. Not checked: that a member of a program’s own type
takes the lock (the example below compiles and prints 1 with no lock taken), and a closure that stores
something read out of the guarded value where it outlives the call.
import sysl.container.{map, Map}
import sysl.threads.Mutex
static var names: Mutex[Map[string, string]] = Mutex.new(map())
print(names.with((t) -> t.get("a").unwrap_or("none")))
'sysl.threads.Mutex.with' answers a value out of the 'value' it guards, and once the guard is let go that value is shared with whoever holds it next, so every count it reaches has to be atomic — but this answers a 'string', which may share its bytes' count with the guarded one. Answer a fresh string instead — '.copy()' inside the closure gives the string an owner of its own, and a literal is immortal
import sysl.sync.SpinLock
@guards(n)
struct Cell
lock: SpinLock
private n: u64
bump(*self)
self.n += 1
get(self) -> u64 = self.n
val c: &sync Cell = Cell(SpinLock(0), 0)
c.bump()
print(c.get())
1
A table whose every record has its own lock
sysl.sync.Guarded[L, T] is one record of a buffer cache or an inode table: a value, not a box,
with the lock inline beside the T, @guards(value) as Mutex is. The lock is any Lock (acquire,
try_acquire, release, each *self). An array is its elements, so sharing a [4]Guarded[...]
shares four locks, and what the records hold is reached only through with, which hands the closure
the record in place:
import sysl.buf.{Buf, buf}
import sysl.sync.{Guarded, SpinLock}
struct Item
hits: int
log: Buf[int]
static var table: [4]Guarded[SpinLock, Item] = [
Guarded.new(SpinLock(0), Item(0, buf())), Guarded.new(SpinLock(0), Item(0, buf())),
Guarded.new(SpinLock(0), Item(0, buf())), Guarded.new(SpinLock(0), Item(0, buf()))]
touch(i: int) -> int = table[i].with((r) ->
r.hits += 1
r.log.push(i)
r.hits)
val job: &sync Fn() -> unit = () -> print(touch(2))
job()
job()
1
2
The same table of bare Items is refused, naming the Buf two domains would share. What leaves
with is held as Mutex.with‘s result is. A slice or a Buf of records is asked about its own count.
On a freestanding target the table is constant data: Guarded.new is a const function, so a kernel
writes it as a module var and the image carries it laid out, with nothing run before main (a record
whose initializer is not constant is refused there, with the reason).
A frozen buffer crosses
buf.freeze() takes a buffer’s elements and answers a &Frozen[T]: one count on the whole
buffer, nothing that writes it, and any element type. A program that stays in one domain holds it as
it holds any &T — a tree whose nodes keep their children frozen, say:
import sysl.buf.{Buf, buf, Frozen}
struct Node
id: int
children: &Frozen[&Node]
leaf(id: int) -> &Node
var none: Buf[&Node] = buf()
Node(id, none.freeze())
var b: Buf[&Node] = buf()
b.push(leaf(1))
b.push(leaf(2))
val root = Node(0, b.freeze())
var ids = 0
for c in root.children
ids += c.id
print(root.children.len(), root.children[1].id, ids)
2 2 3
Its count is chosen the way a construction’s is. Where the position expects a &sync Frozen[T]
— an annotation, a parameter, a field — the frozen buffer is allocated with an atomic count, and it
goes wherever a &sync reference goes. The two are distinct types, and neither converts to the other,
exactly as &T and &sync T are:
import sysl.buf.{Buf, buf, Frozen}
struct Texture
width: usize
pixels: &sync Frozen[u8]
var b: Buf[u8] = buf()
for i in 0..<6
b.push(u8(i * 40))
val tex: &sync Texture = Texture(3, b.freeze())
val job: &sync Fn() -> unit = () ->
var sum = 0
for p in tex.pixels
sum += int(p)
print(tex.pixels[4], tex.pixels.len(), sum)
job()
print(b.len())
160 6 600
0
- The buffer is left empty, through every name: the elements are copied once into storage sized to
them. A frozen buffer offers
len,is_empty, a checkedf[i],get,for x in f, andview(), a[]const T. Nothing writes one. A view of a&Frozen[T]holds a share of the storage itself; a view of a&sync Frozen[T]holds one atomic share of the buffer through a small box of its own. - Reading a local after
freezeis refused:freezeis@consumes. A field or module storage is not followed, and reads empty. - A shared frozen buffer shares exactly what its elements share, so where the position asks for a
&sync Frozen[T]the element type is held to a&syncstruct’s rule: a scalar, a&sync U, a raw pointer, another shared frozen buffer, arrays and structs of those. Astring, aBufor a&Telement is refused there for its count; a&Frozen[T]holds any of them. buf().freeze()handed to a parameter or a field takes its element type from there, in either kind.- Freezing allocates, so a
@no_allocmodule may not call it.
import sysl.buf.{Buf, buf, Frozen}
struct Cell
n: int
share(f: &sync Frozen[&Cell]) = print(f.len())
var b: Buf[&Cell] = buf()
b.push(Cell(1))
share(b.freeze())
'&sync Frozen[&Cell]' may be reached from two domains at once, so every count inside it has to be atomic — but it holds a '&Cell', whose count is not. Hold it as a '&sync Cell' ('06')
A &Frozen[T] is a &T, so it stays in the domain that made it:
import sysl.buf.{Buf, buf}
var b: Buf[int] = buf()
b.push(1)
val f = b.freeze()
val job: &sync Fn() -> unit = () -> print(f[0])
job()
a closure shared between two domains may be called from either, so every count it captures has to be atomic — but the 'f' it captures reaches a '&Frozen[int]', whose count is not. Hold it as a '&sync Frozen[int]' ('06')
A string crosses into a shared object
A string a &sync Fn captures, or a &sync T holds, is put in bytes of its own whose count is
atomic, where the closure or the object is made. Nothing is written for it: the type stays string,
and the string the program holds keeps its ordinary count. The bytes are copied once, as the box is
filled and before anyone else can reach it, and the copy’s count carries a mark — its top bit — that
every share of it reads. A share of a marked count is taken and given back atomically, as a
&sync T‘s is, wherever it is taken: in the closure’s body, on another thread, in a slice of the
string, in a string a channel carries.
import sysl.threads.scope
val n = 7
val name = s"worker-$n"
val job: &sync Fn() -> string = () -> name[0..<6]
val lens = scope((s) ->
val a = s.spawn(() -> job().len)
val b = s.spawn(() -> (job() + name[6..<name.len]).len)
a.join() * 100 + b.join())
scope((s) -> s.spawn(() -> print(job(), job() + name[6..<name.len])).join())
print(lens, name)
worker worker-7
608 worker-7
- A literal is not copied, nor a string already shared — one read out of another
&syncobject: the first has no count at all, and the second’s is atomic already. - A field, an array element, an
Optionand an enum payload of the object are followed, so a&sync Cfgwhosenames: [2]stringandalias: Option[string]were built at run time shares each. A field a@guardsguards, a frozen buffer’s elements and a struct promising@unchecked(Share)are left as they are, as the rule about what a&sync Tmay hold leaves them. - What it costs: the copy, once per string per object made, and on every share of any string a test of the mark, made on the count it was about to change anyway. A program that shares nothing never sets the mark, and its counts change as they always did.
- Where a word cannot be changed indivisibly (Armv6-M) nothing is marked: the copy is still made, and its count is an ordinary one.
A string is shared only where something copies it on the way. Module storage is reached rather
than captured, so a string there stays in its own domain, and so does a string among a view’s
elements, a frozen buffer’s, a task’s frame, or what a pointer handed to a @crossing parameter
reaches:
static var greeting: string = "hi"
val job: &sync Fn() -> unit = () -> print(greeting)
job()
the module storage 'greeting' it reaches is a 'string', which owns its bytes through a count that is not atomic, and nothing copies it on the way here
A string is therefore Send and still not Share (below): the bound asks about every place a value
of the type may be put, and a pointer’s pointee is one.
@crossing — where the rule is asked
@crossing(p) is written above the function that hands p to another domain.
sysl.threads.spawn carries one, and so does a package binding a scheduler. A *T parameter is
looked through — what crossed is the object at the far end. Nothing is emitted; the refusal is made
at each call, afresh for every set of type arguments:
struct Cell
n: int
struct State
cell: &Cell
@crossing(s)
start(s: *State) -> int = s.cell.n
var c: &Cell = Cell(1)
var st = State(c)
print(start(&st))
what 's' of 'start' points at reaches another concurrency domain, so every count inside it has to be atomic
- Where a body shows the boundary, nobody writes it: a parameter handed on to a crossing one, or a
value stored in a
&syncplace, crosses too, however many functions deep. The address of one of its fields hands over that field. A written@crossingis for the boundaries no body shows — anextern, a function pointer, a closure called through its type, a trait’s requirement. - A member may carry it:
@crossing,@readsand@writesare about a parameter, and are the only annotations a method, a property or an associated function may carry. A field or a variant has no parameter for one to name. - A parameter that crosses by value is handed a copy of every view it holds, at every depth, made
where the callee reads it, so the caller’s count never reaches the other domain. The elements are
still asked about, and a
*Tparameter is looked through and never copied. The copy allocates, so it is refused under@no_alloc.sysl.threads.Channel‘ssendandtry_sendare@crossing(value), which is how a channel takes a view.
Send and Share — the rule given a name
sysl.Send and sysl.Share are the two questions above, as bounds a signature can write. A type
is Send where a value of it may be handed to another domain by value — the question a @crossing
parameter taken by value asks, every view and string inside it copied on the way. It is Share
where an object of it may be reached from two domains at once wherever it is — behind a pointer as
well as a &sync T — with nothing copied, so a view and a string are out. (A &sync T holding a
string copies it in where the object is made, which is a property of that place rather than of the
type.) Share is Send and more.
| type | Send | Share |
|---|---|---|
a scalar, a *T, a &sync T, a Frozen[T] of members, a Mutex[T] | yes | yes |
a string, a []T of members | yes | no |
a &T, a weak T, a Buf[T] | no | no |
| an array, a tuple, a struct or an enum | where every part is | where every part is |
The membership is the compiler’s, and it is the crossing check’s own answer — one rule, so a type
that crosses at a @crossing parameter meets Send, and one that forms a &sync meets Share.
Nothing implements either. A generic states the bound and its body may hand the value on; the
caller is refused where the call is written, naming the part in the way:
struct Cell
n: int
struct Inner
cell: &Cell
struct Outer
b: Inner
post[T: Send](x: T) -> int = 1
val c: &Cell = Cell(1)
print(post(Outer(Inner(c))))
'post' requires its type parameter 'T' to implement 'Send', but Outer does not — a value of it handed over reaches another concurrency domain, so every count inside it has to be atomic — but its 'b.cell' reaches a '&Cell', whose count is not. Hold it as a '&sync Cell' ('06')
A type parameter meets the bound only through its own bounds. Where @crossing waits for each
instantiation, a bound is asked once, where it is written, so a parameter that promises nothing is
refused there, and told the bound to write:
post[T: Send](x: T) -> int = 1
relay[U](x: U) -> int = post(x)
print(relay(1))
'post' requires its type parameter 'T' to implement 'Send', but U does not — a value of it handed over reaches another concurrency domain, so every count inside it has to be atomic — but it is 'U', a type parameter that promises nothing about its counts. Bound it '[U: Send]'
@unchecked(Send) and @unchecked(Share) above a struct are the program’s promise where the
fields do not show it — a struct whose own members keep a &T to one domain at a time. The walk takes
the promise in place of the fields, for every check that asks: a bound, a &sync T, a @crossing
parameter, a capture. It is held to @guards‘ rule: every field the walk would refuse is private,
so the members are the only way to it. @unchecked(Share) also promises that the struct’s writes
are synchronised, which lets its fields be written through a &sync; no field
shows that, so it is never redundant. An @unchecked(Send) the fields already keep is refused, and so
is impl Send.
import sysl.threads.scope
struct Cell
n: int
@unchecked(Share)
struct Gate
private c: &Cell
get(self) -> int = self.c.n
val g = Gate(Cell(6))
scope((s) -> s.spawn(() -> print(g.get())))
6
struct Cell
n: int
@unchecked(Send)
struct Leaky
c: &Cell
print(1)
'@unchecked(Send)' promises that 'Leaky''s own members keep its 'c' safe across a concurrency domain, and a field visible beyond this file is a way round them — declare it 'private'
Places
A place is something with an address: a local or parameter, a dereference, an element, and a field of any of them. Anything else — a call’s result, an arithmetic result, a fresh struct — is a value with no address of its own.
| operation | what it does |
|---|---|
&place | yields a *T — C’s address-of |
&value | writes the value into a hidden local of this scope, and yields a *T to that |
*p | reads through a *T or a &T, and is itself a place |
p.f | selects, dereferencing one level automatically on both *T and &T |
& on a place yields a raw pointer, never a reference: a place lives in a frame or inside another
object, with no count to share. Selection is the only implicit dereference, with the subscript of
an indexable pointee: p.x is (*p).x (Go’s rule, no ->), p[i] on a pointer to an array or a
container is (*p)[i], and matching a reference to an enum is match *e. Assignment, compound
assignment and ++/-- take a place. The shorthand stops at one level, and says how many are
left:
struct Point
x: int
y: int
var p = Point(1, 2)
var pp = &p
var ppp = &pp
print(ppp.x)
selection reaches through one level of indirection and **Point has more
An element has an address whether or not the expression naming it does: a view’s or a pointer’s
elements live wherever the storage is, which is what makes rows(g)[i] = v write through to the grid.
An array’s elements are places exactly when the array is. A string’s bytes never are — writing a byte
of UTF-8 is refused as immutability. The one dangle a single statement can make is &f()[i] where
a temporary view is its buffer’s only holder: the buffer goes at the end of the statement, and the
*T is the raw tier behaving as advertised.
Addressing a value
& in front of something with no address makes the storage: the value is written into a hidden
local of the scope the & stands in, and the slot’s address comes back:
trait Shape
area(self) -> int
struct Rect
w: int
impl Shape for Rect
area(self) -> int = self.w
var s: *Shape = &Rect(2)
print(s.area())
2
&Rect(2) is var t = Rect(2) and &t with the name left out: the slot is the frame’s, its count is
taken as a var‘s initializer takes one, and it is released where the scope ends. Any value, not
only a construction — &1, &(a + b), &make(). It is storage, not a copy handed out, so a write
through it lands, and the operand is evaluated once, at the &. A pointer carried out of the scope
is stale, as one to a named local would be; returning one is refused (above).
A name is answered rather than copied: &x, &t.f, &xs[i] and &*p ask for that thing’s
address and are refused where it has none. A property is why: t.f at a property and at a field
are one spelling, and a pointer into a copy would make a write go nowhere while looking like one that
lands. A constant is the same (&capacity is refused; &8 makes a slot).
struct Temp
c: int
f -> int = self.c * 9 / 5 + 32
var t = Temp(0)
var p = &t.f
print(*p)
something with an address
Module storage has no such scope: its initializer runs in a prologue whose frame is gone by the
first statement. Name the value with a static var and take its address instead.
struct Rect
w: int
static var p: *Rect = &Rect(2)
print(p.w)
module storage has no such scope
The & in a type is a different thing. &T is a counted box, which owns what is in it; the
operator takes an address, which owns nothing. A box is made by a value arriving where a &T is
wanted, with no operator — var s: &Shape = Rect(2):
trait Shape
area(self) -> int
struct Rect
w: int
impl Shape for Rect
area(self) -> int = self.w
var s: &Shape = &Rect(2)
print(s.area())
an address is not a way of making a box
ref — a name for a place
var t = self.tasks[i] binds a copy, so every access walks the path again; &self.tasks[i] gives
up bounds checking, within checking, invariant re-checking and the guarantee at the top of this page
in one step. ref binds a name to a place:
struct Task
state: int
prio: int
struct Kernel
tasks: [4]Task
advance(*self, i: usize)
ref t = self.tasks[i]
t.state = 2
t.prio = t.prio + 1
end Kernel
var k = Kernel([Task(0, 7); 4])
k.advance(2)
print(k.tasks[2].state, k.tasks[2].prio, k.tasks[0].prio)
2 8 7
- The place is evaluated once, where the binding is written: a later
i += 1leavestnaming the element it always named (not Scala’s by-name=> T). - It is a declaration, never a type. A ref cannot be a field, a parameter, an element or a type argument, cannot be re-pointed, cannot be captured by a closure, and does not outlive its block. A ref of a ref is one more name for the same place. That is what keeps the compiler’s knowledge complete: a ref never travels, so the analyzer holds its place expression in the same body.
- At run time it stores an address; at compile time it remembers a place, so a write through it
re-runs the
invariantclauses of every struct the place lies in, a ref into avalis read-only, a ref to awithinslot is checked on assignment, and a subscript’s bounds check is paid once, at the binding. A ref inherits the place’s writability and has no modifier of its own. - A user type’s subscript is a place when the type implements
IndexPlace, whose method answers the element’s address —b[i]is*b.index_place(i).Bufis one. ThroughIndexalone a subscript is a call answering a value. - A ref to a slot holding a
&Tnames the slot, not the object: binding it takes no count,r = otheris the field assignment, and readingrtakes a count as reading the field would. - The one rule holds what may move under it.
make() -> int = 7
demo()
ref x = make()
print(x)
demo()
'ref' names a place — a local, a field, an element, or a dereference — and this expression has no address for 'x' to name
The place must lie in storage something holds past the statement — a local, a parameter, module
storage, or what a *T points at. Bind a call’s answer with val first:
import sysl.buf.{Buf, buf}
fresh() -> Buf[int]
val b: Buf[int] = buf()
b.push(5)
b
ref t = fresh()[0]
t += 1
't' would stand on a place inside a value nothing holds — a temporary, released at the end of this statement while the name lives on
A member that answers a place
A method can say its call is a place: -> ref T. Its body comes to a place reached through a
parameter, and every call is that place in the caller — written through at once, named by a ref, or
read, which reads a copy:
struct Task
state: int
prio: int
bump(*self) = self.prio += 100
struct Kernel
tasks: [4]Task
task(*self, i: usize) -> ref Task = self.tasks[i]
var k = Kernel([Task(0, 7); 4])
k.task(2).state = 2
ref t = k.task(1)
t.prio += 1
k.task(0).bump()
val copy = k.task(2)
k.task(2).state = 9
print(k.tasks[2].state, t.prio, k.tasks[0].prio, copy.state)
9 8 107 2
It is the same ref, written in the callee: the body’s place is kept as a template over the
parameters, so every hazard of the one rule is refused through a method too. The body’s last
expression and nothing else is the answer — a field chain, an element or a dereference from a parameter
or module storage, leaving the parameter’s own bytes through a *self, a reference, a view, an element
or a *T. Refused: a field of a by-value self or a local; a place reached through a call’s answer or
through a local that copies a reference or a pointer, wherever its storage lies, since the caller
follows the path and neither is a step it can; a value or a place chosen by an if; a
return or ? in the body; a place inside a struct with an invariant. It is written on a type’s own
member, inherent or generic, and not on a free function, in a trait, or on an impl member a trait
declares. The address is never a value: &k.task(0) and &Kernel.task are refused.
struct Pair
a: int
get(self) -> ref int = self.a
'Pair.get' would answer a place in storage of its own call — a by-value parameter or a local — which is gone when it returns
The raw tier
Anything C can do through a pointer, sysl can, and the pointer is where the guarantees stop.
null is the absent raw pointer, with no type of its own: it takes the *T its context expects.
A generic parameter is such a context and answers late — an argument with no type of its own is set
aside until the others have settled the parameter, in either order — and a call with nothing else to
settle it is refused rather than defaulted:
struct Node
value: int
next: *Node
var third = Node(3, null)
var second = Node(2, &third)
var first = Node(1, &second)
var walk = &first
var total = 0
while walk != null
total += walk.value
walk = walk.next
print(total)
6
one[T](a: *T) -> bool = true
print(one(null))
'null' takes its type from its context, and there is none here
*const T — a pointer that is read through and not written
The const sits after the *, where it sits after a slice’s [], and for the same reason: it is a
property of the pointer — what may be done through it — and not of what it points at. It is the
signature a function that only reads through a pointer should have, and it is what C writes
const T *:
struct P
x: int
ys: [2]int
total(p: *const int, n: int) -> int
var s = 0
for i in 0..<n do s += p[i]
s
field(p: *const P) -> int = p.x + p.ys[1]
var xs = [1, 2, 3]
var q = P(4, [5, 6])
print(total(&xs[0], 3), *(&xs[1]), field(&q))
6 2 10
Every road to a write through one is refused alike — *p = v, p[i] = v, p.f = v, a part of
any of them, a ref bound through it, and a *self method called through it:
set(p: *const int) = *p = 1
this is reached through a '*const int', which may be read and not written, so there is nothing to assign through. A pointer that writes is a '*int'
It is one type with a bit, as the two views are: the same address, passed and stored alike. So a
*T is accepted wherever a *const T is wanted — an argument, a binding, a result, an extern‘s
parameter — and never the other way round:
writes(p: *int) = *p = 1
reads(p: *const int) = writes(p)
a '*const int' may be read through and not written, and a '*int' is a licence to write
Where the two have to agree — the branches of an if, the operands of == — they meet at the
read-only pointer, and a view taken of a *const T is a []const T. What it does not reach is
storage behind an address it leads to: a *T field of the pointee is written exactly as that pointer
allows. ptr_cast reaches between the two, as it reaches between any two pointers.
*nonnull T — a pointer that is never null
*nonnull T is a raw pointer that is never the null address. It has every operation a *T has
— *p, p.f, p[i], p[0..<n], p - q, usize(p) — and is laid out and passed as one. The word
sits after the *, and after a const: *const nonnull T is a read-only one, access first and then
what the value promises, in that one order. nonnull is a soft word, special only in front of a
type, so a type a program calls nonnull is still pointed at by *nonnull.
It has the null niche, as a &T does: an Option[*nonnull T] is the address alone, with None
as null, where an Option[*T] keeps its tag:
print(sizeof(*nonnull int), sizeof(Option[*nonnull int]), sizeof(Option[*int]))
8 8 16
An address is never null, so &x, &p[n], r.into_raw() and a c"…" literal are each a
*nonnull T wherever one is wanted. With nothing asking, &x is the *T it has always been, which
may later be set to null. A *T becomes one only by being asked: p.nonnull() answers an
Option[*nonnull T] — the same bits, so it costs nothing — and p.nonnull().unwrap() is the checked
conversion, which traps on null. A *nonnull T goes wherever a *T, a *const T or a *const nonnull T is wanted, and where the two have to agree they meet at the pointer that may be null:
first(p: *nonnull int) -> int = *p
plain(p: *int) -> int = *p
var x = 41
val p: *nonnull int = &x
var raw: *int = &x
print(first(p), plain(p) + 1, first(&x))
for i in 0..<2
raw.nonnull() match
Some(q) -> print("some", *q)
None -> print("none")
raw = null
41 42 41
some 41
none
null is not one, wherever a *nonnull T is wanted — a binding, an argument, a field, a result —
and comparing one with null is the same mistake:
val p: *nonnull int = null
'null' is the address a '*nonnull int' never holds, so it is neither stored in one nor compared with one — a pointer that may be absent is an 'Option[*nonnull int]', one word all the same, whose null is 'None'
Nor is a *T, which may be null:
var x = 1
val p: *int = &x
val q: *nonnull int = p
a '*int' may be null, and a '*nonnull int' never is — so the one does not become the other. Check it with '.nonnull()', which answers an 'Option[*nonnull int]' that is 'None' for null
It has no zero value, so a struct holding one has none either and is given its field at
construction; like every raw pointer it is not Plain. The other order of the two words is refused,
naming this one:
var x = 1
val p: *nonnull const int = &x
'const' goes before 'nonnull' — what may be done through the pointer first, then what its value promises: '*const nonnull T'
The raw tier. nonnull_unchecked(p), imported from sysl.raw as ptr_cast is, takes a *T as a
*nonnull T with nothing checked: a null handed to it is read as None by any Option holding it,
and a read through it faults. ptr_cast from a *nonnull A to a *nonnull B stays non-null, since
re-typing cannot make an address null, and makes one out of a literal address that is not zero — a
device’s base. Anything else is refused, naming .nonnull():
import sysl.raw.{nonnull_unchecked, ptr_cast}
var x: u32 = 7
val p: *u32 = &x
val q = nonnull_unchecked(p)
val bytes: *nonnull u8 = ptr_cast(q)
val device: *nonnull u32 = ptr_cast(0x4000_C000)
print(*q, usize(bytes) == usize(q), usize(device))
7 true 1073790976
A function pointer takes it too: *nonnull extern(int) -> int is a callback that is never null,
made by &f, with the same niche and the same refusals. At the C boundary Option[*nonnull T] is C’s
nullable T *, matched rather than compared (ffi.md).
An extern and the @export defining its symbol may differ in a pointer’s nonnull, one way for a
result and either way for a parameter
(the table).
Arithmetic: two directions, one spelling each
p - q between two pointers of one pointee is an isize counting elements — C’s ptrdiff_t, the
inverse of &p[n] — which is what turns memchr‘s or strstr‘s answer into an index. Offsetting
stays &p[n]: p + n is not spelled, and p + q names no address. Two pointee types are refused by
the ordinary matching-types rule, and a &T has no arithmetic of its own: an operator reads it
through to its referent (generics), so two
&Points subtract only where Point does, and the refusal names Point. Whether two pointers into
unrelated objects may be subtracted is the programmer’s business.
var buf: [8]int = [10, 20, 30, 40, 50, 60, 70, 80]
var base = &buf[0]
var third = &buf[2]
print(*third, third - base, base - third, *(&base[3]))
30 2 -2 40
struct Point
x: int
var a: &Point = Point(1)
var b: &Point = Point(2)
print(a - b)
operator '-' is not defined for Point
Bounds safety follows length, not pointers. Arrays and views carry their length, so indexing is
checked in every context — hosted or allocator-free, over static, stack or heap memory — except where
the program asked by name for unchecked access. *T carries
none: p[i] and p[0..<n] are unchecked, as in C. A pointer to something with a subscript of its own
— a *[N]T, a *Buf[T] — is indexed as that thing, with its check
(arrays).
Reinterpreting storage
| written | direction | tier |
|---|---|---|
usize(p) | a pointer as a number | an ordinary conversion |
ptr_cast(n) | a number as a pointer | unsafe |
ptr_cast(p) | one pointee type as another | unsafe |
xs.view_as[T]() | a view’s plain-data elements as other plain data, owner kept, boundary and tail checked | safe (arrays) |
ptr_cast is imported from sysl.raw, beside str_cast and str_alias, so every
reinterpretation is found by its imports; an alias, a wildcard and a module path reach it as they
reach anything. A function or local the program names ptr_cast wins, and importing the form under
such a name is refused.
var arena: [8]u8 = [0u8; 8]
val p: *u32 = ptr_cast(&arena[0])
print(*p)
'ptr_cast' is in sysl.raw: add 'import sysl.raw.ptr_cast'
A pointer becomes an integer by ordinary conversion — usize (or isize) holds any address, so
it is total, and the number cannot be dereferenced. The address of a function converts the same way.
A number becomes a pointer only from an address-width integer, usize or isize. The operand of
ptr_cast is an address-width position, so a bare literal — or an expression of nothing but bare
literals — is a usize at the target’s width, written as the datasheet prints it; one too wide for the
target, or negative, is refused as a literal that does not fit. A value that already has a type keeps
it, and is converted where it is meant as an address:
import sysl.raw.ptr_cast
struct Uart
data: u32
status: u32
val uart: *Uart = ptr_cast(0x4000_4000)
val status: *u32 = ptr_cast(0x4000_4000 + 4)
val bit: *u8 = ptr_cast(1 << 20)
val none: *Uart = ptr_cast(0)
print(usize(uart), usize(status), usize(bit), usize(none))
1073758208 1073758212 1048576 0
import sysl.raw.ptr_cast
var base = 0x4000_4000
val uart: *u32 = ptr_cast(base)
print(usize(uart))
'ptr_cast' reads an address, and int is not address-width — convert it first, as 'ptr_cast(usize(n))'
The target comes from whatever receives the result, or is written on the form —
ptr_cast[*Node](&arena[0]); with neither, the program is told to annotate. ptr_cast never
produces a &T, a weak T, a view or a string: a reference is counted and non-null, and the fat
types are wider than an address.
import sysl.raw.ptr_cast
struct Node
value: int
var arena: [64]u8 = [0u8; 64]
var n: &Node = ptr_cast(&arena[0])
print(n.value)
'ptr_cast' never produces a reference: a '&T' is counted and non-null, and an address read out of bytes carries no count for anything to own — read it as a '*T'
Storage the compiler did not lay out may not hold a counted value
A &T, a weak T, a view or a string may not be written into memory reached by ptr_cast — nor
a struct or enum carrying one — because an assignment releases what occupied the slot, and the release
would walk whatever the bytes held. Nothing refuses this: the compiler does not track where a
pointer came from. Keep an index, a raw pointer or a copy instead — an arena of nodes linked by index
costs nothing a box was buying. A type of scalars, raw pointers and arrays of those may live in storage
you carved, which covers every C ABI struct. sizeof, alignof and offsetof are on
expressions.
Zeroed storage is the exception — what calloc or a collector gives. An all-zero counted
reference names nothing, so a &T field (or a Buf, Map or Deque) in zeroed storage takes its
first assignment safely. Until then it is the one null &T, and is_null(r) asks, with no share
taken; it answers false for any &T the language made, and refuses a trait object, a weak T and a
non-reference. release(place) is its other half: it gives back the share the place held, running
the destructor on the last one, and leaves the place empty; a second release gives back nothing. A
container gives its share back through its own .release() member, and an Option or weak T is
emptied by assigning None, so release refuses those. Both are forms a same-named function or local
overrides.
import sysl.raw.ptr_cast
extern "calloc" c_calloc(n: usize, size: usize) -> *u8
extern "free" c_free(p: *u8)
struct Item
label: string
struct Slot
item: &Item
val s: *Slot = ptr_cast(c_calloc(1, sizeof(Slot)))
print(is_null(s.item))
s.item = Item("a")
print(is_null(s.item), s.item.label)
release(s.item)
print(is_null(s.item))
c_free(ptr_cast(s))
true
false a
true
Slot storage: room that holds no value yet
A growable container needs a spare end that holds nothing, not a fill value that would keep what
it names alive. Four forms give the raw tier that, and sysl.buf.Buf is written
with them:
slot_storage(n)(orslot_storage[T](n)) is a[]Tofnslots of which none is live; the element type comes from the position, and with none it is refused.slot_storage(0)allocates nothing — it is the empty view[]is, so a container made empty costs no storage until it grows — and neither does[v; n]ortry_slot_storage(n)whennis zero while running.slot_place(xs, i, v)fills the first slot past the live run without letting go of anything; a live slot is an ordinary assignment; a slot further on would leave a gap, and traps.slot_place_run(xs, at, src)isslot_place(xs, at + k, src[k])for every element of the viewsrc, under the same rules; the slotsat ..< at + src.lenmust exist, or it is a bounds trap.slot_vacate(xs, n)lets go of every live slot fromnon — only where nothing else holds the storage; while a view handed out earlier exists it does nothing, and the next vacate catches up.
struct Node
n: int
var xs: []&Node = slot_storage(4)
slot_place(xs, 0, Node(1))
slot_place(xs, 1, Node(2))
print(xs.len, xs[0].n + xs[1].n)
slot_vacate(xs, 1)
slot_place(xs, 1, Node(5))
print(xs[0].n + xs[1].n)
4 3
6
The live run is the storage’s own: the buffer’s box counts the live slots, and its destructor
releases exactly those; the view’s len is still the whole room. The caller owes the one check the
compiler cannot make: nothing reads a slot past the live run. On storage slot_storage did not make,
the writing forms are an assignment and nothing.
A run costs what its element does. Where the element holds no count, placing it is a store that
lets go of nothing, so slot_place_run is one memmove of the run’s bytes — which is what
Buf.extend and a Buf‘s growth are, whatever the run’s length. Where it holds one, the run is placed
slot by slot, each taking a count of its own, exactly as the loop would be: the same counts, let go of
in the same order. Either way a run read out of the slots it fills arrives whole, as memmove‘s does.
struct Node
n: int
var bytes: []u8 = slot_storage(6)
slot_place_run(bytes, 0, "abc".bytes)
slot_place_run(bytes, 3, "xyz".bytes)
print(bytes[0], bytes[5])
var nodes: []&Node = slot_storage(4)
slot_place_run(nodes, 0, [Node(1), Node(2)])
slot_place_run(nodes, 2, nodes[0..<2])
print(nodes[0].n + nodes[1].n + nodes[2].n + nodes[3].n)
97 122
6
A growth relocates. A copy of every element into fresh slot storage — a slot_place_run, or a
counted loop of slot_places whose slot index steps with the loop — followed at once by a write of
that fresh storage over the place the elements were read from, moves them: the old storage is let go
of on the next line, so the counts the copy would take and the old storage’s destructor would give
back end where they began. Where the old storage has no other holder, the copy hands each slot’s count
over untouched and the old storage frees without visiting them; where it covers the rest of the old
live run and starts at the fresh storage’s first free slot, it is one memmove of the elements’
bytes, as C++’s growth is. Where a view handed out earlier still holds the old storage, the copy
counts each element as written, and the view keeps them. Either way a program sees the same thing:
each element let go of once, when the last holder lets go of it. This is a Buf‘s growth, whether
it traps on a refusal (push) or answers it (try_push, whose storage comes from try_slot_storage
and is checked by its length before the copy).
struct Job
id: int
impl Drop for Job
drop(self) = print(f"let go ${self.id}")
struct Jobs
storage: []&Job
last: usize
grow(*self, n: usize)
var fresh: []&Job = slot_storage(n)
slot_place_run(fresh, 0, self.storage[0..<self.last])
self.storage = fresh
var j = Jobs(slot_storage(2), 0)
slot_place(j.storage, 0, Job(1))
slot_place(j.storage, 1, Job(2))
j.last = 2
j.grow(4)
print(j.storage.len, j.storage[1].id)
4 2
let go 1
let go 2
Two forms answer the heap’s refusal instead of trapping on it (above):
try_slot_storage(n)isslot_storage(n), except that where the heap answers null — ornslots do not fit in a word, in which case the heap is not asked — it answers an empty view. A caller asking forn > 0slots tells the two apart by the length.try_heap(v)is the box a&Tofvwould be, as anOption[&T]:Nonewhere the heap answered null, with nothing stored and no count ofvtaken.
struct Node
n: int
val xs: []&Node = try_slot_storage(4)
val big = try_slot_storage[u64](usize::Max)
print(xs.len, big.len)
try_heap(Node(7)) match
Some(b) -> print((*b).n)
None -> print("refused")
4 0
7
Moving one value through a raw pointer
Storage whose live slots are not a prefix — a ring’s run wraps — moves one value at a time, as Rust’s
ptr::read and ptr::write do. slot_take(p) moves the value out: the slot’s share becomes the
result’s, no count is taken or given back, and the slot is left empty (zeroed, over an element
holding a count). slot_put(p, v) moves v into an empty slot, giving nothing back. A taken
slot must be live, a put slot empty, and nothing reads an empty slot — the caller’s to keep. Both
refuse what is not a *T.
An empty local: one slot in the frame
A generic body sometimes has to hold a T before it has one — a copy made a word at a time into
storage of its own — and a T may have no zero value to start it at: a simple enum with no
variant written = 0, a constrained subtype, a &T. var out: T = slot_empty() declares a local
that is an empty slot, the one storage the other forms leave behind: it holds no value, and
nothing is let go of for it until one is put there. Its storage is the frame’s, aligned as T is
(an @align(64) type starts on a 64-byte boundary), like Rust’s MaybeUninit<T>.
- What it holds is
slot_take‘s empty: the zero whereTholds a count, so the local’s release at the end of its block gives back nothing, and otherwise bytes nobody wrote — no store at all. - It is filled like any local: an assignment (to the whole or to a part),
slot_put(&out, v), or a copy through&out. An assignment to an empty slot of a counted type lets go of nothing; a later one lets go of what the first put there. ADropvalue put in is dropped once, when the local goes, and one never put in is never dropped. - Its first mention writes it. Read in the order the body is written, the first thing done with
the name must be a write — an assignment,
&out, arefto it — and a read before one is refused; so is a write whose own value reads it (out = out + 1,out += 1) and a closure capturing it. A write on one arm of aniffollowed by a read after it is the caller’s to get right, as a slot past a buffer’s live run is. - An empty array is written element by element, and is written once every element is. An
assignment to one element does not settle it; what does is the statements of its own block
assigning elements at constant indices that between them cover every one (
out[0] = a,out[1] = b), or a counted loop there,for i in 0..<out.len, one of whose own statements assignsout[i]— or is itself such a loop overout[i], for an array of arrays — and that holds nobreakorcontinue. Until then any read of it is refused, a read inside the fill included. Its.lenis its type’s and reads nothing. A fill left early by?orreturnleaves the rest as the slot did, so the elements written are let go of once and the others not at all. An element’s address (slot_put(&out[0], v)) is a write the program vouches for, as the local’s own address is. - It stands only as a
var‘s initial value, with the type on the declaration or inslot_empty[T](): aval, an argument, an assignment’s value or avarwith no type is refused.
enum Mode
Idle
Busy
struct Res
n: int
impl Drop for Res
drop(self) = print(s"drop ${self.n}")
fill[T](v: T) -> T
var out: T = slot_empty()
out = v
out
keep[T](v: T)
var out: T = slot_empty()
slot_put(&out, v)
print("kept")
print(fill(Busy) == Busy, fill(7))
keep(Res(1))
true 7
kept
drop 1
f() -> int
var x: int = slot_empty()
x += 1
x
'x' is an empty slot, read here before anything was written to it
enum Mode
Idle
Busy
alternate(n: usize) -> Result[[4]Mode, string]
var out: [4]Mode = slot_empty()
for i in 0..<out.len
if i == n then return Err(s"stopped at $i of ${out.len}")
out[i] = if i % 2 == 0 then Idle else Busy
Ok(out)
print(alternate(9).unwrap()[3] == Busy, alternate(2).unwrap_err())
true stopped at 2 of 4
f() -> int
var out: [3]int = slot_empty()
for i in 0..<2 do out[i] = i
out[0]
'out' is an empty slot, read here before anything was written to it
sysl.sync‘s load_relaxed and SeqLock[T] build their answer in one, so they copy a Plain type
with no zero value as they copy any other, and sysl.codec decodes an array of one element at a
time into one. A var out: T with no initial value at such a T is
refused at the call that chose the type, naming the instance and the declaration’s line, since the
line in the generic’s body is the same for every instance and may be the library’s.
A counted reference given up as a pointer
r.into_raw() gives up a &T as a *T — the address of the object itself, so its fields read and
write through it — and the pointer carries one count of the object away: the count is not given
back, so the object lives until something adopts it. from_raw(p), imported from sysl.raw,
adopts that count back: it answers the &T the pointer was given up from, which owns the count
and gives it back where any reference would. This is Rust’s Box::into_raw and from_raw, and it is
how an object is handed to code that holds a plain pointer — a C caller above all
(ffi.md).
import sysl.raw.from_raw
struct Db
n: int
impl Drop for Db
drop(self) = print("closed", self.n)
open(n: int) -> *Db
val d: &Db = Db(n)
d.into_raw()
close(p: *Db)
val d: &Db = from_raw(p)
val p = open(5)
p.n += 1
print(p.n)
close(p)
print("done")
6
closed 6
done
d.into_raw() at d‘s last use hands d‘s own count over; one still used after takes a second, so
the object then has two owners until both are gone. A &sync T gives up and adopts back the same way —
a position wanting a &sync T makes from_raw answer one — and from_raw[T](p) names the type where
no position does. into_raw is the reference’s, so a value (T) and a plain pointer have none,
and a type’s own member of the name is what a call reaches first. A trait object is refused: it is two
words, and the table would be lost.
from_raw is in the raw tier, which is why it is imported. Nothing can check its pointer: it has to
be one into_raw answered for a reference of that kind — &T or &sync T — and it is adopted once.
A pointer from anywhere else is read as a box header that is not there, and adopting one twice gives
the count back twice. The header sits a fixed distance before the payload whichever header the type’s
box has — the count alone, or the count, the destructor and the weak count beside a weak — so a type
that is weakened, destroyed or neither round-trips the same.
struct Db
n: int
val d = Db(1)
val p = d.into_raw()
'into_raw' gives up a counted reference, so hold the value as a '&Db'
Device memory
An optimizer may assume that reading storage twice yields one value, that a store nobody reads is not needed, and that two accesses may merge — all false at a device. So sysl has C’s qualifier, in the type:
struct Uart
status: volatile u32
data: volatile u32
baud: u32
var block = Uart(1, 0, 115200)
var regs: *Uart = &block
regs.data = 65
print(regs.status, regs.data, regs.baud)
1 65 115200
A
volatileplace is one whose reads and writes are effects, not value computations: the compiler emits exactly the accesses the source wrote, once each, in the order written — never adding, dropping, merging or moving them.
It constrains the compiler, not the machine: no atomicity, no ordering against another core, no
protection from a torn read. Talking to another thread is &sync T, Mutex[T] and Atomic[T].
It qualifies storage, and a value read out of storage is an ordinary value: regs.status is a
u32. The qualifier goes on a struct field, an element ([4]volatile u32), a pointee
(*volatile u32) and module storage (var tick: volatile u64, which an interrupt handler writes and
the program polls). A local, a parameter, a result and a type argument are values:
var x: volatile u32 = 0u32
print(x)
'volatile u32' is the type of *storage*, and this is a value — what a read of a volatile place hands back is an ordinary 'u32'. The qualifier goes where the storage is named: a struct field, an element, or the pointee of a '*T', as '*volatile u32'
var ticks: volatile u64 = 0
@export("on_timer")
on_timer()
ticks += 1
@export("wait_for")
wait_for(n: u64)
while ticks < n do ()
ticks += 1is a volatile load then a volatile store — not atomic. Where both sides write, or two cores share the word, the tool isAtomic[T].- Per field, not per aggregate: a register block’s shadow values (a cached baud, a reserved word)
stay ordinary memory.
*volatile Uartandvolatile Countsare refused, and the refusal points at qualifying the fields. Avalis refused: a constant has nothing writing it. - Only a scalar or a raw pointer may be qualified — one access, one instruction. A counted value, a
trait object (two words), a constrained subtype (a register holds whatever the device put there;
convert on arrival) and a data enum are refused; a simple enum and a bitfield (a read-modify-write of
its container, see
@packed) are admitted. A struct holding a register carries noinvariant. - A qualified field is on its type’s boundary: one a
@packedstruct places at an offset that is not a multiple of its type’s alignment on the target (tag: u8, word: volatile u32) is refused where it is selected, since its one access would be off the boundary — the rule and its exact definition are in@packed. - What the compiler does:
load volatile/store volatile, with no runtime cost. A qualified field is reached at its own address, never lifted out of the block; copying a whole block is an access to every register in it;®s.statusis a*volatile u32; a type parameter never binds a qualified type. - On AArch64 a volatile access is one plain load or store of the declared width —
ldrb/strb,ldrh/strh,ldr/strof aworxregister, the address a bare register: never written back to the base (ldr x9, [x0], #-8), never one half of anldp/stp, never through a floating-point register, never merged or split. That is the form a hypervisor can emulate: an access of any other form traps at a device with no syndrome (ISV=0), and QEMU under HVF stops on it. The compiler writes each access as anasmof that one instruction, because LLVM may otherwise fold a volatile load in a loop walking down registers into a post-indexed one — Linux’sreadl/writelareasmfor the same reason. It holds at every optimisation level and under LTO, and it costs only what the optimizer might have folded. Abooland an integer narrower than its storage (u12) move their storage’s width (ldrb,ldrh), a float an integer register’s. A whole register block copied or stored (var u = *regs,*regs = Uart(1, 2, 3)), and a bitfield register changedwithnew fields, is one such access per register, the lowest address first. A volatile wider than 64 bits is refused on AArch64 — au128, ani128or any wider integer has no one instruction, and LLVM’s volatile of it is anldp/stppair, the form a hypervisor cannot emulate. Write two 64-bit volatile accesses. - On 32-bit ARM — every Thumb target, ARMv6-M to ARMv8-M — a volatile access of 1, 2 or 4 bytes is
the same one plain instruction:
ldrb/strb,ldrh/strh,ldr/strof a general register, the address a bare register — never written back (ldr r3, [r2], #4), never anldm/stm(an M0+’sldm r2!, {r3}), never anldrd/strd, never through a floating-point register (vldr s2, [r0]). An exception may abandon anldm,stm,ldrdorstrdpart-way and run it again from the start, reading a read-to-clear register twice; oneldris done or not begun. It is anasmhere too, at every optimisation level and under LTO, and abool, au12, a float, a pointer, a whole block and a register changedwithnew fields move as they do on AArch64 — a 32-bit bitfield register is oneldrand onestreven on an M0+, which would otherwise make it four bytes. - On 32-bit ARM a volatile wider than 32 bits is one such
ldrorstrper 32-bit word, the word at the lowest address first. Au64, ani64or anf64is two plain word accesses, au128four; a float goes through the general registers. They are separate accesses: neither atomic nor one bus transaction, so a device or an interrupt handler may change the high word between the two reads — a free-running 64-bit counter is read again until two reads agree on the high word. A width that is not whole words (u40,u48) has a tail no word access moves, and is refused there. - On 32-bit ARM a volatile of 32 bits or fewer must be held in 1, 2 or 4 bytes. A
u12is oneldrhand au3oneldrb, but a width of 17 to 24 bits (u24,i20) is held in 3 bytes, which LLVM moves as anldrhand anldrbin either order, so it is refused at every place avolatilegoes. A bitfield struct is reached as its one container, so there the container decides: twou12fields are a 3-byte container and twou20fields a 5-byte one, both refused with a volatile field, while au12and au20are oneldr. A C bitfield is reached as its declared unit, which is always 8, 16, 32 or 64 bits. - Every other processor keeps LLVM’s
load volatile: x86 decodes the faulting instruction itself, and RISC-V has no writeback addressing, so avolatile u128is accepted there.
struct Regs
wide: volatile u128
'volatile u128' is not a type on aarch64-freestanding: it is 128 bits wide, and an AArch64 volatile access is one 'ldr' or 'str' of at most 8 bytes (64 bits). Make two 64-bit volatile accesses instead, as two 'volatile u64' fields or elements
struct Timer
stamp: volatile u48
'volatile u48' is not a type on thumb-freestanding: it is 48 bits wide, and a 32-bit ARM volatile wider than 32 bits is made as whole 32-bit words, one 'ldr' or 'str' each, which 48 bits is not
struct Dma
count: volatile u24
'volatile u24' is not a type on thumbv6m-freestanding: it is 24 bits wide, held in 3 bytes, and a 32-bit ARM volatile of 32 bits or fewer is made as one 'ldr' or 'str' of 1, 2 or 4 bytes, which 24 bits is not
@packed
struct Pair
lo: volatile u12
hi: volatile u12
'Pair.lo' is volatile, and 'Pair' is a bitfield struct held in one integer of 24 bits on thumbv6m-freestanding, which every access to it moves whole
The counter read on a Cortex-M, where a volatile u64 is two word reads:
struct Clock
count: volatile u64
@export("now")
now(c: *Clock) -> u64
loop
val before = c.count
val after = c.count
if after >> 32 == before >> 32 then return after
end now
A loop walking down a FIFO’s registers is the shape LLVM folds. Each read of *at here is
ldr x9, [x0] and then a separate sub x0, x0, #8, never the one ldr x9, [x0], #-8 an ordinary load
would become:
@export("drain")
drain(fifo: *volatile u64, n: int) -> u64
var at = fifo
var sum: u64 = 0
for i in 0..<n
sum ^= *at
at = &at[-1]
sum
end drain
volatileis not reserved — special only before a type, assyncis after&.[]const volatile u32is a read-only register view:constis the view’s property,volatilethe element’s.- A
[]Tis accepted where a[]volatile Tis wanted, and an array where its view would be — the same elements, every access through the new view an effect. It keeps the view’sconst: a[]const T, avalarray or a string’s bytes reach only a[]const volatile T. It is never taken away, and it goes one level only: a[][]u8is not a[][]volatile u8, whose slots could then be handed a view of device memory that the[][]u8holder reads as ordinary memory. This is whatsysl.slices.zeroizeis built on — a clearing of a buffer nothing reads again, kept at-O2:
clear(v: []volatile u8)
for i in 0..<v.len
v[i] = 0
var key = [3u8, 1, 4]
clear(key)
print(key)
[0, 0, 0]
- A type parameter may be qualified where its bound closes it to the scalars —
[T: Integer], a family whose membership is the compiler’s and every member of which is one integer.Tis read through the widening, so a[]u32handed to a[]volatile Tbindsu32, and every store is at that width:
clear[T: Integer](v: []volatile T) -> usize
for i in 0..<v.len
v[i] = 0
v.len
var round_keys = [0x9e3779b9u32, 0x7f4a7c15]
var mac = [0xffu8, 0x10, 0x20]
print(clear(round_keys), clear(mac[1..<3]), round_keys, mac)
2 2 [0, 0] [255, 0, 0]
- Any other bound is refused at the declaration: an unbounded
Tmay stand for a struct, and an open trait —Float,Add— may be implemented by one, so neither is known to be a scalar. A view of a constrained subtype is refused at the call, as the wrong elements, since a volatile place holds whatever is written to it:
f[T](v: []volatile T) = ()
'volatile T' is not a type: 'volatile' qualifies a scalar or a raw pointer, since it promises the one load or the one store the source wrote and nothing else -- and nothing bounds 'T' to the scalars
- An array of qualified elements is filled from a literal of the plain type, as a struct’s
qualified field is from a constructor:
var bank: [4]volatile u32 = [1, 2, 3, 4]. - Memory a device reads by DMA is a library type,
sysl.dma‘sRegion, not a qualifier: it needs a device address and a cache-honest handover, neither a property of a place.
Recursive types
A type may reach itself through an indirection, and only through one. The rule is per cycle: a
cycle is legal as soon as one edge on it is a *T, a &T or a []T (a view points at its elements;
a fixed [4]T holds them). Mutually recursive types work, in either declaration order.
struct Node
value: int
next: Node
print(1)
type 'Node' contains itself, so it has no finite size
A type argument is not containment: whether Wrap[Node] holds a Node is Wrap‘s business.
Buf[T] reaches its elements through a []T, so enum Json with Arr(items: Buf[Json]) is finite,
and so is a cycle Json → Buf[Member] → Member → Json. A generic holding its parameter by
value (struct Wrap[T] with a field x: T) closes the cycle, and the refusal names the field.
What a count costs
None of this section changes what a program prints or when a destructor runs; it is where counts are not taken.
A heap object carries three header words: the strong count, a pointer to the function that
destroys it, and a weak count. Release decrements the strong count and at zero calls through the hook,
which releases the payload and returns the storage to the heap it came from
(one heap for the program). The hook
makes release type-erased — what a view’s owner word needs — so ARC works the same in a module
that never allocates, several heaps coexist, and ownership crosses an allocator-free edge like any
value. Values, fixed arrays and *T buffers carry no header.
A box no code can reach without its type carries the strong count alone. The hook and the weak
count are there for the releases that have forgotten what they hold — the drain, a trait object, a
view’s owner word — and for weak references. Where a build sees the whole program (a program with an
entry point, not a library or a C archive, and not one linking a precompiled --lib root), the
compiler leaves both words out of the boxes of each type the program declared that is never made into a
weak T, a &sync T or a trait object, holds no fixed array in place a view could own, and has no
destructor in it or anywhere its teardown reaches. Letting go of such a box calls its type’s own
release, which tears it down as the drain would — a reference of the same type on a list of its own,
anything else released as usual — so a tree of them still comes apart in constant stack, and with no
destructor anywhere the order it is freed in is not something a program can see. The binary-trees
node — an enum of Leaf and Node(left: &Tree, right: &Tree) — is a 32-byte box instead of 48.
Nothing about this is written in the program, and nothing it prints changes.
Teardown is iterative: an object reaching zero is pushed onto a per-thread worklist through its
dead count slot, and the first release to hit zero drains it, so any depth comes apart in O(1) stack.
Inside the drain, a reference the object held is queued on that same list directly, and one whose
object has nothing left to tear down — no counted field, no destructor, an enum variant that holds
nothing, and no weak reference out — is freed on the spot, so the leaves of a tree never reach the
list at all.
On a freestanding target the worklist is asked for: a &sync release reaching zero fetches it
through the weak symbol __sysl_arc_reaper, answering a head pointer and a draining flag of the
running task. Define nothing and the single built-in slot serves a machine where nothing schedules; an
RTOS port defines it in C, and a scheduler written in sysl defines it with
@export, as __sysl_arc_reaper() -> *T over a struct of the same two fields, and
the compiler then leaves its weak default out.
struct sysl_arc_reaper { void *head; unsigned char draining; };
struct sysl_arc_reaper *__sysl_arc_reaper(void) {
return pvTaskGetThreadLocalStoragePointer(NULL, 0);
}
Passing a reference to a call usually costs nothing
An argument is handed over under a guarantee that it stays alive for the call, and the callee
reads it through the caller’s count — Swift’s guaranteed convention. The caller asks one question:
- a temporary is a count the frame holds to the end of the statement: nothing to do;
- a local or parameter whose address has not been let out yet keeps its count where the callee cannot reach it: nothing to do (“yet” counts a statement at a time; a loop is one statement);
- anything else — a field, an element, a global, something behind a
refor a&— costs a retain before and a release after, since the call may write that memory, unless the call can write no field on the way to it: a field or an element read through a parameter, a local or a call’s answer, handed to a parameter the callee borrows, takes no count where neither the callee (nor anything it calls) nor a later argument may write a field the read went through, run code nobody can see, or let go of the root it was read from.tail(x.unwrap().next, y, z)takes none whentailwrites nonext;f(a.b)takes one whenfmay writeA.bthrough another name fora. A call through a closure or a trait object asks the same of every function the program put at that type (each closure made at that&Fntype, each function named as a value of it, each implementation erased into that trait at the object’s arguments), so in a program’s own buildf(n.next)through a&Fn(Option[&Node]) -> inttakes none where none of them writes anext. A library’s build cannot see them all, and a C function pointer names no body: there the count stays. A global’s value, a&syncorweakone, and an argument that crosses by address keep the count.
Which of the two a call is changes nothing it prints: the count left out could never have been the one
keeping the value alive. length(a.b.next) below takes no count, since length writes no field;
replace(a.b) takes one, since replace overwrites A.b through the global, and reads what it was
handed after that (--explain-borrows says which, and why):
struct Node
v: int
next: Option[&Node]
struct A
b: &Node
var SEEN: Option[&A] = None
length(n: Option[&Node]) -> int = n match
Some(x) -> 1 + length(x.next)
None -> 0
replace(n: &Node) -> int
SEEN.unwrap().b = Node(9, None)
n.v
main()
val a: &A = A(Node(1, Some(Node(2, None))))
SEEN = Some(a)
print(length(a.b.next), replace(a.b), a.b.v)
SEEN = None
1 1 9
A callee still takes a count for a parameter it assigns a value it made — a walk that only follows
fields of what it was handed (p = p.next, or a call to itself with n.next that is lowered as a
jump) takes none — and for every parameter of a function something outside the program may call
(@export, a @section, one whose address is taken). A function that calls itself last with values
it made reads its first round’s parameters through its caller’s count, and takes one only for what
each later round is handed. Both of these walk the list with no count operation at all:
struct Node
v: int
next: Option[&Node]
count(p: Option[&Node], n: int) -> int = p match
Some(node) -> count(node.next, n + 1)
None -> n
total(p: Option[&Node]) -> int
var sum = 0
while p is Some(node)
sum += node.v
p = node.next
sum
main()
val list: Option[&Node] = Some(Node(1, Some(Node(2, Some(Node(3, None))))))
print(count(list, 0), total(list))
3 6
A call to an async function moves a temporary into its task, which lets it go at its return,
not at the end of the caller’s statement:
struct Noisy
id: int
impl Drop for Noisy
drop(self)
print(s"dropped ${self.id}")
async keep(n: &Noisy) -> int = n.id
plain(n: &Noisy) -> int = n.id
async run()
print(s"async ${await keep(Noisy(1))}")
print(s"plain ${plain(Noisy(2))}")
val named: &Noisy = Noisy(3)
print(s"named ${await keep(named)}")
print("end of run")
block_on(run())
dropped 1
async 1
plain 2
dropped 2
named 3
end of run
dropped 3
A parameter the function keeps arrives with its count
A parameter kept on every way out is owned: the caller hands over the count at the argument’s last
use, or retains, so b.push(x) at x‘s last use costs nothing. The ways out are each return, each
failing ?, and the end; a branch keeps where each arm does; a loop keeps where each break has kept
(and, unless it is a loop only break ends, where the code before it had); a trapping path does not
leave. One kept on some paths only stays borrowed, and the keeping path takes its own count. A call
through a closure, function value, trait object or C reaches a borrowing entry; an @exported,
async or @scoped function, or one with a contract, keeps the borrowed convention.
A value whose release can run a destructor is still destroyed where its scope ends: such a local is
retained for the call, not handed over at its last use, and not handed into an if‘s arms, since
the call might keep it only in a result that goes at the end of the statement while a view of what it
owns is still being read. Two cases are exempt because nothing can tell the difference. A call that
is the whole statement, with nothing after it to the end of the scope but plain reads, arithmetic,
writes of uncounted places and a return, hands the local over when the callee keeps it calmly: it
puts the value in a buffer’s slot, or hands it to a parameter that does so, and runs nothing after
that which could let it go. An if that is the last thing in its scope takes the local into its arms.
So xs.push(shape) as a function’s last statement costs a &Trait or a &Fn no count, as it costs a
&Node none. xs.push(shape) followed by xs.clear() still retains, and the destructor still runs
where the scope ends:
import sysl.buf.{Buf, buf}
trait Shape
area(self) -> int
struct Noisy
id: int
impl Drop for Noisy
drop(self)
print(s"dropped ${self.id}")
impl Shape for Noisy
area(self) -> int = self.id
put(xs: Buf[&Shape], id: int)
val a: &Shape = Noisy(id)
xs.push(a)
put_and_clear(id: int)
var xs: Buf[&Shape] = buf()
val a: &Shape = Noisy(id)
xs.push(a)
xs.clear()
print("cleared")
main()
val xs: Buf[&Shape] = buf()
put(xs, 1)
print("put 1")
put_and_clear(2)
print(s"held ${xs.len()}")
put 1
cleared
dropped 2
held 1
dropped 1
A count that would be taken and given straight back is not taken
A retain is cancelled against a later release of the same reference when nothing between can give
back the count that release would — loads and stores of the frame’s slots, arithmetic and other
retains never can; a different value’s release may sit between unless the stretch also writes memory
outside those slots; any other call ends it. Releases split by an if or match are given back at the
end of each arm. A value’s last use hands it over: a fresh box, a call’s result, or a local named
for the last time is taken by its destination with no new count, and a struct or enum built on the
spot is handed over field by field. A local still read later, named in a defer, used in a loop it was
declared outside, or reached through an address or a ref is copied. Recursive search over &sync
shapes loses three of every four atomic operations.
A view of something the frame already holds takes no count
A slice of a slice, or a val copied out of a field, of a parameter or a val takes no share
where its parent’s count already holds the object, across a for or the rest of a loop’s round —
provided the parent stays put (not a var assigned in the loop or whose address is taken), the view
stays in a local, and nothing between may look at a count: only arithmetic, reads, and calls to
functions that release nothing and write only their own locals (slot_vacate frees only at a strong
count of one). A view of a parameter’s own storage held in a local needs none of that
(A view of a parameter’s storage takes no count).
The same goes for a reference read out of storage — a field through a parameter, a buffer’s
element, a matched payload, a key built for a lookup — where nothing between can give a count back,
look at one, or hand the thread to other code. A path that ends the program is held to the same rule,
except a function handed only numbers. A call writing memory is judged by the type of what it writes:
growing a Buf[Value] cannot touch a Machine. An await keeps the count, as does storing,
returning, capturing or keeping the value; a tuple built on the spot for a keeping call is handed over
whole.
A release between them does not always keep the count. Where letting go of the released value
runs no destructor, the share goes when nothing that release can tear down is of the share’s type — an
old Option[&Tag] given back cannot free a Packet — or when the reference was read out of a local
that holds a count of its own on it, such as Richards’ message.unwrap() while the old self.input
is given back:
struct Packet
id: int
link: Option[&Packet]
struct Task
input: Option[&Packet]
impl Task
run(*self) -> int
var message: Option[&Packet] = None
message = self.input
self.input = message.unwrap().link // message holds the packet: no share for the read
message.unwrap().id
main()
var t = Task(Some(Packet(1, Some(Packet(2, None)))))
print(t.run(), t.run())
1 2
The local must hold a count on everything stored into it and be read only where it lies. A parameter
does not qualify for a reference read out of storage through it: what a borrowed one holds is its
caller’s, and the share keeps its count. A view of the parameter’s own storage is another matter
(below).
Reading the payload straight out of the place being written (self.input = self.input.unwrap().link)
keeps the share, since that release may be the packet’s last, and so does a release whose teardown
runs a destructor.
A view of a parameter’s storage takes no count
A local holding a view of a parameter’s own storage takes no count at all, whatever runs while it
is held — a call, a destructor, a fiber switch. Such a view can be a slice of a []T or []const T
parameter, a string parameter’s .bytes or a cut of it, a slice of another such local, or a slice
of an array lying by value in a &T parameter’s referent. A borrowed parameter’s caller holds its
share for the whole activation. Its frame is parked under this one, on the same fiber, so nothing can
give that share back while the body runs. It holds when:
- the parameter stays put — the body never assigns it, takes its address, binds a
refto it or jumps back to its own entry. It is also never used whole, only sliced, cut, measured, indexed, walked by aforor read through. Then no way out of the body keeps the parameter, and no last use of it hands its count away while the view is still to be read; - the local only reads the view — its length, an element, a
forover it, a slice of it read the same way, the start of another such local, or an argument of a direct call. A view that is returned, stored, captured or built into a value takes its count like any other local. Where the short string form is on, the bytes of a string that may be short are not handed to a call either: such bytes are the string’s own words, and a callee that keeps them gets a heap copy with a count of its own. With the form off, a string’s bytes are its own storage and are handed to a call as a slice is; - the local is written once — never assigned, its address never taken, no
refbound to it, not named in adefer.
A view behind a second reference, such as h.inner.data for h: &Outer with inner: &Inner, is not
covered. The first referent may let go of the second while the body runs. The fiber-switch check asks
the same question (A count held across a switch is refused),
so a local the rule covers is held across nothing there, and one it does not cover is held:
import sysl.fiber.{Context, Stack, switch}
var home = Context.new()
var away = Context.new()
park()
switch(&away, &home)
send_all(bytes: []const u8) -> usize
var at: usize = 0
while at < bytes.len
val rest = bytes[at..<bytes.len] // no count of the bytes' owner
park()
at += rest.len
at
prompt(said_from: string) -> usize
val said = said_from.bytes
park()
said.len
@pinned(thread)
work()
print(send_all(("pi" + "ng").bytes))
print(prompt("password" + ": "))
run(p: *int)
work()
loop
park()
var unused = 0
main()
val stack = Stack.reserve(64 * 1024).unwrap()
away = Context.start(stack, &run, &unused)
for _ in 0..<4
switch(&home, &away)
4
10
A read of a place that is written over next takes the place’s count
A reference read out of a field or an element that is written before it is read again moves out of it: the read takes no count and the write gives none back, since the count the place held is the one the new name needs. Popping the top of a stack is one move, not a retain and a release:
struct Node
id: int
next: Option[&Node]
struct Stack
top: Option[&Node]
impl Stack
push(*self, n: &Node)
n.next = self.top
self.top = Some(n)
pop(*self) -> &Node
val n = self.top match
Some(t) -> t
None -> panic("an empty stack")
self.top = n.next
n.next = None
n
main()
var s = Stack(None)
for i in 1..3
s.push(Node(i, None))
print(s.pop().id, s.pop().id, s.pop().id)
3 2 1
It moves only where nothing can see that the place and the name share one count. Every way on from the
read must reach the write, or end the program as a failed check or a panic does; an early return,
a write on one branch only, or a read inside a loop written after it keeps both counts. Between the two
nothing may read the place again, write anything that might be it (a field of another struct, or a
slot of the frame, cannot be), call a function that writes outside its own frame or releases anything,
suspend, or let go of a value whose teardown runs a destructor or that holds the count just read.
A loop lends each element to a body that lets go of nothing
for x in seq over elements with counted parts takes no count per element where the body cannot
free one: the loop already holds the sequence’s storage, so x reads the element where it lies,
as a borrowed parameter does, and an iteration costs no retain and no release. The body qualifies when
everything in it could sit in a function that releases nothing — reads, arithmetic, a match, nested
loops, and calls to functions that release nothing and write only their own locals, or that cannot
reach storage of the element’s type or of the sequence’s — and its writes land only in vars of the
function’s own. The parts a pattern in the header binds, and a val copying a field of x held by
value, are lent with it.
Keeping x is not a reason to count it: a break x, a return x or a copy into a var takes the
count where it keeps the value. A count per element stays where the body could free an element under
the name — storing x in module storage or another value’s field, a push, a closure built in the
body, an assignment to x or to a part, a write to the array being walked, or a call that may write
the buffer or anything holding an element.
import sysl.buf.{Buf, buf}
enum Value
Int(v: int)
List(items: Buf[Value])
struct Field
name: string
value: Value
weight(v: Value) -> int = v match
Int(n) -> n
List(items) -> sum(items)
sum(items: Buf[Value]) -> int
var t = 0
for x in items do t += weight(x)
t
fields(fs: Buf[Field]) -> int
var t = 0
for Field{name, value} in fs do t += int(name.len) + weight(value)
t
var tags: Buf[Value] = buf()
tags.push(Int(1))
tags.push(Int(2))
var row: Buf[Field] = buf()
row.push(Field("id", Int(7)))
row.push(Field("tags", List(tags)))
print(sum(tags), fields(row))
3 16
A local that walks storage takes no count
A var, a val, a match arm’s binding or an is binding whose every value is read out of storage
— through fields and payloads, starting from a parameter or a local of the function’s top block — takes
no count where nothing in its scope can cut that chain. The object such a local names is held by the
field it was read from, and that field by the root the walk started at, so a count of the local’s own
could never be the one that keeps the object alive; leaving it out changes nothing a program prints or
when a destructor runs. A walk down a list then costs no retain and no release per step:
struct Element
v: int
next: Option[&Element]
is_shorter_than(x: Option[&Element], y: Option[&Element]) -> bool
var x_tail = x
var y_tail = y
while y_tail is Some(yt)
x_tail match
None -> return true
Some(xt) -> x_tail = xt.next
y_tail = yt.next
false
make(n: int) -> Option[&Element]
var head: Option[&Element] = None
for i in 0..<n
head = Some(Element(i, head))
head
print(is_shorter_than(make(3), make(4)), is_shorter_than(make(4), make(3)))
true false
Keeping such a local is no reason to count it: a return, a break with it, a push, a store, a
copy into a counted local or a value built from it takes the count where it keeps the value, on that
path only. The local keeps its count, for the whole of its life, where its scope may cut the
chain while the local may still be read — in a statement of its block at or before the last one
that reads it, which a loop coming round or an argument handed on keeps alive throughout. A store that
statement ends with is not such a cut: self.current = current.run_task() reads current in the call,
and the store comes after, so current holds no count. The cuts are: a write to a field it was read along (through any reference), a call to a function that may
write one — however deep — or may read a count of it, a release that may run a destructor, a call
through a C function pointer, a foreign call the program cannot trust, an await, and a write to the
root itself, or a use of an owned root that could hand its count away. A program sees every closure
and every trait object it makes, so a call through a closure or a trait object’s table is judged as
a call to each function the program put at that type — the closures made at that &Fn type, the
functions named as values of it, each implementation erased into that trait — and letting one go runs
a destructor only where one of them holds a value with one. A library, which may be handed an object
made elsewhere, cannot see them all: there such a call or release keeps the count. A local read from module storage, or through a &sync, is always counted, and so is one named in
a defer, assigned with a compound operator, or whose address is taken. --explain-borrows says,
for each local read out of storage, which way it went and why.
A method’s answer borrowed from its receiver
A function whose answer is read out of a parameter’s storage is called so that the caller reads it
there: a place of a parameter (a field, an element of a fixed array or of a held buffer, a payload a
match binds where every other arm ends the program, or another such method’s answer), or a value
built on the spot out of references read from it (“+0”). It keeps the ordinary call where some path
answers a reference made there, where the body may release or write what it answers, and where no body
is in sight. So quad(self) -> Kids = self.kids.unwrap() costs what n.kids match Some(q) -> …
costs: no count at all. A generic is decided per instance. In a program, which sees every closure and
trait object it makes, a call through a closure or a trait object’s table answers what each function
the program put at that type answers, and is borrowed only where every one of them is; a library, or
a call through a C function pointer, has no body in sight. Where every one of them answers so and
releases and writes nothing, the call itself reads the answer where it lies: the program’s tables
carry a second entry for that slot, after the ordinary ones, and the call reaches the bodies through
it, so peek(x: &Get) -> int = x.get().v costs no count when every get answers a field. A table is
laid out as before wherever something outside the program may read it – a library, an archive C
links, a table a precompiled module may have made – and a function whose answer is borrowed only
through such a call still keeps its ordinary call. --explain-borrows
(the CLI) reports each — here for a Table whose find
answers Some(it) for an element of its items, a look built on it, and a drained that clears
the buffer after asking:
$ sysl build --explain-borrows table.sysl
table.sysl:13:5: 'Table.find' answers +0 from 'self': self.items.walk()[_]
table.sysl:19:1: 'look' is not borrowed: its answer is a fresh value
table.sysl:23:1: 'drained' answers a place of 't': t.items.walk()[_].unwrap().value, but its body may write or release what it was handed
Edge cases
What a compiler maintainer needs and a program rarely meets:
- Deep or cyclic address chains. An address held inside what is handed over is told apart step by step however deep a chain of distinct types goes; where the caller’s storage holds a cycle, or the pointer’s type reaches itself past eight steps, the callee is asked what it lets out of anything it reads through the pointer, and is refused if it lets out anything read there.
- What a callee with no body can run, for the one rule. A callee’s reach is its body, every body it
calls, and the destructors of what those bodies can let go of: the values they are handed, make,
read or write, the module storage they name and the objects their casts point at, each followed
through what it holds — an object behind a trait through every type the program put behind that
trait, a closure through what it captured. A destructor reached brings what its own body can let go
of, so a destructor two deep is reached too. A walk that reaches a foreign function takes in every
destructor, since C can hand back anything. A maker such as
blank() -> Buf[u8] = buf_filled(n, u8(0))lets go of nothing, so a destructor elsewhere that calls through a pointer does not stop a local it fills from being the only name for its buffer, and a call not handed that local may write otherBuf[u8]s while a view of it is held. A call through a pointer anywhere in that could run anything, so every cast and all module storage count. A call through a trait object, in a program’s own build (sysl build,run,test), runs the method in that slot of each table the program has for the trait at the object’s arguments — one per type it put behind aVisit[int], not those behind aVisit[&Node], and none where it put none — so its reach is those methods’ reach, each handed the object as its own type, so a field the trait hides (aClearerholding a&Keepof owners) counts as an argument would. That holds of a call in the frame holding the ref or view as much as of one deep in a callee (aDisplayrendered through*Writerundermap_err). A call through a closure names no body even there, since nothing in its type says what it captured. A library’s build (build-lib,build-c) may be handed an object whose table it never saw, so there such a call could run anything, as a call through a pointer. A foreign function may call back into whatever C can enter — an@export, a@sectionfunction, one whose address is taken, one with a foreign convention — so it reaches those and all module storage. The standard library’s ownexterns are the exception, since they never call back: aptr_castelsewhere is no reason to refuseread_bytes. A library function already compiled is judged by what its arguments, the module storage it can name, and the casts it can run can reach. Only the paths that come back count: one that ends the program —unwrap‘s report, a failed bounds check — never resumes the frame holding the ref or view, whatever it runs. A view held inside an array or struct of plain values ([Region(base, sram.view_mut())]) lends its elements as a view held alone does, so a callee writing those bytes through the slice it is handed writes no buffer. - The one rule is otherwise local. It sees the
&, the path after it, and the calls and assignments on that path in one body. A second name for a buffer made withval b2 = bis a@relocatescall on the same buffer, refused with that message; a callee through a trait object or function pointer and an aggregate handed to a call are not followed for a pointer. - The
__sysl_arc_reaperslot on two cores needs__atomic_*the board defines, which on a two-core part takes a hardware spinlock. - A view or a
Bufof guarded records is asked about its own count, not the records’, so one reached through a*Tor held as constant data crosses, and one shared through an ordinary count does not. - A generic instance whose own signature was refused at its call says nothing more about its body: everything inside follows from that one complaint.
A program whose only Bus reads may call through one while a view is held, though module storage
holds a Buf[u8]; a second impl Bus whose read wrote that storage would refuse the call, naming
its method:
import sysl.buf.{Buf, buf}
static var keep: Buf[u8] = buf()
trait Bus
read(*self, at: usize) -> u8
struct Ram
cells: Buf[u8]
impl Bus for Ram
read(*self, at: usize) -> u8 = self.cells[at]
copy_in(sram: *Buf[u8], d: &Bus) -> u8
var v = sram.view_mut()
v[0] = d.read(0)
v[0]
var cells: Buf[u8] = buf()
cells.push(7)
var sram: Buf[u8] = buf()
sram.push(0)
print(copy_in(&sram, Ram(cells)), keep.len())
7 0
A callee that lets go of a Quiet, whose destructor only prints, may run while a view is held, though
the program has another destructor that writes module storage holding a Buf[u8]:
import sysl.buf.{Buf, buf}
static var keep: Buf[u8] = buf()
struct Tap
n: int
impl Drop for Tap
drop(self)
keep = buf()
struct Quiet
n: int
impl Drop for Quiet
drop(self) = print("quiet", self.n)
twice(n: int) -> int
val q: &Quiet = Quiet(n * 2)
q.n
fill(sram: *Buf[u8]) -> u8
var v = sram.view_mut()
v[0] = u8(twice(3))
v[0]
val t: &Tap = Tap(1)
var sram: Buf[u8] = buf()
sram.push(0)
print(fill(&sram), t.n)
quiet 6
6 1
One that lets go of a Tap is refused, since its destructor may write the buffer the view reads:
import sysl.buf.{Buf, buf}
static var keep: Buf[u8] = buf()
struct Tap
n: int
impl Drop for Tap
drop(self)
keep = buf()
twice(n: int) -> int
val t: &Tap = Tap(n * 2)
t.n
fill(sram: *Buf[u8]) -> u8
var v = sram.view_mut()
v[0] = u8(twice(3))
v[0]
var sram: Buf[u8] = buf()
sram.push(0)
print(fill(&sram))
'v' is a view borrowed from 'sram', held in a 'Buf[byte]', and 'twice' may write a 'Buf[byte]'
Hazard summary
| segfault source | prevented in the safe subset by |
|---|---|
| use-after-free / double-free | ARC on &T; weak degrades to Option and never dangles |
| a walk whose list is rewritten mid-walk | a local that walks storage keeps its count wherever its scope may write a field it walked, or call what may |
| null dereference | non-null references; nullable is Option |
| out-of-bounds | length-carrying arrays and views, checked everywhere |
| a view or address outliving its storage | block lifetimes; the view’s owner word; escaping frame arrays are promoted |
| refcount race across threads | &sync T is atomic; a &T may not cross a domain |
| dangling or wild pointer | impossible without *T and ptr_cast |
One hazard is not on that list: racing on the fields of an object two threads deliberately share.
Preventing it needs proof of exclusive access, which this language trades away, so it is a Mutex‘s
job. It takes &sync or *T to reach, so it is as greppable as the rest.
The two worlds, one language
- Application, server, utility:
Tand&T, plusweak, views and arrays. Safe and ARC-managed. - Kernel, driver, allocator-free:
T,*T, fixed arrays, views and manualmalloc/free. A module that never creates a&Temits no allocation and no allocator dependency, and stays bounds-checked wherever it uses arrays and views.
The boundary is compiler-enforced through the allocator capability, and it gates allocation, not
ownership: allocator-free code may hold, pass, copy and drop a &T or a heap-backed view something
else made — retain and release are a few instructions, and the free path is the object’s own hook. That
is what lets a driver keep the &Device its bus manager handed it.
Next: arrays and slices — the two sequence types, and what a view keeps alive.