Docs · Language

Expressions

This page lists every expression form: literals and aggregates, field access, calls, indexing, casts, the prefix operators, the control-flow forms that give a value, and try and catch. Guides 04, Functions and closures and 05, Control flow introduce most of them; tokens are in lexical.

Precedence and associativity

The precedence table for the operators, and the method each one calls, are in the operators reference. The forms that are not in that table:

  • try e and known e are prefix operators, at the level of prefix -: try f() + 1 is (try f()) + 1.
  • catch takes everything after it, to the end of the expression, as the fallback: f() catch 5 + 1 falls back to 6. Use parentheses when a catch is part of a larger expression: (f() catch 5) + 1.
  • Pattern shapeof subject sits at the level of ==, so Some(_) shapeof o && ready is (Some(_) shapeof o) && ready.

Literals

Integer, float, bool, char, string, and template literals are defined in lexical. A number literal takes the type its context asks for, i32 or f64 when nothing asks, and a literal that doesn't fit that type is a compile error. A string literal is a [*con]u8.

Identifiers

A name evaluates to what it is bound to: a value, a function (a function is a value), or a type (a type is a known value). Names resolve by lexical scope with shadowing. fn, type, and the other declarations are visible throughout their scope, while a con or mut is visible from its line down (statements, blocks and scope).

Tuple and array literals

(a, b) builds a tuple, and () is the unit value. A single parenthesised expression is grouping, not a tuple: a tuple has two or more elements, or none.

An array literal writes the type and then the elements, [N]T[e0, e1]. Empty brackets fill the array with zeros:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    con pair = (40, true)
    con prices = [3]i32[10, 20, 30]
    con counts = [4]u8[]
    println(pair.0)      // prints 40
    println(prices[1])   // prints 20
    println(counts[3])   // prints 0
    return Ok(0)
}

Struct literals

T{ field: value, ... } builds a struct. Every field gets a value, written in the literal or from the field's default; nothing is zero-filled. Fields are matched by name, in any order.

Where the expected type is already a struct type, _{ ... } builds that type: the expected type comes from a declared type, a parameter, a return type, or a field.

Vyi
import { println } from "@fmt"

struct Point { x: i32, y: i32 }

fn norm1(p: Point) i32 { return p.x + p.y }

fn main() !u8 {
    con a = Point{ y: 2, x: 1 }
    con b: Point = _{ x: 3, y: 4 }
    println(a.x)                     // prints 1
    println(b.y)                     // prints 4
    println(norm1(_{ x: 5, y: 6 }))  // prints 11
    return Ok(0)
}

A field name can be a dynamic identifier, [expr], whose value is a known string (known values).

Enum construction

A variant with a payload is constructed by calling it with the payload values. A variant without a payload is written by name. Enum.Variant always works; the bare Variant works wherever the expected type names the enum: a declared type, an argument, a return, or a match or switch subject. Some, None, Ok, and Err follow the same rule.

Vyi
import { println } from "@fmt"

enum Shape { Dot, Circle(i32), Rect(i32, i32) }

fn area(s: Shape) i32 {
    return match s {
        Dot:        0,
        Circle(r):  3 * r * r,
        Rect(w, h): w * h,
    }
}

fn main() !u8 {
    con wheel = Shape.Circle(2)
    con door: Shape = Rect(2, 3)
    println(area(wheel))   // prints 12
    println(area(door))    // prints 6
    println(area(Dot))     // prints 0
    return Ok(0)
}

With no expected type there is nothing to resolve a bare variant against, so con o = Some(5) is an error (`cannot infer enum constructor type from the surrounding code`).

When the expected type is a union of enums, a bare variant is the variant of the one member enum that declares it, and the value becomes that member. A name that several member enums declare is an error, whatever the order of the union's members; write the enum's name:

Vyi
import { println } from "@fmt"

enum Fan   { Off, Low }
enum Light { Off, On }

fn isFanOff(device: Fan | Light) bool {
    return device == Fan.Off
}

fn main() !u8 {
    con fan: Fan | Light = Low
    con lamp: Fan | Light = Light.Off
    println(fan == Low)          // prints true
    println(isFanOff(lamp))      // prints false
    return Ok(0)
}
Vyi · does not compile
enum Fan   { Off, Low }
enum Light { Off, On }

fn main() !u8 {
    con a: Fan | Light = Off   // error: `Off` is a variant of more than one member of this union
    return Ok(0)
}

