Docs · Language

Statements and declarations

This page lists everything that can stand as a statement: declarations, assignment, the control statements (if, switch, match, for, break, continue, return), defer, panic, and recover, and the block and scope rules they share. Guide 05, Control flow introduces the control statements, and guide 08 covers defer, panic, and recover. How statements are separated (newlines and ;) is in lexical.

Files and the top level

A .vyi file is a sequence of top-level declarations. fn, struct, enum, interface, and type declarations are hoisted: each is visible throughout its scope whatever the order, so nothing needs a forward declaration. File-level con and mut bindings are not hoisted: an initialiser reads only bindings declared above it.

Three more forms appear only at the top level:

  • import and export. import { name } from "path" binds exported names directly into the file's scope, with no namespace object, and export makes a declaration importable (guide 14). An import list holds three kinds of item:
  • a name: stdout;
  • a renamed name: Circle: Disc;
  • a method item, a receiver type, a dot, and a method name: Circle.area, *mut Circle.grow, Circle.@add, i32.squared, [*con]u8.trim, Vec(_).sum, ~Circle.area. It brings in the methods of that name whose receiver it names exactly, or matches as a type pattern (methods and dispatch), under their own name or a new one (Circle.area: size). A method is never imported by its bare name.

import "path" with no list loads the file and binds nothing.

  • Compile-time if and for. A top-level if over a known condition chooses which declarations exist; a top-level for over a known iterable writes declarations for each element (known values).
  • c_include names a C library to link (guide 15).

Declarations

Every declaration below works at the top level and inside a function body. export works only at the top level.

con and mut

Vyi
import { println } from "@fmt"

fn main() !u8 {
    con limit = 42          // can't change; type worked out
    con rate: f64 = 0.5     // type written out
    mut total = 0           // can change
    total += limit
    println(total)          // prints 42
    return Ok(0)
}
  • Every binding starts with a value. A binding without = value is an error; there is no "declare now, set later" and no automatic zero.
  • A mut binding keeps its type for its whole life.
  • Assigning to a con binding is an error.

A file-level con or mut starts from a value the compiler computes, because no code runs before main. Its initialiser must be something the compiler can evaluate: a literal, an expression over other known values, a call the compiler can run (con area = square(7)), or a function. An initialiser that needs the running program, because it reads input, allocates, or prints, is an error; compute that value in main or a function main calls.

Vyi · does not compile
import { println } from "@fmt"

fn askLimit() i32 {
    println("limit?")
    return 10
}

con limit = askLimit()   // error: is not a value the compiler can compute

fn main() !u8 { return Ok(0) }

A con may take a pattern in place of a name, to take apart a struct (by field name or by position) or a tuple (by position). The pattern must match every value of the type: a literal, or a variant of an enum with several variants, can't appear in it at any depth (use match or if for those). Every name a pattern binds is a con.

Vyi
import { println } from "@fmt"

struct Point { x: i32, y: i32 }

fn main() !u8 {
    con corner = Point{ x: 30, y: 12 }
    con Point{ x, y } = corner       // by field name
    con Point(left, _) = corner      // by position; _ discards
    con (low, high) = (5, 7)         // a tuple
    println(y)                       // prints 12
    println(left)                    // prints 30
    println(high)                    // prints 7
    return Ok(0)
}

The full pattern grammar is in the patterns reference.

type

type Name = expr binds a name to a known value, usually a type, and is hoisted like fn. An alias is interchangeable with what it names. Any known value can stand where a type goes, so type Two = 2 and type Mode = "fast" | "slow" are valid too (types, singleton types).

fn

Vyi
struct Point { x: i32, y: i32 }

fn distance(a: i32, b: i32) i32 {     // a function
    if a > b { return a - b }
    return b - a
}

fn (p: Point) sum() i32 {             // a method with a value receiver
    return p.x + p.y
}

fn (p: *mut Point) shift(d: i32) {    // a pointer receiver: may change p
    p.x += d
}

fn (Point) origin() Point {           // a type receiver: Point.origin()
    return Point{ x: 0, y: 0 }
}
  • A parameter is name: Type, optionally with a default (step: i32 = 1) or marked known, a compile-time parameter (known values).
  • The result type follows the parameter list; without one the function returns ().
  • A receiver before the name makes the function a method. A method is a declaration found by scope, not a member of its type (methods and dispatch).
  • Functions of one name overload by their parameter types (expressions, calls).
  • A function body can declare functions of its own. They are hoisted within the body.

