Docs · Language

Known values and compile-time evaluation

A known value is a value the compiler works out while compiling. This page states what is known, when the compiler evaluates it, and how known parameters, generics, type values, dynamic identifiers, file-level if and for, and the limits on compile-time evaluation build on it. Guide 11, Known values, generics, and compile-time evaluation introduces them.

Known values: definition and sources

A value is known when the compiler can work it out completely while compiling. Any other value is a run-time value.

SourceKnown?
a literal (42, "hi", 'a', true, ())yes
a con whose initializer is built from known valuesyes
a call on known arguments that the compiler evaluates: known f(x), the argument of a known parameter, a call in a typeyes
an integer or float operator on known operands (a + b, x << 3, -n)yes (integer arithmetic)
a number conversion of a known value (i64(n), f32(x), u32('A'), uw(5), also through a type binding or a known T)yes, with the value the conversion gives at run time, except in the cases listed below
a type, including type itselfalways
typeof, sizeof, or alignof over a known operandyes
.len of a fixed array [N]T (the length is part of the type)yes
an ordinary parameter, a mut binding, anything read at run timeno

A number conversion is not computed when its value would differ between targets:

  • a NaN or an infinity converted to an integer;
  • a float whose integer part is outside the target type's range, or, for a target type of 32 bits or fewer, outside the range of a 32-bit integer of the same signedness (i8(300.5) is computed, and is 44);
  • bool from a number other than 0 or 1;
  • any conversion with a C type on either side.

A pointer-width integer (iw, uw) has the target's pointer width, so its conversions give the target's own value: u32(uw(4294967296)) is 0 on x86-64, and on wasm uw(4294967296) is already 0.

The word known appears in two places:

  • a parameter qualifier, fn f(known T: type, ...): the argument arrives at compile time (known parameters);
  • a prefix operator, known expr or known { ... }: evaluate this at compile time (the known operator).

A compile-time evaluation reads only known values. A run-time value is rejected, because it doesn't exist yet when the evaluation runs.

Integer arithmetic

An integer operation the compiler computes gives exactly the value the same operation gives at run time, at the operation's width and signedness, for every operator and width, u64 values above the signed range included. Where the run-time operation would panic or wrap depending on the build mode, the compile-time one is an error in both modes, so a known value never depends on the mode:

  • a +, -, *, /, or negation whose exact result does not fit the type is knownOverflow. Write +%, -%, or *% to wrap, and the compiler wraps too;
  • a shift count outside 0 to the width minus one is knownOverflow;
  • a division or remainder by zero is knownDivisionByZero.
Vyi · does not compile
con stock: u8 = 200
con doubled = stock + stock   // error: 200 + 200 is 400 at compile time, which does not fit u8
Vyi
import { println } from "@fmt"

con stock: u8 = 200
con wrapped = stock +% stock

fn main() !u8 {
    println(wrapped)   // prints 144
    return Ok(0)
}

A pointer-width integer computes at the target's pointer width: 32 bits on wasm, 64 on x86-64 and arm64. So the same con can be a value on one target and knownOverflow on another, as sizeof differs between them. A float operation rounds to its type: an f32 product is the nearest f32.

Evaluation is on demand

The compiler evaluates a known value when something needs it. An evaluation that reaches a name not resolved yet waits for it and then continues.

Something needs a value in one of two ways:

  • Required. The language demands the value: a known expression, a file-level con, mut, or type initializer, a type annotation or type argument, an array length, the argument of a known parameter. If the value cannot be worked out, that is a compile error. For a file-level con or mut it is fileLevelRuntimeInit (statements).
  • Opportunistic. The compiler tries on its own because the inputs are known: a call with constant arguments in a run-time position (println(square(12))), an if condition, an index, a range bound. If it gets a value, the code uses it; if not, the code runs at run time as written.

