Data types
Data are values: nominal records and enums, unions and structural shapes for flexibility, and no null.
type User = { id: Uuid name: String email: Email? // Option<Email> roles: Role[]}
enum Role = Admin | Editor | Reader(since: Date)
type Order = "asc" | "desc" // union of literalstype Id = Int | Uuid // union of types
type Tree = { value: Int, children: Tree[] } // recursive: automatic indirectiontype Node = { value: Int, next: Node? } // recursive through an optional-
Primitives.
Int(64 bits, also namedInt64),Int8,Int16,Int32,UInt8…UInt64,Float(64 bits) andFloat32,Bool,Char,String(UTF-8),Bytes. -
Checked arithmetic. An overflow of
+,-,*, of negation or ofMIN / -1stops the program (panic, 8.1), like a division by zero: never a silently wrong result./truncates toward zero and%takes the sign of the dividend;MIN % -1is 0, the exact remainder.<<and>>require a shift between 0 and 63, and>>preserves the sign. A literal that starts with0stays decimal; hexadecimal is written0x, octal0oand binary0b,0o644,0b1010_0001, and a digit outside the base is an error. -
Sized integers. Every integer has its arithmetic checked, like Int:
200 + 100on a UInt8 stops the program, as does0 - 1on a UInt32. Nothing mixes two integer types; a literal takes the expected type, or that of the other operand, and must fit in it (val n: Int16 = 300,b + 1). Conversions are written out:n.toInt16()stops if the value does not fit,n.wrapToUInt8()keeps the low bits,Int16.from(n)returns anInt16?, n being an integer of any type, andInt.from(u)anInt?, and a widening,b.toInt(), cannot fail. Bitwise operations go through methods, the set of operators remaining closed (section 4):and,or,xor,not,countOnes,leadingZeros,trailingZeros,rotateLeft,rotateRight(by a number of steps counted by an Int, modulo the width), andwrappingAdd,wrappingSub,wrappingMulcompute modulo 2^n.<<and>>require a shift smaller than the width of the type, counted by an integer of any type, the result keeping the type of the operand:x << nshifts a UInt8 by n steps, n an Int;>>keeps the sign of a signed integer, and shifts zeros into a UInt. -
Floating-point numbers.
FloatandFloat32follow IEEE 754:1.0 / 0.0is infinity and0.0 / 0.0NaN, without panic, andx.isNaN(),x.isFinite()test for them. A literal is written1.5,2e10or1.5e-3; it is aFloat, or aFloat32where the context expects one. Nothing mixes integers and floating-point numbers:1 + 2.5is rejected, and the conversion is written out,n.toFloat(), to the nearest, orx.toInt(), toward zero, which stops the program if x is NaN or outside an Int;round,floor,ceilandtruncstay Floats;roundgoes to the nearest integer, a tie away from zero:2.5.round()is3.0,(-2.5).round()is-3.0.==and<compare as the standard does, NaN being equal to nothing: lacking a total order, Float adopts neither Eq, nor Ord, nor Hash, and is not a Map key;a.totalCompare(b)gives IEEE’s total order for a sort."${x}"writes the shortest form that reads back,0.1,2.0,1e21, ands.parseFloat()reads a number. A Float32 has the same methods as a Float, computed on 32 bits. Two literals of an operation take the expected type:val inf: Float32 = 1.0 / 0.0,val n: Int16 = 1 + 2. -
Formatting a number.
x.format(precision: 2)writes x with two digits after the decimal point, rounded to the nearest,3.14. The rounding applies to the exact binary value of x, and a tie goes to the even digit, likeprintf:2.5.format(precision: 0)gives2,0.125.format(precision: 2)gives0.12, and2.675.format(precision: 2)gives2.67, 2.675 being 2.67499… in binary; without precision, its shortest form.n.format(width: 5, fill: '0', radix: 16)writes an integer of any size in a base from 2 to 36, with lowercase digits. Both are padded on the left with fill up to width characters, zeros coming after the sign,-0042. The rest goes through named arguments rather than through a mini-language in the interpolation:"${x.format(precision: 2)}". A Float has its mathematical functions as methods:sqrt,pow,exp,ln,sin,atan2,abs,min,max… -
Records. Nominal, constructed by
User{id, name, …}. The brace is attached to the name, as in Go:Name{always opens a record, a brace preceded by a space never does. A modified copy is obtained byu.with(name: "Ada"). A field of function type is called like a method,p.apply(x); a method of the same name is rejected, since it would make the call ambiguous. A field may have a default value,{ name: String, retries: Int = 3, tags: String[] = [] }, evaluated at each construction that omits it,Config{name: "a"}. -
Characters and bytes.
Charis a Unicode code point,'é'or'\u{85}';Char.from(n)returns aChar?.for ch in siterates over the characters of a string, an invalid sequence yielding U+FFFD.Byteshas the shape of aUInt8[](index,len,push,for) and its own methods:Bytes.filled(n, with: 0),count(b),find(needle),indexOf(b, from:),lastIndexOf(b, before:),utf8Chunks(), anduint32BE(at),uint32LE(at)and their 16- and 64-bit siblings, which read an integer with a single index check, andsetUint64LE(at, v), which writes one likewise; the array methods (get,countWhile,map…) apply to it too.s.bytes()views a string as bytes, without copying, and a string is passed as is whereBytesare expected;b.utf8()returns the string of those bytes if they are UTF-8. A byte is tested like an ASCII character:isAsciiDigit,isAsciiAlphabetic,isAsciiAlphanumeric, which Char has too;b'a'is the byte of an ASCII character,b == b'"',b'0'..=b'9'in a pattern.s.trim(),trimStart()andtrimEnd()remove Unicode whitespace;find,contains,stripPrefix,stripSuffix,repeat(n), andtoUpper,toLower, which change only ASCII letters. An integer literal where aUInt8is expected is one, if it is between 0 and 255:sep: 0,b + 1. -
Strings and arrays.
Stringis a sequence of UTF-8 bytes:s.byteLen()counts bytes, and==,<compare byte by byte. An array,Array<T>, is writtenT[]: elements contiguous in memory, growing at the end. Its literal is[a, b]; an empty array takes the type the context expects,val xs: Int[] = [].xs[i]checks its index and stops the program if it is out of the array, unless the compiler proves it in range:xs[i]infor i in 0..xs.len(),xs[x + 1]underif x >= 0 && x + 1 < xs.len(), as long as the body neither resizes xs nor assigns the index. The suffix composes with?, left to right:Int?[]is an array of optionals,Int[]?an optional array,(any Shape)[]an array of existential values.T[](capacity: n)reserves room for n elements,T[].filled(n, with: v)gives n times v (no zero value is implicit),xs.reserve(n)andxs.capacity()set and read the room.xs + ysis a new array, the elements of xs then those of ys, andxs += ysappends them in place (concatandextend, bound by@operatorin core);xs.contains(x)andxs.indexOf(x)requireT: Eq.xs.swap(i, j)swaps two elements,xs.truncate(n)removes those from index n to the end (n does not exceed the length),xs.clear()removes them all: the array keeps its room, to be refilled without reallocating. On an array of resources,truncateandclearare rejected, since the removed elements would not be disposed of:pop()orfor using x in xs.drain()hand them back.len,isEmpty,pushandbyteLenare language methods: on an array or a string, they take precedence over a function of the same name. -
String literals. Two independent choices write a string. The delimiter decides its lines:
"…"holds on one line,"""opens a block over several. The prefix decides how its text is read: without one, escapes (\n,\t,\u{e9}) and interpolations,"${x}"; with one,sql"…", the text is raw and its interpolations go to the prefix’s meta fn (5.4). A block’s"""ends its line, and its closing"""stands alone on its own: the closing line’s indentation is taken off every line, so that the text moves with the code, and the newlines after the opening and before the closing are not part of it. A line indented less than the closing is an error, unless it is blank: a blank line is empty. In a plain block, a\ending a line joins it to the next, without a newline.\${writes a${in a plain string,$${in a prefixed one, which has no escapes. An interpolation costs nothing to a literal without one, which stays a constant.fn usage(levels: String[]): String = """usage: logcount [-v] <file>Counts the lines of a log by level: ${levels.join(", ")}.""" -
Fixed-size arrays.
T[n]stores its n elements in the value itself, without a heap block:UInt8[16], orInt[3][3], threeInt[3]. n is computed at compile time: an integer literal, an integermeta valconstant,UInt8[Page], or an expression of these values,UInt8[2 * Page]; there is no generic size. A fixed array is born from a literal of exactly n elements,val id: UInt8[4] = [1, 2, 3, 4], or fromT[n].filled(with: v): no zero value is implicit.a[i]checks its index,a[i] = vwrites in place in avar,a.len()is a constant,for x in aiterates over its elements. It is copied like a record, element by element, and adopts Eq, Hash, Ord and Show when its elements adopt them: a record that contains one derives#Eq #Hash. It does not grow and has no view:a.toArray()makes aT[]of it, by a copy, and nothing converts implicitly from one to the other. Its elements are arbitrary values, resources included, disposed of from last to first;filleddoes not copy one. Since it allocates nothing, it suits@assert(noalloc)code. -
Map literals.
["ada": 31, "tom": 27]is a map, and[:]the empty map. The expected type chooses it, if it adoptsMapLiteral<K, V>(core):val m: Map<String, Int> = [:], or a map of the program. Without an expected type, it is aMap<K, V>, K and V given by the entries, and the file must importweaver.collections.Map. The map is created with room for its entries (fromLiteral(capacity:)), then receives them in source order (addLiteral). Two equal constant keys are a compile error; two equal computed keys stop the program. -
Maps.
weaver.collectionshas two maps.Map<K, V>is an open-addressing map, with no specified iteration order.OrderedMap<K, V>keeps insertion order, like a JSON object: storing a value under a present key replaces it in its place, removing it then putting it back stores it at the end. Both are iterated byfor (k, v) in m(3.2), and adopt MapLiteral:val o: OrderedMap<String, Int> = ["b": 1, "a": 2].Set<T>is iterated byfor x in sand adopts SetLiteral:val s: Set<String> = ["a", "b"]. A map also holds resources (7.1):insertreceives them and returns the one it replaces, which the caller adopts,using old = m.insert(k, v),removereturns its own, andfor (k, v) in mborrows them. -
Mutability. It applies to the binding, not to the type:
valis immutable,varis mutable, fields included. Avalwhose value or type ismut,val xs = mut [1, 2],val p: mut Point = …, has a content modified in place,xs.push(3),p.x = 5,grow(&xs), but is not reassigned (memory-model.md); a scalar, having no content apart from its value, is never lent asmut, except toreplace, which reassigns it (6.2).wv migratewritesmutwhere avar’s content is modified in place, andvalwhere it is never reassigned. -
Shadowing. A variable may shadow one from an enclosing block (
val x = …in an inner block), never another one of the same block. -
Enums. Algebraic types with payload. A variant is constructed the way a function is called,
Reader(since: d)orReader(d). Its name alone suffices; when two enums of the module use it, it must be qualified,Role.Admin. Where the type is known,.equaldesignates its variant without naming it:return .equal,o != .equal, and likewise a variant that carries values,area(.Circle(r: 2)),val s: Shape? = .Rect(w: 3, h: 4). Two values of an enum without payload are compared by==.matchis exhaustive and checked at compile time: an error gives a missing case, and an arm that no value can reach triggers a warning. -
Recursive types. A type contains itself through an array, which stores its elements on the heap, or through an enum, an optional included:
type Node = { value: Int, next: Node? },enum Expr = Num(n: Int) | Add(l: Expr, r: Expr). The indirection is automatic: a variant field that closes the cycle is stored in a counted heap box, a single one per cycle. A cycle that goes through an optional places it in its Some, so thatNonecosts nothing: inenum List = Cons(head: Int, tail: List?),Cons(head: 1, tail: None)allocates nothing. Between two enums of the program,enum Even = Zero | SuccE(o: Odd)andenum Odd = SuccO(e: Even), the compiler chooses which one breaks the cycle. A copy shares its boxes, a write first copies a shared box (6.1): the value remains a value. Freeing a list of a million nodes does not deepen the stack. A type that contains itself without an enum or an array,type R = { r: R }or{ p: (R, Int) }, has no finite size: it is an error. -
Unions and aliases.
Int | Uuidis a union of types, with the rules of 8.1: its members have neither order nor duplicates, a pattern matches a member by its name,Int(n), and a value of a member enters it where it is expected, on one side of==included. A union automatically adopts a contract that each of its members adopts, if each method to write receives self, read-only ormut, and receives no other Self than theotherof==; a method that returns Self returns the value of the active member, which enters the union,u.normalized(), whereas a Self received as a parameter could be another member; the method is dispatched to the active member, which anmut selfmethod modifies in place: a union ofWriters is aWriter. Thus"${id}",a == b, true for the same member with equal values, andid.hash(), which mixes the member’s hash with its index: a union can serve as a Map key. Ord is not one of them, two members having no order.type Id = Int | Uuidnames a type without creating one: an alias, interchangeable with what it names, for any type (type Ids = Id[],type Handler = (Request) => Response); it carries neither annotation norimpl, which go to the named record or enum. An alias has its parameters:type Pairs<T> = (T, T)[],type StrMap<V> = Map<String, V>, andPairs<Int>is(Int, Int)[]. A resource enters a union, which becomes a resource.()can be a member of one,Int | (), matched by the pattern(). A member whose type has the same name as a variant of another,Timeout, is matched by its name alone:Timeout =>meansTimeout(_). -
Literal unions. A string, integer, character or boolean literal, written as a type, is a type that has only that value: as a member of a union, it is a variant without payload.
type Order = "asc" | "desc"is thus an enum of two literals, an index in memory;type Sep = ',' | ';'is another, andtype Width = "auto" | Intortype Flag = true | "auto"mix a literal with a type or with another literal. A literal enters the union where it is expected,val o: Order = "asc",o == "asc"; any other is rejected at compile time. Amatchmatches the literals,"asc" => …, and checks its exhaustiveness. A literal union is not a string: nothing converts it to one on its own,"${o}"writes it, andOrder.from(s)reads a string back as anOrder?,Noneif it is no member.fromchooses by the type of the value, and always returns an optional: on"auto" | Int,Width.from(3)isSomeof the Int member,Width.from("auto")the literal, and nothing is parsed,Width.from("3")isNone; a value of a type the union does not contain is rejected at compile time. An unnamed union is read back by.from(v)where it is expected:fn order(s: String): ("asc" | "desc")? = .from(s). A negative integer is a literal like any other,type Sign = -1 | 0 | 1. A literal adopts Eq, Hash and Show, so that the union can serve as a key. A literal type alone,type X = "a", is rejected. -
Flags. A set of independent flags, each on one bit, is a
Flags<E>over an enum without payload that adoptsFlag:#Flag enum Perm = Read | Write | Exec, thenval p: Flags<Perm> = [.Read, .Write]. AFlags<Perm>is neither an integer nor aFlags<OpenFlag>: two families do not mix. Variant i occupies bit i, in declaration order, or the one its tag gives when the value is imposed by C:#Flag enum OpenFlag = Create `flag(bit: 6)` | Append `flag(bit: 10)`; at most 64 flags. The set is stored in the smallest unsigned integer that holds its highest bit, or in the one requested by#Flag(repr: UInt32). It is read and written through methods, the set of operators remaining closed (section 4):p.has(.Write),p.with(.Exec),p.without(.Read),p.union(q),p.intersect(q),p.isEmpty(), andfor f in piterates over the flags present;[]is the empty set, and the literal goes through theSetLiteral<T>contract (core), as a map’s goes throughMapLiteral, whichSetalso adopts: a repeated constant element in it is an error, a repeated computed element stops the program. It adopts Eq, Hash and Show, which writesRead | Write, and[]for the empty set. TheFlagcontract requiresmask(),name()andall(), which#Flaggenerates;p.word()andFlags<Perm>.fromWord(w)go through a UInt64 whatever the storage integer, andFlags<Perm>.known()returns the bits that the flags name. To an integer and back, the conversion is written out:p.toBits(), andFlags<Perm>.from(n)receives the storage integer. A bit that no flag names is not an error, but often one from a more recent version: it is kept,toBits()returns it,==compares it,withandwithoutpreserve it,hasandforignore it,p.unknownBits()gives it so it can be reported, and Show writes it in hexadecimal,Read | 0x40. A constantfromthat sets an unknown bit triggers a compile-time warning. -
Bit fields. A record whose representation is an integer stores several pieces of information in a single word:
packed type Header: UInt16 = { … }, each field taking the number of bits its tag gives. A Bool takes one bit, an enum without payload as many as its variants need, an integer its width, or less via`bits(4)`(in two’s complement if it is signed). Fields are laid out from the least significant bit to the most significant bit, in declaration order: nothing depends on the compiler, unlike C bitfields. The sum of the widths is exactly that of the integer; bits that nothing uses are declared by a_field,_: UInt16 `bits(9)`, never read or written by its name and preserved from one modified copy to the next, as a hardware register requires. The value is the integer itself, which passes as is to C: reading a field is a shift and a mask. A write,h.with(version: 5), or in place on a variable,h.version = 5andh.version += 1, which are sugar for it (a bit field has no location of its own: it cannot be lent,&h.version), checks that the value fits in its bits, at compile time for a literal, otherwise by stopping the program, like a sized integer.h.toBits()returns the integer;Header.from(raw)returns aHeader?,Noneif an enum field receives a code it does not name: checked once on entry, a field is then read without failure. A field that must accept future codes is declared as an integer.enum Kind = Data | Ack | Resetpacked type Header: UInt16 = {version: UInt8 `bits(4)`kind: Kindurgent: Bool_: UInt16 `bits(9)`} -
Structural shapes.
{ name: String, .. }accepts any record having at least that field, of that type, and a named tuple, an anonymous record,f((name: "a", count: 3)). It is written only as a parameter type, read-only ormut:fn bump(c: mut { count: Int, .. }) { c.count += 1 }modifies the field of the record passed; or as the constraint of a function’s type parameter,fn label<T: { name: String, .. }>(x: T, …), whose values then have that field,x.name, and which the meta fns of computed types read (5.2). Each use is monomorphized, hence without runtime cost. -
Optionals.
T?is equivalent toOption<T>. A value of typeTwhere aT?is expected is wrapped:greet("Ada")forfn greet(name: String?),if n > 0 { "positive" } else { None }in a function that returnsString?, just as a return value is wrapped inOk(8.1).x?.y,x?.f(…)andpair?.0, a tuple’s element, areNoneifxisNone, without leaving the expression, and otherwiseSomeof the field or result; a field or result that is already optional is not wrapped a second time, so thata?.b?.cchains. Every access on an optional is written?.:n?.chars()?.len().??provides a default value.?alone does not exist: propagating an error is written!(8.1).o.unwrap()lends the present value, read througho, stopping the program on None;o.take()gives it up, which a resource leaving an option needs. -
Ranges as values. Outside a loop,
a..banda..=bare values of typeRange<T>,{ start, end, inclusive }, T an integer of any size, a character or a floating-point number, given by the bounds or the expected type:buf.copyWithin(used..used + n, to: 0),val r = start..end,val all: Range<UInt8> = 0..=255. The Range keeps its end as written, and whether it is included: an excluded end could not express0..=255on a UInt8.r.contains(x)andr.isEmpty()apply to any Range,r.len()to a Range of integers or characters (surrogates are not characters), andfor i in riterates over it like the written range. A Range of floating-point numbers can be tested but not iterated: its step cannot be guessed,for x in a..b step k.xs[r], r a Range, is the view of those elements, like xs[r.start..r.end]orxs[r.start..=r.end]. -
Generics.
T[], constrained bywhere T: Ord. A record can have its parameters,type Heap<T> = { items: T[], by: (T, T) => Ordering };Heap<Int>is an instance of it, and a literal deduces its own from the expected type or from its fields. Its functions are written inimpl<T> Heap<T> { … }. A type parameter is constrained,type Heap<T: Ord> = { items: T[] }, or by a clause before the=,type Wrap<T, I> where I: Iterable<T> = { it: I }: each instance is checked,Heap<F>requires F to adopt Ord, andWrap<Int, Lines>that Lines adoptIterable<Int>, not just Iterable, and a generic function that writesHeap<T>constrains its T,fn f<T: Ord>(h: Heap<T>). Inimpl<T> Heap<T>, T holds the template’s constraints, which all its instances satisfy. Calling a type calls itsnewfunction:Heap<Int>(by: f)meansHeap<Int>.new(by: f),Key[]()an empty array. An enum likewise has its parameters,enum Tree<T> = Leaf | Node(left: Tree<T>, value: T, right: Tree<T>): a construction takes its instance from the expected type, or from its fields (Node(left: Leaf, value: 1, right: Leaf)is aTree<Int>); a variant without fields says nothing about T and requires the expected type, likeNone:val t: Tree<Int> = Leaf, orTree<Int>.Leaf. An associated function ofimpl<T> Tree<T>is found likewise:Tree<Int>.empty(),Tree.of([1, 2])which deduces T from its arguments, orval t: Tree<Int> = Tree.empty(). -
No class inheritance. Composition and contracts (section 4).
-
Tuples.
(a, b), destructuring byval (a, b) = …,var (a, b) = …,using (a, b) = …andfor (a, b) in …, nested as needed,val (a, (b, c)) = t, and()for the absence of a value.()is a value like any other, which takes no space:Option<()>,()[],Set<()>,Parser<()>; it adopts Eq, Ord, Hash, Show and Default. Only the error of a Result cannot be(), which would not say what failed; and a bindingval x = ()is rejected, like that of the result of a function that returns nothing. Elements can be named,(on: Bool, value: Int), which makes it an anonymous record. A tuple adopts Eq, Hash, Ord and Show when its elements adopt them:Map<(Int, String), V>, a sort of pairs. A tuple is either positional or named: as soon as an element carries a name, a name alone meansname: name, as in a record ((last: x, spilled)). Positional access.0exists, but the IDE discourages it beyond two elements. A part bound to_has no name, but lives until the end of the block like a variable:val (tx, _) = Channel<Int>(capacity: 1)keeps the receiver, which closes only with the block; a resource, however, is not bound to_(7.1).
fn label(r: Role): String = match r { Admin => "admin" Editor => "editor" Reader(since) => "reader since ${since}"}
fn greet(p: { name: String, .. }) = print("Hello ${p.name}")Construction by projection. ..source takes the same-named fields of another record, of any type. Elements apply from left to right and the last one wins, which gives two uses depending on the order:
// Override: start from the source, then replace some fieldsval s = Selection{..args, lines: true}
// Complete: set default values, which the source replaces where it provides themval cfg = Config{port: 8080, host: "localhost", ..overrides} // overrides: Partial(Config)- A source field of type
T?, destined for a field of typeT, replaces the value only if it isSome. This is what makesPartial(5.2) useful for completing. The field must therefore have a value before it, written or from a preceding source:Config{..patch}alone is an error. - Source fields that the target does not declare are ignored.
- A field of the same name but of incompatible type is an error, as is a target field left without a value.
- An explicit value always overridden by a non-optional source triggers a warning: it serves no purpose.
- Several sources are allowed:
Config{..defaults, ..file, ..cli}. u.with(name: "Ada")is a shorthand forUser{..u, name: "Ada"}.