A parameter's type or the result type may be followed by a lifetime annotation: an apostrophe and parenthesised names, such as '(a & b). It ties the value to what each named parameter, receiver, or file-level variable points at; & joins names, and , separates pointer levels, outermost first:

Vyi
struct Point { x: i32, y: i32 }

fn xOf(p: *mut Point) *mut i32 '(p) {
    return &p.x
}
  • A written result lifetime is checked against the body and relied on by callers.
  • A written parameter lifetime is checked against the body's stores and at every call.
  • Where none is written, a function's parameter lifetimes are worked out from its body.
  • A function-typed parameter's own parameters may carry an annotation naming another parameter of the function.
  • The annotation is not part of the type.
  • Lifetimes on an interface method's parameters, slots on interface types, and result lifetimes on function types are (planned).

Guide 09 and the memory model have the details.

struct, enum, interface

Each declares a nominal type, and each is short for a hoisted type binding: struct P { ... } is type P = struct { ... }. Their bodies are lists separated by commas: fields name: Type (optionally pub, optionally = default), variants Name or Name(T, U), and method signatures fn (s: ~Name) method() R. See types and guides 03 and 12.

export and pub

export before a top-level declaration lets other files import its name; everything else is private to its file. pub on a struct field lets other files read that field. export { names } re-exports imported names, and export { Type.method } re-exports methods imported with a method item. Guide 14.

Decorators

A decorator is :< followed by a call, on its own line directly before the declaration it marks. Several may stack, one per line.

The four decorators are compiler markers that the standard library uses. A package may use markInline and markBuiltIn only when its manifest opts in; any other decorator name is an error.

DecoratorMarksEffect
:<markInline()a functionthe compiler puts the function's body in place of each call. Needs hasInlineMarkers: true in the package manifest
:<markBuiltIn()a function, method, or typeevery file in the program sees it without an import. On a type, the package's exported methods on that type are seen everywhere too; on a method, this is how a package adds methods to types no import can name (i32, [*con]u8), as @fmt does with intoString. Needs hasBuiltIns: true in the package manifest (@core has it)
:<markStablePtr()a named con or mut bindingdeclares that the pointers the binding holds stay valid as long as the program runs (memory model)
:<markWellKnown(name)a function or typelinks the declaration to one the language's syntax relies on (Optional, Result, Array, Range, Writer). One declaration per name per program; the package registry refuses to publish a package that uses it

A decorator on a declaration it doesn't fit is an error:

Vyi · does not compile
:<markInline()   // error: cannot decorate a `con`/`mut` value binding
con limit = 10

fn main() !u8 { return Ok(0) }

C declarations

c_fn (a C function, declared or written in Vyi under a C name), c_struct, c_enum, and c_union (types with C layout, reached through the c. namespace), and c_include (a C library to link). They follow C's rules, not Vyi's; guide 15 covers them.

Assignment

place = value stores into a place: a mut binding, a field of a place, an element of a place, or a dereference, to any depth:

Vyi
import { println } from "@fmt"

struct Box { size: i32 }

fn main() !u8 {
    mut count = 1
    mut box = Box{ size: 1 }
    mut sizes = [2]i32[1, 2]
    con p = &count

    count = 2       // a binding
    box.size = 5    // a field
    sizes[0] = 7    // an element
    *p = 3          // through a pointer
    println(count)      // prints 3
    println(box.size)   // prints 5
    println(sizes[0])   // prints 7
    return Ok(0)
}

Anything else is a value, which nothing stores, so it can't be assigned to: a call's result, an operator's result, a literal, a slice (a[1..3]), and a field or element of any of these. The element a collection's @index method returns is a value too: v[0] = x (an @setIndex call) replaces a whole element, but v[0].field = x is an error; copy the element into a mut binding, change it, and store it back. A fixed array's .len is part of its type, not storage. Assigning to a value is an error:

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

fn main() !u8 {
    make() = 2       // error: cannot assign to this expression
    return Ok(0)
}
Vyi · does not compile
fn main() !u8 {
    mut a = [4]i32[1, 2, 3, 4]
    a.len = 2        // error: the length of a fixed array is part of its type
    return Ok(0)
}

