Composite Types
Composite Types
Section titled “Composite Types”A type declares a record with named fields and methods. A value of a type is a reference to a heap
record (see Memory Model), unless the type’s whole shape fits one machine word — see
Inline Packed Records.
Declaration
Section titled “Declaration”typealias Coord = int(i64.min to i64.max)
type Point export var x as Coord export var y as Coord
static function create(x Coord, y Coord) returns Point return Point{x: x, y: y} end 'create'end 'Point'
function main() returns ExitCode let p = Point.create(10, y: 20) print("{p.x}, {p.y}\n") return 0end 'main'varfields can be reassigned after construction;letfields cannot (E2013,'version' is a let field and cannot be reassigned). Aletfield’s record can still be written through:self.columns.push(x)is legal on alet columnsarray.- A field without a default names its type after
as(var x as Coord); a field with a default takes its type from the default (see Required Field Initialization). The type is an alias,bool, a type, or another named type — a bareintorfloatis refused. - An unmarked field is visible to its type’s declaring directory and that directory’s subdirectories:
a method of another type, a free function and an
extensionwritten there all read and write it. Reading or writing it from any other directory is E3014 (field 'Box.v' is not exported). - A type cannot contain itself, directly or through other types:
var next as NodeinsideNodeis E4014 (recursive type references are not allowed). Use a container such asArray with Nodeor an index.
Construction
Section titled “Construction”A type literal Point{x: 1, y: 2} — or Self{...} — is legal only inside the type’s own body. Code elsewhere
constructs through a static factory, which is where invariants are established. A literal outside the
type is E3076 (type 'Point' can only be constructed from within its own methods; use a static factory method instead).
Required Field Initialization
Section titled “Required Field Initialization”Every field must have a value when a record is constructed. A field is initialized when:
-
The declaration supplies a default, evaluated each time a literal omits the field. The field’s type comes from the default, which takes one of three shapes:
- a
true/falseliteral (bool) or a string literal (String):var enabled = true; Type.memberorType.member(...)— an enum case or a static factory — typedTypeand checked against it:var level = Priority.low,var items = IntArray.create(0);- an expression whose outermost node is a cast, typed by the cast:
var count = 0 as Tally,var span = NoSpan as SpanId,var total = (1 + 2) as Tally.
A number has no type of its own, so
var count = 0is E2004, as is any other default, such as a bare global (var span = NoSpan) or1 + 2 as Tally(whose outermost node is the+). A field declares its type afterasonly when it has no default:var count as Tally = 0is E2010. A cast that gives the field its type is legal even on a value that already has it (NoSpan as SpanId); a cast on a default whose shape already gives the type (var g = Gauge.make() as Gauge) is E3010. - a
-
The literal supplies it:
Counter{value: 5}. A supplied value always wins over the default. -
A static factory assigns it with
self.field = expron every path beforereturn Self{}(or the type’s own literal).
A literal that leaves a field uninitialized is E3086, listing the fields.
typealias Tally = int(0 to u64.max)
type Counter export var value as Tally export var version = 0 as Tally
static function create(initial Tally) returns Self self.value = initial // rule 3 return Self{} // version comes from its default end 'create'end 'Counter'Rule 3 requires definite assignment: a write on only one branch of an if, or only inside a loop body,
does not count.
Methods
Section titled “Methods”Methods are declared inside the type body. Inside a method, fields and sibling methods are reachable by
bare name; self names the receiver explicitly.
typealias Coord = int(i64.min to i64.max)
type Point export var x as Coord export var y as Coord
static function create(x Coord, y Coord) returns Point return Point{x: x, y: y} end 'create'
function add(other Point) returns Point return Point.create(x + other.x, y: y + other.y) end 'add'
function manhattan() returns Coord return magnitudeOf(x) + magnitudeOf(y) // sibling call: self.magnitudeOf(x) end 'manhattan'
function magnitudeOf(v Coord) returns Coord return v if v >= 0 else -v end 'magnitudeOf'end 'Point'
function main() returns ExitCode let p = Point.create(3, y: -4).add(Point.create(1, y: 1)) print("{p.manhattan()}\n") // 7 return 0end 'main'- An unmarked method is visible to its declaring directory’s subtree, like a top-level declaration; its visibility does not inherit from the type’s. Calling it from another directory is E3008.
- A local declaration inside a method (a
let/var, parameter, pattern binding or loop variable) may not reuse a field’s name (E3006). selfcannot be bound by any declaration (E2051 / E2010).
Static Methods
Section titled “Static Methods”A static function belongs to the type rather than an instance. It has no self and is called as
Type.method(). Factories are static methods.
| Instance method | Static method | |
|---|---|---|
| Declaration | function name() |
static function name() |
| Receiver | self (implicit) |
none |
| Call | value.name() |
Type.name() |
An instance method called with no receiver is E3193:
a bare call to it from a static method or a file-scope initializer, or
Type.name() with no arguments. Type.name(value, …) calls it on value.
A type declares each field and method name once. Two fields of one name, a static and an instance method of
one name, a method in the type’s body and one an extension of it adds, and a field and a method are each two
declarations of one name, and the second is E3006, in
any file and for a standard-library type too (Duplicate field 'count' in type 'Counter', Duplicate method 'add' in type 'Counter', 'total' names both a field and a method of type 'Counter'). Give the second its own
name. An interface extension’s
method is a default: a conforming type may declare its own method of that name, and its values call that
one.
Static Fields
Section titled “Static Fields”static let declares one constant per type, read as Type.name:
typealias Byte = int(0 to u8.max)
type Limits static let MAX_COUNT = 1000 static let SEPARATOR = 61 as Byteend 'Limits'
function main() returns ExitCode print("{Limits.MAX_COUNT} {Limits.SEPARATOR}\n") // 1000 61 return 0end 'main'A static member is a function or a let: var after static is a syntax error. State a function updates
belongs in a local var passed to a mutable parameter, in a field of a value the caller holds, or in a
service.
- A static field needs an initializer. Assigning to a
static letis E2013; naming a static the type does not declare is E2073. - An initializer is a value known before the program runs, read as though written inside the type’s body: a
literal, an array or map literal,
Type from [...], another constant, or a struct literal of the enclosing type. It calls nothing:static let shared = Cache.create()is E3220, and a call in the initializer of a scalar static is E2045. A closure literal’s body is not part of the initializer, since it runs only when the closure is called. A struct literal of another type is E3076. - A
static letis image data, laid down beforemain. Nothing runs to build it, whether or not the field is ever read, and an initializer that reads another static follows it in dependency order, whatever the declaration order. Initializers that depend on each other in a cycle, or one that reads its own field, are E2012. Its bytes sit in read-only memory as one copy that every function and thread reads, and it isimmutable(see Constant Data);.clone()gives a mutable copy. - A static declared in
stdlib/is kept only when reachable code reads it; one nothing reads is not emitted, and neither is its initializer. - A static field is a top-level binding whose name carries the type as a qualifier, so what its initializer
may reach follows the Top-Level Bindings rules: a
spawnin a global initializer is E3220 like any call — adefaultdeclaration starts a program-wide service beforemain. - A
letwithoutstaticin a type body is an ordinary field with a default.
Equality and Copying
Section titled “Equality and Copying”a == banda != bon two records call the type’s ownequals(other)method, which must returnbool. Two values of one generic instance (Box with Score) compare the same way, through the generic type’sequals. Declaringimplements Equatableis not required. A type with noequalscannot be compared: E3005 (cannot compare Box with Box, naming the type). Ordering (<) on records is refused the same way.a == bon two arrays of one type compares them element by element, through the element’s ownequals. It needs an element that isHashableandEquatable(E4006 otherwise).a is basks whether two names refer to the same record (see Reference Identity).- A type whose fields are all cloneable gets
clone()automatically, producing an independent deep copy (see Memory Model).
Inline Packed Records
Section titled “Inline Packed Records”A type whose whole shape fits one machine word is not a heap record: its value is the word. The
qualification is inferred — there is no syntax and no annotation for it. A type qualifies when:
- every field is
let; - every field’s declared type is an unsigned zero-based ranged alias (
int(0 to N)), abits(n)alias, orbool— resolved as the file declaring thetypesees the name; - it takes no type parameters and carries no
whereclause; - it has at least one field;
- the fields’ storage widths sum to 64 bits or fewer.
A type the program spawns is a heap record whatever its fields: it is the state its service loop owns.
A field’s storage width is the array-element ladder under Storage: bool and int(0 to 1)
take 1 bit, int(0 to 3) 2, int(0 to 15) 4, int(0 to u8.max) 8, int(0 to u16.max) 16,
int(0 to u32.max) 32, anything wider 64, and bits(n) takes its own n.
The word is laid out first field in the low bits: the first field occupies bits 0 .. w0-1, the
second w0 .. w0+w1-1, and so on. A Self{…} shifts each field into its place, range-checked at its
door exactly as a heap record’s field is, and a field read extracts it with a shift and a mask.
typealias Half = int(0 to u32.max)
type Pair export let lo as Half export let hi as Half
static function create(lo Half, hi Half) returns Pair return Pair{lo: lo, hi: hi} end 'create'end 'Pair'
function main() returns ExitCode let p = Pair.create(7, hi: 9) print("{p.lo} {p.hi} {sizeof(Pair)}\n") // 7 9 8 return 0end 'main'Because the value is a word and not a box:
sizeof(T)is 8, whatever the fields sum to.- A local, a parameter and a return are the word itself. A field of a heap record is one 8-byte slot,
and
Array with Tis a dense 8-byte element. - Nothing is allocated, retained, released or destroyed. A module-level
letof one always holds a scalar word: an initializer the compiler folds is baked in and nothing runs beforemain, while one it cannot fold runs its factory beforemainand stores the word into that slot. clone()is the identity — the copy is the same word.isandis notare refused with E3068, the diagnostic every value gets: there is no record for two names to share (see Reference Identity).==is unchanged — it calls the type’s ownequals, and a type without one is E3005.HashableandEquatableconformance is unchanged, so an inline record is aMapkey like any other.
An enum field is not admitted. A type with one stays a heap record, as does every type that fails any
part of the rule above — a var field, a signed or non-zero-based range, a type parameter, or fields
summing past 64 bits. Nothing about those types changes.
Interfaces
Section titled “Interfaces”An interface lists method signatures a type promises to provide:
typealias Tally = int(0 to u64.max)
interface Shape function area() returns Tallyend 'Shape'
type Square implements Shape export let side as Tally
static function create(side Tally) returns Self return Self{side: side} end 'create'
function area() returns Tally return side * side end 'area'end 'Square'
function describe(item Shape) returns String return "area {item.area()}"end 'describe'
function main() returns ExitCode print("{describe(Square.create(3))}\n") // area 9 return 0end 'main'- A type lists every interface it conforms to:
type Foo implements A, B. Anenumor auniondeclares conformance the same way and on the same terms — see Enum Interface Conformance. A missing or mis-typed method is E3016. - A requirement’s parameter and return types are matched as declared: a typealias is its own type, and a
typealias of a generic instance is a brand, so
make() returns IntArrayis not met bymake() returns Otherover the same instance (E3016). A call through an interface value or awhereconstraint checks each argument against the requirement’s declared type as a direct call does (E3005), and its result carries the requirement’s typealias. Selfin a requirement means the conforming type.- A requirement may be
static function; the conforming type provides it as a static method. interface Derived extends BaseinheritsBase’s requirements; a type implementingDerivedprovides both, and satisfies parameters typedBase.- A requirement is read-only and never waits or yields unless it declares otherwise:
mutable selfwhere a conformer writes the receiver,mutableorimmutableon a parameter,returns isolatedorreturns immutableon its result (see Capabilities at Function Types and Requirements). A conformer that does more is E3210.
Interface-typed parameters, returns and fields. An interface can be used as a type, as describe
does above: a parameter typed Shape accepts any conforming type, enum and union conformers
included, a function may return an interface,
and a field may hold one. A function that returns an interface may return match … with a different
conformer in each gives arm. A struct literal (Self{shape: Square.create(3)}) or an assignment
(self.shape = Strip.create(5)) stores a conforming value straight into such a field, exactly as passing it
to a Shape parameter would; assigning a different conformer releases the one the field held. A value that
does not conform is E3005, and a conformer whose associated-type binding contradicts the field’s
with clause is E3127. Where the compiler can see the concrete type, calls dispatch statically;
otherwise they dispatch through a witness table at run time. A record holding such a field is cloneable
on the terms Explicit Cloning states.
The standard interfaces (declared in the standard library):
| Interface | Requirement |
|---|---|
Equatable |
function equals(other Self) returns bool |
Hashable |
function hash() returns HashValue |
Comparable |
function compare(other Self) returns Ordering |
Cloneable |
function clone() returns Self |
Stringable |
function toString() returns String |
FormattedStringable |
function toString(format String) returns String |
Error |
none — a marker for thrown values |
Iterable uses Element, Iter |
function createIterator() returns Iter throws IterationError |
Parsable |
static function fromString(input String) returns Self throws Error |
A type used in string interpolation needs a toString() method; one used with a format specifier
({value:spec}) needs toString(format String). A type declares toString once, so it implements
Stringable or FormattedStringable.
Hashable and Hasher
Section titled “Hashable and Hasher”A type used as a Map key or Set element implements Hashable and Equatable:
typealias Score = int(i64.min to i64.max)
type Cell implements Hashable, Equatable export let row as Score export let col as Score
static function create(row Score, col Score) returns Self return Self{row: row, col: col} end 'create'
function hash() returns HashValue let hasher = Hasher.create() hasher.combine(row.hash() as HashDigest) hasher.combine(col.hash() as HashDigest) return hasher.finalize() end 'hash'
function equals(other Self) returns bool return row == other.row and col == other.col end 'equals'end 'Cell'
typealias CellNames = Map with (Cell, String)
function main() returns ExitCode let names = CellNames.create() names.upsert(Cell.create(1, col: 2), value: "b1") let found = try names.get(Cell.create(1, col: 2)) otherwise "missing" print("{found}\n") // b1 return 0end 'main'Payload-free enums are Hashable and Equatable automatically; unions are not (see
Unions).
String.hash(), Character.hash() and Array.hash() are folds of the standard library’s
Hasher, and a type’s own hash() folds its fields with one, as Cell’s does.
Every process draws its own seed at startup, so a hash value is a property of one process: it differs between
runs, and a Map’s or Set’s iteration order with it. A digest the program keeps is a
KeyedHasher fold from a HashSeed of its own, and a value that must be
the same in every process is a SHA-256 digest (sha256).
function main() returns ExitCode let seed = HashSeed.random() let a = KeyedHasher.create(seed) a.combineBytes("ab".toByteArray()) a.combineBytes("c".toByteArray())
let b = KeyedHasher.create(seed) b.combineBytes("abc".toByteArray())
let again = KeyedHasher.combinedBytes(KeyedHasher.combinedBytes(KeyedHasher.empty(seed), bytes: "ab".toByteArray()), bytes: "c".toByteArray()) print("{a.finalize() == b.finalize()} {a.finalize() == again}\n") // false true return 0end 'main'Each step’s state seeds the next, so the steps are delimited: "ab" then "c" reaches a digest apart from
"abc". KeyedHasher.empty(seed) and KeyedHasher.combinedBytes(state, bytes:) are the same fold as pure
functions.
Parsable
Section titled “Parsable”Parsable is the interface for types that parse themselves from text. int, float and bool provide
fromString, which throws ParseError.invalidFormat:
function main() returns ExitCode let n = try int.fromString("42") otherwise 0 let f = try float.fromString("2.5") otherwise 0.0 print("{n} {f}\n") // 42 2.5 return 0end 'main'A type conforms with a static fromString that throws an error type:
typealias Cents = int(0 to i64.max)
enum MoneyError implements Error negativeend 'MoneyError'
type Money implements Parsable export let cents as Cents
static function fromString(input String) returns Self throws MoneyError let value = try int.fromString(input) otherwise throw MoneyError.negative if value < 0 'negative' throw MoneyError.negative end 'negative'
return Self{cents: value as Cents} end 'fromString'end 'Money'A fromString that does not throw, or throws a type that is not an error, is E3016.
Initializing From Literals
Section titled “Initializing From Literals”A type can be written from a string or character literal with Type from "…", which calls its
static function init(value String) returns Self. The type must declare the conformance:
| Interface | Literal | Requirement |
|---|---|---|
InitableFromStringLiteral |
T from "text" |
static function init(value String) returns Self |
InitableFromCharLiteral |
T from 'c' |
static function init(value Character) returns Self |
type Wrapper implements InitableFromStringLiteral export let value as String
static function init(value String) returns Wrapper return Wrapper{value: value} end 'init'end 'Wrapper'
let greeting = Wrapper from "hello"
function main() returns ExitCode print("{greeting.value}\n") return 0end 'main'Type from "…" is also allowed as a module-level initializer. Using it on a type without the conformance is
E3005 (Type 'Wrapper' does not conform to InitableFromStringLiteral).
The standard collections accept bracketed literals: a plain [1, 2, 3] is an Array, ["a": 1] is a
Map, and Array, Set, List and FixedArray aliases take Alias from [ ... ], for example
CharSet from ['a', 'e']; the alias states the element type, and a FixedArray alias’s literal must write
exactly as many elements as the alias holds (a runtime-sized alias holds
as many as its literal writes). When that element is itself an array alias, each element is a
value of it: another Alias from [ ... ], a bare [ ... ] that takes its element type from the alias, or
a local of the inner alias — Rows from [Ints from [1, 2], [3], row] over typealias Rows = Array with Ints. Set and List also take any Array value, under the bare name or an alias: Set from names builds
a set of names’ elements, and an alias head takes an Array of exactly its element; any other source is E3005.
An Array or FixedArray alias head takes an array literal. A type that declares implements InitableFromArrayLiteral with Element takes Type from [ ... ], which is Type.init(value ElementArray) over the literal:
typealias Digit = int(0 to 9)typealias DigitArray = Array with Digittypealias Number = int(0 to i64.max)
type Digits implements InitableFromArrayLiteral with Digit export var value as Number
static function init(digits DigitArray) returns Self var total = 0 as Number
for d in digits 'each' total = total * 10 + d as Number end 'each'
return Self{value: total} end 'init'end 'Digits'
function main() returns ExitCode let n = Digits from [4, 0, 7] print("{n.value}\n") return 0end 'main'Generic Types
Section titled “Generic Types”uses declares type parameters. A generic type is instantiated with with, through a typealias:
typealias Integer = int(i64.min to i64.max)
type Box uses T export var item as T
static function create(item T) returns Self return Self{item: item} end 'create'
function get() returns T return item end 'get'end 'Box'
typealias IntBox = Box with Integer
function main() returns ExitCode let b = IntBox.create(42) let inferred = Box.create("hi") // Box with String, from the argument print("{b.get()} {inferred.get()}\n") // 42 hi return 0end 'main'- Several parameters:
type Pair uses A, B, instantiatedPair with (Integer, String). - A static called on the bare generic name infers the arguments from its parameters: a parameter written
at a type parameter, or at an instance over one (
Array with T, or the generic itself). A call whose result is written over a parameter that no argument fixes (Holder.make()declaredreturns T) has no type and is E3162; inside the generic’s own body the enclosing instance types it. - One compiled body serves every instantiation. A method learns how its type arguments are laid out and
owned from the instance it is called on, and that includes instances the body composes over its own
parameters —
Array with (Pair with T),Box with (T, Integer). A closure uses what the function it is written in received. - A
static functionlearns it from the instance its call names: the typealias it is called through (IntBox.create(42)), the instance its arguments fix on the bare generic name, or, called from a method of the same generic, what that method received. This covers every static, whatever it returns, that needs its instance’s layout, itscountof(Self)or the tables of awhereconstraint, itself or through what it calls. A call that names no instance, from a function holding none to hand on, is E3162 when the static needs the layout (below), and E2015 when it needs the count or the tables. - A generic type whose methods reach an instance of itself through an ever-growing type argument
(
Node with (Pair with T)insideNode) has no finite set of instances, and is E2015. So is a method that widens such an instance to an interface (Gen with Treturned as aSinkinsidetype Wrap uses T) when the instance’s methods reach the enclosing type again: give the type argument a concrete type, or pass the value it wraps as a type parameter of its own. - A concrete instance widened to an interface releases and clones through its own witness table whenever its
type arguments change how it is released; a widening over the enclosing type’s own parameter reads that table
from the layout descriptor the enclosing instantiation hands down, so
Wrap with Stringreleases aGen with StringandWrap with TallyaGen with Tally. - Wrong argument count is E2056; a bare
intargument is E2061; a type argument to a non-generic type is E2055. Awithlist names at most 64 type arguments; a longer one is E2015. - A
floattype argument, bare or through a ranged float alias such asFullRangeFloat, is E2062 (Box with FullRangeFloat). The element of anArrayor aFixedArrayis the exception, because it is stored inline in a buffer:Array with FullRangeFloatandFixedArray with 2 FullRangeFloatcompile, and there a barefloatis E2061. - A container element at an interface type (
Array with Named,Box with Named) is E2015: an element slot is one machine word, and a value at an interface type is two (the value and its witness table). It is reported once, where the instance is written, however many uses the typealias that names it has. An interface base’s arguments bind its associated types instead; one bound to an interface is E2015 only where a requirement takes that associated type as a parameter. - A base may be written through the directory that declares it:
typealias Good = lib.Pair with (Integer, Integer)instantiates the generic typelib/exports, andArray with (lib.Pair with (Integer, Integer))nests it as an argument. The qualifier names that directory’s type whatever the bare name means in the reading file, so two directories that each declare aPairare told apart by it, and each alias takes the type parameters of the one it names. A type the directory does not export is E3008 at the base. - A bare base is the declaration the bare name resolves to in the reading file (see
Bare Names and Ambiguity). Where that declaration is a
typealias— the file’s own, a sibling file’s in its directory, or the project root’s — the base is an alias, which has no type parameters, and thewithis E2055 (Type 'Pair' has no associated types) even when another directory exports a generic type of that name. Write the qualified base (a.Pair with …) to name that type.
Inside type Outer uses T, another generic type written without with arguments binds by parameter NAME:
Inner uses T means Inner with T. A base whose parameters the scope does not declare (Box uses Element)
binds nothing and stays the bare base, and a call on it — static (Box.create(first)) or through a receiver
of that type — may neither hand a slot written over one of its type parameters (Element, or
Array with Element) a value typed at Outer’s parameters nor call a method that needs a layout descriptor
(E3162). Name the instance with a
typealias instead: typealias Inner = Box with T. Outside a generic type body, a layout-needing call on a
bare generic base is E3162 as well unless the calling function carries a layout descriptor of its own — a
static whose arguments do not fix every one of the base’s parameters (Holder.create() in main), or a
method called through a receiver of the bare base type.
Where Clauses
Section titled “Where Clauses”where constrains a type parameter to conform to interfaces, which lets the body call their methods:
typealias Code = int(i64.min to i64.max)
interface Digest function digest() returns Codeend 'Digest'
type Tagged uses T where T is Digest export var item as T
export static function create(item T) returns Self return Self{item: item} end 'create'
function itemDigest() returns Code return item.digest() end 'itemDigest'end 'Tagged'- Several interfaces on one parameter:
where T is Hashable and Equatable. - Several parameters:
where K is Hashable, V is Cloneable. - An instantiation whose argument does not conform is E3017 (
Type 'X' does not satisfy constraint 'Digest' required by type parameter 'T' of 'Tagged'). - A constraint can bind an associated type:
where S is Cursor with E. - In the body,
T.memberreaches a member through the parameter, whatever top-level type or alias shares its spelling. Astaticrequirement dispatches on a concrete type, so calling one throughT(T.make()) is E3116, and naming one without its call is E2078. An instance requirement called throughT(T.id()) and an undeclared member are E2073: call an instance requirement on a value of typeT.
Generic Functions
Section titled “Generic Functions”A free function or a static method declares type parameters with uses after its parameter list, and
constrains them with where at the end of the declaration line:
typealias Score = int(0 to 100)
function larger(a T, b T) uses T returns T where T is Comparable if a > b 'first' return a end 'first'
return bend 'larger'
function main() returns ExitCode print("{larger(30 as Score, b: 70)} {larger("pear", b: "apple")}\n") // 70 pear return 0end 'main'A call infers T from the arguments whose parameters are declared T:
- Arguments of one alias give that alias. An argument with no alias (a literal, arithmetic over literals)
adopts the other arguments’ alias. Two different aliases give their nearest common ancestor under
implements, and two with none are E3180. - A type parameter binds a number,
String,bool,Character, a typealias, a record or an enum; any other argument is E3181. A type parameter no parameter is declared with is E3179. - An inferred type that does not conform to a
whereinterface is E3017.
Each distinct inferred type compiles its own copy of the function in the declaring file, and the body is
checked against that type. Every integer and float type, every alias of one, String, bool and
Character conform to Equatable and Comparable (see Primitive Conformances),
and a record that implements Comparable is ordered by <, >, <= and >= through its compare.
A copy may call its argument type’s where requirements — compare, equals, any method of the
constraining interface, and a method an extension of that interface declares — whatever their visibility,
because the caller granted the conformance by passing the type. The grant reaches a closure written inside
the copy too. The calls the language makes on the author’s behalf over a value of a type parameter —
interpolation’s conversion to text ("{a}", "{a:q}"), a record’s == and <, and the iteration a for
performs — are judged for the caller that instantiated the copy, so a generic declared in another file, such
as Expect.equal, accepts the caller’s unexported type. Every other member of the type, and a match,
accessor or .rawValue the body writes over a value of it, needs ordinary visibility from the declaring
file. A generic
function is itself visible like any function: an unmarked one called from another directory is E3008.
A generic function and a non-generic one of the same name in one directory are two declarations of one name (E3006); name each its own.
A generic body is checked against the bound of T only, so it never reassigns a parameter declared T,
marked mutable or not (E2013, 'item' is a generic parameter and cannot be reassigned; return the new value); see Parameter Passing.
Associated Types
Section titled “Associated Types”An interface can declare associated types with uses; a conforming type binds them with with:
typealias Slot = int(0 to u64.max)typealias Score = int(i64.min to i64.max)
interface Container uses Element function at(index Slot) returns Elementend 'Container'
type Scores implements Container with Score export var base as Score
static function create(base Score) returns Self return Self{base: base} end 'create'
function at(index Slot) returns Score return base + (index as Score) end 'at'end 'Scores'Several associated types bind positionally: implements Iterable with (Entry, MapIterator). A missing
binding or a method whose types disagree with the binding is E3016.
Parameterized Existentials
Section titled “Parameterized Existentials”An alias over an interface with its associated types bound — typealias IntegerSeq = Seq with Integer —
is a value type that holds any conforming value and dispatches at run time:
typealias Integer = int(i64.min to i64.max)
interface Seq uses Element function current() returns Element function advance(mutable self) throws IterationErrorend 'Seq'
type Upto implements Seq with Integer var pos as Integer let limit as Integer
static function create(limit Integer) returns Self return Self{pos: 1, limit: limit} end 'create'
function current() returns Integer return self.pos end 'current'
export function advance() throws IterationError if self.pos >= self.limit 'atTheLast' throw IterationError.exhausted end 'atTheLast'
self.pos = self.pos + 1 end 'advance'end 'Upto'
typealias IntegerSeq = Seq with Integer
function total(source IntegerSeq) returns Integer var sum = 0 as Integer for item in source 'walk' sum = sum + item end 'walk'
return sumend 'total'
function main() returns ExitCode print("{total(Upto.create(4))}\n") // 10 return 0end 'main'The with arguments are a claim checked against every conformer that reaches the existential; a conformer
binding the associated type differently is E3125.
The Self Type
Section titled “The Self Type”Inside a type, interface or extension body, Self names the enclosing type. It is legal in signatures
(returns Self), in literals (Self{...}), and as the base of a member expression: Self.create(…),
Self.someCase, Self.MAX mean exactly what the type’s own name would. Self outside a type declaration
is E2015.
Inside type Box uses T, Self or Box written as a type argument is the instance over the type’s own
parameters, Box with T. A member typealias Peers = Array with Self is therefore one type per
instantiation: an IntBox’s Peers is an Array with IntBox and is E3005 where a FlagBox’s is
expected, and an element read out of it is a Self.
Extension Targets
Section titled “Extension Targets”extension Name names a declared type, enum, union or interface, or a primitive. A name that
declares none of these is refused: an unknown name is
E3011, and a typealias is E2015, to be replaced
by the declaration it names. An extension of an enum or a union adds methods and may declare
implements; see Enum Methods.
Interface Extensions
Section titled “Interface Extensions”extension InterfaceName adds methods to every type that conforms to the interface, with one
implementation:
typealias Tally = int(0 to u64.max)
interface Shape function area() returns Tallyend 'Shape'
extension Shape function doubledArea() returns Tally return self.area() * 2 end 'doubledArea'end 'Shape'selfis the conforming value; the extension may call any requirement of the interface, including one a conformer implements with an unexported function.- Associated types resolve to each conformer’s binding. A member may take or return an associated type a conformer binds to an interface: for that conformer the parameter or result is held at the interface, as in a plain function declared with it.
- A conformer’s binding of an associated type to an interface is E2015 where an extension of the
interface holds that associated type in a one-word slot. A container element (
typealias ItemArray = Array with Item) is E2015 at the conformer’s binding (type Impl implements Source with Named); a function type’s parameter or result and a tuple element are E2015 at the extension’s alias. Each is reported once, however many bodies use the alias. The standard library’s extensions count:extension IterableholdsElementas a container element (ElementArray) and as a function type’s parameter (ElementTransform,ElementPredicate), so a conformer that bindsElementto an interface is E2015 at that binding and at the library’s alias. Bind a concrete type that implements the interface. - Extensions of a parent interface apply to types conforming to a derived one.
- An extension’s member is a default. A conforming type that declares the member keeps its own, and so does
a conforming type the compiler supplies the member to, which for a
typeis itsclone. The compiler’s member is the one every call reaches, whatever layer declares the extension and whatever layer declares the type. A conformer the compiler supplies nothing to takes the default. To give atypeacloneof its own, declare it in the type’s body or in anextensionof the type. Anenumor auniontakes no default from an interface extension, so thehashandequalsof a payload-free enum are always the compiler’s.
Conditional Extensions
Section titled “Conditional Extensions”A where clause restricts an extension to conformers whose associated types satisfy it. With the Seq
interface above:
extension Seq where Element is Equatable function has(target Element) returns bool for item in self 'loop' if item == target 'found' return true end 'found' end 'loop'
return false end 'has'end 'Seq'Upto.create(4).has(3) is available because Integer is Equatable. Several constraints on one
parameter join with and: where Key is Hashable and Equatable.
The method belongs to the conformers that satisfy the clause; calling it on any other is E4006, which names the unmet constraint. A conformer that declares its own method of that name calls its own, whether its binding satisfies the clause or not.
Conditional Interface Conformance
Section titled “Conditional Interface Conformance”An extension can also add a conformance under a condition:
extension Array implements Hashable, Equatable where Element is Hashable and Equatable function hash() returns HashValue // ... end 'hash'
function equals(other Self) returns bool // ... end 'equals'end 'Array'The constraint is checked wherever an instantiation is created: an explicit typealias
(typealias IntArr = Array with Integer), a bracketed literal ([1, 2], ["a": 1]), or a static factory
call on the bare generic name (Box.create("hi")). If Integer is Hashable and Equatable, Array with Integer is too and can be a Map key; if not, an instantiation used where the conformance is required is
E3017.
Extensions Over Primitives
Section titled “Extensions Over Primitives”extension int, extension float and extension bool add methods to a primitive, and may declare
conformances. Inside, self is the value and Self the primitive:
typealias Integer = int(i64.min to i64.max)
extension int function doubled() returns Integer return self * 2 end 'doubled'end 'int'
function main() returns ExitCode let n = 21 print("{n.doubled()}\n") // 42 return 0end 'main'A hash, equals, compare, toString, clone or fromString the primitive already has is
E3006 at its name in such an extension; a member it
lacks, hash for bool say, is yours to declare. An extension body cannot declare stored var/let members
(E2015).
Tuples
Section titled “Tuples”A tuple is a fixed-size, ordered group of values that may have different types. Tuples are written with parentheses, both as values and as types.
typealias Amount = int(i64.min to i64.max)
function sum(t (Amount, Amount)) returns Amount return t.0 + t.1end 'sum'
function makePair(a Amount, b Amount) returns (Amount, Amount) return (a, b)end 'makePair'
function main() returns ExitCode var t = makePair(0, b: 0) t.0 = 20 t.1 = 22 print("{sum(t)}\n") // 42
let mixed = (42, "hello") print("{mixed.0} {mixed.1}\n") // 42 hello
let (x, y) = makePair(10, b: 32) print("{x} {y}\n") // 10 32 return 0end 'main'Literals and Element Access
Section titled “Literals and Element Access”(a, b)builds a tuple; a tuple has at least two elements.(expr)is just a parenthesized expression.- Elements are read and written by position:
t.0,t.1,t.2. - A tuple type in a signature is a parenthesized type list:
(Amount, String). It can also be named:typealias Span = (Amount, Amount). - A tuple literal written where a tuple type is declared — a parameter, a field, a variable, a return, an
element of a typed array literal, a
matchor ternary arm, or an element of an enclosing tuple — takes that type’s element types, so a closure literal as an element takes the declared function type. - Each element keeps its own alias, so a tuple type is its element aliases in order:
(Tally, Tally)and(Score, Score)are two types even over one range, an element is checked against its alias’s range, and an element of an unsigned alias stays unsigned through a parameter, a nested tuple or a destructuring.
Destructuring Declarations
Section titled “Destructuring Declarations”let (a, b) = expr and var (a, b) = expr bind each element to a new name. _ discards an element:
let (first, _) = makePair(1, b: 2)Tuple Assignment
Section titled “Tuple Assignment”A tuple pattern on the left of = assigns to existing vars, and may declare new names in the same pattern:
var p = 0 as Amountvar q = 0 as Amount(p, q) = makePair(1, b: 2) // both existing(p, let r) = makePair(3, b: 4) // p existing, r newly declared(q, _) = makePair(5, b: 6) // discard the second element- A name without
var/letmust already be avar; alettarget is E2013. - The number of names must match the element count (E3005).
- Discarding every element of a pure function’s result is E3064, a lint rule.
Destructuring in For Loops
Section titled “Destructuring in For Loops”A for loop over tuples can destructure each one — a Map yields (key, value) pairs:
let ages = ["ada": 36, "alan": 41]var total = 0 as Countfor (_, age) in ages 'loop' total = total + ageend 'loop'Tuple Casts
Section titled “Tuple Casts”t as T between two tuple types converts element by element: each element whose type differs goes through
the cast its own value would take, with that cast’s refusals and range checks, and a nested tuple element
converts the same way. So (1, 2, big) as MyTriple is E3005 when the constant big is outside an
element’s range, a value computed at run time is checked there and panics when it is outside, and
(Color, Wide) as (Wide, Wide) is E3009, as Color.green as Wide is. An unneeded cast (E3010) is
judged once, for the cast as written.
The result is a new tuple whenever any element type differs, even between aliases of one range, and the source stays as it was, so a write through either name reaches only that name’s tuple:
typealias Small = int(0 to 100)typealias Big = int(0 to 100000)typealias SmallPair = (Small, Small)typealias BigPair = (Big, Big)
function main() returns ExitCode var wide = (1 as Big, 2 as Big) let narrow = wide as SmallPair wide.0 = 5000 print("{narrow.0}\n") // 1
let small = (1 as Small, 2 as Small) var widened = small as BigPair widened.1 = 70000 print("{small.1}\n") // 2 return 0end 'main'- A cast whose elements each denote the same type and capability, such as two brands of one instance, shares the record.
- A cast written on a tuple literal (
(a, b) as T) converts the literal’s own element values, and retypes the literal when no element converts. - The two tuples have the same number of elements:
(a, b) as (A, B, C)is E3009 (a tuple converts only to a tuple with the same number of elements). - Each element keeps its capability:
(Box, Wide) as (immutable Box, Wide)and the reverse are E3226. Build the tuple from a frozen element (freeze x.clone()), or from aclone()for an unmarked element.immutableon an element of a value type means the type itself, so(immutable P, W)is the type(P, W)for a value-like recordP.
Memory Semantics
Section titled “Memory Semantics”A tuple is a reference-counted record, like a type. Assigning a tuple shares it, and a cast between tuple
types whose elements differ builds a new one (see Tuple Casts); a tuple holding managed
values (strings, records) releases them when the last reference goes away. A returned pair is the one
exception: a two-element tuple of register-wide elements (a whole-word integer or a bool), returned by a
function that does not throw and whose address is not taken, comes back in the two return registers and
allocates nothing. Callers may be mixed: a call site that reads the two halves, or returns the pair from
another such function, takes the registers as they are, and a call site that needs the record (it stores
the tuple, passes it on as a value, or returns it from a function that throws) builds one from them.