Spec chapters

7. Expressions

Precedence, lowest first; binary operators are left-associative except comparisons, which cannot be chained (a < b < c is E002), and &, | and ^, which cannot be mixed without parentheses (a | b & c is E002; a | b | c is fine):

Level Operators Operand types Result
1 e catch f, e orelse f !T / ?T, fallback T T (section 13)
2 or bool bool
3 and bool bool
4 == != both the same number type, bool, str, enum, pointer or function type; or both text (str, []u8, Buf(u8); section 8) bool
4 < <= > >= both the same number type; or both text (str, []u8, Buf(u8); section 8) bool
5 & \| ^ both the same integer type that type
6 << >> an integer, shifted by any integer type the left side’s type
7 + - both the same number type that type
7 +% -% both the same integer type that type
8 * / both the same number type that type
8 % *% both the same integer type that type
9 unary -, !, ~, try, & signed integer or float / bool / integer / !T / place  
10 a.f, a.m(...), a.*, a[i], a[lo..hi], calls    
  • and / or short-circuit: the right side is evaluated only if needed.
  • Bitwise operators bind tighter than comparisons, so x & 1 == 0 is (x & 1) == 0, and + tighter than a shift: 1 << n + 1 is 1 << (n + 1). A literal on the left of a shift takes the type the context expects (const m: u8 = 1 << 7).
  • Structs, unions and arrays cannot be compared with == (E103).
  • Evaluation is left to right. Operands and arguments are evaluated in the order they are written, so f() + g() always calls f first, and in f(x, bump(&x)) the first argument is the value of x before bump changes it. An operand may not borrow what a later or earlier one changes through an inout argument of a call inside it, or moves into a sink parameter of one (first(b[0..], grow(a, &b)), b == grow(a, &b), first(b[0..], eat(a, b)); E117): the borrow would see the buffer before a resize, or after a free. Read values are copies, so @len(b) + @len(grow(a, &b)) and @len(b) + eat(a, b) are fine.

if with a value

if (c) a else b is an expression: a when the bool c is true, else b, and only the chosen branch is evaluated. Both branches are expressions, without braces, and the else is required (E002 otherwise, and for a block in place of a branch); else if chains. An if that starts a statement is the if statement (section 6). The else branch reaches as far as an expression goes, as in Zig: if (c) 1 else 2 + 3 is if (c) 1 else (2 + 3).

The branches have one type: the type the context expects, or else the first branch’s; a literal (5, .red) takes the other branch’s type, so if (c) 1 else x is x’s type (E103 when they differ). null still needs a ?T or pointer from the context: const m: ?i64 = if (c) x else null. The result must be a value, not void or a type (E103).

An if may yield a slice when its branches are slices or text (if (c) b[1..] else ""): it views what either branch does, so it goes where a slice may (a local const, an argument, a for, a function’s result) and borrows both branches’ variables like a slice of each (E149, E151).

An owned value moves out of the branch that makes or names it, and the branches must agree on what they move (E134), as the branches of an if statement do: if (c) b else d moves only one of two buffers, so it is E134; use an if statement that also frees the other one. An if with an owned value cannot be borrowed from (n(if (c) b else d) with a plain Buf parameter, for (if (c) b else d): E133), since it would hide which variable is held; slice the branches instead (if (c) b[0..] else d[0..]), which borrows both.

// expect: -1
// expect: green
// expect: 99
// expect: ello
// expect: 2
uses alloc, io

const Color = enum { red, green }

fn name(c: Color) str {
    return if (c == .red) "red" else "green"
}

// A slice result: what either branch views.
fn rest(s: []u8, n: i64) []u8 {
    return if (n < @len(s)) s[n..] else ""
}

fn main(io: Io, a: Allocator) void {
    const x: i64 = -3
    io.print(if (x < 0) -1 else 1)
    io.print(name(if (x > 0) .red else .green))
    const m: ?i64 = if (x > 0) x else null
    io.print(m orelse 99)
    const b = a.concat("hel", "lo")
    defer a.free(b)
    io.print(rest(b, 1))
    const xs = [3]i64{ 1, 2, 3 }
    const tail = if (x < 0) xs[1..] else xs[0..]
    io.print(@len(tail))
}

Integer types

i8, i16, i32, i64 are signed and u8, u16, u32, u64 unsigned, of that many bits; usize is unsigned and as wide as a pointer. Indexes, lengths (@len) and for indexes are i64; the bytes of a str are u8.

Both operands of an arithmetic or ordering operator must have the same type (E103): nothing converts implicitly. A literal takes its type from the other operand or from what the context expects, and is i64 when nothing says otherwise:

// expect: 255
// expect: 248
// expect: 125
uses io

fn main(io: Io) void {
    const x: u8 = 200        // the literal is a u8
    io.print(x + 55)        // so is 55
    const n = 1000           // i64
    io.print(@as(u8, n / 4 - 1) - 1)
    const big = n > 10
    io.print(@as(u8, if (big) n / 8 else n))
}

@as(T, x) converts the integer x to the integer type T, and panics integer cast out of range if the value does not fit. Only literals, and arithmetic on literals only, take T as their type (@as(u8, 300) is E003, and @as(f64, 1 / 2) is 0.5); any other x, such as an if whose branches are i64, keeps its own type and is converted. Negating an unsigned value is E103.

Floating-point types

