Skip to content
Weaverv0.5.0

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 literals
type Id = Int | Uuid // union of types
type Tree = { value: Int, children: Tree[] } // recursive: automatic indirection
type Node = { value: Int, next: Node? } // recursive through an optional
  • Primitives. Int (64 bits, also named Int64), Int8, Int16, Int32, UInt8…UInt64, Float (64 bits) and Float32, Bool, Char, String (UTF-8), Bytes.

  • Checked arithmetic. An overflow of +, -, *, of negation or of MIN / -1 stops 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 % -1 is 0, the exact remainder. << and >> require a shift between 0 and 63, and >> preserves the sign. A literal that starts with 0 stays decimal; hexadecimal is written 0x, octal 0o and binary 0b, 0o644, 0b1010_0001, and a digit outside the base is an error.

  • Sized integers. Every integer has its arithmetic checked, like Int: 200 + 100 on a UInt8 stops the program, as does 0 - 1 on 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 an Int16?, n being an integer of any type, and Int.from(u) an Int?, 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), and wrappingAdd, wrappingSub, wrappingMul compute 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 << n shifts a UInt8 by n steps, n an Int; >> keeps the sign of a signed integer, and shifts zeros into a UInt.

  • Floating-point numbers. Float and Float32 follow IEEE 754: 1.0 / 0.0 is infinity and 0.0 / 0.0 NaN, without panic, and x.isNaN(), x.isFinite() test for them. A literal is written 1.5, 2e10 or 1.5e-3; it is a Float, or a Float32 where the context expects one. Nothing mixes integers and floating-point numbers: 1 + 2.5 is rejected, and the conversion is written out, n.toFloat(), to the nearest, or x.toInt(), toward zero, which stops the program if x is NaN or outside an Int; round, floor, ceil and trunc stay Floats; round goes to the nearest integer, a tie away from zero: 2.5.round() is 3.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, and s.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, like printf: 2.5.format(precision: 0) gives 2, 0.125.format(precision: 2) gives 0.12, and 2.675.format(precision: 2) gives 2.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 by u.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. Char is a Unicode code point, 'é' or '\u{85}'; Char.from(n) returns a Char?. for ch in s iterates over the characters of a string, an invalid sequence yielding U+FFFD. Bytes has the shape of a UInt8[] (index, len, push, for) and its own methods: Bytes.filled(n, with: 0), count(b), find(needle), indexOf(b, from:), lastIndexOf(b, before:), utf8Chunks(), and uint32BE(at), uint32LE(at) and their 16- and 64-bit siblings, which read an integer with a single index check, and setUint64LE(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 where Bytes are 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() and trimEnd() remove Unicode whitespace; find, contains, stripPrefix, stripSuffix, repeat(n), and toUpper, toLower, which change only ASCII letters. An integer literal where a UInt8 is expected is one, if it is between 0 and 255: sep: 0, b + 1.

  • Strings and arrays. String is a sequence of UTF-8 bytes: s.byteLen() counts bytes, and ==, < compare byte by byte. An array, Array<T>, is written T[]: 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] in for i in 0..xs.len(), xs[x + 1] under if 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) and xs.capacity() set and read the room. xs + ys is a new array, the elements of xs then those of ys, and xs += ys appends them in place (concat and extend, bound by @operator in core); xs.contains(x) and xs.indexOf(x) require T: 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, truncate and clear are rejected, since the removed elements would not be disposed of: pop() or for using x in xs.drain() hand them back. len, isEmpty, push and byteLen are 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], or Int[3][3], three Int[3]. n is computed at compile time: an integer literal, an integer meta val constant, 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 from T[n].filled(with: v): no zero value is implicit. a[i] checks its index, a[i] = v writes in place in a var, a.len() is a constant, for x in a iterates 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 a T[] 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; filled does 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 adopts MapLiteral<K, V> (core): val m: Map<String, Int> = [:], or a map of the program. Without an expected type, it is a Map<K, V>, K and V given by the entries, and the file must import weaver.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.collections has 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 by for (k, v) in m (3.2), and adopt MapLiteral: val o: OrderedMap<String, Int> = ["b": 1, "a": 2]. Set<T> is iterated by for x in s and adopts SetLiteral: val s: Set<String> = ["a", "b"]. A map also holds resources (7.1): insert receives them and returns the one it replaces, which the caller adopts, using old = m.insert(k, v), remove returns its own, and for (k, v) in m borrows them.

  • Mutability. It applies to the binding, not to the type: val is immutable, var is mutable, fields included. A val whose value or type is mut, 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 as mut, except to replace, which reassigns it (6.2). wv migrate writes mut where a var’s content is modified in place, and val where 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) or Reader(d). Its name alone suffices; when two enums of the module use it, it must be qualified, Role.Admin. Where the type is known, .equal designates 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 ==. match is 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 that None costs nothing: in enum 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) and enum 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 | Uuid is 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 or mut, and receives no other Self than the other of ==; 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 an mut self method modifies in place: a union of Writers is a Writer. Thus "${id}", a == b, true for the same member with equal values, and id.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 | Uuid names 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 nor impl, which go to the named record or enum. An alias has its parameters: type Pairs<T> = (T, T)[], type StrMap<V> = Map<String, V>, and Pairs<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 => means Timeout(_).

  • 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, and type Width = "auto" | Int or type 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. A match matches 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, and Order.from(s) reads a string back as an Order?, None if it is no member. from chooses by the type of the value, and always returns an optional: on "auto" | Int, Width.from(3) is Some of the Int member, Width.from("auto") the literal, and nothing is parsed, Width.from("3") is None; 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 adopts Flag: #Flag enum Perm = Read | Write | Exec, then val p: Flags<Perm> = [.Read, .Write]. A Flags<Perm> is neither an integer nor a Flags<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(), and for f in p iterates over the flags present; [] is the empty set, and the literal goes through the SetLiteral<T> contract (core), as a map’s goes through MapLiteral, which Set also adopts: a repeated constant element in it is an error, a repeated computed element stops the program. It adopts Eq, Hash and Show, which writes Read | Write, and [] for the empty set. The Flag contract requires mask(), name() and all(), which #Flag generates; p.word() and Flags<Perm>.fromWord(w) go through a UInt64 whatever the storage integer, and Flags<Perm>.known() returns the bits that the flags name. To an integer and back, the conversion is written out: p.toBits(), and Flags<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, with and without preserve it, has and for ignore it, p.unknownBits() gives it so it can be reported, and Show writes it in hexadecimal, Read | 0x40. A constant from that 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 = 5 and h.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 a Header?, None if 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 | Reset
    packed type Header: UInt16 = {
    version: UInt8 `bits(4)`
    kind: Kind
    urgent: 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 or mut: 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 to Option<T>. A value of type T where a T? is expected is wrapped: greet("Ada") for fn greet(name: String?), if n > 0 { "positive" } else { None } in a function that returns String?, just as a return value is wrapped in Ok (8.1). x?.y, x?.f(…) and pair?.0, a tuple’s element, are None if x is None, without leaving the expression, and otherwise Some of the field or result; a field or result that is already optional is not wrapped a second time, so that a?.b?.c chains. 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 through o, stopping the program on None; o.take() gives it up, which a resource leaving an option needs.

  • Ranges as values. Outside a loop, a..b and a..=b are values of type Range<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 express 0..=255 on a UInt8. r.contains(x) and r.isEmpty() apply to any Range, r.len() to a Range of integers or characters (surrogates are not characters), and for i in r iterates 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] or xs[r.start..=r.end].

  • Generics. T[], constrained by where 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 in impl<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, and Wrap<Int, Lines> that Lines adopt Iterable<Int>, not just Iterable, and a generic function that writes Heap<T> constrains its T, fn f<T: Ord>(h: Heap<T>). In impl<T> Heap<T>, T holds the template’s constraints, which all its instances satisfy. Calling a type calls its new function: Heap<Int>(by: f) means Heap<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 a Tree<Int>); a variant without fields says nothing about T and requires the expected type, like None: val t: Tree<Int> = Leaf, or Tree<Int>.Leaf. An associated function of impl<T> Tree<T> is found likewise: Tree<Int>.empty(), Tree.of([1, 2]) which deduces T from its arguments, or val t: Tree<Int> = Tree.empty().

  • No class inheritance. Composition and contracts (section 4).

  • Tuples. (a, b), destructuring by val (a, b) = …, var (a, b) = …, using (a, b) = … and for (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 binding val 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 means name: name, as in a record ((last: x, spilled)). Positional access .0 exists, 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 fields
val s = Selection{..args, lines: true}
// Complete: set default values, which the source replaces where it provides them
val cfg = Config{port: 8080, host: "localhost", ..overrides} // overrides: Partial(Config)
  1. A source field of type T?, destined for a field of type T, replaces the value only if it is Some. This is what makes Partial (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.
  2. Source fields that the target does not declare are ignored.
  3. A field of the same name but of incompatible type is an error, as is a target field left without a value.
  4. An explicit value always overridden by a non-optional source triggers a warning: it serves no purpose.
  5. Several sources are allowed: Config{..defaults, ..file, ..cli}.
  6. u.with(name: "Ada") is a shorthand for User{..u, name: "Ada"}.