The Zeno Book Zeno 0.1 zeno-lang.org

30 Ownership

A collector has two costs that firmware notices. It pauses the program when it runs, and memory comes back at no particular moment. A buffer filled a thousand times a second inside a control loop wants neither. So a value in Zeno can be marked owned. An owned value has exactly one owner, and is freed the moment its owner’s block ends, at a line you can point to.

Shared values stay the default. Nothing changes for a program that does not say owned.

30.1 Three words

owned class Packet {
    id: int
    data: owned list[int]
}

function make(id: int) -> Packet {
    let data: owned list[int] = [id, id * 2, id * 3]
    return Packet(id, data)       # `data` moves into the packet
}

function size(packet: Packet) -> int {      # looks
    return len(packet.data)
}

function send(packet: take Packet) -> int {  # takes
    return packet.id
}

let packet = make(7)
print(size(packet), packet.data)
print(send(packet))               # `packet` moves into `send`
3 [7, 14, 21]
7
  • owned class: every object of the class has exactly one owner. It is decided once, where the class is declared.

  • owned list[T]: a list with exactly one owner.

  • take on a parameter: the function takes the value over. A parameter without it only looks: the function may read the value and change what is inside it, and may not keep it.

There are no lifetimes to write, and no &.

30.2 The rules

1. One owner.

A variable, a parameter, or a field of an owned object holds the value. Nothing else does.

2. Storing it gives it away.

Assigning it to another variable, passing it to a take parameter, putting it in a field, or returning it moves it. The old name holds nothing afterwards, and using it is an error that says where it went:

owned class Packet {
    id: int
}
function send(packet: take Packet) -> int {
    return packet.id
}
let packet = Packet(1)
print(send(packet))
print(packet.id)
error: `packet` was given away on line 8 and holds nothing now. Use it before it goes, or give it only to what looks: a parameter without `take`
 --> main.zeno:9:7
  |
9 | print(packet.id)
  |       ^

1 error found. Nothing was run.

3. Looking is free.

Reading a field, calling a method, printing, indexing, comparing and looping over it move nothing.

4. A parameter looks, unless it says take.

What is only looked at cannot be kept, returned or passed on to something that keeps it, so it can never outlive the call:

owned class Packet {
    id: int
}
function keep(packet: Packet) -> Packet {
    return packet
}
error: `packet` is only looked at here: its owner still has it. So it cannot be kept, returned or given away. If it is a parameter, write `take` in front of its type to take the value over
 --> main.zeno:5:12
  |
5 |     return packet
  |            ^

1 error found. Nothing was run.

5. It is freed where its owner’s block ends:

at the closing }, or at a return, break or continue that leaves the block early. A var given a new value frees the old one at that line.

6. Owned may hold shared; shared may not hold owned.

A shared list can be reached from many places, and if it held an owned value, each of them would think the value was still there after its owner had freed it. So a list of owned objects must itself be owned:

owned class Packet {
    id: int
}
let queue: list[Packet] = []
error: each item of this list is an owned Packet, which has one owner: the list. So the list needs an owner too. Write `owned list[...]`
 --> main.zeno:4:1
  |
4 | let queue: list[Packet] = []
  | ^

1 error found. Nothing was run.
owned class Packet {
    id: int
}
var queue: owned list[Packet] = []
queue.append(Packet(1))
queue.append(Packet(2))
let first = queue.pop(0)          # taken out: `first` owns it now
print(first, queue)
Packet(id=1) [Packet(id=2)]

An owned list owns its items, and frees them with itself. A Packet or none can own a packet or nothing.

30.3 Branches and loops

The checker follows each path. After an if, a value is gone if any branch gave it away, unless that branch left with return:

if not ok {
    discard(frame)
    return
}
send(frame)          # fine: only reached with the frame still here

A value given away on one trip round a loop would not be there on the next, so an owner from outside a loop cannot be given away inside it, except just before a break:

owned class Packet {
    id: int
}
function send(packet: take Packet) {
    print("sent", packet.id)
}
let packet = Packet(1)
for turn in range(3) {
    send(packet)
}
error: `packet` is given away inside a loop, and the loop may come round again with nothing in it. Give it away after the loop, or just before a `break`
 --> main.zeno:9:10
  |
9 |     send(packet)
  |          ^

1 error found. Nothing was run.

In a try, an error may leave the body after any line, so the except starts with everything the body gives away already gone.

30.4 Seeing the frees

This program from the examples folder makes 120 frames of 600 samples each, sends some and skips others. Every list and object in it is owned:

buffer.zeno

