machdocs
Home Ecosystem Changelog

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:

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.

Note

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.

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

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.

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