f32 and f64 are IEEE 754 single and double precision. A literal with a fraction or an exponent (1.5, 2e10, 6.02e-23) is a float: f64, or f32 where the context wants one. An integer literal also becomes a float where one is expected, so x * 2 with x: f64 needs no 2.0; a fraction never becomes an integer. A literal that does not fit its type (1e400, or 1e39 as an f32), or that is not zero but rounds to zero (1e-400), is E003.

Float arithmetic follows IEEE 754 and never panics: 1.0 / 0.0 is inf, 0.0 / 0.0 is nan, and results round to the nearest value. That is defined behaviour, not overflow. There is no % on floats (declare C’s fmod, section 20). @as converts between any two number types: to a float it rounds to the nearest value; from a float to an integer it truncates toward zero and panics float cast out of range if the result does not fit, or the value is nan or infinite.

io.print and a.float_str(x) write the shortest decimal that reads back as the same value; a finite value always has a . or an exponent: 0.1, 3.0, 1e+16, 1.5e-07. The others are nan, inf and -inf.

// expect: 0.30000000000000004
// expect: 3.5
// expect: 1e+16
// expect: 0.1
// expect: inf
// expect: -7
// expect: 0.5
uses io

fn half(x: f64) f64 {
    return x / 2
}

fn main(io: Io) void {
    io.print(0.1 + 0.2)
    io.print(half(7))
    io.print(1e16)
    const f: f32 = 0.1
    io.print(f)
    const zero = 0.0
    io.print(1 / zero)
    io.print(@as(i64, -7.9))
    io.print(@as(f64, 1 / 2))   // literals: divided as f64
}
// panic: float cast out of range
uses io

fn main(io: Io) void {
    const big = 1e10
    io.print(@as(i32, big))
}
// error: E103
uses io

fn main(io: Io) void {
    const n = 3
    io.print(1.5 * n)       // i64 and f64: convert n with @as(f64, n)
}

Integer arithmetic is checked

Outside allow unsafe code (section 18, the one place it can arise), Egg has no undefined behaviour. Every checked arithmetic operation (+ - * / %, unary -), in every integer type, either produces the mathematically correct result or stops the program with a panic; the wrapping ones (+% -% *%) give the result modulo 2^N; bitwise operations work on the value’s bits in two’s complement and are defined for every input except a shift amount out of range:

Operation Result
a + b, a - b, a * b, -a exact result, or panic integer overflow (for unsigned types, also when a - b is negative)
a +% b, a -% b, a *% b the result modulo 2^N for the type’s N bits, as two’s complement for a signed type: it wraps around and never panics (@as(u8, 200) +% 100 is 44, @as(i16, 200) *% 200 is -25536)
a / b quotient truncated toward zero; panic division by zero if b == 0; panic integer overflow for the minimum value of a signed type divided by -1
a % b remainder with the sign of a (so a == (a / b) * b + a % b); panic division by zero if b == 0; the minimum value % -1 is 0
a & b, a \| b, a ^ b, ~a and, or, xor and not of each bit; never panic
a << n the bits of a moved up n places, the ones shifted out dropped (@as(u8, 0x81) << 1 is 2); panic shift out of range unless 0 <= n and n is below the bit width of a’s type (E003 for a literal n)
a >> n the bits moved down n places, bringing in zeros, or ones for a negative a (-16 >> 2 is -4); the same range for n

Indexing and slicing are checked too: panic index out of bounds or slice out of bounds. A panic prints egg panic: <message> to standard error and aborts the process with a non-zero status.

// expect: -3
// expect: -1
// expect: 3
// expect: 1
uses io

fn main(io: Io) void {
    io.print(-7 / 2)
    io.print(-7 % 2)
    io.print(7 / 2)
    io.print(7 % -2)
}
// panic: integer overflow
uses io

fn main(io: Io) void {
    const big = 9223372036854775807
    io.print(big + 1)
}

Wrapping arithmetic, +%, -% and *%, is for code whose definition says modulo 2^N, such as hashes and ciphers; elsewhere + - * catch the mistake instead. A top-level constant cannot use it (E150): constant arithmetic is exact, on i64, with no type width to wrap at.

// expect: 44 255 0
// expect: -25536 127
// expect: 16088033396387240377
uses io

fn main(io: Io) void {
    const a: u8 = 200
    const b: u32 = 0xFFFF_FFFF
    io.print(a +% 100, " ", a -% 201, " ", b +% 1)
    const c: i16 = 200
    const d: i8 = -128
    io.print(c *% c, " ", d -% 1)
    const golden: u64 = 0x9E37_79B9_7F4A_7C15
    io.print(golden *% golden)
}
// error: E150
uses io

const K = 0xFFFF_FFFF +% 1  // constant arithmetic is exact: write 0x1_0000_0000, or compute it in a function

fn main(io: Io) void {
    io.print(K)
}
// expect: 10 207 53
// expect: 2 -4 false
// expect: 128
uses io

fn main(io: Io) void {
    const a: u8 = 0b1100_1010
    io.print(a & 0x0f, " ", a | 0x0f, " ", ~a)
    io.print(@as(u8, 0x81) << 1, " ", -16 >> 2, " ", a & 1 == 1)
    const m: u8 = 1 << 7
    io.print(m)
}
// expect: 1
// expect: 2
// expect: 3
uses io

fn one(io: Io) i64 {
    io.print(1)
    return 1
}

fn two(io: Io) i64 {
    io.print(2)
    return 2
}

fn main(io: Io) void {
    io.print(one(io) + two(io))
}