Two ordering rules follow:

  • Declarations need no order. fn, struct, enum, interface, and type declarations may refer to each other in any order, within a file or across files.
  • File-level initializers read upward. A file-level con or mut initializer may read only bindings declared above it.
Vyi
import { println } from "@fmt"

con answer = known double(21)   // double is declared below

fn double(n: i32) i32 { return n * 2 }

fn main() !u8 {
    println(answer)   // prints 42
    return Ok(0)
}
Vyi · does not compile
con total = tax + 1   // error: undefined name "tax"
con tax = 1

known parameters

known before a parameter requires the argument to be a known value, and the function receives it at compile time. Any type works: type is the common case (that is what a generic function is), and plain values work the same way.

Vyi
import { println } from "@fmt"

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

fn scale(known factor: i32, n: i32) i32 {
    return factor * n
}

fn main() !u8 {
    println(larger(i32, 3, 7))   // prints 7
    println(larger(_, 30, 5))    // prints 30
    println(scale(3, 4))         // prints 12
    return Ok(0)
}

Every known parameter is written at the call, as its value or as _. _ asks the compiler to infer the argument. That works when the parameter appears in an ordinary parameter's type, directly or nested (xs: [*con]T), or as an array length (a: [N]i32): each run-time argument has a type, and the compiler solves the parameter from it.

CallError
a known argument left out`call to "larger" has no argument for known parameter "T"`
a _ that no argument's type decides`cannot infer known parameter "T" of "size"`
a run-time value in a known slot`argument to known parameter "factor" is not known at compile time`
Vyi · does not compile
fn scale(known factor: i32, n: i32) i32 { return factor * n }

fn main() !u8 {
    mut factor = 3
    con result = scale(factor, 2)   // error: argument to known parameter "factor" is not known at compile time
    return Ok(0)
}

Type variables without a slot

Two spellings declare a type parameter that is always inferred and has no argument at the call:

  • a _ in a parameter's type (fn show(v: _), fn free(p: [*mut]_)): an unnamed type variable. typeof v names the type in the body;
  • an undeclared type name in a signature (fn larger(a: T, b: T) T): a named type variable.

The rule for names is exact. In the parameter and return types of a function declared at file level, a name that the file doesn't declare, doesn't import, and that isn't built in is a type variable. Anywhere else an undeclared name is undefined name: in a method's or a closure's parameters, in a struct field, in a function body. A misspelled type name in a file-level function's signature is therefore a type variable too, and a call reports a type the body can't handle in the instance (total(Prise = i32)). A type variable that appears only in the return type is decided by no argument, so every call is an error:

Vyi
import { println } from "@fmt"

fn bytes(v: _) i32 { return sizeof typeof v }

fn larger(a: T, b: T) T {
    if a > b { return a }
    return b
}

fn main() !u8 {
    println(bytes(i64(1)))     // prints 8
    println(larger(3, 7))      // prints 7
    return Ok(0)
}
Vyi · does not compile
fn double(n: i32) i23 {
    return n * 2
}

fn main() !u8 {
    con d = double(4)   // error: cannot infer type "i23"
    return Ok(0)
}

A function with a type variable is compiled once for each type it is called with. In it, match typeof v is decided for each of those types: only the arm that accepts the type is compiled, the other arms are not checked for it, and the match needs no default. A call whose type no arm accepts is an error at that call: `"describe" has no match typeof arm for [*con]u8 and no default```.

Order of parameters

A signature reads left to right. A parameter's type and its default may use the parameters to its left, known or not, and nothing to its right: fn sum(a: [N]i32, known N: i32) is `undefined name "N"`. So a later parameter's type can be built from an earlier known parameter, a type or a value:

Vyi
import { println } from "@fmt"

fn sum(known N: i32, values: [N]i32) i32 {
    mut total = 0
    for i in 0..N { total += values[i] }
    return total
}

fn main() !u8 {
    con scores = [4]i32[1, 2, 3, 4]
    println(sum(4, scores))   // prints 10
    println(sum(_, scores))   // prints 10
    return Ok(0)
}