Field access

  • x.f reads the field f.
  • Through a pointer, strict or *c_ptr, field access dereferences one level: p.f, not (*p).f. Each . looks through one pointer, so a pointer to a pointer needs an explicit *.
  • Tuple elements are fields named by position: t.0, t.1, and t.0.1 for a nested tuple.
  • An array pointer [*con]T or [*mut]T has the fields .len and .ptr. A fixed array [N]T has .len, the known value N.
  • From another file, a field is readable only when it is pub (guide 03).

A method is not a field. x.method(args) calls it, and x.method without the argument list is an error. To pass behavior around, use a function's name or an arrow expression (guide 04).

Calls

callee(arg, ...) passes arguments by position, evaluated left to right. A trailing comma is allowed, and the argument list may span lines after the (.

Defaults. A parameter declared with = expr may be left out, from the end of the list only, since arguments are positional:

Vyi
import { println } from "@fmt"

fn area(width: i32, height: i32 = width) i32 {
    return width * height
}

fn main() !u8 {
    println(area(3))      // prints 9
    println(area(3, 4))   // prints 12
    return Ok(0)
}

The default is evaluated at each call that leaves the argument out, after the arguments before it. It may name the parameters to its left (height: i32 = width, cap: i32 = sizeof T), never itself or a later one. Every other name in it resolves where the function is declared, not at the call.

Overloads. Several functions may share a name when their parameter types differ. A call picks the one whose parameters match its arguments: by number of arguments, then by their types, with a method's receiver counted as a parameter. When no single candidate matches best, the call is an ambiguity error.

Vyi
import { println } from "@fmt"

fn describe(n: i32) [*con]u8 { return "number" }
fn describe(flag: bool) [*con]u8 { return "flag" }
fn describe(a: i32, b: i32) [*con]u8 { return "pair" }

fn main() !u8 {
    println(describe(7))       // prints number
    println(describe(true))    // prints flag
    println(describe(1, 2))    // prints pair
    return Ok(0)
}

Which functions overload one another. A call's name resolves like any name, to the innermost scope that binds it, and the functions of that name in that scope are the candidates:

  • In a file's scope: the file's own top-level functions of that name, and every function each import of the name brings in. An import brings the whole set its source exports under that name, re-exports included.
  • A function without export is invisible to other files, so two files' private functions of one name never meet.
  • In a block, including a function body: the block's own fn declarations of that name, which overload one another as top-level functions do.
  • A binding of the name in an inner scope (a parameter, a local, a local fn) hides every outer function of that name.
  • The names every file sees without an import sit outside the file's scope, so a file's own declaration of such a name shadows them.

When two candidates have the same parameter types, the one declared last and closest wins: the file's own function beats any import, and among imports the later import statement wins. This changes only the importing file's calls; each imported file keeps calling its own functions. A function body resolves names where it is written, so a generic function instantiated from another file still calls the functions visible in its own file. A re-export (export { name }) passes on the set its file sees, in the same order.

Overloads differ by their parameters only. Two functions of one name in one scope with the same parameter types are a duplicate declaration, whatever their result types: fn f(x: i32) i32 beside fn f(x: i32) i64, or fn parse(s: [*con]u8) i32 beside fn parse(s: [*con]u8) ParseErr!i32. To let the caller choose the result type, take it as a parameter: fn parse(known T: type, s: [*con]u8) T, called as parse(i64, s).

Method calls. v.m(args) finds an m whose receiver fits v: a *mut or *con receiver takes v's address, and a value receiver called on a pointer gets a copy of the value it points at. When several fit, the one whose receiver matches exactly wins. The lookup order and ranking are in methods and dispatch.

Known arguments. A known parameter takes its argument at compile time and is always written at the call: its value, or _ to have it worked out from the other arguments. Leaving it out is an error (`call to "max" has no argument for known parameter "T"). A _-typed parameter (v: _`) has an argument like any other and needs no type at the call (known values).

Vyi
import { println } from "@fmt"

fn max(known T: type, a: T, b: T) T {
    if a > b { return a }
    return b
}

fn main() !u8 {
    println(max(i64, 3, 7))    // prints 7
    println(max(_, 10, 20))    // prints 20
    return Ok(0)
}

Calling a type like a function is a cast (below). Calling a generic function that returns a type, like Box(i32), is an ordinary call made at compile time, and its result is a type.

Indexing and slicing

xs[i] reads, xs[i] = v writes, and xs[a..b] slices. On a type of your own they call @index, @setIndex, and @slice (operators). On the built-in arrays (fixed arrays and array pointers):

  • An index is bounds-checked; out of range panics at run time.
  • An index counts from the start, never from the end. The last element is s[s.len - 1]. A negative index is out of range: a compile error when the index is known, a panic otherwise.
  • Indexing and slicing look through one strict pointer to a fixed array: with p: *mut [N]T, p[i] is (*p)[i] and p[a..b] is (*p)[a..b], checked against N, with the pointer's write permission. A pointer to anything else can't be indexed.
  • A slice is a [*con]T or [*mut]T view of the same elements, not a copy, keeping the write permission. Either bound may be left out: s[..2], s[3..], s[..]. A bound counts from the start like an index, so the last two elements are s[s.len - 2..].
  • A fixed array is sliced where it is: the view is [*mut]T when the array is a writable place and [*con]T otherwise. The array must be a place, so slicing a call's result is an error, and known bounds outside the array are a compile error (memory model, fixed arrays).
Vyi
import { println } from "@fmt"

fn main() !u8 {
    con word = "hello"
    println(word[1..3])            // prints el
    println(word[word.len - 1])    // prints 111
    println(word[3..])             // prints lo
    return Ok(0)
}

word[word.len - 1] is the byte for o, 111.

Vyi · does not compile
fn main() !u8 {
    con word = "hello"
    return Ok(word[-1])   // error: index -1 is out of range
}

The compiler checks a known negative index only on the built-in arrays. Your own @index, @setIndex, and @slice receive the argument as written and decide what a negative number means. Vec and String count from the start and panic on a negative index; a map keyed by integers may take m[-1] as an ordinary key. A C pointer has no length: cp[i] is pointer arithmetic for any i, negative included.

A missing slice end is the subject's length: .len on a built-in array, length() on your own type. A type with @slice and no length() takes only slices with both bounds.

Vyi
import { println } from "@fmt"
import { Vec } from "@core"
import { ArenaAllocator, systemAllocator } from "@mem"

fn main() !u8 {
    mut arena = ArenaAllocator.new(systemAllocator)
    mut scores = Vec(i32).new(&arena)
    scores.push(70)
    scores.push(85)
    scores.push(90)
    println(scores[scores.length() - 1])   // prints 90
    println(scores[1..].len)               // prints 2
    return Ok(0)
}

Range expressions

a..b is a half-open range, from a up to but not including b; a...b includes b. A range is a Range value, an ordinary struct from @core with the fields start, end, and inclusive. The ends are stored as written and inclusive records the spelling, so a range means the same thing written in place or stored in a binding:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    con word = "hello"
    con middle = 1...3
    println(word[1...3])       // prints ell
    println(word[middle])      // prints ell
    println(middle.inclusive)  // prints true
    return Ok(0)
}

