sysl

Types

Every type the language has — the open integer families, the closed float set, and the aggregates built on them.

sysl’s types fall into four groups: scalars (numbers, bool, char), the built-in string, the aggregates you build (arrays, slices, structs, enums, tuples), and the modes that decide where a value lives (T, &T, *T). This page covers the first three. The modes have a page of their own, because they are about storage rather than shape. ref is not a type and is refused wherever a type is written: it declares a local name for a place, and a method’s -> ref T says its call is a place (A member that answers a place).

struct Holder
    r: ref int
'ref' is a declaration, never a type, so it cannot be a field's, a parameter's, an element's or a type argument's type

A conversion is implicit exactly when it cannot lose information: where every value of one numeric type is exactly a value of another — a byte into an int, an int into a long or a real, an f32 into an f64 — a position that expects the wider type accepts the narrower one directly. Every other width change, signedness change, and float/integer conversion is written as a conversion call, so a conversion that could lose information is always visible. The table is in Which conversions are implicit.

Integers are an open family

iN and uN are not a fixed set of four sizes. They are an open family parameterized by an arbitrary bit width: i5, u3, u12 and i128 are all valid types, with no list of widths built into the compiler. LLVM supports integers of any width natively, so this is a capability of the target rather than something sysl emulates.

var small: u3 = 5
var odd: i5 = -7
var wide: u12 = 4000

print(small, odd, wide)
5 -7 4000

iN/uN is the general mechanism, and a short list of aliases names the common widths.

aliasisaliasis
byteu8shorti16
ushortu16inti32
uintu32longi64
ulongu64realf64

Unlike C’s, each alias has a fixed width: long is exactly i64 on every target.

This fixes the width, not the C ABI match. On a 64-bit host every alias matches its C namesake, so they are safe in extern declarations there. On a 32-bit target C’s long is 32 bits while sysl’s is still 64, so precise FFI should use the explicit-width names, which match C’s int32_t and int64_t on every target. i8 has no alias, since C has no established name for a signed byte.

An integer literal has no maximum of its own. Its value is exact at any size and must fit the type it takes, so a literal can be as wide as the widest type:

val c: u256 = 115792089237316195423570985008687907853269984665640564039457584007913129639935

print(c)
115792089237316195423570985008687907853269984665640564039457584007913129639935

A value that does not fit the type is refused rather than wrapped:

val z: u8 = 300
the literal 300 does not fit u8

A literal with no type from its context is an int, and one too large for int is refused rather than widened — give it a type, with a suffix, on the declaration, or with a conversion, whose argument is read at its target:

val big = 4294967295
the literal 4294967295 does not fit int

Beside an operand of an integer type, an integer literal takes that type, fitting or not, as in Rust: b + 200 over a u8 is a u8 sum (which +% wraps), and b + 300, b < 300 and b + -1 are refused at the literal, whatever the sum is for. int(b) + 300 is the int sum. Two operands that each have a type of their own still widen to each other, so u8 + u16 is a u16 (expressions).

val b: u8 = 100
val w: u16 = 1000

print(b +% 200, int(b) + 300, b + w)
44 400 1100
val b: u8 = 100
val z: int = b + 300
the literal 300 does not fit u8

A binding given a bare literal takes its type from its first use that fixes one, not from the literal: a comparison, an argument, a result, or arithmetic beside an operand of a type of its own. In var sum = 250 followed by sum + b over a u8, sum is a u8 — and var s = 300 beside the same b is refused as 300 would be with u8 written. A binding no use fixes is the literal’s default, int or real (declarations).

Arithmetic wraps

What a plain +, - or * does when the answer does not fit is the build mode’s. In a release build — what sysl build makes — integer arithmetic wraps at the declared width, and this is defined behaviour, never undefined: i5 wraps mod 2⁵ exactly as i32 wraps mod 2³². In a debug build — what sysl run and sysl test make — the same overflow is a bug, and it stops the program with a report naming the operation, its types and the line. The same holds of a unary - (negating i8‘s −128) and of a written conversion that cannot hold its value (u8(n) with n at 300). The mode is never the reason a program is right: code that means to wrap says so — and a conversion that means the bit pattern is u8.wrap(n), unchecked in every build. Code whose overflow is a fault in every build says that too: a @checked function or block, or a package’s checked_overflow = true, checks it in a release build as well.

var small: byte = 250

print(small +% 10, small +| 10)
4 255

