Atoll has one owning pointer type, ^T, and the two borrows a callee takes
of a value that is not its own, &T and &mut T. &place and &mut place
are the operators that make them at a call. There is no Box, no Rc, and no
lifetime annotation.
Every example on this page is compiled and executed by the compiler’s own test suite, and its heap is checked back to zero.
The four spellings
| You write | You get |
|---|---|
^T |
the type: a pointer to a T |
&place |
a borrow &T of storage that already exists; a pointer where a ^T is asked |
^T{ … } |
a pointer to a fresh block holding a new T |
x.^ |
the pointee, as a value |
struct Point { x int, y int }
fn main() int {
p: Point = Point { x: 1, y: 2 }
a: ^Point = &p // points at `p`, in this frame
b: ^Point = ^Point { x: 3, y: 4 } // points at a block of its own
return a.x + b.x
}& needs a place — a binding, a field, an element — with one exception:
a temporary handed straight to a &T parameter lives for the call, as in
Rust, so len(&mk()) and look(&5) are taken. Anywhere else &(a + b), &5
and &f() name a temporary with no storage outliving the expression, and are
refused (ATOLL1047): bound to a name (r := &mk()), taken &mut, or handed
where a ^T is asked.
fn len(s &string) int { return s.len() }
fn mk() string { return "abc" }
fn look(n &int) int { return n }
fn main() int {
return len(&mk()) * 10 + look(&5) // each temporary lives for its call
}Where nothing asks for a type, &place is the borrow &T, as Rust’s &x
is: r := &s is a &string, [&s] a []&string, (&s, 1) an (&string, int) and Some(&s) a &string?. A borrow reads what it borrows and writes
none of it, and it lasts until its last use: a change to the place while the
borrow is still to be read is refused, as Rust refuses it. A borrow of a
number or of plain data is passed as the value, which no program can tell,
and r.^ reads it as Rust’s *r does. Where a pointer is wanted, ask for one:
p: ^Point = &pt points at pt and may be written through, and a pin optional
is written as one, held: ^int? = Some(&n). &mut place is the writable
pointer too.
Where a value is asked, as a typed binding, an assignment, an argument, a
result, a field or an operand asks for one, &place of a number or of plain
data that holds no borrow is that value, read where it is, as a &int name
reads as its int. x: int = &a is a copy of a and borrows nothing, so a
may change while x is still to be read. Where nothing asks, r := &a is the
borrow, and the same change is refused while r is.
fn twice(n int) int { return n * 2 }
fn main() int {
mut a := 5
x: int = &a // a copy of `a`: nothing is borrowed
a = 1
return x + twice(&a) // 5 + 2
}front-run=7 marks an answer the new compiler gives. Today’s compiler holds x
as a borrow of a and refuses the change (ATOLL1097).
Of a value that owes, &place stays the borrow, and a borrow is not the value
it borrows: t: string = &s is refused (ATOLL2002), since reading it through
would be a copy the program never wrote. t := s.clone() makes a value of its
own.
fn main() int {
s := "abc"
t: string = &s // refused: `&s` is a `&string`
return t.len()
}front-fail=ATOLL2002 marks a refusal the new compiler gives. Today’s compiler
reads &s through and takes it.
Where a ^T is expected, the & is inserted for you. pointer.same(a, b)
on two int locals is pointer.same(&a, &b) and answers the same thing, and the
insertion is
not confined to arguments — it fires at a binding’s annotation, a struct-literal
field and a return alike. The two spellings part company in one direction only:
a written & handed where a ^T is asked demands a place and refuses a
temporary, while an inserted one takes the frame slot the temporary already
occupies. So p: ^int = add(1, 2) compiles, and p: ^int = &add(1, 2) is
refused (ATOLL1047). Either way the pointer names a frame slot, so it goes
only where a position promised not to keep it: pointer.same promises that,
while an ordinary fn hold(p ^int) owns what it is handed, and hold(add(1, 2)) is refused (ATOLL1055, below). A &int parameter, as look above,
takes both add(1, 2) and &add(1, 2).
What is already pointer-shaped is not taken again, and the test is the shape
rather than the outermost constructor — a ^T?, a ptr[T], a rawptr[T] and
a distinct alias over any of them all name storage and are left alone.
So a written & of a place that holds a ^T, where that ^T or its ^T? is
asked, is no pointer to the pointer: it reads the pointer, as the place written
bare does, and the block gains a holder while the place stays whole.
p: ^Cell = &c is p: ^Cell = c, and take(&c) hands take a holder of its
own. &mut c reads it the same way and still asks that c be mut
(ATOLL2007); handed to a parameter that owns the pointer it is refused
(ATOLL1110), since that parameter writes nothing of the caller’s. A & or
&mut name of the place, r := &mut c, is read through where the ^T is
asked, too.
struct Cell { n int }
fn take(p ^Cell) int { return p.n }
fn main() int {
mut c := ^Cell{ n: 3 }
p: ^Cell = &c // the pointer: one more holder of the block
r := &mut c
q: ^Cell = r // read through the name
c = ^Cell{ n: 1 } // `p` and `q` still hold the first block
return take(&p) + q.n + c.n // 3 + 3 + 1
}front-run=7 marks an answer the new compiler gives. Today’s compiler refuses
&c and the &mut name where the ^Cell is asked (ATOLL2002).
^ allocates, and it takes a value literal: ^Point{ x: 1, y: 2 }. What
^p over an existing value would mean — copy it into the new block, or move it
there — is not decided, so it is refused rather than guessed.
Dereferencing is usually invisible
A ^T in a value position derefs itself, so a.x reads through the pointer:
struct Point { x int, y int }
fn main() int {
p: Point = Point { x: 1, y: 2 }
a: ^Point = &p
return a.x
}A call reads through a pointer to a function the same way: p(10) with
p: ^fn(int) -> int calls the function p points at, as p.x reads the field
p points at.
fn apply(f &fn(int) -> int, x int) int {
return f(x)
}
fn main() int {
step := 3
add_step := (x int) => x + step
p: ^fn(int) -> int = &add_step
return p(10) + apply(&add_step, 20)
}x.^ exists for where that would not fire — most often to say copy what it
points at rather than copy the pointer:
struct Point { x int, y int }
fn main() int {
p: Point = Point { x: 1, y: 2 }
a: ^Point = &p
q: ^Point = a // another pointer to the same `Point`
r: Point = a.^ // a copy of the `Point`
return q.x + r.x
}It is postfix because a bare prefix or suffix ^ is ambiguous with the
bitwise-xor operator.
&xs[i] borrows the element, and &xs.get(i) answers ^T?
xs[i] answers T and traps out of range, so &xs[i] borrows the element,
&T, or points at it where a ^T is asked, and traps the same way. xs.get(i)
answers T?, so
&xs.get(i) is ^T?: the element’s address, or nothing if the index missed.
fn main() int {
xs: [3]int = [10, 20, 30]
here: int = match &xs.get(2) { Some(p) => p.^ None => 0 - 1 }
past: int = match &xs.get(9) { Some(p) => p.^ None => 0 }
return here + past
}A ^T? is one word, with null standing for None. It costs nothing over a
^T — no tag, no box — which is why accessors answer it rather than T?.
Every element. &xs[i] on a [3]int, a []int, a []string, a [][]int
or a list of anything with a destructor is ordinary. A collection’s length lives
in the value, so the block keeps a count of its own for the case where a
pointer outlives every value holding it, written when the pointer is taken.
What is refused is changing the collection while a borrow or pointer into
it is still to be used, for every element type, []int as much as
[]string — ATOLL1070, said at the later use: nothing copies the block to
make room for both. The borrow is in force only until its last use on each
path, so finishing with it before the change is the repair. Today’s compiler
lends a copy of a number’s element, and holds any other to the end of the block
that binds it, where a narrower scope is the repair.
Lending a collection through a pointer stops no task. total(b.items) and
for x in b.items read the list out of the box, and other tasks go on running
at every poll while this one reads. What the reader was lent stays good until it
has finished: a block another task grows out of, empties or replaces is held
back, and a ^T whose last owner lets go stays whole, so the reader can keep
it. The reader sees what other tasks write in place, as any read through a
pointer does. To read a list exactly as it was, take a .clone() first. What
is held back is memory for as long as the loan lasts, and a loan that holds back
as much as the rest of the heap keeps its task’s turn until it finishes. What
the task does itself is still checked: ATOLL1070 refuses a write of its own to
what it lent, and a suspension under the loan where another task can reach it.
A collection reached through a pointer (&b.^.items[i]) can be written by
anything that reaches its holder: a call handed the pointer, or something that
reaches it, and another task, wherever this one lets it run. So while such a
reference is live, ATOLL1070 refuses any spawn or select, any assignment
over a value holding the collection, and any call that may write the
collection or let another task run, each at its own line.
Another task gets to run at a poll — a loop has one, and so does every
function that calls another — but it can only write what it can reach. So a
loop, or a call whose only risk is a poll, is refused only when some spawn in
the program hands its task a way to the holder behind a pointer: what the
spawn captures, and what that reaches through fields, elements, type
arguments, pointer targets and closures. The refusal names that spawn. In a
program where no task can reach the holder, loops and such calls are allowed.
Which calls may write, the compiler works out from the bodies of everything
the call can reach. A call is allowed when nothing it reaches suspends, and —
where a task can reach the holder — nothing it reaches loops or calls another
function, and nothing it may write through — or give up, running a destructor
— has a type that can reach a collection of that type. println of a string,
b.items.len(), and a function of your own that only reads fields of b are
allowed. A function that copies b into a mut local and adds to b.items,
one that may suspend, a call through a closure or a function pointer, and a
call that adds to any list of the same element type are not; nor, where a task
can reach the holder, one that loops, recurses or calls another, or a string
template that formats a number.
A value given up while the reference is live runs its destructor as a call
would, so one whose destructor may write the collection or let another task
run is refused where it may be given up: where it is made, where it is
assigned over, and, for a local declared before the reference, wherever it is
named — a local is given up after its last use. The collection’s own elements
never count here: the reference keeps their block alive, so giving up b
itself under it runs none of their destructors. Reads, and calls like these,
are what a reference like this is for:
struct Tag { k int }
impl Drop for Tag {
fn drop(&mut self) void { }
}
struct Bag { items []Tag, scale int }
fn scale(b ^Bag) int {
return b.scale
}
fn first(b ^Bag) int {
p := &b.^.items.get(0)
println("reading") // writes nothing, and lets no task run
n := scale(b) * b.items.len() // reads
return match p {
Some(t) => t.k * n
None => 0
}
}
fn main() int {
return first(^Bag { items: [Tag { k: 7 }], scale: 1 })
}A call that may write the collection is refused at the call:
struct Tag { k int }
impl Drop for Tag {
fn drop(&mut self) void { }
}
struct Bag { items []Tag }
fn grow(b ^Bag) void {
mut m := b
m.items.push(Tag { k: 1 })
}
fn first(b ^Bag) int {
p := &b.^.items.get(0)
grow(b) // ATOLL1070 — `grow` adds to `b.items`
return match p {
Some(t) => t.k
None => 0
}
}
fn main() int {
return first(^Bag { items: [Tag { k: 7 }] })
}Reading the collection into a local first changes none of this. c := b.^.items takes nothing out of b, and with elements that owe a destructor
there is no copy to make, so c names the same block: &c[0] is held to
what may write b.^.items as &b.^.items[0] is. The same goes for a field
of a local, c := bag.items, where adding to bag.items under the reference
is refused. And since c names the field’s block rather than a copy of it,
writing through c itself (mut c := bag.items then c.push(x)) is refused
for such elements: write through the field instead.
^T? reads as Option[^T], an optional pointer. The other nesting — a
pointer to an optional — is ^(T?), and the parentheses are what say so.
Borrowing: the whole model
A parameter says what the callee may do with what it is handed. There are seven cases, and this table is all of them:
| You want to | The parameter | The call | The callee may |
|---|---|---|---|
| keep a value | p T |
f(x) |
keep it, write its own copy |
| read | p &T |
f(x) or f(&x) |
read it; never keep it; the caller keeps the storage |
| take a heap block | p ^T |
f(^T{ … }) |
keep the block |
write the caller’s T |
p &mut T |
f(&mut x) |
write it, visibly; never keep it |
| consume and mutate | mut p ^T |
f(^T{ … }) |
write the block and keep it |
| reseat the caller’s pointer | p &mut ^T |
f(&mut ptr) |
write p.^ = to |
| scratch copy | mut h := h in the body |
f(x) |
write the copy; the caller sees nothing |
mut x on a binding means one thing: the binding can be reassigned in this
frame and, for an owned ^T, its pointee can be written by its owner. It never
reaches the caller. What reaches the caller is &mut.
&T borrows a T wherever it lives — in a frame or in a ^T block — and
that is one case, not two:
struct Point { x int, y int }
fn look(p &Point) int { return p.x } // borrows: may read, may not keep
fn main() int {
n: Point = Point { x: 3, y: 0 }
b: ^Point = ^Point { x: 4, y: 0 }
return look(n) + look(b) // a frame value and a block: one parameter
}The marker goes on the type, right of the name — p &Point, not
&p: Point, which is ATOLL1072. A shared borrow is a type, written wherever a
type is (below); parent &Node? is a field that owes nothing.
The old p &^T is ATOLL1108: write p &T.
This matters because a borrowed and an owned parameter are indistinguishable
inside the callee. &local and ^T{…} produce the identical type and both
arrive as one address; only the declaration can say whether the callee may keep
it.
struct Point { x int, y int }
fn keep(p ^Point) int { return p.x } // owns: may keep
fn main() int {
return keep(^Point { x: 1, y: 2 }) // a block of its own
}Handing over a pointer that names a block is always fine. Handing over a pointer into a frame is fine only where the position promised not to keep it:
fn keep(p ^int) int { return p.^ }
fn main() int {
n: int = 7
return keep(&n) // ATOLL1055 — `n` dies with this frame
}A borrowed optional pointer is &Option[^T]
xs.get(i) answers a T?, and &xs.get(i) the optional pointer ^T?. A parameter
that reads one without keeping it borrows the Option that holds the pointer:
&Option[^T]. (&T? is an optional borrow, Option[&T], as ^T? is an
optional pointer; a borrow of an Option[T] is written &(T?).) The
writable form, which also reseats the caller’s variable, is
&mut Option[^T].
struct Tag { k int }
fn key(r &Option[^Tag]) int {
return match r { Some(t) => t.k None => 0 }
}
fn drop_it(p &mut Option[^Tag]) void { p.^ = None }
fn main() int {
xs: []Tag = [Tag { k: 3 }]
a := key(&xs.get(0))
mut cur: ^Tag? = ^Tag { k: 4 }
drop_it(&mut cur)
return a * 10 + key(cur) + 4
}&T is a type
A borrow is a type like any other. A list holds borrows, a function returns one
and a field keeps one, and nothing is copied: &string is the text it was read
from, under a name that owes nothing. A list’s read-only walks answer them.
fn main() int {
names := ["ann", "bo"]
short: []&string = names.filter(n => n.len() == 2).collect()
return short[0].len().to_int()
}There is no lifetime syntax. What a borrow may not do is outlive what it
borrows, and the compiler reads that from the body. ATOLL1116 is a borrow
leaving the function that owns what it borrows:
fn last_name() &string {
names := ["ann", "bo"]
return names[1]
}Inside a body, a borrow ends where what it borrows changes. s = … or
s.append(…) may free the text r lends, so a use of r after it is
ATOLL1097, as Rust refuses the change while r is in use. Finish with the
borrow first, or borrow again after:
fn main() {
mut s := "ab".repeat(3)
r: &string = &s
s = "cd".repeat(3)
println(r)
}A function may hand back what it was handed, because the caller still has it.
.clone() is a value of its own, and it is the one way to keep text past the
list or the string it came from:
struct Tok { text &string }
fn first(s &string) Tok { return Tok { text: s } }
fn main() int {
s := "hi"
t := first(s)
kept: string = t.text.clone()
return kept.len().to_int()
}A number, a bool and a pointer have nothing to borrow: &int is int.
A position that keeps what it is handed takes a value: an argument the
parameter owns, a field or an element of a literal, an assignment, a mut
binding, a result. ATOLL1117 refuses a value something else owns there, a
field read through a borrow, an element, a &T, so nothing is shared or copied
behind the program’s back:
struct User { name string }
fn name_of(u &User) string {
return u.name
}Return a &string, or spell the copy with .clone(). A field of a value the
body holds moves out of it instead:
struct User { name string, age int }
fn keep(s string) int { return s.len().to_int() }
fn main() int {
u := User { name: "ann", age: 30 }
return keep(u.name)
}&mut T writes the caller’s value, and says so at the call
A &mut parameter writes the caller’s T. The call spells the borrow, so the
write is visible where it happens; there is no automatic &mut. The place has
to be writable itself: a mut binding, a &mut parameter, a &mut self
context.
struct Ctr { n int }
fn bump(c &mut Ctr, by int) void { c.n = c.n + by }
fn main() int {
mut c := Ctr { n: 10 }
bump(&mut c, 2)
return c.n
}The parameter’s own name is the caller’s place. Reading it reads the caller’s
value, and assigning it writes the caller’s value, as p += v and p.^ = v
do. The binding is not mut, so there is nothing else for p = v to mean:
fn bump(n &mut int) void {
n = n + 1
}
fn reset(xs &mut List[int]) void {
xs = [1, 2, 3, 4, 5]
}
fn main() int {
mut n := 0
bump(&mut n)
mut xs := [9]
reset(&mut xs)
return n + xs.len()
}A &mut is exclusive and is never kept, so a field cannot hold one
(ATOLL1109), and a place handed to a &mut parameter without the borrow
written is ATOLL1110:
struct Ctr { n int }
fn bump(c &mut Ctr) void { c.n = c.n + 1 }
fn main() int {
mut c := Ctr { n: 1 }
bump(c) // ATOLL1110 — write `bump(&mut c)`
return c.n
}struct Ctr { n int }
fn bump(c &mut Ctr) void { c.n = c.n + 1 }
fn main() int {
c := Ctr { n: 1 }
bump(&mut c) // `c` is not `mut`: nothing may write it
return c.n
}A &mut parameter of your own is passed on as it is, which is a reborrow:
struct Ctr { n int }
fn bump(c &mut Ctr) void { c.n = c.n + 1 }
fn twice(c &mut Ctr) void { bump(c) bump(c) }
fn main() int {
mut c := Ctr { n: 1 }
twice(&mut c)
return c.n
}A function value takes &mut too
&mut T is the borrow of a call, so it is written wherever a call has a
parameter: a function type, fn(&mut string, int) -> void, and a closure,
(out &mut string, n int) => …. A function value of that type writes the
caller’s own string, in place, and the call through it spells the borrow as
any other call does. It is a parameter and not a held borrow, so a field of
that function type is allowed:
struct Writer {
render fn(&mut string, int) -> void
}
fn twice(f fn(&mut string, int) -> void, out &mut string, n int) void {
f(out, n)
f(out, n)
}
fn main() int {
mut out := ""
w := Writer { render: (o &mut string, n int) => { o.append_int(n) } }
w.render(&mut out, 7)
twice(w.render, &mut out, 4)
return out.len().to_int() * 2
}A declared function is a value of that type too, as in Rust: bump below is a
fn(&mut int) -> void. A closure written where such a type is asked for takes
its parameters’ types from it, so n => n += 10 writes the caller’s int:
fn bump(n &mut int) { n += 1 }
fn twice(f fn(&mut int) -> void, n &mut int) {
f(n)
f(n)
}
fn main() int {
mut n := 0
twice(bump, &mut n)
f := bump
f(&mut n)
n = n * 2
twice(k => k += 2, &mut n)
return n
}A &T parameter is spelled the same way: fn size(s &string) int is a
fn(&string) -> int wherever it is named, f := size as much as
xs.map(size), and a call through f borrows its argument as a call of size
does. The type says which parameters write, so a function that writes and one
that does not are two types (ATOLL2002), and a call through the value is
checked as a call of a declared function is:
fn main() int {
mut out := ""
render := (o &mut string) => { o.append("x") }
render(out) // ATOLL1110 — write `render(&mut out)`
return out.len().to_int()
}A closure parameter takes &mut and nothing else of the borrow markers: a
shared &T is still written on a declared function’s parameter and a field
only (ATOLL1046).
A &mut does not outlive its call
A &mut parameter is the caller’s own place, lent for the length of the call.
A closure that captures it may run while the call does: it can be called in the
function, or handed to a function that runs it. It cannot leave:
struct Ctr { n int }
fn run(f fn(int) -> void) void {
f(1)
f(2)
}
fn bump(c &mut Ctr) void {
run(x => { c.n = c.n + x })
run(x => { c.n = c.n + x * 10 })
}
fn main() int {
mut c := Ctr { n: 0 }
bump(&mut c)
return c.n
}Returned, or stored where the caller can read it back, the closure would write
a place the caller has taken back (ATOLL1112). The refusal is at the closure
and the same at every optimization level:
struct Ctr { n int }
fn counter(c &mut Ctr) fn() -> int {
return () => {
c.n = c.n + 1
c.n
}
}
fn main() int {
mut c := Ctr { n: 0 }
f := counter(&mut c)
return f()
}Capture a value instead of the borrow (n := c.n, then use n), or take the
parameter as c ^Ctr, which owns its block and may be kept in a closure.
Bound to a name, a &mut parameter lends that name the place, as Rust’s
reborrow does: after x := p, the place is x’s until x’s last use, and a
use of p before then is refused (ATOLL1123). After it, p is the place’s
again. A name bound from x (y := x) borrows from x in turn: p and x
both wait for y’s last use. A binding with the value’s type (v: int = p) is
a copy and borrows nothing:
fn bump(p &mut int) int {
mut x := p
x += 1 // the place is `x`'s here
p += 1 // and `p`'s from here: `x` is not used again
return p
}
fn main() int {
mut n := 2
return bump(&mut n)
}fn old_value(p &mut int) int {
old := p
p += 1 // ATOLL1123: `old` still borrows the place
return old
}
fn main() int {
mut n := 2
return old_value(&mut n)
}A name lent a place in the body itself, mut r := &mut x or &mut p.a, names
that place for its whole life. So a use of the place while the name is still
to be used is a use through the name, a read, a write or a lend to one call,
where Rust refuses it. Still refused: a move of the place, a & of it held
across a write through the name (ATOLL1097), the place and the name both lent
to one call where either writes, and a place reached through an element, which
the name may have moved out.
fn main() int {
mut x := 1
mut r := &mut x
x += 10 // a write through `r`
r.^ += 100
return x
}One call borrows a place once, if a borrow writes it
f(&mut x, &mut x) and f(&mut x, &x) give the callee two ways to reach x
while one of them writes, so a write through the first would be seen through
the second. Different parts of a value are different places:
struct Pair { a int, b int }
fn set_both(x &mut int, y &mut int) void {
x.^ = 1
y.^ = 2
}
fn main() int {
mut pair := Pair { a: 0, b: 0 }
set_both(&mut pair.a, &mut pair.b)
return pair.a * 10 + pair.b
}The same place twice is ATOLL1113, at the second borrow, with the first as its
label. Every element of a collection is the collection’s place, so
f(&mut xs[0], &xs) and f(&mut xs[0], &xs[1]) are refused as well. A method
that writes its receiver counts as a &mut of it, so x.add_from(&x) is the
same refusal. So does a closure the call runs or may
run, the callee or an argument for a function parameter: it borrows what it
uses of the names it captures, so walk(&mut xs) where walk loops over the
xs it captures is refused. A closure that reads only plain data, such as an
int field, sees the write instead, and a closure handed as a value to keep
(fs.push(() => fs.len())) does not run in the call. The check reads the
call’s own operands: a borrow that reaches the call through a local bound to a
&, or from a callee’s result, is not seen here.
struct Pair { a int, b int }
fn set_both(x &mut int, y &mut int) void {
x.^ = 1
y.^ = 2
}
fn main() int {
mut pair := Pair { a: 0, b: 0 }
set_both(&mut pair.a, &mut pair.a)
return pair.a
}One block through two pointers
Two ^T can name one block, and the call above can then reach one place twice
under two names: grow(&mut m.a, &r.a) with m and r the same ^P hands
grow the string it writes as a and reads as b, and growing it through a
moves what b reads. Where the place holds no storage, b may read it before
the write or after it, as grow is compiled. A call that lends a place through
a ^T to be written, beside a borrow through another ^T of a block of the
same type that reaches the same part, is refused (ATOLL1121) unless the
compiler can tell the two blocks apart. So is a call that hands on a &mut
parameter beside a copy of it: k(&mut d, c) after mut d := c, and one that
hands a pin bound to a name beside the place it points into: h(&mut r, &mut v)
after mut r := &mut v. A pin assigned anew (r = &mut w) may point into any
place it was bound to, and is handed beside none of them.
A ^T handed on by value is held the same way where the callee writes through
it, which the compiler reads off the callee’s body as it does its effects. A
&T names a place nothing writes while it is lent, so poke(c, c) of a
fn poke(p ^Cell, c &Cell) that writes p.^.v is refused, and so is
through(&h, c) of a callee that writes mut q := h.p q.^.v = 7 with h.p
being c: a block a pointer an argument holds names is held where the callee
writes a block of its type through a pointer it reads out of the argument. A
callee that only reads through the pointer, or writes only the parts of the
block the borrow does not reach, is handed both.
The compiler tells two blocks apart three ways:
- Where they come from. Two allocations are two blocks, and a block allocated in the function is none its parameters named on the way in. The same pointer under two names is one block, and refused as one.
- The program’s own test. Inside
if !pointer.same(m, r) { … },mandrare two blocks. - The callers. When both are the function’s own parameters, their being two
blocks becomes something the function asks of its callers, inferred the way
its effects are, and each call of it is held to it the same way: a call
handing it two allocations is taken, and one handing it one block twice is
refused there. A closure is called through a value, never by its name, so it
asks nothing: its body proves the two apart or is refused. A function that
asks is refused where it is named as a value (
f := copy_into), since no call throughfis held to it. A place reached through a parameter, a field or an element of it, is that parameter’s:put(out, &xs[k])in a body handedout &mut stringandxs &mut []stringlends two of its parameters, which every call of it lent apart or was refused.
Different parts of one block, &mut m.a beside &r.b, and a write that frees
nothing, a number, need none of it. Nothing is checked at run time: every proof
is the compiler’s, and the one comparison a program may write is its own.
import pointer
struct P { a string }
fn grow(a &mut string, b &string) {
a.append(b)
}
// Asks its callers for two blocks.
fn copy_into(m ^P, r ^P) {
mut w := m
grow(&mut w.a, &r.a)
}
fn grow_if_apart(xs []^P) {
mut m := xs[0]
n := xs[1]
if !pointer.same(m, n) {
grow(&mut m.a, &n.a)
}
}
fn main() int {
q := ^P { a: "q" }
r := ^P { a: "r" }
copy_into(q, r)
grow_if_apart([q, r])
grow_if_apart([r, r])
return if q.a == "qrr" { 0 } else { 1 }
}struct P { a string }
fn grow(a &mut string, b &string) {
a.append(b)
}
fn copy_into(m ^P, r ^P) {
mut w := m
grow(&mut w.a, &r.a)
}
fn main() {
q := ^P { a: "q" }
copy_into(q, q)
}struct Cell { v int }
fn poke(p ^Cell, c &Cell) int {
mut q := p
q.^.v = 5
return c.v
}
fn main() int {
c := ^Cell { v: 1 }
return poke(c, c)
}mut p ^T consumes a block and may keep it
mut on a pointer parameter is the binding property and nothing more: the
callee owns the block it is handed, may write it, and may keep it. The caller
hands the block over, so a borrow of a frame is refused (ATOLL1055), as it is
at any owning parameter.
struct Node { v int, next ^Node? }
fn bumped(mut p ^Node) ^Node {
p.v = p.v + 5
return p
}
fn main() int {
return bumped(^Node { v: 1, next: None }).v
}A receiver is spelled as a parameter is
A receiver is a parameter named self, and it takes the markers every
parameter takes: self owns what it is handed, &self borrows it, and
&mut self borrows it and writes the caller’s value.
| spelling | the method |
|---|---|
&self |
reads the receiver; the caller keeps it |
&mut self |
writes the caller’s value in place |
self |
takes the receiver: a value nothing reads afterwards moves in, one that is read afterwards is shared |
struct Counter {
v int
fn get(&self) int { return self.v }
fn bump(&mut self) void { self.v = self.v + 1 }
fn take(self) int { return self.v }
}
fn main() int {
mut c: Counter = Counter { v: 7 }
c.bump()
return c.get() + 0 * c.take()
}mut self takes the receiver as self does, and the body may write it: as
mut on any parameter taken by value, it is a binding of the method’s own,
never the caller’s value.
struct Counter {
v int
fn bumped(mut self) int {
self.v = self.v + 1
return self.v
}
}
fn main() int {
c := Counter { v: 7 }
return c.bumped() // 8, and `c` is handed over
}planned marks a design not built yet. Today’s compiler refuses mut self
(ATOLL1048), and the new compiler takes it once its parser does.
@owned self is refused (ATOLL1048); it was the spelling of a different
default.
struct Counter {
v int
fn take(@owned self) int { return self.v }
}
fn main() int {
c: Counter = Counter { v: 7 }
return c.take()
}Writing through a pointer
A pointee is storage. mut on the pointer binding is the permission to
write it — including calling a &mut self method at any depth:
struct Ctr { n int }
fn Ctr.bump(&mut self) void { self.n = self.n + 1 }
struct Box { c Ctr, items List[int] }
fn main() int {
mut p: ^Box = ^Box { c: Ctr { n: 0 }, items: [] }
p.c.bump() // a field of the pointee
p.items.push(7) // one that owns its contents
p.items.push(8)
return p.c.n * 10 + p.items.len()
}A frozen p: ^T is read-only. p.^ = …, p.n = …, and p.bump() all need
mut p. Reseating p = q is also a write of that binding; it does not change
which pointer the caller holds — that is p &mut ^T, below.
A callee that has to change which pointer the caller holds takes the
caller’s pointer by &mut: p &mut ^T, and p.^ = to writes the caller’s
variable. The call is f(&mut ptr).
struct Node { v int, next ^Node? }
fn drop_head(p &mut Option[^Node]) void {
p.^ = match p.^ { Some(n) => n.next None => None }
}
fn main() int {
mut list: ^Node? = ^Node { v: 1, next: ^Node { v: 10, next: None } }
drop_head(&mut list)
return match list { Some(n) => n.v None => 0 }
}A function with a &mut parameter is a value of the type that says so,
fn(&mut Option[^Node]) -> void for drop_head, and a call through that value
hands it the place written at the call, &mut list.
The .^ is optional at every one of those positions, and dropping it changes
nothing: reaching a field of the pointee is reaching the pointee either way.
struct Ctr { n int }
fn Ctr.bump(&mut self) void { self.n = self.n + 1 }
struct Box { c Ctr, items List[int] }
fn main() int {
mut p := ^Box { c: Ctr { n: 0 }, items: [] }
p.^.c.bump() // the same write, with the `.^`
p.^.items.push(7)
p.^.c.n = p.^.c.n + 6
return p.^.c.n * 10 + p.^.items.len()
}A &mut self receiver is a pointer even when the type is a single scalar, which
is what makes assigning to self outright mean anything:
distinct type Counter = int
fn Counter.reset(&mut self) void { self = Counter(9) }
fn main() int {
mut c: Counter = Counter(0)
c.reset()
return int(c)
}A value that holds itself by value — struct Tree { l Tree? } — lives in a
block of its own, and a pointer to one points at that block, whichever way it
was taken: ^Tree { … }, &t, &s.f or &xs[i]. So p.^ = … writes the new
value’s fields into that block, and every pointer to it sees them:
struct Tree { v int, w int, l Tree? }
fn main() int {
mut p := ^Tree { v: 4, w: 7, l: None }
q := p
p.^ = Tree { v: 5, w: 6, l: None }
return q.v * 10 + q.w
}Only pointers share that block. The value itself is still a value: a clone of it is independent of the original, and so is a value read out of a pointer. Writing one never changes the other:
struct Tree { v int, l Tree? }
fn main() int {
mut t := Tree { v: 4, l: None }
d := t.clone()
t.v = 9
mut p := ^Tree { v: 7, l: None }
e := p.^
p.v = 1
return d.v * 10 + e.v
}A value that holds itself lives in a block of its own, and a write to it
rebuilds it: when anything else holds the block, a copy or a reference, the
value’s block moves to a new one when its name changes. A reference taken
before the change goes on naming the block as it was, so using it afterwards,
to read or to write, is refused (ATOLL1097). Finish with the reference
before the change, or take it again after. The reference may have been
stored by a function that took the holder as a &mut parameter, or handed back
in a struct or a closure; it is followed there. Writing through a second
reference to the value is a change to the first one.
struct Tree { v int, l Tree? }
fn main() int {
mut t := Tree { v: 4, l: None }
p := &t
t.v = 9 // t moves to a block of its own
return p.v
}Handing the value on gives its block a second holder, so a write through a
reference into it would change both. That is refused too (ATOLL3107), at the
hand-off:
struct Tree { v int, l Tree? }
fn main() int {
mut t := Tree { v: 4, l: None }
mut p: ^Tree = &t
d := t
p.v = 9
return d.v
}A pointer shares its block by design and is not affected; neither is a struct that holds no block of its own, whose reference follows the name.
Where a pointer may go
A pointer into a block may go anywhere: returned, stored, captured. The block stays alive because the pointer keeps its count.
A pointer into a frame — &local, &local.field, &arr[i] on a fixed
array — is good for as long as that activation is. It may be read, and it may be
passed to a callee, whose activation is contained in this one. It may not be
returned, stored into a block, or captured by a closure that escapes.
fn take() ^int? {
xs: [3]int = [10, 20, 30]
return &xs.get(2) // `xs` dies with this frame
}There is no annotation that makes those safe, and no promotion that quietly
moves the local to the heap to allow it. A pointer that must outlive the frame
is one you write as ^T{…}, which allocates.
A match does not launder it — returning the same pointer through an arm is the
same escape, refused the same way.
A borrowed number is the same case one step removed. p &int is the caller’s
int, and a number crosses a call as its value, so a reference to p names the
callee’s copy. Returning one is ATOLL1111, at the reference:
struct Boxed { r &int }
fn make(p &int) Boxed {
return Boxed { r: p } // ATOLL1111 — return the value, or take `p &mut int`
}A borrowed struct crosses as the caller’s address when the result can hold a
reference, so fn hold(p &Point) Held with struct Held { p &Point } hands
back a borrow of the caller’s Point.
References is the whole of that rule: what a
join of two arms must agree on, what a store releases, and the one shape
(fn get(o &O) ^C) that is still refused.
== compares pointees; same compares addresses
import pointer
fn main() int {
a: int = 1
b: int = 1
eq: bool = &a == &b // true — 1 == 1
id: bool = pointer.same(&a, &b) // false — two addresses
mut n: int = 0
if eq { n = n + 10 }
if id { n = n + 1 }
return n
}== on a ^T dereferences both sides, at any depth, so ^^T derefs twice and
the comparison lands on T. That is the useful default; it also means == is
spent, so identity needs its own name. pointer.same(p, q) is that name, in
module pointer: import pointer and call it by the module’s name.
The rule reaches everything that asks for equality. A ^T is Equatable and
Hashable through its pointee, so xs.contains(p) and a Map[^Node, V]
compare and hash what the pointers point at: two structurally equal nodes are
one key. That is right for a memo and wrong for a set of nodes already
visited, which wants same.
On a pointer optional it is pointer.same_or_none(p, q), which is the same single
instruction — a ^T? is the pointer word with null standing for None, so one
address comparison answers every case, and two Nones are one word and
therefore the same:
import pointer
struct N { v int }
fn main() int {
n := ^N { v: 1 }
m := ^N { v: 1 } // equal contents, a different block
a: ^N? = n
b: ^N? = a
c: ^N? = m
d: ^N? = None
e: ^N? = None
mut t: int = 0
if pointer.same_or_none(a, b) { t = t + 1 } // one address
if pointer.same_or_none(a, c) { t = t + 10 } // two — `==` would say true
if pointer.same_or_none(d, e) { t = t + 100 } // absence is absence
if pointer.same_or_none(a, d) { t = t + 1000 } // an address is not absence
return t
}same itself takes two ^T and refuses a ^T?: they are not one type. The
compiler does not insert a & to make them fit, which would compare the
addresses of the two parameter slots and report nothing.
pointer.same(&a.field, &a) is false: they name different bytes of one block, and
this compares the references rather than asking which block each lands in.
A pointer field owns its block
A field of pointer type owns what it points at, the same way a parameter does:
struct Node { v int, next ^Node? }
fn main() int {
n: ^Node = ^Node { v: 7, next: ^Node { v: 5, next: None } }
return n.v
}Releasing the Node releases what next points at, and so on down the list.
Write & for a field that only borrows — parent &Node? on a back-pointer,
say — and that field owes nothing: releasing the struct does not touch it, and
storing a counted pointer there is refused. A type that holds such a field
carries a borrow, so it never goes in a ^T block (ATOLL1140): a block lives
as long as its last pointer, which may be past what the field borrows. Share
through a ^T of the value, or hold an index.
A &T field is read-only, as a &T parameter is: q.d.n = 7 and a
&mut self call on q.d are refused (ATOLL2001), while pointing the field
at something else, q.d = &e, is fine. A &mut of a place under the field is
refused too (ATOLL2007), whatever holds the field:
struct B { items []int }
struct H { b &B }
fn add(xs &mut []int, v int) void { xs.push(v) }
fn main() int {
b := B { items: [5] }
mut h := H { b: &b }
add(&mut h.b.items, 1) // refused: `h.b` is a borrow
return b.items.len()
}front-fail=ATOLL2007 marks a refusal the new compiler gives. Today’s compiler
passes the check and stops at code generation (ATOLL5106). A write through a
&T reached under a &mut, r.items.push(1) with r &mut &B, is refused the
same way; today’s compiler takes it, leaving b as it was and a block
unreleased.
So a field reads the way a parameter and a local do: ^T owns and &T
borrows. The common case is the unmarked one, and each case has a spelling of
its own. @owned on a field is ATOLL1073 — the field already owns.
A ptr[T] field is an address the compiler does not count: copying one out of
the field retains nothing, and releasing a struct with no Drop releases
nothing through it, so a type that owns a block through a ptr counts it by
hand. Today’s compiler still has a ptr[T] field own its block, and releases
it with a struct that has no Drop. A structure that frees a block by hand can
hold its address in a field marked unsafe — unsafe slot rawptr[T] — which
owns nothing and is set only inside unsafe { ... }
(ATOLL4014). Unsafe says
what such a field promises and what its author keeps.
What you never write
| Elsewhere | Atoll |
|---|---|
Box, Rc, Arc |
^T — one pointer, and the compiler decides what it costs |
&T / &mut T |
the same: a shared and an exclusive borrow; a &T may be held in a local or a field, and &mut T is written on a parameter only (a local lent with mut r := &mut x infers it) |
&^T |
&T — a borrow does not care whether the T is in a frame or a block |
| lifetime annotations | none — escaping a frame is refused, not annotated |
*p to dereference |
implicit, or p.^ to be explicit |
| a null check the type does not require | ^T is never null; ^T? is, and match reads it |
Diagnostics
ATOLL1047 |
& applied to something that is not a place, except a temporary handed straight to a &T parameter, which lives for the call |
ATOLL1048 |
@owned self — a receiver is spelled self, mut self, &self or &mut self |
ATOLL1049 |
&c[i] where the element is computed and has no address |
ATOLL1050 |
^ applied to something other than a value literal |
ATOLL1051 |
@owned on a parameter that is not the receiver |
ATOLL1052 |
@owned &mut self — given away and still observed |
ATOLL1053 |
mut p &T or mut p &mut T — mut is the binding, & the borrow; write one |
ATOLL1054 |
@box — not a decorator; a value in its own block is ^T |
ATOLL1073 |
@owned on a field — a pointer field already owns; &T borrows |
ATOLL1055 |
a borrow handed to a parameter that owns — write p &T |
ATOLL1063 |
retired: mut x T is a binding of the callee’s own. Today’s compiler still says it of mut x T when T is not a pointer, where scratch is a local (mut x := x) and writing the caller’s value is x &mut T |
ATOLL1108 |
&^T — write &T |
ATOLL1109 |
&mut T written as a type where something would keep it — a field, a local’s annotation (r: &mut int), a return type; an inferred mut r := &mut x is taken |
ATOLL1110 |
a &mut parameter handed its place without &mut — write f(&mut x); or &mut handed to a parameter that does not write |
ATOLL1111 |
a reference to a borrowed number, bool, char or pointer returned — return the value, or take p &mut T or p ^T |
ATOLL1112 |
a closure that captures a p &mut T parameter is returned or stored where the caller can reach it — capture a value instead, or take p ^T |
ATOLL1113 |
one call borrows a place twice and one borrow writes it: f(&mut x, &mut x), f(&mut x, &x) — borrow it once, or borrow different parts |
ATOLL1121 |
one call lends a place through a ^T to be written beside a borrow through another ^T that may be the same block — allocate them apart, test !pointer.same(m, r), or take both as parameters, which asks the callers for two blocks |
ATOLL1140 |
a ^T of a type that carries a borrow — a &T field, or a field of a type that has one; a block never holds a borrow — share through a ^T of the value, or hold an index |
ATOLL1123 |
a &mut parameter used while a name it was bound to (x := p) is still to be used — reach the place through x until its last use, or bind a copy (v: T = p) |
ATOLL1115 |
a slice of a fixed array (b[1..3]) goes where the array’s bytes cannot follow or is used against them: returned or stored past the array, written, used after the array was written, or made of an array whose elements own storage — List.copy(..) the slice where it must outlast the array |
ATOLL1116 |
a borrow leaves the function that owns what it borrows, or a value that ends with an arm is joined with a borrow — return a value of its own (.clone()), or take what is borrowed as a parameter |
ATOLL1064 |
&c[i] on affine elements where c has no name at all — a call’s result or a literal |
ATOLL1070 |
a collection changed while a borrow into it is still to be used, for every element type; reached through a pointer, a call that may write it or let another task run, a loop, a spawn, a select, an assignment over its holder, or a value released whose destructor may write it or let another task run, while the reference is live |
ATOLL1066 |
mut on an @host parameter — the boundary never writes back through one |
ATOLL1090 |
a lambda points a captured ^T somewhere else — it holds the address, not the slot; write through it, or return the new pointer |
ATOLL4014 |
an unsafe field set outside unsafe { ... } — in a struct literal or by assignment |
ATOLL4015 |
unsafe on a field that is not a rawptr[T] — a ^T field owns its block and a ptr[T] field is an address nothing counts; neither takes the marker |
A reference into static storage
&CONST names storage no activation owns, so it outlives every frame and is
never released:
const BASE: int = 7
fn look(p &int) int { return p }
fn main() int {
return look(&BASE)
}&CONST is ordinary surface syntax, and PinTarget::Static is what a & on
a constant produces. A &mut CONST is refused: no one may write it.
Not yet
A window of a list is not a second pointer type. It is a List[T] whose
cap == 0 — see Lists. ^[T] is not a
type. Taking &n of a mut scalar homes it so later reads load the slot;
fn f(mut n int) gives f a binding of its own, never the caller’s value (today’s compiler refuses it, ATOLL1063). Writing the caller’s value is n &mut int and f(&mut place).