A known parameter may sit anywhere in the list, and arguments bind parameters in written order. Putting known parameters first is the convention the standard library follows, and the only order in which later parameter types can use them.

The known operator

known expr evaluates an expression at compile time, where it is written. known { ... } is the block form; its value is the block's last expression. Being known is a property of an evaluation, not of a function: the same function can run at compile time at one call and at run time at another.

Vyi
import { println } from "@fmt"

fn square(n: i32) i32 { return n * n }

fn main() !u8 {
    con area = known square(12)
    con total = known {
        mut sum = 0
        for n in 1...10 { sum += n }
        sum
    }
    mut side = 5
    println(area)            // prints 144
    println(total)           // prints 55
    println(square(side))    // prints 25
    return Ok(0)
}

A mut inside a compile-time evaluation is allowed. It exists only during that one evaluation, and what leaves the evaluation is a finished, immutable value. A run-time value can never flow in:

Vyi · does not compile
fn square(n: i32) i32 { return n * n }

fn main() !u8 {
    mut side = 5
    con area = known square(side)   // error: not computable
    return Ok(0)
}

type, typeof, sizeof, alignof

type is the type whose values are types. A type is always a known value, so types can be bound (type Id = u32), passed to known parameters, and returned from functions.

OperatorOperandResult
typeof exprany expression, which is not evaluatedthe expression's type
sizeof Ta typeits size in bytes, an i32 known value
alignof Ta typeits alignment in bytes, an i32 known value

Parentheses are optional: sizeof T and sizeof(T) are the same. Sizes and alignments depend on the target (memory model).

Vyi
import { println } from "@fmt"

fn add(a: i32, b: i32) i32 { return a + b }

type Sum = typeof add(1, 2)   // i32; add is not called

fn main() !u8 {
    con total: Sum = 40
    println(total)          // prints 40
    println(sizeof i64)     // prints 8
    return Ok(0)
}

Generic functions and types

A generic function is a function with known parameters, and a generic type is a function that returns type.

  • One copy per set of known arguments. For each distinct combination of known arguments, the program has one compiled copy of the function. Run-time arguments never affect this.
  • The same arguments give the same type. Every mention of Box(i32), in any file and through any type binding, is the same type, and values pass between the spellings. Box(i64) is a different type. ?i32 and Optional(i32) are the same type by this rule.
Vyi
import { println } from "@fmt"

fn Box(known T: type) type {
    return struct { value: T }
}

type IntBox = Box(i32)

fn main() !u8 {
    con a = Box(i32){ value: 40 }
    con b: IntBox = a   // the same type
    println(b.value)    // prints 40
    return Ok(0)
}

The body of a type-returning function is ordinary code run at compile time. It may branch on sizeof T, loop, and compute before it returns a struct, enum, or interface (guide 11).

Every instance is checked

A generic body is checked for each instance the program makes, at that instance's types, with every check ordinary code gets. There are no bounds to write: whatever an instance's types make wrong is an error. The diagnostic sits at the offending expression, names the instance (widen(T = bool), show(typeof v = bool), Box(bool).get), and has a note at the call that made it, and at each call back to the one that started a chain of instances. The same mistake in two instances is two errors; one instance made by many calls is one. Code that does not depend on the known parameters is checked once, whether or not the function is ever called.

Vyi · does not compile
fn widen(known T: type, v: T) i32 {
    con wide: i32 = v   // error: this value has type bool, but the binding is declared i32, in the instance `widen(T = bool)`
    return wide
}

fn main() !u8 {
    con a = widen(i32, 1)
    con b = widen(bool, true)
    return Ok(0)
}

Only the code an instance keeps is checked for it. A branch that a known condition rules out (if T == bool, if sizeof T == 4) does not exist in that instance, so it may be ill-typed there:

Vyi
import { println } from "@fmt"