for x in 1...5 runs from 1 to 5. A for loop iterates a range written in place; a range stored in a binding is not iterable (guide 05). Range types, 0..101 in a type position, are in types.

Casts

A cast is the target type called like a function: Target(x). No number converts to another type on its own, so every such change is written as a cast.

CastResult
integer to integerthe same value when it fits; otherwise the low bits, so a run-time 300 cast to u8 is 44
float to integerthe fraction dropped: i32(2.9) is 2, i32(-2.9) is -2
integer to float, f32 to f64, f64 to f32the number converted
char to integer, integer to charthe code point's number, and back
bool to integer1 for true, 0 for false
integer to booltrue for any value but 0
struct to structthe copy by shape, written out (types)
between array shapesa view or a copy between [N]T, *mut [N]T, [*con]T, and [*mut]T (types)
Vyi
import { println } from "@fmt"

fn main() !u8 {
    con big: i32 = 300
    println(u8(big))      // prints 44
    println(i32(2.9))     // prints 2
    println(u32('A'))     // prints 65
    println(char(66))     // prints B
    println(i32(true))    // prints 1
    return Ok(0)
}

A literal that doesn't fit is a compile error, but a cast of a run-time value keeps the low bits, because writing the cast says you meant it. Casting a struct, enum, or tuple to a primitive is an error; read a field instead. A pointer cast to an integer gives its address, which C interop sometimes needs (guide 15); an integer never casts back to a strict pointer.

A cast of a known value is itself known: the compiler computes it, with the result the same cast gives at run time on every target. The cases it doesn't compute are listed in known values.

Prefix operators

FormMeaning
-xnegation; built in for numbers, x.@neg() for other types
!bboolean not; b must be a bool (integers are not truthy)
&xaddress of: *mut T for a mut binding, *con T for a con one
*pdereference; also the target of a store, *p = v
try eunwrap, or return the failure (below)
known eevaluate e at compile time (known values)