Assignment is a statement and produces no value, so a = b = c and if a = b { } don't exist (if Pattern = subject is a pattern binding, not an assignment). To ignore a call's result, write the call as a statement.

Compound assignment

There are thirteen compound forms: += -= *= /= %= +%= -%= *%= &= |= ^= <<= >>=. place OP= value calls the type's in-place method (@compAdd for +=) when it has one, and otherwise is place = place OP value with the place evaluated once (operators, compound assignment).

A place that contains a call would run the call twice, so it is an error. Bind the index first:

Vyi · does not compile
fn nextSlot() i32 { return 0 }

fn main() !u8 {
    mut counts = [2]i32[0, 0]
    counts[nextSlot()] += 1   // error: compound assignment would evaluate this place twice
    return Ok(0)
}

Expression statements

Any expression can stand as a statement, and its value is dropped. The usual case is a call made for its effect. try f() as a statement passes a failure on and drops the success value.

Blocks and scope

{ ... } is a block, and a block is a new scope. Bindings declared in it end with it. Declaring a name that an enclosing scope already binds shadows the outer binding until the block ends. Within one scope a name is declared once; declaring it again is a duplicate error, except for functions, which overload when their parameter types differ (expressions, calls). Scope is purely lexical:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    con score = 5
    {
        con score = 100
        println(score)   // prints 100
    }
    println(score)       // prints 5
    return Ok(0)
}

A block's storage ends with the block, as its names do. A pointer to a variable in a block can't be kept in a variable declared outside it, and a loop body is a block that ends with each iteration (memory model, stability and escape).

A block where a value is expected is an expression (expressions, block expressions), and a labeled block is a break target (below).

if

Vyi
fn sign(n: i32) i32 {
    if n < 0 {
        return -1
    } else if n == 0 {
        return 0
    } else {
        return 1
    }
}

The condition takes no parentheses and must be a bool; an integer is not a condition. Braces are always required.

if Pattern = subject { } runs its block when the subject matches the pattern, with the pattern's names bound inside it. A condition after ; must also hold:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    con stock: ?i32 = Some(33)
    if Some(n) = stock; n > 10 {
        println(n)        // prints 33
    } else {
        println("low")
    }
    return Ok(0)
}

Both forms work as expressions too (expressions, patterns).

switch

switch subject { ... } chooses by value. The subject is evaluated once. Each arm is an expression compared with the subject using ==. Arms are tried from the top, an arm's expression is evaluated only when every arm above it failed, and the first arm that matches runs:

Vyi
fn limitFor(tier: i32) i32 { return tier * 100 }

fn classify(code: i32, limit: i32) i32 {
    return switch code {
        0:            0,   // a literal
        limit:        1,   // a variable
        limitFor(2):  2,   // a call, made only when reached
        1...9:        3,   // a range
        default:      9,
    }
}
  • An arm is a value: a literal, a variable, a field, a call, any expression. Over an enum subject, a variant may be bare (Red:) or qualified (Color.Red:). The subject's type must have ==, so a struct needs @eq. Over a union, each arm is a value of one of its members.
  • Every arm must compare with the subject. An arm that can't be compared with the subject's type ("hi": over an i32) is an error at the arm. Over a _-typed or generic subject this is checked in every instance, and each call that makes an instance with such an arm is reported at the arm. To branch on the type first, write match typeof v with a switch in each arm.
  • Range arms. Over a number or char subject, an arm whose value is a Range matches when the subject is in the range: lo..hi excludes hi, lo...hi includes it, and a missing end has no limit. The ends may be run-time values.
  • default: matches when no other arm does. There is at most one, and it is the last arm.
  • Coverage. A switch without default: must have an arm for every case, as a statement as well as an expression. The compiler can prove that only from known arms, and only for a bool, an enum without payloads, a union of singletons, or an integer or char whose whole range the known values and ranges cover. Every other switch needs default: (patterns, exhaustiveness).
  • Unreachable arms. An arm that the known arms above it cover completely (a repeated known value, or a value or range inside earlier ranges) is an error. A partial overlap is allowed.
  • No guards. There is no per-arm guard; switch true with conditions as arms does that job (guide 05).

A pattern that takes a value apart, such as Circle(r), is not a value, so it is an error as a switch arm; use match.

Vyi · does not compile
fn word(v: _) [*con]u8 {
    switch v {
        1:       return "one",
        "hi":    return "greeting",   // error: this `switch` arm has type [*con]u8, which cannot be compared with the subject's type i32
        default: return "other",
    }
}