fn asInt(known T: type, v: T) i32 {
    if T == bool {
        if v { return 1 }
        return 0
    }
    con n: i32 = v   // not in asInt(T = bool)
    return n
}

fn main() !u8 {
    println(asInt(bool, true))   // prints 1
    println(asInt(i32, 41))      // prints 41
    return Ok(0)
}

Types as run-time values

A type can also be a run-time value. typeof over a value of a union type asks which member the value holds now, and that is answered at run time; over any other operand it is a known value. match typeof u selects the member (patterns). A type value can be compared arm by arm with switch, which needs a default arm, because a type has no end of possible values.

Vyi
import { println } from "@fmt"

fn typeName(t: type) [*con]u8 {
    return switch t {
        i32:     "i32",
        bool:    "bool",
        default: "another type",
    }
}

fn main() !u8 {
    mut answer: i32 | bool = 42
    println(typeName(typeof answer))   // prints i32
    answer = true
    println(typeName(typeof answer))   // prints bool
    return Ok(0)
}

Dynamic identifiers

A name can be written [expr], a dynamic identifier. The expression is evaluated at compile time and must be a known string, which becomes the name.

SlotExample
the name of a file-level declarationcon [name] = ..., fn [name]() { ... }, struct [name] { ... }
a struct field, in the declaration and in a literalstruct S { [f]: i32 }, S{ [f]: 1 }
an enum variantenum E { [v], Other }
a field accesss.[f]
a switch or match arm head[name]:, the variant or type with that name

A declaration inside a function body cannot take a dynamic identifier: the name it declares is not found.

Vyi
import { println } from "@fmt"

con unit = "celsius"
con helper = "triple"

struct Reading { [unit]: i32 }

fn [helper](n: i32) i32 { return n * 3 }

fn main() !u8 {
    con today = Reading{ [unit]: 21 }
    println(today.celsius)    // prints 21
    println(triple(5))        // prints 15
    return Ok(0)
}

if and for at file level

At file level, if and for run while compiling and decide which declarations exist. Their conditions and arrays must be known values.

FormEffect
if cond { decls } else { decls }keeps the declarations of the branch the condition selects; the other branch is never built
for name in knownArray { decls }repeats the body's declarations once for each element

The loop variable of a file-level for is usable only inside a dynamic identifier in the body, to name what each pass declares (con [name] = ...). It cannot be read as a value there.

Vyi
import { println } from "@fmt"

con verbose = false

if verbose {
    fn log(message: [*con]u8) { println(message) }
} else {
    fn log(message: [*con]u8) {}
}

for feature in [2][*con]u8["search", "upload"] {
    con [feature] = true
}

fn main() !u8 {
    log("starting")
    println(search)   // prints true
    println(upload)   // prints true
    return Ok(0)
}

A run-time value cannot decide what gets compiled:

Vyi · does not compile
mut counter: i32 = 0

if counter > 0 {   // error: file-scope `if` requires a known-reducible condition
    fn helper() i32 { return 1 }
}

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

A known condition inside a function

Inside a function an if whose condition is known keeps only the branch it selects, as a statement and as a value. The branch it drops may hold code that would not compile for this target. A value-position if whose condition is known to be true needs no else:

Vyi
import { println } from "@fmt"
import { targetOS } from "@target"

fn main() !u8 {
    con pageSize = if targetOS == "wasm" { 65536 } else { 4096 }
    con bonus = if 7 > 3 { 30 }
    println(bonus)   // prints 30
    return Ok(0)
}

A value-position if whose condition is known to be false and that has no else has no value, and is an error:

Vyi · does not compile
fn main() !u8 {
    con bonus = if 1 > 3 { 10 }   // error: if-expression requires an else branch
    return Ok(0)
}

Limits on compile-time evaluation

Compile-time evaluation runs real code, so it can fail to end. The compiler bounds it three ways, and each bound is a compile error at a source location, never a hang.

