Control flow
$if and $or branch on comptime-evaluable conditions. Only the taken arm is compiled. The discarded arms are never resolved, type-checked, or emitted. A runtime if / or always generates a branch.
The $if / $or form
A $if chain mirrors runtime if / or in shape, but each gate is a comptime condition and only the selected branch reaches the binary. $or with a condition is an else-if; $or with no condition is the comptime else.
$if (cond) {
...
}
$or (cond) {
...
}
$or {
... # comptime else
}
Target gating is the most common use: select the right import or backend per build, and leave the rest out of the binary entirely.
$if ($mach.build.sys == $mach.sys.linux) {
use std.system.os.linux;
}
$or ($mach.build.sys == $mach.sys.windows) {
use std.system.os.windows;
}
$or {
$error("unsupported OS");
}
A name a module declares only in an arm this build does not take is left out of the build. A use of it is reported as unresolved, pointing at the declaration and at the condition that left it out:
error[visibility.not_exported] no symbol `cpu_count` exported by `app.os`
@ src/bin/main.mach:7:23
7 | val n: usize = os.cpu_count();
| ^^^^^^^^^
@ src/os.mach:6:14 declared here, in a branch this build does not select
6 | fwd impl.cpu_count;
| ---------
@ src/os.mach:5:6 this condition is false in this build
5 | $if (HAS_THREADS) {
| -----------
Comptime conditions
The gate must be a comptime expression. Common shapes:
$mach.*reads for target and build conditions- comparisons of comptime constants (
valdeclarations) - comparisons of a comptime function parameter, see below
A condition is a u1. A comparison is one, and so is a constant declared u1 or through a def that ends at u1, as std's bool does. Any other integer is refused with comptime branch condition must have type u1. A gate that reads a runtime binding, or has no compile-time value for another reason such as a call, is refused.
A comptime comparison or arithmetic relates the mathematical values of its operands, exactly as the runtime operators do. A constant in the range 2^63 to 2^64 - 1 carries its true unsigned magnitude, so $if (0xFFFFFFFFFFFFFFFFu64 > 0) is taken, and any cross-sign comparison agrees with the runtime form: $if (X < Y) never selects a branch that if (X < Y) would not. An unsuffixed literal with no typed context is an i64, so that magnitude needs its suffix.
Comptime arithmetic computes the exact result and never wraps to an operand's width: with val Z: u8 = 255, $if (Z + 1 > 255) is taken. A result outside the 128-bit range the evaluator works in is a compile error, not a silent wrap.
When a declaration-scope $if is decided
A $if chain written in declaration scope runs at one of two times, and what its arms contain picks which.
- Some arm declares something. The chain is decided while the modules load, because what it decides is which declarations exist and every later stage reads the resulting set. Nothing has a type at that point, so the gate cannot ask a type question:
$size_of,$align_of,$length_of,$offset_of,$type_id,$type_of,$type_nameor an$is_*predicate there is rejected, with a message naming the question. - No arm declares anything. The chain contributes no name and no type whichever arm is taken, so nothing depends on deciding it early. It is decided during type checking instead, where its gate may measure a type (
$size_of,$align_of,$length_of), query one ($is_recordand friends), or compare one.
The question is answered from the syntax, over every arm ($if, every $or, and a trailing $or {}) before any gate is evaluated. One declaring arm anywhere keeps the whole chain at the earlier time. Per-arm answers are not possible: which stage runs the gate would then depend on which arm the gate selects, and the stage that would have to know that is the one being chosen.
A use is a declaration, so a conditional import is always decided while the modules load. That is what makes the common target-gating form above work.
A declaring gate reads build facts ($mach.*, $bin.*, $project.*) and val constants from any module, in the order they depend on each other rather than the order they are written in. A gate may read a constant declared later in its module, or one declared under another $if. Gates and constants that depend on each other in a cycle are rejected with a message naming the cycle.
rec MeshUniforms { model: [16]f32; }
# no arm declares: decided during type checking, so the gate may measure
$if ($size_of(MeshUniforms) != 64) {
$error("MeshUniforms must be 64 bytes");
}
# the second arm declares, so the whole chain is decided while the modules
# load, and the gate is rejected there
$if ($size_of(MeshUniforms) != 64) {
$error("MeshUniforms must be 64 bytes");
}
$or {
val PADDING: u32 = 0;
}
The second chain is refused with:
error[gate.type_question] `$size_of` asks a type question, which this `$if` cannot answer because an arm declares something and the gate is decided before types are known. move the declarations out of the `$if` so it is decided during type checking
A $if inside a function body is always decided during type checking. It selects statements rather than declarations, so the question does not arise and its gate may always ask about a type.
A module refused by its own $error
A $error at module scope, bare or in an arm of a declaration-scope chain, states that the module cannot exist in this build. A module in which one fires is refused: it reports every module-scope $error that fires in it and nothing else, and a module that imports it, directly or through others, is not analysed and reports nothing. One refused module gives one diagnostic however long the chain of imports above it is. A refused module in a dependency reports at the import in the project's own source that reaches it.
# on any target but linux this module gives this one diagnostic and nothing else
$if ($mach.build.sys == $mach.sys.linux) {
use native: std.system.os.linux;
}
$or {
$error("this module needs a linux target");
}
A module with a lexical or syntax error is never refused. It reports those errors, so a syntax error is never hidden behind a $error that fires on some targets only. A $error in a function body, or in an arm an instance selects, refuses nothing. mach doc decides no gate and fires no $error.
Branching on a comptime parameter
A comptime function parameter ($mode: u8) is a compile-time-known argument, fixed per call site. $if / $or may branch on it: the compiler monomorphizes the body once per distinct comptime-argument value, and each instance compiles only the arm its value selects.
val MODE_DOUBLE: u8 = 0;
val MODE_SQUARE: u8 = 1;
fun apply($mode: u8, n: i64) i64 {
$if (mode == MODE_DOUBLE) {
ret n + n;
}
$or (mode == MODE_SQUARE) {
ret n * n;
}
ret 0;
}
# apply(MODE_DOUBLE, ..) and apply(MODE_SQUARE, ..) emit two distinct bodies,
# each carrying only its selected arm.
A comptime parameter also sizes types in the body of its function. Each instance resolves those types at its own values, so [N]i64 in fun count($N: i64) is three elements long in count(3) and one in count(1):
fun count($N: i64) i64 {
var xs: [N]i64;
ret $length_of([N]i64) + $size_of([N]i64)::i64; # count(3) is 27
}
A comptime parameter never sizes a type in the function's own signature. fun first($N: i64, xs: [N]i64) is refused with a comptime parameter sizes a type only in the body of its function, never in a parameter or return type.
Rules
- The argument bound to a
$-parameter must be a compile-time constant at the call site: a literal, avalconstant, or another comptime parameter. A runtime value is rejected withcomptime argument is not a compile-time constant. Cross-module constants work, whether imported by bare name or as a qualified member (alias.CONST). A value the parameter's type cannot represent is refused, never truncated:narrow(300)againstfun narrow($n: u8)reportscomptime argument 300 is out of range for u8 (0..255). - Each arm gate must itself be comptime-foldable: its identifiers must all be comptime (parameters or constants). A gate that references a runtime local or parameter is rejected.
- A comptime parameter has no storage, so its address cannot be taken:
?modeis rejected withcannot take the address of a comptime parameter. - A comptime-parameter function is a template, not a value. It can only be called, never assigned, passed, or compared.
val fp: fun(i64) i64 = apply;is rejected withcannot reference a comptime-parameter function as a value. - Comptime parameters carry no runtime cost: they are stripped from the lowered signature and ABI, so only the runtime parameters are passed. They may be mixed freely with runtime parameters in any order.
- An instance is emitted against its declaring module and folds its gates against that module's own comptime constants, so a library can export a comptime-parameter function gated on its own
vals, private ones included. - A comptime parameter on a generic function (
fun f[T]($mode: u8, ...)) is refused at each call withcomptime value parameters on a generic function are not yet supported. A function has type instances or value instances, never both.
Because each instance compiles only its taken arm, a comptime parameter can safely gate per-target asm blocks: a register one backend does not recognize lives only in the arm the other backend never compiles.
pub fun load($order: Order, ptr: *i64) i64 {
var result: i64 = 0;
$if ($mach.build.arch == $mach.arch.aarch64) {
$if (order == RELAXED) {
asm armv8-a {
ldr x9, {ptr}
ldr x9, [x9]
str x9, {result}
}
}
$or (order == ACQUIRE) {
asm armv8-a {
ldr x9, {ptr}
ldar x9, [x9]
str x9, {result}
}
}
}
ret result;
}
Discarded branches
An untaken $if branch is absent from the compiled output, but what "not taken" means for name resolution depends on what the gate reads.
$mach.*or constant gates: the untaken arms are entirely absent and the compiler does not even resolve names inside them. This is what makes per-targetasmblocks safe when one arm references registers the other backend has never heard of. A name that does not exist in the arm the gate selects is reported as an ordinary unresolved name, once.- comptime-parameter gates: the one exception. Because arm selection happens per call site at monomorphization, name resolution and type checking run over all arms structurally, and only the selected arm is emitted into each instance. Every arm must therefore be independently resolvable and type-checkable.
$type_oftype gates: not an exception. At monomorphization the operand's concrete type is known, so provably-dead arms are pruned and only the selected arm is type-checked and emitted. Each arm may use its value at its own concrete type with no per-arm cast. Names are still resolved in every arm.
What only a value can decide waits for the instance. A $error in the arm an instance selects is reported once for each distinct instance that selects it, at the call that asked for the instance. A $error in an arm no instance selects never fires, and neither does one in a function nothing calls:
fun shifted($n: u8, x: u64) u64 {
$if (n == 2) {
$error("no two");
}
ret x << n;
}
fun use_it(x: u64) u64 {
ret shifted(1, x) + shifted(2, x); # shifted(2, ..) is refused, shifted(1, ..) is not
}
error[comptime.user_error] no two
@ src/shift.mach:9:25
9 | ret shifted(1, x) + shifted(2, x);
| ^^^^^^^^^^^^^
@ src/shift.mach:3:9 in this body, checked against this instance's comptime arguments
3 | $error("no two");
| -----------------
See also
- The comptime channel -
$mach.*reads for target and build conditions - Intrinsics -
$type_ofdispatch and the comptime toolkit - Statements - the runtime
if/orcounterpart - Variadic packs -
$if/$orinside$eachbodies