# Owned values: memory that is given back at a line you can point to.
#
#     cargo run -- run examples/buffer.zeno
#     cargo run -- build --memory examples/buffer.zeno && ./buffer
#     cargo run -- build --no-collector --memory examples/buffer.zeno && ./buffer
#
# Most values in Zeno are shared, and a garbage collector frees them some
# time after their last use (docs/memory.md). A value marked `owned` has
# exactly one owner instead, and is freed the moment its owner's block
# ends. docs/ownership.md explains the rules. This file is the short tour.
#
# Every list and object here is owned, so the third command above can
# build the program with no collector in it at all (docs/no-collector.md).

# Every Frame has one owner. When that owner's block ends, the frame and
# the list inside it are freed, there and then.
owned class Frame {
    channel: int
    samples: owned list[int]

    # A method only looks at the object it is called on.
    function peak(self) -> int {
        var highest = 0
        for sample in self.samples {
            if sample > highest {
                highest = sample
            }
        }
        return highest
    }
}

# An ordinary, shared class. An error to raise.
class Overload {
    channel: int
    peak: int
}

# Makes a frame and hands it to the caller, who owns it from then on.
function capture(channel: int, size: int) -> Frame {
    let samples: owned list[int] = [(n * n + channel * 13) % (400 + channel) for n in range(size)]
    return Frame(channel, samples)    # `samples` moves into the frame
}

# A parameter looks at what it is given and cannot keep it. Any list
# will do here, owned or shared, and the caller still has it afterwards.
function average(samples: owned list[int]) -> int {
    return sum(samples) // len(samples)
}

# `take`: `send` takes the frame over. The caller's variable is empty
# after the call, and the frame is freed when `send` is done with it.
function send(frame: take Frame) -> int raises Overload {
    if frame.peak() > 480 {
        raise Overload(frame.channel, frame.peak())
    }
    return len(frame.samples)
}

var sent = 0
var quiet = 0
var refused: owned list[int] = []

for channel in range(120) {
    let frame = capture(channel, 600)
    if average(frame.samples) < 205 {
        quiet += 1
        continue                      # `frame` is freed here,
    }
    try {
        sent += send(frame)           # or it moves into `send`, which frees it.
    } except Overload as overload {
        refused.append(overload.channel)
    }
}

print(f"sent {sent} samples, skipped {quiet} quiet frames")
print(f"refused {len(refused)} frames, the first on channel {refused[0]}")

# A `var` that owns its value can be given a new one. The old one is freed
# at that line.
var window: owned list[int] = [0, 0, 0, 0]
for round in range(3) {
    window = [value + round for value in window]
}
print(window)

# After a move the old name holds nothing, and the checker says so. Take
# the `#` off the last line to see the message:
let last = capture(7, 4)
print(send(last))
# print(last.channel)
$ zeno build --memory buffer.zeno > /dev/null
$ ./buffer
sent 44400 samples, skipped 13 quiet frames
refused 33 frames, the first on channel 84
[3, 3, 3, 3]
4
memory: 1806 blocks made (2646705 bytes), at most 15870 bytes in use at once, 0 collections, 1625 blocks freed without the collector

It made megabytes of buffers, never held more than a few kilobytes, and the collector never ran: every block was freed at a line, the moment its owner was done.

Rust showed that one owner, checked by the compiler, gives memory back at exact moments with no collector and no mistakes. It also showed that borrowing everywhere, with lifetimes written in the program, is the hardest thing in Rust to learn. Zeno takes the first half. A parameter looks, which needs nothing written, and only keeping needs a word. No lifetimes are needed because a look can never outlive the call. Owned values are a choice made where it pays, and shared values stay the easy default. (Decisions 5.8 and 5.15, and the audit, which made looking the default.)

30.5 What owned values cannot do

In version 0.1 an owned value cannot sit in a function type, be taken out of a field (that would leave a hole the type does not admit to), be replaced through a look, or be raised. Each is an error that says what to do instead, and allowing any of them later breaks no program.

owned class and owned list[T] have one owner, and are freed where the owner’s block ends. Storing gives a value away; looking is free. A parameter looks unless it says take. Owned may hold shared, never the other way. The checker follows branches, loops and try, and says where a value went when it is used after.

  1. Change size above to return the packet’s list. Read the message, and say in your own words why it is right.

  2. Write a queue of owned packets with put and get methods, where get gives Packet or none.

  3. In buffer.zeno, remove take from send. What changes in the report?

  4. Give an owned value away inside a loop and then break on the next line. Why does the checker accept that?