A call that needs its own result is a cycle. Evaluating a call asks for the result of that function with those known arguments. If answering asks for the same thing again, the compiler reports it at once:

Vyi · does not compile
fn loop(known n: i32) i32 {
    return loop(n)   // error: known evaluation of "loop" recurses on itself
}

fn main() !u8 { return Ok(u8(loop(1))) }

Nesting is bounded by depth. Each known call and each instance of a generic is evaluated in its own frame, and a call made during a frame's evaluation nests one frame deeper. Evaluation may nest at most 1,024 frames deep. A recursion whose argument is new at every level never repeats a question, so it is not a cycle; it reaches the depth limit. The error lists the chain of calls, each with its known arguments: the first few, an ellipsis, and the last two.

Vyi · does not compile
fn count(known n: i32) i32 {
    return count(n + 1)   // error: compile-time evaluation may nest at most 1024 frames deep
}

con k = known count(0)

A generic type that makes itself with an ever-larger type argument fails the same way, and the chain shows the growing type:

Vyi · does not compile
fn Wrap(known T: type) type {
    return struct { inner: Wrap(Wrap(T)) }   // error: compile-time evaluation may nest at most 1024 frames deep
}

fn size(w: Wrap(i32)) i32 { return 0 }

The limit counts nesting, not work. A recursion that reaches its base case within 1,024 frames is evaluated normally, a function is one frame however many bindings it makes, and a long expression such as a + b + c is one frame.

Work is bounded by steps. Each pass through a loop body is one step, and each call is one step. One evaluation may take at most 100,000 steps:

Vyi · does not compile
fn spin(known start: i32) i32 {
    mut i = start
    for i >= 0 {   // error: one compile-time evaluation may take at most 100000 steps
        i = (i + 1) % 1000
    }
    return i
}

con k = known spin(0)

One evaluation is one thing the program asks the compiler to work out (a known expression, a con initializer, the type function in a type annotation) together with every call it makes. The loops of a function called from a loop count toward the evaluation that called it, however shallow the nesting. Here table never goes more than two frames deep, but its calls to sumTo run more than 100,000 loop passes between them:

Vyi · does not compile
fn sumTo(known n: i32) i32 {
    mut total = 0
    for i in 0..n { total += i }   // error: one compile-time evaluation may take at most 100000 steps
    return total
}

fn table(known rows: i32) i32 {
    mut total = 0
    for row in 0..rows { total += sumTo(row) }
    return total
}

con cells = known table(500)

The count starts from zero for each evaluation, so neither the size of a program nor the number of evaluations in it brings any of them closer to the limit. Only work done is counted: a call whose result the compiler has already worked out (the same function with the same known arguments) costs nothing, so a compile-time fib(n - 1) + fib(n - 2) takes one step per distinct n.

Vyi
import { println } from "@fmt"

fn fib(known n: i32) i64 {
    if n < 2 { return i64(n) }
    return fib(n - 1) + fib(n - 2)
}

con f = known fib(40)   // 41 steps

fn main() !u8 {
    println(f)   // prints 102334155
    return Ok(0)
}

When a required evaluation reaches a limit, the compiler stops evaluating and reports that limit alone. It does not go on to report the parts of the program it could not finish.

When an opportunistic evaluation reaches a limit, that is not an error: the compiler gives up on it and the code runs at run time as written. An opportunistic evaluation stops after 10,000 steps, so a build does not spend long on work it may throw away. Whether a call in a run-time position is computed while compiling can depend on how much work it is, never on whether the program is correct.

Vyi
import { println } from "@fmt"

fn depth(n: i32) i32 {
    if n == 0 { return 0 }
    return 1 + depth(n - 1)
}

fn main() !u8 {
    println(depth(3000))   // prints 3000
    return Ok(0)
}

Both limits can be raised for a package in its manifest (comptime):

yaml
comptime:
  maxDepth: 4096
  maxSteps: 400000