fn main() !u8 {
    con w = word(1)
    return Ok(0)
}

match

match subject { ... } chooses by shape. Each arm's head is resolved at compile time to a variant of the subject's enum (with or without its payload), a type (in match typeof u), an error, or a pattern that takes apart the subject's struct or tuple. A variant pattern binds the payload directly:

Vyi
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,
    }
}
  • Exhaustiveness. An enum subject needs every variant handled; match typeof u on a union needs every member type; a struct or tuple needs an arm that takes every value. A default: arm covers the rest, and an error subject always needs one. The catch-all is default:, never _ or else (patterns, exhaustiveness). A match or switch reported as not covering its subject is not also reported as a missing return.
  • Subjects. An enum value, typeof a union value, an error value, or a struct or tuple value (match p { Point{ x, y }: ... }, match t { (a, b): ... }). A value with no shape, such as an i32, is an error; use switch.
  • An arm's head is never a run-time value. A name in a match arm is a variant or a type, never a variable.

Arms in switch and match

Both share their arm syntax:

  • Commas. Written over several lines, every arm ends with a comma, the last one included. Written on one line, arms are separated by commas, with no comma after the last.
  • Arm bodies. An arm holds one expression or one statement bare (Dot: 0,, Dot: return 0,). An arm with several statements, or whose body is an assignment, uses braces.
  • Several values in one arm. Red, Green: ... shares one body between them. In a switch they are tried left to right; in a match they can't bind payloads.
  • default is not a reserved word. Only an arm whose head is exactly default is the catch-all; a variant, variable, or type named default is written (default):.
  • Dynamic identifiers. An arm head may be [name]: (known values, dynamic identifiers).

A missing comma is a parse error, reported at the next arm:

Vyi · does not compile
fn label(n: i32) i32 {
    switch n {
        1: return 10
        default: return 99,   // error: expected `,` between switch arms, found `default`
    }
}

fn main() !u8 { return Ok(0) }

for

for is the only loop keyword. It has three forms.

Condition (a while loop) and infinite:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    mut fuel = 3
    for fuel > 0 {        // runs while the condition holds
        fuel -= 1
    }
    println(fuel)         // prints 0
    mut tries = 0
    for {                 // runs until break or return
        tries += 1
        if tries == 4 { break }
    }
    println(tries)        // prints 4
    return Ok(0)
}

for x in iterable goes through a range written in place, a fixed array [N]T, an array pointer [*con]T or [*mut]T, or a value whose type has an @iter() method, or @index(i32) and length() methods. The loop variable is a new con binding in each iteration, so assigning to it is an error.

Vyi
import { print, println } from "@fmt"

fn main() !u8 {
    for n in 1...3 { print($"${n} ") }          // prints 1 2 3
    println("")
    for p in [2]i32[40, 50] { print($"${p} ") } // prints 40 50
    println("")
    for b in "hi" { print($"${b} ") }           // prints 104 105
    println("")
    return Ok(0)
}

