Guides · 11
Known values, generics, and compile-time evaluation
Vyi runs parts of your program while it compiles. A value the compiler works out during compilation is a known value. A value that exists only once the program runs is a runtime value.
This guide shows where known values come from and where Vyi needs one. Then it
builds on them: a function can take a known value as a parameter, a type is a
known value, and together those two facts give you generic functions and
generic types. Later sections cover running your own code at compile time with
known, the limits on that, and two advanced tools: dynamic identifiers, and
if and for at file level.
Known values
These are known values:
- literals, such as
42,"hi", andtrue, - a
conwhose value is built from known values, - every type, such as
i32orPoint, - a function call that the compiler evaluates while compiling.
Everything else is a runtime value: a function's parameters, a mut binding,
and anything the program reads while it runs.
import { println } from "@fmt"
con secondsPerMinute = 60
con secondsPerHour = secondsPerMinute * 60
fn main() !u8 {
println(secondsPerHour) // prints 3600
return Ok(0)
}secondsPerHour is a known value. The compiler does the multiplication, and
the compiled program contains 3600.
Some places need a known value, because the compiler has to decide something
there before the program runs. The length of an array type is one: the length
is part of the type. con size = 3 works there. A mut binding doesn't,
because its value can change while the program runs:
fn main() !u8 {
mut size = 3
con row = [size]u8[1, 2] // error: is a runtime value
return Ok(0)
}A file-level con or mut needs a known value too, as guide
02 showed. The rest of
this guide meets two more: type arguments, and known parameters.
Declarations can come in any order
The compiler works out a known value when something needs it, not from the top of the file down. So you can use a function or a type above the line that declares it:
import { println } from "@fmt"
con boxArea = area(3, 4) // area is declared below
fn area(width: i32, height: i32) i32 {
return width * height
}
fn main() !u8 {
println(boxArea) // prints 12
return Ok(0)
}This freedom is for declarations: fn, struct, enum, interface, and
type. A file-level con or mut can read only the bindings written above
it, the same rule as inside a function body.
Types are known values
A type is a value too. Its type is type, and it is always a known value. You
have already given types names with type Meters = i32. Three operators give
you facts about types:
typeof expris the type of an expression,sizeof Tis the size of typeTin bytes, as ani32,alignof Tis its alignment in bytes, as ani32.
Parentheses are optional: sizeof(T) and sizeof T are the same.
import { println } from "@fmt"
struct Point { x: i32, y: i32 }
fn main() !u8 {
println(sizeof i64) // prints 8
println(sizeof Point) // prints 8
println(alignof Point) // prints 4
return Ok(0)
}A Point is two 4-byte i32s, so it takes 8 bytes, and its alignment is an
i32's.
typeof works out the type without running the expression:
import { println } from "@fmt"
fn loadScore() i32 {
println("loading")
return 90
}
fn main() !u8 {
type Score = typeof loadScore()
con best: Score = 100
println(best) // prints 100
return Ok(0)
}Score is i32, the return type of loadScore. The program prints only
100: loadScore never runs, so loading never prints.
Generic functions
A parameter marked known takes a known value. The function receives it while
compiling. When that parameter is a type, the function is generic: Vyi has no
other syntax for generics.
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(i32, 3, 7)) // prints 7
println(max(u8, 200, 100)) // prints 200
return Ok(0)
}T is an argument like a and b, written in the same list. The compiler
builds a separate copy of max for each type it's called with: one where T
is i32 and one where it is u8. Calls with the same known arguments share a
copy. Runtime arguments never make a new copy.
Writing _ to infer the argument
A known argument is always written at the call. You can write _ in its
place, and the compiler works the value out from the other arguments:
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(_, 3, 7)) // prints 7
return Ok(0)
}3 and 7 are i32s, so T is i32. Leaving the argument out is an error:
fn max(known T: type, a: T, b: T) T {
if a > b { return a }
return b
}
fn main() !u8 {
con m = max(3, 7) // error: no argument for known parameter
return Ok(0)
}The compiler finds T wherever it appears in a parameter's type, including
inside another type. Here T is the element type of an array pointer:
import { println } from "@fmt"
fn first(known T: type, items: [*con]T) T {
return items[0]
}
fn main() !u8 {
con prices = [3]i32[5, 8, 2]
println(first(_, prices[..])) // prints 5
return Ok(0)
}prices[..] is a [*con]i32, so T is i32.
When no argument's type mentions the parameter, there is nothing to work it
out from, and _ is an error. Write the type instead, as in byteSize(i64):
fn byteSize(known T: type) i32 {
return sizeof T
}
fn main() !u8 {
con n = byteSize(_) // error: cannot infer known parameter
return Ok(0)
}Parameters typed _
Often a function wants "a value of any type" and never needs to name the type.
Write _ as the parameter's type:
import { println } from "@fmt"
fn double(n: _) _ {
return n + n
}
fn main() !u8 {
println(double(21)) // prints 42
println(double(i64(5000000000))) // prints 10000000000
return Ok(0)
}A parameter typed _ is generic, and the compiler builds a copy of the
function for each argument type. The type has no slot at the call: you write
double(21), not double(_, 21). The _ return type is worked out from the
return statements. println takes its argument this way, which is why it
accepts a value of any type that can be printed.
The _ can also sit inside a larger type, as in items: [*con]_, and a method
can have _-typed parameters too.
Choosing code by type
Inside the function, typeof n names the argument's type. A match typeof
on it picks an arm separately for each copy of the function. Only the arm that
matches becomes part of that copy, so the other arms don't have to make sense
for that type:
import { println } from "@fmt"
struct Temperature { celsius: i32 }
fn degrees(v: _) i32 {
match typeof v {
i32: return v,
Temperature: return v.celsius,
}
}
fn main() !u8 {
con today = Temperature{ celsius: 30 }
println(degrees(21)) // prints 21
println(degrees(today)) // prints 30
return Ok(0)
}In the copy for i32, the Temperature arm isn't there, so v.celsius is
never checked against an i32. A call whose type no arm matches, and that no
default arm catches, is an error at the call:
struct Temperature { celsius: i32 }
fn degrees(v: _) i32 {
match typeof v {
i32: return v,
Temperature: return v.celsius,
}
}
fn main() !u8 {
con d = degrees(true) // error: no `match typeof` arm for bool
return Ok(0)
}Named type variables
When two parameters must have the same type, or the return type needs a name, use a type name you haven't declared:
import { println } from "@fmt"
fn larger(a: T, b: T) T {
if a > b { return a }
return b
}
fn main() !u8 {
println(larger(3, 7)) // prints 7
return Ok(0)
}T isn't declared anywhere, so it is a type variable: generic like a _
parameter, with no slot at the call, and worked out from the arguments every
time larger is called.
The rule 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 an
error, undefined name: in the parameters of a method or a closure, in a
struct field, or in a function body.
So a misspelled type name in a function's signature is read as a type variable too. What happens then depends on the calls:
- If the body works for every argument the program passes, the program compiles and runs, as if you had written a generic function.
- If a call passes a type the body can't handle, the error names the type variable.
fn total(p: Prise) i32 { return p.amount }called astotal(5)reports `type i32 has no field "amount", in the instancetotal(Prise = i32). ThePrise = i32shows thatPrise` was read as a type variable. - If the misspelled name appears only in the return type, no argument can decide it, and every call is an error:
fn double(n: i32) i23 {
return n * 2
}
fn main() !u8 {
con d = double(4) // error: cannot infer type "i23"
return Ok(0)
}Known values as parameters
A known parameter can have any type, not only type. An array's length is
part of its type, so a known i32 can give the length:
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 = [3]i32[10, 20, 30]
println(sum(3, scores)) // prints 60
println(sum(_, scores)) // prints 60
return Ok(0)
}_ works out a known value the same way it works out a type: scores is a
[3]i32, so N is 3. As with types, each different N gets its own copy
of the function.
A known parameter needs a known argument. A runtime value is an error, because it doesn't exist yet when the compiler needs it:
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 = [3]i32[10, 20, 30]
mut size = 3
con t = sum(size, scores) // error: parameter "N" is not known
return Ok(0)
}Order of parameters
A signature reads left to right. A parameter's type can use the parameters to its left, and nothing to its right:
fn sum(nums: [N]i32, known N: i32) i32 { // error: undefined name "N"
return nums[0]
}
fn main() !u8 {
return Ok(0)
}A known parameter can sit anywhere in the list, and arguments always match
parameters one to one, in order. fn repeat(text: [*con]u8, known times: i32)
is fine. Still, put known parameters first. That keeps a function's
compile-time inputs at the front of its signature and of every call, as in
max(i32, 3, 7), and it's the only order in which later parameter types can
use them. The standard library follows this convention.
Each copy is checked
Each copy of a generic function is checked as ordinary code, with its own
types. A body that is fine for one type can be wrong for another. The error
names the copy, here widen(T = bool), and a note points at the call that
asked for it:
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, 7)
con b = widen(bool, true)
return Ok(0)
}An if whose condition is a known value keeps only the branch it takes. So a
branch such as if T == bool { ... } is part of the copy for bool and of no
other copy, and isn't checked for the others.
Generic types
A type is a known value, so a function can return one. A function that takes a type and returns a type is a generic type:
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: 7 }
con b: IntBox = a
println(b.value) // prints 7
return Ok(0)
}The compiler calls Box once for each different argument. Every Box(i32)
in the program, in any file and through any alias such as IntBox, is the
same type, so a value moves freely between them. Box(i64) is a different
type.
The body is ordinary code that runs while compiling, so it can make decisions. This counter picks the smallest field type that can hold its maximum:
import { println } from "@fmt"
fn Counter(known max: i32) type {
if max <= 255 { return struct { count: u8 } }
return struct { count: i32 }
}
fn main() !u8 {
println(sizeof Counter(100)) // prints 1
println(sizeof Counter(1000)) // prints 4
return Ok(0)
}Enums and interfaces work the same way.
fn Maybe(known T: type) type { return enum { Nothing, Just(T) } } is a
generic enum, and guide 12 builds generic interfaces.
Running code at compile time
A file-level con is always worked out while compiling. Inside a function,
write known before an expression to have the compiler evaluate it there:
import { println } from "@fmt"
fn square(n: i32) i32 {
return n * n
}
fn main() !u8 {
con area = known square(12)
mut side = 5
println(area) // prints 144
println(square(side)) // prints 25
return Ok(0)
}square is an ordinary function. The first call runs while compiling, and the
program contains 144. The second runs while the program runs. Being known is
a property of a call, not of a function.
known also takes a block. The block's value is its last expression:
import { println } from "@fmt"
fn main() !u8 {
con total = known {
mut sum = 0
for n in 1...10 { sum += n }
sum
}
println(total) // prints 55
return Ok(0)
}A mut inside the block is fine. It exists only while the compiler evaluates
the block, and what comes out is a finished value.
Everything a known expression reads must be known. A runtime value is an
error, for the same reason as with a known parameter:
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)
}Without known, the compiler may still evaluate a call whose arguments are
known values, on its own. If it can't, the call runs with the program, as
written. Write known when you need the value worked out while compiling and
want an error if it can't be.
Limits on compile-time evaluation
Code that runs while compiling can loop or recurse forever, like any code. The compiler doesn't hang: it stops and reports which limit was reached.
- One evaluation, such as one
knownexpression, one file-levelcon, or one generic type, may take at most 100,000 steps. Each loop iteration and each call is a step. - Calls made while compiling, including generic types made inside other generic types, may nest at most 1,024 deep.
fn countForever() i32 {
mut ticks = 0
for true { ticks += 1 } // error: at most 100000 steps
return ticks
}
con ticks = countForever()
fn main() !u8 { return Ok(0) }fn countUp(n: i32) i32 {
return countUp(n + 1) // error: at most 1024 frames deep
}
con top = countUp(0)
fn main() !u8 { return Ok(0) }The step count starts again for each evaluation, so a program can do as much
compile-time work in total as it needs. These errors come only from
evaluations the language requires. When the compiler tries a call on its own
and reaches a limit, it gives up quietly, and the call runs with the program.
Both limits can be raised in package.vyipac or on the command line; see
Limits on compile-time evaluation.
Types as runtime values
A type can also be a runtime value. You meet this with unions: a binding of
type i32 | bool holds one member at a time, and typeof on it asks which one
it holds at that moment. That question is answered while the program runs.
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)
}typeName takes a type as an ordinary parameter, and switch compares it
arm by arm. A switch on a type needs a default arm, because there is no
end to the types it could be given.
You don't choose between the two kinds of typeof. Over a value whose type is
fixed, such as an i32, the answer is known while compiling. Over a union
value, it's a runtime value. Guide 06 shows
match typeof, which branches on a union's member directly.
Pointers to known values
A known value the program uses at run time is stored in the compiled program
itself. A pointer to a file-level con therefore stays valid for the whole
run, and a function may return it:
import { println } from "@fmt"
con limit: i32 = 100
fn limitPtr() *con i32 {
return &limit
}
fn main() !u8 {
println(*limitPtr()) // prints 100
return Ok(0)
}A pointer to a local binding can't leave its function. Guide 09 has the full rules.
Dynamic identifiers
This section and the next cover tools you'll rarely need: most programs never use them.
A name can be computed. In place of a name you can write [expr], a
dynamic identifier. The expression must be a known string, and that string
becomes the name:
import { println } from "@fmt"
con unit = "celsius"
struct Reading { [unit]: i32 }
fn main() !u8 {
con today = Reading{ celsius: 21 }
println(today.[unit]) // prints 21
return Ok(0)
}[unit]: i32 declares a field named celsius. today.[unit] and
today.celsius reach the same field. A dynamic identifier works in these
places: the name of a file-level declaration (fn [name]() { ... }), a struct
field, an enum variant, a field access, and an arm head in switch or
match.
if and for at file level
At file level, if and for run while compiling, and they decide which
declarations exist. A file-level if keeps the declarations in the branch it
takes and drops the others:
import { println } from "@fmt"
con verbose = false
if verbose {
fn log(message: [*con]u8) { println(message) }
} else {
fn log(message: [*con]u8) {}
}
fn main() !u8 {
log("starting")
println("done") // prints done
return Ok(0)
}With verbose false, log does nothing, and the program prints only done.
A file-level for repeats its declarations once for each element of a known
array. With a dynamic identifier, each round declares a different name:
import { println } from "@fmt"
for feature in [2][*con]u8["search", "export"] {
con [feature] = true
}
fn main() !u8 {
println(search) // prints true
return Ok(0)
}The loop declares two bindings, search and export.
The condition of a file-level if, and the array of a file-level for, must
be known values. A runtime value can't decide what gets compiled:
mut requests = 0
if requests > 0 { // error: requires a known-reducible condition
fn report() {}
}
fn main() !u8 { return Ok(0) }See also: the known values reference, which has the complete rules.