Regions & Capabilities
A region is a group of objects reached through one entry, with nothing outside the group pointing in. Code running in one function and its callees works in the current region: every ordinary record it makes belongs to it, and records alias freely inside it (see Reference-by-Default Assignment). Two further kinds of data sit outside the current region:
current region separate region frozen data ┌────────────────────────┐ ┌──────────────────┐ ┌──────────────────┐ │ a ─▶ Table ─▶ rows │ │ index ─▶ counts │ │ pinned ─▶ Table │ │ b ───────┘ │ entry │ (isolated) │ │ (immutable) │ │ holder ─ index ────────┼────────▶│ │ │ read by anyone │ └────────────────────────┘ └──────────────────┘ └──────────────────┘ writable here one entry, writable only read-only for good inside a `modify` blockisolateddata is a region of its own. One name enters it, and nothing inside points out to the current region or to another region. It is written only through amodifyblock or a one-call open, and it moves between owners as a unit.immutabledata is frozen: shared by any number of holders and threads, and read-only for the rest of its life. Afreezewalk marks every object in the region it freezes as shared, so the result is read with atomic counts from any thread.
A capability is a prefix word on a type, read like an adjective. The words are contextual:
mutable, isolated and immutable are qualifiers exactly where the grammar expects a type, and a name or an
operand everywhere else. A local named mutates or captures keeps its meaning, and swap(1, right: 2), with the
parenthesis against the name, calls a function named swap, where freeze (Box.create(7)) with a space is the
operator over a parenthesized operand (specs/regions-syntax.md).
| Written | Reads as |
|---|---|
function pick(pair (immutable Box, Box)) |
immutable qualifies the first tuple element |
function bump(immutable self) |
immutable is the receiver’s capability |
type Cell uses T where T is isolated |
isolated is the bound |
typealias Visit = function(mutable Box) |
mutable qualifies the parameter of type Box |
swap slot with mutable(seed) |
mutable(seed) is a call to a function named mutable |
typealias A = immutable int |
immutable qualifies a type that belongs to no region: E2010 |
typealias B = immutable (X, Y) |
immutable qualifies a tuple, which is not a record type: refused |
| Spelling | Meaning |
|---|---|
isolated T |
a region of its own; a field, parameter, result or as target |
immutable T |
frozen data; the same positions, and a type argument (Array with immutable Box) |
mutable T |
on a parameter or function-type parameter, write access to what the caller passed (see Parameter Passing) |
function f(immutable self), function f(mutable self) |
the receiver’s capability, written as the first parameter |
let x = e as isolated T |
a local that is a region of its own; as isolated T is the whole initializer. From a local r, the value moves to x and reading r afterwards is E3102 |
type T is unique |
values that move and are never copied or aliased (see Unique Types) |
where T is isolated, where T is sendable |
bounds on a generic type’s parameter (see Region Bounds) |
modify x 'label' … end 'label' |
opens an isolated value for several statements |
freeze x, swap path with value, merge x |
turn a region into frozen data, take a region out of a slot, bring a region into the current one |
A capability word written directly on a number, bool, an enum, a payload-free union or a String is not a
type there: those values belong to no region. A union with a payload does, and takes isolated and
immutable like a record, on the union and on each payload (see Payload Declarations). mutable on a parameter or function-type parameter of a value type is the one
place it is accepted, and it makes the parameter by reference. The same words in other positions fail as any
stray word does: the cases are in specs/regions-syntax.md.
A method may declare its receiver as its first parameter, function reported(immutable self), where
inference cannot express what the method needs. self is not written at the call. A receiver capability on a
static or free function, or self after another parameter, is a parse error (specs/regions-syntax.md).
The capability checks run on every body of every program, whether or not it spells a region word. In a program
that spells none, what they report is the conversion rule: a function value or a conformer converts to a function type or an interface
requirement only if it declares what it does. One that writes, keeps or returns a parameter, or may wait or
yield, against a type or requirement that does not declare it is E3210 (specs/regions-everywhere.md).
Frozen Data: freeze and immutable
Section titled “Frozen Data: freeze and immutable”freeze x turns a region into frozen data. The result is immutable and is shared freely. freeze
consumes a local, so reading the local afterwards is E3102. An expression whose inputs are all
values, immutable data or moved isolated data cannot point back into the current region, so
freeze Point.create(2, y: 3) needs no isolated declaration. A local written as ordinary mutable data is
part of its region and cannot be frozen: freeze cursor.clone() freezes a copy, and freezing the local
itself is E3200, whose message names the fix ('cursor' is used as mutable at line 15; freeze a copy: `freeze cursor.clone()` ).
specs/regions-freeze.md pins these.
immutable T is a type, usable on a typealias, a field, a parameter, a result and a type argument:
typealias SettledIndex = immutable IndexBuilderA write through frozen data is E3197 (cannot write 'numeric' through 'pinned', which is immutable), and
storing a mutable value where frozen data is held, or the reverse, is E3196 (cannot store a mutable 'Row' into 'pinned', which holds an immutable 'Row'; freeze it, or store a copy). Storing immutable data
into a plain holder is E3196 too, and the message names the declaration to change (cannot store an immutable 'ByteArray' into 'Tok.value', which holds a mutable 'ByteArray'; declare the field `immutable ByteArray` ). A method that writes its receiver, called on immutable data, is E3207 ('push' needs a writable receiver; 'frozen' is immutable). A value that joins frozen
and mutable data, through a ternary, a match arm, a try … otherwise or a var assigned both, is
read-only (E3197: which is read-only, as it joins immutable and mutable data). The cases are in
specs/regions-modify.md and specs/regions-inferred.md.
A generic type argument carries a capability. List with Box holds mutable Box values of the current
region and List with immutable Box holds frozen ones; a value that flows into either position is compared
against it as a store into a slot, so a frozen value into the mutable position and a mutable one into the
immutable position are both refused (E3196 at a store, E3207 at a call argument that the callee
stores). Array with immutable Box and Array with Box are
different types (specs/regions-generic-flows.md). An element read out of an immutable slot is read-only, so a
for loop variable over Array with immutable Box, and what an extension member returns out of such an
instance, is written through only as E3197; a clone() is the mutable copy.
Constant Data
Section titled “Constant Data”A let whose initializer is a compile-time constant names image data: a literal, a b"…" byte string, a
constant record, array or tuple literal, or another constant let. The let may be a module-level binding, a
static let, a let field or a local, and the data is immutable; every module-level let and static let is
image data, because its initializer calls nothing (E3220). So is every inline b"…" literal, bound
or not. Image data allocates nothing at run time and is read with plain counts from any thread.
Immutable data goes where it is only read, or where it is held as immutable:
- A parameter that only reads it, an
immutableparameter, and a parameter the callee stores into animmutableplace all take it. - A field, array element or union payload declared
immutable Tholds it. Declared as plainT, the holder is one something may write, so storing it there is E3196 (cannot store an immutable 'ByteArray' into 'Tok.value', which holds a mutable 'ByteArray'; declare the field `immutable ByteArray`); the message names the holder to declare. - A result that returns it is declared
immutable; an unmarked result is E3209 (a return does not fit the declared result: 'Name' is immutable, the result is not `immutable`; declare the result `immutable`). - Writing through it, binding it to a
varand writing, or passing it to a parameter the callee writes is E3207 ('push' needs a writable receiver; 'Name' is immutable;'grow' writes 'name' (line 5: `name.push(100)`); 'Name' is immutable). A mutable copy comes from.clone(), or from building the value (ByteArray.createandpush, or"text".toByteArray()). - A field default that names it (
var names = sharedNames) stores it into a mutable field, so it is E3196; build the value in the default, or declare the fieldimmutable. A closure that returns it returnsimmutabledata (see Closures).
let Name = b"abc"
type Tok export let value as immutable ByteArray
static function create(value ByteArray) returns Self return Self{value: value} end 'create'end 'Tok'
function main() returns ExitCode let t = Tok.create(Name) // create only stores its parameter into an `immutable` field // Name.push(1) // E3207: 'push' needs a writable receiver; 'Name' is immutable print("{t.value.count()}\n") // 3 return 0end 'main'Reading an immutable field, payload or element slot yields immutable data, whatever holds the slot, and the
read leaves the holder as it was: t.value goes straight into another immutable holder, and a for over
an Array with immutable ByteArray binds immutable names.
Data built at run time is immutable once it is frozen, so freeze it where it enters an immutable holder
(Tok.create(freeze ByteArray.create(4))). A Map key and a Set element are immutable slots: a number, a
String or another value type needs nothing, a constant is inserted as it is, and a record or array built at
run time needs freeze ('upsert' takes `immutable` 'key'; a fresh value is mutable. Freeze it first,
E3207). A key read back out of a map is immutable, so it goes into an immutable holder with no copy.
A record whose fields are all let is immutable only structurally: every field is let and every field’s type
is a value type or an immutable aggregate. A record with a let items as Counts array field is an ordinary
mutable record, and sending it as immutable needs freeze.
A record that is an immutable aggregate counts as a value, like a String: immutable over it means the type
itself, it enters an immutable slot or a service message with no freeze, and freeze of one is E3200.
This holds in a tuple element too: (immutable P, W) is the type (P, W).
Parameter Capabilities Are Inferred
Section titled “Parameter Capabilities Are Inferred”An unmarked parameter, and an omitted receiver, takes one of three classes from how the body uses it:
| Class | The body | Accepts |
|---|---|---|
| any capability | only reads it | a mutable, read-only or frozen argument |
| mutable only | writes through it, stores it, captures it, or passes it where a callee needs it mutable | a mutable argument |
| immutable only | sends it, or passes it to an immutable parameter or an immutable self call |
a frozen argument |
A body that needs both is E3206 (parameter 't' is used as mutable (it calls 'add', which writes its receiver) and as immutable at line 27; a parameter cannot be both). An argument the class refuses is
E3207, and the message names the use that decided it:
typealias Tally = int(0 to u64.max)typealias TallyArray = Array with Tally
type Table var rows as TallyArray
static function create() returns Self return Self{rows: TallyArray.create(0)} end 'create'
function count() returns Count return self.rows.count() end 'count'
function add(n Tally) self.rows.push(n) end 'add'end 'Table'
function describe(table Table) returns String return "{table.count()} rows"end 'describe'
function stamp(table Table) table.add(9)end 'stamp'
function main() returns ExitCode let live = Table.create() let frozen = freeze Table.create() print("{describe(live)} {describe(frozen)}\n") // describe takes either stamp(live) // stamp takes the mutable one return 0end 'main'stamp(frozen) is E3207: 'stamp' writes 'table' (it calls 'add', which writes its receiver); 'frozen' is immutable. specs/regions-inferred.md (read-only-param-takes-mutable-and-frozen,
transitive-writer-refused) pins the example and the refusal. A parameter declared immutable T takes a
frozen argument only (E3207: 'create' takes `immutable` 'settings'; 's' is mutable. Freeze it first),
and a method declared immutable self runs on a frozen receiver only.
The classes are computed together over the call graph, so they do not depend on declaration order. A union parameter is judged like a record parameter, and a parameter passed on, even through an alias or as an interface-typed argument, to a callee that stores or writes it is mutable only, so a read-only argument is E3207.
A result’s capability comes from the arguments at the parameters some return path comes from, and from
no other argument. Every such argument mutable gives a mutable result. Every such argument frozen gives a
frozen result when each return path returns a parameter, and a read-only one when some path returns a fresh
or local value. Any read-only source gives a read-only result. An argument at a parameter no path returns
plays no part (specs/regions-results.md). A call whose return paths return parameters of different
capabilities is E3208 ('pick' returns 'a' or 'b'; they must both be mutable or both immutable here).
A function that declares returns immutable T and returns a mutable value, or declares a plain result and
returns an isolated one, is E3209 (a return does not fit the declared result: 'fresh' is mutable, the result is immutable; freeze it). So is a plain result that returns immutable data, a constant or an
immutable field read ('Name' is immutable, the result is not `immutable`; declare the result `immutable` ).
A value joined from a parameter’s data and fresh or local mutable data is judged by the same rule against
the parameter’s final class, and a write through it makes the parameter mutable only. A join with frozen data
is read-only (specs/regions-soundness.md).
A function whose return paths mix frozen data (its own, such as an immutable field, a module let or a
static let) with writable or fresh data hands back a read-only result to every caller, whatever the receiver
or the arguments are: writing through it is E3197, passing it to a mutable parameter is E3207, and
moving it into an isolated position is E3200, and calling a mutates captures function value it hands
back is E3211. One return whose if … else, ternary or match joins
both counts too, and a function that returns a mixed result unchanged is mixed. Declare the function
returns immutable when every path is frozen, or return a .clone() of the frozen path
(specs/settled-results-through-merges.md).
A record built from a parameter’s data and returned (return Self{field: parameter}) holds that data and only
reads it, so the parameter stays any-capability: a frozen argument gives a read-only record, a mutable one a
writable record. A write through the record that reaches the parameter’s data, or handing the record to a callee
that writes that data, stores the record or returns it, makes the parameter mutable only. A parameter a record is built from takes no argument that
is merely read-only, such as data an open modify block pauses. A function value, an interface requirement and
a generic method are judged as if they build a record from each unmarked argument they cannot see into
(specs/returned-and-local-holders.md).
Separate Regions: isolated
Section titled “Separate Regions: isolated”A field, parameter, result or local is declared isolated. A local takes the word after its whole initializer
(written inside a call argument, as isolated T is a syntax error):
let builder = IndexBuilder.create() as isolated IndexBuilderAn expression whose inputs are all values, immutable data or moved isolated data is a fresh region where
an isolated position asks for one, so Self{index: WordIndex.create()} fills an isolated field. A
variable of ordinary mutable data does not become isolated by being stored: it is E3200 ('spare' is not isolated: only a clean call, a `swap` or an `isolated` local goes where an isolated value is wanted; declare it `as isolated Bag`, or store a copy).
A local initialised from a fresh value (let spare = Bag.create()) goes into an isolated position the first
time the program reads it: an isolated parameter or slot, the initializer of an isolated declaration
(let keep = Slot.holding(spare) as isolated Slot reads it inside the union literal), freeze and merge.
That read moves the local, so a later read is E3102. A local the program read earlier and one with a second
name are ordinary mutable data and E3200 (specs/regions-recover.md).
A local assigned a fresh value (spare = Bag.create()) is fresh in the same way, from that assignment on. Where
an if, a match or a statement try joins fresh values, the joined local is fresh until some path has read
it. A loop header joins the value before the loop with the value each back edge brings, the back edges of every
enclosing loop included: a local that a loop relies on as fresh needs all of them to be fresh values nothing has
read, so a lap that assigns it a fresh value on every path to its end, continue included, refills it, and any
other lap is E3200.
A unique argument is a clean input of a call only when its type is closed: every field and payload in its
closure is a value, immutable, isolated, a service handle, or a unique or linear type that is itself closed.
A call given a unique argument whose type holds a plain record, array, union, function value or interface value
is not a clean call, and its result goes to no position that wants an isolated value (E3200). Reading a
plain part out of a unique parameter the callee only lends is not a keep, so the caller’s value stays usable
after the call.
isolated values are linear. Every use of an isolated local or parameter moves it except opening it, so
let b = a moves a and a later read of a is E3102. An isolated parameter owns the region it is
handed; mutable isolated is by reference, and the callee may open, swap or replace it, or lend it on to
another mutable isolated parameter (a method’s own recursion included), but never move it out, alias it,
store it or pass it to an isolated parameter (E3202). Reading an isolated value without opening it, such as
self.part outside a block, is E3198 ('self.part' is isolated and cannot be read outside a block; open it with `modify`, or take it out with `swap` ).
modify Blocks
Section titled “modify Blocks”modify x 'label' … end 'label' opens an isolated local, parameter or field for several statements. Inside,
x keeps its name and is writable; everything outside is read-only except block locals, objects made inside
the block and outer vars that hold a number, bool, enum, payload-free union, String or Character:
function buildIndex(declarations DeclarationArray) returns SettledIndex let builder = IndexBuilder.create() as isolated IndexBuilder
modify builder 'fill' for declaration in declarations 'eachDeclaration' builder.add(declaration.clone()) end 'eachDeclaration' end 'fill'
return freeze builderend 'buildIndex'The index is filled in a region of its own and frozen on return; specs/regions-modify.md
(build-then-freeze-runs) runs the whole program. modify on a name that is not isolated is E3198
('counter' is not isolated; 'modify' opens an isolated value. Declare it `as isolated Counter` ). Opening,
swapping, sending or freezing a region needs a writable holder, so one reached through read-only data is
E3199.
Inside a block:
- Only the region’s contents are writable. The slot holding
xcannot be reassigned or passed by reference in its own block (E3203). An outervarthat holds anything but a number,bool, enum, payload-free union,StringorCharactercannot be reassigned (E3204); the message names what it holds ('keep' holds a linear value from outside 'fill' and cannot be reassigned while 'fill' is open). - A mutable value cannot leave the block by
return, bythrowor by an outer variable (E3202): what leaves is a value,immutabledata or a freshisolatedregion. - A nested
modifyleaves the root of every enclosing block read-only. - An
isolatedlocal or parameter declared outside the block is read-only inside it and cannot be opened: a call that passes it in an unmarked position (as argument or receiver), a read or write through it, and a nestedmodifyof it are E3199 ('outer' cannot be opened: the value that holds it is read-only while 'fill' is open). It still goes where anisolatedvalue goes: anisolatedparameter or slot, a send,merge. Anisolatedlocal the block creates is opened like any block local. The state of an acquired service is held by itsacquireand is not such a local: inside amodifyof one state another state is read one statement at a time, and a write to it is E3197 or E3207. - Waiting on another party and running a coroutine are refused:
await,awaitAny,acquire, a runtime park such asScheduler.quiesce(), and a call that may wait or may yield are E3205 (Waiting and Yielding). A statement that needs a writable argument or receiver of outer data is E3207 ('noteFile' needs a writable receiver; 'self' is read-only while 'fill' is open). - An
isolatedvalue of a linear type from outside the block cannot be moved into a parameter the callee keeps and that is notisolated, because it would become part of the open region (E3201): move it into anisolatedparameter or slot, send it, ormergeit. The receiver of aconsuming selfmethod is such a parameter when the method stores, returns or passesselfon; a finalizer that only readsselfand ends indestruct selfis accepted. Anisolatedvalue older than the innermost open block stays outside it through every rename inside it: a local it is moved into, theisolatedresult of a call it is moved into, the payload amatchof it binds, the value a failed send hands back inmailboxFullorserviceStopped, and amutable isolatedparameter, which is the caller’s variable. Such a value is not opened inside the block (E3199) and still goes where anisolatedvalue goes. Amutable isolatedparameter open in its own block is read inside a block nested in it. - Outside every open block, a method of an
isolatedreceiver takes an un-openedisolatedlocal of a linear type into a parameter it owns:bx.eat(v)movesv, and its region joins the receiver’s. A non-linearisolatedlocal, or a plain linear local, beside the opened receiver is E3201, and the call inside amodifyblock is E3199, since the receiver is then an outer value. merge xmoves anisolatedregion into the region the block writes, sobuilt.reader = merge readeris accepted insidemodify built, and in a one-statement open as well.- A
forover an array the loop drains makes the array read-only in the body (E3197).
One-Call and One-Statement Opens
Section titled “One-Call and One-Statement Opens”A call that passes an isolated value in an unmarked position, as receiver or argument, opens it for that
call. A statement that reads or writes through an un-opened isolated value (lines.count(),
job.number = 4, holder.page.lines.push("a")) opens it for that statement. A number read straight out of an
isolated parameter (self.total = self.total + point.x) opens nothing, so the statement may write other
data; a read through a record field of one (point.inner.n) opens the parameter and leaves the statement’s
other data read-only (E3197). The same rules apply as in a
block: one isolated root per statement, every other operand a value, immutable data or a moved isolated
value, and only values, immutable data and fresh isolated data leave. Two roots in one statement are
E3201 (one statement reaches through two isolated values, 'left' and 'right'; a statement opens one isolated value, so open one with `modify` or split the statement), as is mutable outer data beside the opened
region ('spare' is mutable outside 'index'; a call into an isolated region takes values, immutable or isolated). For an if or while the open covers the condition alone; a for or match over the value
opens it for the whole statement.
Match Arms That Lend an isolated Payload
Section titled “Match Arms That Lend an isolated Payload”The arm of a match over a union whose case holds an isolated payload is a window, as a modify block is:
data that existed before the arm is read-only in it, whether or not the arm names the payload. A write to a
field of an outer record, of a parameter, of self, of the root of an enclosing modify or of an acquired
state is E3197 (cannot write 'n' through 'b', which is read-only while 'x1' is open), and a call that needs
that data writable is E3207. Data the arm creates, the payload through its binding, a variable that holds a
number, and the arm of a case with no isolated payload are writable. A union with a linear payload is consumed
by the match, so its arms own their payloads and open no window, a frozen union lends nothing, and a union held
in an isolated local hands its payload out as a region of its own.
specs/regions-modify.md pins the forms (a-match-arm-lending-an-isolated-payload-refuses-a-write-to-outer-data).
Every other union is ordinary region data, held by a plain let, a var, a parameter, a field or an element, and
it aliases freely: a second name, a call that keeps it and a call that returns it reach the same payload. The
payload an arm binds is therefore lent to the arm and is a part read: the
arm opens it, as it opens any isolated value it does not own, and an owned isolated position (an isolated
parameter or slot, a send, freeze, a binding) refuses it with E3198. A payload bound from a union held in an
isolated local is an owned value, and passing it twice to isolated parameters is E3102.
specs/regions-match-lend.md pins both.
An arm that lends a unique payload, and a for body that lends unique elements, are no window when the payload
or element is not isolated: outer data stays writable (have(t) then o.n = 5), and the holder is protected
instead. The matched variable is not reassigned, rebound, swapped, moved, copied, kept or passed by reference in
its arm. In a lend from a field path (match h.u, for t in h.xs) the whole root h is the holder, read-only
for the lend: a write through it is E3197 (cannot write 'n' through 'h', which is read-only while 'arm' lends a unique value out of it), and a call that needs it writable is E3207. The matched variable itself goes to a
callee that writes through it only in a statement that names no binding of the arm: the receiver, a function
value or an interface method that writes through it beside a binding is E3102, because the callee cannot know
that two of its parameters reach one unique value. The binding is a lent unique value that is never kept,
stored, moved or sent, and its plain parts are ordinary data of the current region.
Part Reads and Handed-Back Results
Section titled “Part Reads and Handed-Back Results”A read of an isolated field, element or payload outside a block is a part read: data its region still
holds. A part read becomes no other holder’s data, whatever road it takes. Binding it, storing it in a field
or a variable, returning it, putting it in a tuple, a union or a constructor, capturing it in a closure,
freezing it, casting it as isolated, and handing it to an async call, a service message, an isolated
parameter or a parameter that keeps it are E3198. The read carries its mark through a join (if … else,
a ternary, a match arm, otherwise), through a field of it, through the result of a call given it, through
each element a for loop hands out over an isolated collection field, and through a closure that captures
it. .clone() and a function that returns isolated make a fresh value of a part read, and a value read out
of one — a number, a count, a comparison — leaves freely.
A method of an opened region that hands back mutable data of that region (holder.blob.inner()) gives a
handed-back result, which the same statement consumes: a comparison, a for loop over it, or a call
whose other inputs and whose result are values (holder.blob.inner().count()). One still unconsumed at the
end of the statement is E3201 ('inner' hands back mutable data of the isolated region it opens; use it inside a `modify` block). The message quotes the whole argument or receiver that carries the read.
specs/regions-soundness.md pins these.
swap and merge
Section titled “swap and merge”swap path with value takes the region out of an isolated field or element and leaves value in the slot:
function takeIndex() returns isolated WordIndex return swap self.index with WordIndex.create()end 'takeIndex'merge x moves an isolated region into the current one, and the result is ordinary mutable data:
return merge box returns an isolated parameter as a plain result. swap on a path that is not an
isolated field is E3198; merge of a value that is not isolated, and freeze of a value type, are
E3200. The cases are in specs/regions-modify.md and specs/regions-freeze.md.
An isolated field filled in modify, written by a one-call open and taken out whole with swap is run in
specs/regions-modify.md (isolated-field-modify-one-call-swap-runs).
Unique Types
Section titled “Unique Types”type Ticket is unique declares values that are never cloned and never aliased. let b = a moves a,
whether a is a let or a var (E3102 on a later read of a); storing a unique value moves it; an argument is lent for the call, and a
callee that keeps its parameter takes the caller’s variable. A parameter moves as a local does: after the
function binds it to a second name, stores it, or answers it (Reply), a later read of it on a path that
follows, or the same move on the next lap of a loop, is E3102. clone() is E3214 ('Ticket' is unique and cannot be cloned):
type Ticket is unique export var serial as Serial
static function create(serial Serial) returns Self return Self{serial: serial} end 'create'end 'Ticket'A type with a unique field is unique too, with no declaration and no generated clone() (E3214:
'Wallet' is unique (its field 'ticket' holds a unique 'Ticket') and cannot be cloned); so is a type that
holds an array of unique values, and so is a union with a unique payload (slot.clone() is E3214). A unique
value cannot be frozen, and reading one out of a field or an element
to bind, return or store it is E3214, and so is a for loop variable or a tuple destructure of one handed
to a parameter that keeps it: move it out with pop, remove, removeFirst or Slot.take, or swap it out
of an isolated field. Handing a unique value to a parameter the callee only reads leaves it
readable, and an element a container call hands back is lent for the call in the same way:
show(items.get(0)) reads it, and let ticket = items.get(0) is E3214. A match over a unique union lends
it to its arms: the variable that holds the matched union (its name, the record whose field is matched, or an
operand of a cond scrutinee) is not moved, copied, stored, captured or passed to a parameter that keeps it
inside an arm (E3214), while a call that only reads it is accepted; move or copy it before or after the
match. A message argument or spawn factory argument is handed to another green thread, so the sender must
own a unique value there: one read from a field or an element, lent by a loop, a tuple or a match, or
borrowed through a mutable parameter is E3214, and an owned one crosses only as the whole of its region
(What crosses a message). The standard library’s Promise is
unique, so is Reply, and so are the OS handle types (TcpClient,
TcpListener, TlsStream, TlsListener, HttpServer, StreamingSubprocess, SharedSegment) and every type
that holds one: binding a handle with let, pushing it into a container or handing it to a spawn moves it, a
later read of the name is E3102, and a handle is never cloned. One owner holds a handle and lends it to calls.
The cases are in specs/regions-unique.md.
Linear Types and Finalizers
Section titled “Linear Types and Finalizers”A destruct self statement ends the life of the value a method is called on. A method that contains one is a
finalizer, and it takes consuming self: a call to it moves the receiver, and reading the receiver
afterwards is E3102, and so is a read or write of self after destruct self. A destruct self, or any
other move of the receiver, inside a loop is E3102 too: the next lap reads a receiver the previous lap
moved. A type with at least one finalizer is linear, and a linear type is unique: never
cloned, frozen or aliased (E3214).
typealias Code = int(0 to 999)
type Resp var code as Code
static function create(code Code) returns Self return Self{code: code} end 'create'
function peek() returns Code return self.code end 'peek'
function fin(consuming self) print("fin {self.code}\n") destruct self end 'fin'end 'Resp'
function use(r Resp) print("use {r.peek()}\n") r.fin()end 'use'
function main() returns ExitCode let first = Resp.create(1) print("peek {first.peek()}\n") first.fin()
let second = Resp.create(2) use(second) return 0end 'main'Output: peek 1, fin 1, use 2 and fin 2. A finalizer belongs to a type that holds fields, and a method
that takes consuming self contains destruct self; either one alone is E3224.
-
A linear value is consumed exactly once on every path out of its scope, throws, early returns and propagating
trys included. A finalizer call consumes it, and so does moving it on: to a function that takes it (an argument at a linear position always moves, so a function that takes one consumes it), into areturn, athrowor a message. Dropping it, overwriting it, rebinding it while live, discarding it withlet _ = r, or leaving it in a temporary nobody consumes is E3223:error E3223: this drops 'dropped', a linear value that was never consumed: call one of its finalizers (a `consuming self` method) on it, or move it into a call, a send or a `return`, on every path out of here, `throw`s and early `return`s included -
A linear value lives only in locals, parameters, message arguments and the arguments of a
spawn. A field, a container or other type argument, a tuple item, a closure capture, a promise payload, a message reply, a union stored in a field, the argument or result of anasynccall and an argument of an interface or function value call are E3224: each would keep the value past the code that must consume it. Aspawnof a factory that cannot throw takes a linear argument, which the factory consumes; a factory that may throw takes none (E3224), because a factory that fails starts no service and drops the value. A value lent to code that does not own it, such as a parameter of a function that does not take it orselfof a method that does not takeconsuming self, is consumed only by its owner: passing, returning or building it into a union there is E3224. -
No linear value is live across a wait. An
await, a send with asendTimeout:and a call that waits may never end, so a linear value is consumed before one (E3223). -
A union with a linear payload is linear. A
matchover one consumes it: every arm for a case with a linear payload binds it to a name and consumes it, and adefaultarm cannot cover such a case (E3224). An arm may assign the variable it matched once the payload is consumed, sosome(r) then m = recycle(r)refillsm; a read ofmafter thematchneeds every arm to have refilled it, and a loop that matchesmneeds every path to the end of the lap,continueincluded, to have refilled it. A failed send hands a linear argument back inmailboxFullorserviceStopped, and the handler of the failure consumes it. -
A
matchconsumes the union on its own path. Each branch of anif, and the body and the handler of anacquire, may match the same union, and a read after the join is E3102 when any path matched it. The same holds for a union with a managed payload that is not linear. -
A union held in an
isolatedlocal, anisolatedparameter or a behaviour’s message parameter is matched where it stands. Thematchhands its payloads over as fresh owned values: the lone plain payload of its case goes where anisolatedvalue goes (anisolatedparameter or slot,freeze,merge), and inside an openmodifywindow it belongs to the window’s region, so the arm may write it, keep it in a call, or store it into the window’s data. The linear argument a failed send hands back isisolatedtoo (specs/regions-recover.md). -
An owned linear value goes where an
isolatedvalue goes only when its type is closed. An owned linear parameter orconsuming selfreceiver goes to anisolatedparameter, slot, declaration or result, a send ormergeonly when every field and payload in its type’s closure is a value,immutable,isolated, a service handle, or auniqueor linear type that is itself closed. A plain record, array or union, a function value and an interface value are plain parts, which other code may still name: such a value is ordinary data of its region, matched, finalized or moved on to another plain linear position, and anisolatedposition refuses it with E3200, naming the plain part. Declare the partisolated, or consume the value where it is. The payload amatchof a union in anisolatedlocal binds keeps the standing of that local. -
A case that carries no linear value owes nothing. A variable of a linear union that holds such a case (
Maybe.nothing) on every path to a point is not a linear value there: assigning it, leaving its scope or leaving it live across a wait is not a drop. A branch, a loop lap or atryhandler that can leave the linear case in it keeps the obligation, and so does a value that came from a call. Such a variable takes anisolatedvalue withoutmerge; once it may hold the linear case on some path, storing that value is E3196. -
Cancellation consumes. A coroutine that holds a linear value is cancelled cooperatively, so its own code consumes the value on the path the early return of its wait leads it down.
The standard library’s HttpResponder is linear: respond,
respondWith and abandon are its finalizers.
Region Bounds
Section titled “Region Bounds”A generic type may bound a type parameter in its own where clause:
type Pool uses T where T is sendable export var item as T ...end 'Pool'T is sendable takes a value, a service handle or an immutable record: a plain record, which the caller
keeps sharing, and a unique type, whose values move, are refused. T is isolated takes a value, a service
handle or a unique type. Every instantiation is checked against the bound, including an instance made
through a type parameter, and a refusal is E3215 ('Job' is not sendable, so it cannot be 'T' of 'Pool', which declares `where T is sendable`: a plain record is shared with the caller; use `immutable Job`, or a value or a service handle). A function’s or an extension’s where clause cannot spell either bound (E3215).
A generic type accepts an isolated type argument only when it declares where T is isolated
(Wrapper with isolated Box over an unbounded Wrapper is a parse error). specs/regions-bounds.md pins
these.
Capabilities at Function Types and Requirements
Section titled “Capabilities at Function Types and Requirements”A function type and an interface requirement have no body for the checker to read, so they declare what the callee does. Unmarked, they are read-only and neither wait nor yield:
| Spelling | Meaning |
|---|---|
function(mutable T), function f(mutable self) |
the callee writes that parameter, or the receiver |
function(immutable T), returns immutable T |
the callee reads frozen data, or hands frozen data back |
returns isolated T |
the result is a region of its own |
function(…) returns R mutates captures |
the closure may write what it captured |
interface Grows function grow(mutable self, by Tally)end 'Grows'
typealias Step = function(mutable Counter) returns TallyA closure, function value or conformer converts to one only if each unmarked parameter, its receiver and each capture is read and not written, and it neither waits nor yields. Anything else is E3210:
error E3210: 'Bag.grow' writes its receiver, but 'Grows.grow' does not declare `mutable self`error E3210: function value for 'Look' writes its parameter 'counter', but 'Look' does not declare it `mutable`error E3210: function value for 'Array.SortComparator' writes data it captured, but 'Array.SortComparator' does not declare `mutates captures`error E3210: function value for 'Step' may yield (it awaits a coroutine at line 12), but a function type never waits or yieldserror E3210: 'Relay.echo' may wait (it awaits a reply from 'Bouncer' at line 28), but a requirement never waits or yieldserror E3210: function value for 'KeyOf' returns data reached from its read-only parameter 'key', which 'KeyOf' does not allowA function value that returns its read-only parameter, or throws it in an error payload, converts once it
returns a .clone() of it (specs/regions-everywhere.md).
A closure that writes what it captured, or builds a record from it, mutates its captures; the compiler infers
it, so nothing is written on the closure. It converts only to a function type that declares mutates captures,
and a plain function type refuses it (E3210). A closure that writes through a captured iterator writes the
collection the iterator runs over, which therefore has to be mutable data
(specs/closure-captured-iterators.md). A conformer whose result holds data from its receiver needs
mutable self on the interface requirement (E3210).
A conformer or function value whose declaration marks a position the boundary leaves unmarked, or the
reverse, is refused too. A value of a mutates captures type called through frozen or read-only
data is E3211 ('Tallier' mutates captures and cannot be called through immutable data): on frozen data
anywhere, and inside an open modify block when the value was returned from, read out of or stored in the data
the block holds.
A caller trusts the declaration: an argument at a mutable position is writable, and one at an immutable
position is frozen (E3207). A result read through an interface or function value is read-only, so a
requirement that wants to hand back data to store declares returns isolated T or returns immutable T.
specs/capability-qualifiers.md and specs/regions-convert.md pin these.
Waiting and Yielding
Section titled “Waiting and Yielding”Two facts are inferred for every function, with no marker. A function may wait when it waits on another
party: a service reply, awaitAny, a send with a timeout, an acquire, a spawn of a factory that throws, a runtime park (Scheduler.quiesce(), CownTorture.violations), or a call to a function
that may. A function may yield when it awaits a coroutine, or calls one that may yield or may wait. File,
socket and process I/O and sleep are neither: they park the green thread, and while a modify block is open the
runtime does not switch to a sibling coroutine of the same green thread, so the thread waits for the block
(specs/regions-runtime.md, break-leaves-window-lets-sibling-run).
A message or a spawn factory that may wait is
E3221: Holders Never Wait.
Inside a modify block, an acquire block or a one-call open (a call that passes an isolated value in an
unmarked position, as receiver or argument), a coroutine await, awaitAny, a call that may wait or yield, the
start of a coroutine that may wait and a spawn of a factory that may wait or yield are E3205, and the
message names why. A callee that only reads, writes or sleeps is accepted:
error E3205: cannot call 'settle' inside 'fill'; it may yield (it awaits a coroutine at line 12). Call it before or after the blockerror E3205: cannot call 'ask' inside 'fill'; it may wait (it awaits a reply from 'Oracle' at line 16). Call it before or after the blockA call through a function value that can be anything feeds the caller’s may-yield bit, and a call whose body cannot be read counts as may-wait. Await before the block and pass the result in.
Coroutines and Regions
Section titled “Coroutines and Regions”An async call that takes the caller’s mutable data produces a tied promise, and every promise held in a
local is must-use. Tied and Must-Use Promises states both rules. A variable
handed to a mutable parameter of an async callee is lent to the coroutine until the promise is awaited or
cancelled (Starting a Coroutine).
Pending Operands
Section titled “Pending Operands”A value already read for one operand survives the operands after it. A field read used as a constructor,
union-literal, send, spawn or async argument is held across every later operand that may run user code,
and a match subject is held across the arms that write back (specs/regions-holds.md). A by-reference
write is the exception a hold cannot cover, and E3186 refuses it at compile time
(Aliasing Between Arguments).
Capability Errors
Section titled “Capability Errors”| Code | Refuses |
|---|---|
| E3196 | storing a value of one capability where another is held |
| E3197 | a write through frozen or read-only data |
| E3198 | an isolated value read outside a block, modify or swap of a value that is not isolated |
| E3199 | opening, swapping, sending or freezing a region held by read-only data |
| E3200 | ordinary mutable data where an isolated value is wanted, and freeze or merge of what they do not apply to |
| E3201 | one statement reaching two isolated regions or two acquired states, mutable outer data beside one, or an outer isolated linear value moved into an open region |
| E3202 | a mutable value leaving a modify or acquire block, an acquired state leaving its block, a mutable isolated parameter moved out |
| E3203 | the slot of an open value reassigned in its own block |
| E3204 | an outer var holding anything but a number, bool, enum, payload-free union, String or Character reassigned in a block |
| E3205 | waiting or yielding inside a modify or acquire block or a one-call open |
| E3206 | a parameter the body needs both mutable and immutable |
| E3207 | an argument whose capability the parameter refuses |
| E3208 | a result whose source arguments disagree |
| E3209 | a return that does not fit the declared result |
| E3210 | a function value or conformer that does more than its function type or requirement declares |
| E3211 | a mutates captures value called through frozen or read-only data |
| E3212 | a tied promise returned, stored, captured, sent, passed on, or left unconsumed on an exit |
| E3213 | a promise dropped, overwritten or discarded |
| E3214 | a unique value cloned, aliased, frozen or moved out of a slot it was only read from |
| E3215 | a type argument that breaks a where T is sendable or where T is isolated bound |
| E3216 | a service type whose state can hold a promise |
| E3217 | a service message or factory parameter, or a message reply, that holds data of its region and names neither isolated nor immutable, or whose type cannot cross at all (a promise holder, a function value, an opaque type parameter, a thread-bound handle) |
| E3221 | a message or spawn factory that may wait on another party while it holds its own service |
| E3222 | reply.later() or a Reply used where the holder could not answer it exactly once, or a Reply leaving its service’s code |
| E3223 | a linear value dropped, overwritten, discarded, or live across a wait |
| E3224 | a linear value in a field, container, tuple, capture, promise, reply or other place that cannot consume it exactly once, and a finalizer or consuming self written outside its rules |
| E3226 | a tuple cast that gives an element a different capability |