The operand of & is a place: a binding, a field of a place, an element of a place, or a dereference (statements, assignment). So &pt.x, &arr[i], &view[i] on an array pointer (bounds-checked like a read), and &*p (which is p) all work.

  • A value has no address. &make(), &(a + b), &5, &Point{ x: 1 }, &make().x, and &v[0] on a collection whose @index returns the element are errors. Bind the value to a name and take the name's address.
  • & on a function's or a type's name (&main, &Point, &i32) is an error. A function's name is already its value: pass main, not &main. A type is not storage.
  • A con binding is a variable, so &limit works, and so does &f on a binding f that holds a function value.
  • &c.callback on a C function is planned, giving a *c_ptr to the C function's type.
  • **pp dereferences twice, one level per *.

Through a C pointer the address of a place is a C pointer: with cp: *c_ptr T, &*cp, &cp[i], and &cp[i].f are all C pointers. Crossing to a strict pointer is the explicit null-checking cast ?*mut T(...) (guide 15).

Vyi · does not compile
fn make() i32 { return 1 }

fn main() !u8 {
    con p = &make()   // error: cannot take the address of this expression
    return Ok(0)
}
Vyi · does not compile
fn twice(x: i32) i32 { return x * 2 }

fn apply(f: fn(i32) i32, x: i32) i32 { return f(x) }

fn main() !u8 {
    con n = apply(&twice, 4)   // error: cannot take the address of function `twice`
    return Ok(0)
}

typeof, sizeof, alignof

These three take their operand with or without parentheses: sizeof T and sizeof(T) are the same.

  • typeof expr is the type expr has. The operand is type-checked and never evaluated.
  • sizeof T is the size of a T in bytes, padding included, as an i32 known value. sizeof S.field is the size of that field's type (types).
  • alignof T is the alignment of T in bytes, as an i32 known value.

The operand of sizeof and alignof is written as any type is: sizeof ?i32, alignof E!i64, sizeof *mut T, sizeof [*con]u8, sizeof [4]i32. It binds more tightly than every binary operator (n * sizeof T), so a union operand takes parentheses: sizeof (A | B). The type must be complete, since nothing flows into the operand: sizeof Vec(_), or sizeof !i64 with its error type left open, is an error (cannot infer operand type from the surrounding code).

Vyi
import { println } from "@fmt"

struct Header { tag: u8, len: i32 }

fn main() !u8 {
    println(sizeof Header)       // prints 8
    println(alignof(Header))     // prints 4
    con count = 5
    con limit: typeof count = 30
    println(limit)               // prints 30
    return Ok(0)
}

Header is 8 bytes: one for tag, three of padding so that len starts at a multiple of its alignment, and four for len.

shapeof

Pattern shapeof subject is a bool: true when subject matches the pattern. The pattern is on the left, as in if Pattern = subject. It tests only and can't bind names; discards such as _ and Some(_) are allowed. To take the value apart, use if Pattern = subject.

Vyi
import { println } from "@fmt"

fn main() !u8 {
    con reply: ?i32 = Some(5)
    println(Some(_) shapeof reply)   // prints true
    println(None shapeof reply)      // prints false
    return Ok(0)
}
Vyi · does not compile
fn main() !u8 {
    con reply: ?i32 = Some(5)
    con hit = Some(n) shapeof reply   // error: `shapeof` is a pure match test and cannot bind names
    return Ok(0)
}

if, switch, and match as expressions

The statement forms (statements) also work where a value is expected. Each branch gives the value of its block's last expression.

An if expression needs an else, so that it has a value on every path:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    con stock = 0
    con label = if stock > 0 { "in stock" } else { "sold out" }
    println(label)   // prints sold out
    return Ok(0)
}

Without the else it is an error (if-expression requires an else branch). An if whose condition is a known value is decided by the compiler: only the taken branch exists, and it needs no else (known values).

A branch that leaves (return, break, continue, panic) gives no value; the if takes the value of the branch that doesn't leave:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    mut total = 0
    for price in [3]i32[10, -1, 5] {
        total += if price < 0 { continue } else { price }
    }
    println(total)   // prints 15
    return Ok(0)
}

if Pattern = subject works as an expression too (patterns).

A switch or match expression gives the value of the arm that runs. An arm that leaves gives no value:

Vyi
import { println } from "@fmt"

fn shipping(zone: i32) i32 {
    return switch zone {
        1:       5,
        2:       12,
        default: return -1,
    }
}