1...3 includes 3; 1..3 stops at 2. A string literal is a [*con]u8, so the loop goes through its bytes.

  • The iterator protocol. When the iterable's type has @iter(), found by ordinary method lookup (an interface's declared methods included), the loop calls iterable.@iter() once before the first iteration and keeps the result as its own mut iterator. Each iteration calls @next() on that iterator (a *mut receiver gets the iterator's address, so it advances in place). @next() returns an optional ?T: Some(x) binds x and runs the body, and None ends the loop. The iterator's type needs no declaration; only its methods are checked. Both calls are typed as the written calls. The iterator lives for the whole for statement and ends with it, however the loop exits. String goes through its code points this way, and HashMap through its entries (Entry(K, V), with .key and .value).
  • The index protocol. Otherwise, a type with @index(i32) and length() (as Vec has) is read as iterable.@index(i) for an i32 counter i from 0 up to length(), which is read once. @index is typed as that call, so an @index whose parameter can't take an i32 is an argument error at the iterable. When a type has both protocols, @iter() wins.
Vyi
import { print, println } from "@fmt"

struct Countdown { left: i32 }

fn (c: Countdown) @iter() Countdown { return c }

fn (c: *mut Countdown) @next() ?i32 {
    if c.left == 0 { return None }
    c.left -= 1
    return Some(c.left + 1)
}

fn main() !u8 {
    con launch = Countdown{ left: 3 }
    for n in launch { print($"${n} ") }   // prints 3 2 1
    println("")
    return Ok(0)
}

To change elements in place, iterate something whose @next() returns ?*mut T; the loop variable is then a pointer into the collection. A pointer that @next() returns lives as long as what it points into: the collection, or the loop statement when it points into the iterator. Nothing stops a program from changing a collection while iterating it; what a stale iterator then does is up to the iterator (@core's read through bounds-checked views, so they panic or read the storage they started with, never past its end).

A range stored in a binding is not iterable; a for loop iterates a range written in place (expressions, ranges).

Labels, break, and continue

break leaves the nearest enclosing loop, and continue goes on to its next iteration. A label, #name before a for or a block, lets them target an enclosing loop or block instead. There is no jump sideways and no goto:

Vyi
import { print, println } from "@fmt"

fn main() !u8 {
    #sizes for size in 1..4 {
        for color in 0..2 {
            if size == 2 { break #sizes }
            print($"${size}-${color} ")   // prints 1-0 1-1
        }
    }
    println("")
    return Ok(0)
}

break #name also leaves a labeled block. continue targets loops only; a block is never a continue target. break value and break #name value give a value from a block where a value is expected (expressions); in a loop or a statement block, break takes no value.

return

return expr leaves the function with a value; a bare return leaves a function that returns (). Every path through a function that returns a value must return; reaching the end of the body is an error unless the function returns (). In a function that can fail, the returned value goes into the result like any other value: return Err(e), return Ok(try f(x)) (error model).

defer

defer statement or defer { ... } schedules code to run when the enclosing function exits:

Vyi
import { println } from "@fmt"

fn save() {
    defer println("file closed")
    println("saving")
}

fn main() !u8 {
    save()   // prints saving
    return Ok(0)
}

save() prints saving, then file closed.

  • Every exit runs the defers: a return, reaching the end of the body, an error leaving through try, and a panic unwinding through the function.
  • Last in, first out. The defer registered last runs first.
  • Registration happens when it runs. A defer registers each time execution reaches it, so a defer in a loop body registers once per iteration. It belongs to the function, not to the block it is in.
  • The body sees final values. It runs at exit, with the function's locals as they are then, not as they were when the defer registered.
  • A return inside a defer body replaces the function's return value.

Guide 08 shows each of these.

panic

panic reason stops the current function and unwinds the stack, running each function's defers on the way out. The reason is a [*con]u8, and a string literal is one. If nothing recovers it, the program prints panic:, the reason, and the calls in progress to stderr, and exits with status 101.

Vyi
import { println } from "@fmt"

fn half(n: i32) i32 {
    if n % 2 != 0 { panic "odd input" }
    return n / 2
}

fn main() !u8 {
    println(half(10))   // prints 5
    return Ok(0)
}
  • panic always takes a reason, and the reason is a [*con]u8; anything else is a compile error.
  • The runtime panics in the same way when an invariant breaks, such as an index out of bounds.
  • Running out of stack is not a panic. It ends the program at once, with no unwinding and no defers (guide 08).

A panic is for a broken invariant. A failure a caller should handle belongs in an error union.

recover

recover(reason) { ... } catches a panic. It is allowed only inside a defer body, because a panic can be caught only while the unwind runs a function's defers:

Vyi
import { println } from "@fmt"

fn explode() i32 { panic "kaboom" }

fn safe() i32 {
    defer {
        recover(reason) {
            println(reason)   // prints kaboom
            return 7
        }
    }
    return explode()
}

fn main() !u8 {
    println(safe())           // prints 7
    return Ok(0)
}
  • The block runs only when the defer runs because of a panic. On a normal return or an error return it is skipped, and the rest of the defer body still runs.
  • reason is the panic's [*con]u8. Write recover(_) when you don't need it.
  • A return in the block sets the function's return value and stops the unwind: the caller sees an ordinary return.
  • A block without a return only looks at the panic. The unwind goes on to the next function up, and ends the program if nothing stops it.

recover catches panics only. An error leaving through try is a value: it runs the defers but never a recover block. Handle it with catch (error model). Outside a defer, recover is an error:

Vyi · does not compile
fn main() !u8 {
    recover(reason) { return Ok(1) }   // error: usable only inside a `defer` body
    return Ok(0)
}