Where the wrap is the point — a hash, a checksum, a counter that rolls over — +%, -% and *% say so in the spelling, and where the edge of the range is the right answer instead, +|, -| and *| stop there. Both families mean the same in every build, at every width (wrapping and saturating operators). A plain small + 10 prints 4 from a release build and stops a debug one with `integer overflow: byte

Asking whether it fit

Where an overflow means the input was wrong — a number read out of a document, a total over untrusted data — the question is whether the operation fit, and the wrapped result cannot answer it afterwards. Every plain integer type answers it with the prelude trait Checked: checked_add, checked_sub, checked_mul, checked_div, checked_rem and checked_neg, each returning Option[Self] — the result, or None where the plain operator would have wrapped or trapped.

var small: byte = 250

print(small.checked_add(5), small.checked_add(6))
print(0u8.checked_sub(1), i8(-128).checked_neg(), i8(-128).checked_div(-1), 7.checked_rem(0))
Some(255) None
None None None None

They are defined at every width, odd ones and those past a machine word included, and lower to the machine’s own overflow flag (llvm.sadd.with.overflow and its siblings) rather than to a test written after the fact. The operand is the receiver’s type: a literal takes it, and a value of another type is refused rather than converted.

val a: byte = 1
val b: int = 2

print(a.checked_add(b))
'rhs' of method 'Checked.checked_add' is byte, but int was given

A generic body asks for them with the bound [T: Checked]. The members are the plain iN and uN types only: a ranged type‘s overflow is a breach of its range and already traps, and a float has no overflow to report. There is no checked_shl or checked_shr, because a shift by the width or more is defined.

Carrying from one word to the next

A number wider than any integer type is added a word at a time, and each word’s sum needs the carry the word below it produced. Every unsigned integer type answers that with the prelude trait Carrying: x.add_carry(y, c) is x + y + c and x.sub_borrow(y, c) is x - y - c, where c is a bool, and each answers the pair of the low bits and whether the operation carried (or borrowed) out of the type.

val top: u8 = 255
val zero: u8 = 0

print(top.add_carry(0, false), top.add_carry(0, true), top.add_carry(top, true))
print(zero.sub_borrow(0, true), zero.sub_borrow(1, false), top.sub_borrow(top, false))
(255, false) (0, true) (255, true)
(255, true) (255, true) (0, false)

Chained from the lowest word up, the carry out of each call is the carry in of the next. The members are defined at every unsigned width, u12 and u128 included, and each is two with.overflow calls and an or (llvm.uadd.with.overflow and llvm.usub.with.overflow at the receiver’s width), so the back end can form an add-with-carry instruction. The two operands are the receiver’s type and the carry a bool; anything else is refused as checked_add‘s operand is. A signed type is not a member, since the carry out of a word means something only where the word is a magnitude: ask a signed type whether it fit with Checked. A generic body asks for them with [T: Carrying].

Arithmetic over literals is exact

An expression written out of integer literals alone — 65536 * 65536, (1 << 16) - 1, 200 + 100 — is a constant the compiler computes with no width at all, and the value it comes to must fit the type it is read at, exactly as a single literal’s must. Overflow is something that happens to a value held in a variable; a value nobody has stored yet has nothing to overflow, so a constant that does not fit is a mistake in what was written — refused in every build mode alike.

val b: u32 = 65536 * 65536
the value 4294967296 does not fit u32

Only the whole expression is held to the type. The steps on the way are plain numbers, so a step may pass the type’s range provided the result comes back inside it, and a division or a right shift works on the exact value rather than a wrapped one:

val mask: u32 = 65536 * 65536 - 1
val top: u32 = (65536 * 65536 * 256 - 1) >> 20
val low: u8 = ~0xF0

print(mask, top, low)
4294967295 1048575 15

~ is the complement at the type’s own width, so ~0 is a u32‘s largest value rather than the -1 that has no place in an unsigned type. Suffixed literals are literals too: 255u8 + 1u8 is refused as the value 256. A literal with no type from its context is an int here as well, so val big = 65536 * 65536 is refused as int, and is written val big: long = 65536 * 65536.

A left shift is a bit operation, as in C and Rust: the bits shifted past the top of its type are dropped. The type is the one the shift is read at, which for an unsuffixed literal is the type of the whole expression, so a mask shifted left stays a mask and a one shifted into the sign bit is the signed type’s minimum. What the shift comes to is then an ordinary step, and the operator around it is held to the type as any other:

val hi: u64 = 0xffffffffffffffff << 27
val min = 1 << 31
val max: u32 = (1 << 31) + ((1 << 31) - 1)

print(hi, min, max)
18446744073575333888 -2147483648 4294967295

A shift has no value by a count below zero or at or past the width of its type, and one of a value the type does not hold would hide that value’s mistake by dropping it; all three are refused:

val big = 1 << 40
a constant shifted by 40 places, at or past the 32 bits of int

A division or a remainder by a literal zero has no value at all, and is refused where it is written:

val z = 1 + 10 / (3 - 3)
a constant divided by zero

An untyped integer const is the literal it stands for, so it takes part in all of this: const Half = 200 makes Half * 2 the exact 400, and it is refused at u8 as 200 * 2 is. So are a chain of such constants (const Quad = Half * 2), a constant of a constant, one from another module, and negative values and shifts of them. Such an expression also chooses an overload as the literal spelling does: h(Half * 2) over h(v: u8) and h(v: u16) is the u16 one.

const Half = 200

val b: u8 = Half * 2
the value 400 does not fit u8

Any other name in the expression makes it ordinary arithmetic, which overflows as the build mode says. A val, a variable, and a const declared with a type are names of a value of that type, so the arithmetic built on them is the arithmetic of the type, and the constant is not exact:

const Base: u8 = 200

print(Base +% 100)
print(Base + 100)
44

The first line wraps in every build; the second is plain + at u8, which a debug run — the one above — stops, and a release build prints as 44.

A literal read as a float is not an integer constant at all: val r: f64 = 1 / 0 is IEEE 754’s division, and is infinity.

Storage is not N / 8

An integer’s alignment rounds up to the smallest width the target names, and its stride rounds up to that alignment. A u12 occupies two bytes aligned to two; a u96 occupies sixteen aligned to sixteen. This is LLVM’s rule.

Where the width stops

Up to 64 bits every operation is a machine instruction. Beyond that the arithmetic is still native — the back end expands a wide multiply or divide inline, with no runtime routine — but decimal rendering is done by sysl itself, since C’s printf has no length modifier that wide. A value wider than 64 bits is printed through a digit loop, and %d is refused for it.

The maximum width is LLVM’s limit of 2²³ − 1 bits, and a wider type is a diagnostic naming it.

var wide: u256 = 1
var i = 0

while i < 200 do
    wide = wide * 2
    i = i + 1

print(wide)
1606938044258990275541962092341162602522202993782792835301376

A conversion between a wide integer and a float is inline as well, by the rules every width follows: an integer becomes the float nearest it, ties to even, rounded once, and one past the float’s range is an infinity; a float becomes an integer truncated toward zero, saturating at the width’s ends, with a NaN as 0 (conversions are calls).

var big: i256 = 9007199254740993
var wide = u1000(1) << 999
var x = 1.0e30

print(real(big), real(big + 2), real(-big), f32(wide))
print(i256(x), u256(-x), i200(real.nan), i200(real.infinity) == i200::Max)
9007199254740992 9007199254740996 -9007199254740992 inf
1000000000000000019884624838656 0 0 true

Extreme widths have two costs, neither of which is diagnosed: the digit buffer is stack space proportional to the width, so printing a value near the maximum width overflows the stack frame, and sizing the buffer evaluates 2^N at compile time. Only a program that names such a width is affected.

The narrowest widths

Any N ≥ 1 is valid. u1 is a single binary digit. i1 holds {-1, 0} — one bit of two’s complement, where the only bit is the sign bit. It is degenerate but consistent, and nothing special-cases it: abs at i1 answers -1 because -1 is that width’s most negative value, as abs at any width answers its own minimum, and signum never returns +1 because no value of the type is positive. For a single bit, write u1 or bool.

Fixed point is the integers read in units

iWqF and uWqF (q7, q15, q31) are a W-bit integer counting units of 2^-F — see fixed-point numbers. They are the one scalar family whose arithmetic saturates rather than wraps, unless a type is declared wrapping, because a fixed-point value models a real number in a range, as a float does.

Floating point is a closed set

fN is not open: only real formats exist, since there is no meaningful f37. The set is f16, bf16, f32, f64 and f128.

Only the default width has an alias, named real rather than float, because float means 32-bit to C, C++, Rust and Java programmers.

var a: f32 = 1.5
var b: real = 2.25

print(a + 1, b / 2)
2.5 1.125

A float renders in the shortest form that round-trips, so a value with no fractional part prints without one.

Infinity and NaN

An infinity and a NaN have no decimal literal, so each float type names them: real.infinity and real.nan, and the same on every width — f32.infinity, f16.nan, bf16.infinity. They are written without parentheses, because they are constants rather than functions, so a const initializer or a within bound may use one.

infinity and nan written on their own are the real ones. Negative infinity is a minus in front, as for any other value:

const top = infinity
val low = -f32.infinity

print(top > 1.0e308, low < -3.0e38, nan != nan, -infinity < 0)
true true true true

A NaN compares unequal to everything, itself included, as the third value shows; test for one with is_nan().

The bare names have the outermost scope. Anything the program declares or imports under the same name takes precedence — a local, a parameter, a const, a function — so a program that declares its own infinity keeps it:

f(nan: int) -> int = nan + 1

print(f(2))
3

Where a declared function has the name, reading it bare as a value is refused as usual, and the message gives the spelling no declaration can hide:

infinity() -> real = 2

val x = infinity

print(x)
The built-in constant this declaration hides is spelled 'real.infinity'

The Float trait’s associated functions real.infinity() and real.nan(), which a routine generic over the width calls as T.infinity(), are also available, as are sysl.math‘s infinity() and nan().

The two sixteen-bit formats

bf16 is the one name in the set that is not a width, because width alone does not identify a format at sixteen bits. Both formats use one bit for the sign and divide the other fifteen differently:

exponentsignificandlargest finitedecimal digits
f165 bits10 bits65504~3
bf168 bits7 bits3.4 × 10³⁸~2

So bf16 is not a smaller f16 but a shorter f32: its bits are the top sixteen of a binary32, so it has exactly binary32’s range. f16 is the more precise of the two but has a small range, while bf16 covers every exponent an f32 does at the cost of three bits of significand.

Both are ordinary arithmetic types. A tenth shows the difference in precision, and doubling the largest f16 shows the difference in range:

var h: f16 = 0.1
var b: bf16 = 0.1

print(h, b)
print(real(h), real(b))

var big: f16 = 65504
var wide: bf16 = 65504.0

print(big * 2, real(wide * 2))
0.1 0.1
0.0999755859375 0.10009765625
inf 131072

Both print 0.1, because print writes the fewest digits that read back as the value at its own width, and 0.1 reads back as each format’s nearest value to a tenth. Neither holds a tenth exactly, and the two nearest values differ: widened to a real, which represents every value of both formats exactly, each shows all of its digits. (wide * 2 is widened for the same reason: at bf16‘s width the shortest reading of 131072 is 131000.) The bf16 initializer is written 65504.0 because the value rounds there: an integer literal is accepted at a float type only where the format holds it exactly, and bf16‘s nearest value is 65536.

f16 and bf16 are also the one pair where neither conversion is a widening or a narrowing. It is still written as an ordinary conversion:

var b: bf16 = 0.1

print(f16(b))
0.1001

The result is bf16‘s tenth rather than f16‘s: a conversion carries the value the source actually holds. Here f16 represents it exactly — its ten bits of significand hold bf16‘s seven with nothing to round — and distinguishes it from its own tenth, so it needs four digits to print. The other direction rounds, since seven bits cannot hold ten: bf16(h), with h the f16 tenth from above, is bf16‘s own tenth (0.10009765625 widened) rather than h‘s 0.0999755859375, because that value has no exact seven-bit representation.

The f16 text round-trips: sysl.text.parse_f16 reads a decimal rounded once to the nearest f16, so every to_string of an f16 parses to the same f16, and a long decimal a hair from half way between two of them goes to the nearer one rather than through a wider float to the even one.

import sysl.text.parse_f16

val h: f16 = 0.1

print(parse_f16(h.to_string()).unwrap().bits() == h.bits())
print(parse_f16("65519.99").unwrap(), parse_f16("65520").unwrap())
print(parse_f16("1.00048828125000000000000000000000000000001").unwrap().bits() == 0x3c01)
true
65500 inf
true

sysl.math‘s Float trait covers both, so sqrt, floor, pi and the rest are called the same way as for real. libm has no sixteen-bit entry points, so those functions widen to f32, compute, and narrow back; the widening is exact, so the only rounding is to the destination.

Neither format has an alias. A literal takes one through a suffix or through the type it is written into: 1.5f16, 1.5bf16, or var x: bf16 = 1.5.

f128, binary128

f128 is IEEE binary128: a 15-bit exponent, as wide as x87’s, and 112 bits of fraction, about 34 decimal digits where real has 16. It is an ordinary arithmetic type — + - * /, the comparisons, unary minus, f128.infinity and f128.nan, and a conversion to and from every integer and float width — and its literals are read from their text, so 0.1f128 is binary128’s own tenth rather than a double’s tenth widened:

val tenth: f128 = 0.1
val third: f128 = 1 / 3

print(third.bits() == 0x3FFD5555555555555555555555555555)
print(real(tenth) == 0.1, tenth + 0.2 > 0.3, f128(0.1) == tenth)
true
true true false

The last value is false because f128(0.1) exactly widens the double nearest a tenth, which is not the binary128 value nearest a tenth. x.bits() is the encoding as a u128, and f128.from_bits(b) reads one back.

No machine sysl targets has quad-precision hardware, so every operation is a call into software, at about a hundred times the cost of a real operation. The routines follow compiler-rt’s names and contracts (__addtf3, __lttf2, __fixtfdi and the rest), and the standard module provides its own in sysl.softfloat, because a Mac’s runtime has none (C’s long double is a double there) and a bare-metal image has no runtime library at all. A program, archive or kernel image that computes in f128 is linked with them, and one that does not contains none. They always round to nearest, ties to even.

A real on a 32-bit board works the same way one size down. Every Cortex-M floating-point unit sysl targets is single-precision or absent, and the 32-bit RISC-V targets have none, so an f64 operation there is also a call — __aeabi_dmul on Arm, __muldf3 on RISC-V. The standard module provides those in sysl.softfloat.binary64, with the same rounding and the same rule: an image that computes with a real contains them, and one that does not contains none. Results are bit for bit what a double-precision unit gives. The same holds for dividing a long, which no 32-bit core does in one instruction (sysl.softint). This archive for a Cortex-M4F defines __aeabi_ldivmod, __aeabi_l2d and __aeabi_dmul itself:

@export("scale")
scale(x: real, n: long) -> real = x * real(n / 1000)

An f32 on a core with no floating-point unit at all — a Cortex-M0+ or M3, RISC-V with no F — is a call as well, __aeabi_fmul or __mulsf3, from the same module and under the same rule. Each routine computes in binary64 between an exact widening and a narrowing. Because 53 bits is more than twice 24 plus two, the double rounding is harmless, and the result is bit for bit what a single-precision unit gives. This archive for a Cortex-M0+ computes with an f32 and needs nothing from its board but memcpy and memset:

@export("mix")
mix(a: f32, b: f32, t: f32) -> f32 = a + (b - a) * t

An f16 on bare x86-64 or WebAssembly is computed in f32 and converted at every store, and neither machine has a binary16 conversion instruction at the baseline sysl builds for, so each conversion is a call: __extendhfsf2, __truncsfhf2, and __truncdfhf2 from a real. The same module provides these three there. Narrowing rounds once, to nearest with ties to even, so an f64 is never rounded through an f32 first, and the results are bit for bit what the conversion instructions of an Arm core give. This archive for a bare x86-64 needs nothing from its machine:

@export("blend")
blend(a: f16, b: f16, t: real) -> f16 = a + (b - a) * f16(t)

print, str and a plain interpolation hole write an f128 in the fewest digits that read back as it, positionally, as every float prints. It is never narrowed to a real, which would print a different number. A format specifier renders the exact value’s digits, correctly rounded at the requested precision, as it does for a real. All of this is the standard module’s own arithmetic, so it needs no C library and works on bare metal:

val tenth: f128 = 0.1
val third: f128 = 1 / 3

print(tenth, third, -0.0f128, f128.infinity)
print(third.to_string().bytes.len, s"$tenth", f"${third}%.40f", f"${tenth}%.3e")
0.1 0.3333333333333333333333333333333333 -0 inf
36 0.1 0.3333333333333333333333333333333333172839 1.000e-01

The text round-trips: sysl.text.parse_f128 reads a decimal, rounded once to the nearest binary128 value, so every to_string of an f128 parses to the same f128. sysl.fmt.shortest accepts an f128 as it accepts a real.

import sysl.text.parse_f128

val x: f128 = 2 / 7

print(parse_f128(x.to_string()).unwrap().bits() == x.bits())
true

A const computes at f128 too, including in a const function: every step is the exact result rounded once to binary128, as the run-time routines would round it, and the resulting encoding is stored, so third below is binary128’s third, not a widened double‘s:

const third(x: f128) -> f128 = x / 3

const harmonic(n: int) -> f128
    var sum: f128 = 0

    for k in 1..n
        sum = sum + 1 / f128(k)

    sum
end harmonic

const T = third(1)
const H = harmonic(20)

print(T.bits() == 0x3FFD5555555555555555555555555555, H)
true 3.597739657143681911483769068908388

A c const may be declared f128; it is measured as a long double, with every bit kept (ffi). An f128 passes through a variadic ... and is read back with va_arg, by each machine’s own convention. It cannot be a vector lane. C’s long double is not the same as f128: it is binary128 on AArch64 Linux, RISC-V and WebAssembly, a double on Apple’s arm64 and on Windows, and x87’s 80-bit format on x86. A c type measured as "long double" is the one spelling that matches it on every machine.

usize and isize

Pointer-width integers. They are distinct types from every uN, not aliases for u64, because sysl targets 32-bit embedded machines as well as 64-bit hosts.

A length, an index, and sizeof are all usize.

var xs = [10, 20, 30]
var n: usize = xs.len

print(n, xs[1])
3 20

bool

true and false. Nothing converts to bool implicitly, so if x = 0 is a type error: if requires a bool, and an assignment yields the assigned value. No integer is ever a condition. The other way is a written conversion: int(b) is 1 for true and 0 for false, at any integer width (§ Conversions).

char

One Unicode scalar value — a code point up to 0x10FFFF, excluding the surrogate range. It is its own type, an alias of neither u8 nor u32, so a character and a byte remain distinct, as they must in a language with a UTF-8 string. Conversion to u32 is total and written u32(c); conversion from u32 is partial, with a checked form that traps and a fallible form that returns an Option.

unit and never

unit is the type with exactly one value — what a function that returns nothing returns. It is an ordinary type, so a Fn() -> unit needs no special case. Its value is written (), and so is its pattern.

It implements the four traits a tuple does, each in the only way a single value allows: Eq (every () equals every other), Ord (none is less than another), Hash (all hash alike) and Display (it prints as ()). These let a Result[unit, E] or an Option[unit] be compared, printed and passed to assert_eq. A unit occupies no storage, and a unit operand is passed as nothing. A program may implement its own traits for unit too.

enum Fault
    Low

impl Display for Fault
    display(self, out: *Writer, fmt: FormatSpec) = display_str("Low", out, fmt)

check(n: int) -> Result[unit, Fault] = if n > 0 then Ok(()) else Err(Low)

print(check(1) == Ok(()), check(0) == Err(Low), () < ())
print(check(1), check(0))
assert_eq(check(0), Err(Low))
true true false
Ok(()) Err(Low)

() is also the type’s spelling, wherever a type is written: Result[(), E] is Result[unit, E], and -> () returns unit.

done() -> Result[(), string] = Ok(())

val u: () = ()
print(done(), u == ())
Ok(()) true

A unit still has an address. & of a unit binding is a *unit, and a &unit or a weak unit may hold one, as at every zero-sized type: the address is non-null and aligned, a load through it is () and a store writes nothing, so neither touches memory. This is what lets a generic body that takes the address of a T compile at unit like at any other type. C sees a *unit as a void *. An array, a slice or a Buf of unit is accepted and takes no storage: [(); 1000000] has length one million and occupies zero bytes, an element reads as (), and indexing is still bounds-checked. An array of never is refused, as there is no value to fill it with.

through[T](x: T) -> T
    var v = x
    val p: *T = &v
    *p

var u = ()
val p = &u

*p = ()
print(through(()), through(3), *p, usize(p) != 0)
() 3 () true

never is the type with no values: the type of an expression that does not finish. A call to exit has type never, as does a return or a break used as an expression. Because it has no values, never is a subtype of every type, so a match arm that aborts can sit beside arms that produce an int.

never is also an ordinary type argument. Result[T, never] is a result that cannot fail, Option[never] one that is always None, Buf[never] a buffer that stays empty, and a generic function, struct or impl may be instantiated at it. A variant whose payload holds a never — by itself, or through a struct, tuple or enum that must hold one — can never be built, so a match may leave it out; writing the arm anyway stays legal. never implements Eq, Ord, Hash, Display and Debug, vacuously, so a type holding it compares, hashes and prints as its other parts allow. And ? on a Result[T, never] needs no From: its failure path is never taken, so it crosses into a function returning any error type.

enum Error[E] derives Eq, Display
    Io(cause: E)
    Short

enum Fault
    Low

header(n: int) -> Result[int, Error[never]] = if n > 0 then Ok(n) else Err(Short)

doubled(n: int) -> Result[int, never] = Ok(n * 2)

total(n: int) -> Result[int, Fault]
    val d = doubled(n)?
    Ok(d + 1)
end total

header(0) match
    Ok(n) -> print(n)
    Err(Short) -> print("short")

doubled(4) match
    Ok(n) -> print(n)

print(header(3), total(4), header(0) == Err(Short))
short
8
Ok(3) Ok(9) true

Only the argument itself may be never. A part of one — Option[&never], Buf[[2]never] — still names a value of a type that has none, and so does a field, a parameter or a variable that writes never out:

var o: Option[&never] = None
'never' is the type of an expression that does not finish, so it can only be a result type or a type argument

An expression that does not finish is still refused wherever a value must arrive, and a generic parameter is never inferred from one: id(exit(1)) is refused, as val x = exit(1) is. A read of storage whose type is never — the payload an Err arm binds out of a Result[T, never], or a parameter of a body instantiated at never — is not refused: no run reaches it.

Raw pointers

typewhat it is
*Tan address of a T, which promises nothing about what is there
*const Tthe same address, which may be read through and not written

*const T is []const T‘s rule for a pointer: one type with a bit, a *T accepted wherever a *const T is wanted and never the other way round. A C header spells it const T *.

first(p: *const int) -> int = *p

var n = 41

print(first(&n) + 1)
42

The raw tier covers both in full.

string

A validated UTF-8 string, three words wide. It is immutable; indexing it by byte position gives bytes, iterating it gives chars, and + concatenates but rejects a non-string operand. Strings covers it in full — the representation, the validity guarantee, and every form that creates new bytes — and the library operations are under sysl.text.

Fixed arrays and slices

sysl has two sequence types.

typewhat it is
[N]Ta fixed array: N elements, a value, no header, length known while compiling
[]Ta slice: a view of elements someone else owns — { owner, pointer, length }
[]const Ta slice that may be read and not written

An array is its elements, so copying one copies all of them and passing one by value passes the whole thing. A slice names elements that live somewhere else, and copying a slice copies the three-word header rather than the data.

var a = [1, 2, 3]
var b = a

b[0] = 99

var v = a[..]
v[1] = 88

print(a[0], a[1], b[0])
1 88 99

Writing through b did not change a, because b is a copy; writing through v did, because v is a view.

Both carry a length, so every index is checked. Arrays and slices covers them in full — literals, storage sized at run time, the indexing and slicing rules, and what a view keeps alive.

Vectors

A third sequence type, which is a register value rather than storage.

typewhat it is
<N>Ta vector: N lanes of T in a register, whose operators work on every lane at once

It holds the same values an [N]T holds, in the same order; the two type constructors differ only in their brackets because a vector is an array whose operators work lane-wise:

val a: <4>f32 = [1, 2, 3, 4]
val b: <4>f32 = [10, 20, 30, 40]

print((a + b)[3], (a * 2)[0], (a * b).sum())
44 2 300

That + is one instruction performing four additions, and the 2.0 is broadcast into every lane. A lane is read by a constant index, which is checked at compile time rather than at run time. A run of an array or a slice moves into a vector and back with xs.load(i) and xs.store(i, v), which are checked at run time.

A machine with no vector unit needs no special handling: the back end splits a vector across as many registers as it needs, or into ordinary scalar operations, so <4>f32 compiles on every target. Vectors covers them in full — masks and select, the reductions, and writing one kernel that compiles for more than one register width.

Structs

A named product type. Fields are declared one per line, and a struct is a value — assigning one copies it.

struct Point
    x: int
    y: int

var p = Point(1, 2)
var q = p

q.x = 99

print(p.x, q.x)
1 99

A large struct is copied as its bytes. Every copy of a struct, enum or variant payload over 128 bytes — a literal built from calls, an assignment, an argument, a return, a payload bound by a pattern — is a block copy (memcpy) from where the value was read, and reading one field reads only that field. Copying a struct that holds a large array costs what copying the array costs, and the copy is independent: it holds what its source held when it was made.

struct Frame
    pixels: [32768]u8
    id: int

frame(id: int) -> Frame = Frame([u8(id); 32768], id)

struct Pair
    a: Frame
    b: Frame

var p = Pair(frame(1), frame(2))
val kept = p.a

p.a = frame(3)
print(kept.id, kept.pixels[32767], p.a.id, p.b.pixels[0])
1 1 3 2

Structs may carry methods, an invariant, and a visibility modifier per field. A struct may also be declared opaque, which hides its layout from code outside its own module — a separate property from visibility, covered under modules.

A field may be a C bitfield, written name: uW in T — C’s T name : W;. It holds W bits allocated in a unit of T, the type C declares it with, and a struct with any such field is laid out as the target’s C compiler lays its counterpart out. The value type is an integer of W bits, a simple enum, or bool; _: uW in T is an unnamed field and _: in T a zero-width one. The field is read, written, built and matched like any other (attributes has the rules):

struct Status
    ready: bool in u32
    mode: u3 in u32
    _: u4 in u32
    count: i12 in i32

var s = Status(true, 5, -7)

s.count -= 1
print(sizeof(Status), s.ready, s.mode, s.count)
4 true 5 -8

Unions

A union is storage its fields share: every field begins at its first byte, and nothing records which one was written last. It is for the C structures that contain one — in6_addr, epoll_data, SDL_Event, a register read as a word or as its bits. It is declared like a struct, and union is a contextual word, so a function may still be named union.

union In6
    b8: [16]u8
    b16: [8]u16
    b32: [4]u32

var a = In6(b32 = [0, 0, 0, 0])
a.b8[15] = 1

print(sizeof(In6), alignof(In6), a.b32[3])
16 4 16777216

The layout is C’s: the largest field rounded up to the widest boundary among them, every field at offset 0, @packed giving a boundary of one and no rounding, @align(n) raising both. The layout is the same on every target, and @assert(sizeof(U) == …) can state it. A union can be a field, an element or a value like any other: it is copied, passed and returned whole.

A union is built from exactly one field, by name, and the bytes past it are zero. Only the name says which field the value is for, so a value by position is refused even when there is one field; adding a field therefore never changes what an existing construction means. A write to a field stores that field’s bytes and leaves the rest unchanged. Since every field has a zero value, so does the union: all zero bytes.

union Wide
    small: u8
    big: u32

var w = Wide(big = 0x01020304)
w.small = 0xff
print(w.big, Wide(small = 7).big)
16909311 7
union Wide
    small: u8
    big: u32

val w = Wide(7)
union 'Wide' is built from one field, named — 'Wide(small = …)': a value by position would mean another field once one is declared in front of it

Every part of a field is plain data or a raw pointer. A union does not know which field it holds, so nothing could release a counted value: a reference, a string, a slice, a closure, a data enum, a Buf or a type with a drop is refused at the field — or, for a generic union, where the instance is made. An integer narrower than its byte is refused too; a bitfield struct can hold one.

union Name
    s: string
    n: u64
union 'Name' cannot hold its field 's': a string is counted, and nothing in a union says whether one is there to release

A field whose bytes may not be a valid value of its type is checked where it is read. Every bit pattern of an AnyBits field — integers of whole bytes, floats, raw and function pointers, and arrays, vectors and structs of them — is a valid value, so reading one is a plain load. A bool, a simple enum, a char and a subtype with a range or a predicate are not: reading one that holds no valid value (a bool holding 2, an enum holding no variant’s number) traps, and an enum’s trap reports the number it found and where, as a bitfield’s enum field does. Reading a nested field (ev.key.down) checks the part it reads, and reading a whole struct checks each part of it that can be invalid. A ref may not name a checked field, because a read through the name would skip the check while a write to a sibling field changes the bytes under it.

union Key
    raw: u8
    down: bool

var k = Key(raw = 1)
print(k.down)
k.raw = 0
print(k.down)
true
false

A *T field beside an integer converts the integer to a pointer without ptr_cast, as epoll_data and sigval do. Creating that pointer is harmless, since dereferencing any *T is already raw-pointer code, but union … * is a second searchable spelling of the conversion.

A union is AnyBits where every field is, and Plain where every field is both AnyBits and Plain, because a decode cannot know which field’s bytes to check.

What a union does not have, since nothing records which field it holds:

  • no ==: comparing bytes is wrong for a float (+0.0 and -0.0) and for the bytes past a short field. An impl Eq of the program’s own compares the field it knows; derives is refused.
  • no destructuring: a pattern cannot take one apart, though binding one whole is fine.
  • a Debug that shows the bytes: the name and every byte in hex, so showing a union never reads a field and never traps. An impl Debug of the program’s own replaces it.
union Word
    whole: u32
    f: f32

print(Word(f = 1))
Word(00 00 80 3f)
union Word
    whole: u32
    f: f32

val w = Word(whole = 1)
print(w == w)
'==' is not defined for the union Word — comparing its bytes is wrong for a float and for the bytes past a short field. Write 'impl Eq' comparing the field you know is there

A union crosses to C by value and is declared in a generated header as C’s own union; see a union at the boundary.

Anonymous members

Inside a struct or a union, a line that is exactly union or struct opens an anonymous member, as in C11: its fields belong to the enclosing type, so p.word reads one, offsetof(Packet, level) measures one, and a construction names one. It is laid out as C lays it out — where a named field of the same shape would be — and the generated header writes it in place as union { … };. It may close with end union or end struct.

struct Packet
    tag: u8
    union
        word: u32
        level: f32
    len: u16

union Split
    all: u64
    struct
        lo: u32
        hi: u32

var p = Packet(tag = 1, word = 0x3f800000, len = 2)

print(p.level, offsetof(Packet, level), offsetof(Packet, len), sizeof(Packet))
print(Split(lo = 1, hi = 2).all, p)
1 4 8 12
8589934593 Packet(tag: 1, union(00 00 80 3f), len: 2)

A type holding an anonymous member is built by naming its fields: every field a struct holds, and exactly one of each anonymous union. A name may appear only once across all the levels, as in C11. An unnamed bitfield (_: u4 in u32) is never named; it holds zero, as in any struct.

struct Packet
    tag: u8
    union
        word: u32
        level: f32

val p = Packet(tag = 1, word = 7, level = 2)
the anonymous union in 'Packet' is built from exactly one field, and 2 were named — it holds 'word' and 'level'
struct Packet
    tag: u8
    union
        tag: u16
        level: f32
'tag' is declared twice — an anonymous member's fields are its enclosing type's own, so a name appears once across the levels

An invariant also names them without qualification, at any depth. A clause reads a union’s field only when evaluation reaches the name, so a field it does not evaluate is never read: below, raw = 7 is not a valid bool, and the clause is satisfied at tag == 0 without reading ok.

struct Packet
    tag: int
    union
        ok: bool
        raw: u8
    invariant tag == 0 || ok

val p = Packet(tag = 0, raw = 7)
val q = Packet(tag = 1, ok = true)

print(p.raw, q.ok)
7 true

Unions in constant data and with a byte order

A module val built from constants is emitted as static data, with a union in it stored as the bytes of the field it was built with followed by zeros. A register map or a protocol table holding unions therefore costs nothing at start-up and works on bare metal. The same holds for a @packed struct holding a union, at the unaligned offset the struct gives it. A const function may build a union, write a field of it, and read it back through the field it was built or last written with. Compile-time evaluation works on values, not bytes, so a read through another field is refused there (at run time it is an ordinary reinterpreting read).

union Reg
    bits: u32
    level: f32

const make(n: u32) -> Reg = Reg(bits = n)
const bits_of(r: Reg) -> u32 = r.bits
const K = bits_of(make(7))

const rewritten(n: u32) -> u32
    var r = Reg(level = 1)

    r.bits = n
    r.bits

const W = rewritten(5)

val table = [Reg(level = 1), make(9)]

print(K, W, table[0].bits, table[1].bits)
7 5 1065353216 9
union Reg
    bits: u32
    level: f32

const level_of(r: Reg) -> f32 = r.level
const K = level_of(Reg(bits = 7))
evaluation while compiling reads a union only through the field it was built with — this 'Reg' was built with 'bits', and 'level' would read its bytes as another type

@byte_order(big) or (little) on a union orders every integer of every field, as on a struct (@byte_order), including the fields of its anonymous members. sysl prove refuses a union by name, because WhyML has no model of bytes with which to define a read through another field.

Tuples

A product type with no name: a fixed-length, positional group of values, written with parentheses. A struct names its parts; a tuple numbers them.

var p: (int, string) = (1, "one")
var q = (3, 4)

print(p.0, p.1)
print(q.0, q.1)

q.0 = 30
q.1 += 1

print(q.0, q.1)

val a, b = q

print(a, b)
1 one
3 4
30 5
30 5

The example shows the four rules that define the type.

A part is reached by position, t.0 and t.1. It is written like a field because it is one — a tuple’s fields are named for their positions — so a part is a place like any other field, and q.0 = 30 and q.1 += 1 write through it.

The type is inferred from the parts. (3, 4) is a (int, int), and an annotation is needed only where the parts alone do not determine it, as anywhere else.

A tuple is taken apart with the ordinary comma binding, val a, b = q, or with a tuple pattern in a match.

Arity starts at one, and one part needs a comma. (x) is a parenthesized expression, and (T) a type in parentheses; the tuple of one part is written (x,) and its type (T,), as in Rust. There is no zero-tuple; unit fills that role, and () in a type is unit. A trailing comma is allowed after any tuple’s last part, in a value, a type and a pattern alike.

A tuple of one part

A one-tuple is an ordinary tuple: its part is t.0, a place like any other, and it prints, compares, orders and hashes by the same blocks every arity has. It keeps its comma when printed, so it never reads as a grouping:

val t: (int,) = (7,)
val pair = (1, 2,)

print(t.0, t, pair)

t match
    (0,) -> print("zero")
    (n,) -> print(n + 1)

val (a,) = ("one",)

print(a)
7 (7,) (1, 2)
8
one

Its use is where a type stands for a list of parts. A generic that walks T::Fields over a tuple type is handed one part as (Pos,); handed Pos itself it walks Pos‘s own fields, a different question with a different answer:

struct Pos
    x: int
    y: int

parts[Q]() -> usize
    var n: usize = 0

    for const f in Q::Fields
        if sizeof(f::Type) > 0 then n += 1

    n

print(parts[(Pos, Pos)](), parts[(Pos,)](), parts[Pos]())
2 1 2

A type pack matches a one-tuple at arity one, and a written list names a pack of one type directly (generics).

The comma is required: one part in parentheses with none after it is refused, and told both spellings it could have meant.

val x: (int) = 1
'(int)' is a type in parentheses — write 'int' for the type itself, or '(int,)' for a tuple of one part

A nested part needs parentheses

t.0.1 does not select part 1 of part 0, because the lexer reads 0.1 as a floating-point number. The second step is therefore parenthesized:

val t = ((1, 2), 3)

print((t.0).1)
2

The compiler recognizes a float after a . and gives the form to write instead:

val t = ((1, 2), 3)

print(t.0.1)
'.0.1' reads as a number rather than as two tuple indices — write '(x.0).1' to select part 1 of part 0

A tuple is a type; a result list is not

This is the difference between a tuple and a result list. A result list is a property of a signature: several values pass from callee to caller, and nothing holds them together afterwards. A tuple is a type — it can be stored in a variable, held in a field, put inside an Option, made the element of a container, and named as a generic argument.

list(n: int) -> int, int = n / 2, n % 2

pair(n: int) -> (int, int) = (n / 2, n % 2)

val a, b = list(7)
val c, d = pair(7)

val held = pair(9)

print(a, b, c, d, held.0, held.1)
3 1 3 1 4 1

-> int, int and -> (int, int) look alike but mean different things. In most code the caller does not need to know which one it is calling, because val a, b = f(x) takes either apart. The choice is the callee’s, and changing it breaks only call sites that store the pair. Only the tuple can be held, as held shows.

Use a result list when the values do not need to stay together, and a tuple when they do.

What the library gives every tuple

Eq, Ord, Hash and Display are provided structurally, at every arity, whenever every component implements the trait. Ordering is lexicographic, first component first. unit, the tuple with no parts, has the same four (unit and never).

val pair = (1, "one")
val trip = (1, 2.5, 'x')

val o = Some(("k", 7))

o match
    Some((k, v)) -> print(k, v)
    None -> print("none")

print(pair)
print(trip)
print(pair == (1, "one"), (1, 2) < (1, 3))
print(sizeof((u8, u8, u8)))
k 7
(1, one)
(1, 2.5, x)
true true
3

None of these implementations is generated by the compiler. They are ordinary impl blocks in the standard library, written once over a type pack: a (..A) matches a tuple of any arity, so four blocks cover every tuple.

The last line of the example shows the layout rule: a tuple is laid out as a struct with those fields in that order, so (u8, u8, u8) is three bytes, and a tuple holding a &T retains and releases it exactly as a struct field does.

Who may implement what

Each arity is its own type, so an impl for a pair says nothing about a triple. A trait of your own may be implemented for a tuple, because the trait is local, which the coherence rule permits:

trait Tag
    tag(self) -> string

impl Tag for (int, string)
    tag(self) -> string = "pair"

print((1, "a").tag())
pair

impl Eq for (int, string) is refused by the ordinary coherence rule: a tuple type has no declaration and therefore no module of its own, and a built-in type belongs to the library. Both the trait and the type are therefore foreign, which coherence forbids:

impl Eq for (int, string)
    eq(self, rhs: (int, string)) -> bool = true

print(1)
an 'impl' may be written only in the module that declares the trait or in one that declares a type the block names, and 'Eq' is the library's while nothing in '(int, string)' is declared outside the library — so this one has no home. A trait of your own, or a type of your own in what it is written for or in the trait's arguments, gives it one

Enums

One keyword declares two kinds of type. A simple enum is a set of named discriminants with an underlying integer type; a data enum gives its variants payloads, making it a sum type.

enum Color
    Red
    Green
    Blue

enum Shape
    Circle(r: real)
    Rect(w: real, h: real)

area(s: Shape) -> real = s match
    Circle(r)  -> 3.14159 * r * r
    Rect(w, h) -> w * h

print(int(Green), area(Circle(1)), area(Rect(2, 3)))
1 3.14159 6

Option[T] and Result[T, E] are ordinary data enums declared in the standard library, with no special treatment by the compiler, so an enum you write works the same way.

A variant that carries a payload is constructed, never named on its own. Written without its values it is neither a value of the enum nor a function that makes one. A position that expects the enum does not change this, because it determines which enum is meant, not what the variant holds:

enum Shape
    Circle(r: real)
    Dot

val shapes: []Shape = [Shape.Dot, Shape.Circle]

print(shapes.len)
variant 'Circle' carries data — construct it with 'Circle(…)'

A variant belongs to its enum

Two enums in one module may each have a variant named Circle, and neither has to be renamed. What a bare name means is decided where it is used, by the type expected there — an argument, an annotated binding, a return and a field all supply one, so the short form is the usual one:

enum Shape
    Circle(r: int)
    Square(side: int)

enum Hole
    Circle(r: int)
    Slot(len: int)

area(s: Shape) -> int = s match
    Circle(r)    -> 3 * r * r
    Square(side) -> side * side

depth(h: Hole) -> int = h match
    Circle(r) -> r
    Slot(len) -> len

val s: Shape = Circle(2)

print(area(s), depth(Circle(5)))
12 5

Where two enums match and nothing says which is meant, the compiler reports it rather than choosing one, so a line’s meaning cannot change when an unrelated enum is added elsewhere:

enum Shape
    Circle(r: int)
    Square(side: int)

enum Hole
    Circle(r: int)
    Slot(len: int)

var s = Circle(1)

print(1)
'Circle' is a variant of 'Shape' and 'Hole', and nothing here says which — qualify it, as 'Shape.Circle'

That line should be Shape.Circle(1). The qualified form works at a construction exactly as it works in a pattern.

Where no type is expected, a neighbour or the variant’s own payload can still say which enum is meant. A branch of an if, an arm of a match or an element of an array literal whose variant belongs to one enum alone settles its siblings, and a construction whose payload fits only one of the candidates — by the number of values, their names or their types — is that candidate’s. A bare name fits only a variant that carries nothing:

enum Value
    Null
    Bool(b: bool)
    Int(n: int)

enum Expr
    Null
    Bool(b: bool)
    Interval(lo: int, hi: int)

enum Span
    Interval(lo: int, hi: int, step: int)
    Point(at: int)

name(v: Value) -> string = v match
    Null    -> "null"
    Bool(b) -> "bool"
    Int(n)  -> "int"

steps(s: Span) -> int = s match
    Interval(lo, hi, step) -> (hi - lo) / step
    Point(_)               -> 0

val c = true
val v = if c then Null else Int(1)
val vs = [Bool(true), Null, Int(2)]
val spans = [Interval(0, 10, 2)]

print(name(v), name(vs[1]), steps(spans[0]))
null null 5

Int is Value‘s alone, so Null beside it is Value‘s too; Interval(0, 10, 2) carries three values, which only Span‘s Interval holds. Each rule answers only where exactly one enum fits, so adding an enum that fits as well brings the refusal back rather than changing what a line means. Where every candidate fits — if c then Null else Bool(true) here, since both enums have both — the refusal names them all.

The expected type works across modules too, so a program may declare a variant whose name the library also uses. Result and Option are in the prelude, so Ok, Err, Some and None are the names most likely to collide with your own enums, and a module that declares its own Ok can still return a Result:

enum Status
    Ok
    Bad

f() -> Result[int, string] = Ok(1)
g() -> Result[int, string] = Err("no")

s() -> Status = Ok

print(f().unwrap(), g().is_err(), s() == Ok)
1 true true

Each Ok resolves to the variant of the type expected on its line: the library’s where the expected type is the library’s, and the module’s own where it is the module’s. At a position that expects a Result but means the module’s variant, write Status.Ok.

An enum imported by name makes its variants available bare in the same way, at every position that expects it, including inside an Err or a Some. Here only the enum is imported, none of its variants:

import sysl.fs.IoError

open_it(there: bool) -> Result[int, IoError]
    if !there then return Err(NotFound)
    Ok(3)

val clash: IoError = AlreadyExists

print(open_it(false).unwrap_err().code(), clash.code(), open_it(true).unwrap())
2 17 3

A name the file already uses for something else — its own function NotFound(), say — keeps that meaning, and an enum the file has not imported contributes no bare names; sysl.fs.IoError.NotFound is the spelling that needs no import. A pattern needs no import either: its bare names are read against the scrutinee’s own enum by the bare-name rule, so Err(NotFound) -> matches what read_text answers in a file that imports only read_text.

As in Rust, a variant is namespaced under its enum; unlike Rust, a use site does not need Shape::Circle or a use Shape::*.

A variant may share its name with a constant, a val, a module var or an extern variable. The two are separate lookups: the name is the variant where the position expects the variant’s enum — a pattern included, whose scrutinee is the expected type — and the value everywhere else, a position that expects no type at all among them. A call is the variant wherever the value could not be called:

enum Clause
    Limit(n: int)
    Top
    Where

const Limit: int = 10
const Top = 5

pick(c: Clause) -> int = c match
    Limit(n) -> n
    Top      -> 1
    Where    -> 0

val c: Clause = Top
val k: int = Top

print(pick(c), k, Limit + 1, pick(Limit(3)), c is Top)
1 5 11 3 true

Clause.Top is the variant wherever the position does not ask for a Clause.

Type aliases

type Name = Existing introduces a second name for a type, interchangeable with the first. It creates no new type and no checking: an alias shortens a long name; it does not distinguish two uses of the same representation.

The base may be any type, which matters most for compound types, whose names are the long ones:

struct Point
    x: int
    y: int

type P = Point
type Comparison = *extern(*u8, *u8) -> i32
type Triple = [3]int
type MaybeInt = Option[int]

val p: P = P(3, 4)
var t: Triple = [1, 2, 3]
val m: MaybeInt = Some(t[2])

print(p.x + p.y, m.unwrap())
7 3

Because an alias is a name and not a type, everything the base has is available through it: a value of one name is accepted where the other is expected, a struct is constructed and read through the alias, and a method or trait implementation declared on the base applies to the alias unchanged.

How a diagnostic names a type

A diagnostic names a type the way the declaration it points at wrote it. The spelling is carried beside the type rather than in it, so u16 and ushort, or MaybeInt and Option[int], stay one type to every check; only the message differs. Where the spelling names an alias that reads differently from the type it stands for, the message adds the real type after aka:

type Celsius = real

val boiling: Celsius = 100.0
val s: string = boiling
declared string but the value is Celsius (aka real)

Which spelling a message shows:

  • A declared type — a binding’s annotation, a parameter, a struct field, a function’s result — is quoted as that declaration wrote it: val x: u16 is called u16, and val y: ushort is called ushort.
  • A value is quoted as the declaration it was read from wrote it: a local by its binding, a call by its function’s declared result, a field by the struct’s declaration of it, module storage by its annotation. A local binding with no annotation takes the spelling of the value it was initialised from.
  • Where two spellings meet — a: u16 given to b: ushort, a Buf[P] where a Buf[Point] is wanted — each side keeps its own: the expected side is the declaration’s, the given side the value’s.
  • Everything else is shown canonically: a value with no declaration behind it (a literal, an arithmetic result, a method’s result, module storage written with no type), and a written type that names a type parameter, so a generic’s T at a call is shown as the type it was instantiated with. The canonical name of a width that has a built-in alias is that alias (int, ushort, real).

aka is shown only for an alias declared with type, and only where its expansion is spelled differently: P (aka Point), Cb (aka Fn(int) -> int), an alias of an alias by the type at the bottom of the chain. A built-in width name is never an alias for this purpose — ushort and u16 are both the type’s own names, so neither earns an aka.

type P = Point

struct Point
    x: int

takes(p: P) -> int = p.x

val q: u16 = 1
val r = takes(q)
'p' of 'takes' is P (aka Point), but u16 was given

A distinct type — one the compiler will not let you confuse with its base — is a constrained type, written with new and covered under contracts. A new type may take type parameters that change which type it is but not how it is laid out: UserPtr[Frame] and UserPtr[u8] over type UserPtr[T] = new u64 are two types, both a u64 underneath (declarations).

Function types

A callable’s type is written with Fn:

apply(f: &Fn(int) -> int, x: int) -> int = f(x)

print(apply(n -> n * 3, 7))
21

A named function used where a callable is expected is the capture-free case of the same type; there is no separate function-pointer concept. A raw C function pointer, for a foreign boundary, is written *extern(A) -> R and is covered under the foreign interface.

A generic function may be named with its type arguments there too, as at a call: echo[int] is the copy for int, and its arguments are checked against the callable’s as the call echo[int](x) would check them.

echo[T](x: T) -> T = x
pair[A, B](a: A, b: B) -> (A, B) = (a, b)

apply(f: &Fn(int) -> int, x: int) -> int = f(x)

val g: &Fn(string, int) -> (string, int) = pair[string, int]

print(apply(echo[int], 7), g("x", 2).0)
7 x

A type’s member named through the type is a value there too. An associated function, S.make, is the function it is; Box[int].make and S.pick[int] name a copy as the call would. A method’s receiver becomes its first parameter, taken exactly as the method declares it — S.get over get(self) takes an S, S.bump over bump(*self, …) a *S, a &self method an &S — so a callable giving that parameter another form or another type is refused rather than calling some other member of the name. A type parameter’s member is reached the same way, T.make, through its bound. A trait’s own name reaches nothing: its member is reached through a type that implements it.

struct Counter
    n: int

impl Counter
    start(n: int) -> Counter = Counter(n)
    get(self) -> int = self.n
    bump(*self, by: int) -> int
        self.n += by
        self.n

apply[T](f: &Fn(T) -> int, x: T) -> int = f(x)

val make: &Fn(int) -> Counter = Counter.start
val bump: &Fn(*Counter, int) -> int = Counter.bump
var c = make(1)

print(bump(&c, 4), apply(Counter.get, c))
5 5
struct Counter
    n: int

impl Counter
    bump(*self, by: int) -> int = self.n + by

val f: &Fn(Counter, int) -> int = Counter.bump
'Counter.bump' takes its receiver as '*Counter', and as a value the receiver is its first parameter

A parameter written with a bare arrow is a type parameter. f: A -> B is shorthand for [$F: Fn(A) -> B](f: $F): the closure’s type is a type argument, so the function is monomorphized and calls the closure directly, with nothing on the heap. f: &Fn(A) -> B is a counted reference to a trait object, so the closure is boxed at the call — in the caller’s frame where nothing keeps it past the frame (closures), on the heap otherwise — and dispatched through a table. Both accept the same closures; they differ in what the call costs and in what the declaration compiles to.

Parentheses before the arrow are its parameter list, whatever its length: (string) -> usize is the same type as string -> usize, () -> T takes nothing, and ((int, int)) -> int takes one tuple. Only the arrow makes them a list — (string) with none after it is a type in parentheses, and refused. A comma before the arrow is the list’s own, so (string,) -> usize takes one string too, and a callable taking a tuple of one part writes it in a second pair, ((string,)) -> usize.

apply(f: (string) -> usize, s: string) -> usize = f(s)
sum(f: ((int, int)) -> int) -> int = f((3, 4))

print(apply(t -> t.len, "four"), sum(t -> t.0 + t.1))
4 7

A trait member may use either, with one further consequence: an arrow makes the member declare a type parameter, so it gets no table slot and cannot be dispatched through a trait object (traits). A trait meant for trait objects uses &Fn(…); one meant for static dispatch can use the arrow.

trait Applies
    tag(self) -> int
    apply(self, f: int -> int) -> int

struct N
    v: int

impl Applies for N
    tag(self) -> int = self.v
    apply(self, f: int -> int) -> int = f(self.v)

reach[T: Applies](x: T) -> int = x.apply(n -> n * 2)

print(N(20).apply(n -> n + 1), reach(N(21)))
21 42

A parameter the callable may keep: @keeps

A callable borrows what it is handed for the call, as a C function does, so a closure that stores a pointer it was handed is refused (memory). @keeps in front of a parameter of the type says the callable may keep it, exactly as an extern‘s @keeps(p) says it of a C function. It is written in Fn(…), in a bare arrow’s parameters, and through an alias, a generic type and a struct field like any other part of the type:

import sysl.buf.{Buf, buf}

struct Handle
    n: int

type Step = &Fn(@keeps *Handle) -> int

var seen: Buf[*Handle] = buf()
var a = Handle(4)
var b = Handle(6)

each(body: @keeps *Handle -> unit)
    body(&b)

val f: Step = (h) ->
    seen.push(h)
    h.n

print(f(&a))
each(h -> seen.push(h))
print(seen.len(), seen[1].n)
4
2 6

The mark is part of the type. A callable that keeps nothing stands wherever a marked one is asked for; a marked one never stands where the parameter is borrowed, since a call through that type may hand it the address of its own storage:

type Step = &Fn(@keeps *int) -> int
type Loose = &Fn(*int) -> int

widen(f: Loose) -> Step = f
narrow(f: Step) -> Loose = f
a '&Fn(@keeps *int) -> int' may keep its parameter 1 past the call, and a '&Fn(*int) -> int' borrows what it is handed for the call

A mark on a parameter that holds no address — an int — changes nothing, as it does on an extern. What a call through a marked type may be handed is in memory.

A function pointer type takes the mark too, with the same meaning: *extern(@keeps *Heap) -> unit is the type of a pointer to a function that may keep its parameter, and a function whose address is taken at it may. The mark is part of that type as well, and is named in no symbol:

type Roots = *extern(@keeps *int) -> unit
type Loose = *extern(*int) -> unit

widen(f: Loose) -> Roots = f
narrow(f: Roots) -> Loose = f
a '*extern(@keeps *int) -> unit' may keep its parameter 1 past the call, and a '*extern(*int) -> unit' borrows what it is handed for the call

What the callable reads may outlive the call: @lets_out

@lets_out is the narrower mark: the callable may let out what it reads through the parameter, but does not keep the parameter itself. It is written where @keeps is, on a callable’s type or a function pointer type. A collector’s root hook is the shape it is for: the hook puts what it finds into the heap it is handed, so the heap may live in the caller’s frame:

struct Node
    next: *Node
    v: int

struct Heap
    gray: *Node

type Roots = *extern(@lets_out *Heap) -> unit

var root = Node(null, 7)

roots(h: *Heap)
    root.next = h.gray
    h.gray = &root

collect(h: *Heap, r: Roots)
    r(h)

main()
    var h = Heap(null)
    collect(&h, &roots)
    print(h.gray.v)
7

@keeps says all @lets_out does and more, so the three marks stand in order: an unmarked callable stands where a @lets_out one is asked for, and a @lets_out one where a @keeps one is, never the other way:

type Hard = *extern(@keeps *int) -> unit
type Roots = *extern(@lets_out *int) -> unit

widen(f: Roots) -> Hard = f
narrow(f: Hard) -> Roots = f
a '*extern(@keeps *int) -> unit' may keep its parameter 1 past the call, and a '*extern(@lets_out *int) -> unit' lets out only what it reads through it, never the parameter itself

What a call through a @lets_out type may be handed is in memory.

A parameter passed by name

A parameter written with the arrow and nothing on its left takes an expression the call does not evaluate, and the body evaluates at each use:

static var built: int = 0

message() -> int
    built += 1
    42

log(on: bool, m: -> int)
    if on then print(m)

log(false, message())
log(true, message())
print(built)
42
1

message() ran once, not twice: the first call never evaluated its argument. This makes an argument the callee may not use free to pass.

Each use is an evaluation, because each use is a call, so a body that names the parameter twice evaluates the argument twice. To evaluate it once, bind it to a val first.

The same holds inside a closure or a nested function in the body: the parameter is still read by name, and the argument is evaluated each time the closure is called rather than once when the closure is created.

static var built: int = 0

message() -> int
    built += 1
    built * 10

show_twice(m: -> int)
    val show = () -> print(m + 1)
    show()
    show()

show_twice(message())
print(built)
11
21
2

It has no run-time overhead. x: -> T has the type Fn() -> T, so it compiles to a bounded type parameter exactly as the ordinary bare arrow does: one specialized copy per call site, called directly, with no allocation.

x: () -> T is a different form. It has the same type, but the caller writes the callable itself and the body calls it:

twice(f: () -> int) -> int = f() + f()

print(twice(() -> 21))
42

Search

Esc
↑↓ to navigate ↵ to open Esc to close