fn main() !u8 {
    println(shipping(2))   // prints 12
    println(shipping(9))   // prints -1
    return Ok(0)
}

The arm rules (coverage, exhaustiveness, default, commas) are the same as for the statements (statements, switch, statements, match, patterns).

Block expressions and break with a value

A block { ... } where a value is expected gives the value of its last expression. Inside it, break value gives a value early. A label on the block, #name { ... }, lets break #name value give the value from anywhere inside, including from a loop within the block:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    con prices = [4]i32[12, 30, 45, 8]
    con firstBig = #search {
        for p in prices {
            if p > 40 { break #search p }
        }
        0
    }
    println(firstBig)   // prints 45
    return Ok(0)
}

"Where a value is expected" means a place that uses the value: an initialiser, an argument, an operand. A block written as a statement, including one directly after return, is a statement block and takes a plain break.

A loop never gives a value, so break with a value that targets a loop is an error:

Vyi · does not compile
fn main() !u8 {
    for {
        break 5   // error: `break` with a value leaves a block that produces a value
    }
    return Ok(0)
}

known { ... } is a block evaluated at compile time; its last expression is a known value (known values).

Arrow functions

(params) R => body is a function value: a parameter list, an optional result type, =>, then one expression or a block. Parameter and result types may be _, filled from the expected function type. fn name(...) { } and fn() T { } are declarations, not expressions: only an arrow makes a function value inside an expression, and fn(T) R is how a function type is written.

Vyi
import { println } from "@fmt"

fn apply(g: fn(i32) i32, x: i32) i32 { return g(x) }

fn main() !u8 {
    con add = (a: i32, b: i32) i32 => a + b
    con same = (x: i32) => x
    con double = (a: i32) i32 => {
        return a * 2
    }
    println(add(1, 2))                       // prints 3
    println(same(4))                         // prints 4
    println(double(5))                       // prints 10
    println(apply((y: _) i32 => y - 1, 10))  // prints 9
    return Ok(0)
}

same has no result type written; it comes from the body.

Vyi · does not compile
fn main() !u8 {
    con one = fn() i32 { return 1 }   // error: function values use arrow syntax
    return Ok(0)
}

An arrow captures the con bindings it uses by value when it is created. Capturing a mut binding is an error, and a captured pointer must outlive the closure. Guide 04 has the closure rules.

try and catch

try and catch take apart a value that can fail: E!T, !T, or ?T. They are shorthand over ordinary enums; match and if Some(v) = o always work as well.

try expr gives the success value. On failure it returns the failure from the enclosing function at once. The failure must fit the enclosing function's own result: a Result through a function that returns a Result, an Optional through one that returns an Optional. Crossing from one to the other takes a catch.

Vyi
import { println } from "@fmt"

enum MathErr { DivZero }

fn divide(a: i32, b: i32) MathErr!i32 {
    if b == 0 { return Err(DivZero) }
    return Ok(a / b)
}

fn average(total: i32, count: i32) MathErr!i32 {
    con avg = try divide(total, count)
    return Ok(avg)
}

fn main() !u8 {
    println(average(90, 3) catch -1)   // prints 30
    println(average(90, 0) catch -1)   // prints -1
    return Ok(0)
}

try works as a statement (return the failure, drop the success value) and inside larger expressions: return Ok(try f(x)) is a common last line.

expr catch fallback gives the success value, and on failure gives the fallback. What follows catch picks the form:

  • a value: f() catch 0;
  • a block, whose last expression is the fallback, or which leaves with return, break, or continue: f() catch { return Err(Missing) };
  • a function or arrow, called with the error: f() catch codeOf.
Vyi
import { println } from "@fmt"

enum MathErr { DivZero, Overflow }

fn divide(a: i32, b: i32) MathErr!i32 {
    if b == 0 { return Err(DivZero) }
    return Ok(a / b)
}

fn codeOf(e: MathErr) i32 {
    return match e { DivZero: -1, Overflow: -2 }
}

fn main() !u8 {
    println(divide(40, 4) catch 0)       // prints 10
    println(divide(9, 0) catch 0)        // prints 0
    println(divide(9, 0) catch codeOf)   // prints -1
    con seven = divide(9, 0) catch (e: MathErr) i32 => 7
    println(seven)                       // prints 7
    return Ok(0)
}

A ?T has no error value, so on an optional catch gives the fallback for None, and a handler takes no argument. The full rules (staying in one channel, inferring error types through try, crossing channels) are in the error model reference; guide 07 introduces them.