or for one build on the command line, which overrides the manifest: --comptime-max-depth and --comptime-max-steps (CLI flags).

Inferred return types

A function whose return type is written _ returns the smallest union of the types its reachable returns give: one type when they agree, their union when they don't (return 0 and return "x" give i32 | [*con]u8). The type belongs to the function and its known arguments: `fn id(known T: type, v: T) _ has one return type per T`, never one per run-time argument.

A recursive function's return type depends on itself. A recursive call contributes whatever the function returns, so the base case decides the type, wherever it is written. Functions that call each other are solved together:

Vyi
import { println } from "@fmt"

fn countDown(n: i32) _ {
    if n != 0 { return countDown(n - 1) + 1 }
    return 0
}

fn isEven(n: i32) _ {
    if n == 0 { return true }
    return isOdd(n - 1)
}

fn isOdd(n: i32) _ {
    if n == 0 { return false }
    return isEven(n - 1)
}

fn main() !u8 {
    println(countDown(4))   // prints 4
    println(isEven(4))      // prints true
    return Ok(0)
}

The type must have a fixed size. A return that puts the function's own result inside a value (a tuple element, a field, a payload, or behind a pointer) never settles; write the return type, and for a recursive shape declare a struct or enum with a pointer in between:

Vyi · does not compile
fn nest(n: i32) _ {   // error: the inferred return type of "nest" contains itself by value
    if n == 0 { return 0 }
    return (nest(n - 1), 1)
}

A function whose every return is a call back into the same cycle has no return that gives it a type, and is reported at the function:

Vyi · does not compile
fn forever(n: i32) _ {   // error: the return type of "forever" cannot be inferred
    return forever(n - 1)
}

A known argument can be a value, so the return type can depend on it. An if over a known parameter is decided for each instance before its returns are read, and only the returns that instance can reach give it its type:

Vyi
import { println } from "@fmt"

fn measure(known wide: bool) _ {
    if wide { return i64(7) }
    return i32(7)
}

fn main() !u8 {
    con narrow: i32 = measure(false)
    con big: i64 = measure(true)
    println(big)   // prints 7
    return Ok(0)
}

Pointers to known values

A known value the program uses at run time is stored in the compiled program. A pointer to a file-level con points at that storage, so it is stable: it may be returned, stored, and captured, because the storage outlives every call. String literals are the everyday case: "hi" is a [*con]u8 over bytes stored in the program.

A local binding is not stored in the program by being known: its address dies with its call, and letting it leave is an error. The full rules are in the memory model.

Vyi
import { println } from "@fmt"

con limit: i32 = 100

fn limitPtr() *con i32 {
    return &limit
}

fn main() !u8 {
    println(*limitPtr())   // prints 100
    return Ok(0)
}

The address of a file-level variable

The address of a file-level con or mut is a known value: &total names total's own storage. The same holds for a field, a tuple element, or a fixed array element at a known index, reached from it without passing through a pointer (&total.count, &table.rows[2]). The address is the same wherever it is written: in a function body, in another file-level initializer, inside a struct, tuple, array, or enum payload that initializes a file-level variable, or as the argument of a known pointer parameter. Through an import it names the exporting file's storage.

Only the address is known, not what it points at. Reads and writes through it happen at run time, so a mut initialized with &counter sees every later write to counter. The address of anything else (a local, a parameter, storage reached through a pointer) is a run-time value.

Vyi
import { println } from "@fmt"

mut visits: i32 = 0
mut tracker: *mut i32 = &visits

fn main() !u8 {
    *tracker += 1
    println(visits)               // prints 1
    println(tracker == &visits)   // prints true
    return Ok(0)
}

Initializers read upward, so two file-level variables cannot hold each other's address, and one cannot hold its own:

Vyi · does not compile
mut first: *mut i32 = &second   // error: undefined name "second"
mut second: i32 = 0

See also: guide 11, Known values, generics, and compile-time evaluation, memory model, and types.